text:
Q: what is the difference between ls | grep *e* and ls | grep e When used ls | grep *e* gives much lesser result than ls | grep e, why is it so. Are they not the same commands. Anybody knows the difference between these commands.

A:
Are ls | grep *e* and ls | grep e not the same commands?

No, they are different. With
$ ls | grep *e*

the command shell expands the pattern *e* to match all files which contain the letter e in the current directory. This expanded file list is then passed to the grep command:
$ ls
Hello.txt  Null.txt  Sample.txt

When executing
$ ls | grep *e*

the actual command will be ls | grep Hello.txt Sample.txt
With
$ ls | grep e

there is no file name expansion and the actual command will be ls | grep e.
See also

*

*Bash reference manual: 3.5.8 Filename Expansion
If you want to pass the parameter without being expanded, you need to quote it:
$ ls | grep "*e*"

Then, the command actually will be ls | grep *e* (with "*e*" being passed as argv[1] to the grep command).
Note that the shell expansion is different from a regular expression - the shell matches any string for *, while in regular expressions * denotes that any number of the previous expression shall occur.

A: The shell expands *e* before executing the command. So if you have files named beer and free, you end up grepping for beer in free, and ignoring the input from ls.
*e* is not a valid regular expression, anyway. * means "zero or more of the preceding expression" and there is no preceding expression in the first instance. Properly, grep should display an error for this, but doesn't. It ends up matching nothing repeated zero or more times, followed by e repeated zero or more times. Because every imaginable input contains zero or more occurrences of e, it would end up matching every input line.
But anyhow, as noted above, grep would not see this input, because it is intercepted and expanded by the shell. If you want to use * literally, you need to quote it.
ls | grep '.*e.*'

is just a really lame way to say
ls | grep 'e'

because the leading and trailing wildcards add no value -- grep always looks for a match anywhere on each input line.
What you actually want is to use the wildcard matching features of the shell:
ls *e*

The glob expression *e* is not a regular expression, but a glob pattern. It does what you apparently expect.


text:
Q: How to Align Equations to Top of Minipage I have two align environments in 2 minipages and I want them to be aligned at the very top. I am usually able to do it with 2 regular equations, but it doesn't work when I tried doing it on the two align environment, I end up getting a gap on the left minipage so it looks a bit off. Below is my code and output.
\documentclass[a4paper, 11pt, letterpaper]{article}
\usepackage{comment}
\usepackage{fullpage}
\usepackage{amssymb}
\usepackage{mathtools,amsthm}
\usepackage{tabularx}
\begin{document}
\begin{minipage}[t]{0.6\textwidth}
\vspace{0pt}
\begin{align*}
    \f{dy}{dx} &= 1\cdot (2x-1)^2 + (x+3)\cdot 2 \cdot (2x-1) \cdot 2\\
    &= (2x-1)^2 + 4(x+3)(2x-1)\\
    &= (2x-1)[(2x-1)+4(x+3)]\\
    &= (2x-1)(2x-1+4x+12)\\
    &= (2x-1)(6x+11)
\end{align*}
\end{minipage}
\hfill
\begin{minipage}[t]{0.3\textwidth}
\vspace{0pt}
\begin{tabular}{|p{\textwidth}}
{$\!\begin{aligned}
    &u=x+3\\
    &v=(2x-1)^2\\
    &u'=1\\
    &v'=4(2x-1)
\end{aligned}$}
\end{tabular}
\end{minipage}
\end{document}

Thanks for any help!

A: You don't need minipages: it all can be done with alignat*:
\documentclass[a4paper, 11pt, letterpaper]{article}

\usepackage{comment}
\usepackage{fullpage}
\usepackage{amssymb}
\usepackage{empheq, amsthm}

\begin{document}

\begin{alignat*}{2}
    \smash[b]{\frac{dy}{dx}} &= 1\cdot (2x-1)^2 + (x+3)\cdot 2 \cdot (2x-1) \cdot 2%
     & \hspace{4em} \smash{\rule[-12ex]{0.4pt}{14ex}}\enspace & u=x+3 \\
    &= (2x-1)^2 + 4(x+3)(2x-1)& &v=(2x-1)^2 \\
    &= (2x-1)[(2x-1)+4(x+3)] & &u'=1 \\
    &= (2x-1)(2x-1+4x+12) & & v'=4(2x-1) \\
    &= (2x-1)(6x+11)
\end{alignat*}

\end{document}

A: You seem to want aligned and array side-to-side:
\documentclass[a4paper,11pt]{article}
\usepackage{mathtools}
\usepackage{array}

\begin{document}

\begin{equation*}
\begin{aligned}[t]
  \frac{dy}{dx}
  &= 1\cdot (2x-1)^2 + (x+3)\cdot 2 \cdot (2x-1) \cdot 2\\
  &= (2x-1)^2 + 4(x+3)(2x-1)\\
  &= (2x-1)[(2x-1)+4(x+3)]\\
  &= (2x-1)(2x-1+4x+12)\\
  &= (2x-1)(6x+11)
\end{aligned}
\qquad
\begin{array}[t]{|l@{}>{{}}l}
u&=x+3\\
v&=(2x-1)^2\\
u'&=1\\
v'&=4(2x-1)
\end{array}
\end{equation*}

\end{document}

I used left alignment for the first column in the array because the result seems more symmetric than with the usual right alignment.
Note that a4paper and letterpaper override each other; so just one should be specified.

A: This probably achieves what you want (I made the code compilable by replacing \f by \frac and changed the minipage alignment to [h]):
\documentclass[a4paper, 11pt, letterpaper]{article}
\usepackage{comment}
\usepackage{fullpage}
\usepackage{amssymb}
\usepackage{mathtools,amsthm}
\usepackage{tabularx}
\begin{document}
\begin{minipage}[h]{0.6\textwidth}
\vspace{0pt}
\begin{align*}
    \frac{dy}{dx} &= 1\cdot (2x-1)^2 + (x+3)\cdot 2 \cdot (2x-1) \cdot 2\\
    &= (2x-1)^2 + 4(x+3)(2x-1)\\
    &= (2x-1)[(2x-1)+4(x+3)]\\
    &= (2x-1)(2x-1+4x+12)\\
    &= (2x-1)(6x+11)
\end{align*}
\end{minipage}
\hfill
\begin{minipage}[h]{0.3\textwidth}
\vspace{0pt}
\begin{tabular}{|p{\textwidth}}
{$\!\begin{aligned}
    &u=x+3\\
    &v=(2x-1)^2\\
    &u'=1\\
    &v'=4(2x-1)
\end{aligned}$}
\end{tabular}
\end{minipage}
\end{document}

