Q: How to set the browser name parameter in the protractor script I have started using protractor and now able to execute same test script on multiple browsers by doing below changes in protractor.conf.js file.
multiCapabilities: [{
'browserName': 'chrome'
}, {
'browserName': 'firefox'
}],

Now, I would like to parameterized my tests to provide browser name on which it should run. For e.g.: I have 2 test cases, 1 should run on chrome and other should run on firefox. This should be handled by providing browser name parameter in the test itself. Below is my first test case. Can you please help me to pass the browser name parameter in it.
'use strict';

/* https://github.com/angular/protractor/blob/master/docs/toc.md */

describe('Login and Logout Test Case', function () {

    //before Each unittests case load the login page
    beforeEach(function () {
        browser.get('#/login');
    });

    it('unittests the scenario when the user clicks on Dutch', function () {

        //The link for Dutch language from the login page is clicked

        element(by.id('username')).sendKeys('kaustubhsaxena');
        element(by.id('password')).sendKeys('saxena');

        element(by.id('login')).click();

        browser.quit();

     });
});

Thanks in advance for your help

A: To get the browser name, you can use browser.getCapabilities():
browser.getCapabilities().then(function(capabilities) {
    // Outputs 'chrome' when on Chrome
    console.log(capabilities.caps_.browserName);
});

If waiting until a promise is resolved isn't good for your use case, then a hackier way that works on my system is to access the resolved/fulfilled session object directly:
// Outputs 'chrome' when on Chrome
console.log(browser.driver.session_.value_.caps_.caps_.browserName);


Q: Decodable JSONDecoder handle different coding keys for the same value I'm using Swift decodable protocol to parse my JSON response:
{
    "ScanCode":"4122001131",
    "Name":"PINK",
    "attributes":{
            "type":"Product",
            "url":""
     },
    "ScanId":"0000000kfbdMA"
}

I'm running into an issue where sometimes I get the ScanId value with a key "Id" instead of "ScanId".
Is there a way to work around that?
Thanks

A: You have to write a custom initializer to handle the cases, for example
struct Thing : Decodable {
    let scanCode, name, scanId : String

    private enum CodingKeys: String, CodingKey { case scanCode = "ScanCode", name = "Name", ScanID, Id }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        scanCode = try container.decode(String.self, forKey: .scanCode)
        name = try container.decode(String.self, forKey: .name)
        if let id = try container.decodeIfPresent(String.self, forKey: .Id) {
            scanId = id
        } else {
            scanId = try container.decode(String.self, forKey: .ScanID)
        }
    }
}

First try to decode one key, if it fails decode the other.
For convenience I skipped the attributes key


Q: Return MongoDB result to an HTTP request I have a NodeJS route that looks like this:
app.get("/search/:query", (req, res, next) => {

    let obj = SearchText(req.params.query);

    res.status(200);
    res.json(obj);

});

which calls this function:
async function SearchText(query) {
    query = "Custom";
    let mongoPromise = new Promise((resolve, reject) => {
      MongoClient.connect(url,function(err, db) {
          if (err) throw err;
          var dbo = db.db("FunLibsTest");
          dbo.collection("texts").find({"name": { $regex: query }}).toArray(function(err, result) {
            if (err) reject(err);
            resolve(result);
            console.log(result);
            db.close();
        });
      });
    })

    let results = await mongoPromise;

    return results;
}

Expected result is whatever MongoDB finds, but it always returns "FAILED".
I do not believe MongoDB has a synchronous version of "find", but I want it to act synchronously so I can return the response to the HTTP request. How could I do this?

A: EDIT:
This code jumps around to a lot of places when we could just make it very linear.
function SearchText(query) {
    return new Promise((resolve, reject) => {
      MongoClient.connect(url, (err, db) => {
          if (err) throw err;
          var dbo = db.db("FunLibsTest");
          dbo.collection("texts").find(query).toArray((err, result) => {
            if (err) reject(err);
            db.close();
            resolve(result);
        });
      });
    })
}

Then to use the function
app.get("/search/:query", (req, res, next) => {

    SearchText(req.params.query).then((results) => {
        res.status(200);
        res.json(results);
    });

});


Q: Can a single solution hold projects from multiple repositories? I've begun setting up SVN repositories to store my code, and am wondering if a single Visual Studio solution can have projects from multiple repositories. I have a shared library with different helper functions, generic custom controls, etc, that are used by multiple projects, and hosted in its own repository. Then I have my project repository, which contains all of the program-specific code such as forms, etc. I know I could copy the shared library into the program's repository, then copy them back when I make changes, but I'd much rather keep them in different repositories so I can hit "Commit" and the general library commits to it's repository, and the program code commits to it. I'm currently using AnkhSVN, but if it's possible with other tools, I'll look into it.

Preemptive clarification for all the "just use one repository" answers: The shared library is hosted in an online repository, viewable by anyone, but the program code is proprietary and resides on our office servers, so they need different repositories.

A: Yes it can, though you'll only be able to commit to projects from one repository at a time. One way of achieving this and making it reproducible by any developer who checks out your project is to use the svn:externals property on your solution's root folder to pull in projects from other repositories.
To edit or add this property, you can either use the svn command line, or TortoiseSVN. You'll find more details on the svn:externals property itself in the Subversion red book.

A: Like David says this is possible.
I would like to add to this that having multiple repositories not only takes away the ability to atomically commit, but also you won't be able to branch/tag the project and its dependencies into a single tag or branch. I wouldn't recommend using multiple repositories for these reasons.


Q: Infinite dimensional manifold In Hamiltonian mechanics, one essentially work with $\mathbb{R}^{2n}$. However, this is only a local description of our configuration manifold $M$. More precisely, the mechanical system is regarded as $(M, \omega)$ where $\omega$ is a sympathetic form on $M$ corresponding to the Poisson bracket. Given a Hamiltonian $H$, its flow is the trajectory of our particle with initial conditions. Now, in local coordinates, we can write
$$
  \vec{z} = P_t \vec{z}(0) \quad (1)
$$
where $P_t$ is the flow evaluated at $\vec{z}(0)$, which is the propagator. Note that there is a differential equation that (1) also satisfies. In particular, just differentiate both side by $t$, then we get an ODE which we can solve the flow $P_t$ if we only know the Hamiltonian vector field. Now, in quantum mechanics, I learned from class that we obtain an similar equation that looks like
$$
  | \psi \rangle = U_t | \psi_0 \rangle \quad (2)
$$
where $U_t$ is unitary and satisfies $U_{t+s} = U_tU_s$ for all $s,t$ defined. And (2) also satisfies a differential equation similar to that of (1). So my understanding is that every thing we did in my quantum class is just a local theory. My intuition tells me that globally, one which to have some configuration space $N$ that is in some sense "diffeomorphic" to the projective space of $l^2(\mathbb{N})$ locally. And the manifold we want to work with is $M:=TN$ whatever $TN$ means in this case. Then our states are just point on $M$, with Hamiltonian defined over $M$ to $\mathbb{R}$. And $U_t$ would be a Hamiltonian flow. \
However, anything that goes infinite dimensional can go crazy. So I am looking for a global picture of quantum mechanics. In particular, a definition for

*

*What does smoothness mean (or even differentability) for $f: l^2(\mathbb{N}) \rightarrow \mathbb{R}$ or $l^2(\mathbb{N})$.

*definition of locally $l^2(\mathbb{N})$ manifold

*explaination/theorem on the global picture of quantum mechanics.

*Or perhaps none of that makes any sense whatsoever, then what should I be looking into?

Thanks tonnes!

A: Have a look at section 48 of:
Andreas Kriegl, Peter W. Michor: The Convenient Setting of Global Analysis. Mathematical Surveys and Monographs, Volume: 53, American Mathematical Society, Providence, 1997,
(pdf).
There is a mistake there that I did not yet correct online.

A: As far as the QM goes, I don't know enough to really say, but books like Quantum Mechanics for Mathematicians would give a mathematical overview of the large pieces of QM. However, infinite dimensional manifolds are out there in the literature. A quick googling brought up what looks like a good place to is arXiv:math/9202206. This paper is appears to be a 20 year old survey of infinite dimensional manifolds. For something a tad more recent and superficial you can try the wiki article on Banach manifolds which does not have many references but it will provide you with the keywords to do more googling.
EDIT: As mentioned by Kofi, what you need to extend the definition of a smooth manifold to an infinite dimensional setting is a notion of a derivative in an infinite dimensional setting. There is one that goes by the name of ``Frechet derivative.'' Using this derivative you just start mimicking finite dimensional spaces. For QM you will probably only ever need the Hilbert manifold case (locally diffeomorphic to a Hilbert space) and not the more general Banach or Frechet spaces but the idea for those is that as long as a notion of derivative is available you can define a smooth structure.


Q: Add Up/Down buttons to UITableView navigation bar Many apps, including Apple's own native Mail.app on the iPhone implement an Up/Down button in the detail view which allows for quick and easy browsing. I wish to create such an interface in my own app, but am struggling to do so. So far I've setup a segmented control which links to an action in my navigation bar, but I'm struggling with what to put in the action to make the detail view for the table update when the user presses the "Up" button or "Down" button to navigate to the item before or after the current one.
Any help would be appreciated. Thanks.

A: It depends on how you have your data set up, but why can't you hook into your existing code? What are you doing in your existing code to refresh the detail view when a user selects a row in master view table? Can't you just call that method directly?
It's hard to give specific advice without more detailed information on your current design.


Q: Fabric UI Checkbox Label Alignment I'm trying to add a checkbox to an Excel Add-In task pane but even when using a straight copy and paste of the sample code from the MS site, the label for the checkbox is on the line below. How do I make this so that the text is on the same line as the Check Box?

  <input tabindex="-1" type="checkbox" class="ms-CheckBox-input">

    Checkbox

The task pane is plenty wide enough but the labels always appear on the line below.

A: Set a CSS property for .ms-Checkbox where display: flex; This will default to a row layout which will make the children of .ms-Checkbox to be displayed inline.

.ms-CheckBox {
  display: flex;
}
<link href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/css/fabric.components.min.css" rel="stylesheet"/>
<link href="https://static2.sharepointonline.com/files/fabric/office-ui-fabric-js/1.4.0/css/fabric.min.css" rel="stylesheet"/>

  <input tabindex="-1" type="checkbox" class="ms-CheckBox-input">

    Checkbox


Q: How to invert these matrix via Gauss method? Im trying to find the inverse matrix based on
$\left[\begin{array}{ccc}
2 & 2 & -1\\
0 & 4 & -1\\
-1 & -2 & 1
\end{array}\right]$
$R_{1}=$ First row
$R_{2}=$ Second row
$R_{3}=$Third row
but at a certain step I can't reduce it further. Which must be the next operation?
$\left[\begin{array}{ccc}
2 & 2 & -1\\
0 & 4 & -1\\
-1 & -2 & 1
\end{array}\mid\begin{array}{ccc}
1 & 0 & 0\\
0 & 1 & 0\\
0 & 0 & 1
\end{array}\right]$ $\rightarrow\frac{R_{1}}{2}$
$\left[\begin{array}{ccc}
1 & 1 & \frac{-1}{2}\\
0 & 4 & -1\\
-1 & -2 & 1
\end{array}\mid\begin{array}{ccc}
\frac{1}{2} & 0 & 0\\
0 & 1 & 0\\
0 & 0 & 1
\end{array}\right]$ $\rightarrow R_{3}+R_{1}$
$\left[\begin{array}{ccc}
1 & 1 & \frac{-1}{2}\\
0 & 4 & -1\\
0 & -1 & \frac{1}{2}
\end{array}\mid\begin{array}{ccc}
\frac{1}{2} & 0 & 0\\
0 & 1 & 0\\
\frac{1}{2} & 0 & 1
\end{array}\right]$$\rightarrow\frac{R_{2}}{4}$
$\left[\begin{array}{ccc}
1 & 1 & \frac{-1}{2}\\
0 & 1 & \frac{-1}{4}\\
0 & -1 & \frac{1}{2}
\end{array}\mid\begin{array}{ccc}
\frac{1}{2} & 0 & 0\\
0 & \frac{1}{4} & 0\\
\frac{1}{2} & 0 & 1
\end{array}\right]$$\rightarrow R_{1}-R_{2}$
$\left[\begin{array}{ccc}
1 & 0 & \frac{-1}{4}\\
0 & 1 & \frac{-1}{4}\\
0 & -1 & \frac{1}{2}
\end{array}\mid\begin{array}{ccc}
\frac{1}{2} & -\frac{1}{4} & 0\\
0 & \frac{1}{4} & 0\\
\frac{1}{2} & 0 & 1
\end{array}\right]$$\rightarrow R_{3}+R_{2}$
$\left[\begin{array}{ccc}
1 & 0 & \frac{-1}{4}\\
0 & 1 & \frac{-1}{4}\\
0 & 0 & \frac{1}{4}
\end{array}\mid\begin{array}{ccc}
\frac{1}{2} & -\frac{1}{4} & 0\\
0 & \frac{1}{4} & 0\\
\frac{1}{2} & \frac{1}{4} & 1
\end{array}\right]$$\rightarrow4R_{3}$
$\left[\begin{array}{ccc}
1 & 0 & \frac{-1}{4}\\
0 & 1 & \frac{-1}{4}\\
0 & 0 & 1
\end{array}\mid\begin{array}{ccc}
\frac{1}{2} & -\frac{1}{4} & 0\\
0 & \frac{1}{4} & 0\\
2 & 1 & 4
\end{array}\right]$$\rightarrow?$

