text:
Q: Problema con botón "onclick" que llama a un javascript he creado un fichero .js para mostrar y ocultar contraseña en un login de usuario. Lo he puesto en un button, con un onclick, para que cuando el usuario le de se oculte o se desoculte. El problema es que cuando le doy al botón no me hace nada y he mirado con el f12 y me sale el siguiente error:
Uncaught ReferenceError: mostrarContrasena is not defined at HTMLButtonElement.onclick.
Yo creo que el fichero de javascript es correcto, no sé si igual lo llamo mal desde el html. Adjunto código. El error me sale en el fichero .php cuando pongo el button y llamo con el onclick a la función del javascript. Si me podéis ayudar. Muchas gracias.
Este es mi fichero mostarContrasena.js

function mostrarContrasena() {
        var cambio = document.getElementById("ucontra");
        if (cambio.type == "password") {
            cambio.type = "text";
            $('.icon').removeClass('fa fa-eye-slash').addClass('fa fa-eye');
        } else {
            cambio.type = "password";
            $('.icon').removeClass('fa fa-eye').addClass('fa fa-eye-slash');
        }
    }

Este es mi fichero login.php

<!DOCTYPE html>

    <meta charset="UTF-8">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<form action="../public/forms/login.php" method="post">

EMAIL

<input type="text" id="uemail" name="uemail" />

CONTRASEÑA

    <button id="mostrar_contrasena" type="button" onclick="mostrarContrasena()">  </button>

<input type="password" id="ucontra" name="ucontra" />

<input type="submit" name="ulogin" value="ENTRAR" />

</form>

A: Verifica en inspector web que WebBurger/public/js/mostrarContrasena.js carga correctamente y que no contiene errores de sintaxis. Me parece extraño que tengas <form action="../public/ pero

NOTAS:

*

*Te recomiendo cambiar el jQuery en linea por la descarga del fichero.

A: Para que tu código funcione tienes que llamar antes a jQuery y después tu código:


text:
Q: inline-block not working with grid when used for varying width according to content I'm working with grid and the problem i'm facing is inline block is not working with it. i.e I want my div's height and width to vary with the content inside it. If i'm not using grid then it is working fine but with grid it stretch to the column's width

.BotWrapper {
  position: relative;
  width: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 1em;
  grid-auto-rows: minmax(20px, auto);
  margin-top: 0.8em;
  word-wrap: break-word;
}

.BotWrapper > div {
  margin-left: 2%;
  background: #BEE9E8;
  padding: 1.7%;
  display: inline-block;
  min-height: 40px;
  min-width: 6em;
  max-width: 20em;
  margin-bottom: 5px;
  margin-top: 10px;
  font-size: 0.9em;
  word-wrap: break-word;
}

.BotWrapper > div:nth-child(even) {
  background: transparent;
}

UserWrapper {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 1em;
  grid-auto-rows: minmax(30px, auto);
  margin-right: 1em;
  margin-top: 1em;
  word-wrap: break-word;
  background: blue;
}

.UserWrapper > div {
  float: right;
  margin-right: -2.2em;
  background-color: #62B6CB;
  padding: 1.7%;
  max-width: 20em;
  min-width: 6em;
  min-height: 40px;
  margin-top: 10px;
  display: inline-block;
  margin-bottom: 5px;
  font-size: 0.9em;
  word-wrap: break-word;
}

.UserWrapper > div:nth-child(odd) {
  background: transparent;
}

.speech-bubble {
  padding: 5rem;
  border: 2px solid #376996;
  border-top-right-radius: .6em;
  border-bottom-right-radius: .6em;
  border-bottom-left-radius: .6em;
}

.speech-bubble1 {
  position: relative;
  background: #62B6CB;
  border: 2px solid #376996;
  border-top-left-radius: .6em;
  border-bottom-left-radius: .6em;
  border-bottom-right-radius: .6em
}

.timeRight {
  font-size: 0.52em;
  float: right;
  margin-top: -1em;
  margin-bottom: 0;
  font-family: 'Mina', sans-serif;
}

.timeLeft {
  font-size: 0.52em;
  float: right;
  margin-top: -1em;
  margin-bottom: 0;
  font-family: 'Mina', sans-serif;
}

Hi

02:12:02

Bye

02:12:03

The first div is when i'm using grid and for the second one i have removed . from the UserWrapper so it is not being executed as a grid.
Why is this happening?

A: I think what you are looking for is justify-items: start on the container. This aligns items to be flush with the start edge of their cell whereas the default is stretch which forces the children to fill the whole width of the cell
CSS-Tricks Complete Guide

.BotWrapper {
  position: relative;
  width: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 1em;
  grid-auto-rows: minmax(20px, auto);
  margin-top: 0.8em;
  word-wrap: break-word;
  justify-items: start; /* this */
}

.BotWrapper > div {
  margin-left: 2%;
  background: #BEE9E8;
  padding: 1.7%;
  min-height: 40px;
  min-width: 6em;
  margin-bottom: 5px;
  margin-top: 10px;
  font-size: 0.9em;
  word-wrap: break-word;
}

.BotWrapper > div:nth-child(even) {
  background: transparent;
}

UserWrapper {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 1em;
  grid-auto-rows: minmax(30px, auto);
  margin-right: 1em;
  margin-top: 1em;
  word-wrap: break-word;
  background: blue;
}

.UserWrapper > div {
  float: right;
  margin-right: -2.2em;
  background-color: #62B6CB;
  padding: 1.7%;
  max-width: 20em;
  min-width: 6em;
  min-height: 40px;
  margin-top: 10px;
  display: inline-block;
  margin-bottom: 5px;
  font-size: 0.9em;
  word-wrap: break-word;
}

.UserWrapper > div:nth-child(odd) {
  background: transparent;
}

.speech-bubble {
  padding: 5rem;
  border: 2px solid #376996;
  border-top-right-radius: .6em;
  border-bottom-right-radius: .6em;
  border-bottom-left-radius: .6em;
}

.speech-bubble1 {
  position: relative;
  background: #62B6CB;
  border: 2px solid #376996;
  border-top-left-radius: .6em;
  border-bottom-left-radius: .6em;
  border-bottom-right-radius: .6em
}

.timeRight {
  font-size: 0.52em;
  float: right;
  margin-top: -1em;
  margin-bottom: 0;
  font-family: 'Mina', sans-serif;
}

.timeLeft {
  font-size: 0.52em;
  float: right;
  margin-top: -1em;
  margin-bottom: 0;
  font-family: 'Mina', sans-serif;
}

Hi

02:12:02

Bye

02:12:03

redpajama_set_name: RedPajamaStackExchange