Just for the records: if I wanted to get the vertical line, I'd use
\documentclass[a4paper, 11pt]{article} % either letterpaper or a4paper
\usepackage{fullpage}
\usepackage{amssymb}
\usepackage{mathtools}
\usepackage{tikz}
\newcommand{\tikznode}[2]{%
\tikz[remember picture,baseline=(#1.base),inner sep=0pt] \node (#1) {$#2$};%
}%from https://tex.stackexchange.com/questions/402462/tikz-equivalent-of-pstricks-commands-ncbar-and-rnode/402466#402466
\begin{document}
\begin{align*}
   \frac{\mathrm{d}y}{\mathrm{d}x} &= 1\cdot (2x-1)^2 + (x+3)\cdot 2 \cdot (2x-1) \cdot 2
       & \tikznode{u}{\strut}u&=x+3\\
    &= (2x-1)^2 + 4(x+3)(2x-1)
       & v&=(2x-1)^2\\
    &= (2x-1)[(2x-1)+4(x+3)]
       &u'&=1\\
    &= (2x-1)(2x-1+4x+12)
      &  \tikznode{v}{\strut}~v'&=4(2x-1)\\
    &= (2x-1)(6x+11)
\end{align*}
\tikz[overlay,remember picture]{\draw (v|-u.north)--(v.south);}
\end{document}

Note that I kicked out some of the unnecessary packages and also removed one of the conflicting options (letterpaper).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error al llamar un procedimiento almacenado(MariaDB) con parametro en Laravel 5.6 No he conseguido ejecutar un procedimiento almacenado con parámetro. Especificamente me sale este error:
"SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'getIngresosID(?)' at line 1 (SQL: getIngresosID(2))
en el index paso el parametro de esta forma:
<a href="{{URL::action('CuentaController@show',$cue->idcuenta)}}">
                            <button class="btn btn-primary">
                                Detalles
                            </button>
                        </a>

El procedimiento esta en MariaDB y es el siguiente:
CREATE DEFINER=`root`@`localhost` PROCEDURE `getIngresosID`(in id int)
BEGIN
    select i.idingreso, i.fecha, i.tipo_comprobante, i.num_comprobante, i.impuesto, i.estado, p.nombres, sum(di.cantidad*di.precio_compra) as total
        from ingresos as i
        join detalleingresos as di
        on i.idingreso=di.ingreso_id
        join personas as p
        on i.provedor_id=p.idpersona
        where i.idingreso=id
        group by i.idingreso, p.nombres, i.tipo_comprobante, i.num_comprobante,
        i.impuesto, i.estado;
END

Las tablas son las siguientes:

En laravel llamo el procedimientos de esta manera:
namespace App\Http\Controllers;

use App\Persona;
use App\Ingreso;
use App\DetalleIngreso;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Input;
use DB;
use Response;
use Illuminate\Support\Collection;

class IngresoController extends Controller
{
      public function show($id)
        {
            $ingreso=DB::select('getIngresosID"'. $id.'"');

            return view("compras.ingreso.show",["ingreso"=>$ingreso);
        }
}

He intentado de varias formas:
$ingreso=DB::select('getIngresosID(?)', array($id));

$ingreso=DB::select('getIngresosID ?', array($id));

$ingreso=DB::select('getIngresosID ?', $id);

Con las dos primeras me sale el mismo error pero en la ultima me notifica este error:
"Argument 1 passed to Illuminate\Database\Connection::prepareBindings() must be of the type array, string given, called in C:\xampp\htdocs\Pro_laravel\crediPaisa

A: He dado con la respuesta y funciona con laravel 9
DB::select('CALL getIngresosID(?)', array($id));


text:
Q: Find the term p with matrix . how I can solve this. Find $p$. Let $x,y,z,p\in\mathbb{R}^{n}$ and $a,b,c$ are constants, such that
$$2\langle p,x-y\rangle=(\vert\vert x\vert\vert^2-\vert\vert y\vert\vert^2)-(a^2-b^2)$$
$$2\langle p,z-y\rangle=(\vert\vert z\vert\vert^2-\vert\vert y\vert\vert^2)-(c^2-b^2)$$
$$2\langle p,x-z\rangle=(\vert\vert x\vert\vert^2-\vert\vert z\vert\vert^2)-(a^2-c^2)$$
I think the left ride side, if $k=(k_1,...,k_n)$, then I can write the matrix
$$\begin{pmatrix}
x_1-y_1 & x_2-y_2 & ... & x_n-y_n\\
z_1-y_1 & z_2-y_2 & ... & z_n-y_n\\
x_1-z_1 & x_2-z_2 & ... & x_n-z_n\\
\end{pmatrix}
\begin{pmatrix}
p_1\\
p_2\\
\vdots\\
p_n\\
\end{pmatrix}$$
And the right side is the same. But, what happen if exist terms emptys, maybe the matrix can't be resolve. Any hint?? , I think maybe works the singular value descomposition (SVD).. but I not sure. Regards


text:
Q: What does this match : bash regex if [[ "$len" -lt "$MINLEN" && "$line" =~ \[*\.\] ]]

This is from Advanced bash scripting guide "Example 10-1. Inserting a blank line between paragraphs in a text file"
As I understand this matches "any string or a dot character". Right ?

A: It matches zero or more open bracket characters (\[*), followed by a period and a close square bracket (\.\]).  Note that it only requires that a match exist somewhere in "$line", not that the whole string match.  Here's a demo:
$ showmatch() { [[ "$1" =~ \[*\.\] ]] && echo "matched: '${BASH_REMATCH[0]}'" || echo "no match"; }
$ showmatch "abc[.]def"
matched: '[.]'
$ showmatch "abc.]def"
matched: '.]'
$ showmatch "abc[[[[[[[.]def"
matched: '[[[[[[[.]'
$ showmatch "abc[[[[[[[xyz.]def"
matched: '.]'
$ showmatch "abc[[[[[[[.xyz]def"
no match

...and I'm pretty sure that's not what it's supposed to be doing in that example script.

A: It means any string ended with dot inside bracers, for example: [.]
[abc.]

A: Update: +1 to Gordon Davisson, who has summed it up pretty well... so I've redacted my original post
In brief: You can test the result of a bash regex match like this:
[[ "[*.]" =~ \[*\.\] ]] ; echo ${BASH_REMATCH[0]}


text:
Q: Replace Bootstrap default css I am trying out divshot for to evaluate if we can use it for our company, but have one question. Our company uses a custom version of bootstrap, is there a way to specify a "theme" for bootsrap or to replace the bootstrap default css? I've basically ripped all drop shadows and border radius from everything and made the styles more flat. Just wanted to know if we could over ride that default bootstrap stylesheet.
Thanks!

A: Yes, you can upload a custom bootstrap.css file into your project and then simply replace the <link> tag in any Divshot HTML page with a relative link. So if I uploaded my custom theme to css/my-bootstrap.css in the project, I could then link it like so:
<link rel="stylesheet" href="css/my-bootstrap.css">


text:
Q: Wrong number of parameters with Create Grids PyQgis I want to create a grid with a python script in PyQgis.
I have the layer from which I want to take the extent.
it seems that there is different formula :
The one from QGIS doc : https://docs.qgis.org/2.6/en/docs/user_manual/processing_algs/qgis/vector_creation_tools/creategrid.html
processing.runalg('qgis:creategrid', type, width, height, hspacing, vspacing, centerx, centery, crs, output)

The one I found on different forums with a string for extent :
processing.runalg('qgis:creategrid', type, extent, hspacing, vspacing, crs, output)
I tried both and I always got :
I tried it from my script and from the console.
Here is my code if it can help :
#!/usr/bin/env Python
from glob import glob
from os import path
import numpy as np
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *
from qgis.utils import iface
import processing

class Grid:
def __init__(self, iface,crs):
    """Initialize using the qgis.utils.iface
    object passed from the console.

    """
    self.iface = iface
    self.crs=crs

def new_grid(self,cellsizex,cellsizey,extent,centerx,centery,grid_out):
    processing.runalg('qgis:creategrid', type=1, extent=extent, hspacing=cellsizex, vspacing=cellsizey, crs=self.crs, output=grid_out)

class Extent:
def __init__(self, iface):
    """Initialize using the qgis.utils.iface
    object passed from the console.

    """
    self.iface = iface

def main(self):

    pabs= "K:\Histo_Europe_All" #path absolu
    path=pabs+"\0_Quadrillage\extent_eu.shp"
    name_l="extent_eu"

    layer=QgsVectorLayer(path,name_l, "ogr")

    extent = QgsVectorLayer( path, '', 'ogr' ).extent()

    cellsize = 1000
    centerx = (extent.xMinimum() + extent.xMaximum()) / 2
    centery = (extent.yMinimum() + extent.yMaximum()) / 20

    #first method
    width = (extent.xMaximum() - extent.xMinimum())
    height = (extent.yMaximum() - extent.yMinimum())/10

    #second method
    extent2 = str(extent.xMinimum())+ ',' + str(extent.xMaximum())+ ',' +str(ymin)+ ',' +str(extent.yMaximum())

    cellsizex = 0,002775
    cellsizey = 0,002775
    ymin=extent.yMinimum()+ 0,8 * (extent.yMaximum() - extent.yMinimum())

    grid=pabs+"\1_Grids\Grid0.shp"
    g=Grid(self.iface,layer.crs().authid())
    g.new_grid(cellsizex,cellsizey,extent2,centerx,centery,grid)

Don't mind the missing spaces at the beginning of the classes, they do exist in my code.
I edit my question based on comments.
I also gave up the extent as QGIS advise width and height.
My code is now the following :
class Grid:
def __init__(self, iface,crs):
    """Initialize using the qgis.utils.iface
    object passed from the console.

    """
    self.iface = iface
    self.crs=crs

def new_grid(self,cellsizex,cellsizey,width,height,centerx,centery,grid_out):
    #processing.runalg("qgis:creategrid", cellsizex, cellsizey, width, height, centerx, centery, 1, layer.crs().authid(), grid_out)
    #processing.runalg('qgis:creategrid', width, height, cellsizex, cellsizey, centerx, centery,"EPSG:4326", grid_out)
    #processing.runalg('qgis:creategrid', type=1, extent=extent, hspacing=cellsizex, vspacing=cellsizey, crs=self.crs, output=grid_out)
    processing.runalg('qgis:creategrid', 1, width,height, cellsizex, cellsizey, self.crs, output=grid_out)

class Extent:
def __init__(self, iface):
    """Initialize using the qgis.utils.iface
    object passed from the console.

    """
    self.iface = iface

def main(self):

    pabs= "K:/Histo_Europe_All" #path absolu
    path=pabs+"/0_Quadrillage/extent_eu.shp"
    name_l="extent_eu"

    layer=QgsVectorLayer(path,name_l, "ogr")

    extent = QgsVectorLayer( path, '', 'ogr' ).extent()

    cellsize = 1000
    centerx = (extent.xMinimum() + extent.xMaximum()) / 2
    centery = (extent.yMinimum() + extent.yMaximum()) / 20
    width = (extent.xMaximum() - extent.xMinimum())
    height = (extent.yMaximum() - extent.yMinimum())/10
    print(width)
    print(height)

    cellsizex = 0.002775
    cellsizey = 0.002775
    ymin=extent.yMinimum()+ 0.8 * (extent.yMaximum() - extent.yMinimum())
    extent2 = str(extent.xMinimum())+ ',' + str(extent.xMaximum())+ ',' +str(ymin)+ ',' +str(extent.yMaximum())

    grid=pabs+"/1_Grids/Grid0.shp"
    g=Grid(self.iface,layer.crs().authid())
    g.new_grid(cellsizex,cellsizey,width,height,centerx,centery,grid)

Now it answers :
Error: Wrong parameter value: 40.967325 (width)

A: I think there's a couple of things you could try:

*

*In your new_grid() function, replace the processing line with the following (if you want to assign variables such as type=1 etc. then you should use a dictionary as described in this post:
processing.runalg('qgis:creategrid', 1, extent, cellsizex, cellsizey, self.crs, output=grid_out)

*When defining a path for your output, either include the raw string (r) or use a single forward slash to escape:
grid=pabs+"/1_Grids/Grid0.shp"

Edit:
Made some changes to your code which might help (unfortunately, I can't test it at the moment):
class Grid:
def __init__(self, iface):
    """Initialize using the qgis.utils.iface
    object passed from the console.
    """
    self.iface = iface

def new_grid(self,cellsizex,cellsizey,layer_extent,crs,grid_out):
    processing.runalg('qgis:creategrid', 1, layer_extent, cellsizex, cellsizey, crs, grid_out)

class Extent:
def __init__(self, iface):
    """Initialize using the qgis.utils.iface
    object passed from the console.
    """
    self.iface = iface

def main(self):
    pabs= "K:/Histo_Europe_All" #path absolu
    path=pabs+"/0_Quadrillage/extent_eu.shp"
    name_l="extent_eu"

    layer=QgsVectorLayer(path,name_l, "ogr")
    crs=layer.crs().authid()

    extent = layer.extent()
    xmin = extent.xMinimum()
    xmax = extent.xMaximum()
    ymin = extent.yMinimum()
    ymax = extent.yMaximum()

    cellsizex = 0.002775
    cellsizey = 0.002775

    grid=pabs+"/1_Grids/Grid0.shp"
    g=Grid(self.iface)
    g.new_grid(cellsizex,cellsizey,"%f,%f,%f,%f"% (xmin,xmax,ymin,ymax),crs,grid)

Edit 2:
Combined both classes into one, did a quick test and works fine for me so hopefully it will for you too.
class Grid:
    def __init__(self, iface):
        """Initialize using the qgis.utils.iface
        object passed from the console.
        """
        self.iface = iface

    def main(self):
        pabs = "K:/Histo_Europe_All" #path absolu
        path = pabs+"/0_Quadrillage/extent_eu.shp"
        grid = pabs+"/1_Grids/Grid0.shp"
        name_l = "extent_eu"

        layer = QgsVectorLayer(path,name_l, "ogr")
        crs = layer.crs().authid()
        extent = layer.extent()
        xmin = extent.xMinimum()
        xmax = extent.xMaximum()
        ymin = extent.yMinimum()
        ymax = extent.yMaximum()

        cellsizex = 0.002775
        cellsizey = 0.002775

        processing.runalg('qgis:creategrid', 1, "%f,%f,%f,%f"% (xmin,xmax,ymin,ymax), cellsizex, cellsizey, crs, grid)

Then use self.main() to call the function.


text:
Q: Django Foreign Key to_field I have 2 models CustomUser and Magazine with random/unique slug fields. Now I want to create a third model (Article) with foreign keys to the slug field:
class CustomUser(AbstractBaseUser):
    slug = RandomSlugField(length=6, unique=True)
    ...

class Magazine(models.Model):
    slug = RandomSlugField(length=6, unique=True)
    name = models.CharField()

class Article(models.Model):
    magazine = models.ForeignKey(Magazine, to_field='slug')
    author = models.ForeignKey(settings.AUTH_USER_MODEL, to_field='slug')

But when I migrate the database to create the Article model, I get the following error:
django.core.exceptions.FieldDoesNotExist: CustomUser has no field named 'slug'

But CustomUser obviously has a field named 'slug'.
And for the Magazine model I don't get this error.
Has anyone an idea what is going wrong?
I use this package for the slug field:
https://github.com/mkrjhnsn/django-randomslugfield
EDIT:
Here is the full CustomUser model:
class CustomUser(AbstractBaseUser, PermissionsMixin):
    slug = RandomSlugField(length=6, exclude_upper=True)
    username = models.CharField(
        _('username'), max_length=30,
        help_text=_('Required. 30 characters or fewer.'
                'Letters, digits and '
                '@/./+/-/_ only.'),
        validators=[
            validators.RegexValidator(r'^[\w.@+-]+$',
                                  _('Enter a valid username.'), 'invalid')
        ])
    first_name = models.CharField(_('first name'), max_length=30, blank=True)
    last_name = models.CharField(_('last name'), max_length=30, blank=True)

    # email is our unique field for authentication
    email = models.EmailField(_('email address'), unique=True)

    is_staff = models.BooleanField(
        _('staff status'), default=False,
        help_text=_('Designates whether the user can log '
                    'into this admin site.')
        )
    is_active = models.BooleanField(
        _('active'),
        default=True,
        help_text=_('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.')
        )
    date_joined = models.DateTimeField(_('date joined'), default=timezone.now)

    objects = UserManager()

    profile = models.OneToOneField('UserProfile', blank=True, null=True,
                               related_name='user_profile')

    image = models.ImageField(default='images/noimage.jpg',
                          upload_to=settings.PROFILE_IMAGE_PATH,
                          max_length=255)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

A: delete the database, all migrations except init and try it


text:
Q: how to jQuery .load() with script tags *I know this was answered previously using Ajax and other methods, but nothing corresponds to my needs.
I'm making a bootstrap admin theme and I'm using jQuery's .load() to avoid page refresh and have smoother transactions, though it doesn't load the script ... /script that is at the bottom of the page, it gets ignored.

I can't create a new file for each script and load it particularly, because this would mean anyone using my theme, would have to the same for the smallest scripts used for tables and so on (when they could simply be placed inside script tags), therefore it wouldn't be an usable template.
My jQuery load code:
$('.navigation .nav li a').not('.nav-item-expandable > a').click(function(navActive){
            var href = $(this).attr('href');

            navActive.preventDefault();
            $('.content').load('/' + href + ' .content>*');
            $('.breadcrumb').load('/' + href + ' .navbar .breadcrumb>*').delay(200).queue(function(){
                breadcrumb();
                $(this).dequeue();
                });
            $('#scripts').load('/' + href + ' #scripts>*')

            history.pushState('', '', href);
        });

Lower part of my html:

 ...

A: The documentation explicitly mentions this:

If .load() is called with a selector expression appended to the URL, however, the scripts are stripped out prior to the DOM being updated, and thus are not executed.

This thread seems to have the answer - use get instead:
$('.navigation .nav li a').not('.nav-item-expandable > a').click(function(navActive){
    var href = $(this).attr('href');

    navActive.preventDefault();
    $.get('/' + href, function(html){
        var doc = $(html);
        $('.content').empty().append(doc.find('.content > *'));
        $('.breadcrumb').empty().append(doc.find('.navbar .breadcrumb > *'));
        $('#scripts').empty().append(doc.find('#scripts > *'));
        setTimeout(function(){ breadcrumb(); }, 200);
    });

    history.pushState('', '', href);
});

That will also be more efficient, since you're only making one request for the new page, rather than the three that your current script issues.


text:
Q: Is there any way to have flexbox equal height columns with baseline font alignment of text with varying font sizes and font familys? Equal heights and baseline are not a problem. However, if I'd like a hover effect on the element that displays the text with a differing font size, it is shifted out of alignment. I'm willing to use Javascript or any other solution, but am having trouble finding a way to fix the element that has the hover effect so that it doesn't get shifted out of alignment when the baseline is applied.
Simple Example:

.wrapper {
  height: 50px;
  display: flex;
  align-items: baseline;
}

.column {
  height: 100%;
  display: flex;
  align-items: center;
}

.span1, .span2 {
  height: 100%;
  display: inline-flex;
  align-items: flex-end;
}

.span1:hover, .span2:hover {
  background-color: gray;
}

.span1 {
  justify-content: flex-start;
  margin-right: 4px;
  font-size: 32px;
}

.span2 {
  justify-content: flex-end;
  margin-left: 4px;
  font-size: 8px;
}

    Some content

    Some content
   span {
  position:relative;
  z-index:0;
}
.span1:hover::before,
.span2:hover::before {
  content:"";
  position:absolute;
  z-index:-1;
  top:-200px;
  bottom:-200px;
  left:0;
  right:0;
  background-color: gray;
}

.span1 {
  margin-right: 4px;
  font-size: 32px;
}

.span2 {
  margin-left: 4px;
  font-size: 8px;
}

    Some content

    Some content


text:
Q: Recursive Permutation C++ I have problem with assignment, we need to implement recursive permutation in c++ for numbers.
Here is the code which is partly working, but missing some numbers.
I can't find where the problem is.
This code does work, but not exactly the right way.
This code take and array of number with size of that array.
in this case I am trying to solve the problem which appears when I send array longer than 3 numbers. If I send 3 numbers, output is:
///
1 2 3 /
1 3 2 /
3 1 2 /
2 1 3 /
2 3 1 /
3 2 1 /

Output in this case is correct. But when I set array to 4 and send size of it 4 I get:
///
1 2 3 4 /
1 2 4 3 /
1 4 2 3 /
4 1 2 3 /
**2 1 3   /
2 3 1   /
3 2 1   /**
3 2 1 4 /
3 2 4 1 /
3 4 2 1 /
4 3 2 1 /

Output is partly correct, but some numbers are missing.
Program should give output of all possible variations of numbers in array
#include <iostream>
using namespace std;

bool nextPermutation(int[],int);
void swap(int&, int&);
int Maxind(int[],int);
int Minind(int[],int);
void print (int[], int);
bool test (int[], int);
int fl=0;

int main() {
    int a[]={1,2,3,4};
    nextPermutation(a,4);
    return 0;
}

void print(int a[], int s) {
    for(int i=0; i<s; i++)
    {
        cout<<a[i]<<" ";
    }
    cout<<endl;
}
bool nextPermutation(int a[], int s)
{
    int i=Maxind(a,s);
    if(fl==0)
        print(a,s);
    if(i!=0) {
        swap(a[i],a[i-1]);
        nextPermutation(a,s);
    }

    else if(i==0 && test(a,s))
    {
        int p=a[0];
        for(int i=0; i<=s-2; i++)
            a[i]=a[i+1];
        fl=1;
        nextPermutation(a,s-1);
        a[s-1]=p;
        fl=0;
        nextPermutation(a,s);
    }
    else
        return false;
}

bool test (int a[], int s) {
    if (Maxind(a,s)==0 && Minind(a,s)==s-1)
        return false;
    else
        return true;
}

void swap(int& a, int& b)
{
    int t=a; a=b; b=t;
}

int Maxind(int a[], int s)
{
    int m=a[0], ind=0;
    for(int i=0; i<s; i++)
        if(m<a[i]) {
            m=a[i];
            ind=i;
        }
    return ind;
}

int Minind(int a[], int s)
{
    int m=a[0], ind=0;
    for(int i=0; i<s; i++)
        if(m>a[i]) {
            m=a[i];
            ind=i;
        }
    return ind;
}

A: You need to send all numbers of possibilities for permutation.
If you change your main function you will get the solution. Add a loop in main funciton and send to nextPermutation(a, i) with variable i
int main() {
    for(int i = 1; i < 5; i++) {
        int a[]= {1,2,3,4};
        nextPermutation(a,i);
    }
    return 0;
}

You should debug your program and also i figure out that your s value is decrasing here:
else if(i==0 && test(a,s)) {
    int p=a[0];
    for(int i=0; i<=s-2; i++) {
        a[i]=a[i+1];
    }
    fl=1;
    nextPermutation(a,s-1);
    //*** careful you are decreasing s here and your output gives 3 numbers. !!***
    a[s]=p;
    fl=0;
    nextPermutation(a,s);
}

A: I just modified the nextPermutation method of your code as follows and it worked.
bool nextPermutation(int a[], int s)
{
    if(s == 0)
        return false;
    int i=Maxind(a,s);
    if(fl==0)
        print(a,s);
    if(i!=0) {
        swap(a[i],a[i-1]);
        if(fl == 0)
            nextPermutation(a,s);
        else{
            int temp = fl;
            fl = 0;
            nextPermutation(a,s+temp);
        }
    }
    else if(i==0){
        int p=a[0];
        for(int i=0; i<=s-2; i++)
            a[i]=a[i+1];
        a[s-1]=p;
        fl+=1;
        nextPermutation(a,s-1);
    }
    else
        return false;
}

Also I removed the methods test and Minind as they are not useful in my code.


text:
Q: Variable doesn't change outside of function JSFiddle : http://jsfiddle.net/veksen/7TRgE/1/
If I call the variable value from inside my function, it works. However, it doesn't if I call it outside of the function.
I feel like it has something to do with change, as it is first assigned ok, but won't change.
var diff_res = { norm:0, nm:-40, hell:-100 };
var difficulty = "hell";
$("select").change(function () {
    difficulty = $("select option:selected").val();
    $(".inside").text(diff_res[difficulty]);
})
.change();

var char_fr = 30;
char_fr += diff_res[difficulty];

$(".outside").text(diff_res[difficulty]);

A: .inside have a event which says: "If someone change-me [...]". .outisde have not events. So:
$(".outside").text(diff_res[difficulty]);

Will execute once only.
See http://jsfiddle.net/7TRgE/2/
Selected option is: "nm" and default value is "-40".

A: UPDATE:
By re-executing, I meant something like this:
$(document).ready(function () {
    'use strict';
    var diff_res = {
            norm: 0,
            nm: -40,
            hell: -100
        },
        difficulty = "hell",
        char_fr = 30,
        changeOutside = function changeOutside() {
            $(".outside").text(diff_res[difficulty]);
        };
    $("select").change(function () {
        difficulty = $("select option:selected").val();
        $(".inside").text(diff_res[difficulty]);
        changeOutside();
    }).change();
    char_fr += diff_res[difficulty];
});

The point was that $(".outside").text(diff_res[difficulty]); is only being executed once, when the DOM is loaded, which is why the text() is initially set to -100. To change the .outside again, you need to re-run $(".outside").text(diff_res[difficulty]);
ORIGINAL:
Your problem is that:
$(".outside").text(diff_res[difficulty]);

is only executed one time, in the $(document).ready() function. If you want it to change more often, you'll need to re-execute that in your change handler.


text:
Q: activemq apollo create broker error I have been trying to create a broker on my activemq apache-apollo 1.6 installation. When I execute the following command:
$APOLLO_HOME/bin/apollo create log1broker

I get the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: /usr/local/lib64/activemq/apache-apollo-1/6
Caused by: java.lang.ClassNotFoundException: .usr.local.lib64.activemq.apache-apollo-1.6
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: /usr/local/lib64/activemq/apache-apollo-1.6. Program will exit.

A: This happens because the apollo startup script assumes your PWD is $APOLLO_HOME.
Do it in this order instead:
$ cd $APOLLO_HOME
$ ./bin/apollo create log1broker


text:
Q: How to fix: The provider did not return a ProviderManifestToken string? I created an ASP.NET Web Application (.NET Framework) with .NET Framework 4.7 and with ASP.NET Web Forms template and authentication mode Individual User Accounts.
My connection string

<add name="DefaultConnection" connectionString="server=mysql server;password=password;port=3306;uid=username;database=schemaname" providerName="MySql.Data.MySqlClient"/>

(It's filled with CORRECT values, but I don't want to publish them...)
Entity Framework

  <entityFramework>
    <defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6" />
    <providers>
        <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
    </providers>
</entityFramework>

Error

System.InvalidOperationException: 'The Entity Framework provider type
  'MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6'
  registered in the application config file for the ADO.NET provider
  with invariant name 'MySql.Data.MySqlClient' could not be loaded. Make
  sure that the assembly-qualified name is used and that the assembly is
  available to the running application. See
  http://go.microsoft.com/fwlink/?LinkId=260882 for more information.'

at

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
     public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)//<-- this line
     {
     }

     public static ApplicationDbContext Create()
     {
         return new ApplicationDbContext();
     }
}

I already read those:

*

*Exception : The provider did not return a ProviderManifestToken string-Entityframework

*The provider did not return a ProviderManifestToken string

*The provider did not return a ProviderManifestToken string error

*Dynamic MySQL database connection for Entity Framework 6

*https://learn.microsoft.com/en-us/aspnet/identity/overview/extensibility/implementing-a-custom-mysql-aspnet-identity-storage-provider

*https://dev.mysql.com/doc/connectors/en/connector-net-entityframework60.html
When I fixed an error another appeared after fixing than appeared another and so on, so I created a new project with settings above and I hope someone can help me to solve this issue. (This is my first time using ASP.NET Web Forms)

A: You appear to be using MySql.Data.Entity 6.10.7. I'm going to guess you're also using MySql.Data 8.0.11.
These two libraries are not compatible. Oracle renamed the package to MySql.Data.EntityFramework for v8.x. You need to uninstall MySql.Data.Entity and install MySql.Data.EntityFramework.


text:
Q: Sproutcore menu I'm starting to learn sproutcore(v1.7.1.beta). I am very concerned about the issues of proper implementation some things...one of them is main menu.
What the right way to do that?
I think I need to change state if menu item has been clicked, right? I tried to do it with SC.TemplateCollectionView, but can't understand, how to determine what item have been clicked?
My CollectionView:
App.MainMenuItemView = SC.TemplateCollectionView.extend({
  contentBinding: 'App.mainMenuController',
  mouseUp: function(){
    //
  }
});

A: You want to use
SC.SegmentedView.  Something like
topNav: SC.SegmentedView.extend({
    classNames: ['top-nav'],
    items: [
        {
            title: "App.title1".loc(),
            value: 1,
            action: 'action1'
        },
        {
            title: "App.title2".loc(),
            value: 2,
            action: 'action2'

        },
        ....
    ],
    itemTitleKey: 'title',
    itemValueKey: 'value',
    itemWidthKey: '85',
    itemActionKey: 'action',
    valueBinding: 'Binding to current tab value'
})

You can specify an icon via itemIconKey....
Or just roll your own custom SC.View.


text:
Q: Disable only Excel previews in Windows 10 folder preview pane Pretty self explanatory title.
I've got a Windows 10 machine with the preview pane turned on, because I often have to sort through PDFs. However, large Excel files hog the computer for 3-10 seconds at a time, when usually what I do with them is just copy-pasting them around (no need for previewing them).
Can I only disable excel previews, but still have PDFs previewing regularly?

A: ShellExView is a great utility that allows to do this.

A: There is a "Preview Handler" associated with every file extension in the registry, that can be disabled.
The known file extensions are under HKEY_CLASSES_ROOT as ".xlsx" for example. If the extension has a Preview Handler, then there is a subkey always called "HKEY_CLASSES_ROOT\.xlsx\ShellEx\{8895b1c6-b41f-4c1c-a562-0d564250836f}".
That subkey has a default value that points to the Preview Handler, if you clear that default value or remove the subkey, the preview for that file extension will be disabled.
You could store a copy of that key by going right-click -> Export, so that you can restore the preview handler later if need be.
I gathered this from a Microsoft document here, even though they describe an extra "step" in mapping the preview handler, which i found not to be the case on Windows 7, 10 and Server 2016. Maybe someone can explain/correct this.

A: Windows Explorer:
Click one of the following: Tools > Folder Options > View or Organize >Folder and search options. Clear Show preview handlers in preview pane.

A: I needed to disable Excel previewer because of some issues it was causing with Excel display scaling. ShellExView and Windows Explorer approaches didn't work for me but the direct registry edit did.


text:
Q: How to redirect to thank you page after woocommerce checkout order processed im trying to change order status to "completed" and skip payment page (go to thank you page) after order is processed.
so far i manage to change order status to completed but instead of redirecting me to thank you page, i will be redirected to payment page with the following error :

this is the code i use :
add_filter( 'woocommerce_checkout_order_processed' , 'skip_join_payment' );
function skip_join_payment( $order_id ) {
     if ( ! $order_id ) {
        return;
    }
    if( $_COOKIE['isjoinForFree'] == "yes" ){
        $order = wc_get_order( $order_id );
        $order->update_status( 'completed' );

        ** i tried to redirect here but getting error on checkout page **
        // if ( $order->has_status( 'completed' ) ) {
                // header("Location: /jtnx/");
                // die();
        // }

    }
}

in addition i tried adding another hooks with redirect :
add_action( 'woocommerce_payment_complete', 'skiped_join_payment_redirect', 1 );
function skiped_join_payment_redirect ( $order_id ){
    $order = wc_get_order( $order_id );
    if( $_COOKIE['isjoinForFree'] == "yes" ){
    $order = wc_get_order( $order_id );
    if ( $order->has_status( 'completed' ) ) {
            header("Location: /jtnx/");
            die();
        }
    }
}

A: if anyone step into this error that was my fix.
the reason for the redirect fail occur cause of the checkout ajax still running,
i added this code into my function.php, works well.
add_action( 'template_redirect', 'joined_for_free_redirect_to_thankyou' );
    function joined_for_free_redirect_to_thankyou(){
        if( !is_wc_endpoint_url( 'order-pay' )) {
            return;
        }

        global $wp;
        $order_id =  intval( str_replace( 'join/order-pay/', '', $wp->request ) );
        $order = wc_get_order( $order_id );
        if ( $order->has_status( 'completed' ) && $_COOKIE['isjoinForFree'] == "yes" ) {
            wp_redirect( site_url() . '/jtnx/' );
            exit;
        }
    }

if anyone think he has a better way to fix it i will still be happy to hear :)

A: try steps below:

*

*use absolute, full target page address in header like
header('Location: http://www.example.com/');. See header for the reason.

*Ensure that if( $_COOKIE['isjoinForFree'] == "yes" ) { is true.

*If you need, insert the else { part of if( $_COOKIE['isjoinForFree'] == "yes" ) { loop


text:
Q: Configuring TDS manually with Encryption DB2 When I upgrade my Simple DB2 v10.5.0.0 with Fix pack for Encryption DB2,it changes the db2level from 10.5.0.0 to 10.5.0.3.
And when I tune my DB2 with TDS. I first create an instance then set admin password and when I run command "/opt/IBM/ldap/V6.3/sbin/idscfgdb -n -I <instance name> -a <instance name> -w <password> -t <ids database name> -l /home/<instance name>", for create Database it failed with error
GLPCTL026I Creating database: 'db2ldap'.
GLPCTL028E Failed to create database: 'db2ldap'. The failure might have occurred because the system was not set up correctly before using the tool.
GLPCTL011I Stopping database manager for the database instance: 'db2inst1'.


text:
Q: How can I convert a uploaded XML file that is in the form of a HttpPostedFIle to a string in C# asp.net? How can I convert a uploaded XML file that is in the form of a HttpPostedFIle to a string in C# asp.net? I am trying to create the ability to upload an XML file and store it on a database server for a client that is using my web application. I need to convert it to a string so I can do string manipulation to the XML file and remove some elements in the XML file that are not compatible with SQL server.
I've tried this and a few other things. I keep getting the error

InputStream is not in this current context

and another error.
string xmlString = System.IO.File.ReadAllText(fl.InputStream.ToString());
            string fName = fl.FileName;
            if (fName.IndexOf("\\") != -1) { fName = fName.Substring(fName.LastIndexOf("\\") + 1); }
            string fileDataLink = uniqueName + Path.GetExtension(fName);
            outputPath += fileDataLink;
            fl.SaveAs(outputPath);
            transactionTypeID = Convert.ToInt32(Request["textInput"]);
            integrationTypeDt = DAC.ExecuteDataSetText(db.ConnectionString, "SELECT [StoredProcName], [Configuration] FROM [dbo].[ITransactionType] WITH(NOLOCK) WHERE [TransactionTypeID] =" + transactionTypeID, new string[] { "IntegrationType" }).Tables[0];

            string workbookXML = "";
            //load the file,
            string xmlString = System.IO.File.ReadAllText(fl.InputStream.ToString());

            //make changes

            //Assign the file to the XML var,

            //and then save it into the database

I expect it to return a string value of the entire file that was uploaded. Instead, I am getting two errors. One says InputStream is not in the current context.

A: There are several ways to fix your code.
This would be one way:
        string fileDataLink = uniqueName + Path.GetExtension(fl.FileName);
        outputPath += fileDataLink;
        // not needed if you do not want the file on both disk and database
        //fl.SaveAs(outputPath);

        transactionTypeID = Convert.ToInt32(Request["textInput"]);
        integrationTypeDt = DAC.ExecuteDataSetText(db.ConnectionString, "SELECT [StoredProcName], [Configuration] FROM [dbo].[ITransactionType] WITH(NOLOCK) WHERE [TransactionTypeID] =" + transactionTypeID, new string[] { "IntegrationType" }).Tables[0];

        string workbookXML = "";
        //load the file,
        string xmlString = null;
        using(var reader = new StreamReader(fl.InputStream))
        {
           xmlString = reader.ReadToEnd();
        }

Another way would be to keep the SaveAs and write:
string xmlString = System.IO.File.ReadAllText(outputPath);

Which would load the file from disk.
Please note two things:

*

*Your solution loads the entire xml file into memory for processing. This might not be a problem in your scenario, but if you for example have many users and they upload multiple large files simultaneously your server might run out of memory. In such a case it would be better to try a different solution that in some way feeds the stream as a stream to the database.

*You should never concatenate a value that is input from a web page to your sql as is done in the statement  "SELECT [StoredProcName], [Configuration] FROM [dbo].[ITransactionType] WITH(NOLOCK) WHERE [TransactionTypeID] =" + transactionTypeID Use SQL parameters instead instead.


text:
Q: Apache Spark function to_timestamp() not working with PySpark on Databricks I'm getting NULL output when I execute the code to_timestamp()
The code that I'm executing is as follows:
.withColumn("LAST_MODIFICATION_DT", to_timestamp(concat(col('LAST_MOD_DATE'), lit(' '), col('LAST_MOD_TIME')), 'yyy-MM-dd HH:mm:ss'))

The schema for the fields LAST_MOD_DATE & LAST_MOD_TIME is as follows:

I'm getting the output 'NULL' for the column 'LAST_MODIFICATION_DT'
Any thoughts?

A: In Spark SQL concat doesn't convert null to ''; any null argument will cascade into a null result. It's often easier to write these kind of expressions in python and register them as UDFs, eg
from pyspark.sql.types import StringType

def concat2_(s1, s2) -> str:
  return str(s1) + ' ' + str(s2)

concat2 = spark.udf.register("concat2", concat2_, StringType())

Then you can use it in Spark queries in built in python,
from pyspark.sql.functions import col
df = spark.sql('select 1 a, 2 b').withColumn("c",concat2(col('a'),col('b')))
display(df)

or SQL
%sql
with q as
(select 1 a, 2 b)
select a,b,concat2(a,b) c
from q


text:
Q: TFS Build using conditional compilation symbols (DefineConstants) from .csproj file I have a solution that I build in TFS 2010 build. This solution and its build has 3 configurations set (Development, Integration, Release). I have set the build to build all of them, and it works mostly fine.
In this solution, there's a Silverlight project, which sets different conditional compilation symbols depending on which configuration is being built because it has different web service URLs for each configuration, like this:
    private const string STR_WS_EndPoint =
#if INTEGRATION
        "Integration_WS_EndPoint";
#elif DEVELOPMENT
        "Development_WS_EndPoint";
#elif DEBUG
        "Debug_WS_EndPoint";
#else
        "Release_WS_EndPoint";
#endif

When I build these different configurations in Visual Studio, it selects the right string for each configuration, but when TFS builds the different configuration, they all end up with the "Release_WS_EndPoint" string (I checked using ILSpy), i.e. none of the conditional symbols were active. How do I get TFS build to pick up on these compilation symbols? I can't use the "MSBuild Arguments" field in the build for this, because like I said, it builds all the different configurations, so I need it to use the .csproj compilation symbols like Visual Studio does.

A: I'm using XmlPreprocess tool for config files manipulation depending on the build configuration. It is using one mapping file for multiple environments/servers. You can edit mapping file by Excel. It is very easy to use.
Call XmlPreprocess in the after build step and pass configuration as environment parameter.


text:
Q: Using mysqli_multi_query in an existing function I have a function that can make different types of database connections and, simplified below with only two such $ActionType values, it is the second one I am having difficulty with. No errors but no results either. Any ideas?
The query contains multiple queries such as:
$Query = "SQL statement #1;";
$Query .= "SQL statement #2;";
$Query .= "SQL statement #3;";

and this is the function, cut down to fit here:
function DBConnect($Query, $ActionType, $DBname, $selType='array') {
    $ActionType = trim(strtolower($ActionType));

    if (!$Query) :
        exit();
    endif;

    $MySQLError = "";
    $mysqli = dbConn($DBname);

    if ($Query && $mysqli->connect_errno != 0):
        $MySQLError = "
";
        $MySQLError .= printf("Connect failed: %s\n", $mysqli->connect_error);
        $MySQLError .= "
\n\n";
        return $MySQLError;
        exit();
    endif;

    switch ($ActionType) :
        case "multiple":
            if ($result = $mysqli->query($Query)) :
                $numrowsCat = $result->num_rows;
                if ($numrowsCat >= 1) :
                    $result = $mysqli->query($Query);
                    if ($selType === "assoc") :
                        while($row = $result->fetch_assoc()) :
                            $results_array[] = $row;
                        endwhile;
                    else :
                        while($row = $result->fetch_array()) :
                            $results_array[] = $row;
                        endwhile;
                    endif;
                    return $results_array;
                endif;
                $MySQLError = ($mysqli->connect_errno) ? mysqli_error($mysqli) : "";
                $mysqli->close();
                if ($MySQLError) return $MySQLError;
            endif;
        break;

        case "multiquery":
            if ($result = $mysqli->multi_query($Query)) :
                if ($result) :
                    while($row = $result->fetch_array()) :
                        $results_array[] = $row;
                    endwhile;
                    return $results_array;
                endif;

                $MySQLError = ($mysqli->connect_errno) ? mysqli_error($mysqli) : "";
                $mysqli->close();
                if ($MySQLError) return $MySQLError;
            endif;
        break;

    endswitch;
}


text:
Q: How to sort-object lastlogon -descending? I have to check the lastlogon for different users.
My script queries my domain controllers to output my report, however I have an issue.
My report does not come out in descending order. I added sort-object lastlogon -descending, but the dates don't come out correctly in my file. Can you help me?
$data = @()
$DCs = Get-ADDomainController -Filter * | Select-Object -ExpandProperty name
$users =
@'
samaccountname;
user1
user2
'@ | ConvertFrom-Csv -Delimiter ';'
foreach ($DC in $DCs) {
            foreach($user in $users)
                {$data += Get-ADUser $User.samaccountname.Trim() -Properties displayname, userprincipalname, samaccountname, lastlogon -server $DC | Select-Object DisplayName, UserPrincipalName, SamAccountName, Enabled, @{name='LastLogon';expression={[datetime]::fromFileTime($_.lastLogon).ToString('yyyy-MM-dd')}} }
                    }
$data | Group-Object Lastlogon | Foreach-Object {$_.Group | Sort-Object lastLogon -Descending | Select-Object  -Last 10 | Export-Excel "C:\temp\lastlogon ($(Get-Date -Format "yyyy-MM-dd")).xlsx"}

write-host Done! -ForegroundColor Green

A: It's unclear what you want to accomplish with your script but basically, if you .ToString(..) a DateTime object then Sort-Object will not know how to sort it correctly. Here is how you can approach your code:
$DCs = (Get-ADDomainController -Filter *).Name
$users = @'
samaccountname;
user1
user2
'@ | ConvertFrom-Csv -Delimiter ';'

& {
    foreach ($DC in $DCs) {
        foreach($user in $users) {
            $params = @{
                Properties = 'displayname', 'lastlogon'
                Server     = $DC
                Identity   = $User.samaccountname.Trim()
            }
            Get-ADUser @params | Select-Object @(
                'DisplayName'
                'UserPrincipalName'
                'SamAccountName'
                'Enabled'
                @{
                    Name = 'LastLogon'
                    Expression = {
                        [datetime]::fromFileTime($_.LastLogon)
                    }
                }
            )
        }
    }
} | Group-Object { $_.Lastlogon.ToString('yyyy-MM-dd') } | Foreach-Object {
    $_.Group | Sort-Object LastLogon -Descending | Select-Object -Last 10 |
    Export-Excel "C:\temp\lastlogon ($(Get-Date -Format "yyyy-MM-dd")).xlsx"
}

You also want to avoid adding elements (+=) to a fixed collection (@()).


text:
Q: Video Periodically freezes on Home Network I have a Windows 7 tower sharing video to my Xbox and Macbook laptop over a Gigabit / Wireless N home network (router is the linksys wireless N model).  Whenever I watch a video streamed from my tower to either the xbox or laptop, the movie freezes every few minutes.  The freezes last longer and longer until the video freezes for good.  What is going on here?  Is there some bottleneck in the router like a full cache file that needs to be cleaned or something?  Thanks for any help.

A: This could be a number of things, the most likely cause is signal strength on Wireless or a faulty cable if using wired. It could even be a bad router which simply cannot cope with high throughput.
The other causes are slow I/O on your machine where it cannot cache/send the video fast enough - however, it should not be getting worse as you go along.
How are you connected from device to device? If you are doing wireless to router, wireless to Xbox, I would highly recommend you just use a wire temporarily to rule out a problem with wireless.

A: Windows 7 has a powerful network monitor which is worth checking with.
Task Manager -> Performance -> Resource Monitor -> Network
You should be able to identify if anything else is clogging up the streaming on your PC side.


text:
Q: Scrapy broad crawl returning error "filedescriptor out of range in select()" I'm trying to run a simple broad crawl on 2,000 domains using Scrapy.
I have 4 lists of 500 domains each then I simple run the process.crawl on these 4 lists.
I'm just scraping their homepage for now.
The issue is after the 1,000 first domains, I start getting the following error ("filedescriptor out of range in select()"):
2019-10-20 00:24:59 [scrapy.core.scraper] ERROR: Error downloading <GET https://www.******.com>
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/scrapy/core/downloader/middleware.py", line 44, in process_request
    defer.returnValue((yield download_func(request=request, spider=spider)))
twisted.internet.error.ConnectError: An error occurred while connecting: [Failure instance: Traceback: <class 'ValueError'>: filedescriptor out of range in select()

Note: replaced the domain with ****** in the error

Below is my function:
import scrapy
class scan_scripts(scrapy.Spider):

    name = 'scan_scripts'

    custom_settings = {
        'CONCURRENT_REQUESTS': 500,
        'CONCURRENT_REQUESTS_PER_DOMAIN': 25,
        'CONCURRENT_ITEMS': 50,
        'REACTOR_THREADPOOL_MAXSIZE': 500,
        'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)',
        'LOG_LEVEL': 'ERROR',
        'HTTPCACHE_ENABLED': False,
        'COOKIES_ENABLED': False,
        'SCHEDULER_PRIORITY_QUEUE': 'scrapy.pqueues.DownloaderAwarePriorityQueue',
        'RETRY_ENABLED': False,
        'DOWNLOAD_TIMEOUT': 15,
        'REDIRECT_ENABLED': False,
        'AJAXCRAWL_ENABLED': True,
        'DEPTH_PRIORITY': 1,
        'SCHEDULER_DISK_QUEUE': 'scrapy.squeues.PickleFifoDiskQueue',
        'SCHEDULER_MEMORY_QUEUE': 'scrapy.squeues.FifoMemoryQueue'
    }

    def start_requests(self):

        for domain in self.domains:
            yield scrapy.Request("https://" + domain, self.parse)

    def parse(self, response):

        print('### SCANNED: %s', (response.request.url))

Then I run this:
process = CrawlerProcess({})

process.crawl(scan_scripts, domains=domains_list1)
process.crawl(scan_scripts, domains=domains_list2)
process.crawl(scan_scripts, domains=domains_list3)
process.crawl(scan_scripts, domains=domains_list4)

process.start()


text:
Q: Проблема с списком enemys у меня есть список enemys в котором enemys[0][0] это enemys_x, а enemys[0][1] - enemy_y список выглядит так:
[[enemy_x, enemy_y, enemy_size, enemy_size, color]]

полная ошибка:
line 40, in painter
    for i in enemys[b]:
TypeError: 'enemy' object is not iterable

    for b in range(len(enemys)):
        for i in enemys[b]:
            if i != enemys[i][0] and i != enemys[i][1]:
                i.draw(window)

этот код должен проверить есть ли одинаковые элементы в списке и если их нету выводить результат, но выводит 'enemy' object is not iterable.

A: На сколько я понял, элемент из списка enemys выглядит так: (enemy_x, enemy_y), если это так, то python не может выполнить этот код, так как enemys[b] это координаты, а не список

A: Попробуйте этот код:
for i in enemys:
    for j in enemys:
        if i != j:
            i.draw(window)


text:
Q: Uh oh Looks like something went wrong. Please try again later. Yahoo Passport I'm build autheticate using passport yahoo, this is my configuration
yahoo : {
      clientID: "YYYYYYYYYYYYYYYYYYYYYYYYYYYYy",
      clientSecret: "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
      callbackURL: "http://black.jack.co/auth/yahoo/callback"
    }

and this is my configuration on yahoo developer
Aplication Name: autheticate yahoo
Home page URL:  http://black.jack.co
Callback Domain : http://jack.co
When I tried to login, yahoo callback give an error
Uh oh
Looks like something went wrong.
Please try again later. How to fix this?

A: Please look after your URL
just double clicking and trying to change clientid will not help due to -- present in the url below
https://api.login.yahoo.com/oauth2/request_auth?
client_id=dj0yJmk9ak5IZ2x5WmNsaHp6JmQ9WVdrOVNqQkJUMnRYTjJrbWNHbzlNQS0tJnM9Y29uc3VtZXJzZWNyZXQmeD1hYQ-- //this over here is ok -- might be extra for your client id
&redirect_uri=oob
&response_type=code
&language=en-us
double click will generate
https://api.login.yahoo.com/oauth2/request_auth?
client_id=[YOURIDAND]--
&redirect_uri=oob
&response_type=code
&language=en-us
If this wont help please delete app and recreate
Your client id will not always have -- at the end
I made a stupid mistake and spend extra time to resolve the issue hope it helps


text:
Q: Angular $http not handling error My angular app doesn't handle the errors in $http calls.
I have a $httpProvider where I return $q.reject(response) in errorResponse as required by documentation. In the console the angular just puts angular.min.js:99 GET http://localhost:8080/my/api 500 (Internal Server Error).
Code
console.log('before');
$http.get('/my/api', function(response){
   console.log('ok');
   console.log(response);
}, function(response){
    console.log('not ok');
    console.log(response)
});
console.log('after');

I just get 'before', 'after' and the message above.
Also in the network tab I get the expected response from server with status 500 and a json content in the body.
Except for the $httpProvider's errorResponse without a return $q.reject(), what could be the problem?

A: You have syntactical mistake, you should use .then function and then put success & error callback to them.
Code
$http.get('/my/api').then(function(response){
   console.log('ok');
   console.log(response);
}, function(response){
    console.log('not ok');
    console.log(response)
});

What I understood by your code/question is, you are expecting to get error callback function to execute, but it is not doing that. If I missed something then do ask same in comments.


text:
Q: SqlDataAdapter with using keyword Is this the following code healthy? Or I don't need to use the using keyword as the SqlDataAdapter will handle closing the connection?
public static DataSet Fetch(string sp, SqlParameter [] prm)
{
    using (SqlConnection con = new SqlConnection(ConStr))
    {
        using (SqlCommand cmd = con.CreateCommand())
        {
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = sp;
            cmd.Parameters.AddRange(prm);

            using (SqlDataAdapter dta = new SqlDataAdapter(cmd))
            {
                DataSet dst = new DataSet();
                dta.Fill(dst);

                return dst;
            }
        }
    }
}

@MarkGravell I need a suggestions here, I am really looking to use DataReader, but I was looking all the time to use the using keyword to ensure closing the connections. Where with DataReader we can not use it because it will close the connection if we want to return the DataReader back to some method.
So do you think the following technique is fine with DataReader and the using keyword:
public static SqlDataReader Fetch(string sp, SqlParameter [] prm)
{
    SqlCommand cmd = new SqlConnection(ConStr).CreateCommand();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.CommandText = sp;
    cmd.Parameters.AddRange(prm);
    cmd.Connection.Open();

    return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}

using (SqlDataReader dtrPrize = Sql.Fetch("SelectPrize", new SqlParameter[] { new SqlParameter("id", id) }))
{
    dtrPrize.Read();

    Prize prize = new Prize();
    prize.id = (int)dtrPrize[dtrPrize.GetOrdinal("id")];
    prize.artitle = (string)dtrPrize[dtrPrize.GetOrdinal("artitle")];
    prize.entitle = (string)dtrPrize[dtrPrize.GetOrdinal("entitle")];
    prize.ardetail = (string)dtrPrize[dtrPrize.GetOrdinal("ardetail")];
    prize.endetail = (string)dtrPrize[dtrPrize.GetOrdinal("endetail")];
    prize.image = (string)dtrPrize[dtrPrize.GetOrdinal("image")];
    prize.theme = (string)dtrPrize[dtrPrize.GetOrdinal("theme")];
    prize.price = (int)dtrPrize[dtrPrize.GetOrdinal("price")];
    prize.audience = (int)dtrPrize[dtrPrize.GetOrdinal("audience")];
    prize.type = (byte)dtrPrize[dtrPrize.GetOrdinal("type")];
    prize.status = (byte)dtrPrize[dtrPrize.GetOrdinal("status")];
    prize.voucher = (string)dtrPrize[dtrPrize.GetOrdinal("voucher")];
    prize.supplierid = (int)dtrPrize[dtrPrize.GetOrdinal("supplierid")];
    prize.created = (DateTime)dtrPrize[dtrPrize.GetOrdinal("created")];
    prize.updated = (DateTime)dtrPrize[dtrPrize.GetOrdinal("updated")];

    return prize;
}

A: Healthy-ish; personally I'd say the unhealthy bit is the bit where it makes use of DataSet and DataAdapter, but that is perhaps just my personal bias.
Yes, you should dispose the adapter etc here (which is what the using does for you, obviously).
As a trivial pointless tidy, you can stack the usings - just makes it a little less verbose:
using (SqlConnection con = new SqlConnection(ConStr))
using (SqlCommand cmd = con.CreateCommand())
{

A: It will be enough to leave just the first using (the one on the Connection) because disposing the connection will dispose everything you need disposed.
However, there is no harm disposing everything, just a bit more code.


text:
Q: setVisibility() in onClick() makes app crash I'm trying to show pic after pressing ImageButton, but when I test it on my phone it just crashes and drops me on previous Activity.
There are some more Activities, but each of them works normally.
ActionActivity.java
public class ActionActivity extends AppCompatActivity implements View.OnClickListener {

    ImageButton PhotoHint;
    ImageView PhotoPic;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.action);

        ImageButton PhotoHint = (ImageButton) findViewById(R.id.PhotoHint);
        ImageView PhotoPic = (ImageView) findViewById(R.id.Photo);

        PhotoPic.setVisibility(View.INVISIBLE);
        PhotoHint.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.PhotoHint:
                PhotoPic.setVisibility(View.VISIBLE);
        }

    }
}

action.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
...

    <FrameLayout
        android:id="@+id/frameLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/Photo"
            android:layout_width="189dp"
            android:layout_height="169dp"
            android:layout_gravity="center"
            android:background="@drawable/somepic"
            />

        <ImageButton
            android:id="@+id/PhotoHint"
            android:layout_width="42dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center|bottom"
            app:srcCompat="@android:drawable/ic_menu_gallery" />

    </FrameLayout>
</LinearLayout>

A: try now it will work fine...
the problem was with this line
 ImageButton PhotoHint = (ImageButton) findViewById(R.id.PhotoHint);
        ImageView PhotoPic = (ImageView) findViewById(R.id.Photo);

they were not globally initialized that's why you were facing crash.!
public class ActionActivity extends AppCompatActivity implements View.OnClickListener {

        ImageButton photoHint;
        ImageView photoPic;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.action);

             photoHint = (ImageButton) findViewById(R.id.PhotoHint);
             photoPic = (ImageView) findViewById(R.id.Photo);

            photoPic.setVisibility(View.INVISIBLE);
           photoHint.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.PhotoHint:
                    photoPic.setVisibility(View.VISIBLE);
            }

        }
    }


text:
Q: Matplotlib displaying histogram with a specific value on x and y axis fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

value = [8904,8953,8977,9147,9243,9320]
bin = np.arange(0,70,10)
ax.hist(value, bins=bin)
plt.grid(True)
plt.show()

I am trying to plot a histogram with the value array on the x-axis and the y-axis will be the bin. But when I run the code I get an empty chart. Could anyone please help me out. Thank you

A: First thing I see is that in your values array, your data points aren't separated by commas.
Second thing, your values are outside the ranges of your bins. All your values are well into the thousands, and your bins' range is between 0 and 70.
Here is my edited version of your code (I included my import statements to make things clear). I changed the values to being within your bin ranges:
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

value = [7, 8, 15, 45, 50, 80]
bin = np.arange(0,70,10)
ax.hist(value, bins=bin)
plt.grid(True)
plt.show()

The result I get is this image, which illustrates what's going on. The data point 80 is outside the bin range, and therefore isn't shown at all, just like the data points you originally had. Other than that, all data points are shown in the histogram.
Hope this helps!
Edit: you said in a comment to this answer that you want it to be horizontal, not vertical. You add orientation="horizontal" to your ax.hist statement as an argument. New code looks like this:
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)

value = [7, 8, 15, 45, 50, 80]
bin = np.arange(0,70,10)
ax.hist(value, bins=bin, orientation="horizontal")
plt.grid(True)
plt.show()

Your plot should now look like this.


text:
Q: Spring Auditable entity is being modified even when nothing has changed NOTE: This is a complicated question so I hope I've covered the relevant parts. If not, I will edit and add more information as requested.
We're using Spring (4.1.0) with Hibernate (4.3.6) and we've defined a base class that all of our entities extend called BaseAuditableEntity (code below). When any entity is loaded in a @Transactional method and then modified and saved, that entity's modified_by_user_id and modified_ts are both updated with the id of the user logged in performing whatever change is being made.
Our problem is that whenever an AppUser (which also extends BaseAuditableEntity) is loaded in one of these @Transactional methods, it's also seeing the modified_by_user_id and the modified_ts being set even if it hasn't been modified. This creates a problem because we're writing to our user table with almost every request when we don't need to be. Note that this also may affect @Transactional methods that don't load the AppUser explicitly because the AuditorBean loads an AppUser itself.
I'm assuming this has something to do with the fact that the AppUser entity is part of the BaseAuditableEntity itself. Can someone confirm this? Is there a way to solve this problem?
Our BaseAuditableEntity class that every entity including AppUser extends:
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class BaseAuditableEntity implements Auditable<AppUser, Long> {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "hibernate_sequence")
    @SequenceGenerator(name = "hibernate_sequence", sequenceName = "blah_sequence", allocationSize = 1)
    @Column(name = "id")
    private Long id;

    @CreatedBy
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "created_by_user_id")
    private AppUser createdBy;

    @LastModifiedBy
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "modified_by_user_id")
    private AppUser lastModifiedBy;

    @Column(name = "created_ts")
    @CreatedDate
    @Temporal(TemporalType.TIMESTAMP)
    private Date createdDate;

    @Column(name = "modified_ts")
    @LastModifiedDate
    @Temporal(TemporalType.TIMESTAMP)
    private Date lastModifiedDate;

    // ...
}

Our JpaConfig:
@Configuration
@EnableJpaRepositories(basePackages = {
        "blah.blah.blah"})
@ComponentScan(basePackageClasses = {AuditorBean.class})
@EnableTransactionManagement
@EnableJpaAuditing(auditorAwareRef = "auditorBean")
public class JpaConfig extends BaseConfig {

    // ...

}

And our AuditorBean:
@Component
public class AuditorBean implements AuditorAware<AppUser> {

    @Override
    public AppUser getCurrentAuditor() {
        // omitting some code that finds a user. I think the only relevant thing here
        // is that we're using the repo to find the user by ID and not using an
        // entity that's already been loaded
        return userRepository.findOne(id);
    }

}

A: My suggestion is to keep audit simple anddefine
@CreatedBy
private Long createdBy;

without actual association and store there just AppUser's id.
@Component
public class AuditorBean implements AuditorAware {
@Override
public Long getCurrentAuditor() {
    // .... find out the id
    return id;
}

}


text:
Q: Canceling noise given a LPCM array of 44 samples per second I have an array of 44100 samples per second of LPCM data.  Actually I have two channels worth of data.
Every 11.61 milliseconds I get around 512 samples.
Now I want to follow the directions on How to cancel noise from audio
However, that explanation assumes the input is a sinusoidal wave.
Should I convert my LPCM to sinusoidal waves to cancel the noise?  That is, am I required to run FFT on the LPCM in order to apply this technique?
And if so, how do I convert the resulting wave forms back to LPCM so they can be played?

A: If you need to convert back from frequency domain to time domain, you can just use inverse Fourier transform. Otherwise, I think there are plenty more noise-reduction algorithms.

A: you want to cancel noise where?  to cancel noise at the detector (where you have the microphone) you simply need to invert the signal (swap + and - cables), match the amplitude, and shape the frequency to correct for your equipment.  to cancel noise at some other point on a line that joins source and microphone you need to also add a delay (if cancelling further away) or somehow "advance" the sound (if cancelling between source and microphone).  if cancelling off-axis then things get more complicated (and you need both signals).
in the complicated cases (off-axis or before the microphone) you need to do some kind of more advanced signal processing.  one way to do that is to use ffts, but it might be more efficient to find approximations that use digital filters
i would guess that bose headphones and the like use signal inversion, amplification and some fairly simple frequency shaping, plus perhaps some kind of feedback detection (to avoid deafening people if it all goes wrong).
update: here is a really good paper on how the headphones work.  they have various approaches including training a filter on white noise.   and it's more complex than i guessed above.


text:
Q: Warning in rnorm and shiny: NAs produced Has anyone come across and managed to solve an issue with sampling from normal distribution in Shiny R, please? I'm struggling to find a solution: this question was asked before but no answer was found.
Sampling using rnorm results in output consisting entirely of NAs in Shiny; no such problems outside Shiny app.
library(shiny)

ui<-shinyUI(fluidPage(

sidebarPanel(
sliderInput("Rmax", label="growth", min=0,max=2, value=1),
sliderInput("sd_Rmax", label = "sd for rmax", min=0.05, max=1, value = 0.35),
sliderInput("K", label="K", min=2, max=70, value = 10.1),
sliderInput("sd_K", label="sd for K", min=2,max=70, value=1.48),
sliderInput("ss", label="Sample Size", min=30,max=300, value=30)
),

mainPanel(
verbatimTextOutput("Statistics"))
))

server<-shinyServer(function(input, output){
data<-reactive({

#here are my inputs; convert inputs to log-scale:
ln_rmax<-log(input$Rmax, base=exp(1))
ln_K<-log(input$K, base=exp(1))
ln_sd_rmax<-log(input$sd_Rmax, base=exp(1))
ln_sd_K<-log(input$sd_K, base=exp(1))

#sample from normal
s_ln_rmax<-rnorm(input$ss*19,mean=ln_rmax,sd=ln_sd_rmax) # Here's where the problem is
s_ln_K<-rnorm(input$ss*19,mean=ln_K,sd=ln_sd_K)

phi<-seq(0,0.9, by=0.05)
phi_s<-rep(phi, input$ss)

#convert back
s_rmax<-exp(s_ln_rmax)
s_K<-exp(s_ln_K)
D<-runif(19*input$ss,min=0.2*s_K, max=0.8*s_K)

#combine into a dataframe
combs<-as.data.frame(cbind(s_rmax,s_K, phi_s, D))
})

output$Statistics <- renderPrint({ summary(data())})
})

shinyApp(server = server, ui = ui)

This is the warning message I get:
 Warning in rnorm(input$ss * 19, mean = ln_rmax, sd = ln_sd_rmax) : NAs produced. Strangely, the problem is with the first sampled variable s_rmax, and not the second sampled variable s_K.
I need to use the first variable further along in my code.
Thank you for any help in advance.

A: Your default sd parameter for rnorm is negative (-1.049822) for s_ln_rmax. However, it is positive for s_ln_K (0.3920421), hence why you can extract a random sample for one set of parameters and not the other.
In fact, you will have to change all your paramters in the sliderInput for "sd_Rmax".
sliderInput("sd_Rmax", label = "sd for rmax", min=0.05, max=1, value = 0.35)

precludes any possibility of getting a random distribution because of how you transform input$sd_Rmax. It must be something of this sort if you want to keep transforming the input using a natural log:
sliderInput("sd_Rmax", label = "sd for rmax", min=1, max=Inf, value = 2.5)


text:
Q: Centering is not working The below piece of code is not getting center aligned. Kindly help in finding out the solution for the same
\begin{table}[!ht]
\begin{tabular}{|c||c|c|c|c|c|} \hline
\centering
AE mode & 512 Byte & 1KB  & 1 MB & 1 GB & 2048 PetaBytes ($2^{64}$) \\ \hline \hline
%IACBC & BC & & & m + 2 & n & n & n & 2 independent random keys are required  \\ \hline
\end{tabular}
}
\end{table}

A: You want to center the tabular itself. Then you should put \centering outside that environment (but still inside table environment). By the way, you have an extra }.
\begin{table}[!ht]
  \centering
  \begin{tabular}{|c||c|c|c|c|c|}
    \hline
    AE mode & 512 Byte & 1KB  & 1 MB & 1 GB & 2048 PetaBytes ($2^{64}$) \\
    \hline
    \hline
    %IACBC & BC & & & m + 2 & n & n & n & 2 independent random keys are required  \\
    \hline
  \end{tabular}
\end{table}


text:
Q: Preventing JIT inlining on a method I've got sort of a unique situation.  I've been working on an open source library for sending email.  In this library, I need a reliable way to get the calling method.  I've done this with a StackTrace by analyzing the StackFrame objects inside it.  This works without issue in a debug-mode project where optimizations are turned off.
The problem occurs when I switch to release mode where optimizations are turned on.  The stack trace looks like this:
> FindActionName at offset 66 in file:line:column <filename unknown>:0:0
> Email at offset 296 in file:line:column <filename unknown>:0:0
> CallingEmailFromRealControllerShouldFindMailersActionName at offset 184
     in file:line:column <filename unknown>:0:0
> _InvokeMethodFast at offset 0 in file:line:column <filename unknown>:0:0
> InvokeMethodFast at offset 152 in file:line:column <filename unknown>:0:0
...

This is taken from a failing unit test.  In line 3 of this trace, I should see a method called TestEmail which is defined elsewhere, but I believe the JITter is inlining it.  I've read that you can prevent inlining by making a method virtual, but this doesn't work.  Does anyone know of a reliable method for preventing method inlining so your method will show up in a stack trace?

A: You could use additional parameters marked with System.Runtime.CompilerServices.CallerMemberNameAttribute and it's siblings CallerFilePath and CallerLineNumber. If I understand it correctly this should get you the correct method name, no matter what's inlined an what's not. You will only get the method name however, I don't see anything to get the class name/assembly etc.
It should go without saying, but just to be sure... something like this should not be used outside of logging/diagnostics.
Proper ways to do this would probably be:

*

*Pass the required information as a parameter

*Temporarily store the required information in Thread.ExecutionContext while calling the function

I realize that this probably won't be of any help to Scott after all this time, but maybe someone else can benefit from it.

A: You could use MethodImplAttribute and specify MethodImplOptions.NoInlining.
[MethodImpl(MethodImplOptions.NoInlining)]
void YourMethod()
{
    // do something
}

Note that this still doesn't guarantee that you can get at the actual calling method as seen in the source code. Your method won't be inlined, but your method's caller could be inlined into its own caller, etc etc.


text:
Q: protractor-jasmine2-screenshot-reporter not generating screenshots in the required folder My protractor.conf.js has the following content. I was unable to find out whats wrong here. I have manually created target/screenshots in my root folder of angular-cli. When i run protractor conf.js the protractor tests in browser window but the screenshots aren't being generated. Can anyone help me resolve this?
// Protractor configuration file

const { SpecReporter } = require('jasmine-spec-reporter');
var HtmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter');
var fs = require('fs');

var reporter = new HtmlScreenshotReporter({
  dest: 'target/screenshots',
  filename: 'my-report.html',
  cleanDestination: false,
  showSummary: true,
  showConfiguration: false,
  reportTitle: null,
  ignoreSkippedSpecs: false,
  captureOnlyFailedSpecs: false,
  reportOnlyFailedSpecs: false
});

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './e2e/**/*.e2e-spec.ts'
  ],
  capabilities: {
    'browserName': 'chrome'
  },
  directConnect: false,
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  chromeOnly: true,
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['spec.js'],
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {}
  },
  onPrepare() {
    require('ts-node').register({
      project: 'e2e/tsconfig.e2e.json'
    });
    jasmine.getEnv().addReporter(reporter);
  },
  afterLaunch: function(exitCode) {
    return new Promise(function(resolve){
      reporter.afterLaunch(resolve.bind(this, exitCode));
    });
  }
};

Thanks in Advance!

A: protractor-jasmine2-screenshot-reporter compatible with jasmine2, so change to framework: 'jasmine2' in your conf.js
And you need to use higher version of Protractor which includes jasmine2
I did a quick test with your conf(did little changes) and it worked.
conf.js
var HtmlScreenshotReporter = require('protractor-jasmine2-screenshot-reporter');
// var fs = require('fs');

var reporter = new HtmlScreenshotReporter({
  dest: 'target/screenshots',
  filename: 'my-report.html',
  cleanDestination: false,
  showSummary: true,
  showConfiguration: false,
  reportTitle: null,
  ignoreSkippedSpecs: false,
  captureOnlyFailedSpecs: false,
  reportOnlyFailedSpecs: false
});

exports.config = {
  allScriptsTimeout: 11000,
//   specs: [
//     './e2e/**/*.e2e-spec.ts'
//   ],
  capabilities: {
    'browserName': 'chrome'
  },
  directConnect: false,
//   baseUrl: 'http://localhost:4200/',
  framework: 'jasmine2',
//   chromeOnly: true,
  seleniumAddress: 'http://localhost:4444/wd/hub',
  specs: ['spec.js'],
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {}
  },
  onPrepare() {
    jasmine.getEnv().addReporter(reporter);
  },
  afterLaunch: function(exitCode) {
    return new Promise(function(resolve){
      reporter.afterLaunch(resolve.bind(this, exitCode));
    });
  }
};

spec.js
   describe('xxx', function(){

        it('yyy', function(){

            browser.get('https://angular.io/');
        });
    });

target/screenshots folder and HTML report,
(I run for twice, so there are two screenshots.)

*

*click the yyy will open the screenshot

*protractor-jasmine2-screenshot-reporter will create target/screenshots folder if not exist, no need to create in advance.

Version I used:
protractor 5.3.0
protractor-jasmine2-screenshot-reporter  0.5.0

A: You can check by adding the  'protractor-screenshoter-plugin'
plugins: [{
    package: 'protractor-screenshoter-plugin',
    screenshotPath: <specify the path>,
    screenshotOnExpect: 'failure',
    screenshotOnSpec: 'failure+success',
    withLogs: 'true',
    writeReportFreq: 'asap',
    imageToAscii: 'failure',
    htmlReport:'true',
    verbose:'info',
    clearFoldersBeforeTest: true,
    failTestOnErrorLog: {
        failTestOnErrorLogLevel: 900
    }
},

Can also check https://www.npmjs.com/package/protractor-screenshoter-plugin


text:
Q: pip-compile error using Anaconda - File "/opt/anaconda3/bin/pip-compile", line 8, in  sys.exit(cli()) My pip version is 22.0.4. I had the most recent version but had to downgrad because I noticed the same error mentioned here: https://github.com/jazzband/pip-tools/issues/1617)
When I try to run pip-compile to update the requirements.txt file but I keep seeing the below error:
(base) krs@me-user ds-airflow % pip-compile
WARNING:pip._internal.metadata.base:Ignoring invalid distribution -rllib3 (/opt/anaconda3/lib/python3.8/site-packages)
WARNING:pip._internal.metadata.base:Ignoring invalid distribution -otocore (/opt/anaconda3/lib/python3.8/site-packages)
WARNING:pip._internal.metadata.base:Ignoring invalid distribution -ix (/opt/anaconda3/lib/python3.8/site-packages)
WARNING:pip._internal.metadata.base:Ignoring invalid distribution - (/opt/anaconda3/lib/python3.8/site-packages)
Traceback (most recent call last):
  File "/opt/anaconda3/bin/pip-compile", line 8, in <module>
    sys.exit(cli())
  File "/opt/anaconda3/lib/python3.8/site-packages/click/core.py", line 829, in __call__
    return self.main(*args, **kwargs)
  File "/opt/anaconda3/lib/python3.8/site-packages/click/core.py", line 782, in main
    rv = self.invoke(ctx)
  File "/opt/anaconda3/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
    return ctx.invoke(self.callback, **ctx.params)
  File "/opt/anaconda3/lib/python3.8/site-packages/click/core.py", line 610, in invoke
    return callback(*args, **kwargs)
  File "/opt/anaconda3/lib/python3.8/site-packages/click/decorators.py", line 21, in new_func
    return f(get_current_context(), *args, **kwargs)
  File "/opt/anaconda3/lib/python3.8/site-packages/piptools/scripts/compile.py", line 313, in cli
    repository = PyPIRepository(pip_args, cache_dir=cache_dir)
  File "/opt/anaconda3/lib/python3.8/site-packages/piptools/repositories/pypi.py", line 93, in __init__
    self._setup_logging()
  File "/opt/anaconda3/lib/python3.8/site-packages/piptools/repositories/pypi.py", line 451, in _setup_logging
    assert isinstance(handler, logging.StreamHandler)
AssertionError

EDIT: I just tried running: pip-compile --upgrade
  File "/opt/anaconda3/bin/pip-compile", line 8, in <module>
    sys.exit(cli())
  File "/opt/anaconda3/lib/python3.8/subprocess.py", line 512, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['/opt/anaconda3/bin/python3', '/opt/anaconda3/lib/python3.8/site-packages/pep517/in_process/_in_process.py', 'get_requires_for_build_wheel', '/var/folders/2b/d94v_0s54rxfx2ylxg20xh5c0000gn/T/tmp2o517hrt']' returned non-zero exit status 1.

EDIT EDIT:
I've run conda list '(pip|click)' and see the following, but my requirements.txt file has hundreds of packages:
# packages in environment at /opt/anaconda3:
#
# Name                    Version                   Build  Channel
click                     7.1.1                    pypi_0    pypi
click-default-group       1.2.2                    pypi_0    pypi
clickclick                20.10.2                  pypi_0    pypi
pip                       20.2.4                   pypi_0    pypi
pip-tools                 6.6.0                    pypi_0    pypi

A: The version combination of pip=20.2.4 and pip-tools=6.6.0 is not compatible. Either upgrade pip to >=21.2, or downgrade pip-tools to 5.5.


text:
Q: How to use audio units in an application I've been looking for things online that teach how to use audio units in an application, with no luck. I'm trying to make an application that allows the user to apply AUTimePitch to the playback of audio files, on the fly. But i can't find anything online to teach a total beginner how to use audio units.
also, i'm making this for mac, not iOS

A: The best document by far on the subject is Apple's Audio Unit Hosting Guide for iOS in the dev library. For a more general introduction, you can check out the Core Audio Overview.
I also found the MixerHost and iPhoneMultichannelMixerTest sample code incredibly helpful in starting to use audio units.
Finally, I find class references and service references like the Audio Unit Processing Graph Services Reference and the Audio Unit Component Services Reference useful for exploring the functionality of particular methods, constants, classes, and so on.
Edit: I realized that your question doesn't say whether you're working in Mac OS or iOS. This answer is obviously heavily iOS-centric. Could you edit your question to tell us what environment you're in?


text:
Q: Httpwebrequest soap Request Hi What is the best practice for sending Http Request using C#, passing a number of parameters to a SOAP end point. I also require to Add few headers in the request.
I have a SOAP API defined as
<soapenv:Envelope xmlns:soapenv="schemas.xmlsoap.org/soap/envelope/" ; xmlns:mac="iib.macinfra.in/mac">;
    <soapenv:Header>
        <mac:RequestHeader>
            <mac:Id>GFyZxV0</mac:ApplicationId>
            <mac:MessageId>pfoshdttc</mac:MessageId>
        </mac:RequestHeader>
    </soapenv:Header>
    <soapenv:Body>
        <mac:FindMailRequest>
            <mac:QueryString>CM7JT</mac:QueryString>
        </mac:FindMailRequest>
    </soapenv:Body>
</soapenv:Envelope>

I would like to build a HttpRequest and pass the parameters using HttpWebRequest webreq = WebRequest.Create(webserviceUrl) as HttpWebRequest;


text:
Q: How to always find the nearest hundredth? I have a number which can always change. I want to find the previous hundredth of that number. I'm only able to find the closest hundredth. Here's how I'm doing it atm:
Dim  mynum as integer
mynum = 549
Dim tempnumber as integer
tempnumber = Round(mynum / 100, 0) * 100 '>>> equals 500 which is correct

What if mynum was 551? >> it will get 600 which i don't want, i only want 500 whether the number is 556, 588, or 599, i want the number to still be 500.
I want it to be 599 >> 500, 799>> 700. Basically the hundredth of the current number.

A: There are two ways to do this:
Round((mynum-50)/100,0)*100

And using the Worksheet Function:
Application.WorksheetFunction.RoundDown(mynum,-2)


text:
Q: how to add a screen when the screen is off like the default alarm screen when the alarm ring with flutter
how to add a screen when the screen is off like the default alarm screen when the alarm ring with flutter.

A: These screens are actually notifications with full screen intent
https://pub.dev/packages/flutter_local_notifications
This package support full screen intent.

A: There is an overlay screen on the lock screen and turn on Screen;
I get only java code for android ;
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>

for MainActivity.java
 public void overlayScreen(){
    if (Build.VERSION.SDK_INT >=
         Build.VERSION_CODES.O_MR1)
     {
        setShowWhenLocked(true);
        setTurnScreenOn(true);
        KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        if(keyguardManager!=null)
            keyguardManager.requestDismissKeyguard(this, null);
    }
    else
    {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
                WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

    }
}

And Add this; which activity do you want to show over lock screen;
for OverlyActivity.java
void fullScreen(){
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON|             WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD|             WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|             WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
   }

Both functions call from onCreate method;


text:
Q: AWS Reserved IP addresses I have multiple VPC in my account and I created most of VPC using subnet 10.0.0.0/8 or 192.168.0.0/16 or 172.16.0.0/12 subnet blocks.
I am exhausted with my range due to not optimizing the IP address properly and adding a wrong route of 10.0.0.0/8 under a VPC. I got to know about this when I tried attempted to establish VPC peering between two different VPC of 10.0.0.0 subnet. I got to know later that I can use CIDR range 20.0.0.0/16 and 30.0.0.0/16 as private address in aws to create VPC. Also I created a VPC with CIDR 20.0.0.0/16 and it works.
How come aws can offer multiple IP range for private IP address to create VPC and multiple subnet under VPC? Can somebody help me to understand aws private IP range?
Is this something being virtual we can use any range of IP address as private address? How does this not affect connectivity from aws server to internet if we can choose any random CIDR as private IP address or there is some limit?


text:
Q: Simultaneous equations and negative exponents I am an elderly maths ignoramus! But trying to help my granddaughter with a problem. The simultaneous equations are:  $x^2 + y^2 = 25$  and $y - 3x = 13$. I have tried to get a value for y from equation b) in order to substitute it into a). But then I get to  $10x^2 = -144$ and I do not think x^2 can be a negative number! Is this correct? Can someone solve this simple (!) problem? Many thanks!