A: Continuing with $R_{1}\rightarrow R_{1}+\frac{1}{4}R_3$ and $R_{2}\rightarrow R_{2}+\frac{1}{4}R_{3}$ we have
$$\left[\begin{array}{ccc}
1 & 0 & 0\\
0 & 1 & 0\\
0 & 0 & 1
\end{array}\mid\begin{array}{ccc}
1 & 0 & 1\\
\frac{1}{2} & \frac{1}{2} & 1\\
2 & 1 & 4
\end{array}\right]$$


Q: Code signing certificate has to be imported from Java console to view Publisher correctly and avoid signature error We have purchased a code signing certificate, and I have signed an Applet jar with this certificate, using the jarsigner command and certificate in .pfx format. But when the applet is loaded in the browser, it shows the "Publisher Unknown" and "digital signature could not be verified" error.If I import the certificate from Java Control Panel -> Security -> Certificates -> Signer CA, the Publisher starts showing up correctly and "Digital signature is verified" message appears.
My question is that as we are signing the jar with a trusted certificate, then why do I have to still import the certificate to see correct results? Shouldn't it show the Publisher correctly/verify signature correctly , even without having to import it?

A: My issue got resolved.
There was a problem in the certificate (in .pfx format) that I was using to sign the jar.
When this certificate was generated from the site of the CA, the checkbox of "Include All Certificates in the path", was not selected. As a result the certificate did not have the complete chain required for signature verification in the applet jar.
The following command can be used to display the details of the certificates in a .pfx file
openssl pkcs12 -in <pfx_file_name>.pfx  -nodes
The certificate that had an issue, had only 1 certificate listed; while the one generated later had the complete chain of 3 certificates.


Q: como hacer para que se obtengan mas rapido los datos? Buen dia.
Tengo el siguiente Query el cual para obtener los datos que se requieren dura 25 minutos y quiero saber si hay alguna manera de hacerlo que dure menos en obtener los datos.
El Query es:
 SELECT   max(b.DateBonePile) Dates
                           FROM            STRGD12.SSS.[dbo].UdtBonepileTrend b
                           WHERE          b.Project = 'LUCENT FAD' and b.DateBonePile >= getdate() - 90
                           GROUP BY cast(b.DateBonePile AS date)

Cuando no filtro por el proyecto, query dura 7 segundos, pero cuando se filtra el proyecto es cuando dura 25 minutos.
Los campos de la tabla son los siguientes:
 CREATE TABLE [dbo].[UdtBonepileTrend](
[Site] [varchar](9) NOT NULL,
[Project] [char](15) NOT NULL,
[ProductionOrderNumber] [char](20) NOT NULL,
[PartNumber] [char](37) NOT NULL,
[RevisionNbr] [char](20) NOT NULL,
[SerialNumber] [char](25) NOT NULL,
[CreationTime] [datetime] NULL,
[CreationAging] [int] NULL,
[FirstScanTime] [datetime] NULL,
[FirstScanAging] [int] NULL,
[FirstScanStation] [varchar](14) NOT NULL,
[Last Station/Work Center] [char](10) NOT NULL,
[Unit State] [varchar](4) NOT NULL,
[Unit Status] [varchar](10) NOT NULL,
[Last Update] [datetime] NOT NULL,
[Last Update Aging] [int] NULL,
[Total Visit Repair] [int] NULL,
[Looper Count] [int] NULL,
[Last Looper Count Date] [datetime] NULL,
[Last Looper Count Aging] [int] NULL,
[PeriodLastUpdate] [varchar](36) NULL,
[WipDaysException] [int] NULL,
[ExceptionDescription] [varchar](500) NULL,
[sysWCID] [int] NOT NULL,
[LastFail] [datetime] NOT NULL,
[LastFailAging] [int] NOT NULL,
[Flag] [varchar](76) NOT NULL,
[PassDate] [datetime] NULL,
[FailDate] [datetime] NULL,
[isPass] [int] NOT NULL,
[BonePileCriteria] [varchar](44) NULL,
[ContainerID] [dbo].[BarCode_type] NULL,
[Parent Serial Number] [varchar](1) NOT NULL,
[Parent Status] [varchar](1) NOT NULL,
[CreationTime_format] [nvarchar](30) NULL,
[Last Update_format] [nvarchar](30) NULL,
[FirstScanTime_format] [nvarchar](30) NULL,
[Last Looper Count Date Format] [nvarchar](30) NULL,
[StandardCost] [float] NULL,
[period] [int] NULL,
[strike] [int] NULL,
[DateBonePile] [datetime] NULL,
[ReportType] [varchar](8) NOT NULL
)

Los datos que contiene la tabla son los siguientes:

El sql que utilizo es:

Espero me puedan ayudar.


Q: Edge detection on colored background using OpenCV I am using following code to detect edges from given document.
private Mat edgeDetection(Mat src) {
    Mat edges = new Mat();
    Imgproc.cvtColor(src, edges, Imgproc.COLOR_BGR2GRAY);
    Imgproc.GaussianBlur(edges, edges, new Size(5, 5), 0);
    Imgproc.Canny(edges, edges, 10, 30);
    return edges;
}

And then I can find the document from this edges by finding largest contour from this.
My problem is I can find the document from following pic:

but not from following pic:

How can I improve this edge detection?

A: I use Python, but the main idea is the same.
If you directly do cvtColor: bgr -> gray for img2, then you must fail. Because the gray becames difficulty to distinguish the regions:

Related answers:

*

*How to detect colored patches in an image using OpenCV?

*Edge detection on colored background using OpenCV

*OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

In your image, the paper is white, while the background is colored. So, it's better to detect the paper is Saturation(饱和度) channel in HSV color space.  For HSV, refer to https://en.wikipedia.org/wiki/HSL_and_HSV#Saturation.

Main steps:

*

*Read into BGR

*Convert the image from bgr to hsv space

*Threshold the S channel

*Then find the max external contour(or do Canny, or HoughLines as you like, I choose findContours), approx to get the corners.

This is the first result:

This is the second result:

The Python code(Python 3.5 + OpenCV 3.3):
#!/usr/bin/python3
# 2017.12.20 10:47:28 CST
# 2017.12.20 11:29:30 CST

import cv2
import numpy as np

##(1) read into  bgr-space
img = cv2.imread("test2.jpg")

##(2) convert to hsv-space, then split the channels
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)

##(3) threshold the S channel using adaptive method(`THRESH_OTSU`) or fixed thresh
th, threshed = cv2.threshold(s, 50, 255, cv2.THRESH_BINARY_INV)

##(4) find all the external contours on the threshed S
cnts = cv2.findContours(threshed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
canvas  = img.copy()
#cv2.drawContours(canvas, cnts, -1, (0,255,0), 1)

## sort and choose the largest contour
cnts = sorted(cnts, key = cv2.contourArea)
cnt = cnts[-1]

## approx the contour, so the get the corner points
arclen = cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, 0.02* arclen, True)
cv2.drawContours(canvas, [cnt], -1, (255,0,0), 1, cv2.LINE_AA)
cv2.drawContours(canvas, [approx], -1, (0, 0, 255), 1, cv2.LINE_AA)

## Ok, you can see the result as tag(6)
cv2.imwrite("detected.png", canvas)

A: In OpenCV there is function called dilate this will darker the lines. so try the code like below.
private Mat edgeDetection(Mat src) {
    Mat edges = new Mat();
    Imgproc.cvtColor(src, edges, Imgproc.COLOR_BGR2GRAY);
    Imgproc.dilate(edges, edges, Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(10, 10)));
    Imgproc.GaussianBlur(edges, edges, new Size(5, 5), 0);
    Imgproc.Canny(edges, edges, 15, 15 * 3);
    return edges;
}


Q: sort string with delimiter as string in unix I have some data in the following format::
Info-programNumber!/TvSource/11100001_233a_32c0/13130^Info-channelName!5 USA^Info-Duration!1575190^Info-programName!CSI: ab cd

Delimiter = Info-

I tried to sort the string based on the delimiter in ascending order. But none of my solutions are working.
Expected Result:
Info-channelName!5 USA^Info-Duration!1575190^Info-programName!CSI: ab cd^Info-programNumber!/TvSource/11100001_233a_32c0/13130

Is there any command that will allow me to do this or do i need to write an awk script to iterate over the string and sort it?

A: Temporarily split the info into multiple lines so you can sort:
tr ^ \\n | sort | tr \\n ^

Note: if you have multiple entries, you have to write a loop, which processes it per line.. with huge datasets this is probably not a good idea (too slow), in which case pick a programming language.. but you were asking about the shell...

A: Can be done in awk itself:
awk -F "^" '{OFS="^"; for (i=1; i<=NF; i++) a[i]=$i}
          END {n=asort(a, b); for(i=1; i<=n; i++) printf("%s%s", b[i], FS); print ""}' file


Q: Format date and time in a Windows batch script In a Windows (Windows XP) batch script I need to format the current date and time for later use in files names, etc.
It is similar to Stack Overflow question How to append a date in batch files, but with time in as well.
I have this so far:
echo %DATE%
echo %TIME%
set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__%time:~0,2%_%time:~3,2%_%time:~6,2%
echo %datetimef%

which gives:
28/07/2009
 8:35:31.01
2009_07_28__ 8_36_01

Is there a way I can allow for a single digit hour in %TIME%, so I can get the following?
2009_07_28__08_36_01

A: The following may not be a direct answer but a close one?
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__0%time:~1,2%_%time:~3,2%_%time:~6,2%
else set datetimef=%date:~-4%_%date:~3,2%_%date:~0,2%__%time:~0,2%_%time:~3,2%_%time:~6,2%

At least it may be inspiring.

A: REM Assumes UK style date format for date environment variable (DD/MM/YYYY).
REM Assumes times before 10:00:00 (10am) displayed padded with a space instead of a zero.
REM If first character of time is a space (less than 1) then set DATETIME to:
REM YYYY-MM-DD-0h-mm-ss
REM Otherwise, set DATETIME to:
REM YYYY-MM-DD-HH-mm-ss
REM Year, month, day format provides better filename sorting (otherwise, days grouped
REM together when sorted alphabetically).

IF "%time:~0,1%" LSS "1" (
   SET DATETIME=%date:~6,4%-%date:~3,2%-%date:~0,2%-0%time:~1,1%-%time:~3,2%-%time:~6,2%
) ELSE (
   SET DATETIME=%date:~6,4%-%date:~3,2%-%date:~0,2%-%time:~0,2%-%time:~3,2%-%time:~6,2%
)

ECHO %DATETIME%

A: I usually do it this way whenever I need a date/time string:
set dt=%DATE:~6,4%_%DATE:~3,2%_%DATE:~0,2%__%TIME:~0,2%_%TIME:~3,2%_%TIME:~6,2%
set dt=%dt: =0%