text:
Q: Client does not have permissions to send as this sender (office 365, grails) I am continuously receiving following error message while trying to configure grails mail plugin (https://grails.org/plugin/mail) for grails spring security plugin.
Here is my configuration looks so far,

    grails {
        mail {
            host = "smtp.office365.com"
            port = 587
            username = "info@email.com"
            password = "password"
            props = ["mail.smtp.starttls.enable":"true",
                     "mail.smtp.port":"587"]
        }
    }

    grails.mail.default.from = "info@email.com"

And here is my stack-trace.

    .......| Error 2015-04-17 11:59:39,184 [http-bio-8080-exec-8] ERROR errors.GrailsExceptionResolver  - MailSendException occurred when processing request: [POST] /retouch/register/forgotPassword - parameters:
    username: customer
    Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 550 5.7.60 SMTP; Client does not have permissions to send as this sender
    . Stacktrace follows:
    Message: Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 550 5.7.60 SMTP; Client does not have permissions to send as this sender
        Line | Method
    ->>  131 | sendMessage    in grails.plugin.mail.MailMessageBuilder
    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    |     55 | sendMail       in grails.plugin.mail.MailService
    |     59 | sendMail . . . in     ''
    |    156 | forgotPassword in grails.plugin.springsecurity.ui.RegisterController
    |    198 | doFilter . . . in grails.plugin.cache.web.filter.PageFragmentCachingFilter
    |     63 | doFilter       in grails.plugin.cache.web.filter.AbstractFilter
    |     53 | doFilter . . . in grails.plugin.springsecurity.web.filter.GrailsAnonymousAuthenticationFilter
    |     49 | doFilter       in grails.plugin.springsecurity.web.authentication.RequestHolderAuthenticationFilter
    |     82 | doFilter . . . in grails.plugin.springsecurity.web.authentication.logout.MutableLogoutFilter
    |   1145 | runWorker      in java.util.concurrent.ThreadPoolExecutor
    |    615 | run . . . . .  in java.util.concurrent.ThreadPoolExecutor$Worker
    ^    745 | run            in java.lang.Thread

Note: Problem is only find in Grails spring security plugin.

A: I ran into the exact same issue. Problem seems to arise due to spring security trying to set "from" attribute in the email as no-reply@localhost.
Try adding these lines to the config file
 grails.plugin.springsecurity.ui.register.emailFrom = 'info@email.com'
 grails.plugin.springsecurity.ui.forgotPassword.emailFrom = 'info@email.com'

note: info@email.com is your office365 email

A: username = "info@emal.com"
grails.mail.default.from = "info@email.com"
username email must equal to from email.

A: I got Grails sending email pretty easily using a test GMail account, but the code crashed with the error when I tried to send from an outlook.office365.com account:

Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 550 5.7.60
  SMTP; Client does not have permissions to send as this sender

It turns out I was only missing this line:
grails.mail.default.from = "sample@somewhere.com"

Note the the email address specified in grails.mail.default.from must match the one in grails.mail.username .
Here is the configuration that worked for me.  Base example is the Hubbub example from the book Grails in Action (2nd Ed):
grails.mail.default.from = "sample@somewhere.com"
grails {
  mail {
      host = "outlook.office365.com"
      port = 587
      username = "sample@somewhere.com"
      password = "secret"
      props = [ "mail.smtp.starttls.enable" : "true",
                "mail.smtp.port"            : "587",
                "mail.smtp.debug"           : "true" ]
  }

and here is the corresponding email sending function:
def email() {
  println( "Sending email.." );
  sendMail {
      to "test@gmail.com"
      subject "[mail-test]"
      body ("This is a test email, time: " + new Date() )
  }
  println( "  success!!!" );
  flash.message = "Successfully sent email"
  redirect( uri: "/" );
}


text:
Q: How to fadeIn and fadeOut elements in one div after defined time? How to display queued messages one after another with delay in the same div? Current solution is bad because is showing instantly new divs.
HTML:

<button id="show">First message</button>
<button id="next">Next message</button>

JavaScript:
var timeout;
$("#show").click(function () {
    alertBar("this appears first");
});
$("#next").click(function () {
    alertBar("this should wait and show after first disappeared");
});
function alertBar(msg) {
    var message_span = $('').html(msg);
    var wrap_bar = $('
').addClass('alert_bar');
    $('#alert-bar-container').html(wrap_bar.append(message_span).hide());
    clearTimeout(wrap_bar.data("timer"));
    wrap_bar.clearQueue();
    if (wrap_bar.filter(":hidden").length == 1) wrap_bar.fadeIn('fast');
    wrap_bar.data("timer", setTimeout(function () {
        wrap_bar.fadeOut("slow");
        wrap_bar.remove();
    }, 2500));
}

Example: http://jsfiddle.net/LsRK8/

A: Hope this helps...edited with no button...
<!doctype html>

<meta charset="utf-8">
<title>delay demo</title>

A: Try:
HTML:

first

second

third

fourth

JS:
setInterval(function(){
    var active = $("#container").find(".active");
    var i = $(active).index();
    var len = $("#container").find(".msg").length;
    var next;
    if(i == (len-1)){
        next = $("#container").find(".msg:first");
    }
    else{
        next = $("#container").find(".msg:eq("+(i+1)+")");
    }
    $(active).removeClass("active").hide();
    $(next).addClass("active").fadeIn();
},3000);

Fiddle here.


text:
Q: Serial COM port output I got a little question here.
I'm making a little weather station, and I'm trying to read the data in visual studio.
In arduino it looks like this
http://oi59.tinypic.com/2uzbknm.jpg
But when i try to read it in in Visual studio I get this
http://i59.tinypic.com/2rykccn.jpg
This is the code I have and I already think where the problem is, but I dont know how to solve it ..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;

namespace WeatherStation
{
public partial class Form1 : Form
{
    public delegate void PrintString(String data);
    public PrintString printDelegate;
    private SerialPort port;
    private char[] data;
    private int index;
    public Form1()
    {
        InitializeComponent();
        data = new char[128];
        index = 0;
        printDelegate = new PrintString(PrintData);

    }

    private void btnStart_Click(object sender, EventArgs e)
    {
        try
        {
            port = new SerialPort("COM3", 9600, Parity.None, 8);
            port.DataReceived += DataReceivedHandler;
            port.Open();

        }

        catch (Exception exc)
        {
            MessageBox.Show(exc.Message);
        }

    }
    private void PrintData(String data)
    {
        txtBoxData.AppendText(" " + data + Environment.NewLine);
    }
    private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {
        try
        {
            data[index] = (char)port.ReadByte();
            if (data[index] == '\n' )
            {
                if (this.InvokeRequired)
                {
                    this.Invoke(printDelegate, new object[] { new String(data) });
                }

                index = 0;
            }

            else
            {
                index++;
            }
        }

        catch (Exception exc) //!!
        {
            MessageBox.Show(exc.Message);
        }
    }

    private void btnStop_Click(object sender, EventArgs e)
    {
        port.Close();
    }
  }
}

I think the problem is in this part with the '\n' but as i said before, I have no idea how to solve it.
            data[index] = (char)port.ReadByte();
            if (data[index] == '\n' )

Thanks in advance for your help.


text:
Q: Two Loop QED Feynman Diagram I'm trying to find the momentum space integral representation of the below Feynman Diagram, but am having troubles with the fact that there are two loops within the system.
The main question I have is how to deal with a 2 loop system in Feynman Diagrams. If I have that, I can solve the rest of my problems myself!

Starting from the right hand side and going in an anti-clockwise loop, I get (Line breaks are required to be a bit more readable)
$$ \int \frac{d^4 k_1}{(2 \pi)^4} \int \frac{d^4 k_2}{(2 \pi)^4}\epsilon^*_\mu (q) \\Tr \left[ (-ie\gamma^\mu)  \frac{i({\gamma^\alpha q_\alpha} + \gamma^\alpha {{k_1}_\alpha} + m)}{(q + k_1)^2 - m^2 + i\epsilon}(-ie\gamma^\nu) \frac{i(\gamma^\alpha q_\alpha + \gamma^\alpha {k_2}_\alpha + m)}{(q + k_2)^2 - m^2 + i\epsilon}\\(-ie\gamma^\sigma) \frac{i(\gamma^\alpha{k_2}_\alpha + m)}{(k_2)^2 - m^2 + i\epsilon} (-ie\gamma^\rho) \frac{\gamma^\alpha{k_1}_\alpha + m}{(k_1)^2 - m^2 + i\epsilon} \right] \\   \frac{-i(g_{\rho\nu} - \frac{(k_1 - k_2)_\rho (k_1 - k_2)_\nu}{(k_1 - k_2)^2} )}{(k_1 - k_2)^2 + i\epsilon} \epsilon_\sigma (q) $$


text:
Q: Find a rotated bounding box of known size around a rectangle with noisy sides I'm trying to find a rotated bounding box around a less-than-perfect binarized image of a rectangle. The imperfections are always different: sometimes it's hollow, sometimes there's stuff inside, sometimes one of the edges is missing a chunk, sometimes there's an extra chunk somewhere on the edge, and they're always slightly rotated by a random amount, but the size and shape of the expected bounding box is always nearly the same absolute value in pixels.
Here's some samples of what I have as inputs (resized to fit better in the post):

And ideally I'd like to find a bounding box around the outside of the white rectangle (although I'm mostly just interested in the edges) like this:

(found by inverting one of the hollow ones, getting the largest connected component, and getting a rotatedrect of forced size)
So far I've tried just getting a rotatedrect and forcing a shape afterwards, which works for almost every case except for when there's an extra chunk along one of the edges. I've tried getting connected components to isolate parts of it and get bounding boxes around those, which works for every case as long as they're hollow. I've tried dilating and eroding the image, getting contours and hough lines to try to find only the four cornerpoints, but I've had no luck with that either. I've also looked online for anything useful to no avail.
Any help or ideas would be greatly appreciated.

A: My solution comprises two parts:

*

*Find (upright) bounding box of the big white rectangle by finding the biggest connected component, fill all holes in it, find outside vertical and horizontal lines (Hough), get the bounding box by taking the min/max x/y coordinates.

*Match a (filled) rectangle of given size with center at center of bounding box from step 1 at different angles, print the best match as result.

Following is a simple program demonstrating this approach. The arguments at the beginning (filename, size of know rectangle, angle search range) would normally be passed in from the command line.
    import cv2
    import numpy as np

    # arguments
    file = '1.png'
    w0, h0 = 425, 630  # size of known rectangle
    ang_range = 1      # posible range (+/-) of angle in degrees

    # read image
    img = cv2.imread(file, cv2.IMREAD_GRAYSCALE)
    h, w = img.shape

    # find biggest connceted components
    nb_components, output, stats, _ = cv2.connectedComponentsWithStats(img, connectivity=4)
    sizes = stats[:, -1]
    max_label, max_size = 1, sizes[1]
    for i in range(2, nb_components):
        if sizes[i] > max_size:
            max_label = i
            max_size = sizes[i]
    img2 = np.zeros(img.shape, np.uint8)
    img2[output == max_label] = 128

    # fill holes
    contours, _ = cv2.findContours(img2, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
    for contour in contours:
        cv2.drawContours(img2, [contour], 0, 128, -1)

    # find lines
    edges = cv2.Canny(img2, 50, 150, apertureSize = 3)
    lines = cv2.HoughLinesP(edges, 1, np.pi/180, 40)

    # find bounding lines
    xmax = ymax = 0
    xmin, ymin = w-1, h-1
    for i in range(lines.shape[0]):
        x1 = lines[i][0][0]
        y1 = lines[i][0][1]
        x2 = lines[i][0][2]
        y2 = lines[i][0][3]
        cv2.line(img2, (x1,y1), (x2,y2), 255, 2, cv2.LINE_AA)
        if abs(x1-x2) < abs(y1-y2):
            # vertical line
            xmin = min(xmin,x1,x2)
            xmax = max(xmax,x1,x2)
        else:
            # horizcontal line
            ymin = min(ymin,y1,y2)
            ymax = max(ymax,y1,y2)
    cv2.rectangle(img2, (xmin,ymin), (xmax,ymax), 255, 1, cv2.LINE_AA)
    cv2.imwrite(file.replace('.png', '_intermediate.png'), img2)

    # rectangle of known size centered at bounding box
    xc = (xmax + xmin) / 2
    yc = (ymax + ymin) / 2
    box = np.zeros(img.shape, np.uint8)
    box[int(yc-h0/2):int(yc+h0/2), int(xc-w0/2):int(xc+w0/2)] = 255

    # find best match of this rectangle at different angles
    smax = angmax = 0
    for ang in np.linspace(-ang_range, ang_range, 20):
       rm = cv2.getRotationMatrix2D((xc,yc), ang, 1)
       rotbox = cv2.warpAffine(box, rm, (w,h))
       s = cv2.countNonZero(cv2.bitwise_and(rotbox, img))
       if s > smax:
           smax = s
           angmax = ang

    # output and visualize result
    def draw_rotated_rect(img, size, center, angle, color, thickness):
        rm = cv2.getRotationMatrix2D(center, angle, 1)
        p0 = np.dot(rm,(xc-w0/2, yc-h0/2,1))
        p1 = np.dot(rm,(xc-w0/2, yc+h0/2,1))
        p2 = np.dot(rm,(xc+w0/2, yc+h0/2,1))
        p3 = np.dot(rm,(xc+w0/2, yc-h0/2,1))
        pnts = np.int32(np.vstack([p0,p1,p2,p3]) + 0.5).reshape(-1,4,2)
        cv2.polylines(img, pnts, True, color, thickness, cv2.LINE_AA)
        print(f'{file}: edges {pnts[0].tolist()}, angle = {angle:.2f}°')

    res = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    draw_rotated_rect(res, (w0,h0), (xc,yc), angmax, (0,255,0), 2)
    cv2.imwrite(file.replace('.png', '_result.png'), res)

Intermediate results to show how it works (gray = filled biggest connected component, thick white lines = Hough lines, thin white rectangle = upright bounding box):
(to view the full size pictures click on them and then remove the final m before the file extension)

Visualization of results (green = rotated rectangle of known size):

Results (should eventually be clamped to [0,image size), -1 is due to floating point rotation):
1.png: edges [[17, -1], [17, 629], [442, 629], [442, -1]], angle = 0.00°
2.png: edges [[7, 18], [9, 648], [434, 646], [432, 16]], angle = 0.26°
3.png: edges [[38, 25], [36, 655], [461, 657], [463, 27]], angle = -0.26°
4.png: edges [[36, 14], [28, 644], [453, 650], [461, 20]], angle = -0.79°

As we see in image 3, the match is not perfect. This could be due to the example images that were shrinked to somewhat differing sizes and of course I didn't know the size of the known rectangle, so I just assumed an appropriate value for the demonstration.
If this occurs with real data too, you may want to not only vary the angle to find the best match, but also shift the matching box a couple of pixels up/down and right/left. See for instance section 8.1 of Dawson-Howe: A Practical Introduction to Computer Vision with OpenCV for further details.


text:
Q: Use for loop for multi row column plot I am attempting to run a for loop in order to plot multiple scatter plots.  For the code that I have, I only get one plot at the end.  How to go about generating the correct row x column plots to save?
I have checked out some of the answers given here and here, but it does not work for me.  Is there a more optimum way to generate these plots?
Here is my code:
from sklearn.datasets import make_classification
import seaborn as sns
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd

# Generate noisy Data
num_trainsamples = 500
num_testsamples = 50
X_train,y_train = make_classification(n_samples=num_trainsamples,
                          n_features=240,
                          n_informative=9,
                          n_redundant=0,
                          n_repeated=0,
                          n_classes=10,
                          n_clusters_per_class=1,
                          class_sep=9,
                          flip_y=0.2,
                          #weights=[0.5,0.5],
                          random_state=17)

n_components=2
n_neighbours=[1, 5, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 25, 30]
local_connectivity=2
min_dist=0.15
target_names = ['t1', 't2', 't3', 't4', 't5', 't6', 't7', 't8', 't9', 't10']

plt.figure(figsize=(15,15))

for i in range(0, len(n_neighbours)):

    plt.subplot(3,5,i+1)
    plt.clf()
    plt.scatter(
        X_train[:, 0],
        X_train[:, 1],
        s = 20,
        c=y_train,
        cmap=plt.cm.nipy_spectral,
        edgecolor="k",
        linewidths=0.75,
        label=y_train,
        alpha=0.45,
    )
    plt.title(f'n_components = {n_components}, n_neighbors = {n_neighbours[i]}, local_conn = {local_connectivity}, min_dist = {min_dist}')
    cbar = plt.colorbar(boundaries=np.arange(11)-0.5)
    cbar.set_ticks(np.arange(10))
    cbar.set_ticklabels(target_names)

A: The reason for you seeing just one plot is the line plt.clf(). This command tells matplotlib to clear current figure. So, each time you loop through the code, it clear the previous figure and so, you see just the last one. Commenting that  line will give you the below figure, which is what I think you are looking for...
PLOT


text:
Q: Eigen solve symmetric positive definite system using LLT I want to solve a symmetric positive definite matrix using the LLT solver, to that effect I wrote this (to test):
Eigen::SparseMatrix<float> bijection(vert_count, vert_count);
Eigen::LLT<Eigen::SparseMatrix<Scalar>> llt_mat(bijection);

This fails to compile with error:
error: 'Eigen::SparseMatrixBase<Eigen::Block<Eigen::SparseMatrix<float, 0, int>, -1, 1, true> >::FixedSegmentReturnType<-1>::Type' {aka 'class Eigen::VectorBlock<Eigen::Block<Eigen::SparseMatrix<float, 0, int>, -1, 1, true>, -1>'} has no member named 'lpNorm'
  448 |       abs_col_sum = m_matrix.col(col).tail(size - col).template lpNorm<1>() + m_matrix.row(col).head(col).template lpNorm<1>();

I am not entirely sure how I should solve a system using the built in LLT solver.


text:
Q: Trouble with parsing and evecvp I am trying to write a C program that reads in a Lunix command as a string parses the string into a char*[] and then executes the command using evecvp.
This is my code:
Parsing the string
        char *args[40];
        char command[80];
        fgets (command, MAX_LINE, stdin);
        int counter = 0;
        token = strtok(command," ");
        args[0] = token;

        //printf("%s\n",args[0]);

        while(should_run == 1){
            token = strtok(NULL," ");
            if (token == NULL){
                break;
            }
            counter++;
            args[counter] = token;
            printf("%s\n",token);
        }
        args[counter+1] = NULL;
        executeCommands(args, counter, -1);

Executing the command
void executeCommands(char *args[], int counter, int histCounter){
/*int j;
for (j = 0; j <= counter; j++){
    printf("%s",args[j]);
}*/
printf("\n");
pid_t pid;
pid = fork();
if (pid == 0){
    execvp(args[0], args);
    printf("exec failed: %s\n", strerror(errno));
}
else{
    if(counter == -1 && histCounter == 1){
        wait(NULL);
    }
    else if(*args[counter] == '&'){
        wait(NULL);
    }
}

}
When I give a simple input such as "ls" or "pwd" it outputs "exec failed: No such file or directory." The only command that slightly works is "pwd &" this out puts "ignoring non-option arguments" followed by the correct current path.

A: One problem is that the newline character from your input stays at the end of the string, e.g. you're passing ls\n to execvp() instead of ls. Try something like this before calling executeCommands():
char *a = args[counter];
a[strlen(a) - 1] = '\0';
args[counter+1] = NULL;
executeCommands(args, counter, -1);


text:
Q: Are the Hogwarts Potion Books intentionally misleading? They don't seem to be giving the correct instructions in concocting the potions- as seen when Hermione isn't able to make her draught in Slughorn's class.

A: The potions books are not actually misleading, and Hermione can make the draught, it just takes longer than when Harry makes it with the help of Snape's side-notes. The reason for that is: Potion recipes are like regular food recipes, while the recipe is the same, the potions masters (just like the cooking chefs) don't follow the recipes and do something in a way to make the recipe faster or more powerful. For example, in one of the side-notes, Snape says that crushing an ingredient with the side of the knife is more efficient than cutting it, which makes Harry go through that point of the recipe faster, while Hermione, who follows the original recipe, uses a less efficient method, which leads to taking longer to complete a step.
So, again, the text books are not misleading, they just don't have, necessarily, the best way to do something.

A: Hermione is able to make her draught, and Slughorn approved of it, as is clear from the relevant passage in Half-Blood Prince.

Hermione's potion he gave an approving nod.

It's just not perfect. This is to be expected, even of someone who is a decent potions-maker and follows the textbook. As Slughorn tells them when they start:

We have a little over an hour left to us, which should be time for you to make a decent attempt at the Draught of Living Death. I know it is more complex than anything you have attempted before, and I do not expect a perfect potion from anybody.

Thus, the textbook is not inherently misleading. It's just that under the specific circumstances even someone as good as Hermione can't get a perfect potion by following the book.

A: I would hazard a guess that potion making is insanely more tough than cooking. Remember, this is something that is taught as a full subject over the course of (at least) 5 years.
There once was a course that I had to do, Engineering Drawing (Technical Drawing). It was about drawing things using a robust protocol and tools like a drafter. It seemed quite mechanical and easy to me -- all we had to do was make lines in a certain order.
Except that it wasn't easy. While it was easy to figure out what lines had to be drawn, we all made infinite mistakes. You make a mistake in one line, and notice it 20 lines later -- you have to redo the whole thing.
I think that Potions is similar. While there's a definite set and order of things to be done, these are easy to mess up. One mistake, and the potion will stop working. Following the instructions correctly may not be as easy as it looks. Hermione was never portrayed as infallible; it's quite possible she made a mistake.
Also, take a look at cooking. While following the instructions usually gets you an OK product, there's always something that a skilled cook can tweak to make it better. And there's always something a newbie can mess up. Same goes for Potions.

Here's another thing, as mentioned by Rob below: Not all the recipes may be exact. There might be something akin to "season to taste" found in cookbooks, or "left as an exercise to the reader" found in math and physics textbooks.

A: While I don't disagree with Manishearth; I always thought of it like the old saying:

"Those who can't do - teach." (1)

But amend it with

"Those who can't teach - write the text book."

Most of potion recipes were passed down through the ages; there might have been reluctance to alter them.
It is also entirely possible that the authors of the books were not as gifted in potion-making as Snape was (e.g., to crush the bean with the flat side of a silver blade instead of cutting), and did not think outside the box.
When it would be time to release a new version of potion-making recipes they would add new ones, but leave the old recipes alone; thinking "If it isn't broke - don't fix it"

(1) Not to say that the teachers at Hogwarts were not exceptional.

A: In the movie, it's portrayed as if everyone failed to produce the potion except Harry.
I did not read the book, but I'm guessing in the book, others were also able to produce the potion, but of a mediocre quality. While Harry, following Snapes side notes, were able to produce the best quality.


text:
Q: How to delete a document when multiple conditions are matched, firestore firebase I want to delete a firestore object when multiple conditions are matched.
Like below
db.collection('facilityOwners').where('facilityId', '==', facilityId).where('ownerId', '==', ownerId).delete()

In my facilityOwners collection

I want to delete a document when these two properties are matched.
And I dont want to find the documents first and then perform the delete.

A: You can only write (and thus delete) a document in Firestore if you know the complete, exact path to that document. Firestore does not support the equivalent of SQL's DELETE FROM facilityOwners WHERE ... queries.
This means that you will first have to get() the results of the query, loop through them, and delete each document individually, or in batches. Something like:
let query = db.collection('facilityOwners').where('facilityId', '==', facilityId).where('ownerId', '==', ownerId);
query.get().then((querySnapshot) => {
  querySnapshot.forEach((doc) => {
    doc.ref.delete();
  });
});

Also see:

*

*Cloud Firestore Swift: How to delete a query of documents

*How to delete document from firestore using where clause


text:
Q: Pyspark rdd.zip ValueError: Can not deserialize RDD with different number of items in pair I'm using spark 1.6.0 and I have a pyspark.mllib.tree.RandomForestModel for a prediction task. My data_rdd is formatted as follows:
[LabeledPoint(id1,feature),
 LabeledPoint(id2,feature),
...]

My code is
rfmodel = RandomForestModel.load(sc,modelpath)

What I want is to get ids along with predicted labels. So I do the followings,
predictions = rfmodel.predict(data_rdd.map(lambda x:x.features))
idsAndPredictions = data_rdd.map(lambda lp: lp.label).zip(predictions)

I run this code and it gives an error
ValueError: Can not deserialize RDD with different number of items in pair: (91, 90)

The error happens because of the zip function. It seems people get this error for not having data_rdd and predictions of the same length. But in my case, data_rdd and predictions obviously have the same length.
My question is how to get this working and if it's a spark bug, is there any other way to achieve the same outcome?

A: Strangely I make it work by reduce the number of partitions from around 500000 by default to 500. I hope someone could enlighten me.


text:
Q: Jquery Post & ASP.NET MVC Anti-ForgeryToken Validation In my controller,
  [HttpPost]
        [OutputCache(CacheProfile = "Short", VaryByParam = "id", VaryByCustom = "none")]
        [ValidateAntiForgeryToken(Salt = @ApplicationEnvironment.SALT)]
        public ActionResult username(string id) {
            try {
                if (id == null || id.Length < 3)
                    return Json(false, JsonRequestBehavior.AllowGet);

                var member = Membership.GetUser(id);

                if (member == null) {
                    //string userPattern = @"^([a-zA-Z])[a-zA-Z_-]*[\w_-]*[\S]$|^([a-zA-Z])[0-9_-]*[\S]$|^[a-zA-Z]*[\S]$";
                    string userPattern = "[A-Za-z][A-Za-z0-9._]{5,14}";
                    if (Regex.IsMatch(id, userPattern))
                        return Json(true, JsonRequestBehavior.AllowGet);
                }

            } catch (Exception ex) {
                CustomErrorHandling.HandleErrorByEmail(ex, "Validate LogName()");
                return Json(false, JsonRequestBehavior.AllowGet);
            }
            //found e false
            return Json(false, JsonRequestBehavior.AllowGet);

        }

and in my view I am doing this for post, I was able to retrieve data for getJSON using HTTP Get.  The problem is, when the user puts a space in the name, it doesn't validate and gives a 404.  So I thought I could do this using the post method, but it seems that I am unable to send my logname because I am sending an Antiforgery token in the data by serializing it ...
Can any one please help? I would be grateful.
@{
    string SALT = ApplicationEnvironment.SALT;
}

<script type="text/javascript" defer="defer">
    $(function () {
        if($("#LogName").length > 0){

            $("#LogName").blur(function(){
                var logValidate = "/Validation/username/" + $("#LogName").val();
                //anti-forgery token works don't need to create the input field here but if I pass the logname into the form as an input then if a user puts double quote/single quote then it will also crash.. so is there any other way around.
                var data = $('<form>@Html.AntiForgeryToken(SALT)</form>').serialize();
                $.post(logValidate, data, function (json) {
                    alert(json);
                });
            });
            $("#Email").blur(function(){
                var emailValidate = "/Validation/email/" + $("#Email").val();

                alert("got it");
            });
        }
    });
</script>

A: How about you take the value of the antiforgery token by jquery when sending the request?
Generate your antiforgery key as a hidden field:
@Html.AntiForgeryToken()

Look at the sourcecode and adjust the "#__RequestVerificationToken" selector
var antiForgeryVal = $('#__RequestVerificationToken').val();
data["__RequestVerificationToken"] = antiForgeryVal ;
$.post(logValidate, data, function (json) {
    alert(json);
});


text:
Q: SSH hot to check remote directory exist Idea is to check remote folder. Is it exist or no?
I try this

ssh -p 22 -tt user@server.com  'bash -d /home/test22

and it works fine

/home/test22: /home/test22: is a directory
  Connection to server.com closed.

But when I try to use it with "IF" - it is wrong...always said "That directory exists"
#!/bin/bash

if [ "ssh -p 22 -tt user@server.com  'bash -d /home/test22'" ]; then
    echo "That directory exists"
else
    echo "That directory doesn't exists"
fi

Can you show correct example?
Thank you!

A: The command to use is not bash but test or its alias [:
if ssh -p 22 -tt user@server.com  'test -d /home/test22'; then
    echo "That directory exists"
else
    echo "That directory doesn't exists"
fi

The other important thing is that [] is not part of the if syntax. if is always followed by a command and if evaluates its exit status. So no need to surround your ssh command with [].
-d dir are actually the arguments of command test or [.
test -d dir
[ -d dir ]

are identical, the latter form requires a closing ] argument.


text:
Q: Uneven looping and iteration in Matlab I am a beginner in MATLAB and I am encountering the following problem.
I am trying to write a code that will run the x first then after each 4 runs, k increments by 1. I have searched for the solution, but could not find one.
a=[1;2;3;4];
b=[8;4;6;7];
k=[7;4;5;6;7;8;9];
for i = 1:1:4
    for j = 1:1:7
       m=a[i]+ b[i]*k[j]
    end
end

my equation is M=a(x)+b(x)*k(t)
where x=1:4 and t=1:7
Like :
1+8*7
2+4*7
3+6*7
4+7*7
Then
1+8*4
2+4*4
.
.
.
and so on.
Can anyone please help on this? Thank you

A: Here is the final code I have. Thank you again for the help.
a=[1;2;3;4];
b=[8;4;6;7];
k=[7;4;5;6;7;8;9];
for j = 1:1:7
    for i = 1:1:4
        m=a(i)+ b(i)*k(j)
    end
end

Kind regards


text:
Q: How to update existing custom connection manager without breaking existing packages We have an existing MQ custom connection manager that's currently being used by several existing SSIS packages.
I want to add a new property and modify the code a little bit, but if I do that, it looks like I am breaking everything else (have to redo all of them).
Is there a way where I can get around this without disrupting the existing packages that use it?

A: Assuming that your you need to edit the SSIS package by adding the property and RUN it. After that you don't need the SSIS package. Following code method should be added to your application and call this method. So all the changes will be applied only to the new package without modifying another package.

*

*Get the SSIS package

*Create the copy of it by appending the GUID. so your package name is like PackageName_GUID.dtsx

*Add your property.

*RUN your SSIS package

*OnSuccess full execution. Delete the SSIS package.

Code
    public static DtsErrors RunSSISPackage(string packagePath, string MQProperty)
    {
             * Append the auto generated GUID with the package name for running the SSIS package
             */
            string uniqueId = Guid.NewGuid().ToString();

            string uniquePackage = Path.GetDirectoryName(packagePath) + @"\" + Path.GetFileNameWithoutExtension(packagePath) + "_" + uniqueId + ".dtsx";

            File.Copy(packagePath, uniquePackage);

            Package pkg;
            Microsoft.SqlServer.Dts.Runtime.Application app = new Microsoft.SqlServer.Dts.Runtime.Application();

            pkg = app.LoadPackage(uniquePackage, null);

            //MessageBox.Show(srcFileName);
            //MessageBox.Show(TPODBConnection);

            pkg.Connections["MQConnection"].<<YourPropertyName>> = MQProperty;

            //Uncomment this to overwrite the existing file
            //Do nothing until you are using a version control system
            //app.SaveToXml(packagePath, package, null);

            DTSExecResult result = pkg.Execute();

            if (result == DTSExecResult.Failure)
            {
                return pkg.Errors;
            }

            File.Delete(uniquePackage);

        return null;
    }


text:
Q: .NET 4.8 not creating a self-contained file for Linux I have a a little .NET Core console application that I would like to make a self-contained file of. Not only that, I would also like to create a self-contained file that will run on CentOS.
The issue I am having is when I run dotnet publish -r linux-x64 -c release --self-contained true I get multiple files and the files seem to be configured for Windows only. I also tried removing <OutputType>Exe</OutputType>. This makes sure there isn't any EXE file file when publishing, but I still get multiple files that I am not sure if they can even run on CentOS since they are only .dll files. My target framework is set to <TargetFramework>net4.8</TargetFramework>.
Here are some visuals of the output I am getting:
Having <OutputType>Exe</OutputType> set in my .csproj:

Having <OutputType>Exe</OutputType> removed:

A: As pointed out by Jonathon Chase and Herohtar, I targeted the wrong framework. The framework I used (net4.8) is Windows only.
The correct framework to use would be something like netcoreapp3.0.


text:
Q: Can I have more Community Licenses? The project that I am working on, predicts to have more than 20 Partner Community Users, which is the maximum number of this kind of licenses, as you can see from the screenshot too.
How can I obtain other licenses? Should we buy the extra ones?
Thank you,
Endrit.


text:
Q: I get the following error while trying to run my python script: 'TypeError: 'str' object is not callable' I'm building a GUI with PySimpleGUI in this GUI I want to see the availability of certain machines.
I can get the availability (see function: downtime). but when I try to implement this in my GUI window it produces an error.
This is my full code:
import PySimpleGUI as sg
import pyodbc
import databaseconfig as conf
from datetime import datetime, timedelta, time
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
sg.theme('GrayGrayGray')
# Connect to the SQL server
cnxn = pyodbc.connect(DRIVER= conf.driver,
                      SERVER= conf.server,
                      DATABASE= conf.database,
                      UID= conf.username,
                      PWD= conf.password)
cursor = cnxn.cursor()
# Selects the 'device' of database table
cursor.execute("SELECT device FROM kt_machines")
device = cursor.fetchall()
list_devices = [(row)[0] for row in device]
# Selects the 'Omschrijving' of database table
cursor.execute("SELECT Omschrijving FROM kt_machines")
omschrijving = cursor.fetchall()
omsch = [(row)[0] for row in omschrijving]

# This will remove everything that comes after '.'. now it prints like: 2023-02-10 07:20:10.747000. After this function it prints like: 2023-02-10 07:20:10
def removeAfterN(yourStr, nth, occurenceOf):
    return occurenceOf.join(yourStr.split(occurenceOf)[:nth])#print(removeAfterN(str(data[0]),1,"."))

# This function removes certain prefix
def my_removeprefix(omsch, prefix):
    if omsch.startswith(prefix):
        return omsch[len(prefix):]
    else:
        return omsch

# Removes prefix of your choosing
def removePrefix(num,prefixToDel):
    return my_removeprefix(omsch[num], prefixToDel)

# Gets timestamp from database
def timeStamp():
    cursor.execute(f"SELECT TS FROM kt_2010 WHERE id=(SELECT max(id) FROM kt_2010)")
    data = cursor.fetchone()
    if data[0] is not None:
        window[f'TS1'].update(data[0])
        return str(data[0])
    else:
        return 0

def timeStampDiff():
    # Get current time stamp. This shows the date and the time
    cursor.execute(f"SELECT TS FROM kt_2010 WHERE id=(SELECT max(id) FROM kt_2010)")
    data = cursor.fetchone()
    timestampp = datetime.now()
    difference = (timestampp - data[0])
    differenceMin = (difference.seconds / 60)
    differenceMinn = removeAfterN(str(differenceMin),1,".")
    return differenceMinn or 0

def createCircle():
    graph = window['graph0']
    circle = graph.draw_circle((88, 15), 7, fill_color='red', line_color='black')
    if int(timeStampDiff()) > 5:# If difference between current timestamp and latest timestamp from table is greater that 5 the circle will turn red.
            graph.TKCanvas.itemconfig(circle, fill='red')
    elif int(timeStampDiff()) < 5:# If difference between current timestamp and latest timestamp from table is less that 5 the circle will turn green.
        graph.TKCanvas.itemconfig(circle, fill='green')
    return circle or 0

def downtime():
    # Define when the workday starts, also define when the workday ends
    start_time = datetime.combine(datetime(2023,2,21), time(7, 30))
    end_time = datetime.combine(datetime(2023,2,21), time(16, 15))
    # Calculate how much minutes there are in the work day
    time_range_minutes = int((end_time - start_time).total_seconds() / 60)
    time_range_minutes = time_range_minutes - 45
    # Set the time threshold for downtime to 5 minutes (300 seconds)
    time_threshold = 300
    # Execute a SQL query to retrieve the timestamps of all the 1s from the sensor
    query = f"SELECT TS FROM kt_2010 WHERE message = 1 AND TS BETWEEN ? AND ? ORDER BY TS"
    cursor.execute(query, [start_time, end_time])
    # Initialize downtime counter
    downtime_counter = 0
    # Initialize previous timestamp variable
    prev_timestamp = None
    # Loop through the query results
    for row in cursor:
        # Extract the timestamp from the row
        timestampp = row[0]
        # If this is the first timestamp or if the previous timestamp was more than the time threshold
        if prev_timestamp is None or (timestampp - prev_timestamp).total_seconds() >= time_threshold:
            # Add the threshold to the downtime_counter
            downtime_counter += time_threshold
        # Otherwise: add the difference between the current timestamp and the previous one to the downtime counter
        else:
            downtime_counter += (timestampp - prev_timestamp).total_seconds()
        # This updates the prev_timestamp
        prev_timestamp = timestampp
    # If the last '1' was seen before they day ends (16:15) add the remaining time until the day ends(16:15)
    if prev_timestamp is not None and (end_time - prev_timestamp).total_seconds() >= time_threshold:
        downtime_counter += (end_time - prev_timestamp).total_seconds()
    # Calculate the total downtime in minutes
    downtime_minutes = int(downtime_counter / 60 - 45)
    #Beschikbaarheid = str(int(downtime_counter / 60 - 45) / time_range_minutes * 100)
    Beschikbaarheid = str((downtime_counter / 60 - 45) / time_range_minutes * 100)
    Beschikbaarheid = Beschikbaarheid.split('.')
    Beschikbaarheid = Beschikbaarheid[0]
    #Beschikbaarheid = Beschikbaarheid_partss
    #print(f"Total downtime for kt_2010: {downtime_minutes} minutes out of {time_range_minutes} minutes")
    print(f'Beschikbaarheid: {Beschikbaarheid}')
    window['besch1'].update(Beschikbaarheid)
    return Beschikbaarheid

Frame_Row1 = [[sg.Frame("",[[sg.Text(list_devices[0], font=('Helvetica', 12))],[sg.Text(removePrefix(0,'2010 - '), font=('Helvetica', 12))],[sg.Text('', font=('Helvetica', 12), key='TS1')],[sg.Text('', font=('Helvetica', 12), key='kt_2010'), sg.Text('', font=('Helvetica', 12), key='besch1')],
                                  [sg.Graph(canvas_size=(350,100), graph_bottom_left=(0,0),graph_top_right=(100,50),enable_events=True,key='graph0')]],size=(350,250)),]]
layout = [Frame_Row1]

window= sg.Window('Status kantbanken', layout, size= (1900,800), element_justification='c', finalize=True, grab_anywhere=True)

stamptime = timeStamp()
diffStamp = timeStampDiff()
Circlecreation = createCircle()
timeDown = downtime()

#print(downtime(datetime(2023,2,21).date(),'kt_2010',1))
import threading
t = threading.Timer(2,timeDown)
t.start()

#timer_thread = threading.Thread(target=timeDown)
#timer_thread.start()
while True:
    event, values = window.read(timeout=500) # returns every 5sec
    if event == 'close' or event == sg.WIN_CLOSED:
        break
    # If timout=100 gets to 100 it will do the following actions: it wll refresh the latest timestamp for every table. It will also create a red or green circle (see function 'createCircle()')
    if event == sg.TIMEOUT_EVENT:
        # Updates the timestamp for 9 bending machines (the other ones dont have a sensor)
        timeStamp()
        # Creates a circle for 9 bending machines (the other ones dont have a sensor)
        createCircle()
    pass

# Close the cursor, connection and window
cursor.close()
cnxn.close()
window.close()

The full error I get is:
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Users\stagiair\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
    self.run()
  File "C:\Users\stagiair\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1394, in run
    self.function(*self.args, **self.kwargs)
TypeError: 'str' object is not callable

I have already searched the internet and interacted with chatGPT to look for some anwsers, but nothing resolves this issue.
I feel like it has something to do with my function: downtime().
How do I fix this?


text:
Q: Count of records processed during batch I have a batch apex in which I am trying to insert 1000 records at a time. I am using Database.insert() to insert the records.For this is there any way to get the count of records that has been inserted successfully and the count of records that has failed during insert?
Thanks!

A: Can't give you code but you can proceed with following hints:-

*

*Implement Database.stateful with your batchable inteface

*Declare two/one instance variable which will store failed and successful insert records information

*Leverage Database.insert result as:
Database.SaveResult[] srList = Database.insert(accts, false);
// Iterate through each returned result
for (Database.SaveResult sr : srList) {
    if (sr.isSuccess()) {
        // Operation was successful, so get the ID of the record that was processed
        // fill list with successfult IDs + sr.getId()); // new Ids
    }
    else {
        // Operation failed, so get all errors
        for(Database.Error err : sr.getErrors()) {
            // get error fields and other stuff from Error class
        }
    }
}

*After it, in finish() method you can collect and process information for failed and successful records.

A: For that you'll need to use Database.SaveResult and iterate through the results to check whether it's a success or a fail:
Database.SaveResult[] saveResult = Database.insert(accounts, false);
Integer counter = 0;

for (Database.SaveResult sr : saveResult)
{
    if (sr.isSuccess())
    {
        counter++;
    }
}

system.debug(counter); // Total number of successfully inserted accounts

A: You have to implement Database.Stateful in your batch class and then you can have instance variables that don't lose state between batches.
global class implements Database.Batchable<sobject>, Database.stateful{

  public String query = 'Select id from Opportunity' ;
  public Integer totalAmtOfRecords = 0;

  global Database.QueryLocator start(Database.BatchableContext BC) {
     return Database.getQueryLocator(query);
   }

   global void execute(Database.BatchableContext BC, List<sobject> scope) {
      totalAmtOfRecords += scope.size();
      //your logic ...
    }

     global void finish(Database.BatchableContext BC) {
        // Print Total amount of records processed in Batch Job
        system.debug('Total amount of records processed :' + totalAmtOfRecords);
     }

   }

For more details check : How To Get Total Amount Of Records Processed In Batch Job In 10 Minutes And Still Look Your Best


text:
Q: write a Request using JPA How can I retrieve the environment names  by given Platform names using JPA request (1 environment can be associated to n Plateform and 1 Platform can be associated to n Environmnt)?
public class HPe implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected HPePK hPePK;
@Column(name = "PE_TIMEOUT")
private Integer peTimeout;
@Column(name = "PE_STATUS")
private Boolean peStatus;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "hPe")
private Collection<HPesp> hPespCollection;
@JoinColumn(name = "PE_ENV", referencedColumnName = "ENV_URL", insertable = false, updatable = false)
@ManyToOne(optional = false)
private HEnv hEnv; // HEnv  classe name
@JoinColumn(name = "PE_PLATFORM", referencedColumnName = "PLATFORM_NAME", insertable = false, updatable = false)
@ManyToOne(optional = false)
private HPlatform hPlatform;  //HPlatform  classe name
}

Update
problem Resloved :
SELECT h.hPePK.peEnv FROM HPe h WHERE h.hPePK.pePlatform = :w

A: Please try
select hpe.hEnv.envName from HPe hpe where hpe.hPlatform.platName = :platName

(Use platName as parameter)
Maybe it needs something more like a join but please try first


text:
Q: Como desabilitar um botão em java sem retirar sua cor Tenho um botão que, ao clicá-lo ele muda de cor, mas se clicar nele novamente nada deve acontecer. Porém ainda não consigo bloquear essa ação.
Tentei esse codigo:
private void Button1_1ActionPerformed(java.awt.event.ActionEvent evt) {
    if(TextoJogador.getText().equals("Jogador 1")){
        Button1_1.setBackground(Color.CYAN);
        TextoJogador.setText("Jogador 2");
        play(sound);

    }else{
        Button1_1.setBackground(Color.GREEN);
        TextoJogador.setText("Jogador 1");
        play(sound);
    }
    Button1_1.setEnable(false); //essa parte que faz o button perder a cor
}

mas o botão perde a cor que foi selecionada ao ser desativado.

A: Pelo que eu entendo o setEnabled(false) muda a aparência do botão mesmo, não tem jeito. Mas experimente assim:
private void Button1_1ActionPerformed(java.awt.event.ActionEvent evt) {
    if (Button1_1.getBackground() != Color.CYAN && Button1_1.getBackground() != Color.GREEN) {
        if(TextoJogador.getText().equals("Jogador 1")){
            Button1_1.setBackground(Color.CYAN);
            TextoJogador.setText("Jogador 2");
            play(sound);

        }else{
            Button1_1.setBackground(Color.GREEN);
            TextoJogador.setText("Jogador 1");
            play(sound);
        }
    }
}

A: Isso ocorre por causa do LookAndFeel(LAF), pois é ele quem define as estilizações de todos os componentes do swing. Se você aplicar o LAF Metal, que é um LAF mais básico, esse problema não irá acontecer.
Porém, imagino que esteja utilizando o Nimbus, que é o LAF padrão de projetos criados pelo netbeans, ainda tem como alterar direto nele, mas a outra resposta acaba sendo mais simples e viável, sem ter que deixar a aparência da aplicação mais básica.
Se quiser se aventurar em alterar o LAF, pode adicionar apenas a linha abaixo dentro do main, antes de iniciar a tela:
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");

Com isso, o setEnabled(false)  não afeta o background que você alterou inicialmente do botão, porém, como consequência de ser um tema básico, sua aplicação fica com uma aparência mais rudimentar, quando comparada ao Nimbus.


text:
Q: Cannot read property 'originalname' of undefined nodejs mongoose I'm trying to store images using mongoose, express, multer but when I test with postman it always gives the following error:

TypeError: Cannot read property 'originalname' of undefined

var express=require("express")
var  router= express.Router();
var app=express()
var artisanModel=require("../models/artisanModel")
var fs = require('fs')
const multer = require('multer');
const upload = multer({dest: __dirname + '/uploads/images'});

router.post('/add', upload.single('image'), function (req, res) {
  console.log(req.file.originalname)
  var file = __dirname + '/uploads/' + req.file.originalname;
  fs.readFile(req.file.path, function (err, data) {
    fs.writeFile(file, data, function (err) {
      if (err) {
        console.error(err);
        var response = {
          message: 'Sorry, file couldn\'t be uploaded.',
          filename: req.file.originalname
        };
      } else {
        response = {
          message: 'File uploaded successfully',
          filename: req.file.originalname
        };

        artisan = new artisanModel({
          firstName: req.body.firstName,
          lastName: req.body.lastName,
          email: req.body.email,
          password: req.body.password,
          tel: req.body.tel,
          image:  req.file.originalname

        })

        artisan.save(function (err) {
          if (err) {
            res.send({'State': 'Not Ok', 'msg': 'err' + err})
          }
          else {
            res.send({'State': 'Okay', 'msg': 'added'})
          }
        });
      }``
    });
  })
})

A: //model
//Require Mongoose
var mongoose = require('mongoose');

//Define a schema
var Schema = mongoose.Schema;

var artisanModelSchema = new Schema({
  firstName: {type:String,
    trim:true,
    required:false},

  lastName : {
    type:    String,
    trim:true,
    required:false},
  tel : {
    type:    String,
    trim:true,
    required:false},
  adresse: {
    type:    String,
    trim:true,
    required:false},
  password: {
    type: String,
    trim: true,
    required: false
  },
  imagee:
    { dataa: Buffer, contentType: String , path : String }

});
var artisanModel=mongoose.model('artisanModel',artisanModelSchema);
module.exports=artisanModel;

A: pls check the multer documentation it will not process any form which is not multipart (multipart/form-data).
NOTE: Multer will not process any form which is not multipart (multipart/form-data).

https://www.npmjs.com/package/multer
Check the second line in the above link.
EDIT
Please upload the images using postman changing the body type into form-data and upload the image. Refer the screenshot.


text:
Q: $.get sends prototype functions in request URL? I have some prototype functions added to Object which in my opinion were practical in certain scenarios. However, I noticed that when I executed a $.get, the prototype functions are handled as data members and are sent like http://...?prototypefunc=false.
This is rather useless as I don't supply these as data members, but they are added to the query string.
To be exact, I have this code:
Object.prototype.in = function() {
    for(var i=0; i<arguments.length; i++)
       if(arguments[i] == this) return true;
    return false;
}

$.get('http://localhost/test.php', {'test': 'foo'}, function(text) { });

The corresponding URL constructed is:
http://localhost/test.php?test=foo&in=false
How can I avoid this?

A: jQuery runs a for...in loop on the object passed, which iterates over all enumerable properties of an object, whether inherited or not.  It doesn't do any checks to see if the object's property is owned by the object or inherited via the prototype chain.
Also, if it encounters a property whose value is a function during the serialization of the object it will execute the function and use the return value.
There are a few solutions:

*

*Change your code so that it doesn't modify Object.prototype.

*Pass a string instead of an object, or serialize the object to a string using your own code.

*Override the jQuery.param() function with your own, and force it to check each property with .hasOwnProperty(propertyName).

*Make the property on the prototype chain non-enumerable by using Object.defineProperty() (ECMAScript 5 compliant browsers only).

A: In your case, if you dont't want to remove that in function, you should serialize data (with function, which works similary to jQuery serialize) to string and append it to URL.


text:
Q: A unique 'discount' challenge for a jQuery calculator I've been muddling through this one for a while...  I have three form fields: individuals, couples, total. This is a cost calculator for a conference registration.
A single person (#individuals) costs $50. A couple (#couples) costs $75.  There's a discount applied if there are more than 3 total people signing up. Each person costs $40 under the discount. So we count the total people, and if 3 or more people, apply a new price of $40 to each person. Before counting total people between #individuals and #couples fields, the value of #couples needs to be multiplied by two, since there are two people per couple. The new 'discounted' #individuals price is $40 and new #couple price is $80.
My question is simply "where have I gone wrong?".  Any insight is greatly appreciated.
My current code, which is yielding incorrect numbers in the #total field:
   $('#individuals').change(compute);
   $('#couples').change(compute);
   function compute() {
      var ind = $('#individuals').val(); // number of individuals
      var coup = $('#couples').val()*2; // number of people in a couple (2)
      var people = ind + coup; // add up the total people
      if (people >= 3) {
        var a = $('#individuals').val()*40; // discount price of an individual
        var b = $('#couples').val()*80; // discount price of couple
      }
      else {
        var a = $('#individuals').val()*50; // normal price of an individual
        var b = $('#couples').val()*75; // normal price of couple
      }
      var total = a + b;
      $('#total').val(total);
   }

A: *

*don't repeat yourself - only make one call to $('#element').val() for each field

*use parseInt(val, 10) to ensure your numbers are numbers and not strings.  Your ind field is currently a string and will cause errors when you "concatenate" it to coup:
e.g.:
function compute() {
  var ind = parseInt($('#individuals').val(), 10); // number of individuals
  var coup = parseInt($('#couples').val(), 10);    // number of couples
  var people = ind + 2 * coup;                     // add up the total people
  var total;
  if (people >= 3) {
    total = 40 * people;
  } else {
    total = 50 * ind + 75 * coup;
  }
  $('#total').val(total);
}

$('#individuals,#couples').on('change', compute);


text:
Q: How to add more lines in a Xamarin Pin I want to add more lines in my Xamarin application.
I am using Xamarin maps to add pins to the map. I thought that Xamarin pin renders differently from Google maps markers so I tried writing a paragraph and it seems they are limited to 1 line. I know for sure that on Google maps marker you need to make a custom snippet but is this the same case for Xamarin? I don't want a full custom one just more lines to write. Is there any customisation without making a custom renderer for xamarin maps? I couldn't find any website about this.
Thanks alot


text:
Q: How to mark an item completed with Redux? I'm playing around with the Redux todo example sandbox.
I changed /components/TodoList.js, since I don't want to use the input field and the "Add todo" button, but I just want to have my own car data there. Here is my code:
import React from 'react'
import PropTypes from 'prop-types'
import Todo from './Todo'

const cars = [
  {text: 'Audi', id: 1},
  {text: 'Nissan', id: 2},
  {text: 'Mazda', id: 3},
]

const TodoList = ({ todos, onTodoClick }) => (
  <ul>
    {cars.map(todo =>
      <Todo
        key={todo.id}
        {...todo}
        onClick={() => onTodoClick(todo.id)}
      />
    )}
  </ul>
)

export default TodoList

How do I get the toggling to work (I mean marking the car completed: true || false)?
In /reducers/todos.js I have the following:
const todos = (state = [], action) => {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        {
          id: action.id,
          text: action.text,
          completed: false
        }
      ]
    case 'TOGGLE_TODO':
      return state.map(todo =>
        (todo.id === action.id)
          ? {...todo, completed: !todo.completed}
          : todo
      )
    default:
      return state
  }
}

export default todos

This part is clearly wrong:
(todo.id === action.id)

I tried various things, but can't get the toggling (completed: true || false) to work on the "Audi", "Nissan", and "Mazda". I also tried at looking at other questions, but couldn't find a solution.
How do I mark the cars "completed"?

A: The problem here is you're using your hard-coded list of cars, and not the state returned via Redux.  It doesn't matter what you dispatch; the cars variable is never updated, and thus never receives the toggled state.
The solution here is to use that list of cars in your initial Redux state.
const initialState = [
  { text: 'Audi', id: 1, completed: false },
  { text: 'Nissan', id: 2, completed: false },
  { text: 'Mazda', id: 3, completed: false }
]

const todos = (state = initialState, action) => {
  switch (action.type) {
  case 'ADD_TODO':
    return [
      ...state,
      {
        id: action.id,
        text: action.text,
        completed: false
      }
    ]
  case 'TOGGLE_TODO':
    return state.map(todo =>
      (todo.id === action.id)
        ? {...todo, completed: !todo.completed}
        : todo
    )
  default:
    return state
  }
}

export default todos


text:
Q: Scala: Is there a difference between method parameter String* and Array[String] Is there a difference between a method parameter String* and Array[String]?
Console:
scala> def main(args: Array[String]): Unit = {}
main: (args: Array[String])Unit

scala> def main(args: String*): Unit = {}
main: (args: String*)Unit

Code 1:
object Example {
  def main(args: Array[String]): Unit = {
    println("Hello")
  }
}

>> Hello

Code 2:
object Example {
  def main(args: String*): Unit = {
    println("Hello")
  }
}

>> Exception in thread "main" java.lang.NoSuchMethodException: Example.main([Ljava.lang.String;)
    at java.lang.Class.getMethod(Class.java:1786)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:126)

A: Yes,
String* is a varargs, it takes in any number of Strings, which will be passed to the method as a Seq[String].
Array[String] take in a single Array of Strings.
If you have a sequence of String that you want to pass as a String*, you cannot do so directly, but you can "splat" out the sequence to pass it in using the :_* type ascription.
def varArg(input: String*){}

val strings = Seq("hello", "world")
varArg(strings:_*)

A: I went and asked on the forum.
The annotation you want is annotation.varargs.
I had some inkling that they had that glue, but I never had a reason to use it.
Personally, I'd rather it were automatic for a main method, b/c obvious.
$ scala
Welcome to Scala 2.12.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_131).
Type in expressions for evaluation. Or try :help.