A: $x^2$ can be negative if imaginary numbers are allowed, e.g., $x^2 = -1$ means $x = \pm i$.  But we don't need to worry about that here.
$y - 3x = 13$ means $y = 3x + 13$.  Substitute this into the other equation.
\begin{align*}
  x^2 + y^2 &= 25\\
  x^2 + (3x + 13)^2 &= 25\\
  x^2 + 9x^2 + 78x + 169 &= 25\\
  10x^2 + 78x + 144 &= 0
\end{align*}
Divide both sides by $2$ to get $5x^2 + 39x + 72 = 0$.  This can be factored but since the numbers are bordering on the unpleasant, the quadratic formula may be a good way to go instead.

A: it is $$x^2+(3x+13)^2=25$$
$$x^2+9x^2+169+78x=25$$
Can you proceed?
write for $y$: $$y=3x+13$$
simplifying and factorizing we obtain
$$2\, \left( 5\,x+24 \right)  \left( x+3 \right) =0$$
from here you will get two cases:
$$5x+24=0$$ or $$x+3=0$$

A: It can happen that a system of equations has no solutions but somewhere along the way, probably something went wrong in the calculations.
Substitution of $y=3x+13$ into $x^2+y^2=25$ gives:
$$x^2+(3x+13)^2=25 \iff 10 x^2 + 78 x + 144 = 0$$
which is a (standard) quadratic equation.
Although it's possible that this equation has no (real) solutions, that's not the case here.