This is for the German date/time format (dd.mm.yyyy hh:mm:ss). Basically I concatenate the substrings and finally replace all spaces with zeros.
The resulting string has the format: yyyy_mm_dd__hh_mm_ss

Short explanation of how substrings work:
%VARIABLE:~num_chars_to_skip,num_chars_to_keep%

So to get just the year from a date like "29.03.2018" use:
%DATE:~6,4%
       ^-----skip 6 characters
         ^---keep 4 characters

A: Here is how I generate a log filename (based on http://ss64.com/nt/syntax-getdate.html):
@ECHO OFF
:: Check WMIC is available
WMIC.EXE Alias /? >NUL 2>&1 || GOTO s_error

:: Use WMIC to retrieve date and time
FOR /F "skip=1 tokens=1-6" %%G IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
   IF "%%~L"=="" goto s_done
      Set _yyyy=%%L
      Set _mm=00%%J
      Set _dd=00%%G
      Set _hour=00%%H
      SET _minute=00%%I
      SET _second=00%%K
)
:s_done

:: Pad digits with leading zeros
      Set _mm=%_mm:~-2%
      Set _dd=%_dd:~-2%
      Set _hour=%_hour:~-2%
      Set _minute=%_minute:~-2%
      Set _second=%_second:~-2%

Set logtimestamp=%_yyyy%-%_mm%-%_dd%_%_hour%_%_minute%_%_second%
goto make_dump

:s_error
echo WMIC is not available, using default log filename
Set logtimestamp=_

:make_dump
set FILENAME=database_dump_%logtimestamp%.sql
...

A: @ECHO OFF
: Sets the proper date and time stamp with 24Hr Time for log file naming
: convention ('YYYYMMDD_HHMMSS')

: Scrapes the characters out of their expected permissions in the date/time
: environment variables.

: Expects a date format of '____MM_DD_YYYY'
: Expects a time format of 'HH:MM:SS' or ' H:MM:SS'

SET HOUR=%time:~0,2%
SET dtStamp9=%date:~-4%%date:~4,2%%date:~7,2%_0%time:~1,1%%time:~3,2%%time:~6,2%
SET dtStamp24=%date:~-4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%

if "%HOUR:~0,1%" == " " (SET dtStamp=%dtStamp9%) else (SET dtStamp=%dtStamp24%)

ECHO %dtStamp%

PAUSE

A: The offset:length formatting supported with the SET command in Windows will not allow you to pad the 0 as you seem to be interested in.
However, you can code a BATCH script to check for the hour being less than 10 and
pad accordingly with a different echo string.
You will find some information on the SET command on this link.

You can also change to other programming methods to get here.
It is quite simple in unix bash (available with Cygwin on Windows) to just say,
date +%Y_%m_%d__%H_%M_%S

And, it always pads correctly.

A: I did it this way:
REM Generate FileName from date and time in format YYYYMMTTHHMM

Time /T > Time.dat
set /P ftime= < Time.dat

set FileName=LogFile%date:~6%%date:~3,2%%date:~0,2%%ftime:~0,2%%ftime:~3,2%.log

echo %FileName%

LogFile201310170928.log

A: I'm really new to batch files and this is my code!! (I am not sure why, but I couldn't combine date /t and time /t together and I couldn't use %date% and %time% directly without a variable...)
@ECHO OFF
set ldt=%date% %time%
echo %ldt%>> logs.txt
EXIT

It is kind of reused from others (the question was to get a formatted timedate to use as filename).

A: ::========================================================================
::== CREATE UNIQUE DATETIME STRING IN FORMAT YYYYMMDD-HHMMSS
::======= ================================================================
FOR /f %%a IN ('WMIC OS GET LocalDateTime ^| FIND "."') DO SET DTS=%%a
SET DATETIME=%DTS:~0,8%-%DTS:~8,6%

The first line always outputs in this format regardles of timezone:
20150515150941.077000+120
This leaves you with just formatting the output to fit your wishes.

A: If PowerShell is installed, then you can easily and reliably get the Date/Time in any format you'd like, for example:
for /f %%a in ('powershell -Command "Get-Date -format yyyy_MM_dd__HH_mm_ss"') do set datetime=%%a
move "%oldfile%" "backup-%datetime%"

Of course nowadays PowerShell is always installed, but on Windows XP you'll probably only want to use this technique if your batch script is being used in a known environment where you know PS is available (or check in your batch file if PowerShell is available...)
You may reasonably ask: why use a batch file at all if you can use PowerShell to get the date/time, but  I think some obvious reasons are: (a) you're not all that familiar with PowerShell and still prefer to do most things the old-fashioned way with batch files or (b) you're updating an old script and don't want to port the whole thing to PS.

A: This batch script will do exactly what the O.P. wants (tested on Windows XP SP3).
I also used that clever registry trick described by "jph" previously which IMHO is the simplest way of getting 100% consistent formatting of the date to "yyyy_MM_dd" on any Windows system new or old. The change to one Registry value for doing this is instantaneous temporary and trivial; it only lasts a few milliseconds before it is immediately reverted back.
Double-click this batch file for an instant demo, Command Prompt window will pop up and display your timestamp . . . . .
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: generates a custom formatted timestamp string using date and time.
:: run this batch file for an instant demo.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

@ECHO OFF
SETLOCAL & MODE CON:COLS=80 LINES=15 & COLOR 0A

:: --- CHANGE THE COMPUTER DATE FORMAT TEMPORARILY TO MY PREFERENCE "yyyy_MM_dd",
REG COPY "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f 2>nul >nul
REG ADD "HKCU\Control Panel\International" /v sShortDate /d "yyyy_MM_dd" /f 2>nul >nul

SET MYDATE=%date%

:: --- REVERT COMPUTER DATE BACK TO SYSTEM PREFERENCE
REG COPY "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f 2>nul >nul
REG DELETE "HKCU\Control Panel\International-Temp" /f 2>nul >nul

:: --- SPLIT THE TIME [HH:MM:SS.SS] TO THREE SEPARATE VARIABLES [HH] [MM] [SS.SS]
FOR /F "tokens=1-3 delims=:" %%A IN ('echo %time%') DO (
SET HOUR=%%A
SET MINUTES=%%B
SET SECONDS=%%C
)

:: --- CHOOSE ONE OF THESE TWO OPTIONS :
:: --- FOR 4 DIGIT SECONDS        //REMOVES THE DOT FROM THE SECONDS VARIABLE [SS.SS]
:: SET SECONDS=%SECONDS:.=%
:: --- FOR 2 DIGIT SECONDS        //GETS THE FIRST TWO DIGITS FROM THE SECONDS VARIABLE [SS.SS]
SET SECONDS=%SECONDS:~0,2%

:: --- FROM 12 AM TO 9 AM, THE HOUR VARIABLE WE EXTRACTED FROM %TIME% RETURNS A SINGLE DIGIT,
:: --- WE PREFIX A ZERO CHARACTER TO THOSE CASES, SO THAT OUR WANTED TIMESTAMP
:: --- ALWAYS GENERATES DOUBLE-DIGIT HOURS (24-HOUR CLOCK TIME SYSTEM).
IF %HOUR%==0 (SET HOUR=00)
IF %HOUR%==1 (SET HOUR=01)
IF %HOUR%==2 (SET HOUR=02)
IF %HOUR%==3 (SET HOUR=03)
IF %HOUR%==4 (SET HOUR=04)
IF %HOUR%==5 (SET HOUR=05)
IF %HOUR%==6 (SET HOUR=06)
IF %HOUR%==7 (SET HOUR=07)
IF %HOUR%==8 (SET HOUR=08)
IF %HOUR%==9 (SET HOUR=09)

:: --- GENERATE OUR WANTED TIMESTAMP
SET TIMESTAMP=%MYDATE%__%HOUR%_%MINUTES%_%SECONDS%

:: --- VIEW THE RESULT IN THE CONSOLE SCREEN
ECHO.
ECHO    Generate a custom formatted timestamp string using date and time.
ECHO.
ECHO    Your timestamp is:    %TIMESTAMP%
ECHO.
ECHO.
ECHO    Job is done. Press any key to exit . . .
PAUSE > NUL

EXIT

A: There is another easy way of doing it:
set HH=%time:~0,2%
if %HH% LEQ 9 (
set HH=%time:~1,1%
)

A: This bat file (save as datetimestr.bat) produces the datetime string 3 times: (1) long datetime string with day of week and seconds,
(2) short datetime string without them and
(3) short version of the code.
@echo off
REM "%date: =0%" replaces spaces with zeros
set d=%date: =0%
REM "set yyyy=%d:~-4%" pulls the last 4 characters
set yyyy=%d:~-4%
set mm=%d:~4,2%
set dd=%d:~7,2%
set dow=%d:~0,3%
set d=%yyyy%-%mm%-%dd%_%dow%

set t=%TIME: =0%
REM "%t::=%" removes semi-colons
REM Instead of above, you could use "%t::=-%" to
REM replace semi-colons with hyphens (or any
REM non-special character)
set t=%t::=%
set t=%t:.=%

set datetimestr=%d%_%t%
@echo  Long date time str = %datetimestr%

set d=%d:~0,10%
set t=%t:~0,4%
set datetimestr=%d%_%t%
@echo Short date time str = %datetimestr%

@REM Short version of the code above
set d=%date: =0%
set t=%TIME: =0%
set datetimestr=%d:~-4%-%d:~4,2%-%d:~7,2%_%d:~0,3%_%t:~0,2%%t:~3,2%%t:~6,2%%t:~9,2%
@echo Datetimestr = %datetimestr%

pause

To give proper credit, I merged the concepts from Peter Mortensen (Jun 18 '14 at 21:02) and opello (Aug 25 '11 at 14:27).
You can write this much shorter, but this long version makes reading and understanding the code easy.

A: I came across this problem today and solved it with:
SET LOGTIME=%TIME: =0%

It replaces spaces with 0s and basically zero-pads the hour.
After some quick searching I didn't find out if it required command extensions (still worked with SETLOCAL DISABLEEXTENSIONS).

A: To generate a YYYY-MM-DD hh:mm:ss (24-hour) timestamp I use:
SET CURRENTTIME=%TIME%
IF "%CURRENTTIME:~0,1%"==" " (SET CURRENTTIME=0%CURRENTTIME:~1%)
FOR /F "tokens=2-4 delims=/ " %%A IN ('DATE /T') DO (SET TIMESTAMP=%%C-%%A-%%B %CURRENTTIME%)

A: I like the short version on top of @The lorax,
but for other language settings it might be slightly different.
For example, in german language settings (with natural date format: dd.mm.yyyy) the month query has to be altered from 4,2 to 3,2:
@ECHO OFF
: Sets the proper date and time stamp with 24h time for log file naming convention i.e.

SET HOUR=%time:~0,2%
SET dtStamp9=%date:~-4%%date:~3,2%%date:~7,2%_0%time:~1,1%%time:~3,2%%time:~6,2%
SET dtStamp24=%date:~-4%%date:~3,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%

if "%HOUR:~0,1%" == " " (SET dtStamp=%dtStamp9%) else (SET dtStamp=%dtStamp24%)

ECHO %dtStamp%
: Outputs= 20160727_081040
: (format: YYYYMMDD_HHmmss; e.g.: the date-output of this post timestamp)

PAUSE

A: As has been noted, parsing the date and time is only useful if you know the format being used by the current user (for example, MM/dd/yy or dd-MM-yyyy just to name two). This could be determined, but by the time you do all the stressing and parsing, you will still end up with some situation where there is an unexpected format used, and more tweaks will be be necessary.
You can also use some external program that will return a date slug in your preferred format, but that has disadvantages of needing to distribute the utility program with your script/batch.
There are also batch tricks using the CMOS clock in a pretty raw way, but that is tooo close to bare wires for most people, and also not always the preferred place to retrieve the date/time.
Below is a solution that avoids the above problems. Yes, it introduces some other issues, but for my purposes I found this to be the easiest, clearest, most portable solution for creating a datestamp in .bat files for modern Windows systems. This is just an example, but I think you will see how to modify for other date and/or time formats, etc.
reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f
reg add "HKCU\Control Panel\International" /v sShortDate /d "yyMMdd" /f
@REM reg query "HKCU\Control Panel\International" /v sShortDate
set LogDate=%date%
reg copy "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f