scala> object Main { @annotation.varargs def main(args: String*) =
     | println(args.size)
     | }
defined object Main

scala> Main.main(Array("hello","world"): _*)
2

OK, cool.


text:
Q: How can I change a format of an exported java object into a file? I'm trying to export java object into a txt file, but the output in that file is not well formated and contains unnecessary data. If someone could tell me what am I doing wrong. So this is the simple example of the code:
import java.io.Serializable;

public class Test implements Serializable{

    private static final long serialVersionUID = 1L;
    private String shortName;
    private String fullName;

    public Test(String shortName, String fullName) {
        this.shortName=shortName;
        this.fullName=fullName;
    }

    public String getShortName() {
        return shortName;
    }
    public void setShortName(String shortName) {
        this.shortName = shortName;
    }
    public String getFullName() {
        return fullName;
    }
    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    @Override
    public String toString() {
        return "Name:" + shortName +   "\nFullName: " + fullName;
    }

}

And this is a part of the method:
FileOutputStream outputStream = new FileOutputStream(fullPath);
        ObjectOutputStream o = new ObjectOutputStream(outputStream);
        Test test = new Test("Short name of test","Full name of test");
        o.writeObject(test);
        o.close();
        outputStream.close();

And this is what I get in the file:
' sr &com.testing.project.Evaluation.model.Test        L fullNamet Ljava/lang/String;L     shortNameq ~ xpt Full name of testt Short name of test