A: I think you may have made a small arithmetical error. You used the second equation to get $y = 3x+13$, and then insertet this into the first equation to get $x^2 + (3x+13)^2 = 25$. Then from here, I suspect that you went directly for $x^2 + 9x^2 + 169 = 25$. This is a mistake. $(3x+13)^2$ and $9x^2 + 169$ are not the same thing.
I think this is best seen if you write $(3x+13)^2$ as $(3x+13)\cdot (3x+13)$ (this is what $^2$ means, after all), and then multiply the parentheses the long way. Because squaring is so common, many books teach you to just look at $(3x + 13)^2$ and immediately see that it's equal to $9x^2 + 26x + 169$ (usually through a formula like $(a+b)^2 = a^2 + 2ab + b^2$). I suggest you only start to do that after having squares a few different brackets and seen how everything work.
So the actual equation you should solve is $10x^2 + 26x = -144$, or $10x^2 + 26x + 144 = 0$.
Side note: It is entirely possible for equations to have no solutions, particularily when the highest power the unknown is raised to is even. $10x^2 = -144$ is one example of this, as you rightly point out. There are number systems invented (or maybe discovered?) to deal with this. By far the most popular are the so-called complex numbers, which didn't get their name because they're difficult, but because they're put together from two parts. But for now it's safe to just say that there is no solution.