A: This is my 2 cents for adatetime string. On MM DD YYYY systems switch the first and second %DATE:~ entries.
    REM ====================================================================================
    REM CREATE UNIQUE DATETIME STRING FOR ADDING TO FILENAME
    REM ====================================================================================
    REM Can handle dd DDxMMxYYYY and DDxMMxYYYY > CREATES YYYYMMDDHHMMSS (x= any character)
    REM ====================================================================================
    REM CHECK for SHORTDATE dd DDxMMxYYYY
    IF "%DATE:~0,1%" GTR "3" (
        SET DATETIME=%DATE:~9,4%%DATE:~6,2%%DATE:~3,2%%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%
    ) ELSE (
    REM ASSUMES SHORTDATE DDxMMxYYYY
        SET DATETIME=%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%%TIME:~0,2%%TIME:~3,2%%TIME:~6,2%
        )
    REM CORRECT FOR HOURS BELOW 10
    IF %DATETIME:~8,2% LSS 10 SET DATETIME=%DATETIME:~0,8%0%DATETIME:~9,5%
    ECHO %DATETIME%

A: set hourstr = %time:~0,2%
if "%time:~0,1%"==" " (set hourstr=0%time:~1,1%)
set datetimestr=%date:~0,4%%date:~5,2%%date:~8,2%-%hourstr%%time:~3,2%%time:~6,2%

A: Create a file called "search_files.bat" and place the contents below into the file.  Then double click it.  The temporary %THH% variable was put in place to handle the AM appropriately.  If there is a 0 in the first 2 digits of the time, Windows ignores the rest of the file name of the LOG file.
CD .
SET THH=%time:~0,2%
SET THH=%THH: =0%
dir /s /b *.* > %date:~10,4%-%date:~4,2%-%date:~7,2%@%THH%.%time:~3,2%.%time:~6,2%.LOG

A: You may use these...
Parameters:
%date:~4,2% -- month
%date:~7,2% -- days
%date:~10,4% -- years

%time:~1,1% -- hours
%time:~3,2% -- minutes
%time:~6,2% -- seconds
%time:~9,2% -- mili-seconds

%date:~4,2%%date:~7,2%%date:~10,4% : MMDDYYYY
%date:~7,2%%date:~4,2%%date:~10,4% : DDMMYYYY
%date:~10,4%%date:~4,2%%date:~7,2% : YYYYMMDD

A: I ended up with this script:
set hour=%time:~0,2%
if "%hour:~0,1%" == " " set hour=0%hour:~1,1%
echo hour=%hour%
set min=%time:~3,2%
if "%min:~0,1%" == " " set min=0%min:~1,1%
echo min=%min%
set secs=%time:~6,2%
if "%secs:~0,1%" == " " set secs=0%secs:~1,1%
echo secs=%secs%

set year=%date:~-4%
echo year=%year%

:: On WIN2008R2 e.g. I needed to make your 'set month=%date:~3,2%' like below ::otherwise 00 appears for MONTH
set month=%date:~4,2%
if "%month:~0,1%" == " " set month=0%month:~1,1%
echo month=%month%
set day=%date:~0,2%
if "%day:~0,1%" == " " set day=0%day:~1,1%
echo day=%day%

set datetimef=%year%%month%%day%_%hour%%min%%secs%

echo datetimef=%datetimef%

A: If you don't exactly need this format:
2009_07_28__08_36_01

Then you could use the following 3 lines of code which uses %date% and %time%:
set mydate=%date:/=%
set mytime=%time::=%
set mytimestamp=%mydate: =_%_%mytime:.=_%

Note: The characters / and : are removed and the character . and space is replaced with an underscore.
Example output (taken Wednesday 8/5/15 at 12:49 PM with 50 seconds and 93 milliseconds):
echo %mytimestamp%
Wed_08052015_124950_93

A: I tried the accepted answer and it works pretty well.  Unfortunately the US Time Format appears to be H:MM:SS.CS, and the missing 0 on the front was causing parsing problems before 10 am.  To get over this hurdle and also allow parsing of most any of the world time formats, I came up with this simple routine that appears to work quite well.
:ParseTime
rem The format of %%TIME%% is H:MM:SS.CS or (HH:MM:SS,CS) for example 0:01:23.45 or 23:59:59,99
FOR /F "tokens=1,2,3,4 delims=:.," %%a IN ("%1") DO SET /A "%2=(%%a * 360000) + (%%b * 6000) + (%%c * 100) + %%d"
GOTO :EOF

The nice thing with this routine is that you pass in the time string as the first parameter and the name of the environment variable you want to contain the time (in centiseconds) as the second parameter.  For example:
CALL :ParseTime %START_TIME% START_CS
CALL :ParseTime %TIME% END_CS
SET /A DURATION=%END_CS% - %START_CS%

(*Chris*)

A: Maybe something like this:
@call:DateTime

@for %%? in (
    "Year   :Y"
    "Month  :M"
    "Day    :D"
    "Hour   :H"
    "Minutes:I"
    "Seconds:S"
) do @for /f "tokens=1-2 delims=:" %%# in (%%?) do @for /f "delims=" %%_ in ('echo %%_DT_%%$_%%') do @echo %%# : _DT_%%$_ : %%_

:: OUTPUT
:: Year    : _DT_Y_ : 2014
:: Month   : _DT_M_ : 12
:: Day     : _DT_D_ : 17
:: Hour    : _DT_H_ : 09
:: Minutes : _DT_I_ : 04
:: Seconds : _DT_S_ : 35

@pause>nul

@goto:eof

:DateTime
    @verify errorlevel 2>nul & @wmics Alias /? >nul 2>&1
    @if not errorlevel 1 (
        @for /f "skip=1 tokens=1-6" %%a in ('wmic path win32_localtime get day^,hour^,minute^,month^,second^,year /format:table') do @if not "%%f"=="" ( set "_DT_D_=%%a" & set "_DT_H_=%%b" & set "_DT_I_=%%c" & set "_DT_M_=%%d" & set "_DT_S_=%%e" & set "_DT_Y_=%%f" )
    ) else (
        @set "_DT_T_=1234567890 "
    )
    @if errorlevel 1 (
        @for %%? in ("iDate" "sDate" "iTime" "sTime" "F" "Y" "M" "D" "H" "I" "S") do @set "_DT_%%~?_=%%~?"
        @for %%? in ("Date" "Time") do @for /f "skip=2 tokens=1,3" %%a in ('reg query "HKCU\Control Panel\International" /v ?%%~? 2^>nul') do @for /f %%x in ('echo:%%_DT_%%a_%%') do @if "%%x"=="%%a" set "_DT_%%a_=%%b"
        @for /f "tokens=1-3 delims=%_DT_T_%" %%a in ("%time%") do @set "_DT_T_=%%a%%b%%c"
    )
    @if errorlevel 1 (
        @if "%_DT_iDate_%"=="0" (set "_DT_F_=_DT_D_ _DT_Y_ _DT_M_") else if "%_DT_iDate_%"=="1" (set "_DT_F_=_DT_D_ _DT_M_ _DT_Y_") else if "%_DT_iDate_%"=="2" (set "_DT_F_=_DT_Y_ _DT_M_ _DT_D_")
        @for /f "tokens=1-4* delims=%_DT_sDate_%" %%a in ('date/t') do @for /f "tokens=1-3" %%x in ('echo:%%_DT_F_%%') do @set "%%x=%%a" & set "%%y=%%b" & set "%%z=%%c"
        @for /f "tokens=1-3 delims=%_DT_T_%" %%a in ("%time%") do @set "_DT_H_=%%a" & set "_DT_I_=%%b" & set "_DT_S_=%%c"
        @for %%? in ("iDate" "sDate" "iTime" "sTime" "F" "T") do @set "_DT_%%~?_="
    )
    @for %%i in ("Y"                ) do @for /f %%j in ('echo:"%%_DT_%%~i_%%"') do @set /a _DT_%%~i_+=  0 & @for /f %%k in ('echo:"%%_DT_%%~i_:~-4%%"') do @set "_DT_%%~i_=%%~k"
    @for %%i in ("M" "D" "H" "I" "S") do @for /f %%j in ('echo:"%%_DT_%%~i_%%"') do @set /a _DT_%%~i_+=100 & @for /f %%k in ('echo:"%%_DT_%%~i_:~-2%%"') do @set "_DT_%%~i_=%%~k"
@exit/b

A: Use REG to save/modify/restore what ever values are most useful for your bat file.  This is windows 7, for other versions you may need a different key name.
reg save    "HKEY_CURRENT_USER\Control Panel\International" _tmp.reg /y
reg add     "HKEY_CURRENT_USER\Control Panel\International" /v sShortDate  /d "yyyy-MM-dd" /f
set file=%DATE%-%TIME: =0%
reg restore "HKEY_CURRENT_USER\Control Panel\International" _tmp.reg
set file=%file::=-%
set file=%file:.=-%
set file

A: In situations like this use a simple, standard programming approach:
Instead of expending a huge effort parsing an unknown entity, simply save the current configuration, reset it to a known state, extract the info and then restore the original state. Use only standard Windows resources.
Specifically, the date and time formats are stored under the registry key
HKCU\Control Panel\International\ in [MS definition] "values": "sTimeFormat" and "sShortDate".
Reg is the console registry editor included with all Windows versions.
Elevated privileges are not required to modify the HKCU key
Prompt $N:$D $T$G

::Save current config to a temporary (unique name) subkey, Exit if copy fails
Set DateTime=
Set ran=%Random%
Reg copy "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp%ran%" /f
If ErrorLevel 1 GoTO :EOF

::Reset the date format to your desired output format (take effect immediately)
::Resetting the time format is useless as it only affect subsequent console windows
::Reg add "HKCU\Control Panel\International" /v sTimeFormat /d "HH_mm_ss"   /f
Reg add "HKCU\Control Panel\International" /v sShortDate  /d "yyyy_MM_dd" /f

::Concatenate the time and (reformatted) date strings, replace any embedded blanks with zeros
Set DateTime=%date%__%time:~0,2%_%time:~3,2%_%time:~6,2%
Set DateTime=%DateTime: =0%

::Restore the original config and delete the temp subkey, Exit if restore fails
Reg copy   "HKCU\Control Panel\International-Temp%ran%" "HKCU\Control Panel\International" /f
If ErrorLevel 1 GoTO :EOF
Reg delete "HKCU\Control Panel\International-Temp%ran%" /f

Simple, straightforward and should work for all regions.
For reasons I don't understand, resetting the "sShortDate" value takes effect immediately in
a console window but resetting the very similar "sTimeFormat" value does NOT take effect
until a new console window is opened. However, the only thing changeable is the delimiter -
the digit positions are fixed.Likewise the "HH" time token is supposed to prepend leading zeros but it doesn't.
Fortunately, the workarounds are easy.

A: Using % you will run into a hex operation error when the time value is 7-9. To avoid this, use DelayedExpansion and grab time values with !min:~1!
An alternate method, if you have PowerShell is to call that:
for /F "usebackq delims=Z" %%i IN (`powershell Get-Date -format u`) do (set server-time=%%i)

A: This script use a WMI interface accessed primary via WMIC tool, which is an integral part of Windows since Windows XP Professional (Home edition is supported too, but the tool is not installed by default). The script also implements a workaround of missing WMIC tool by creating and calling a WSH vbscript for access a WMI interface and write to console output the time with same format as WMIC tool provide.
@ECHO OFF
REM Returns: RETURN
REM Modify:  RETURN, StdOut
REM Required - mandatory: none
REM Required - optionaly: format strings delimited by a space to format an output delimited by predefined delimiter
REM    YYYY = 4-digit year
REM      MM = 2-digit month
REM      DD = 2-digit day
REM      hh = 2-digit hour
REM      mm = 2-digit minute
REM      ss = 2-digit second
REM      ms = 3-digit millisecond

CALL :getTime %*
ECHO %RETURN%
GOTO :EOF