I would appreciate any kind of help.

A: You are using Java Serialization which writes the object into its own binary format, not text. If you need text format, I would suggest you use JSON, with a library such as jackson-databind.
And here is a working example for your convenience (which both writes to a text file and reads back from the text file to an object):
Main.class
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {

    public static void main(String[] args) throws JsonGenerationException, JsonMappingException, FileNotFoundException, IOException {
        ObjectMapper om = new ObjectMapper();
        Test test = new Test("Short name of test","Full name of test");
        om.writeValue(new FileOutputStream("test.json"), test);

        Test readValue = om.readValue(new FileInputStream("test.json"), Test.class);
        System.out.println(readValue.getShortName());
        System.out.println(readValue.getFullName());
    }
}

Test.class
import java.io.Serializable;

public class Test implements Serializable{

    private static final long serialVersionUID = 1L;
    private String shortName;
    private String fullName;

    public Test() {

    }

    public Test(String shortName, String fullName) {
        this.shortName=shortName;
        this.fullName=fullName;
    }

    public String getShortName() {
        return shortName;
    }
    public void setShortName(String shortName) {
        this.shortName = shortName;
    }
    public String getFullName() {
        return fullName;
    }
    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    @Override
    public String toString() {
        return "Name:" + shortName +   "\nFullName: " + fullName;
    }
}