text:
Q: Python ssl sockets TypeError I am coding a simple ssl secured client server echo message program. I am getting a client side type error --> an integer is required. Below is the code for the client
 import socket
import ssl

c_con = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_ip = '*******'
server_port = 4444
print('Connecting to %s port %d' % (server_ip,server_port))
c_con.connect((server_ip,server_port))

ssl_sock = ssl.wrap_socket(c_con,ssl_version = "TLSv1")

try:
    message = raw_input('Enter your message --> ')
    print('Sending "%s"' % message)
    ssl_sock.sendall(message)

    #Echo part
    amount_received = 0
    amount_expected = len(message)

    while amount_received < amount_expected:
        data = ssl_sock.recv(1024)
        amount_received += len(data)
        print('Received "%s"' % data)

finally:
    print('Closing socket')
    ssl_sock.close()

Please help me out. I checked the related questions to the topic but couldn't figure out my solution.

A: here is the probleme :
ssl_sock = ssl.wrap_socket(c_con,ssl_version = "TLSv1")

the tls version are not correct , you must do like that:
ssl_sock = ssl.wrap_socket(c_con,ssl_version = ssl.PROTOCOL_TLSv1)

don't make ssl.PROTOCOL_TLSv1 an str , its alerady defined
and check if you'r host can support TLSv1 protocol