REM SUBROUTINE
REM Returns: RETURN
REM Modify:  RETURN
REM Required - mandatory: none
REM Required - optionaly: format strings delimited by a space to format an output delimited by predefined delimiter
REM    YYYY = 4-digit year
REM      MM = 2-digit month
REM      DD = 2-digit day
REM      hh = 2-digit hour
REM      mm = 2-digit minute
REM      ss = 2-digit second
REM      ms = 3-digit millisecond
:getTime
  SETLOCAL EnableDelayedExpansion
    SET DELIM=-
    WHERE /Q wmic.exe
    IF NOT ERRORLEVEL 1 FOR /F "usebackq skip=1 tokens=*" %%x IN (`wmic.exe os get LocalDateTime`) DO (SET DT=%%x & GOTO getTime_Parse)
    SET _TMP=%TEMP:"=%
    ECHO Wscript.StdOut.WriteLine (GetObject("winmgmts:root\cimv2:Win32_OperatingSystem=@").LocalDateTime)>"%_TMP%\get_time_local-helper.vbs"
    FOR /F "usebackq tokens=*" %%x IN (`cscript //B //NoLogo "%_TMP%\get_time_local-helper.vbs"`) DO (SET DT=%%x & GOTO getTime_Parse)
    :getTime_Parse
      SET _RET=
      IF "%1" EQU "" (
        SET _RET=%DT:~0,4%%DELIM%%DT:~4,2%%DELIM%%DT:~6,2%%DELIM%%DT:~8,2%%DELIM%%DT:~10,2%%DELIM%%DT:~12,2%%DELIM%%DT:~15,3%
      ) ELSE (
        REM Not recognized format strings are ignored during parsing - no error is reported.
       :getTime_ParseLoop
         SET _VAL=
         IF "%1" EQU "YYYY" SET _VAL=%DT:~0,4%
         IF "%1" EQU "MM"   SET _VAL=%DT:~4,2%
         IF "%1" EQU "DD"   SET _VAL=%DT:~6,2%
         IF "%1" EQU "hh"   SET _VAL=%DT:~8,2%
         IF "%1" EQU "mm"   SET _VAL=%DT:~10,2%
         IF "%1" EQU "ss"   SET _VAL=%DT:~12,2%
         IF "%1" EQU "ms"   SET _VAL=%DT:~15,3%
         IF DEFINED _VAL (
           IF DEFINED _RET (
             SET _RET=!_RET!%DELIM%!_VAL!
           ) ELSE (
             SET _RET=!_VAL!
           )
         )
         SHIFT
         IF "%1" NEQ "" GOTO getTime_ParseLoop
      )
  ENDLOCAL & SET RETURN=%_RET%
GOTO :EOF

A: A nice single-line trick to avoid early variable expansion is to use cmd /c echo ^%time^%
cmd /c echo ^%time^% & dir /s somelongcommand & cmd /c echo ^%time^%

A: So the problem with %DATE% is that it depends on locale. So most of the previous answers did not work for me. If you are not picky about the exact format and just want a timestamp to differentiate the files you can do this:
set _date=%DATE%-%TIME%
set _date=%_date:/=-%
set _date=%_date: =-%
set _date=%_date::=-%
set _date=%_date:.=-%
echo %_date%

This should work for most locales. If it doesn't add another line set _date=%_date:<offending_char>=-% to remove the offending character. ie: a character which is not compatible with filenames or something you don't want in the file name.

Please note this doesn't meet the exact criteria laid down by the question.

A: :: =============================================================
:: Batch file to display Date and Time seprated by undescore.
:: =============================================================
:: Read the system date.
:: =============================================================
@SET MyDate=%DATE%
@SET MyDate=%MyDate:/=:%
@SET MyDate=%MyDate:-=:%
@SET MyDate=%MyDate: =:%
@SET MyDate=%MyDate:\=:%
@SET MyDate=%MyDate::=_%
:: =============================================================
:: Read the system time.
:: =============================================================
@SET MyTime=%TIME%
@SET MyTime=%MyTime: =0%
@SET MyTime=%MyTime:.=:%
@SET MyTime=%MyTime::=_%
:: =============================================================
:: Build the DateTime string.
:: =============================================================
@SET DateTime=%MyDate%_%MyTime%
:: =============================================================
:: Display the Date and Time as it is now.
:: =============================================================
@ECHO MyDate="%MyDate%" MyTime="%MyTime%" DateTime="%DateTime%"
:: =============================================================
:: Wait before close.
:: =============================================================
@PAUSE
:: =============================================================

A: Split the results of the date command by slash, then you can move each of the tokens into the appropriate variables.
FOR /F "tokens=1-3 delims=/" %%a IN ("%date:~4%") DO (
SET _Month=%%a
SET _Day=%%b
SET _Year=%%c
)
ECHO Month %_Month%
ECHO Day %_Day%
ECHO Year %_Year%

A: For a very simple solution for numeric date for use in filenames use the following code:
set month=%date:~4,2%
set day=%date:~7,2%
set curTimestamp=%month%%day%%year%

rem then the you can add a prefix and a file extension easily like this
echo updates%curTimestamp%.txt

A: *

*set xtime=%time%

*if "%xtime:~0,1%" == " " set xtime=0%xtime:~1,7%

*set isodate=%date:~-4%%date:~3,2%%date:~0,2%_%xtime:~0,2%%xtime:~3,2%%time:~6,2%

A: Hope this helps:
set MM=%date:~4,2%
set DD=%date:~7,2%
set YYYY=%date:~10,4%

echo %DD%_%MM%_%YYYY%

This will print 05_06_2021

A: for /f "tokens=1-4 delims=/ " %%I in ("%DATE%") do set curdate=%%K_%%J_%%I
for /f "tokens=1-4 delims=:," %%I in ("%TIME: =0%") do set curtime=%%I_%%J_%%K
echo %curdate%__%curtime%

replace delims symbols if your system uses another (used for slicing to %%I,%%J...)
also edit curdate if your system uses another D/M/Y order


Q: Java error loading images from a jar I know there are many threads for this, but im still to silly to fix this problem..
Im loading my images by the following:
ImageIO.read(new File(this.getClass().getResource("../" + src).toString().substring(5)));

I read in some threads (in german) that with this method you can load images from a jar, but also run it correct from eclipse.
But anyway im getting this error, when trying to open the jar:
Exception in thread "main" java.lang.reflect.InvocationTargetException
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.NullPointerException
        at game.Sound.<init>(Sound.java:17)
        at game.GUI.<init>(GUI.java:34)
        at game.GUI.main(GUI.java:115)
        ... 5 more

Im running this from console with:   java -jar CastleNightmare.jar
What im making ewrong?
Thank you!


Q: Sending email with Mandrill using PHP I'm trying to send email using Mandrill and PHP and I can't get it to send.
I've downloaded the PHP API wrapper from here:https://packagist.org/packages/mandrill/mandrill
Mandrill.php is in my root and the Mandrill folder is in the same directory.
Here's my code:
<?php
require_once 'Mandrill.php';

$mandrill = new Mandrill('MY API KEY IS USUALLY HERE');
$message = array(
    'subject' => 'Test message',
    'from_email' => 'jwjody@yahoo.com',
    'from_name' => 'Sender person',
    'html' => '
this is a test message with Mandrill\'s PHP wrapper!.
',
    'to' => array(array('email' => 'jwjody@yahoo.com', 'name' => 'Recipient 1')),
    'merge_vars' => array(array(
        'rcpt' => 'recipient1@domain.com',
        'vars' =>
        array(
            array(
                'name' => 'FIRSTNAME',
                'content' => 'Recipient 1 first name'),
            array(
                'name' => 'LASTNAME',
                'content' => 'Last name')
    ))));

//print_r($mandrill->messages->sendTemplate($template_name, $template_content, $message));
echo ("hello");

?>

But it won't send. I'm not sure where the failure is. Is it something obvious I'm missing?
I see the issue now.
I see what's going on now!
I changed
$mandrill->messages->sendTemplate($template_name, $template_content, $message));

to
$mandrill->messages->send($message, $async=false, $ip_pool=null, $send_at=null);

And it works!

A: Instead of calling the sendTemplate() function I should have used
$mandrill->messages->send($message, $async=false, $ip_pool=null, $send_at=null);

Once I changed the function call the mail was sent.


Q: populate static items into c# WPF combo box I am trying to add the static values in to my combo box which is being written in WPF c#. I have following xaml piece of code which adds the items into my combo box.
<ComboBox Text="MyCombo">
<ComboBoxItem  Name="115200">Item1</ComboBoxItem>
<ComboBoxItem  Name="57600">Item2</ComboBoxItem>
<ComboBoxItem  Name="38400">Item3</ComboBoxItem>
</ComboBox>

But is there any way that I can use "ItemSource" property of the combo box in to my xaml code to populate the combo box or any other UI method to add the static values into combo box.
Note: I do not want to do it in coding way to populate the values. I would like find the way of xaml or UI addition only.

A: You can bind your Combo box items from your view model using item source.
See the example below:
First, you want to set the DataContext of your Window.
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModel();
    }
}

Next,
public class ViewModel
{
    public ObservableCollection<string> CmbContent { get; private set; }

    public ViewModel()
    {
        CmbContent = new ObservableCollection<string>
        {
            "Item 1",
            "Item 2",
            "Item 2"

        };
    }
}

Finally,
<Grid>
    <ComboBox Width="200"
          VerticalAlignment="Center"
          HorizontalAlignment="Center"
          x:Name="MyCombo"
          ItemsSource="{Binding CmbContent}" />
</Grid>


Q: How to remove empty classes from legend in ArcGIS Desktop? I have a classification image with only 12 classes. I'm preparing layout using this image. when I add legend into layout page, a lot of empty classes loaded together with these 12 classes. Totally 255 classes added to layout page. Then I tried to delete them in Symbology tab of data Properties window. How to remove these empty classes from legend.
Is there any way to do this?

A: Right click on Legend rectangle and select properties, legend properties will open. Select items and in the item screen there a block named map extend options.
Check the box of (only show classes that are visible in the current map extent)

A: Have you build the Raster Attribute Table when you classified the classification image ? I had to do that when I clipped from an original GAP or NLCD imagery and need to clip to a vector/polygon. For example, here is what happened, when you clip to a vector, it brings the  whole bunch of legneds carried over from the original imagery to the clipped imagery and I had to build the Raster Attribute Table toolbox to clean up the table in the clipped imagery. This way you will not have to convert them to graphics and lined up the symbology and that is pain !
It works for me and really saved a lot of my time and when I change it to the layout page and it will display what you need right there !

A: Right click on the legend, grouping -> disaggregate, disaggregate again, then you can delete each individual component. When you are done, select all components and re-group them. Hope this helps.

A: Yes build raster attribute table but in cataloge and it will update the new legend


Q: python error message AttributeError: 'Bird' object has no attribute 'unsetflapped' so i am learning to code games from a video coding tutorial series. And my current problem is that when i run the game I get the following error:
File "/home/dev/PycharmProjects/Game6_Flappy_Bird/modules/sprites/bird.py", line 33, in update
self.unsetflapped()
AttributeError: 'Bird' object has no attribute 'unsetflapped'
The code from the "bird class sprites file code:
self.is_flapped = False
    self.down_speed = 0
    self.up_speed = 9

    self.bird_idx = idx
    self.bird_idx_cycle = itertools.cycle([0,1,2,1])
    self.bird_idx_change_count = 0

def update(self, boundary_values, time_passed):

    if self.is_flapped:
        self.up_speed -= 60 * time_passed
        self.rect.top -= self.up_speed

        if self.up_speed <= 0:
            self.unsetflapped()
            self.up_speed = 9
            self.down_speed = 0
    else:
        self.down_speed += 40*time_passed
        self.rect.bottom += self.down_speed

    is_dead = False

    if self.rect.bottom > boundary_values[1]:
        is_dead = True
        self.up_speed = 0
        self.down_speed = 0
        self.rect.bottom = boundary_values[1]
    if self.rect.top < boundary_values[0]:
        is_dead = True
        self.up_speed = 0
        self.down_speed = 0
        self.rect.top = boundary_values[1]
    self.bird_idx_change_count +=1
    if self.bird_idx_change_count%5 == 0:
        self.bird_idx = next(self.bird_idx_cycle)
        self.image = list(self.images.values())[self.bird_idx]
        self.bird_idx_change_count = 0
    return is_dead