Notice that I've added a default constructor to Test.class so that Jackson can create it while deserializing from json.

A: The writeObject function writes the object graph of Test to the file stream. It is used for persistence in JAVA. If you want to store field data to a file I suggest to use a dedicated method in your class using FileWriter.

A: ObjectOutputStream will not write in readable format. You probably want to use a FileWriter:
    try (BufferedWriter writer = new BufferedWriter(new FileWriter("test.txt"))) {
        Test t = new Test("Short name of test", "Full name of test");
        writer.write(t.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }


text:
Q: Need RegEx for following scenario in Perl Hi Friends Im new to perl, I need a Regex to find like what i highlighted below, can some one give solution ?
& # x 2003;Ferrara-Florence 33, 58
Saint Patrick & # x 2019; s Purgatory 1, 2, 5, 6, 11–12, 16, 20, 27, 61, 86, 105–6, 127–62, 179, 184–5, 219, 233, 237–8, 260
Checco Rossi da Meleto 70, 127, 140–3, 151
Aragona, Tullia d& # x 2019; 127, 161–2
Checco 70, 127, 140–3
& # x2003;Ferrara-Florence 33, 58
M & # x00FC;ns & # x 00FC;ter, Sebas & # x00FC;tia & # x00FC;n 215, 228–32
Machiavelli, Niccolò 7–8, 15, 26, 37– 8, 67, 74, 159, 245, 249–50
I gave extra space to show the decimal characters
Thank you

A: you can try this pattern:
(?m)^(?>& *# *x *[A-F0-9]{4};|[\p{L} ,-]+?(?= |&))+

A: Try this one :
(.+?)(?:[\d\-]+,\s)+.+

Demo :
http://rubular.com/r/VAsBRQaRmV
and another demo (with explanation and a minor edit) : http://regex101.com/r/mS9oN3

A: How about:
^(.+?)\s+(?=\d+[,-])


text:
Q: Firebase http functions api suddenly stopped working Firebase Cloud functions return:

Error: Server Error
The server encountered an error and could not complete your request.
Please try again in 30 seconds.

Last time the issue occurred Firebase team has updated their status dashboard with an investigation issue.
Right now it seems that everything is just fine according to their dashboard.
My http functions worked perfectly, suddenly everything stopped. Is it Firebase issue? Haven't they updated the dashboard yet? What can I do in order to be sure it's not my side issue?
Note: Although I can redeploy the functions from my local computer to Firebase (which is also not helping to solve the issue), I cannot redeploy functions directly from google cloud functions editor.
If someone is facing the same issue please comment below so we will be able to know that it is a wide problem.
Thanks a lot
Update (06.09.20 18:30)
Right now it seems that everything is working again. If it was a real Firebase outage you will be able to see the investigation in the dashboard.


text:
Q: Android view alert msg when i receive messege from service Hi i have a problem on my project, i have one activity and service , i use messenger to communication with us. I would view a alert dialog when i receive a message from service ,but this dialog is not appear. On log cat i see a log with text.
Do you have a solution .
My code is:
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.Map;

import ztl.Bologna.activity.Database.DBopenHelper;
import ztl.Bologna.OverlayList;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Messenger;
import android.provider.BaseColumns;
import android.app.AlertDialog;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.Menu;

public class MapsActivity extends MapActivity{
    private MyLocationOverlay mOverlay;

    protected static MapView gmap;
    private DBopenHelper db;
    OverlayList overlay;
    private GuiHandler guiHandler;
    private Messenger messenger;
    public double destLat = 44.497592;
    public double destLong = 11.356151;
    private double Long = 11.352693;
    private double Lat = 44.497271;
    Intent serviceIntent;
    public Cursor cursor;
    int version ;

    //final MapController control = gmap.getController();
    GeoPoint gp = new GeoPoint((int)(Lat * 1e6),(int)(Long * 1e6));

    //Context c = getApplicationContext();

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        Context context;
        context = getApplicationContext();
        Log.e("context",""+context);
        //db = new DBopenHelper(context);
        db = new DBopenHelper(this,1);
        guiHandler = new GuiHandler(this);
        Log.d("put", "database");
        gmap=(MapView)findViewById(R.id.mapview);
        gmap.setClickable(true);
        gmap.setBuiltInZoomControls(true);
        mOverlay=new MyLocationOverlay(this,gmap);

        //control.setCenter(gp);

        // control.animateTo(gp);
        gmap.getOverlays().add(mOverlay);
        Lat=44.497271;
        Long=11.352693;
        updateMapOverlay();
        db.close();

        messenger = new Messenger(guiHandler);
        serviceIntent = new Intent(MapsActivity.this,MessaggeService.class);
        serviceIntent.putExtra(MessaggeService.CALLER, MessaggeService.POSITION);
        serviceIntent.putExtra(MessaggeService.MESSENGER, messenger);
        startService(serviceIntent);
        Log.e("Debug", "Service Started from activity");
        //ms = new MessaggeService(overlay,gmap,c);

        ///destLat = mOverlay.getMyLocation().getLatitudeE6();
        //destLong = mOverlay.getMyLocation().getLongitudeE6();

    }

    private void addOpenPoint(GeoPoint g) {
        OverlayItem overlayitem = new OverlayItem(g, "", "");
        overlay.addOverlay(overlayitem);
        Log.e("over",""+overlayitem);
    }

    protected void onResume() {
        super.onResume();
        mOverlay.enableMyLocation();
        mOverlay.runOnFirstFix(new Runnable() {

            //  @Override
            public void run() {
                //gmap.invalidate();
                gmap.getController().animateTo(mOverlay.getMyLocation());
                gmap.getController().setZoom(16);

                //updateMapOverlay();

            }

        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_maps, menu);
        return true;
    }

    void updateMapOverlay() {
        List<Overlay> mapOverlays = gmap.getOverlays();
        Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
        //mapOverlays.clear();
        overlay = new OverlayList(drawable, this);
        mapOverlays.add(overlay);
        Cursor cursor = db.getZtlStreet();

        if (cursor.moveToFirst()) {
            while(cursor.moveToNext()) {
                Integer lat = (int) (cursor.getDouble(cursor.getColumnIndex("latitude")) * 1e6);
                Integer lon = (int) (cursor.getDouble(cursor.getColumnIndex("longitude")) * 1e6);

                GeoPoint p = new GeoPoint(lat, lon);
                addOpenPoint(p);
            }
        }

    }
    public static class GuiHandler extends Handler {
        // TODO da unificare con quello ChooseEVSEActivity
        public static final int FALSE = 0;
        public static final int TRUE = 1;
        // tiene il conto del tempo che è passato dall'ultima volta;

        WeakReference<MapsActivity> wrActivity;

        public GuiHandler(MapsActivity activity) {
            wrActivity = new WeakReference<MapsActivity>(activity);
        }

        public void handleMessage(android.os.Message msg) {
            final MapsActivity activity = wrActivity.get();
            /*Create alert dialog to access on ztl street*/
            AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            builder.setMessage("Accesso Ztl non puoi accedere");
            builder.setPositiveButton("chiudi",new DialogInterface.OnClickListener() {

                //@Override
                public void onClick(DialogInterface dialog, int id) {
                    // TODO Auto-generated method stub

                    dialog.cancel();
                }
            });

            switch (msg.what) {
            case MessaggeService.UPDATE_UI_MSG:
                AlertDialog alertMsg = builder.create();
                alertMsg.show();

                break;
            }
        }
    }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
}

My service with message is :

    for(int i = 0 ; i< overlay.size();i++){

                Log.e("item : ","n"+overlay.size());
                OverlayItem item = overlay.getItem(i);
                Location l1 = new Location("");
                l1.setLatitude(item.getPoint().getLatitudeE6());
                Log.e("l1", "l1"+l1.getLatitude());
                l1.setLongitude(item.getPoint().getLongitudeE6());
                Location l2 = new Location("");
                l2.setLatitude(destLat);
                l2.setLongitude(destLong);
                Log.e("l2", "l2"+l2.getLatitude());

                try {
                    String caller = "generic";
                    try {
                        caller = intent.getStringExtra(CALLER);
                        Bundle extras = intent.getExtras();
                        if (extras != null) {

                            if (POSITION.equals(caller)) {
                                positionMessenger = (Messenger) extras.get(MESSENGER);
                                Log.e("position",""+positionMessenger);
                            }
                        }

                        System.out.println("Instantiating " + caller + " Messenger OK :" + positionMessenger);
                    } catch (Exception e) {
                        //Log.e(UpdaterService.class.getName(), "Error instantiating " + caller + " Messenger" + e.getMessage());
                        //se il servizio non è ancora partito allora esco da esso in modo che venga istanziato correttamente
                        if(!doUpdate) {
                            stopSelf();
                        }
                    }
                    if (l2.distanceTo(l1) >100) {
                        Log.e("distance","Ztl non puoi accedere");

                        Message msg = Message.obtain();
                        Log.e("msg",""+msg);
                        msg.what = UPDATE_UI_MSG;
                        positionMessenger.send(msg);
                        Log.e("send","send");
                    }} catch (RemoteException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

            }

A: You need to order the builder to show at the end
builder.show();


text:
Q: When to use EF navigation properties over manual indexed queries? I'm wondering if there's any time when performing a query like this:
var documentId = report.DocumentId;
return db.Documents.Find(documentId);

Would be better or worse than setting up a virtual/nav property and doing this:
return report.Document

Where DocumentId is the PK on that table.
Are they the same thing?

A: I'd say if it's the document related to the report that you're after then there's no reason not to do report.Document. Both your options should perform the same query. What you could do which may provide some benefit is to use Include:
db.Reports.Include(x => x.Document).First(report => report.Id == id)

This would allow you to retrieve the report and its related document in a single query. i.e. the document wouldn't be lazy loaded whenever your code reached report.Document.


text:
Q: Unknown job: php5-fpm I am running a debian 7 server and installed nginx and php-fpm
But when I try to start or restart php5-fpm I get this error:
start: Unknown job: php5-fpm

The file php5-fpm exists in /etc/init.d/
When I try to execute
    sh /etc/init.d/php5-fpm
It does not return anything to me in my console.
Hope you can help me.


text:
Q: Ansible: Building a dynamic HTML email template I hitting a roadblock with this task. I am working on a patch management playbook, that is doing a bunch of things, but I hitting the ceiling on building an email template, that uses tables, to report on the facts from the remote servers.
Here is the playbook and jinja2 template I am using:
---
- name: Send HTML Email with System Uptime and Inventory Hostname
  hosts: all
  gather_facts: yes

  vars:
    success_servers: []
    server_hostname: []

  tasks:

    - name: Create custom fact
      set_fact:
        server_hostname: "{{ server_hostname + [inventory_hostname] }}"

    - name: Get system uptime
      shell: 'uptime | cut -f1-6 -d" "'
      register: uptime_result

    - name: Add server to success list if snapshot and patches were successful
      set_fact:
        success_servers: "{{ success_servers + [inventory_hostname] }}"
      when: uptime_result is defined

    - name: Get the total amount of updates remaining
      shell: yum list updates | grep '^.' | wc -l
      register: updates_result

    - name: Create jinja2
      template:
        src: templates/html.j2
        dest: email.html
      delegate_to: localhost

  post_tasks:

    - name: Send HTML email
      mail:
        host: "{{ smtp_server }}"
        port: 25
        subject: "System Uptime and Inventory Hostname"
        body: "{{ lookup('file', 'email.html') }}"
        from: "{{ from_email }}"
        to: "{{to_email }}"
        #content_type: html
        subtype: html
        charset: utf8
      delegate_to: localhost
      run_once: true

Here is a sample of the jinja2 template:

Servers successfully patched

            Hostname
            Uptime
            Successfully Snapped & Patched
            Remaining Updates

        {% for host in groups['all'] %}

            {{ server_hostname }}
            {{ uptime_result }}
            {{ success_servers }}
            {{ updates_result.stdout }}

        {% endfor %}

I believe I figured out how to dynamically populate the tables using the for-loop in the Jinja template, but here are the issues I am having:

*

*By setting the run once statement to true, my jinja2 template is only populated with details from one server. I have a total of two servers in my inventory, so two tables are built, which is correct, but populated with the same server details twice. Which is normally the first server in my inventory list.

*By removing the run_once statement, declaring it false, I am subject to receiving an email for the two servers I have in my inventory list, which builds two tables, with the same server details in each table. Basically, the same thing is happening in 1) but an email for however many servers would be in the inventory list. Based on the design, ansible will loop through all task on each server.

How would I accomplish this by populating the jinja2 template with all of the server names and details, but run it once? I thought about appending everything to a file using line in file module and cat the output to the email body, but it overcomplicates the play more than it needs to, or maybe I should take this route. How would you handle this?
Here is a sample of the email:
(ignore the uptime details I am working on this tee-hee)
Output of the email
Edit: Here is a sample inventory:
[prod_servers]
90vmswipe1.com
90vmswipe2.com

A: Your set of tasks can basically be reduced to (untested, to be amended for your exact requirement). See the documentation for magic var ansible_play_hosts_all:
---
- name: Send HTML Email with System Uptime and Inventory Hostname
  hosts: all

  tasks:

    - name: Get system uptime
      shell: 'uptime | cut -f1-6 -d" "'
      register: uptime_result

    - name: Get the total amount of updates remaining
      shell: yum list updates | grep '^.' | wc -l
      register: updates_result

  post_tasks:

    - name: Send HTML email
      mail:
        host: "{{ smtp_server }}"
        port: 25
        subject: "System Uptime and Inventory Hostname"
        body: "{{ lookup('template', 'html.j2') }}"
        from: "{{ from_email }}"
        to: "{{ to_email }}"
        #content_type: html
        subtype: html
        charset: utf8
      delegate_to: localhost
      run_once: true

with a template which looks like (truncated to the relevant loop only):
        {% for host in ansible_play_hosts_all %}

            {{ hostvars[host].inventory_hostname }}
            {{ hostvars[host].uptime_result | d('N/A') }}
            {{ 'yes' if hostvars[host] uptime_result is defined else 'no' }}
            {{ hostvars[host].updates_result.stdout | d('No result') }}

        {% endfor %}


text:
Q: Increase column width in a list view web part How can I increase the column width in a list view web part?

A: I couldn't resize the grabby part in the th without breaking it, but this works in a Content Editor Web Part:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
  setTimeout(function(){
    $("th[title='Title']").css({"width":"400px"})
  }, 2000)
})
</script>