text:
Q: How to create Jquery products slider? I am trying to create jquery slider that could slide DIV's. I need something like jCarousel or jquery Moving Boxes.
It should be simple sliding of 3 items at a time.

Item text 1

Item text 2

Item text 3

Item text 4

Item text 5

Item text 6

Any suggestions what should I use? Plugin or there any easier way?
Thanks in advance

A: Why not use jCarousel then?  Sounds like you should be alright using it.  You may have to slightly alter it or change the target to $('.item') but I don't see why it wouldn't work.


text:
Q: How to set json web token expire and validate The problem is that when comparing both dates the token would expire in approximately 17 hours, which is wrong, since at the time of generation it should be only 1 minute longer.
If someone can help me I appreciate it very much

A: It looks like your code assumes that the expiration and issued at properties are defined as milliseconds (60000 milliseconds = 60 seconds = 1 minute).
However, the JWT specification states that exp and iat use 'Seconds since the Epoch. See the answer here: https://stackoverflow.com/a/39926886/12086953
So just change the value in your first code snippet to expire in 60 seconds rather than 60000 seconds (which is just under 17 hours), like this:
const myToken = jwt.sign({ id: '12345677', username: 'emailtest@uu.com' }, 'mysecretjsonwebtoken', { expiresIn: 60, audience: '12345677' })