def setFlapped(self):
    if self.is_flapped:
        self.up_speed = max(12, self.up_speed+1)
    else:
        self.is_flapped = True

def unsetFlapped(self):
    self.is_flapped = False

I have checked this against the source code provided by the tutor and it matches exactly so I'm hoping someone can point me in the direction of what i'm doing wrong.

A: Please note: I figured out my problem. Capitalisation of lettering. I needed to change a small "f" to a capital "F"


Q: Is plain-TeX still useful? I mean, are there reasons to use plain one? And if so, where, and what are benifits? Or should we forget plain-tex and use latex instead?
I see plain-Tex docs are much smaller, so the question is "if I can perform daily paper work with it".


Q: MVC Linq for multiple selects that allow multiple selections I have a MVC web application with multiple selects that allow multiple selections that the user can use to filter data. For example: A car database where the user can select by make, color and body style. A possible search would be (Red OR Blue) AND (Chevy OR Ford) AND (SUV). I have all the selects returned in my viewmodel as array of strings and all gets returned to my controller correctly. I have the Color array with 'Red' and 'Blue', the Model array with 'Chevy' and 'Ford' and the BodyStyle array with 'SUV'. Now that I have the model posted to the controller, how do I construct the linq statement that will allow and of these criteria to me blank or contain multiple selections?
Model:
public class SearchViewModel
{
    public string[] Model { get; set; }
    public string[] Color { get; set; }
    public string[] Body { get; set; }
}

Controller:
public ActionResult Search(SearchViewModel search)
{
    //TODO: Create linq for all search criteria
    List<Cars> cars = db.Cars.Where(car => car.Model == search.Model[0]);

    return View(cars);
}

A: var list = new List<string> { "red", "orange"};

    from c in DB.Cars
    where list == null || list.Contains(c.Color)
    select c;


Q: Bluetooth LE with BlueGiga devboard (BLE112) This is my first post so please forgive me for any informality but I will get straight to my point.
I am trying to send RS-232 data (8N1 asynchronous at 115,200+ baud rate) from my PIC micro via bluetooth to a smartphone. I have done this successfully with Bluetooth 2.0 but that was easy since I was able to source BT 2.0 modules with an AT command set that allowed me to configure it to whatever baudrate I wanted. Now I am transitioning to Bluetooth LE (single mode) using the Blue Giga evaluation kit and BLE-112 module. I have a general idea of how to code the BLE-112 to receive serial data using its UART but not sure how to send that data to the radio. It looks like I'll have to save the received data into a GATT file after which it will be transmitted in one of the packets? Is there any way I can just stream data like I did with BT 2.0?
Lastly, I would be streaming the data to the Bluetooth module and I know that Bluetooth 4.0 dual mode may be the better option but this single mode version is what I have to work with at the moment.

A: As you probably know the BLE112 is a Bluetooth 4.0 single mode module, meaning it doesn't support/interoperate with Bluetooth devices older than version 4.0. The iPhone 4s and iPhone 5 are pretty much the most popular phones that have Bluetooth 4.0 support and provide APIs to use Bluetooth 4.0. Some android vendors have their own APIs such as Motrola for its Razr phone, but there is no Android API for Bluetooth 4.0. Currently any solution you make is not going to work with just any smartphone with Bluetooth.
Bluetooth 4.0 is also very different to older Bluetooths in the way it transmits and handles data. All data packets are only 20 bytes long. As you have read, at the heart of it is the slave device's (typically a sensor) GATT database which can be through of as a table with keys and values. Compared to the serial port profile (SPP) this is a very different way of thinking of data.
You can read and write the values (attributes) of the keys (attribute handles) locally (sensor / slave) or remotely (mobile phone). The idea with gatt is that instead of you writing your data like name,measurement,timestamp in one long data stream, you update the name attribute ("value"), measurement attribute and timestamp attribute in the sensor's local gatt. These changes then gets indicated to the mobile phone over the air. In short: Bluetooth 4.0 is not intended to be used for creating a data stream.
However, it is always possible to simulate or emulate streaming even when everything is packetized. Bluegiga provides a "Bluetooth Smart: Cable replacement application note" (registration required) which discusses exactly how to replace a UART cable with Bluetooth 4.0 and they give detailed explanations of how to accomplish that with the BLE112.
Update: Any device with Bluetooth and an Android version 4.3 or newer supports Bluetooth 4.0 natively. All the old vendor specific stacks have been deprecated in favor of the official support.

A: Coming straight to the point:

I have a general idea of how to code the BLE-112 to receive serial data using its UART but not sure how to send that data to the radio. It looks like I'll have to save the received data into a GATT file after which it will be transmitted in one of the packets?

When you build the .bgproj file using BleUpdate utility, it generates a .txt file along with the .hex. This text file has a list of all attributes and their ids. These ids is what you pass as an argument to the write function.
ble_cmd_attclient_write_command(connection,atthandle,data_len,data_data)
atthandle should be the id that you obtain from .txt file.


Q: angular 4 programmatic animation How to add animation programatically ?
@Component({
    moduleId: module.id,
    selector: 'my-toolbar',
    templateUrl: './my-toolbar.component.html',
    styleUrls: ['./my-toolbar.component.scss'],
    encapsulation: ViewEncapsulation.None,
    animations: [
        trigger('myToolbarState', [
            state('initial', style({top: '*'})),
            state('up', style({top: '-50px')),
            transition('initial => up, up => initial',
                animate(HEADER_SHRINK_TRANSITION))
        ])
    ]
})

How to achieve the same without annotation ? My underlying goal is to create a dynamic trigger function that uses different values based on some @Input.
It is important to note that the animations or the triggers must have at-least one variable. That makes this question different from how do I reuse animations.

A: I ended up with following factory class as shown below being used for animations[]:-
This is used as below:
@Component({
  selector: 'my-app-header',
  moduleId: module.id,
  templateUrl: './app-header.component.html',
  styleUrls: ['./app-header.component.scss'],
  animations: [
      MyToolbarAnimator.createTrigger('appHeaderState', '50px', '0')
  ]
})

Defined MyToolbarAnimator with a static method createTrigger which returns AnimationTriggerMetadata as shown below
MyToolbarAnimator
import {trigger, state, style, animate, transition, AnimationTriggerMetadata} from '@angular/animations';

export const HEADER_SHRINK_TRANSITION = '250ms cubic-bezier(0.4,0.0,0.2,1)';

export class MyToolbarAnimator {
    static createTrigger(triggerName: string, initialTop: string, upTop: string): AnimationTriggerMetadata {
        return trigger(triggerName, [
            state('initial', style({top: initialTop})),
            state('up', style({top: upTop})),
            transition('initial => up, up => initial',
                animate(HEADER_SHRINK_TRANSITION))
        ]);
    }
}

UPDATE:
Or if your animation parameters are very dynamic and changes based on the component behavior use https://angular.io/api/animations/AnimationBuilder#usage-notes
This
// import the service from BrowserAnimationsModule
import {AnimationBuilder} from '@angular/animations';
// require the service as a dependency
class MyCmp {
  width = 100;
  constructor(private _builder: AnimationBuilder) {}
  changeWidth(aWidth:number) {
      this.width = aWidth;
  }
  makeAnimation(element: any) {
    // first define a reusable animation
    const myAnimation = this._builder.build([
      style({ width: 0 }),
      animate(1000, style({ width: `${this.width}px` }))
    ]);

    // use the returned factory object to create a player
    const player = myAnimation.create(element);

    player.play();
  }
}


Q: Home Backup Server with Ubuntu - Drive Controller Configuration I am planning a build for a personal backup server; building essentially a NAS that I would install backup utilities on. I want to run Ubuntu Server as the OS, and am hoping for around 5-6 individual drives (2TB+ each) for primary data storage. I am assuming I will utilize RAID (5 or 10), but I am open to other similar solutions if they are better.
The point of this server is long term, reliable storage and ease of recovery on failure (ideally just swap a part out, with minimal other work).
As I am still in the planning stage, I am just trying to figure out a plan on the best way to accomplish this.
What I need to have cleared up:
The motherboard I am looking at has 4 SATA III ports, which I am planning to use for the OS storage. I am looking around for a PCI Express 3x16 compatible SATA Controller. What I am not sure about is this:

*

*Have the SATA controller handle the RAID configuration or the OS? I have heard that it is best to let Linux handle this. Is that true? Is there an easy to use utility used to set RAID (or similar system) up?

*Based on the answer above, will any SATA controller work for my purposes, or is there something to look out for?

Sorry if this is a little off topic, I was not sure exactly where to put this. Thanks in advance for anything that points me in the right direction.

A: Always use hardware RAID if you can afford it as a software RAID might give OS compatibility problems...  (Dual-boot with Windows, Using a boot CD to repair your system, ...)
Use RAID5: write speed is a bit slower then the disks all by themselves, but read speed is superior.
As to which controller: buy the most expensive one your budget allows you to buy and don't buy any unknown Crap! Inc! Cheap-o-RAID ones and stay with major brand names.
That should not make this answer too much off-topic ;-)


Q: Quantum translation operator
Let $T_\epsilon=e^{i \mathbf{\epsilon} P/ \hbar}$ an operator.  Show that $T_\epsilon\Psi(\mathbf r)=\Psi(\mathbf r + \mathbf \epsilon)$.

Where $P=-i\hbar \nabla$.
Here's what I've gotten: $$T_\epsilon\Psi(\mathbf r)= e^{i \mathbf{\epsilon} P/ \hbar}\Psi(\mathbf r)=\sum^\infty_{n=0} \frac{(i\epsilon \cdot (-i\hbar \nabla)/\hbar)^n}{n!} \Psi(\mathbf r)=\sum^\infty_{n=0} \frac{(\mathbf \epsilon \cdot \nabla)^n}{n!}\Psi(\mathbf r)= \Psi(\mathbf r) + (\epsilon \cdot \nabla) \Psi(\mathbf r) + \frac{(\epsilon \cdot \nabla)^2 \Psi(\mathbf r)}{2} + \cdots$$
This looks somewhat like a Taylor expansion of $\Psi(\mathbf r)$, but it's different than I've seen before -- I've never seen it in terms of a directional derivative.  Can you confirm if this is the Taylor expansion of $\Psi(\mathbf r + \mathbf \epsilon)$?  Or if not, what I should be getting when expanding $e^{i \mathbf{\epsilon} P/ \hbar}\Psi(\mathbf r)$?  Thanks.

A: In short, yes.
One thing that you need to clarify is, $\epsilon$ is not a vector while the argument of $\Psi$ is. I'll assume that $\epsilon$ is multiplied by some constant vector $v$.
Consider $\Psi(\vec{r}+\epsilon\vec{v})$ as a function of both $\vec{r}$ and $\epsilon$. Name it $\psi$ for clarity.
$$
\frac{\partial\psi}{\partial\epsilon}|_{\epsilon=0}=\nabla\Psi(\vec{r})
$$
So after the expansion,
$$
\begin{gather}
T_\epsilon\Psi(\vec{r})=&\sum^\infty_{n=0} \frac{(\mathbf \epsilon \cdot \nabla)^n}{n!}\Psi(\vec{r})
\\ =&\sum^\infty_{n=0} \frac{\epsilon^n \cdot \nabla^n}{n!}\Psi(\vec{r})
\\ =&\sum^\infty_{n=0} \frac{\epsilon^n}{n!}\frac{\partial^n\psi(\vec{r})}{\partial\epsilon^n}
\\ =&\psi(\vec{r}+\epsilon\vec{v})
\end{gather}
$$
as required.
However, I have problem with the validity of the Taylor expansion.
$P$ isn't bounded right? Does the Taylor series of an unbounded operator converge? I don't know the math here.