A: There is a workaround to set the column width, but it will effect all columns.
Check the CSS of ListViewWebPart's Html Table (via view source code or IE Dev toolbar)
Consider, ListViewWebPart's Table class name is - .msTable
Then write an inline CSS in your aspx page like
.msTable TD
{
   width:80px;
}

The above code will set the width fixed for column inside ListViewWebPart.

A: To increase the width of a particular column in the List View Web Part
Add a Content Editor Web Part in your page
Add the below css text in it and save.
<style type='text/css'>
.ms-vh-div[DisplayName='<ColumnName>']
{
  width:250px;
}
</style>

You can get the <ColumnName> from the source of the table. [F12]

A: *

*Open the List in Sharepoint designer and then select column (header of the column) of which you wish to increase the width and select the properties for that and select CSS Style to open the styling window and then set the width in it.

*

*Then from the top bar menu select "Insert Tab" then from it select "Customize XSLT-> Customize entire view"

*Goto the header of the column from the markup view and find something like
"<th nowrap="nowrap" scope="col" onmouseover="OnChildColumn(this)">" tag for that column and remove - nowrap="nowrap"
and save it and test, it would work fine!

A: Solution for me was very simply. As soon as multiple [Space]s are not working because are shortened by design, I extended the name of column in setting by using char from ASCII like that: [ALT]+255. It is an invisible char. You can write as many chars as you wish in the tittle of the column and it will make it wider.


text:
Q: c++ .hpp and .cpp Can someone tell me what is the correct way to create a .hpp and .cpp that includes classes, subclasses and methods? Do I have to use export "C" firstClass* create_object { return new firstClass; }? (I am working in C++.) Should I have file.hpp or file.h?
#include <string>

//public ?? how can i have this?
class firstClass
{
public:
    firstClass();

    class secondClass
    {
    public:
        secondClass();
        std::string name;
        virtual std::string method1();
    } *sec;

    virtual void DoSomething();
} *first;

// And for a private class?

class private *priv;

in file.cpp
#include file.hpp
firstClass::firstClass()
{
    sec = new firstClass::secondClass();
}

std::string firstClass::secondClass::method1()
{
    //code
}

And now if I have to extern an object for each class/subclass? It is necessary if I want to create an .so file and use dlsym and dlopen to access classes, subclasses and methods, modify values, send a reference to a specific method? Thanks!
extern "C" firstClass* create_object()
{return new firstClass}
extern "C" secondClass* create_object()
{return new secondClass}

A: Whether you have file.hpp or file.h is just a matter of preference. Personally, I use .hpp to indicate C++ rather than C.
In C++, unlike for example Java, classes in the global namespace are not public or private. You can, however, hide or limit access to classes in various ways. For example:

*

*Having them private in another class.

*Using namespaces.

A few other points:

*

*The syntax for including file.hpp is #include "file.hpp"

*Your firstClass and secondClass classes have virtual methods and a default destructor. You should make your destructor public and virtual, or protected and non-virtual

*Classes are usually defined like this:

Class definition:
class SomeClass {
    // code
};

and when you want a pointer to it, you write SomeClass* myPointer;, rather than the way you declare first and sec.
You usually want to put class declarations and/or definitions in header files, along with function declarations. Implementations goes in the source files. Example:
// Header file:
class FirstClass {
public:
    FirstClass();
    void DoSomething();
};

// Source file:
FirstClass::FirstClass()
{
    // code
}

void FirstClass::DoSomething()
{
    // code
}

I'd recommend you to pick up a C++ textbook, where such basics are plentifully covered. My personal recommendation is Accelerated C++.


text:
Q: Rake db:seed is breaking my database I'm actually facing a big issue regarding the database migration and the seed of it.
I have a formes table which contain 2 fields, name and country_id. I recently needed to add a code field inot it, so I did :
class AddCodeToFormes < ActiveRecord::Migration
  def change
    add_column :formes, :code, :string
  end
end

So far so good, the migration pass with success using rake db:migrate. Then in my seeds file, I wanted to add the new column in order to fill in the new datas. Here is my file :
country = Country.create!( code: 'US', name: 'USA' )
Forme.delete_all
Forme.create!( name: '-', country_id: country.id, code: '-' )
Forme.create!( name: 'item 1', country_id: country.id, code: 'PARTICULIER' )
Forme.create!( name: 'item 2', country_id: country.id, code: 'PATENTE' )
Forme.create!( name: 'item 3', country_id: country.id, code: 'SARL' )
Forme.create!( name: 'item 4', country_id: country.id, code: 'EURL' )

Then, I ran rake db:seed as I did the first time for fill in the database. It's works without errors and the data are populated with success into the database.
But then, when I'm trying to access my application, I've got an error when trying to access associate data such as : @contact.forme.code
And then, when I recreate the database, it works like a charm. So what did I do wrong?
EDIT :
An information who might be useful, I don't know, is that my mysql database engine is InnoDB. As I said in my comments, there is no visible errors and the database looks fine but ActiveRecord can't anymore handle associations
EDIT 2 :
Without the code value in my seeds.rb, it works like a charm
EDIT 3 :
Rails actually give me an error when accessing the page : undefined method 'code' for nil:NilClass on @contact.forme.code

A: Ok so I finally make it works. I'm using :
rake db:setup

which drop the database, create tables and seed it. Now it works well. Apparently, we can't just use rake db:seed itself.
Thanks to everyone for your help

A: What if you don't use the country id, but refer to the country object itself when creating Forme?
country = Country.create!( code: 'US', name: 'USA' )
Forme.delete_all
Forme.create!( name: '-', country: country, code: '-' )

A: I always like using the tap method for seeds.rb. This works:
Country.create!( code: 'US', name: 'USA' ).tap do |country|
  Forme.delete_all
  Forme.create!( name: '-', country_id: country.id, code: '-' )
  Forme.create!( name: 'item 1', country_id: country.id, code: 'PARTICULIER' )
  Forme.create!( name: 'item 2', country_id: country.id, code: 'PATENTE' )
  Forme.create!( name: 'item 3', country_id: country.id, code: 'SARL' )
  Forme.create!( name: 'item 4', country_id: country.id, code: 'EURL' )
end

Once you're inside that block, the country object is available for use, so you can associate the 'forme' and the 'country'.


text:
Q: Translate with CSS to the top of a div I have 3 boxes within a fluid container.
Each box has a heading title, an icon and some text below.
On :hover I want the icon to move to the top of the
 and change it's size, I have managed to "achieve" it but using certain number of pixels.
That will not work in mobile resolutions if the title text is longer and takes 2 lines.
Here is what I have done so far:
Fiddle here
HTML

Title

Certain text below the icon

CSS
.container{
    text-align:center;
}

.market-blocks{
    background: #3aa0d1;
    padding: 30px 0 30px 0;
    cursor:pointer;
}

.orange{
  background: #e97d68;
}

i.market-icon {
   -webkit-transition: 1s ease-in;
    -moz-transition: 1s ease-in;
    -o-transition: 1s ease-in;
    transition: 1s ease-in
}

.market-blocks:hover i.market-icon {
    -webkit-transform: translate(0,-70px);
    -moz-transform: translate(0,-70px);
    -o-transform: translate(0,-70px);
    -ms-transform: translate(0,-70px);
    transform: translate(0,-70px);
    font-size: 1.8em;
}

How can I do it? And also is there a better way to do the movement from the initial position to the top of the
?

A: Pure HTML/CSS solution:

.container {
    text-align: center;
}

.market-blocks {
 background: #3aa0d1;
 padding: 30px 0;
 cursor: pointer;
}

.orange {
    background: #e97d68;
}

.service-box {
    display: inline-block;
}

.service-box-header {
    position: relative;
}

.market-title {
    padding-bottom: 5em;
    -webkit-transition: 1s ease-in;
    transition: 1s ease-in
}

.market-icon {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    -webkit-transition: 1s ease-in;
    transition: 1s ease-in
}

    .market-blocks:hover .market-title {
        padding-bottom: 0;
    }

    .market-blocks:hover .market-icon {
        bottom: 100%;
        font-size: 1.8em;
    }
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>

Very-very-very-very-very-very-very-very loooooooooooooooooooong title

Certain text below the icon


text:
Q: Why can't load the data into mysql: Mysql table price structure:
CREATE TABLE `price` (
  `code` varchar(12) ,
  `date` date ,
  `open` decimal(8,2) ,
  `high` decimal(8,2) ,
  `low` decimal(8,2) ,
  `close` decimal(8,2) ,
  `amount` decimal(20,2) ,
  `volume` decimal(16,2)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Here is the data.csv file which i want to load into tablbe price.
000046.XSHE,19940912,20.0,20.0,16.0,16.92,121262592.0,7043300
000046.XSHE,19940913,17.0,17.32,16.0,16.46,47195860.0,2810800
000046.XSHE,19940914,16.3,16.4,15.49,15.95,24762992.0,1558300

The max value for volume is 47195860.0 which is in the range of decimal(20,2).
Load it with mysql load command.
LOAD DATA local INFILE 'data.csv'
    INTO TABLE finance.price
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    lines terminated by '\r\n';

An error info occurs:
Query OK, 1 row affected, 1 warning (0.09 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 1

Show it to get the reason.
show warnings;
+---------+------+---------------------------------------------+
| Level   | Code | Message                                     |
+---------+------+---------------------------------------------+
| Warning | 1265 | Data truncated for column 'volume' at row 1 |
+---------+------+---------------------------------------------+
1 row in set (0.00 sec)

Number 121262592.0 is so lower than decimal(20,2),why  Data truncated for column 'volume' at row 1,only one row loaded.
select * from price;
+-------------+------------+-------+-------+-------+-------+--------------+------------+
| code        | date       | open  | high  | low   | close | amount       | volume     |
+-------------+------------+-------+-------+-------+-------+--------------+------------+
| 000046.XSHE | 1994-09-12 | 20.00 | 20.00 | 16.00 | 16.92 | 121262592.00 | 7043300.00 |
+-------------+------------+-------+-------+-------+-------+--------------+------------+
1 row in set (0.00 sec)

A: LOAD DATA local INFILE 'data.csv'
    INTO TABLE finance.price
    FIELDS TERMINATED BY ','
    OPTIONAL  ENCLOSED BY '"'
    lines terminated by '\r\n';