Q: How to restore and backup database I need to restore the MySQL database that I used which is a service based database, when I click the button 'RESTORE DATABASE'. I'm using VB.Net 2010. I already did a research for any solution, but I can't come up with any idea how to make it work. Do you have any ideas in mind that might help? I'm currently doing how to backup the database, so any help would be really much appreciated.
Here is the sample code:
Private Sub cmdrestore_Click (ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdrestore.Click

    Dim s As System.IO.StreamWriter
    Try
        Dim portfolioPath As String = My.Application.Info.DirectoryPath
        FileCopy(portfolioPath & "\Backup\Database1.mdf", "C:\Payroll System\Database1.Mdf")
            MsgBox("Restore completed successfully", vbInformation, "DBBES-B Payroll System")

    Catch ex As Exception
        Dim MessageString As String = "Report this error to the system administrator: " & ControlChars.NewLine & ex.Message
        Dim TitleString As String = "Employee Master Details Data Load Failed"
        MessageBox.Show(MessageString, TitleString, MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try
End Sub

A: First you will want to create a batch file that successfully restores the database.  There are plenty of examples when you search Google (MySQL database restore script).
Then your button will call your batch file using the Process class, like in the example found HERE.  You will use a .bat of course not .exe.


Q: Debian UEFI Boot with DELL Latitude 7490 "No bootable devices found" I have tried to install Debian 9.5 on a DELL Latitude 7490 with UEFI, but when I try to boot the machine I get the infamous "No bootable devices found".
EFI partition has been created, and I can see the entry in efibootmgr -v.
I have tried to install Ubuntu with (apparently) the same settings and it works... I am a bit lost here.
Does anybody have any idea what could be wrong here?

A: You should try to disable 'secure boot' option in the UEFI options, had the same problem.

A: If your problem is not solved by disabling the secure boot feature then you should have a look at the following link:
https://wiki.debian.org/UEFI#Quirks.2C_workarounds_and_special_UEFI_features_in_Debian_and_Debian-Installer
You may want to have a look at the section on the removable media path.
The section regarding the removable media path may be your problem, but I have no specifi knowledge if you Dell system has that problem.
If you think this may be the problem you can solve it manually to fix your installation using a bootable Debian usb stick and manually modify you EFI system Partition (ESP) as follows.  Debian default UEFI boot code on ESP is /EFI/debian/grubx64.efi mounted on /boot/efi.  Mount the ESP and create a new (as root) directory /EFI/boot and you copy /EFI/debian/grubx64.efi to /EFI/boot/bootx64.efi.
After this you should be able to boot.  Keep in mind that you probably still have to do the grub install fix mentioned in the wiki to make sure the bootx64.efi is updated with the rest of the system.

A: Here is what worked for my Acer laptop. I had installed Debian in UEFI Mode, but booting produced a “No bootable device” error.
To fix this:

*

*In BIOS, set supervisor password to access secure boot options, skip if you already can change secure boot options.

*In your BIOS find the secure boot options section and navigate to "Select an UEFI file as trusted for executing", then hdd(number), Debian, select grubx64.efi, name it grubx64 and say yes.
Do this again but for shimx64.efi.

*Save changes and reboot into BIOS and set this boot order:
EFI File Boot 1: shimx64
EFI File Boot 0: grubx64
HDD(number): Debian drive

*Save changes and reboot
This worked for me, I hope this helps.


Q: Does there exist some kind of irreversible transfomations on maths? I know that this kind of transformation by itself without control can lead to contradiction because its value changes depending on the state of the function where you do the transformation. Anyway I want to show my idea:
$$F^k\rightarrow k!$$
Some kind of symbol that it exponent, that it takes on normal exponentiation operations of normal algebra, can be transformed after in a specific moment in an irreversible transformation, i.e., in a function that represents a different thing non-linear as a factorial.
We have, for example, a generating function like
$$f(x)=(1+ax+ax^2+ax^3)(1+ax^3+ax^5)=a^{2} x^{8} + a^{2} x^{7} + 2 \, a^{2} x^{6} + a^{2} x^{5} + a^{2} x^{4} + a x^{5} + 2 \, a x^{3} + a x^{2} + a x + 1$$
then, in some moment, I want to transform the $a^k$ coefficients in $k!$ to express permutations
$$f(x)\rightarrow(a^k\to k!)\to 2! x^{8} + 2! x^{7} + 2\cdot 2! x^{6} + 2! x^{5} + 2! x^{4} + x^{5} + 2 x^{3} +  x^{2} + x + 1 $$
I could add another power to express duplicated permutations ($c^k=\frac{1}{k!}$) over groups that I consider equals and lead to repeated patterns.
Is there a symbology or method to do this kind of task?


Q: The default value for a column in not set when copy file using rest api (SharePoint 2013 standalone) I am trying to copy files from one folder to another folder using SharePoint REST API. Some columns inside the destination folder have defined a default value. Even though the files are copied successfully, some files do not get the default value for the columns.
On a closer look, I found that the new office documents types (.docx, .xlsx, .pptx etc.) get the default values, while the old office document types (.doc, .xls, .ppt) do not get the values.
Also the old office documents get the values only when they are coming from a source folder which already contains the columns in the destination folder.
I am wondering why the old office documents do not get the values and if anything can be done.
Is it a bug in SharePoint Server or am I missing any configuration to make all files work?

A: My understanding is that this is expected. Because you are copying files, the copy includes not only the file itself but also its metadata. If the file in the source folder doesn't have values in those columns, it does make sense that if you copy it to a destination folder, those same columns shouldn't have values either. Now, why some files (docx, pptx, etc.) do have values in the destination? Probably because of the SharePoint document parser feature (Document Property Promotion and Demotion). So in your case what you can do is, instead of copying the files, download/upload them using for instance code like this.


Q: How to disable a specific row to be draggable in AG table? I am using the Managed Dragging of AG Grid React table and want to disable a specific row, if it matches the condition.
In Docs I couldn't find enough information how to do that. As it describes here, it is possible to add the draggable feature conditionally, like this
rowDrag: params => !params.node.group

In params object, I couldn't find the row data to implement my condition.
In the code example described below, I want to disable the row to be draggable if the name==='John.
Also, how to that if you have row draggable for entire row: rowDragEntireRow={true}?
Sandbox demo and code
import React from "react";
import { AgGridReact } from "ag-grid-react";
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";
function App() {
  const [gridApi, setGridApi] = React.useState(null);
  const [gridColumnApi, setGridColumnApi] = React.useState(null);

  const onGridReady = (params) => {
    setGridApi(params.api);
    setGridColumnApi(params.columnApi);
  };

  const defaultColDef = {
    flex: 1,
    editable: true
  };

  const columnDefs = [
    {
      headerName: "Name",
      field: "name",
      rowDrag: (params) => {
        console.log("params", params);
        return !params.node.group;
      }
    },
    { headerName: "stop", field: "stop" },
    {
      headerName: "duration",
      field: "duration"
    }
  ];

  const rowData = React.useMemo(
    () => [
      {
        name: "John",
        stop: 10,
        duration: 5
      },
      {
        name: "David",
        stop: 15,
        duration: 8
      },
      {
        name: "Dan",
        stop: 20,
        duration: 6
      }
    ],
    []
  );

  return (

React-App

          <AgGridReact
            columnDefs={columnDefs}
            rowData={rowData}
            defaultColDef={defaultColDef}
            onGridReady={onGridReady}
            rowDragManaged={true}
            //rowDragEntireRow={true}
          ></AgGridReact>

  );
}

export default App;

Any help will be appreciated

A: Update your rowDrag definition in the name column definition to the following:
  rowDrag: (params) => {
    if (params.data.name == "John") {
      return false;
    }
    return true;
  }

Demo.


Q: Embed Bokeh server with multiple roots in Django I have a bokeh app with multiple roots. Inside the bokeh template, I use
{{embed(roots.plot1)}}
{{embed(roots.plot2)}}
# etc

to load the plots. This works fine. Now, I'd like to get the plots to load inside a web page I'll be serving from a Django app. Since my plots are generated using Holoviews, the Bokeh server is essential.
The bokeh documentation https://github.com/bokeh/bokeh/tree/master/examples has examples of how to autoload all plots from a Bokeh server, and it also has examples of how to embed multiple static plots using components(), but none of these seem to cover this use case.
Here's what I've tried:
# The following function is a function-based Django view
def django_view(request):

    bokeh_url = 'http://localhost:5006/experiment'
    roots = {root.name: root for root in session.document.roots}

    with pull_session(url=bokeh_url) as session:

        # I was hoping that these will generate separate autoload scripts for each model.
        # Unfortunately they each embed all the models.
        script1 = server_session(session_id=session.id, url=bokeh_url, model=roots['plot1'])
        script2 = server_session(session_id=session.id, url=bokeh_url, model=roots['plot2'])

    return render(request, "template.html", {"script1": script1, "script2: script2})

Excerpt from template.html:
{{ script1 | safe }}
{{ script2 | safe }}

The result is that each script tag loads all the plots on top of eachother. How can I get each plot embedded exactly once, where I want it? How should I be doing this?


Q: simplexml_load_file() with a variable I'm currently having an issue with simplexml_load_file(); my xml path is a url, that is rendered as a variable
$xurl = "domain/pathto/myfile.xml"; //  This is actually a variable that returns the entire URL to where my xml file is -- this will change from file to file

$xmlpath = parse_url($xurl, PHP_URL_PATH); // to get the path of my xml file ex. /pathto/myfile.xml

$xmlpath = mb_substr($xmlpath, 1);  // returns pathto/myfile.xml

here is where my problem is, when I put it into :
simplexml_load_file($xmlpath);

In my function, I get nothing appearing from the XML file
However, in my same function if I change it to
simplexml_load_file("pathto/myfile.xml");

My function works fine.
I did an echo on $xmlpath and it returns the pathto/myfile.xml just fine.
<?php echo $xmlpath; ?> // returns pathto/myfile.xml

What am I doing wrong?
EDIT: Phil
echo strcmp("pathto/myfile.xml", $xmlpath)

returns a 0.


Q: VBA Transpose to Another target Sheet In the pictures below, I have a source page that is formatted with a device and attributes. I would like to create a macro which copies that source data and pastes it in the format of the target sheet. Ultimately the target sheet would be empty and would populate only when running the macro.
Source page and target page
I am a newb at this. I've tried using the following code from another stack overflow question, but it doesn't do what I want.
Sub ColumnCopy()
Dim lastRow As Long
Dim lastRow As Long
Dim lastCol As Long
Dim colBase As Long
Dim tRow As Long
Dim source As String
Dim target As String

source = "source"       'Set your source sheet here
target = "target"       'Set the Target sheet name

tRow = 2                'Define the start row of the target sheet

'Get Last Row and Column
lastRow = Sheets(source).Range("A" & Rows.Count).End(xlUp).Row
lastCol = Sheets(source).Cells(2, Columns.Count).End(xlToLeft).Column

tRow = 2
colBase = 2

Do While colBase < lastCol
    For iRow = 2 To lastRow
        Sheets(target).Cells(tRow, 1) = Sheets(source).Cells(1, tRow)
        Sheets(target).Cells(tRow, 2) = Sheets(source).Cells(2, tRow)
        Sheets(target).Cells(tRow, 3) = Sheets(source).Cells(3, tRow)
        Sheets(target).Cells(tRow, 4) = Sheets(source).Cells(4, tRow)
        Sheets(target).Cells(tRow, 5) = Sheets(source).Cells(5, tRow)
        Sheets(target).Cells(tRow, 6) = Sheets(source).Cells(6, tRow)
        tRow = tRow + 1
    Next iRow
        colBase = colBase + 1  'Add 4 to the Column Base.  This shifts the loop over to the next Row set.
Loop

End Sub
Thanks,
MJ


Q: How Strict is the rule no dom manipulation inside controller in AngularJS? I know in AngularJS We are not supposed to do any dom manipulation inside a controller. But If i need to do a dom manipulation on click of an element then how am i supposed to handle it. For example while building a menu i need to show submenu on click how do i accomplish it without dom manipulation in the controller?


Q: Fuse amperage for laptop PSU I have cord that is rather short, so I found a longer one and wanted to swap the IEC [kettle lead] type.
I checked the fuse to see if they are the same new one is a 5A & the existing one is 13A; can that be right for a laptop? It's an Acer A13-045N2A its the one that came  with the laptop (I don't remember changing the lead in the past but 13 sounds a bit high would it be safe to use the 5A).

A: I'm not certain whether you mean the new lead is 5A or the existing...
5A is already a bit high for a computer PSU mains cable, but as that's the common minimum, it will be fine. If you were particularly paranoid a 3A would be 'safer' by the tiniest margin.
Most generic cables are supplied with 13A fuses, because that's just the maximum permissible load.
Swap the fuses over if you want, 10 second job, they pry out with a screwdriver on standard moulded plugs, or buy a pack from your local supermarket or DIY store. They cost pence.
I have assumed for this that we're talking UK plugs, as nowhere else seems to put fuses in them.


Q: What are the differences between class diagram and physical class diagram? What are the differences between class diagram and physical class diagram?

A: There is nothing like a Physical Class Diagram, just class diagrams (you may consult Superstructures if you like). What you probably mean is the difference between class model and physical model. The latter focuses on the concrete implementation of a class model. It shows libs, hardware and things you'd need to implement your more abstract class model on some real hardware. With the MDA this part is called PSM (platform specific model) in contrast to the PIM (platform independent model).


Q: How to do you insert array typeof data into apche ignite I am trying to create a table with array data type in apache ignite using following query.
create table test(id int,word varchar,vector array,primary key(id));

with this above query i am able to create a table test.
0
: jdbc:ignite:thin://127.0.0.1/> !tables
+--------------------------------+--------------------------------+--------------------------------+--------------------------------+----------------+
|           TABLE_CAT            |          TABLE_SCHEM           |           TABLE_NAME           |           TABLE_TYPE           |            REM |
+--------------------------------+--------------------------------+--------------------------------+--------------------------------+----------------+
|                                | wordVectorCache                | WORDTOVECTORBASICDETAILS       | TABLE                          |                |
|                             | PUBLIC                         | TEST                           | TABLE                          |                |
+--------------------------------+--------------------------------+--------------------------------+--------------------------------+----------------+

if i tried same with following query
create table test1(id int,word varchar,vector char[],primary key(id));

i got following error,
0: jdbc:ignite:thin://127.0.0.1/> create table test2(id int,word varchar,vector char[],primary key(id));
Error: Failed to parse query. Syntax error in SQL statement "CREATE TABLE TEST2(ID INT,WORD VARCHAR,VECTOR CHAR[[*]],PRIMARY KEY(ID)) "; expected "(, FOR, UNSIGNED, INVISIBLE, VISIBLE, NOT, NULL, AS, DEFAULT, GENERATED, ON, NOT, NULL, AUTO_INCREMENT, BIGSERIAL, SERIAL, IDENTITY, NULL_TO_DEFAULT, SEQUENCE, SELECTIVITY, COMMENT, CONSTRAINT, PRIMARY, UNIQUE, NOT, NULL, CHECK, REFERENCES, ,, )"; SQL statement:
create table test2(id int,word varchar,vector char[],primary key(id)) [42001-197] (state=42000,code=1001)
java.sql.SQLException: Failed to parse query. Syntax error in SQL statement "CREATE TABLE TEST2(ID INT,WORD VARCHAR,VECTOR CHAR[[*]],PRIMARY KEY(ID)) "; expected "(, FOR, UNSIGNED, INVISIBLE, VISIBLE, NOT, NULL, AS, DEFAULT, GENERATED, ON, NOT, NULL, AUTO_INCREMENT, BIGSERIAL, SERIAL, IDENTITY, NULL_TO_DEFAULT, SEQUENCE, SELECTIVITY, COMMENT, CONSTRAINT, PRIMARY, UNIQUE, NOT, NULL, CHECK, REFERENCES, ,, )"; SQL statement:
create table test2(id int,word varchar,vector char[],primary key(id)) [42001-197]
    at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.sendRequest(JdbcThinConnection.java:750)
    at org.apache.ignite.internal.jdbc.thin.JdbcThinStatement.execute0(JdbcThinStatement.java:212)
    at org.apache.ignite.internal.jdbc.thin.JdbcThinStatement.execute(JdbcThinStatement.java:475)
    at sqlline.Commands.execute(Commands.java:823)
    at sqlline.Commands.sql(Commands.java:733)
    at sqlline.SqlLine.dispatch(SqlLine.java:795)
    at sqlline.SqlLine.begin(SqlLine.java:668)
    at sqlline.SqlLine.start(SqlLine.java:373)
    at sqlline.SqlLine.main(SqlLine.java:265)

Now i tried to insert data into test table, using following query
insert into test values(1,'ramoji',{'123','234'});

this time i faced an issue:
0: jdbc:ignite:thin://127.0.0.1/> insert into test values(1,'ramoji',{'123','234'});
Error: Failed to parse query. Syntax error in SQL statement "insert into test values(1,'ramoji',{'123','234'})[*]" [42000-197] (state=42000,code=1001)
java.sql.SQLException: Failed to parse query. Syntax error in SQL statement "insert into test values(1,'ramoji',{'123','234'})[*]" [42000-197]
    at org.apache.ignite.internal.jdbc.thin.JdbcThinConnection.sendRequest(JdbcThinConnection.java:750)
    at org.apache.ignite.internal.jdbc.thin.JdbcThinStatement.execute0(JdbcThinStatement.java:212)
    at org.apache.ignite.internal.jdbc.thin.JdbcThinStatement.execute(JdbcThinStatement.java:475)
    at sqlline.Commands.execute(Commands.java:823)
    at sqlline.Commands.sql(Commands.java:733)
    at sqlline.SqlLine.dispatch(SqlLine.java:795)
    at sqlline.SqlLine.begin(SqlLine.java:668)
    at sqlline.SqlLine.start(SqlLine.java:373)
    at sqlline.SqlLine.main(SqlLine.java:265)

Can any one please help me how should i use array data type in apache ignite & how to insert data with proper example.
Thank you very much for your help & Support in advance.
I will be keep looking for your answers, Please help .....
My sample data for one record is:
insert into text values(
1,'in',"['0.070312', '0.086914', '0.087891', '0.062500', '0.069336', '-0.108887', '-0.081543', '-0.154297', '0.020752', '0.131836', '-0.113770', '-0.037354', '0.069336', '0.078125', '-0.103027', '-0.097656', '0.044189', '0.102539', '-0.060791', '-0.036133', '-0.045410', '0.047363', '-0.120605', '-0.063965', '0.002258', '0.037109', '-0.002914', '0.117676', '0.061768', '0.063965', '0.081055', '-0.068848', '-0.021362', '0.055176', '-0.085449', '0.068848', '-0.127930', '-0.033203', '0.098633', '0.175781', '0.110840', '-0.034668', '-0.047119', '-0.008484', '0.035889', '0.103027', '0.026978', '-0.028687', '-0.005127', '0.106445', '0.059814', '0.094238', '0.033691', '-0.027100', '-0.094238', '0.001030', '-0.048340', '0.034424', '0.081055', '-0.113281', '-0.088867', '0.035889', '-0.145508', '-0.244141', '-0.061523', '0.052979', '0.056885', '0.179688', '0.061035', '0.086914', '0.124023', '-0.040283', '0.022583', '0.177734', '-0.029663', '-0.029663', '0.117188', '0.031128', '-0.096191', '0.066406', '0.004700', '-0.080078', '0.062988', '-0.020630', '-0.054688', '-0.135742', '-0.063477', '0.083496', '-0.063965', '0.021484', '0.077148', '-0.037109', '-0.033691', '-0.183594', '-0.072754', '0.015869', '0.093262', '-0.061523', '-0.014221', '-0.003448', '0.011108', '-0.158203', '-0.017090', '0.006195', '-0.008728', '-0.080566', '-0.015259', '-0.087891', '0.003479', '-0.016113', '-0.012329', '0.097656', '-0.139648', '-0.085938', '-0.026855', '0.053955', '0.132812', '0.112793', '0.121094', '0.085449', '-0.007111', '0.044678', '-0.145508', '-0.003204', '-0.117676', '-0.065430', '0.071289', '-0.094238', '-0.030273', '0.120117', '0.080078', '-0.094727', '-0.162109', '-0.077637', '0.021240', '-0.081543', '0.003937', '-0.157227', '-0.098145', '0.039795', '0.039307', '-0.009094', '0.103027', '0.067871', '-0.042725', '0.063477', '-0.049072', '0.020874', '-0.166992', '0.093262', '0.093750', '0.006866', '0.053711', '0.052490', '-0.024414', '-0.032471', '-0.061523', '-0.005554', '0.096191', '0.037842', '0.012207', '-0.043945', '-0.007477', '0.105469', '0.020386', '0.145508', '0.082031', '0.005768', '0.004578', '-0.092773', '-0.138672', '-0.057373', '-0.051514', '-0.130859', '-0.139648', '-0.020508', '-0.027100', '0.032715', '0.104980', '-0.002335', '-0.022583', '0.000504', '-0.110840', '0.084961', '-0.129883', '-0.017456', '-0.000359', '0.107910', '0.088867', '0.044678', '0.025146', '0.023804', '0.081055', '0.023682', '-0.109863', '0.005371', '-0.017700', '-0.033936', '-0.032959', '-0.164062', '0.095703', '-0.018311', '0.005310', '-0.034424', '-0.044189', '-0.066406', '-0.017944', '-0.029663', '-0.007599', '-0.051270', '-0.054199', '0.089355', '-0.071777', '0.015259', '-0.082520', '-0.031738', '0.035645', '-0.021240', '-0.059326', '-0.013062', '0.046875', '0.023071', '0.020996', '-0.078613', '-0.008057', '0.019531', '-0.005554', '0.041504', '0.027832', '0.013611', '0.034668', '-0.182617', '0.120117', '0.074219', '-0.041016', '-0.009949', '0.042969', '-0.007294', '0.123047', '0.057617', '-0.053467', '-0.032227', '-0.009094', '-0.046631', '0.043945', '-0.050781', '0.068848', '0.002991', '-0.004181', '-0.044189', '0.073730', '-0.012756', '0.067383', '0.006287', '0.075195', '-0.037842', '0.004883', '0.044678', '-0.067383', '0.009705', '0.004730', '0.020508', '0.071289', '0.170898', '0.173828', '0.055664', '0.091309', '-0.037354', '0.049805', '-0.039307', '0.044189', '0.062500', '0.048584', '-0.053223', '0.048828', '-0.130859', '-0.028931', '-0.036133', '-0.060791', '-0.057373', '0.123047', '-0.082520', '-0.011902', '0.125000', '0.001358', '0.063965', '-0.106445', '-0.143555', '-0.042236', '0.024048', '-0.168945', '-0.088867', '-0.080566', '0.064941', '0.061279', '-0.047363', '-0.058838', '-0.047607', '0.014465', '-0.062500']");

How do i insert this much big data for my third column which should be of type Array.

A: Apache Ignite's SQL does not have syntax for reading or writing arrays. You can store arrays in text form if you like (for example, you can store JSON snippets in VARCHAR columns), or you can store arrays as fields in POJO objects using Ignite's Java APIs (they will not be accessible as SQL table columns in this case).
You can create an ARRAY column, but there is no way to populate it with array literal currently.


Q: QLPreviewController playback video I've found strange behaviour on the QLPreviewController modal where Im trying to preview a video and QLPreviewController carries on playing a video after I've dismissed the modal via the "done" button which is provided by default.
Any ideas on why this could be happening or how I can stop the playback?

A: Found the problem. I extended QLPreviewController and in viewWillDisappear i didn't call [super viewWillDisappear] which was causing the video to still playback in the background.


Q: RedirectToAction is Taking Too much Time in Production? I am Trying to redirect from one Controller Action to other controller Index Method.the redirection itself taking 20sec. how can i reduce the time its consuming? Actually it is a direct call it should not consume that much of time?
Is there any other way to Redirect?
here is my code
    public ActionResult LaunchSeletedService(int serviceId)
    {
        //some fuctionality

        if (Request.IsAjaxRequest())
        {

            return new JavaScriptResult() { Script = "document.location.replace('" + Url.Action("Index", "Home", new { area = Area }) + "');" };
            //return RedirectToAction("Index", "Home", new { area = Area });
        }
        else
        {

            return RedirectToAction("Index", "Home", new { area = Area });

        }
    }