Batch command date and time in file name
You should search; you can simply replace all spaces with zero set hr=%hr: =0%
– jeb Oct 11 '11 at 14:16
So I did:
set hr=%time:~0,2%
set hr=%hr: =0%
Then use %hr%
inside whatever string you are formatting to always get a two-digit hour.
(Jeb's comment under the most popular answer worked the best for me and is the simplest. I repost it here to make it more obvious for future users.)
Execute a command in command prompt using excel VBA
The S parameter does not do anything on its own.
/S Modifies the treatment of string after /C or /K (see below)
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
Try something like this instead
Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)
You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.
Shell("perl a.pl c:\temp")
-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here
Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn
Run Executable from Powershell script with parameters
Here is an alternative method for doing multiple args. I use it when the arguments are too long for a one liner.
$app = 'C:\Program Files\MSBuild\test.exe'
$arg1 = '/genmsi'
$arg2 = '/f'
$arg3 = '$MySourceDirectory\src\Deployment\Installations.xml'
& $app $arg1 $arg2 $arg3
How to pass command line argument to gnuplot?
You can pass arguments to a gnuplot script since version 5.0, with the flag -c
. These arguments are accessed through the variables ARG0
to ARG9
, ARG0
being the script, and ARG1
to ARG9
string variables. The number of arguments is given by ARGC
.
For example, the following script ("script.gp")
#!/usr/local/bin/gnuplot --persist
THIRD=ARG3
print "script name : ", ARG0
print "first argument : ", ARG1
print "third argument : ", THIRD
print "number of arguments: ", ARGC
can be called as:
$ gnuplot -c script.gp one two three four five
script name : script.gp
first argument : one
third argument : three
number of arguments: 5
or within gnuplot as
gnuplot> call 'script.gp' one two three four five
script name : script.gp
first argument : one
third argument : three
number of arguments: 5
In gnuplot 4.6.6 and earlier, there exists a call
mechanism with a different (now deprecated) syntax. The arguments are accessed through $#
, $0
,...,$9
. For example, the same script above looks like:
#!/usr/bin/gnuplot --persist
THIRD="$2"
print "first argument : ", "$0"
print "second argument : ", "$1"
print "third argument : ", THIRD
print "number of arguments: ", "$#"
and it is called within gnuplot as (remember, version <4.6.6)
gnuplot> call 'script4.gp' one two three four five
first argument : one
second argument : two
third argument : three
number of arguments: 5
Notice there is no variable for the script name, so $0
is the first argument, and the variables are called within quotes. There is no way to use this directly from the command line, only through tricks as the one suggested by @con-fu-se.
SVN: Is there a way to mark a file as "do not commit"?
If you are on linux, below answer will be useful
Step 1 Create .svnignore
file in root level of your working copy, and add folders/files in each new line(e.g, below)
\.
folder1
folder2
folder3/file2.html
folder4/file1.js
Note: You also need to add \.
as that points to root directory
Tip: To get exact folder/file path, run svn st -u
then copy and paste same path in .svnignore
file
Step 2 Run below command to commit everything except folder/files from .svnignore
file
svn ci -m "YOUR-COMMENT-HERE" $(svn st | grep -v -w -f .svnignore | awk '{print $NF}')
Command Explanation
+-----------------------------------------------------------------------------------------------------------------------------+
¦ svn ci ¦ Shorthand for svn commit ¦
¦--------------------+--------------------------------------------------------------------------------------------------------¦
¦ svn st ¦ Shorthand for svn status ¦
¦--------------------+--------------------------------------------------------------------------------------------------------¦
¦ | ¦ Pipe(|) is used to pass output of previous command to next command's input ¦
¦--------------------+--------------------------------------------------------------------------------------------------------¦
¦ grep ¦ grep is a linux command to filter ¦
¦--------------------+--------------------------------------------------------------------------------------------------------¦
¦ grep -v ¦ Give result other than matched (Inverse) ¦
¦--------------------+--------------------------------------------------------------------------------------------------------¦
¦ grep -w ¦ Exact match(used to match literal Dot(.)) ¦
¦--------------------+--------------------------------------------------------------------------------------------------------¦
¦ grep -f filename ¦ Read pattern from file ¦
¦--------------------+--------------------------------------------------------------------------------------------------------¦
¦ awk '{print $NF}') ¦ print last column data (columns are divided with space delimiter), used to get exact folder/file names ¦
+-----------------------------------------------------------------------------------------------------------------------------+
How to exit a 'git status' list in a terminal?
My preferred combo is Gq
, which prints all diffs and then exits.
You can type h
to show the help commands for interacting with less, which prints this to console:
SUMMARY OF LESS COMMANDS
Commands marked with * may be preceded by a number, N.
Notes in parentheses indicate the behavior if N is given.
h H Display this help.
q :q Q :Q ZZ Exit.
---------------------------------------------------------------------------
MOVING
e ^E j ^N CR * Forward one line (or N lines).
y ^Y k ^K ^P * Backward one line (or N lines).
f ^F ^V SPACE * Forward one window (or N lines).
b ^B ESC-v * Backward one window (or N lines).
z * Forward one window (and set window to N).
w * Backward one window (and set window to N).
ESC-SPACE * Forward one window, but don't stop at end-of-file.
d ^D * Forward one half-window (and set half-window to N).
u ^U * Backward one half-window (and set half-window to N).
ESC-) RightArrow * Left one half screen width (or N positions).
ESC-( LeftArrow * Right one half screen width (or N positions).
F Forward forever; like "tail -f".
r ^R ^L Repaint screen.
R Repaint screen, discarding buffered input.
---------------------------------------------------
Default "window" is the screen height.
Default "half-window" is half of the screen height.
---------------------------------------------------------------------------
SEARCHING
/pattern * Search forward for (N-th) matching line.
?pattern * Search backward for (N-th) matching line.
n * Repeat previous search (for N-th occurrence).
N * Repeat previous search in reverse direction.
ESC-n * Repeat previous search, spanning files.
ESC-N * Repeat previous search, reverse dir. & spanning files.
ESC-u Undo (toggle) search highlighting.
---------------------------------------------------
Search patterns may be modified by one or more of:
^N or ! Search for NON-matching lines.
^E or * Search multiple files (pass thru END OF FILE).
^F or @ Start search at FIRST file (for /) or last file (for ?).
^K Highlight matches, but don't move (KEEP position).
^R Don't use REGULAR EXPRESSIONS.
---------------------------------------------------------------------------
JUMPING
g < ESC-< * Go to first line in file (or line N).
G > ESC-> * Go to last line in file (or line N).
p % * Go to beginning of file (or N percent into file).
t * Go to the (N-th) next tag.
T * Go to the (N-th) previous tag.
{ ( [ * Find close bracket } ) ].
} ) ] * Find open bracket { ( [.
ESC-^F <c1> <c2> * Find close bracket <c2>.
ESC-^B <c1> <c2> * Find open bracket <c1>
---------------------------------------------------
How do I get the name of the current executable in C#?
When uncertain or in doubt, run in circles, scream and shout.
class Ourself
{
public static string OurFileName() {
System.Reflection.Assembly _objParentAssembly;
if (System.Reflection.Assembly.GetEntryAssembly() == null)
_objParentAssembly = System.Reflection.Assembly.GetCallingAssembly();
else
_objParentAssembly = System.Reflection.Assembly.GetEntryAssembly();
if (_objParentAssembly.CodeBase.StartsWith("http://"))
throw new System.IO.IOException("Deployed from URL");
if (System.IO.File.Exists(_objParentAssembly.Location))
return _objParentAssembly.Location;
if (System.IO.File.Exists(System.AppDomain.CurrentDomain.BaseDirectory + System.AppDomain.CurrentDomain.FriendlyName))
return System.AppDomain.CurrentDomain.BaseDirectory + System.AppDomain.CurrentDomain.FriendlyName;
if (System.IO.File.Exists(System.Reflection.Assembly.GetExecutingAssembly().Location))
return System.Reflection.Assembly.GetExecutingAssembly().Location;
throw new System.IO.IOException("Assembly not found");
}
}
I can't claim to have tested each option, but it doesn't do anything stupid like returning the vhost during debugging sessions.
Get Folder Size from Windows Command Line
The following script can be used to fetch and accumulate the size of each file under a given folder.
The folder path %folder%
can be given as an argument to this script (%1
).
Ultimately, the results is held in the parameter %filesize%
@echo off
SET count=1
SET foldersize=0
FOR /f "tokens=*" %%F IN ('dir /s/b %folder%') DO (call :calcAccSize "%%F")
echo %filesize%
GOTO :eof
:calcAccSize
REM echo %count%:%1
REM set /a count+=1
set /a foldersize+=%~z1
GOTO :eof
Note: The method calcAccSize
can also print the content of the folder (commented in the example above)
Execute PowerShell Script from C# with Commandline Arguments
Try creating scriptfile as a separate command:
Command myCommand = new Command(scriptfile);
then you can add parameters with
CommandParameter testParam = new CommandParameter("key","value");
myCommand.Parameters.Add(testParam);
and finally
pipeline.Commands.Add(myCommand);
Here is the complete, edited code:
RunspaceConfiguration runspaceConfiguration = RunspaceConfiguration.Create();
Runspace runspace = RunspaceFactory.CreateRunspace(runspaceConfiguration);
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
//Here's how you add a new script with arguments
Command myCommand = new Command(scriptfile);
CommandParameter testParam = new CommandParameter("key","value");
myCommand.Parameters.Add(testParam);
pipeline.Commands.Add(myCommand);
// Execute PowerShell script
results = pipeline.Invoke();
How do I escape double and single quotes in sed?
The s///
command in sed
allows you to use other characters instead of /
as the delimiter, as in
sed 's#"http://www\.fubar\.com"#URL_FUBAR#g'
or
sed 's,"http://www\.fubar\.com",URL_FUBAR,g'
The double quotes are not a problem. For matching single quotes, switch the two types of quotes around. Note that a single quoted string may not contain single quotes (not even escaped ones).
The dots need to be escaped if sed
is to interpret them as literal dots and not as the regular expression pattern .
which matches any one character.
How to invoke a Linux shell command from Java
Use ProcessBuilder to separate commands and arguments instead of spaces. This should work regardless of shell used:
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(final String[] args) throws IOException, InterruptedException {
//Build command
List<String> commands = new ArrayList<String>();
commands.add("/bin/cat");
//Add arguments
commands.add("/home/narek/pk.txt");
System.out.println(commands);
//Run macro on target
ProcessBuilder pb = new ProcessBuilder(commands);
pb.directory(new File("/home/narek"));
pb.redirectErrorStream(true);
Process process = pb.start();
//Read output
StringBuilder out = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null, previous = null;
while ((line = br.readLine()) != null)
if (!line.equals(previous)) {
previous = line;
out.append(line).append('\n');
System.out.println(line);
}
//Check result
if (process.waitFor() == 0) {
System.out.println("Success!");
System.exit(0);
}
//Abnormal termination: Log command parameters and output and throw ExecutionException
System.err.println(commands);
System.err.println(out.toString());
System.exit(1);
}
}
How do I run a batch script from within a batch script?
Run parallelly on separate command windows in minimized state
dayStart.bat
start "startOfficialSoftwares" /min cmd /k call startOfficialSoftwares.bat
start "initCodingEnvironment" /min cmd /k call initCodingEnvironment.bat
start "updateProjectSource" /min cmd /k call updateProjectSource.bat
start "runCoffeeMachine" /min cmd /k call runCoffeeMachine.bat
Run sequentially on same window
release.bat
call updateDevelVersion.bat
call mergeDevelIntoMaster.bat
call publishProject.bat
Change windows hostname from command line
cmd (command):
netdom renamecomputer %COMPUTERNAME% /Newname "NEW-NAME"
powershell (windows 2008/2012):
netdom renamecomputer "$env:COMPUTERNAME" /Newname "NEW-NAME"
after that, you need to reboot your computer.
Get most recent file in a directory on Linux
ls -lAtr | tail -1
The other solutions do not include files that start with '.'
.
This command will also include '.'
and '..'
, which may or may not be what you want:
ls -latr | tail -1
how to show lines in common (reverse diff)?
In Windows you can use a Powershell Script with CompareObject
compare-object -IncludeEqual -ExcludeDifferent -PassThru (get-content A.txt) (get-content B.txt)> MATCHING.txt | Out-Null #Find Matching Lines
CompareObject:
- IncludeEqual without -ExcludeDifferent : Everything
- ExcludeDifferent without -InclueEqual : Nothing
What's the best way to parse command line arguments?
Just in case you might need to, this may help if you need to grab unicode arguments on Win32 (2K, XP etc):
from ctypes import *
def wmain(argc, argv):
print argc
for i in argv:
print i
return 0
def startup():
size = c_int()
ptr = windll.shell32.CommandLineToArgvW(windll.kernel32.GetCommandLineW(), byref(size))
ref = c_wchar_p * size.value
raw = ref.from_address(ptr)
args = [arg for arg in raw]
windll.kernel32.LocalFree(ptr)
exit(wmain(len(args), args))
startup()
How to test if a file is a directory in a batch script?
One issue with using %%~si\NUL
method is that there is the chance that it guesses wrong. Its possible to have a filename shorten to the wrong file. I don't think %%~si
resolves the 8.3 filename, but guesses it, but using string manipulation to shorten the filepath. I believe if you have similar file paths it may not work.
An alternative method:
dir /AD %F% 2>&1 | findstr /C:"Not Found">NUL:&&(goto IsFile)||(goto IsDir)
:IsFile
echo %F% is a file
goto done
:IsDir
echo %F% is a directory
goto done
:done
You can replace (goto IsFile)||(goto IsDir)
with other batch commands:
(echo Is a File)||(echo is a Directory)
How to switch between python 2.7 to python 3 from command line?
For Windows 7, I just rename the python.exe
from the Python 3 folder to python3.exe
and add the path into the environment variables. Using that, I can execute python test_script.py
and the script runs with Python 2.7 and when I do python3 test_script.py
, it runs the script in Python 3.
To add Python 3
to the environment variables, follow these steps -
- Right Click on My Computer and go to
Properties
.
- Go to
Advanced System Settings
.
- Click on
Environment Variables
and edit PATH
and add the path to your Python 3 installation directory.
For example,
CMD: Export all the screen content to a text file
If your batch file is not interactive and you don't need to see it run then this should work.
@echo off
call file.bat >textfile.txt 2>&1
Otherwise use a tee
filter. There are many, some not NT compatible. SFK the Swiss Army Knife has a tee feature and is still being developed. Maybe that will work for you.
Run function from the command line
Use the python-c tool (pip install python-c) and then simply write:
$ python-c foo 'hello()'
or in case you have no function name clashes in your python files:
$ python-c 'hello()'
Run function in script from command line (Node JS)
simple way:
let's say you have db.js file in a helpers directory in project structure.
now go inside helpers directory and go to node console
helpers $ node
2) require db.js file
> var db = require("./db")
3) call your function (in your case its init())
> db.init()
hope this helps
How to create a database from shell command?
cat filename.sql | mysql -u username -p # type mysql password when asked for it
Where filename.sql holds all the sql to create your database. Or...
echo "create database `database-name`" | mysql -u username -p
If you really only want to create a database.
How can I use xargs to copy files that have spaces and quotes in their names?
Be aware that most of the options discussed in other answers are not standard on platforms that do not use the GNU utilities (Solaris, AIX, HP-UX, for instance). See the POSIX specification for 'standard' xargs behaviour.
I also find the behaviour of xargs whereby it runs the command at least once, even with no input, to be a nuisance.
I wrote my own private version of xargs (xargl) to deal with the problems of spaces in names (only newlines separate - though the 'find ... -print0' and 'xargs -0' combination is pretty neat given that file names cannot contain ASCII NUL '\0' characters. My xargl isn't as complete as it would need to be to be worth publishing - especially since GNU has facilities that are at least as good.
Mysql: Setup the format of DATETIME to 'DD-MM-YYYY HH:MM:SS' when creating a table
As others have explained that it is not possible, but here's alternative solution, it requires a little tuning, but it works like datetime column.
I started to think, how I could make formatting possible. I got an idea. What about making trigger for it? I mean, adding column with type char
, and then updating that column using a MySQL trigger. And that worked! I made some research related to triggers, and finally come up with these queries:
CREATE TRIGGER timestampper BEFORE INSERT ON table
FOR EACH
ROW SET NEW.timestamp = DATE_FORMAT(NOW(), '%d-%m-%Y %H:%i:%s');
CREATE TRIGGER timestampper BEFORE UPDATE ON table
FOR EACH
ROW SET NEW.timestamp = DATE_FORMAT(NOW(), '%d-%m-%Y %H:%i:%s');
You can't use TIMESTAMP
or DATETIME
as a column type, because these have their own format, and they update automatically.
So, here's your alternative timestamp or datetime alternative! Hope this helped, at least I'm glad that I got this working.
Running Command Line in Java
You can also watch the output like this:
final Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");
new Thread(new Runnable() {
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = input.readLine()) != null)
System.out.println(line);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
p.waitFor();
And don't forget, if you are running a windows command, you need to put cmd /c
in front of your command.
EDIT: And for bonus points, you can also use ProcessBuilder
to pass input to a program:
String[] command = new String[] {
"choice",
"/C",
"YN",
"/M",
"\"Press Y if you're cool\""
};
String inputLine = "Y";
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
writer.write(inputLine);
writer.newLine();
writer.close();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
This will run the windows command choice /C YN /M "Press Y if you're cool"
and respond with a Y
. So, the output will be:
Press Y if you're cool [Y,N]?Y
batch file to check 64bit or 32bit OS
Here's my personal favorite, a logical bomb :)
::32/64Bit Switch
ECHO %PROCESSOR_ARCHITECTURE%|FINDSTR AMD64>NUL && SET ARCH=AMD64 || SET ARCH=x86
ECHO %ARCH%
PAUSE
With the AND's (&&
) and OR's (||
) this is a IF THEN ELSE
Batch Construct.
How to resolve "gpg: command not found" error during RVM installation?
On Mac OSX 10.15,
Even after installing gpg, i was getting gpg2 command not found
$ brew install gnupg gnupg2
Warning: gnupg 2.2.23 is already installed and up-to-date
To reinstall 2.2.23, run `brew reinstall gnupg`
$ gpg2 --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
-bash: gpg2: command not found
Instead, this worked for me
$ gpg --keyserver hkp://pool.sks-keyservers.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client
Every once in a while, and this isn't often, but every once in a while, there's a typo in your password. A subtle difference between an upper and lower case letter, for example. I went through many, many of these solutions.
I had simply mistyped the password, and it was saved to my browser, so I didn't think to check it again.
Since this error CAN be caused by a missed password, just double-check before you go on this quest.
"No such file or directory" but it exists
I got this error “No such file or directory”
but it exists because my file was created in Windows and I tried to run it on Ubuntu and the file contained invalid 15\r where ever a new line was there.
I just created a new file truncating unwanted stuff
sleep: invalid time interval ‘15\r’
Try 'sleep --help' for more information.
script.sh: 5: script.sh: /opt/ag/cont: not found
script.sh: 6: script.sh: /opt/ag/cont: not found
root@Ubuntu14:/home/abc12/Desktop# vi script.sh
root@Ubuntu14:/home/abc12/Desktop# od -c script.sh
0000000 # ! / u s r / b i n / e n v b
0000020 a s h \r \n w g e t h t t p : /
0000400 : 4 1 2 0 / \r \n
0000410
root@Ubuntu14:/home/abc12/Desktop# tr -d \\015 < script.sh > script.sh.fixed
root@Ubuntu14:/home/abc12/Desktop# od -c script.sh.fixed
0000000 # ! / u s r / b i n / e n v b
0000020 a s h \n w g e t h t t p : / /
0000400 / \n
0000402
root@Ubuntu14:/home/abc12/Desktop# sh -x script.sh.fixed
How do I use the lines of a file as arguments of a command?
As already mentioned, you can use the backticks or $(cat filename)
.
What was not mentioned, and I think is important to note, is that you must remember that the shell will break apart the contents of that file according to whitespace, giving each "word" it finds to your command as an argument. And while you may be able to enclose a command-line argument in quotes so that it can contain whitespace, escape sequences, etc., reading from the file will not do the same thing. For example, if your file contains:
a "b c" d
the arguments you will get are:
a
"b
c"
d
If you want to pull each line as an argument, use the while/read/do construct:
while read i ; do command_name $i ; done < filename
How do I 'svn add' all unversioned files to SVN?
After spending some time trying to figure out how to recursively add only some of the files, i thought it would be valid to share what did work for me:
FOR /F %F IN ('dir /s /b /a:d') DO svn add --depth=empty "%F"
FOR /F %F IN ('dir /s /b /a *.cs *.csproj *.rpt *.xsd *.resx *.ico *.sql') DO svn add "%F"
Here goes some explanation.
The first command adds all the directories. The second command adds only the files accordingly to the specifed patterns.
Let me give more details:
- FOR: you know, the loop control.
- /F: means take the files and directories (not sure exactly).
- %F: its a variable; it will assume the value of each of the listed files at a time; it could have another one-character-name.
- IN: no need to explain, right?
- ('dir /s /b /a:d'): the DOS command that will list the directories; in my case /s is recursive, /b is to take only the full path, /a:d means only the directory; change it as you wish keeping the parenthesis and apostrophes.
- DO: means that what comes next in the command is what will be executed for each directory
- svn add --depth=empty: it is the desired SVN commando to be run; the depth definition means to add only the directory and not the files inside them.
- "%F": that's how you use the variable defined earlier.
In the second command, the only differences are the dir command and the svn command, i think it is clear enough.
How to pass command-line arguments to a PowerShell ps1 file
After digging through the PowerShell documentation, I discovered some useful information about this issue. You can't use the $args
if you used the param(...)
at the beginning of your file; instead you will need to use $PSBoundParameters
. I copy/pasted your code into a PowerShell script, and it worked as you'd expect in PowerShell version 2 (I am not sure what version you were on when you ran into this issue).
If you are using $PSBoundParameters
(and this ONLY works if you are using param(...)
at the beginning of your script), then it is not an array, it is a hash table, so you will need to reference it using the key / value pair.
param($p1, $p2, $p3, $p4)
$Script:args=""
write-host "Num Args: " $PSBoundParameters.Keys.Count
foreach ($key in $PSBoundParameters.keys) {
$Script:args+= "`$$key=" + $PSBoundParameters["$key"] + " "
}
write-host $Script:args
And when called with...
PS> ./foo.ps1 a b c d
The result is...
Num Args: 4
$p1=a $p2=b $p3=c $p4=d
Windows shell command to get the full path to the current directory?
Quote the Windows help for the set
command (set /?
):
If Command Extensions are enabled, then there are several dynamic
environment variables that can be expanded but which don't show up in
the list of variables displayed by SET. These variable values are
computed dynamically each time the value of the variable is expanded.
If the user explicitly defines a variable with one of these names, then
that definition will override the dynamic one described below:
%CD% - expands to the current directory string.
%DATE% - expands to current date using same format as DATE command.
%TIME% - expands to current time using same format as TIME command.
%RANDOM% - expands to a random decimal number between 0 and 32767.
%ERRORLEVEL% - expands to the current ERRORLEVEL value
%CMDEXTVERSION% - expands to the current Command Processor Extensions
version number.
%CMDCMDLINE% - expands to the original command line that invoked the
Command Processor.
Note the %CD% - expands to the current directory string.
part.
How to use sed to replace only the first occurrence in a file?
The following command removes the first occurrence of a string, within a file. It removes the empty line too. It is presented on an xml file, but it would work with any file.
Useful if you work with xml files and you want to remove a tag. In this example it removes the first occurrence of the "isTag" tag.
Command:
sed -e 0,/'<isTag>false<\/isTag>'/{s/'<isTag>false<\/isTag>'//} -e 's/ *$//' -e '/^$/d' source.txt > output.txt
Source file (source.txt)
<xml>
<testdata>
<canUseUpdate>true</canUseUpdate>
<isTag>false</isTag>
<moduleLocations>
<module>esa_jee6</module>
<isTag>false</isTag>
</moduleLocations>
<node>
<isTag>false</isTag>
</node>
</testdata>
</xml>
Result file (output.txt)
<xml>
<testdata>
<canUseUpdate>true</canUseUpdate>
<moduleLocations>
<module>esa_jee6</module>
<isTag>false</isTag>
</moduleLocations>
<node>
<isTag>false</isTag>
</node>
</testdata>
</xml>
ps: it didn't work for me on Solaris SunOS 5.10 (quite old), but it works on Linux 2.6, sed version 4.1.5
Way to run Excel macros from command line or batch file?
If you're more comfortable working inside Excel/VBA, use the open event and test the environment: either have a signal file, a registry entry or an environment variable that controls what the open event does.
You can create the file/setting outside and test inside (use GetEnviromentVariable for env-vars) and test easily. I've written VBScript but the similarities to VBA cause me more angst than ease..
[more]
As I understand the problem, you want to use a spreadsheet normally most/some of the time yet have it run in batch and do something extra/different. You can open the sheet from the excel.exe command line but you can't control what it does unless it knows where it is. Using an environment variable is relatively simple and makes testing the spreadsheet easy.
To clarify, use the function below to examine the environment. In a module declare:
Private Declare Function GetEnvVar Lib "kernel32" Alias "GetEnvironmentVariableA" _
(ByVal lpName As String, ByVal lpBuffer As String, ByVal nSize As Long) As Long
Function GetEnvironmentVariable(var As String) As String
Dim numChars As Long
GetEnvironmentVariable = String(255, " ")
numChars = GetEnvVar(var, GetEnvironmentVariable, 255)
End Function
In the Workbook open event (as others):
Private Sub Workbook_Open()
If GetEnvironmentVariable("InBatch") = "TRUE" Then
Debug.Print "Batch"
Else
Debug.Print "Normal"
End If
End Sub
Add in active code as applicable. In the batch file, use
set InBatch=TRUE
How to run .NET Core console app from the command line
You can also run your app like any other console applications but only after the publish.
Let's suppose you have the simple console app named MyTestConsoleApp.
Open the package manager console and run the following command:
dotnet publish -c Debug -r win10-x64
-c flag mean that you want to use the debug configuration (in other case you should use Release value)
- r flag mean that your application will be runned on Windows platform with x64 architecture.
When the publish procedure will be finished your will see the *.exe file located in your bin/Debug/publish directory.
Now you can call it via command line tools. So open the CMD window (or terminal) move to the directory where your *.exe file is located and write the next command:
>> MyTestConsoleApp.exe argument-list
For example:
>> MyTestConsoleApp.exe --input some_text -r true
How to best display in Terminal a MySQL SELECT returning too many fields?
Using mysql
's ego
command
From mysql
's help
command:
ego (\G) Send command to mysql server, display result vertically.
So by appending a \G
to your select
, you can get a very clean vertical output:
mysql> SELECT * FROM sometable \G
Using a pager
You can tell MySQL to use the less
pager with its -S
option that chops wide lines and gives you an output that you can scroll with the arrow keys:
mysql> pager less -S
Thus, next time you run a command with a wide output, MySQL will let you browse the output with the less
pager:
mysql> SELECT * FROM sometable;
If you're done with the pager and want to go back to the regular output on stdout
, use this:
mysql> nopager
How to execute powershell commands from a batch file?
Looking for the possibility to put a powershell script into a batch file, I found this thread. The idea of walid2mi did not worked 100% for my script. But via a temporary file, containing the script it worked out. Here is the skeleton of the batch file:
;@echo off
;setlocal ENABLEEXTENSIONS
;rem make from X.bat a X.ps1 by removing all lines starting with ';'
;Findstr -rbv "^[;]" %0 > %~dpn0.ps1
;powershell -ExecutionPolicy Unrestricted -File %~dpn0.ps1 %*
;del %~dpn0.ps1
;endlocal
;goto :EOF
;rem Here start your power shell script.
param(
,[switch]$help
)
How can I get the current date and time in the terminal and set a custom command in the terminal for it?
You can use date
to get time and date of a day:
[pengyu@GLaDOS ~]$date
Tue Aug 27 15:01:27 CST 2013
Also hwclock
would do:
[pengyu@GLaDOS ~]$hwclock
Tue 27 Aug 2013 03:01:29 PM CST -0.516080 seconds
For customized output, you can either redirect the output of date
to something like awk
, or write your own program to do that.
Remember to put your own executable scripts/binary into your PATH
(e.g. /usr/bin) to make it invokable anywhere.
Can't find/install libXtst.so.6?
EDIT: As mentioned by Stephen Niedzielski in his comment, the issue seems to come from the 32-bit being of the JRE, which is de facto, looking for the 32-bit version of libXtst6
. To install the required version of the library:
$ sudo apt-get install libxtst6:i386
Type:
$ sudo apt-get update
$ sudo apt-get install libxtst6
If this isn’t OK, type:
$ sudo updatedb
$ locate libXtst
it should return something like:
/usr/lib/x86_64-linux-gnu/libXtst.so.6 # Mine is OK
/usr/lib/x86_64-linux-gnu/libXtst.so.6.1.0
If you do not have libXtst.so.6
but do have libXtst.so.6.X.X
create a symbolic link:
$ cd /usr/lib/x86_64-linux-gnu/
$ ln -s libXtst.so.6 libXtst.so.6.X.X
Hope this helps.
Running CMD command in PowerShell
To run or convert batch files externally from PowerShell (particularly if you wish to sign all your scheduled task scripts with a certificate) I simply create a PowerShell script, e.g. deletefolders.ps1.
Input the following into the script:
cmd.exe /c "rd /s /q C:\#TEMP\test1"
cmd.exe /c "rd /s /q C:\#TEMP\test2"
cmd.exe /c "rd /s /q C:\#TEMP\test3"
*Each command needs to be put on a new line calling cmd.exe again.
This script can now be signed and run from PowerShell outputting the commands to command prompt / cmd
directly.
It is a much safer way than running batch files!
How to do a HTTP HEAD request from the windows command line?
If you cannot install aditional applications, then you can telnet (you will need to install this feature for your windows 7 by following this) the remote server:
TELNET server_name 80
followed by:
HEAD /virtual/directory/file.ext
or
GET /virtual/directory/file.ext
depending on if you want just the header (HEAD) or the full contents (GET)
Angular - ng: command not found
Try uninstalling the angular cli installed
npm uninstall -g angular-cli
npm uninstall -g @angular/cli
The clean the node cache
npm cache clean
Then
npm install -g @angular/cli@latest
set Path the path
C:\Users\admin\AppData\Roaming\npm\node_modules@angular\cli
Linux command to print directory structure in the form of a tree
You can use this one:
ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'
It will show a graphical representation of the current sub-directories without files in a few seconds, e.g. in /var/cache/:
.
|-apache2
|---mod_cache_disk
|-apparmor
|-apt
|---archives
|-----partial
|-apt-xapian-index
|---index.1
|-dbconfig-common
|---backups
|-debconf
Source
fatal: This operation must be run in a work tree
You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree
option for single commands, or the GIT_WORK_TREE
environment variable. There is also the core.worktree
configuration option but it will not work in a bare repository (check the man page for what it does).
# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status
Execute multiple command lines with the same process using .NET
You can redirect standard input and use a StreamWriter to write to it:
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
using (StreamWriter sw = p.StandardInput)
{
if (sw.BaseStream.CanWrite)
{
sw.WriteLine("mysql -u root -p");
sw.WriteLine("mypassword");
sw.WriteLine("use mydb;");
}
}
Input from the keyboard in command line application
Swift 5 : If you continuously want input from keyboard , without ending the program, like a stream of input, Use below steps:
Create new project of type comnnad line tool
Add below code in main.swift file:
var inputArray = [String]()
while let input = readLine() {
guard input != "quit" else {
break
}
inputArray.append(input)
print("You entered: \(input)")
print(inputArray)
print("Enter a word:")
}
- RunThe project and click the executable under Products folder in Xcode and open in finder
- Double click the executable to open it.
- Now enter your Inputs. Terminal will look something like this:
Is there a command line utility for rendering GitHub flavored Markdown?
I've not found a quick and easy method for GitHub-flavoured Markdown, but I have found a slightly more generic version - Pandoc. It converts from/to a number of formats, including Markdown, Rest, HTML and others.
I've also developed a Makefile
to convert all .md files to .html (in large part to the example at Writing, Markdown and Pandoc):
# 'Makefile'
MARKDOWN = pandoc --from gfm --to html --standalone
all: $(patsubst %.md,%.html,$(wildcard *.md)) Makefile
clean:
rm -f $(patsubst %.md,%.html,$(wildcard *.md))
rm -f *.bak *~
%.html: %.md
$(MARKDOWN) $< --output $@
Using command line arguments in VBscript
Set args = Wscript.Arguments
For Each arg In args
Wscript.Echo arg
Next
From a command prompt, run the script like this:
CSCRIPT MyScript.vbs 1 2 A B "Arg with spaces"
Will give results like this:
1
2
A
B
Arg with spaces
How to change the output color of echo in Linux
I've written swag to achieve just that.
You can just do
pip install swag
Now you can install all the escape commands as txt files to a given destination via:
swag install -d <colorsdir>
Or even easier via:
swag install
Which will install the colors to ~/.colors
.
Either you use them like this:
echo $(cat ~/.colors/blue.txt) This will be blue
Or this way, which I find actually more interesting:
swag print -c red -t underline "I will turn red and be underlined"
Check it out on asciinema!
Matlab: Running an m-file from command-line
Here are the steps:
- Start the command line.
- Enter the folder containing the .m file with
cd C:\M1\M2\M3
- Run the following:
C:\E1\E2\E3\matlab.exe -r mfile
Windows systems will use your current folder as the location for MATLAB to search for .m files, and the -r
option tries to start the given .m file as soon as startup occurs.
PostgreSQL psql terminal command
Use \x
Example from postgres manual:
postgres=# \x
postgres=# SELECT * FROM pg_stat_statements ORDER BY total_time DESC LIMIT 3;
-[ RECORD 1 ]------------------------------------------------------------
userid | 10
dbid | 63781
query | UPDATE branches SET bbalance = bbalance + $1 WHERE bid = $2;
calls | 3000
total_time | 20.716706
rows | 3000
-[ RECORD 2 ]------------------------------------------------------------
userid | 10
dbid | 63781
query | UPDATE tellers SET tbalance = tbalance + $1 WHERE tid = $2;
calls | 3000
total_time | 17.1107649999999
rows | 3000
-[ RECORD 3 ]------------------------------------------------------------
userid | 10
dbid | 63781
query | UPDATE accounts SET abalance = abalance + $1 WHERE aid = $2;
calls | 3000
total_time | 0.645601
rows | 3000
How can I pass a file argument to my bash script using a Terminal command in Linux?
It'll be easier (and more "proper", see below) if you just run your script as
myprogram /path/to/file
Then you can access the path within the script as $1
(for argument #1, similarly $2
is argument #2, etc.)
file="$1"
externalprogram "$file" [other parameters]
Or just
externalprogram "$1" [otherparameters]
If you want to extract the path from something like --file=/path/to/file
, that's usually done with the getopts
shell function. But that's more complicated than just referencing $1
, and besides, switches like --file=
are intended to be optional. I'm guessing your script requires a file name to be provided, so it doesn't make sense to pass it in an option.
Show a popup/message box from a Windows batch file
This application can do that, if you convert (wrap) your batch files into executable files.
Simple Messagebox
%extd% /messagebox Title Text
Error Messagebox
%extd% /messagebox Error "Error message" 16
Cancel Try Again Messagebox
%extd% /messagebox Title "Try again or Cancel" 5
4) "Never ask me again" Messagebox
%extd% /messageboxcheck Title Message 0 {73E8105A-7AD2-4335-B694-94F837A38E79}
Running command line silently with VbScript and getting output?
Dim path As String = GetFolderPath(SpecialFolder.ApplicationData)
Dim filepath As String = path + "\" + "your.bat"
' Create the file if it does not exist.
If File.Exists(filepath) = False Then
File.Create(filepath)
Else
End If
Dim attributes As FileAttributes
attributes = File.GetAttributes(filepath)
If (attributes And FileAttributes.ReadOnly) = FileAttributes.ReadOnly Then
' Remove from Readonly the file.
attributes = RemoveAttribute(attributes, FileAttributes.ReadOnly)
File.SetAttributes(filepath, attributes)
Console.WriteLine("The {0} file is no longer RO.", filepath)
Else
End If
If (attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
' Show the file.
attributes = RemoveAttribute(attributes, FileAttributes.Hidden)
File.SetAttributes(filepath, attributes)
Console.WriteLine("The {0} file is no longer Hidden.", filepath)
Else
End If
Dim sr As New StreamReader(filepath)
Dim input As String = sr.ReadToEnd()
sr.Close()
Dim output As String = "@echo off"
Dim output1 As String = vbNewLine + "your 1st cmd code"
Dim output2 As String = vbNewLine + "your 2nd cmd code "
Dim output3 As String = vbNewLine + "exit"
Dim sw As New StreamWriter(filepath)
sw.Write(output)
sw.Write(output1)
sw.Write(output2)
sw.Write(output3)
sw.Close()
If (attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
Else
' Hide the file.
File.SetAttributes(filepath, File.GetAttributes(filepath) Or FileAttributes.Hidden)
Console.WriteLine("The {0} file is now hidden.", filepath)
End If
Dim procInfo As New ProcessStartInfo(path + "\" + "your.bat")
procInfo.WindowStyle = ProcessWindowStyle.Minimized
procInfo.WindowStyle = ProcessWindowStyle.Hidden
procInfo.CreateNoWindow = True
procInfo.FileName = path + "\" + "your.bat"
procInfo.Verb = "runas"
Process.Start(procInfo)
it saves your .bat file to "Appdata of current user" ,if it does not exist and remove the attributes
and after that set the "hidden" attributes to file after writing your cmd code
and run it silently and capture all output saves it to file
so if u wanna save all output of cmd to file just add your like this
code > C:\Users\Lenovo\Desktop\output.txt
just replace word "code" with your .bat file code or command and after that the directory of output file
I found one code recently after searching alot
if u wanna run .bat file in vb or c# or simply
just add this in the same manner in which i have written
Run a JAR file from the command line and specify classpath
Alternatively, use the manifest to specify the class-path and main-class if you like, so then you don't need to use -cp
or specify the main class. In your case it would contain lines like this:
Main-Class: com.test.App
Class-Path: lib/one.jar lib/two.jar
Unfortunately you need to spell out each jar in the manifest (not a biggie as you only do once, and you can use a script to build the file or use a build tool like ANT or Maven or Gradle). And the reference has to be a relative or absolute directory to where you run the java -jar MyJar.jar
.
Then execute it with
java -jar MyJar.jar
Get DOS path instead of Windows path
Kimbo's answer is perfect for normal files.
for %I in (.) do echo %~sI
For MsDos file names on HardLinks
The hard links created with mklink /H <link> <target>
will not have an MsDos short file name.
In case you dir /X
and you discover that missing short name you should expect the followings:
d:\personal\photos-tofix\2013-proposed1-bad>dir /X
Volume in drive D has no label.
Volume Serial Number is 7C7E-04BA
Directory of d:\personal\photos-tofix\2013-proposed1-bad
03/02/2015 15:15 <DIR> .
03/02/2015 15:15 <DIR> ..
22/12/2013 12:10 1,948,654 2013-1~1.JPG 2013-12-22--12-10-42------Bulevardul-Petrochimi?tilor.jpg
22/12/2013 12:10 1,899,739 2013-12-22--12-10-52------Bulevardul Petrochimi?tilor.jpg
Normal file
In this case
> for %I in ("2013-12-22--12-10-42------Bulevardul-Petrochimi?tilor.jpg") do echo %~sI
I've got what I expected
d:\personal\PH124E~1\2013-P~3\2013-1~1.JPG
Hard link file
In this case
> for %I in ("2013-12-22--12-10-52------Bulevardul-Petrochimi?tilor.jpg") do echo %~sI
I've got the normal MsDos path but the normal filename.
d:\personal\PH124E~1\2013-P~3\2013-12-22--12-10-52------Bulevardul-Petrochimi?tilor.jpg`
run a python script in terminal without the python command
There are three parts:
- Add a 'shebang' at the top of your script which tells how to execute your script
- Give the script 'run' permissions.
- Make the script in your PATH so you can run it from anywhere.
Adding a shebang
You need to add a shebang at the top of your script so the shell knows which interpreter to use when parsing your script. It is generally:
#!path/to/interpretter
To find the path to your python interpretter on your machine you can run the command:
which python
This will search your PATH to find the location of your python executable. It should come back with a absolute path which you can then use to form your shebang. Make sure your shebang is at the top of your python script:
#!/usr/bin/python
Run Permissions
You have to mark your script with run permissions so that your shell knows you want to actually execute it when you try to use it as a command. To do this you can run this command:
chmod +x myscript.py
Add the script to your path
The PATH environment variable is an ordered list of directories that your shell will search when looking for a command you are trying to run. So if you want your python script to be a command you can run from anywhere then it needs to be in your PATH. You can see the contents of your path running the command:
echo $PATH
This will print out a long line of text, where each directory is seperated by a semicolon. Whenever you are wondering where the actual location of an executable that you are running from your PATH, you can find it by running the command:
which <commandname>
Now you have two options: Add your script to a directory already in your PATH, or add a new directory to your PATH. I usually create a directory in my user home directory and then add it the PATH. To add things to your path you can run the command:
export PATH=/my/directory/with/pythonscript:$PATH
Now you should be able to run your python script as a command anywhere. BUT! if you close the shell window and open a new one, the new one won't remember the change you just made to your PATH. So if you want this change to be saved then you need to add that command at the bottom of your .bashrc or .bash_profile
How do you extract IP addresses from files using a regex in a linux shell?
Most of the examples here will match on 999.999.999.999 which is not technically a valid IP address.
The following will match on only valid IP addresses (including network and broadcast addresses).
grep -E -o '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' file.txt
Omit the -o if you want to see the entire line that matched.
BAT file: Open new cmd window and execute a command in there
You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.
What I found out was to use the K switch like this:
start cmd /k echo Hello, World!
start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.
You can also use the /C switch for something similar.
start cmd /C pause
This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.
Use the following in your batch file:
start cmd.exe /c "more-batch-commands-here"
or
start cmd.exe /k "more-batch-commands-here"
/c Carries out the command
specified by string and then
terminates
/k Carries out the
command specified by string but
remains
The /c
and /k
options controls what happens once your command finishes running. With /c
the terminal window will close automatically, leaving your desktop clean. With /k
the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.
Consult the cmd.exe documentation using cmd /?
for more details.
Escaping Commands with White Spaces
The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.
Examples:
Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt
Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"
Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""
Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""
Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""
Source: http://ss64.com/nt/cmd.html
Run C++ in command prompt - Windows
have MinGW compiler bin directory added to path.
use mingw32-g++ -s -c source_file_name.cpp -o output_file_name.o
to compile
then mingw32-g++ -o executable_file_name.exe output_file_name.o
to build exe
finally, you run with executable_file_name.exe
Maximum Length of Command Line String
Sorry for digging out an old thread, but I think sunetos' answer isn't correct (or isn't the full answer). I've done some experiments (using ProcessStartInfo in c#) and it seems that the 'arguments' string for a commandline command is limited to 2048 characters in XP and 32768 characters in Win7. I'm not sure what the 8191 limit refers to, but I haven't found any evidence of it yet.
Best way to parse command-line parameters?
This is largely a shameless clone of my answer to the Java question of the same topic. It turns out that JewelCLI is Scala-friendly in that it doesn't require JavaBean style methods to get automatic argument naming.
JewelCLI is a Scala-friendly Java library for command-line parsing that yields clean code. It uses Proxied Interfaces Configured with Annotations to dynamically build a type-safe API for your command-line parameters.
An example parameter interface Person.scala
:
import uk.co.flamingpenguin.jewel.cli.Option
trait Person {
@Option def name: String
@Option def times: Int
}
An example usage of the parameter interface Hello.scala
:
import uk.co.flamingpenguin.jewel.cli.CliFactory.parseArguments
import uk.co.flamingpenguin.jewel.cli.ArgumentValidationException
object Hello {
def main(args: Array[String]) {
try {
val person = parseArguments(classOf[Person], args:_*)
for (i <- 1 to (person times))
println("Hello " + (person name))
} catch {
case e: ArgumentValidationException => println(e getMessage)
}
}
}
Save copies of the files above to a single directory and download the JewelCLI 0.6 JAR to that directory as well.
Compile and run the example in Bash on Linux/Mac OS X/etc.:
scalac -cp jewelcli-0.6.jar:. Person.scala Hello.scala
scala -cp jewelcli-0.6.jar:. Hello --name="John Doe" --times=3
Compile and run the example in the Windows Command Prompt:
scalac -cp jewelcli-0.6.jar;. Person.scala Hello.scala
scala -cp jewelcli-0.6.jar;. Hello --name="John Doe" --times=3
Running the example should yield the following output:
Hello John Doe
Hello John Doe
Hello John Doe
How to append the output to a file?
Yeah.
command >> file
to redirect just stdout of command
.
command >> file 2>&1
to redirect stdout and stderr to the file (works in bash, zsh)
And if you need to use sudo
, remember that just
sudo command >> /file/requiring/sudo/privileges
does not work, as privilege elevation applies to command
but not shell redirection part. However, simply using
tee
solves the problem:
command | sudo tee -a /file/requiring/sudo/privileges
How can I pretty-print JSON in a shell script?
For Node.js you can also use the "util" module. It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets.
cat file.json | node -e "process.stdin.pipe(new require('stream').Writable({write: chunk => {console.log(require('util').inspect(JSON.parse(chunk), {depth: null, colors: true}))}}))"
Print execution time of a shell command
If I'm starting a long-running process like a copy or hash and I want to know later how long it took, I just do this:
$ date; sha1sum reallybigfile.txt; date
Which will result in the following output:
Tue Jun 2 21:16:03 PDT 2015
5089a8e475cc41b2672982f690e5221469390bc0 reallybigfile.txt
Tue Jun 2 21:33:54 PDT 2015
Granted, as implemented here it isn't very precise and doesn't calculate the elapsed time. But it's dirt simple and sometimes all you need.
What is your single most favorite command-line trick using Bash?
When running commands, sometimes I'll want to run a command with the previous ones arguments. To do that, you can use this shortcut:
$ mkdir /tmp/new
$ cd !!:*
Occasionally, in lieu of using find, I'll break-out a one-line loop if I need to run a bunch of commands on a list of files.
for file in *.wav; do lame "$file" "$(basename "$file" .wav).mp3" ; done;
Configuring the command-line history options in my .bash_login (or .bashrc) is really useful. The following is a cadre of settings that I use on my Macbook Pro.
Setting the following makes bash erase duplicate commands in your history:
export HISTCONTROL="erasedups:ignoreboth"
I also jack my history size up pretty high too. Why not? It doesn't seem to slow anything down on today's microprocessors.
export HISTFILESIZE=500000
export HISTSIZE=100000
Another thing that I do is ignore some commands from my history. No need to remember the exit command.
export HISTIGNORE="&:[ ]*:exit"
You definitely want to set histappend. Otherwise, bash overwrites your history when you exit.
shopt -s histappend
Another option that I use is cmdhist. This lets you save multi-line commands to the history as one command.
shopt -s cmdhist
Finally, on Mac OS X (if you're not using vi mode), you'll want to reset <CTRL>-S from being scroll stop. This prevents bash from being able to interpret it as forward search.
stty stop ""
Compiling/Executing a C# Source File in Command Prompt
In Windows systems, use the command csc <filname>.cs
in the command prompt while the current directory is in Microsoft Visual Studio\<Year>\<Version>
There are two ways:
Using the command prompt:
- Start --> Command Prompt
- Change the directory to Visual Studio folder, using the command: cd C:\Program Files (x86)\Microsoft Visual Studio\2017\ <Version>
- Use the command: csc /.cs
Using Developer Command Prompt :
Start --> Developer Command Prompt for VS 2017
(Here the directory is already set to Visual Studio folder)
Use the command: csc /.cs
Hope it helps!
How to tell if JRE or JDK is installed
@maciej-cygan described the process well, however in order to find your java path:
$ which java
it gives you the path of java
binary file which is a linked file in /usr/bin
directory. next:
$ cd /usr/bin/ && ls -la | grep java
find the pointed location which is something as follows (for me):
then cd
to the pointed directory to find the real home directory for Java. next:
$ ls -la | grep java
which is as follows in this case:
so as it's obvious in the screenshot, my Java home directory is /usr/lib/jvm/java-11-openjdk-amd64
. So accordingly I need to add JAVA_HOME to my bash profile (.bashrc
, .bash_profile
, etc. depending on your OS) like below:
JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"
Here you go!
How can I use goto in Javascript?
Sure, using the switch
construct you can simulate goto
in JavaScript. Unfortunately, the language doesn't provide goto
, but this is a good enough of a replacement.
let counter = 10
function goto(newValue) {
counter = newValue
}
while (true) {
switch (counter) {
case 10: alert("RINSE")
case 20: alert("LATHER")
case 30: goto(10); break
}
}
How do you remove an array element in a foreach loop?
Instead of doing foreach() loop on the array, it would be faster to use array_search() to find the proper key. On small arrays, I would go with foreach for better readibility, but for bigger arrays, or often executed code, this should be a bit more optimal:
$result=array_search($unwantedValue,$array,true);
if($result !== false) {
unset($array[$result]);
}
The strict comparsion operator !== is needed, because array_search() can return 0 as the index of the $unwantedValue.
Also, the above example will remove just the first value $unwantedValue, if the $unwantedValue can occur more then once in the $array, You should use array_keys(), to find all of them:
$result=array_keys($array,$unwantedValue,true)
foreach($result as $key) {
unset($array[$key]);
}
Check http://php.net/manual/en/function.array-search.php for more information.
Connect HTML page with SQL server using javascript
Before The execution of following code, I assume you have created a database and a table (with columns Name (varchar), Age(INT) and Address(varchar)) inside that database. Also please update your SQL Server name , UserID, password, DBname and table name in the code below.
In the code. I have used VBScript and embedded it in HTML.
Try it out!
<!DOCTYPE html>
<html>
<head>
<script type="text/vbscript">
<!--
Sub Submit_onclick()
Dim Connection
Dim ConnString
Dim Recordset
Set connection=CreateObject("ADODB.Connection")
Set Recordset=CreateObject("ADODB.Recordset")
ConnString="DRIVER={SQL Server};SERVER=*YourSQLserverNameHere*;UID=*YourUserIdHere*;PWD=*YourpasswordHere*;DATABASE=*YourDBNameHere*"
Connection.Open ConnString
dim form1
Set form1 = document.Register
Name1 = form1.Name.value
Age1 = form1.Age.Value
Add1 = form1.address.value
connection.execute("INSERT INTO [*YourTableName*] VALUES ('"&Name1 &"'," &Age1 &",'"&Add1 &"')")
End Sub
//-->
</script>
</head>
<body>
<h2>Please Fill details</h2><br>
<p>
<form name="Register">
<pre>
<font face="Times New Roman" size="3">Please enter the log in credentials:<br>
Name: <input type="text" name="Name">
Age: <input type="text" name="Age">
Address: <input type="text" name="address">
<input type="button" id ="Submit" value="submit" /><font></form>
</p>
</pre>
</body>
</html>
Convert java.util.Date to java.time.LocalDate
Better way is:
Date date = ...;
Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()).toLocalDate()
Advantages of this version:
works regardless the input is an instance of java.util.Date
or it's a subclass of java.sql.Date
(unlike @JodaStephen's way). This is common with JDBC-originated data. java.sql.Date.toInstant()
always throws an exception.
it's the same for JDK8 and JDK7 with JSR-310 backport
I personally use an utility class (but it is not backport-compatible):
/**
* Utilities for conversion between the old and new JDK date types
* (between {@code java.util.Date} and {@code java.time.*}).
*
* <p>
* All methods are null-safe.
*/
public class DateConvertUtils {
/**
* Calls {@link #asLocalDate(Date, ZoneId)} with the system default time zone.
*/
public static LocalDate asLocalDate(java.util.Date date) {
return asLocalDate(date, ZoneId.systemDefault());
}
/**
* Creates {@link LocalDate} from {@code java.util.Date} or it's subclasses. Null-safe.
*/
public static LocalDate asLocalDate(java.util.Date date, ZoneId zone) {
if (date == null)
return null;
if (date instanceof java.sql.Date)
return ((java.sql.Date) date).toLocalDate();
else
return Instant.ofEpochMilli(date.getTime()).atZone(zone).toLocalDate();
}
/**
* Calls {@link #asLocalDateTime(Date, ZoneId)} with the system default time zone.
*/
public static LocalDateTime asLocalDateTime(java.util.Date date) {
return asLocalDateTime(date, ZoneId.systemDefault());
}
/**
* Creates {@link LocalDateTime} from {@code java.util.Date} or it's subclasses. Null-safe.
*/
public static LocalDateTime asLocalDateTime(java.util.Date date, ZoneId zone) {
if (date == null)
return null;
if (date instanceof java.sql.Timestamp)
return ((java.sql.Timestamp) date).toLocalDateTime();
else
return Instant.ofEpochMilli(date.getTime()).atZone(zone).toLocalDateTime();
}
/**
* Calls {@link #asUtilDate(Object, ZoneId)} with the system default time zone.
*/
public static java.util.Date asUtilDate(Object date) {
return asUtilDate(date, ZoneId.systemDefault());
}
/**
* Creates a {@link java.util.Date} from various date objects. Is null-safe. Currently supports:<ul>
* <li>{@link java.util.Date}
* <li>{@link java.sql.Date}
* <li>{@link java.sql.Timestamp}
* <li>{@link java.time.LocalDate}
* <li>{@link java.time.LocalDateTime}
* <li>{@link java.time.ZonedDateTime}
* <li>{@link java.time.Instant}
* </ul>
*
* @param zone Time zone, used only if the input object is LocalDate or LocalDateTime.
*
* @return {@link java.util.Date} (exactly this class, not a subclass, such as java.sql.Date)
*/
public static java.util.Date asUtilDate(Object date, ZoneId zone) {
if (date == null)
return null;
if (date instanceof java.sql.Date || date instanceof java.sql.Timestamp)
return new java.util.Date(((java.util.Date) date).getTime());
if (date instanceof java.util.Date)
return (java.util.Date) date;
if (date instanceof LocalDate)
return java.util.Date.from(((LocalDate) date).atStartOfDay(zone).toInstant());
if (date instanceof LocalDateTime)
return java.util.Date.from(((LocalDateTime) date).atZone(zone).toInstant());
if (date instanceof ZonedDateTime)
return java.util.Date.from(((ZonedDateTime) date).toInstant());
if (date instanceof Instant)
return java.util.Date.from((Instant) date);
throw new UnsupportedOperationException("Don't know hot to convert " + date.getClass().getName() + " to java.util.Date");
}
/**
* Creates an {@link Instant} from {@code java.util.Date} or it's subclasses. Null-safe.
*/
public static Instant asInstant(Date date) {
if (date == null)
return null;
else
return Instant.ofEpochMilli(date.getTime());
}
/**
* Calls {@link #asZonedDateTime(Date, ZoneId)} with the system default time zone.
*/
public static ZonedDateTime asZonedDateTime(Date date) {
return asZonedDateTime(date, ZoneId.systemDefault());
}
/**
* Creates {@link ZonedDateTime} from {@code java.util.Date} or it's subclasses. Null-safe.
*/
public static ZonedDateTime asZonedDateTime(Date date, ZoneId zone) {
if (date == null)
return null;
else
return asInstant(date).atZone(zone);
}
}
The asLocalDate()
method here is null-safe, uses toLocalDate()
, if input is java.sql.Date
(it may be overriden by the JDBC driver to avoid timezone problems or unnecessary calculations), otherwise uses the abovementioned method.
How to find locked rows in Oracle
Rather than locks, I suggest you look at long-running transactions, using v$transaction
. From there you can join to v$session
, which should give you an idea about the UI (try the program and machine columns) as well as the user.
Qt jpg image display
#include ...
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
QGraphicsPixmapItem item(QPixmap("c:\\test.png"));
scene.addItem(&item);
view.show();
return a.exec();
}
This should work. :) List of supported formats can be found here
In Oracle, is it possible to INSERT or UPDATE a record through a view?
Views in Oracle may be updateable under specific conditions. It can be tricky, and usually is not advisable.
From the Oracle 10g SQL Reference:
Notes on Updatable Views
An updatable view is one you can use to insert, update, or delete base table rows. You can create a view to be inherently updatable, or you can create an INSTEAD OF trigger on any view to make it updatable.
To learn whether and in what ways the columns of an inherently updatable view can be modified, query the USER_UPDATABLE_COLUMNS data dictionary view. The information displayed by this view is meaningful only for inherently updatable views. For a view to be inherently updatable, the following conditions must be met:
- Each column in the view must map to a column of a single table. For example, if a view column maps to the output of a TABLE clause (an unnested collection), then the view is not inherently updatable.
- The view must not contain any of the following constructs:
- A set operator
- a DISTINCT operator
- An aggregate or analytic function
- A GROUP BY, ORDER BY, MODEL, CONNECT BY, or START WITH clause
- A collection expression in a SELECT list
- A subquery in a SELECT list
- A subquery designated WITH READ ONLY
- Joins, with some exceptions, as documented in Oracle Database Administrator's Guide
In addition, if an inherently updatable view contains pseudocolumns or expressions, then you cannot update base table rows with an UPDATE statement that refers to any of these pseudocolumns or expressions.
If you want a join view to be updatable, then all of the following conditions must be true:
- The DML statement must affect only one table underlying the join.
- For an INSERT statement, the view must not be created WITH CHECK OPTION, and all columns into which values are inserted must come from a key-preserved table. A key-preserved table is one for which every primary key or unique key value in the base table is also unique in the join view.
- For an UPDATE statement, all columns updated must be extracted from a key-preserved table. If the view was created WITH CHECK OPTION, then join columns and columns taken from tables that are referenced more than once in the view must be shielded from UPDATE.
- For a DELETE statement, if the join results in more than one key-preserved table, then Oracle Database deletes from the first table named in the FROM clause, whether or not the view was created WITH CHECK OPTION.
Swapping pointers in C (char, int)
This example does not swap two int pointers. It swaps the value of the integers that pa
and pb
are pointing to. Here's an example of what's going on when you call this:
void Swap1 (int *pa, int *pb){
int temp = *pa;
*pa = *pb;
*pb = temp;
}
int main()
{
int a = 42;
int b = 17;
int *pa = &a;
int *pb = &b;
printf("--------Swap1---------\n");
printf("a = %d\n b = %d\n", a, b);
swap1(pa, pb);
printf("a = %d\n = %d\n", a, a);
printf("pb address = %p\n", pa);
printf("pa address = %p\n", pb);
}
The output here is:
a = 42
b = 17
pa address = 0x7fffdf933228
pb address = 0x7fffdf93322c
--------Swap---------
pa = 17
pb = 42
a = 17
b = 42
pa address = 0x7fffdf933228
pb address = 0x7fffdf93322c
Note that the values swapped, but the pointer's addresses did not swap!
In order to swap addresses we need to do this:
void swap2 (int **pa, int **pb){
int temp = *pa;
*pa = *pb;
*pb = temp;
}
and in main call the function like swap2(&pa, &pb);
Now the addresses are swapped, as well as the values for the pointers. a
and b
have the same values that the are initialized with The integers a and b did not swap because it swap2
swaps the addresses being being pointed to by the pointers!:
a = 42
b = 17
pa address = 0x7fffddaa9c98
pb address = 0x7fffddaa9c9c
--------Swap---------
pa = 17
pb = 42
a = 42
b = 17
pa address = 0x7fffddaa9c9c
pb address = 0x7fffddaa9c98
Since Strings in C are char pointers, and you want to swap Strings, you are really swapping a char pointer. As in the examples with an int, you need a double pointer to swap addresses.
The values of integers can be swapped even if the address isn't, but Strings are by definition a character pointer. You could swap one char with single pointers as the parameter, but a character pointer needs to be a double pointer in order to swap the strings.
How to copy part of an array to another array in C#?
Note: I found this question looking for one of the steps in the answer to how to resize an existing array.
So I thought I would add that information here, in case anyone else was searching for how to do a ranged copy as a partial answer to the question of resizing an array.
For anyone else finding this question looking for the same thing I was, it is very simple:
Array.Resize<T>(ref arrayVariable, newSize);
where T is the type, i.e. where arrayVariable is declared:
T[] arrayVariable;
That method handles null checks, as well as newSize==oldSize having no effect, and of course silently handles the case where one of the arrays is longer than the other.
See the MSDN article for more.
'AND' vs '&&' as operator
I guess it's a matter of taste, although (mistakenly) mixing them up might cause some undesired behaviors:
true && false || false; // returns false
true and false || false; // returns true
Hence, using && and || is safer for they have the highest precedence. In what regards to readability, I'd say these operators are universal enough.
UPDATE: About the comments saying that both operations return false ... well, in fact the code above does not return anything, I'm sorry for the ambiguity. To clarify: the behavior in the second case depends on how the result of the operation is used. Observe how the precedence of operators comes into play here:
var_dump(true and false || false); // bool(false)
$a = true and false || false; var_dump($a); // bool(true)
The reason why $a === true
is because the assignment operator has precedence over any logical operator, as already very well explained in other answers.
How should I validate an e-mail address?
Validate your email address format. [email protected]
public boolean emailValidator(String email)
{
Pattern pattern;
Matcher matcher;
final String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
pattern = Pattern.compile(EMAIL_PATTERN);
matcher = pattern.matcher(email);
return matcher.matches();
}
col align right
From the documentation, you do it like:
<div class="row">
<div class="col-md-6">left</div>
<div class="col-md-push-6">content needs to be right aligned</div>
</div>
Docs
How to calculate cumulative normal distribution?
Taken from above:
from scipy.stats import norm
>>> norm.cdf(1.96)
0.9750021048517795
>>> norm.cdf(-1.96)
0.024997895148220435
For a two-tailed test:
Import numpy as np
z = 1.96
p_value = 2 * norm.cdf(-np.abs(z))
0.04999579029644087
Setting custom UITableViewCells height
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
CGSize constraintSize = {245.0, 20000}
CGSize neededSize = [ yourText sizeWithFont:[UIfont systemFontOfSize:14.0f] constrainedToSize:constraintSize lineBreakMode:UILineBreakModeCharacterWrap]
if ( neededSize.height <= 18)
return 45
else return neededSize.height + 45
//18 is the size of your text with the requested font (systemFontOfSize 14). if you change fonts you have a different number to use
// 45 is what is required to have a nice cell as the neededSize.height is the "text"'s height only
//not the cell.
}
MySQL: Can't create/write to file '/tmp/#sql_3c6_0.MYI' (Errcode: 2) - What does it even mean?
Often this means your /tmp
partition has run out of space and the file can't be created, or for whatever reason the mysqld
process cannot write to that directory because of permission problems. Sometimes this is the case when selinux
rains on your parade.
Any operation that requites a "temp file" will go into the /tmp
directory by default. The name you're seeing is just some internal random name.
YouTube Autoplay not working
This code allows you to autoplay iframe video
<iframe src="https://www.youtube.com/embed/2MpUj-Aua48?rel=0&modestbranding=1&autohide=1&mute=1&showinfo=0&controls=0&autoplay=1" width="560" height="315" frameborder="0" allowfullscreen></iframe>
Here Is working fiddle
C# if/then directives for debug vs release
It is worth noting here that one of the most significant differences between conditionally executing code based on #if DEBUG
versus if(System.Diagnostics.Debugger.IsAttached)
is that the compiler directive changes the code that is compiled. That is, if you have two different statements in an #if DEBUG/#else/#endif
conditional block, only one of them will appear in the compiled code. This is an important distinction because it allows you do do things such as conditionally compile method definitions to be public void mymethod()
versus internal void mymethod()
depending on build type so that you can, for example, run unit tests on debug builds that will not break access control on production builds, or conditionally compile helper functions in debug builds that will not appear in the final code if they would violate security in some way should they escape into the wild. The IsAttached
property, on the other hand, does not affect the compiled code. Both sets of code are in all of the builds - the IsAttached
condition will only affect what is executed. This by itself can present a security issue.
How to fix Error: "Could not find schema information for the attribute/element" by creating schema
Simple: In Visual Studio Report designer
1. Open the report in design mode and delete the dataset from the RDLC File
2. Open solution Explorer and delete the actual (corrupted) XSD file
3. Add the dataset back to the RDLC file.
4. The above procedure will create the new XSD file.
5. More detailed is below.
In Visual Studio, Open your RDLC file Report in Design mode. Click on the report and then Select View and then Report Data from the top line menu. Select Datasets and then Right Click and delete the dataset from the report. Next Open Solution Explorer, if it is not already open in your Visual Studio. Locate the XSD file (It should be the same name as the dataset you just deleted from the report). Now go back and right click again on the report data Datasets, and select Add Dataset . This will create a new XSD file and write the dataset properties to the report. Now your error message will be gone and any missing data will now appear in your reports.
Smart way to truncate long strings
Correcting Kooilnc's solution:
String.prototype.trunc = String.prototype.trunc ||
function(n){
return this.length>n ? this.substr(0,n-1)+'…' : this.toString();
};
This returns the string value instead of the String object if it doesn't need to be truncated.
AngularJS passing data to $http.get request
Solution for those who are interested in sending params and headers in GET request
$http.get('https://www.your-website.com/api/users.json', {
params: {page: 1, limit: 100, sort: 'name', direction: 'desc'},
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}
)
.then(function(response) {
// Request completed successfully
}, function(x) {
// Request error
});
Complete service example will look like this
var mainApp = angular.module("mainApp", []);
mainApp.service('UserService', function($http, $q){
this.getUsers = function(page = 1, limit = 100, sort = 'id', direction = 'desc') {
var dfrd = $q.defer();
$http.get('https://www.your-website.com/api/users.json',
{
params:{page: page, limit: limit, sort: sort, direction: direction},
headers: {Authorization: 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}
)
.then(function(response) {
if ( response.data.success == true ) {
} else {
}
}, function(x) {
dfrd.reject(true);
});
return dfrd.promise;
}
});
Batch File: ( was unexpected at this time
you need double quotes in all your three if
statements, eg.:
IF "%a%"=="2" (
@echo OFF &SETLOCAL ENABLEDELAYEDEXPANSION
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.
set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if "%a%"=="" goto :aPrompt
echo %a%
IF "%a%"=="2" (
title USB WRITE LOCK
echo What do you want to do?
echo 1.Apply USB Write Protection
echo 2.Remove USB Write Protection
::param1
set "param1=%globalparam2%"
goto :param1Check
:param1Prompt
set /p "param1=Enter Choice: "
:param1Check
if "!param1!"=="" goto :param1Prompt
if "!param1!"=="1" (
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001
USB Write is Locked!
)
if "!param1!"=="2" (
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
USB Write is Unlocked!
)
)
pause
public static const in TypeScript
Thank you WiredPrairie!
Just to expand on your answer a bit, here is a complete example of defining a constants class.
// CYConstants.ts
class CYConstants {
public static get NOT_FOUND(): number { return -1; }
public static get EMPTY_STRING(): string { return ""; }
}
export = CYConstants;
To use
// main.ts
import CYConstants = require("./CYConstants");
console.log(CYConstants.NOT_FOUND); // Prints -1
console.log(CYConstants.EMPTY_STRING); // Prints "" (Nothing!)
How to delete node from XML file using C#
You can use Linq to XML to do this:
XDocument doc = XDocument.Load("input.xml");
var q = from node in doc.Descendants("Setting")
let attr = node.Attribute("name")
where attr != null && attr.Value == "File1"
select node;
q.ToList().ForEach(x => x.Remove());
doc.Save("output.xml");
Multiple conditions in a C 'for' loop
Wikipedia tells what comma operator does:
"In the C and C++ programming languages, the comma operator (represented by the token ,
) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type)."
How to store file name in database, with other info while uploading image to server using PHP?
If you want to input more data into the form, you simply access the submitted data through $_POST.
If you have
<input type="text" name="firstname" />
you access it with
$firstname = $_POST["firstname"];
You could then update your query line to read
mysql_query("INSERT INTO dbProfiles (photo,firstname)
VALUES('{$filename}','{$firstname}')");
Note: Always filter and sanitize your data.
How do I write a "tab" in Python?
Here are some more exotic Python 3 ways to get "hello" TAB "alex" (tested with Python 3.6.10):
"hello\N{TAB}alex"
"hello\N{tab}alex"
"hello\N{TaB}alex"
"hello\N{HT}alex"
"hello\N{CHARACTER TABULATION}alex"
"hello\N{HORIZONTAL TABULATION}alex"
"hello\x09alex"
"hello\u0009alex"
"hello\U00000009alex"
Actually, instead of using an escape sequence, it is possible to insert tab symbol directly into the string literal. Here is the code with a tabulation character to copy and try:
"hello alex"
If the tab in the string above won't be lost anywhere during copying the string then "print(repr(< string from above >)" should print 'hello\talex'.
See respective Python documentation for reference.
When should null values of Boolean be used?
Wow, what on earth? Is it just me or are all these answers wrong or at least misleading?
The Boolean class is a wrapper around the boolean primitive type. The use of this wrapper is to be able to pass a boolean in a method that accepts an object or generic. Ie vector.
A Boolean object can NEVER have a value of null. If your reference to a Boolean is null, it simply means that your Boolean was never created.
You might find this useful: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Boolean.java
A null Boolean reference should only be used to trigger similar logic to which you have any other null reference. Using it for three state logic is clumsy.
EDIT: notice, that Boolean a = true;
is a misleading statement. This really equals something closer to Boolean a = new Boolean(true);
Please see autoboxing here: http://en.wikipedia.org/wiki/Boxing_%28computer_science%29#Autoboxing
Perhaps this is where much of the confusion comes from.
EDIT2: Please read comments below.
If anyone has an idea of how to restructure my answer to incorporate this, please do so.
What is the difference between String.slice and String.substring?
substr: It's providing us to fetch part of the string based on specified index.
syntax of substr-
string.substr(start,end)
start - start index tells where the fetching start.
end - end index tells upto where string fetches. It's optional.
slice: It's providing to fetch part of the string based on the specified index. It's allows us to specify positive and index.
syntax of slice - string.slice(start,end)
start - start index tells where the fetching start.It's
end - end index tells upto where string fetches. It's optional.
In 'splice' both start and end index helps to take positive and negative index.
sample code for 'slice' in string
var str="Javascript";
console.log(str.slice(-5,-1));
output: crip
sample code for 'substring' in string
var str="Javascript";
console.log(str.substring(1,5));
output: avas
[*Note: negative indexing starts at the end of the string.]
Storing Python dictionaries
My use case was to save multiple JSON objects to a file and marty's answer helped me somewhat. But to serve my use case, the answer was not complete as it would overwrite the old data every time a new entry was saved.
To save multiple entries in a file, one must check for the old content (i.e., read before write). A typical file holding JSON data will either have a list
or an object
as root. So I considered that my JSON file always has a list of objects
and every time I add data to it, I simply load the list first, append my new data in it, and dump it back to a writable-only instance of file (w
):
def saveJson(url,sc): # This function writes the two values to the file
newdata = {'url':url,'sc':sc}
json_path = "db/file.json"
old_list= []
with open(json_path) as myfile: # Read the contents first
old_list = json.load(myfile)
old_list.append(newdata)
with open(json_path,"w") as myfile: # Overwrite the whole content
json.dump(old_list, myfile, sort_keys=True, indent=4)
return "success"
The new JSON file will look something like this:
[
{
"sc": "a11",
"url": "www.google.com"
},
{
"sc": "a12",
"url": "www.google.com"
},
{
"sc": "a13",
"url": "www.google.com"
}
]
NOTE: It is essential to have a file named file.json
with []
as initial data for this approach to work
PS: not related to original question, but this approach could also be further improved by first checking if our entry already exists (based on one or multiple keys) and only then append and save the data.
How to show multiline text in a table cell
Hi I needed to do the same thing! Don't ask why but I was generating a html using python and needed a way to loop through items in a list and have each item take on a row of its own WITHIN A SINGLE CELL of a table.
I found that the br tag worked well for me. For example:
<!DOCTYPE html>
<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<BODY>
<TABLE>
<TR>
<TD>
item 1 <BR>
item 2 <BR>
item 3 <BR>
item 4 <BR>
</TD>
</TR>
</TABLE>
</BODY>
This will produce the output that I wanted.
Trying to get property of non-object in
Check the manual for mysql_fetch_object()
. It returns an object, not an array of objects.
I'm guessing you want something like this
$results = mysql_query("SELECT * FROM sidemenu WHERE `menu_id`='".$menu."' ORDER BY `id` ASC LIMIT 1", $con);
$sidemenus = array();
while ($sidemenu = mysql_fetch_object($results)) {
$sidemenus[] = $sidemenu;
}
Might I suggest you have a look at PDO. PDOStatement::fetchAll(PDO::FETCH_OBJ)
does what you assumed mysql_fetch_object()
to do
Query Mongodb on month, day, year... of a datetime
You can find record by month, day, year etc of dates by Date Aggregation Operators, like $dayOfYear, $dayOfWeek, $month, $year etc.
As an example if you want all the orders which are created in April 2016 you can use below query.
db.getCollection('orders').aggregate(
[
{
$project:
{
doc: "$$ROOT",
year: { $year: "$created" },
month: { $month: "$created" },
day: { $dayOfMonth: "$created" }
}
},
{ $match : { "month" : 4, "year": 2016 } }
]
)
Here created is a date type field in documents, and $$ROOT we used to pass all other field to project in next stage, and give us all the detail of documents.
You can optimize above query as per your need, it is just to give an example. To know more about Date Aggregation Operators, visit the link.
Python, TypeError: unhashable type: 'list'
The problem is that you can't use a list
as the key in a dict
, since dict
keys need to be immutable. Use a tuple instead.
This is a list:
[x, y]
This is a tuple:
(x, y)
Note that in most cases, the (
and )
are optional, since ,
is what actually defines a tuple (as long as it's not surrounded by []
or {}
, or used as a function argument).
You might find the section on tuples in the Python tutorial useful:
Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.
And in the section on dictionaries:
Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.
Tomcat is not deploying my web project from Eclipse
Got it :)
Usually caused when eclipse is reffering to another (or in correct web folder, may be webConent)
- Update .settings/.jsdtscope to have correct entry for webapp, similar to below
- Update org.eclipse.wst.common.component to have correct entry for webapp
Find UNC path of a network drive?
The answer is a simple PowerShell
one-liner:
Get-WmiObject Win32_NetworkConnection | ft "RemoteName","LocalName" -A
If you only want to pull the UNC
for one particular drive, add a where statement:
Get-WmiObject Win32_NetworkConnection | where -Property 'LocalName' -eq 'Z:' | ft "RemoteName","LocalName" -A
jQuery Ajax requests are getting cancelled without being sent
I had the same problem, but in my case it turned out to be a cookie issue. The guys working on the back-end had changed the path of the JSESSIONID cookie that's set when we log in to our app, and I had an old cookie by that name on my computer, but with the old path. So when I tried logging in the browser (Chrome) sent two cookies called JSESSIONID, with different values, to the server - which understandably confused it - so it cancelled the request. Deleting the cookies from my computer fixed it.
How to use jQuery in AngularJS
Ideally you would put that in a directive, but you can also just put it in the controller. http://jsfiddle.net/tnq86/15/
angular.module('App', [])
.controller('AppCtrl', function ($scope) {
$scope.model = 0;
$scope.initSlider = function () {
$(function () {
// wait till load event fires so all resources are available
$scope.$slider = $('#slider').slider({
slide: $scope.onSlide
});
});
$scope.onSlide = function (e, ui) {
$scope.model = ui.value;
$scope.$digest();
};
};
$scope.initSlider();
});
The directive approach:
HTML
<div slider></div>
JS
angular.module('App', [])
.directive('slider', function (DataModel) {
return {
restrict: 'A',
scope: true,
controller: function ($scope, $element, $attrs) {
$scope.onSlide = function (e, ui) {
$scope.model = ui.value;
// or set it on the model
// DataModel.model = ui.value;
// add to angular digest cycle
$scope.$digest();
};
},
link: function (scope, el, attrs) {
var options = {
slide: scope.onSlide
};
// set up slider on load
angular.element(document).ready(function () {
scope.$slider = $(el).slider(options);
});
}
}
});
I would also recommend checking out Angular Bootstrap's source code:
https://github.com/angular-ui/bootstrap/blob/master/src/tooltip/tooltip.js
You can also use a factory to create the directive. This gives you ultimate flexibility to integrate services around it and whatever dependencies you need.
Limit on the WHERE col IN (...) condition
You can use tuples like this:
SELECT * FROM table
WHERE (Col, 1) IN ((123,1),(123,1),(222,1),....)
There are no restrictions on number of these. It compares pairs.
Removing duplicates from a SQL query (not just "use distinct")
Your question is kind of confusing; do you want to show only one row per user, or do you want to show a row per picture but suppress repeating values in the U.NAME field? I think you want the second; if not there are plenty of answers for the first.
Whether to display repeating values is display logic, which SQL wasn't really designed for. You can use a cursor in a loop to process the results row-by-row, but you will lose a lot of performance. If you have a "smart" frontend language like a .NET language or Java, whatever construction you put this data into can be cheaply manipulated to suppress repeating values before finally displaying it in the UI.
If you're using Microsoft SQL Server, and the transformation HAS to be done at the data layer, you may consider using a CTE (Computed Table Expression) to hold the initial query, then select values from each row of the CTE based on whether the columns in the previous row hold the same data. It'll be more performant than the cursor, but it'll be kinda messy either way. Observe:
USING CTE (Row, Name, PicID)
AS
(
SELECT ROW_NUMBER() OVER (ORDER BY U.NAME, P.PIC_ID),
U.NAME, P.PIC_ID
FROM USERS U
INNER JOIN POSTINGS P1
ON U.EMAIL_ID = P1.EMAIL_ID
INNER JOIN PICTURES P
ON P1.PIC_ID = P.PIC_ID
WHERE P.CAPTION LIKE '%car%'
ORDER BY U.NAME, P.PIC_ID
)
SELECT
CASE WHEN current.Name == previous.Name THEN '' ELSE current.Name END,
current.PicID
FROM CTE current
LEFT OUTER JOIN CTE previous
ON current.Row = previous.Row + 1
ORDER BY current.Row
The above sample is TSQL-specific; it is not guaranteed to work in any other DBPL like PL/SQL, but I think most of the enterprise-level SQL engines have something similar.
jQuery move to anchor location on page load
Put this right before the closing Body tag at the bottom of the page.
<script>
if (location.hash) {
location.href = location.hash;
}
</script>
jQuery is actually not required.
php static function
Entire difference is, you don't get $this
supplied inside the static function. If you try to use $this
, you'll get a Fatal error: Using $this when not in object context
.
Well, okay, one other difference: an E_STRICT
warning is generated by your first example.
drag drop files into standard html file input
What you could do, is display a file-input and overlay it with your transparent drop-area, being careful to use a name like file[1]
. {Be sure to have the enctype="multipart/form-data"
inside your FORM tag.}
Then have the drop-area handle the extra files by dynamically creating more file inputs for files 2..number_of_files, be sure to use the same base name, populating the value-attribute appropriately.
Lastly (front-end) submit the form.
All that's required to handle this method is to alter your procedure to handle an array of files.
Deep-Learning Nan loss reasons
In my case I got NAN when setting distant integer LABELs. ie:
- Labels [0..100] the training was ok,
- Labels [0..100] plus one additional label 8000, then I got NANs.
So, not use a very distant Label.
EDIT
You can see the effect in the following simple code:
from keras.models import Sequential
from keras.layers import Dense, Activation
import numpy as np
X=np.random.random(size=(20,5))
y=np.random.randint(0,high=5, size=(20,1))
model = Sequential([
Dense(10, input_dim=X.shape[1]),
Activation('relu'),
Dense(5),
Activation('softmax')
])
model.compile(optimizer = "Adam", loss = "sparse_categorical_crossentropy", metrics = ["accuracy"] )
print('fit model with labels in range 0..5')
history = model.fit(X, y, epochs= 5 )
X = np.vstack( (X, np.random.random(size=(1,5))))
y = np.vstack( ( y, [[8000]]))
print('fit model with labels in range 0..5 plus 8000')
history = model.fit(X, y, epochs= 5 )
The result shows the NANs after adding the label 8000:
fit model with labels in range 0..5
Epoch 1/5
20/20 [==============================] - 0s 25ms/step - loss: 1.8345 - acc: 0.1500
Epoch 2/5
20/20 [==============================] - 0s 150us/step - loss: 1.8312 - acc: 0.1500
Epoch 3/5
20/20 [==============================] - 0s 151us/step - loss: 1.8273 - acc: 0.1500
Epoch 4/5
20/20 [==============================] - 0s 198us/step - loss: 1.8233 - acc: 0.1500
Epoch 5/5
20/20 [==============================] - 0s 151us/step - loss: 1.8192 - acc: 0.1500
fit model with labels in range 0..5 plus 8000
Epoch 1/5
21/21 [==============================] - 0s 142us/step - loss: nan - acc: 0.1429
Epoch 2/5
21/21 [==============================] - 0s 238us/step - loss: nan - acc: 0.2381
Epoch 3/5
21/21 [==============================] - 0s 191us/step - loss: nan - acc: 0.2381
Epoch 4/5
21/21 [==============================] - 0s 191us/step - loss: nan - acc: 0.2381
Epoch 5/5
21/21 [==============================] - 0s 188us/step - loss: nan - acc: 0.2381
Just disable scroll not hide it?
Crude but working way will be to force the scroll back to top, thus effectively disabling scrolling:
var _stopScroll = false;
window.onload = function(event) {
document.onscroll = function(ev) {
if (_stopScroll) {
document.body.scrollTop = "0px";
}
}
};
When you open the lightbox raise the flag and when closing it,lower the flag.
Live test case.
Javascript: formatting a rounded number to N decimals
I think that there is a more simple approach to all given here, and is the method Number.toFixed()
already implemented in JavaScript.
simply write:
var myNumber = 2;
myNumber.toFixed(2); //returns "2.00"
myNumber.toFixed(1); //returns "2.0"
etc...
How do I time a method's execution in Java?
I basically do variations of this, but considering how hotspot compilation works, if you want to get accurate results you need to throw out the first few measurements and make sure you are using the method in a real world (read application specific) application.
If the JIT decides to compile it your numbers will vary heavily. so just be aware
Convert an integer to an array of digits
**** 2021 Answer ****
This single line will do the trick:
Array.from(String(12345), Number);
Example
_x000D_
_x000D_
const numToSeparate = 12345;
const arrayOfDigits = Array.from(String(numToSeparate), Number);
console.log(arrayOfDigits); //[1,2,3,4,5]
_x000D_
_x000D_
_x000D_
Explanation
1- String(numToSeparate)
will convert the number 12345 into a string, returning '12345'
2- The Array.from()
method creates a new Array instance from an array-like or iterable object, the string '12345' is an iterable object, so it will create an Array from it.
3- But, in the process of automatically creating this new array, the Array.from()
method will first pass any iterable element (every character in this case eg: '1', '2') to the function we set to him as a second parameter, which is the Number
function in this case
4- The Number
function will take any string character and will convert it into a number eg: Number('1')
; will return 1
.
5- These numbers will be added one by one to a new array and finally this array of numbers will be returned.
Summary
The code line Array.from(String(numToSeparate), Number);
will convert the number into a string, take each character of that string, convert it into a number and put in a new array. Finally, this new array of numbers will be returned.
Android appcompat v7:23
Original answer:
I too tried to change the support library to "23". When I changed the targetSdkVersion
to 23, Android Studio reported the following error:
This support library should not use a lower version (22) than the targetSdkVersion
(23)
I simply changed:
compile 'com.android.support:appcompat-v7:23.0.0'
to
compile 'com.android.support:appcompat-v7:+'
Although this fixed my issue, you should not use dynamic versions. After a few hours the new support repository was available and it is currently 23.0.1
.
Pro tip:
You can use double quotes and create a ${supportLibVersion}
variable for simplicity. Example:
ext {
supportLibVersion = '23.1.1'
}
compile "com.android.support:appcompat-v7:${supportLibVersion}"
compile "com.android.support:design:${supportLibVersion}"
compile "com.android.support:palette-v7:${supportLibVersion}"
compile "com.android.support:customtabs:${supportLibVersion}"
compile "com.android.support:gridlayout-v7:${supportLibVersion}"
source: https://twitter.com/manidesto/status/669195097947377664
React "after render" code?
Just to update a bit this question with the new Hook methods, you can simply use the useEffect
hook:
import React, { useEffect } from 'react'
export default function App(props) {
useEffect(() => {
// your post layout code (or 'effect') here.
...
},
// array of variables that can trigger an update if they change. Pass an
// an empty array if you just want to run it once after component mounted.
[])
}
Also if you want to run before the layout paint use the useLayoutEffect
hook:
import React, { useLayoutEffect } from 'react'
export default function App(props) {
useLayoutEffect(() => {
// your pre layout code (or 'effect') here.
...
}, [])
}
How to bind bootstrap popover on dynamic elements
This is how I made the code so it can handle dynamically created elements using popover feature. Using this code, you can trigger the popover to show by default.
HTML:
<div rel="this-should-be-the-target">
</div>
JQuery:
$(function() {
var targetElement = 'rel="this-should-be-the-target"';
initPopover(targetElement, "Test Popover Content");
// use this line if you want it to show by default
$(targetElement).popover('show');
function initPopover(target, popOverContent) {
$(target).each(function(i, obj) {
$(this).popover({
placement : 'auto',
trigger : 'hover',
"html": true,
content: popOverContent
});
});
}
});
How do I use PHP namespaces with autoload?
I recently found tanerkuc's answer very helpful! Just wanted to add that using strrpos()
+ substr()
is slightly faster than explode()
+ end()
:
spl_autoload_register( function( $class ) {
$pos = strrpos( $class, '\\' );
include ( $pos === false ? $class : substr( $class, $pos + 1 ) ).'.php';
});
Make flex items take content width, not width of parent container
Use align-items: flex-start
on the container, or align-self: flex-start
on the flex items.
No need for display: inline-flex
.
An initial setting of a flex container is align-items: stretch
. This means that flex items will expand to cover the full length of the container along the cross axis.
The align-self
property does the same thing as align-items
, except that align-self
applies to flex items while align-items
applies to the flex container.
By default, align-self
inherits the value of align-items
.
Since your container is flex-direction: column
, the cross axis is horizontal, and align-items: stretch
is expanding the child element's width as much as it can.
You can override the default with align-items: flex-start
on the container (which is inherited by all flex items) or align-self: flex-start
on the item (which is confined to the single item).
Learn more about flex alignment along the cross axis here:
Learn more about flex alignment along the main axis here:
How to generate serial version UID in Intellij
with in the code editor,
Open the class you want to create the UID for ,
Right click -> Generate -> SerialVersionUID.
You may need to have the GenerateSerialVersionUID plugin installed for this to work.
Xcode Objective-C | iOS: delay function / NSTimer help?
[NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO];
Is the best one to use. Using sleep(15); will cause the user unable to perform any other actions. With the following function, you would replace goToSecondButton with the appropriate selector or command, which can also be from the frameworks.
Possible reason for NGINX 499 error codes
This error is pretty easy to reproduce using standard nginx configuration with php-fpm.
Keeping the F5 button down on a page will create dozens of refresh requests to the server. Each previous request is canceled by the browser at new refresh. In my case I found dozens of 499's in my client's online shop log file. From an nginx point of view: If the response has not been delivered to the client before the next refresh request nginx logs the 499 error.
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:32 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:33 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:33 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:33 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:33 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:34 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:34 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:34 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:34 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:35 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
mydomain.com.log:84.240.77.112 - - [19/Jun/2018:09:07:35 +0200] "GET /(path) HTTP/2.0" 499 0 "-" (user-agent-string)
If the php-fpm processing takes longer (like a heavyish WP page) it may cause problems, of course. I have heard of php-fpm crashes, for instance, but I believe they can be prevented configuring services properly like handling calls to xmlrpc.php.
Not receiving Google OAuth refresh token
now google had refused those parameters in my request (access_type, prompt)... :( and there is no "Revoke Access" button at all. I'm frustrating because of getting back my refresh_token lol
UPDATE:
I found the answer in here :D you can get back the refresh token by a request
https://developers.google.com/identity/protocols/OAuth2WebServer
curl -H "Content-type:application/x-www-form-urlencoded" \
https://accounts.google.com/o/oauth2/revoke?token={token}
The token can be an access token or a refresh token. If the token is an access token and it has a corresponding refresh token, the refresh token will also be revoked.
If the revocation is successfully processed, then the status code of the response is 200. For error conditions, a status code 400 is returned along with an error code.
jQuery Selector: Id Ends With?
It's safer to add the underscore or $ to the term you're searching for so it's less likely to match other elements which end in the same ID:
$("element[id$=_txtTitle]")
(where element is the type of element you're trying to find - eg div
, input
etc.
(Note, you're suggesting your IDs tend to have $ signs in them, but I think .NET 2 now tends to use underscores in the ID instead, so my example uses an underscore).
How to capitalize the first letter of a String in Java?
The code i have posted will remove underscore(_) symbol and extra spaces from String and also it will capitalize first letter of every new word in String
private String capitalize(String txt){
List<String> finalTxt=new ArrayList<>();
if(txt.contains("_")){
txt=txt.replace("_"," ");
}
if(txt.contains(" ") && txt.length()>1){
String[] tSS=txt.split(" ");
for(String tSSV:tSS){ finalTxt.add(capitalize(tSSV)); }
}
if(finalTxt.size()>0){
txt="";
for(String s:finalTxt){ txt+=s+" "; }
}
if(txt.endsWith(" ") && txt.length()>1){
txt=txt.substring(0, (txt.length()-1));
return txt;
}
txt = txt.substring(0,1).toUpperCase() + txt.substring(1).toLowerCase();
return txt;
}
How do I add options to a DropDownList using jQuery?
Lets think your response is "successData". This contains a list which you need to add as options in a dropdown menu.
success: function (successData) {
var sizeOfData = successData.length;
if (sizeOfData == 0) {
// NO DATA, throw an alert ...
alert ("No Data Found");
} else {
$.each(successData, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
} }
This would work for you ....
How to execute multiple SQL statements from java
you can achieve that using Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously.
Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. reference
When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance.
- JDBC drivers are not required to support this feature. You should use the
DatabaseMetaData.supportsBatchUpdates()
method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.
- The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The
executeBatch()
is used to start the execution of all the statements grouped together.
- The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement.
- Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the
addBatch()
method. However, you cannot selectively choose which statement to remove.
EXAMPLE:
import java.sql.*;
public class jdbcConn {
public static void main(String[] args) throws Exception{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con = DriverManager.getConnection
("jdbc:derby://localhost:1527/testDb","name","pass");
Statement stmt = con.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String insertEmp1 = "insert into emp values
(10,'jay','trainee')";
String insertEmp2 = "insert into emp values
(11,'jayes','trainee')";
String insertEmp3 = "insert into emp values
(12,'shail','trainee')";
con.setAutoCommit(false);
stmt.addBatch(insertEmp1);//inserting Query in stmt
stmt.addBatch(insertEmp2);
stmt.addBatch(insertEmp3);
ResultSet rs = stmt.executeQuery("select * from emp");
rs.last();
System.out.println("rows before batch execution= "
+ rs.getRow());
stmt.executeBatch();
con.commit();
System.out.println("Batch executed");
rs = stmt.executeQuery("select * from emp");
rs.last();
System.out.println("rows after batch execution= "
+ rs.getRow());
}
}
refer http://www.tutorialspoint.com/javaexamples/jdbc_executebatch.htm
In a Dockerfile, How to update PATH environment variable?
This is discouraged (if you want to create/distribute a clean Docker image), since the PATH
variable is set by /etc/profile
script, the value can be overridden.
head /etc/profile
:
if [ "`id -u`" -eq 0 ]; then
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
else
PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
fi
export PATH
At the end of the Dockerfile, you could add:
RUN echo "export PATH=$PATH" > /etc/environment
So PATH is set for all users.
Getting index value on razor foreach
I prefer to use this extension method:
public static class Extensions
{
public static IEnumerable<(T item, int index)> WithIndex<T>(this IEnumerable<T> self)
=> self.Select((item, index) => (item, index));
}
Source:
https://stackoverflow.com/a/39997157/3850405
Razor:
@using Project.Shared.Helpers
@foreach (var (item, index) in collection.WithIndex())
{
<p>
Name: @item.Name Index: @index
</p>
}
What is the !! (not not) operator in JavaScript?
Returns boolean value of a variable.
Instead, Boolean
class can be used.
(please read code descriptions)
var X = "test"; // X value is "test" as a String value
var booleanX = !!X // booleanX is `true` as a Boolean value beacuse non-empty strings evaluates as `true` in boolean
var whatIsXValueInBoolean = Boolean(X) // whatIsXValueInBoolean is `true` again
console.log(Boolean(X) === !!X) // writes `true`
Namely, Boolean(X) = !!X
in use.
Please check code snippet out below ?
_x000D_
_x000D_
let a = 0_x000D_
console.log("a: ", a) // writes a value in its kind_x000D_
console.log("!a: ", !a) // writes '0 is NOT true in boolean' value as boolean - So that's true.In boolean 0 means false and 1 means true._x000D_
console.log("!!a: ", !!a) // writes 0 value in boolean. 0 means false._x000D_
console.log("Boolean(a): ", Boolean(a)) // equals to `!!a`_x000D_
console.log("\n") // newline_x000D_
_x000D_
a = 1_x000D_
console.log("a: ", a)_x000D_
console.log("!a: ", !a)_x000D_
console.log("!!a: ", !!a) // writes 1 value in boolean_x000D_
console.log("\n") // newline_x000D_
_x000D_
a = ""_x000D_
console.log("a: ", a)_x000D_
console.log("!a: ", !a) // writes '"" is NOT true in boolean' value as boolean - So that's true.In boolean empty strings, null and undefined values mean false and if there is a string it means true._x000D_
console.log("!!a: ", !!a) // writes "" value in boolean_x000D_
console.log("\n") // newline_x000D_
_x000D_
a = "test"_x000D_
console.log("a: ", a) // writes a value in its kind_x000D_
console.log("!a: ", !a)_x000D_
console.log("!!a: ", !!a) // writes "test" value in boolean_x000D_
_x000D_
console.log("Boolean(a) === !!a: ", Boolean(a) === !!a) // writes true
_x000D_
_x000D_
_x000D_
Count number of columns in a table row
If the colspan
or rowspan
is all set to 1
, counting the children td
s will give the correct answer. However, if there are spans, we cannot count the number of columns exactly, even by the maximum number of td
s of the rows. Consider the following example:
_x000D_
_x000D_
var mytable = document.getElementById('table')_x000D_
for (var i=0; i < mytable.rows.length; ++i) {_x000D_
document.write(mytable.rows[i].cells.length + "<br>");_x000D_
}
_x000D_
table, th, td {_x000D_
border: 1px solid black;_x000D_
border-collapse: collapse;_x000D_
padding: 3px;_x000D_
}
_x000D_
<table id="table">_x000D_
<thead>_x000D_
<tr>_x000D_
<th colspan="2">Header</th>_x000D_
<th rowspan="2">Hi</th>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Month</th>_x000D_
<th>Savings</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody>_x000D_
<tr>_x000D_
<td colspan="2">hello</td>_x000D_
<td>world</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>hello</td>_x000D_
<td colspan="2">again</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_
How can I write variables inside the tasks file in ansible
Whenever you have a module followed by a variable on the same line in ansible the parser will treat the reference variable as the beginning of an in-line dictionary. For example:
- name: some example
command: {{ myapp }} -a foo
The default here is to parse the first part of {{ myapp }} -a foo
as a dictionary instead of a string and you will get an error.
So you must quote the argument like so:
- name: some example
command: "{{ myapp }} -a foo"
Pass arguments to Constructor in VBA
I use one Factory
module that contains one (or more) constructor per class which calls the Init
member of each class.
For example a Point
class:
Class Point
Private X, Y
Sub Init(X, Y)
Me.X = X
Me.Y = Y
End Sub
A Line
class
Class Line
Private P1, P2
Sub Init(Optional P1, Optional P2, Optional X1, Optional X2, Optional Y1, Optional Y2)
If P1 Is Nothing Then
Set Me.P1 = NewPoint(X1, Y1)
Set Me.P2 = NewPoint(X2, Y2)
Else
Set Me.P1 = P1
Set Me.P2 = P2
End If
End Sub
And a Factory
module:
Module Factory
Function NewPoint(X, Y)
Set NewPoint = New Point
NewPoint.Init X, Y
End Function
Function NewLine(Optional P1, Optional P2, Optional X1, Optional X2, Optional Y1, Optional Y2)
Set NewLine = New Line
NewLine.Init P1, P2, X1, Y1, X2, Y2
End Function
Function NewLinePt(P1, P2)
Set NewLinePt = New Line
NewLinePt.Init P1:=P1, P2:=P2
End Function
Function NewLineXY(X1, Y1, X2, Y2)
Set NewLineXY = New Line
NewLineXY.Init X1:=X1, Y1:=Y1, X2:=X2, Y2:=Y2
End Function
One nice aspect of this approach is that makes it easy to use the factory functions inside expressions. For example it is possible to do something like:
D = Distance(NewPoint(10, 10), NewPoint(20, 20)
or:
D = NewPoint(10, 10).Distance(NewPoint(20, 20))
It's clean: the factory does very little and it does it consistently across all objects, just the creation and one Init
call on each creator.
And it's fairly object oriented: the Init
functions are defined inside the objects.
EDIT
I forgot to add that this allows me to create static methods. For example I can do something like (after making the parameters optional):
NewLine.DeleteAllLinesShorterThan 10
Unfortunately a new instance of the object is created every time, so any static variable will be lost after the execution. The collection of lines and any other static variable used in this pseudo-static method must be defined in a module.
Showing the stack trace from a running Python application
On Solaris, you can use pstack(1) No changes to the python code are necessary. eg.
# pstack 16000 | grep : | head
16000: /usr/bin/python2.6 /usr/lib/pkg.depotd --cfg svc:/application/pkg/serv
[ /usr/lib/python2.6/vendor-packages/cherrypy/process/wspbus.py:282 (_wait) ]
[ /usr/lib/python2.6/vendor-packages/cherrypy/process/wspbus.py:295 (wait) ]
[ /usr/lib/python2.6/vendor-packages/cherrypy/process/wspbus.py:242 (block) ]
[ /usr/lib/python2.6/vendor-packages/cherrypy/_init_.py:249 (quickstart) ]
[ /usr/lib/pkg.depotd:890 (<module>) ]
[ /usr/lib/python2.6/threading.py:256 (wait) ]
[ /usr/lib/python2.6/Queue.py:177 (get) ]
[ /usr/lib/python2.6/vendor-packages/pkg/server/depot.py:2142 (run) ]
[ /usr/lib/python2.6/threading.py:477 (run)
etc.
What's "P=NP?", and why is it such a famous question?
- A yes-or-no problem is in P (Polynomial time) if the answer can be computed in polynomial time.
- A yes-or-no problem is in NP (Non-deterministic Polynomial time) if a yes answer can be verified in polynomial time.
Intuitively, we can see that if a problem is in P, then it is in NP. Given a potential answer for a problem in P, we can verify the answer by simply recalculating the answer.
Less obvious, and much more difficult to answer, is whether all problems in NP are in P. Does the fact that we can verify an answer in polynomial time mean that we can compute that answer in polynomial time?
There are a large number of important problems that are known to be NP-complete (basically, if any these problems are proven to be in P, then all NP problems are proven to be in P). If P = NP, then all of these problems will be proven to have an efficient (polynomial time) solution.
Most scientists believe that P!=NP. However, no proof has yet been established for either P = NP or P!=NP. If anyone provides a proof for either conjecture, they will win US $1 million.
Align nav-items to right side in bootstrap-4
TL;DR:
Create another <ul class="navbar-nav ml-auto">
for the navbar items you want on the right.
ml-auto
will pull your navbar-nav
to the right where mr-auto
will pull it to the left.
Tested against Bootstrap v4.5.2
_x000D_
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"/>
<style>
/* Stackoverflow preview fix, please ignore */
.navbar-nav {
flex-direction: row;
}
.nav-link {
padding-right: .5rem !important;
padding-left: .5rem !important;
}
/* Fixes dropdown menus placed on the right side */
.ml-auto .dropdown-menu {
left: auto !important;
right: 0px;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary rounded">
<a class="navbar-brand" href="#">Navbar</a>
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link">Left Link 1</a>
</li>
<li class="nav-item">
<a class="nav-link">Left Link 2</a>
</li>
</ul>
<ul class="navbar-nav ml-auto">
<li class="nav-item">
<a class="nav-link">Right Link 1</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Dropdown on Right</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="#">Action</a>
<a class="dropdown-item" href="#">Another action with a lot of text inside of an item</a>
</div>
</li>
</ul>
</nav>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
</body>
</html>
_x000D_
_x000D_
_x000D_
As you can see additional styling rules have been added to account for some oddities in Stackoverflows preview box.
You should be able to safely ignore those rules in your project.
As of v4.0.0 this seems to be the official way to do it.
EDIT: I modified the Post to include a dropdown placed on the right side of the navbar as suggested by @Bruno. It needs its left
and right
attributes to be inverted. I added an extra snippet of css to the beginning of the example code.
Please note, that the example shows the mobile version when you click the Run code snippet
button. To view the desktop version you must click the Expand snippet
button.
.ml-auto .dropdown-menu {
left: auto !important;
right: 0px;
}
Including this in your stylesheet should do the trick.
Get the current time in C
guys i got a new way get system time. though its lengthy and is full of silly works but in this way you can get system time in integer format.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char hc1,hc2,mc1,mc2;
int hi1,hi2,mi1,mi2,hour,minute;
system("echo %time% >time.txt");
fp=fopen("time.txt","r");
if(fp==NULL)
exit(1) ;
hc1=fgetc(fp);
hc2=fgetc(fp);
fgetc(fp);
mc1=fgetc(fp);
mc2=fgetc(fp);
fclose(fp);
remove("time.txt");
hi1=hc1;
hi2=hc2;
mi1=mc1;
mi2=mc2;
hi1-=48;
hi2-=48;
mi1-=48;
mi2-=48;
hour=hi1*10+hi2;
minute=mi1*10+mi2;
printf("Current time is %d:%d\n",hour,minute);
return 0;
}
Create an Android GPS tracking application
The source code for the Android mobile application open-gpstracker which you appreciated is available here.
You can checkout the code using SVN client application or via Git:
Debugging the source code will surely help you.
See what's in a stash without applying it
From the man git-stash
page:
The modifications stashed away by this command can be listed with git stash list,
inspected with git stash show
show [<stash>]
Show the changes recorded in the stash as a diff between the stashed state and
its original parent. When no <stash> is given, shows the latest one. By default,
the command shows the diffstat, but it will accept any format known to git diff
(e.g., git stash show -p stash@{1} to view the second most recent stash in patch
form).
To list the stashed modifications
git stash list
To show files changed in the last stash
git stash show
So, to view the content of the most recent stash, run
git stash show -p
To view the content of an arbitrary stash, run something like
git stash show -p stash@{1}
Arduino IDE can't find ESP8266WiFi.h file
Starting with 1.6.4, Arduino IDE can be used to program and upload the NodeMCU board by installing the ESP8266 third-party platform package (refer https://github.com/esp8266/Arduino):
- Start Arduino, go to File > Preferences
- Add the following link to the Additional Boards Manager URLs: http://arduino.esp8266.com/stable/package_esp8266com_index.json and press OK button
- Click Tools > Boards menu > Boards Manager, search for ESP8266 and install ESP8266 platform from ESP8266 community (and don't forget to select your ESP8266 boards from Tools > Boards menu after installation)
To install additional ESP8266WiFi library:
- Click Sketch > Include Library > Manage Libraries, search for ESP8266WiFi and then install with the latest version.
After above steps, you should compile the sketch normally.
Multiple axis line chart in excel
Taking the answer above as guidance;
I made an extra graph for "hours worked by month", then copy/special-pasted it as a 'linked picture' for use under my other graphs. in other words, I copy pasted my existing graphs over the linked picture made from my new graph with the new axis.. And because it is a linked picture it always updates.
Make it easy on yourself though, make sure you copy an existing graph to build your 'picture' graph - then delete the series or change the data source to what you need as an extra axis. That way you won't have to mess around resizing.
The results were not too bad considering what I wanted to achieve; basically a list of incident frequency bar graph, with a performance tread line, and then a solid 'backdrop' of hours worked.
Thanks to the guy above for the idea!
What order are the Junit @Before/@After called?
One potential gotcha that has bitten me before:
I like to have at most one @Before
method in each test class, because order of running the @Before
methods defined within a class is not guaranteed. Typically, I will call such a method setUpTest()
.
But, although @Before
is documented as The @Before methods of superclasses will be run before those of the current class. No other ordering is defined.
, this only applies if each method marked with @Before
has a unique name in the class hierarchy.
For example, I had the following:
public class AbstractFooTest {
@Before
public void setUpTest() {
...
}
}
public void FooTest extends AbstractFooTest {
@Before
public void setUpTest() {
...
}
}
I expected AbstractFooTest.setUpTest()
to run before FooTest.setUpTest()
, but only FooTest.setupTest()
was executed. AbstractFooTest.setUpTest()
was not called at all.
The code must be modified as follows to work:
public void FooTest extends AbstractFooTest {
@Before
public void setUpTest() {
super.setUpTest();
...
}
}
Newline in string attribute
Maybe someone prefers
<TextBlock Text="{Binding StringFormat='Stuff on line1{0}Stuff on line2{0}Stuff on line3',
Source={x:Static s:Environment.NewLine}}" />
with xmlns:s="clr-namespace:System;assembly=mscorlib"
.
Setting dropdownlist selecteditem programmatically
Safety check to only select if an item is matched.
//try to find item in list.
ListItem oItem = DDL.Items.FindByValue("PassedValue"));
//if exists, select it.
if (oItem != null) oItem.Selected = true;
Angular CLI SASS options
Best could be ng new myApp --style=scss
Then Angular CLI will create any new component with scss for you...
Note that using scss
not working in the browser as you probably know.. so we need something to compile it to css
, for this reason we can use node-sass
, install it like below:
npm install node-sass --save-dev
and you should be good to go!
If you using webpack, read on here:
Command line inside project folder where your existing package.json
is: npm install node-sass sass-loader raw-loader --save-dev
In webpack.common.js
, search for "rules:" and add this object to the
end of the rules array (don't forget to add a comma to the end of the
previous object):
{
test: /\.scss$/,
exclude: /node_modules/,
loaders: ['raw-loader', 'sass-loader'] // sass-loader not scss-loader
}
Then in your component:
@Component({
styleUrls: ['./filename.scss'],
})
If you want global CSS support then on the top level component (likely
app.component.ts) remove encapsulation and include the SCSS:
import {ViewEncapsulation} from '@angular/core';
@Component({
selector: 'app',
styleUrls: ['./bootstrap.scss'],
encapsulation: ViewEncapsulation.None,
template: ``
})
class App {}
from Angular starter here.
Java HTTP Client Request with defined timeout
I found that setting the time out settings in HttpConnectionParams
and HttpConnectionManager
did not solve our case. We're limited to using org.apache.commons.httpclient
version 3.0.1.
I ended up using an java.util.concurrent.ExecutorService
to monitor the HttpClient.executeMethod()
call.
Here's a small, self-contained example
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;
/**
* @author Jeff Kirby
* @since <pre>Jun 17, 2011</pre>
*/
public class Example {
private static final String SITE = "http://some.website.com/upload";
private static final int TIME_OUT_SECS = 5;
// upload a file and return the response as a string
public String post(File file) throws IOException, InterruptedException {
final Part[] multiPart = { new FilePart("file", file.getName(), file) };
final EntityEnclosingMethod post = new PostMethod(SITE);
post.setRequestEntity(new MultipartRequestEntity(multiPart, post.getParams()));
final ExecutorService executor = Executors.newSingleThreadExecutor();
final List<Future<Integer>> futures = executor.invokeAll(Arrays.asList(new KillableHttpClient(post)), TIME_OUT_SECS, TimeUnit.SECONDS);
executor.shutdown();
if(futures.get(0).isCancelled()) {
throw new IOException(SITE + " has timed out. It has taken more than " + TIME_OUT_SECS + " seconds to respond");
}
return post.getResponseBodyAsString();
}
private static class KillableHttpClient implements Callable<Integer> {
private final EntityEnclosingMethod post;
private KillableHttpClient(EntityEnclosingMethod post) {
this.post = post;
}
public Integer call() throws Exception {
return new HttpClient().executeMethod(post);
}
}
}
Remove First and Last Character C++
Well, you could erase()
the first character too (note that erase()
modifies the string):
m_VirtualHostName.erase(0, 1);
m_VirtualHostName.erase(m_VirtualHostName.size() - 1);
But in this case, a simpler way is to take a substring:
m_VirtualHostName = m_VirtualHostName.substr(1, m_VirtualHostName.size() - 2);
Be careful to validate that the string actually has at least two characters in it first...
Cannot enqueue Handshake after invoking quit
You can use
debug: false,
Example:
//mysql connection
var dbcon1 = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "node5",
debug: false,
});
How to get the current branch name in Git?
As of version 2.22 of git you could just use:
git branch --show-current
As per man page:
Print the name of the current branch. In detached HEAD state, nothing is printed.
How to put a tooltip on a user-defined function
Also you can use, this Macro to assign Descriptions to arguments and the UDF:
Private Sub RegisterMyFunction()
Application.MacroOptions _
Macro:="SampleFunction", _ '' Your UDF name
Description:="calculates a result based on provided inputs", _
Category:="My UDF Category", _ '' Or use numbers, a list in the link below
ArgumentDescriptions:=Array( _ '' One by each argument
"is the first argument. tell the user what it does", _
"is the second argument. tell the user what it does")
End Sub
Credits to Kendall and the original post here.
For the UDF Categories
Blur the edges of an image or background image with CSS
I'm not entirely sure what visual end result you're after, but here's an easy way to blur an image's edge: place a div with the image inside another div with the blurred image.
Working example here:
http://jsfiddle.net/ZY5hn/1/
HTML:
<div class="placeholder">
<!-- blurred background image for blurred edge -->
<div class="bg-image-blur"></div>
<!-- same image, no blur -->
<div class="bg-image"></div>
<!-- content -->
<div class="content">Blurred Image Edges</div>
</div>
CSS:
.placeholder {
margin-right: auto;
margin-left:auto;
margin-top: 20px;
width: 200px;
height: 200px;
position: relative;
/* this is the only relevant part for the example */
}
/* both DIVs have the same image */
.bg-image-blur, .bg-image {
background-image: url('http://lorempixel.com/200/200/city/9');
position:absolute;
top:0;
left:0;
width: 100%;
height:100%;
}
/* blur the background, to make blurred edges that overflow the unblurred image that is on top */
.bg-image-blur {
-webkit-filter: blur(20px);
-moz-filter: blur(20px);
-o-filter: blur(20px);
-ms-filter: blur(20px);
filter: blur(20px);
}
/* I added this DIV in case you need to place content inside */
.content {
position: absolute;
top:0;
left:0;
width: 100%;
height: 100%;
color: #fff;
text-shadow: 0 0 3px #000;
text-align: center;
font-size: 30px;
}
Notice the blurred effect is using the image, so it changes with the image color.
I hope this helps.
How to search a specific value in all tables (PostgreSQL)?
There is a way to achieve this without creating a function or using an external tool. By using Postgres' query_to_xml()
function that can dynamically run a query inside another query, it's possible to search a text across many tables. This is based on my answer to retrieve the rowcount for all tables:
To search for the string foo
across all tables in a schema, the following can be used:
with found_rows as (
select format('%I.%I', table_schema, table_name) as table_name,
query_to_xml(format('select to_jsonb(t) as table_row
from %I.%I as t
where t::text like ''%%foo%%'' ', table_schema, table_name),
true, false, '') as table_rows
from information_schema.tables
where table_schema = 'public'
)
select table_name, x.table_row
from found_rows f
left join xmltable('//table/row'
passing table_rows
columns
table_row text path 'table_row') as x on true
Note that the use of xmltable
requires Postgres 10 or newer. For older Postgres version, this can be also done using xpath().
with found_rows as (
select format('%I.%I', table_schema, table_name) as table_name,
query_to_xml(format('select to_jsonb(t) as table_row
from %I.%I as t
where t::text like ''%%foo%%'' ', table_schema, table_name),
true, false, '') as table_rows
from information_schema.tables
where table_schema = 'public'
)
select table_name, x.table_row
from found_rows f
cross join unnest(xpath('/table/row/table_row/text()', table_rows)) as r(data)
The common table expression (WITH ...
) is only used for convenience. It loops through all tables in the public
schema. For each table the following query is run through the query_to_xml()
function:
select to_jsonb(t)
from some_table t
where t::text like '%foo%';
The where clause is used to make sure the expensive generation of XML content is only done for rows that contain the search string. This might return something like this:
<table xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<row>
<table_row>{"id": 42, "some_column": "foobar"}</table_row>
</row>
</table>
The conversion of the complete row to jsonb
is done, so that in the result one could see which value belongs to which column.
The above might return something like this:
table_name | table_row
-------------+----------------------------------------
public.foo | {"id": 1, "some_column": "foobar"}
public.bar | {"id": 42, "another_column": "barfoo"}
Online example for Postgres 10+
Online example for older Postgres versions
Export JAR with Netbeans
- Right click your project folder.
- Select Properties.
- Expand Build option.
- Select Packaging.
- Now Clean and Build your project (Shift +F11).
- jar file will be created at your_project_folder\dist folder.
How to compare 2 files fast using .NET?
Something (hopefully) reasonably efficient:
public class FileCompare
{
public static bool FilesEqual(string fileName1, string fileName2)
{
return FilesEqual(new FileInfo(fileName1), new FileInfo(fileName2));
}
/// <summary>
///
/// </summary>
/// <param name="file1"></param>
/// <param name="file2"></param>
/// <param name="bufferSize">8kb seemed like a good default</param>
/// <returns></returns>
public static bool FilesEqual(FileInfo file1, FileInfo file2, int bufferSize = 8192)
{
if (!file1.Exists || !file2.Exists || file1.Length != file2.Length) return false;
var buffer1 = new byte[bufferSize];
var buffer2 = new byte[bufferSize];
using (var stream1 = file1.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
{
using (var stream2 = file2.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
{
while (true)
{
var bytesRead1 = stream1.Read(buffer1, 0, bufferSize);
var bytesRead2 = stream2.Read(buffer2, 0, bufferSize);
if (bytesRead1 != bytesRead2) return false;
if (bytesRead1 == 0) return true;
if (!ArraysEqual(buffer1, buffer2, bytesRead1)) return false;
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="array1"></param>
/// <param name="array2"></param>
/// <param name="bytesToCompare"> 0 means compare entire arrays</param>
/// <returns></returns>
public static bool ArraysEqual(byte[] array1, byte[] array2, int bytesToCompare = 0)
{
if (array1.Length != array2.Length) return false;
var length = (bytesToCompare == 0) ? array1.Length : bytesToCompare;
var tailIdx = length - length % sizeof(Int64);
//check in 8 byte chunks
for (var i = 0; i < tailIdx; i += sizeof(Int64))
{
if (BitConverter.ToInt64(array1, i) != BitConverter.ToInt64(array2, i)) return false;
}
//check the remainder of the array, always shorter than 8 bytes
for (var i = tailIdx; i < length; i++)
{
if (array1[i] != array2[i]) return false;
}
return true;
}
}
How to make overlay control above all other controls?
Robert Rossney has a good solution. Here's an alternative solution I've used in the past that separates out the "Overlay" from the rest of the content. This solution takes advantage of the attached property Panel.ZIndex
to place the "Overlay" on top of everything else. You can either set the Visibility of the "Overlay" in code or use a DataTrigger
.
<Grid x:Name="LayoutRoot">
<Grid x:Name="Overlay" Panel.ZIndex="1000" Visibility="Collapsed">
<Grid.Background>
<SolidColorBrush Color="Black" Opacity=".5"/>
</Grid.Background>
<!-- Add controls as needed -->
</Grid>
<!-- Use whatever layout you need -->
<ContentControl x:Name="MainContent" />
</Grid>
How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message
This isn't appropriate in all situations but you can conditionally return false
inside the component itself if a certain criteria is or isn't met.
It doesn't unmount the component, but it removes all rendered content. This would only be bad, in my mind, if you have event listeners in the component that should be removed when the component is no longer needed.
import React, { Component } from 'react';
export default class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
hideComponent: false
}
}
closeThis = () => {
this.setState(prevState => ({
hideComponent: !prevState.hideComponent
})
});
render() {
if (this.state.hideComponent === true) {return false;}
return (
<div className={`content`} onClick={() => this.closeThis}>
YOUR CODE HERE
</div>
);
}
}
AngularJS : Clear $watch
Ideally, every custom watch should be removed when you leave the scope.
It helps in better memory management and better app performance.
// call to $watch will return a de-register function
var listener = $scope.$watch(someVariableToWatch, function(....));
$scope.$on('$destroy', function() {
listener(); // call the de-register function on scope destroy
});
Problems with Android Fragment back stack
Right!!! after much hair pulling I've finally worked out how to make this work properly.
It seems as though fragment [3] is not removed from the view when back is pressed so you have to do it manually!
First of all, dont use replace() but instead use remove and add separately. It seems as though replace() doesnt work properly.
The next part to this is overriding the onKeyDown method and remove the current fragment every time the back button is pressed.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
if (getSupportFragmentManager().getBackStackEntryCount() == 0)
{
this.finish();
return false;
}
else
{
getSupportFragmentManager().popBackStack();
removeCurrentFragment();
return false;
}
}
return super.onKeyDown(keyCode, event);
}
public void removeCurrentFragment()
{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
Fragment currentFrag = getSupportFragmentManager().findFragmentById(R.id.detailFragment);
String fragName = "NONE";
if (currentFrag!=null)
fragName = currentFrag.getClass().getSimpleName();
if (currentFrag != null)
transaction.remove(currentFrag);
transaction.commit();
}
Hope this helps!
What is an MDF file?
SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.
As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.
More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.
Spring JDBC Template for calling Stored Procedures
There are a number of ways to call stored procedures in Spring.
If you use CallableStatementCreator
to declare parameters, you will be using Java's standard interface of CallableStatement
, i.e register out parameters and set them separately. Using SqlParameter
abstraction will make your code cleaner.
I recommend you looking at SimpleJdbcCall
. It may be used like this:
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withSchemaName(schema)
.withCatalogName(package)
.withProcedureName(procedure)();
...
jdbcCall.addDeclaredParameter(new SqlParameter(paramName, OracleTypes.NUMBER));
...
jdbcCall.execute(callParams);
For simple procedures you may use jdbcTemplate
's update
method:
jdbcTemplate.update("call SOME_PROC (?, ?)", param1, param2);
How can I make visible an invisible control with jquery? (hide and show not work)
Here's some code I use to deal with this.
First we show the element, which will typically set the display type to "block" via .show() function, and then set the CSS rule to "visible":
jQuery( '.element' ).show().css( 'visibility', 'visible' );
Or, assuming that the class that is hiding the element is called hidden, such as in Twitter Bootstrap, toggleClass() can be useful:
jQuery( '.element' ).toggleClass( 'hidden' );
Lastly, if you want to chain functions, perhaps with fancy with a fading effect, you can do it like so:
jQuery( '.element' ).css( 'visibility', 'visible' ).fadeIn( 5000 );
How to disable registration new users in Laravel
This might be new in 5.7, but there is now an options array to the auth method. Simply changing
Auth::routes();
to
Auth::routes(['register' => false]);
in your routes file after running php artisan make:auth
will disable user registration.
Raise error in a Bash script
Basic error handling
If your test case runner returns a non-zero code for failed tests, you can simply write:
test_handler test_case_x; test_result=$?
if ((test_result != 0)); then
printf '%s\n' "Test case x failed" >&2 # write error message to stderr
exit 1 # or exit $test_result
fi
Or even shorter:
if ! test_handler test_case_x; then
printf '%s\n' "Test case x failed" >&2
exit 1
fi
Or the shortest:
test_handler test_case_x || { printf '%s\n' "Test case x failed" >&2; exit 1; }
To exit with test_handler's exit code:
test_handler test_case_x || { ec=$?; printf '%s\n' "Test case x failed" >&2; exit $ec; }
Advanced error handling
If you want to take a more comprehensive approach, you can have an error handler:
exit_if_error() {
local exit_code=$1
shift
[[ $exit_code ]] && # do nothing if no error code passed
((exit_code != 0)) && { # do nothing if error code is 0
printf 'ERROR: %s\n' "$@" >&2 # we can use better logging here
exit "$exit_code" # we could also check to make sure
# error code is numeric when passed
}
}
then invoke it after running your test case:
run_test_case test_case_x
exit_if_error $? "Test case x failed"
or
run_test_case test_case_x || exit_if_error $? "Test case x failed"
The advantages of having an error handler like exit_if_error
are:
- we can standardize all the error handling logic such as logging, printing a stack trace, notification, doing cleanup etc., in one place
- by making the error handler get the error code as an argument, we can spare the caller from the clutter of
if
blocks that test exit codes for errors
- if we have a signal handler (using trap), we can invoke the error handler from there
Error handling and logging library
Here is a complete implementation of error handling and logging:
https://github.com/codeforester/base/blob/master/lib/stdlib.sh
Related posts
SQL query to find record with ID not in another table
There are basically 3 approaches to that: not exists
, not in
and left join / is null
.
LEFT JOIN with IS NULL
SELECT l.*
FROM t_left l
LEFT JOIN
t_right r
ON r.value = l.value
WHERE r.value IS NULL
NOT IN
SELECT l.*
FROM t_left l
WHERE l.value NOT IN
(
SELECT value
FROM t_right r
)
NOT EXISTS
SELECT l.*
FROM t_left l
WHERE NOT EXISTS
(
SELECT NULL
FROM t_right r
WHERE r.value = l.value
)
Which one is better? The answer to this question might be better to be broken down to major specific RDBMS vendors. Generally speaking, one should avoid using select ... where ... in (select...)
when the magnitude of number of records in the sub-query is unknown. Some vendors might limit the size. Oracle, for example, has a limit of 1,000. Best thing to do is to try all three and show the execution plan.
Specifically form PostgreSQL, execution plan of NOT EXISTS
and LEFT JOIN / IS NULL
are the same. I personally prefer the NOT EXISTS
option because it shows better the intent. After all the semantic is that you want to find records in A that its pk do not exist in B.
Old but still gold, specific to PostgreSQL though: https://explainextended.com/2009/09/16/not-in-vs-not-exists-vs-left-join-is-null-postgresql/
SQLAlchemy equivalent to SQL "LIKE" statement
If you use native sql, you can refer to my code, otherwise just ignore my answer.
SELECT * FROM table WHERE tags LIKE "%banana%";
from sqlalchemy import text
bar_tags = "banana"
# '%' attention to spaces
query_sql = """SELECT * FROM table WHERE tags LIKE '%' :bar_tags '%'"""
# db is sqlalchemy session object
tags_res_list = db.execute(text(query_sql), {"bar_tags": bar_tags}).fetchall()
Angularjs - display current date
Just my 2 cents in case someone stumble upon this :)
What I am suggesting here will have the same result as the current answer however it has been recommended to write your controller the way that I have mentioned here.
Reference scroll to the first "Note" (Sorry it doesn't have anchor)
Here is the recommended way:
Controller:
var app = angular.module('myApp', []);
app.controller( 'MyCtrl', ['$scope', function($scope) {
$scope.date = new Date();
}]);
View:
<div ng-app="myApp">
<div ng-controller="MyCtrl">
{{date | date:'yyyy-MM-dd'}}
</div>
</div>
How to Find App Pool Recycles in Event Log
IIS version 8.5 +
To enable Event Tracing for Windows for your website/application
- Go to Logging and ensure either ETW event only or Both log file and ETW event ...is selected.
- Enable the desired Recycle logs in the Advanced Settings for the Application Pool:
- Go to the default Custom View: WebServer filters IIS logs:
Custom Views > ServerRoles > Web Server
- ... or System logs:
Windows Logs > System
How do I create a branch?
Suppose you want to create a branch from a trunk name (as "TEST")
then use:
svn cp -m "CREATE BRANCH TEST" $svn_url/trunk $svn_url/branches/TEST
css rotate a pseudo :after or :before content:""
Inline elements can't be transformed, and pseudo elements are inline by default, so you must apply display: block
or display: inline-block
to transform them:
_x000D_
_x000D_
#whatever:after {
content: "\24B6";
display: inline-block;
transform: rotate(30deg);
}
_x000D_
<div id="whatever">Some text </div>
_x000D_
_x000D_
_x000D_
how to set start page in webconfig file in asp.net c#
The same problem arrised for me when I installed Kaliko CMS Nuget Package. When I removed it, it started working fine again. So, your problem could be because of a recently installed Nuget Package. Uninstall it and your solution will work just fine.
How to send a “multipart/form-data” POST in Android with Volley
As mentioned in the presentation at the I/O (about 4:05), Volley "is terrible" for large payloads. As I understand it that means not to use Volley for receiving/sending (big) files. Looking at the code it seems that it is not even designed to handle multipart form data (e.g. Request.java has getBodyContentType() with hardcoded "application/x-www-form-urlencoded"; HttpClientStack::createHttpRequest() can handle only byte[], etc...). Probably you will be able to create implementation that can handle multipart but If I were you I will just use HttpClient directly with MultipartEntity like:
HttpPost req = new HttpPost(composeTargetUrl());
MultipartEntity entity = new MultipartEntity();
entity.addPart(POST_IMAGE_VAR_NAME, new FileBody(toUpload));
try {
entity.addPart(POST_SESSION_VAR_NAME, new StringBody(uploadSessionId));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
req.setEntity(entity);
You may need newer HttpClient (i.e. not the built-in) or even better, use Volley with newer HttpClient
Finding duplicate values in MySQL
To find how many records are duplicates in name column in Employee, the query below is helpful;
Select name from employee group by name having count(*)>1;
How do I print debug messages in the Google Chrome JavaScript Console?
Improving on Andru's idea, you can write a script which creates console functions if they don't exist:
if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || function(){};
console.error = console.error || function(){};
console.info = console.info || function(){};
Then, use any of the following:
console.log(...);
console.error(...);
console.info(...);
console.warn(...);
These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.
Show Youtube video source into HTML5 video tag?
With the new iframe tag embedded in your website, the code will automatically detect whether you are using a browser that supports HTML5 or not.
The iframe code for embedding YouTube videos is as follows, simply copy the Video ID and replace in the code below:
<iframe type="text/html"
width="640"
height="385"
src="http://www.youtube.com/embed/VIDEO_ID"
frameborder="0">
</iframe>
Scale image to fit a bounding box
This example to stretch the image proportionally to fit the entire window.
An improvisation to the above correct code is to add $( window ).resize(function(){});
function stretchImg(){
$('div').each(function() {
($(this).height() > $(this).find('img').height())
? $(this).find('img').removeClass('fillwidth').addClass('fillheight')
: '';
($(this).width() > $(this).find('img').width())
? $(this).find('img').removeClass('fillheight').addClass('fillwidth')
: '';
});
}
stretchImg();
$( window ).resize(function() {
strechImg();
});
There are two if conditions. The first one keeps checking if the image height is less than the div and applies .fillheight
class while the next checks for width and applies .fillwidth
class.
In both cases the other class is removed using .removeClass()
Here is the CSS
.fillwidth {
width: 100%;
max-width: none;
height: auto;
}
.fillheight {
height: 100vh;
max-width: none;
width: auto;
}
You can replace 100vh
by 100%
if you want to stretch the image with in a div. This example to stretch the image proportionally to fit the entire window.
Reflection: How to Invoke Method with parameters
I tried to work with all the suggested answers above but nothing seems to work for me. So i am trying to explain what worked for me here.
I believe if you are calling some method like the Main
below or even with a single parameter as in your question, you just have to change the type of parameter from string
to object
for this to work. I have a class like below
//Assembly.dll
namespace TestAssembly{
public class Main{
public void Hello()
{
var name = Console.ReadLine();
Console.WriteLine("Hello() called");
Console.WriteLine("Hello" + name + " at " + DateTime.Now);
}
public void Run(string parameters)
{
Console.WriteLine("Run() called");
Console.Write("You typed:" + parameters);
}
public string TestNoParameters()
{
Console.WriteLine("TestNoParameters() called");
return ("TestNoParameters() called");
}
public void Execute(object[] parameters)
{
Console.WriteLine("Execute() called");
Console.WriteLine("Number of parameters received: " + parameters.Length);
for(int i=0;i<parameters.Length;i++){
Console.WriteLine(parameters[i]);
}
}
}
}
Then you have to pass the parameterArray inside an object array like below while invoking it. The following method is what you need to work
private void ExecuteWithReflection(string methodName,object parameterObject = null)
{
Assembly assembly = Assembly.LoadFile("Assembly.dll");
Type typeInstance = assembly.GetType("TestAssembly.Main");
if (typeInstance != null)
{
MethodInfo methodInfo = typeInstance.GetMethod(methodName);
ParameterInfo[] parameterInfo = methodInfo.GetParameters();
object classInstance = Activator.CreateInstance(typeInstance, null);
if (parameterInfo.Length == 0)
{
// there is no parameter we can call with 'null'
var result = methodInfo.Invoke(classInstance, null);
}
else
{
var result = methodInfo.Invoke(classInstance,new object[] { parameterObject } );
}
}
}
This method makes it easy to invoke the method, it can be called as following
ExecuteWithReflection("Hello");
ExecuteWithReflection("Run","Vinod");
ExecuteWithReflection("TestNoParameters");
ExecuteWithReflection("Execute",new object[]{"Vinod","Srivastav"});
How to load Spring Application Context
package com.dataload;
public class insertCSV
{
public static void main(String args[])
{
ApplicationContext context =
new ClassPathXmlApplicationContext("applicationcontext.xml");
// retrieve configured instance
JobLauncher launcher = context.getBean("laucher", JobLauncher.class);
Job job = context.getBean("job", Job.class);
JobParameters jobParameters = context.getBean("jobParameters", JobParameters.class);
}
}
How do I access my webcam in Python?
John Montgomery's, answer is great, but at least on Windows, it is missing the line
vc.release()
before
cv2.destroyWindow("preview")
Without it, the camera resource is locked, and can not be captured again before the python console is killed.
how to get program files x86 env variable?
On a 64-bit Windows system, the reading of the various environment variables and some Windows Registry keys is redirected to different sources, depending whether the process doing the reading is 32-bit or 64-bit.
The table below lists these data sources:
X = HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion
Y = HKLM\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion
Z = HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
READING ENVIRONMENT VARIABLES: Source for 64-bit process Source for 32-bit process
-------------------------------|----------------------------------------|--------------------------------------------------------------
%ProgramFiles% : X\ProgramW6432Dir X\ProgramFilesDir (x86)
%ProgramFiles(x86)% : X\ProgramFilesDir (x86) X\ProgramFilesDir (x86)
%ProgramW6432% : X\ProgramW6432Dir X\ProgramW6432Dir
%CommonProgramFiles% : X\CommonW6432Dir X\CommonFilesDir (x86)
%CommonProgramFiles(x86)% : X\CommonFilesDir (x86) X\CommonFilesDir (x86)
%CommonProgramW6432% : X\CommonW6432Dir X\CommonW6432Dir
%ProgramData% : Z\ProgramData Z\ProgramData
READING REGISTRY VALUES: Source for 64-bit process Source for 32-bit process
-------------------------------|----------------------------------------|--------------------------------------------------------------
X\ProgramFilesDir : X\ProgramFilesDir Y\ProgramFilesDir
X\ProgramFilesDir (x86) : X\ProgramFilesDir (x86) Y\ProgramFilesDir (x86)
X\ProgramFilesPath : X\ProgramFilesPath = %ProgramFiles% Y\ProgramFilesPath = %ProgramFiles(x86)%
X\ProgramW6432Dir : X\ProgramW6432Dir Y\ProgramW6432Dir
X\CommonFilesDir : X\CommonFilesDir Y\CommonFilesDir
X\CommonFilesDir (x86) : X\CommonFilesDir (x86) Y\CommonFilesDir (x86)
X\CommonW6432Dir : X\CommonW6432Dir Y\CommonW6432Dir
So for example, for a 32-bit process, the source of the data for the %ProgramFiles%
and %ProgramFiles(x86)%
environment variables is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86)
.
However, for a 64-bit process, the source of the data for the %ProgramFiles%
environment variable is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramW6432Dir
...and the source of the data for the %ProgramFiles(x86)%
environment variable is the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86)
Most default Windows installation put a string like C:\Program Files (x86)
into the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesDir (x86)
but this (and others) can be changed.
Whatever is entered into these Windows Registry values will be read by Windows Explorer into respective Environment Variables upon login and then copied to any child process that it subsequently spawns.
The registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramFilesPath
is especially noteworthy because most Windows installations put the string %ProgramFiles%
into it, to be read by 64-bit processes. This string refers to the environment variable %ProgramFiles%
which in turn, takes its data from the Registry value HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ProgramW6432Dir
...unless some program changes the value of this environment variable apriori.
I have written a small utility, which displays these environment variables for 64-bit and 32-bit processes. You can download it here.
The source code for VisualStudio 2017 is included and the compiled 64-bit and 32-bit binary executables are in the directories ..\x64\Release
and ..\x86\Release
, respectively.
WordPress - Check if user is logged in
This problem is from the lazy update data request of Chrome.
At the first time you go to homepage. Chrome request with empty data. Then you go to the login page and logged in. When you back home page Chrome lazy to update the cookie data request because this domain is the same with the first time you access.
Solution:
Add parameter for home url. That helps Chrome realizes that this request need to update cookie to call to the server.
add at dashboard page
<?php
$track = '?track='.uniqid();
?>
<a href="<?= get_home_url(). $track ?>"> <img src="/img/logo.svg"></a>
Can I call a function of a shell script from another shell script?
The problem
The currenly accepted answer works only under important condition. Given...
/foo/bar/first.sh
:
function func1 {
echo "Hello $1"
}
and
/foo/bar/second.sh
:
#!/bin/bash
source ./first.sh
func1 World
this works only if the first.sh
is executed from within the same directory where the first.sh
is located. Ie. if the current working path of shell is /foo
, the attempt to run command
cd /foo
./bar/second.sh
prints error:
/foo/bar/second.sh: line 4: func1: command not found
That's because the source ./first.sh
is relative to current working path, not the path of the script. Hence one solution might be to utilize subshell and run
(cd /foo/bar; ./second.sh)
More generic solution
Given...
/foo/bar/first.sh
:
function func1 {
echo "Hello $1"
}
and
/foo/bar/second.sh
:
#!/bin/bash
source $(dirname "$0")/first.sh
func1 World
then
cd /foo
./bar/second.sh
prints
Hello World
How it works
$0
returns relative or absolute path to the executed script
dirname
returns relative path to directory, where the $0 script exists
$( dirname "$0" )
the dirname "$0"
command returns relative
path to directory of executed script, which is then used as argument for source
command
- in "second.sh",
/first.sh
just appends the name of imported shell script
source
loads content of specified file into current
shell
How to style components using makeStyles and still have lifecycle methods in Material UI?
I used withStyles
instead of makeStyle
EX :
import { withStyles } from '@material-ui/core/styles';
import React, {Component} from "react";
const useStyles = theme => ({
root: {
flexGrow: 1,
},
});
class App extends Component {
render() {
const { classes } = this.props;
return(
<div className={classes.root}>
Test
</div>
)
}
}
export default withStyles(useStyles)(App)
Bulk package updates using Conda
You want conda update --all
.
conda search --outdated
will show outdated packages, and conda update --all
will update them (note that the latter will not update you from Python 2 to Python 3, but the former will show Python as being outdated if you do use Python 2).
printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?
The format specifers matter: "%s" says that the next string is a narrow string ("ascii" and typically 8 bits per character). "%S" means wide char string. Mixing the two will give "undefined behaviour", which includes printing garbage, just one character or nothing.
One character is printed because wide chars are, for example, 16 bits wide, and the first byte is non-zero, followed by a zero byte -> end of string in narrow strings. This depends on byte-order, in a "big endian" machine, you'd get no string at all, because the first byte is zero, and the next byte contains a non-zero value.
How to "log in" to a website using Python's Requests module?
The requests.Session()
solution assisted with logging into a form with CSRF Protection (as used in Flask-WTF forms). Check if a csrf_token
is required as a hidden field and add it to the payload with the username and password:
import requests
from bs4 import BeautifulSoup
payload = {
'email': '[email protected]',
'password': 'passw0rd'
}
with requests.Session() as sess:
res = sess.get(server_name + '/signin')
signin = BeautifulSoup(res._content, 'html.parser')
payload['csrf_token'] = signin.find('input', id='csrf_token')['value']
res = sess.post(server_name + '/auth/login', data=payload)
WHILE LOOP with IF STATEMENT MYSQL
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is:
How to get first day of every corresponding month in mysql?
Showing the Procedure is working
Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
LaTeX: Prevent line break in a span of text
Also, if you have two subsequent words in regular text and you want to avoid a line break between them, you can use the ~ character.
For example:
As we can see in Fig.~\ref{BlaBla}, there is nothing interesting to see. A~better place..
This can ensure that you don't have a line starting with a figure number (without the Fig. part) or with an uppercase A.
How to download dependencies in gradle
This version builds on Robert Elliot's, but I'm not 100% sure of its efficacy.
// There are a few dependencies added by one of the Scala plugins that this cannot reach.
task downloadDependencies {
description "Pre-downloads *most* dependencies"
doLast {
configurations.getAsMap().each { name, config ->
println "Retrieving dependencies for $name"
try {
config.files
} catch (e) {
project.logger.info e.message // some cannot be resolved, silentlyish skip them
}
}
}
}
I tried putting it into configuration instead of action (by removing doLast) and it broke zinc. I worked around it, but the end result was the same with or without. So, I left it as an explicit state. It seems to work enough to reduce the dependencies that have to be downloaded later, but not eliminate them in my case. I think one of the Scala plugins adds dependencies later.
How do I export a project in the Android studio?
Firstly, Add this android:debuggable="false" in the application tag of the AndroidManifest.xml.
You don't need to harcode android:debuggable="false"
in your application tag. Infact for me studio complaints -
Avoid hardcoding the debug mode; leaving it out allows debug and release builds to automatically assign one less... (Ctrl+F1)
It's best to leave out the android:debuggable attribute from the manifest. If you do, then the tools will automatically insert android:debuggable=true when building an APK to debug on an emulator or device. And when you perform a release build, such as Exporting APK, it will automatically set it to false. If on the other hand you specify a specific value in the manifest file, then the tools will always use it. This can lead to accidentally publishing your app with debug information.
The accepted answer looks somewhat old. For me it asks me to select whether I want debug build or release build.
Go to Build->Generate Signed APK. Select your keystore, provide keystore password etc.
Now you should see a prompt to select release build or debug build
.
For production always select release build!
And you are done. Signed APK exported.
PS : Don't forget to increment your versionCode
in manifest file before uploading to playstore :)
Is there a way to change the spacing between legend items in ggplot2?
Looks like the best approach (in 2018) is to use legend.key.size
under the theme
object. (e.g., see here).
#Set-up:
library(ggplot2)
library(gridExtra)
gp <- ggplot(data = mtcars, aes(mpg, cyl, colour = factor(cyl))) +
geom_point()
This is real easy if you are using theme_bw()
:
gpbw <- gp + theme_bw()
#Change spacing size:
g1bw <- gpbw + theme(legend.key.size = unit(0, 'lines'))
g2bw <- gpbw + theme(legend.key.size = unit(1.5, 'lines'))
g3bw <- gpbw + theme(legend.key.size = unit(3, 'lines'))
grid.arrange(g1bw,g2bw,g3bw,nrow=3)
However, this doesn't work quite so well otherwise (e.g., if you need the grey background on your legend symbol):
g1 <- gp + theme(legend.key.size = unit(0, 'lines'))
g2 <- gp + theme(legend.key.size = unit(1.5, 'lines'))
g3 <- gp + theme(legend.key.size = unit(3, 'lines'))
grid.arrange(g1,g2,g3,nrow=3)
#Notice that the legend symbol squares get bigger (that's what legend.key.size does).
#Let's [indirectly] "control" that, too:
gp2 <- g3
g4 <- gp2 + theme(legend.key = element_rect(size = 1))
g5 <- gp2 + theme(legend.key = element_rect(size = 3))
g6 <- gp2 + theme(legend.key = element_rect(size = 10))
grid.arrange(g4,g5,g6,nrow=3) #see picture below, left
Notice that white squares begin blocking legend title (and eventually the graph itself if we kept increasing the value).
#This shows you why:
gt <- gp2 + theme(legend.key = element_rect(size = 10,color = 'yellow' ))
I haven't quite found a work-around for fixing the above problem...
Let me know in the comments if you have an idea, and I'll update accordingly!
- I wonder if there is some way to re-layer things using
$layers
...
JNI converting jstring to char *
Thanks Jason Rogers's answer first.
In Android && cpp should be this:
const char *nativeString = env->GetStringUTFChars(javaString, nullptr);
// use your string
env->ReleaseStringUTFChars(javaString, nativeString);
Can fix this errors:
1.error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'
2.error: no matching function for call to '_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'
3.error: no matching function for call to '_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'
4.add "env->DeleteLocalRef(nativeString);" at end.
RestTemplate: How to send URL and query parameters together
One simple way to do that is:
String url = "http://test.com/Services/rest/{id}/Identifier"
UriComponents uriComponents = UriComponentsBuilder.fromUriString(url).build();
uriComponents = uriComponents.expand(Collections.singletonMap("id", "1234"));
and then adds the query params.
PostgreSQL : cast string to date DD/MM/YYYY
In case you need to convert the returned date of a select statement to a specific format you may use the following:
select to_char(DATE (*date_you_want_to_select*)::date, 'DD/MM/YYYY') as "Formated Date"
Getting the source HTML of the current page from chrome extension
Inject a script into the page you want to get the source from and message it back to the popup....
manifest.json
{
"name": "Get pages source",
"version": "1.0",
"manifest_version": 2,
"description": "Get pages source from a popup",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["tabs", "<all_urls>"]
}
popup.html
<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<div id='message'>Injecting Script....</div>
</body>
</html>
popup.js
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
message.innerText = request.source;
}
});
function onWindowLoad() {
var message = document.querySelector('#message');
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.runtime.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
}
window.onload = onWindowLoad;
getPagesSource.js
// @author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);
function DOMtoString(document_root) {
var html = '',
node = document_root.firstChild;
while (node) {
switch (node.nodeType) {
case Node.ELEMENT_NODE:
html += node.outerHTML;
break;
case Node.TEXT_NODE:
html += node.nodeValue;
break;
case Node.CDATA_SECTION_NODE:
html += '<![CDATA[' + node.nodeValue + ']]>';
break;
case Node.COMMENT_NODE:
html += '<!--' + node.nodeValue + '-->';
break;
case Node.DOCUMENT_TYPE_NODE:
// (X)HTML documents are identified by public identifiers
html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
break;
}
node = node.nextSibling;
}
return html;
}
chrome.runtime.sendMessage({
action: "getSource",
source: DOMtoString(document)
});
How to merge specific files from Git branches
Although not a merge per se, sometimes the entire contents of another file on another branch are needed. Jason Rudolph's blog post provides a simple way to copy files from one branch to another. Apply the technique as follows:
$ git checkout branch1 # ensure in branch1 is checked out and active
$ git checkout branch2 file.py
Now file.py
is now in branch1.
Const in JavaScript: when to use it and is it necessary?
Summary:
const creates an immutable binding meaning const variable identifier is not re-assignable.
const a = "value1";
you cannot re-assign it with
a = "value2";
However, if const identifier holds an object or an array, value of it can be changed as far as we are not re-assigning it.
const x = { a: 1 }
x.a = 2; //is possible and allowed
const numbers = [1, 2];
numbers.push(3); //is possible and allowed
Please note that const is a block-scoped just like let which is not same as var (which is function-scoped)
In short, When something is not likely to change through re-assignment use const else use let or var depending on the scope you would like to have.
It's much easier to reason about the code when it is dead obvious what can be changed through re-assignment and what can't be. Changing a const to a let is dead simple. And going const by default makes you think twice before doing so. And this is in many cases a good thing.
What method in the String class returns only the first N characters?
Whenever I have to do string manipulations in C#, I miss the good old Left
and Right
functions from Visual Basic, which are much simpler to use than Substring
.
So in most of my C# projects, I create extension methods for them:
public static class StringExtensions
{
public static string Left(this string str, int length)
{
return str.Substring(0, Math.Min(length, str.Length));
}
public static string Right(this string str, int length)
{
return str.Substring(str.Length - Math.Min(length, str.Length));
}
}
Note:
The Math.Min
part is there because Substring
throws an ArgumentOutOfRangeException
when the input string's length is smaller than the requested length, as already mentioned in some comments under previous answers.
Usage:
string longString = "Long String";
// returns "Long";
string left1 = longString.Left(4);
// returns "Long String";
string left2 = longString.Left(100);
What is the default font of Sublime Text?
On Linux it's Monospace
10 pt. (the exact monospace font used may vary on different Linux distributions or versions), on Windows it's Consolas
10 pt., and on OS X it's Menlo Regular
12 pt.
(The color scheme is Neon
, the syntax highlighting is from PackageDev
, and the font is Liberation Mono
This information is found in the Packages/Default
directory (where Packages
is the directory opened by the Preferences ? Browse Packages...
menu option), in the Preferences (OS).sublime-settings
file where OS
is one of Windows
, Linux
, or OSX
.
You should only customize the font (or any other setting) in Packages/User/Preferences.sublime-settings
, opened by Preferences ? Settings—User
, as Settings—Default
is over-written on upgrade, and also serves as a backup in case you really screw something up in your user settings. This is the case for both the main Sublime settings as well as those for extra packages/plugins.
These default fonts are the same in Sublime Text 2, Sublime Text 3, and the new version currently in development.
How to make IPython notebook matplotlib plot inline
If your matplotlib version is above 1.4, it is also possible to use
IPython 3.x and above
%matplotlib notebook
import matplotlib.pyplot as plt
older versions
%matplotlib nbagg
import matplotlib.pyplot as plt
Both will activate the nbagg backend, which enables interactivity.
Simple way to get element by id within a div tag?
A given ID can be only used once in a page. It's invalid HTML to have multiple objects with the same ID, even if they are in different parts of the page.
You could change your HTML to this:
<div id="div1" >
<input type="text" class="edit1" />
<input type="text" class="edit2" />
</div>
<div id="div2" >
<input type="text" class="edit1" />
<input type="text" class="edit2" />
</div>
Then, you could get the first item in div1 with a CSS selector like this:
#div1 .edit1
On in jQuery:
$("#div1 .edit1")
Or, if you want to iterate the items in one of your divs, you can do it like this:
$("#div1 input").each(function(index) {
// do something with one of the input objects
});
If I couldn't use a framework like jQuery or YUI, I'd go get Sizzle and include that for it's selector logic (it's the same selector engine as is inside of jQuery) because DOM manipulation is massively easier with a good selector library.
If I couldn't use even Sizzle (which would be a massive drop in developer productivity), you could use plain DOM functions to traverse the children of a given element.
You would use DOM functions like childNodes or firstChild and nextSibling and you'd have to check the nodeType to make sure you only got the kind of elements you wanted. I never write code that way because it's so much less productive than using a selector library.
How can I change IIS Express port for a site
Here's a more manual method that works both for Website projects and Web Application projects. (you can't change the project URL from within Visual Studio for Website projects.)
Web Application projects
In Solution Explorer, right-click the project and click Unload Project.
Navigate to the IIS Express ApplicationHost.config file. By default, this file is located in:
%userprofile%\Documents\IISExpress\config
In recent Visual Studio versions and Web Application projects, this file is in the solution folder under [Solution Dir]\.vs\config\applicationhost.config
(note the .vs folder is a hidden item)
Open the ApplicationHost.config file in a text editor. In the <sites>
section, search for your site's name. In the <bindings>
section of your site, you will see an element like this:
<binding protocol="http" bindingInformation="*:56422:localhost" />
Change the port number (56422 in the above example) to anything you want. e.g.:
<binding protocol="http" bindingInformation="*:44444:localhost" />
Bonus: You can even bind to a different host name and do cool things like:
<binding protocol="http" bindingInformation="*:80:mysite.dev" />
and then map mysite.dev
to 127.0.0.1
in your hosts
file, and then open your website from "http://mysite.dev"
In Solution Explorer, right-click the the project and click Reload Project.
In Solution Explorer, right-click the the project and select Properties.
Select the Web tab.
In the Servers section, under Use Local IIS Web server, in the Project URL box enter a URL to match the hostname and port you entered in the ApplicationHost.config file from before.
To the right of the Project URL box, click Create Virtual Directory. If you see a success message, then you've done the steps correctly.
In the File menu, click Save Selected Items.
Website projects
In Solution Explorer, right-click the project name and then click Remove or Delete; don't worry, this removes the project from your solution, but does not delete the corresponding files on disk.
Follow step 2 from above for Web Application projects.
In Solution Explorer, right-click the solution, select Add, and then select Existing Web Site.... In the Add Existing Web Site dialog box, make sure that the Local IIS tab is selected. Under IIS Express Sites, select the site for which you have changed the port number, then click OK.
Now you can access your website from your new hostname/port.
Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?
A more generic solution, which works for non-numeric values as well:
a = {'a': 'foo', 'b':'bar', 'c': 'baz'}
b = {'a': 'spam', 'c':'ham', 'x': 'blah'}
r = dict(a.items() + b.items() +
[(k, a[k] + b[k]) for k in set(b) & set(a)])
or even more generic:
def combine_dicts(a, b, op=operator.add):
return dict(a.items() + b.items() +
[(k, op(a[k], b[k])) for k in set(b) & set(a)])
For example:
>>> a = {'a': 2, 'b':3, 'c':4}
>>> b = {'a': 5, 'c':6, 'x':7}
>>> import operator
>>> print combine_dicts(a, b, operator.mul)
{'a': 10, 'x': 7, 'c': 24, 'b': 3}
How to use regex in XPath "contains" function
In Robins's answer ends-with is not supported in xpath 1.0 too.. Only starts-with is supported...
So if your condition is not very specific..You can Use like this which worked for me
//*[starts-with(@id,'sometext') and contains(@name,'_text')]`\
How to check if a String contains only ASCII?
commons-lang3 from Apache contains valuable utility/convenience methods for all kinds of 'problems', including this one.
System.out.println(StringUtils.isAsciiPrintable("!@£$%^&!@£$%^"));
C# - Multiple generic types in one list
Following leppie's answer, why not make MetaData
an interface:
public interface IMetaData { }
public class Metadata<DataType> : IMetaData where DataType : struct
{
private DataType mDataType;
}
Where to put the gradle.properties file
Actually there are 3 places where gradle.properties
can be placed:
- Under gradle user home directory defined by the
GRADLE_USER_HOME
environment variable, which if not set defaults to USER_HOME/.gradle
- The sub-project directory (
myProject2
in your case)
- The root project directory (under
myProject
)
Gradle looks for gradle.properties
in all these places while giving precedence to properties definition based on the order above. So for example, for a property defined in gradle user home directory (#1) and the sub-project (#2) its value will be taken from gradle user home directory (#1).
You can find more details about it in gradle documentation here.
Global variables in c#.net
Just declare the variable at the starting of a class.
e.g. for string variable:
public partial class Login : System.Web.UI.Page
{
public string sError;
protected void Page_Load(object sender, EventArgs e)
{
//Page Load Code
}
Passing variables, creating instances, self, The mechanics and usage of classes: need explanation
So here is a simple example of how to use classes:
Suppose you are a finance institute. You want your customer's accounts to be managed by a computer. So you need to model those accounts. That is where classes come in. Working with classes is called object oriented programming. With classes you model real world objects in your computer. So, what do we need to model a simple bank account? We need a variable that saves the balance and one that saves the customers name. Additionally, some methods to in- and decrease the balance. That could look like:
class bankaccount():
def __init__(self, name, money):
self.name = name
self.money = money
def earn_money(self, amount):
self.money += amount
def withdraw_money(self, amount):
self.money -= amount
def show_balance(self):
print self.money
Now you have an abstract model of a simple account and its mechanism.
The def __init__(self, name, money)
is the classes' constructor. It builds up the object in memory. If you now want to open a new account you have to make an instance of your class. In order to do that, you have to call the constructor and pass the needed parameters. In Python a constructor is called by the classes's name:
spidermans_account = bankaccount("SpiderMan", 1000)
If Spiderman wants to buy M.J. a new ring he has to withdraw some money. He would call the withdraw
method on his account:
spidermans_account.withdraw_money(100)
If he wants to see the balance he calls:
spidermans_account.show_balance()
The whole thing about classes is to model objects, their attributes and mechanisms. To create an object, instantiate it like in the example. Values are passed to classes with getter and setter methods like `earn_money()´. Those methods access your objects variables. If you want your class to store another object you have to define a variable for that object in the constructor.
Is there any way to wait for AJAX response and halt execution?
The simple answer is to turn off async
. But that's the wrong thing to do. The correct answer is to re-think how you write the rest of your code.
Instead of writing this:
function functABC(){
$.ajax({
url: 'myPage.php',
data: {id: id},
success: function(data) {
return data;
}
});
}
function foo () {
var response = functABC();
some_result = bar(response);
// and other stuff and
return some_result;
}
You should write it like this:
function functABC(callback){
$.ajax({
url: 'myPage.php',
data: {id: id},
success: callback
});
}
function foo (callback) {
functABC(function(data){
var response = data;
some_result = bar(response);
// and other stuff and
callback(some_result);
})
}
That is, instead of returning result, pass in code of what needs to be done as callbacks. As I've shown, callbacks can be nested to as many levels as you have function calls.
A quick explanation of why I say it's wrong to turn off async:
Turning off async will freeze the browser while waiting for the ajax call. The user cannot click on anything, cannot scroll and in the worst case, if the user is low on memory, sometimes when the user drags the window off the screen and drags it in again he will see empty spaces because the browser is frozen and cannot redraw. For single threaded browsers like IE7 it's even worse: all websites freeze! Users who experience this may think you site is buggy. If you really don't want to do it asynchronously then just do your processing in the back end and refresh the whole page. It would at least feel not buggy.
Align text to the bottom of a div
Flex Solution
It is perfectly fine if you want to go with the display: table-cell
solution. But instead of hacking it out, we have a better way to accomplish the same using display: flex;
. flex
is something which has a decent support.
_x000D_
_x000D_
.wrap {_x000D_
height: 200px;_x000D_
width: 200px;_x000D_
border: 1px solid #aaa;_x000D_
margin: 10px;_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.wrap span {_x000D_
align-self: flex-end;_x000D_
}
_x000D_
<div class="wrap">_x000D_
<span>Align me to the bottom</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_
In the above example, we first set the parent element to display: flex;
and later, we use align-self
to flex-end
. This helps you push the item to the end of the flex
parent.
Old Solution (Valid if you are not willing to use flex
)
If you want to align the text to the bottom, you don't have to write so many properties for that, using display: table-cell;
with vertical-align: bottom;
is enough
_x000D_
_x000D_
div {_x000D_
display: table-cell;_x000D_
vertical-align: bottom;_x000D_
border: 1px solid #f00;_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
}
_x000D_
<div>Hello</div>
_x000D_
_x000D_
_x000D_
(Or JSFiddle)
vue.js 2 how to watch store values from vuex
_x000D_
_x000D_
====== store =====_x000D_
import Vue from 'vue'_x000D_
import Vuex from 'vuex'_x000D_
import axios from 'axios'_x000D_
_x000D_
Vue.use(Vuex)_x000D_
_x000D_
export default new Vuex.Store({_x000D_
state: {_x000D_
showRegisterLoginPage: true,_x000D_
user: null,_x000D_
allitem: null,_x000D_
productShow: null,_x000D_
userCart: null_x000D_
},_x000D_
mutations: {_x000D_
SET_USERS(state, payload) {_x000D_
state.user = payload_x000D_
},_x000D_
HIDE_LOGIN(state) {_x000D_
state.showRegisterLoginPage = false_x000D_
},_x000D_
SHOW_LOGIN(state) {_x000D_
state.showRegisterLoginPage = true_x000D_
},_x000D_
SET_ALLITEM(state, payload) {_x000D_
state.allitem = payload_x000D_
},_x000D_
SET_PRODUCTSHOW(state, payload) {_x000D_
state.productShow = payload_x000D_
},_x000D_
SET_USERCART(state, payload) {_x000D_
state.userCart = payload_x000D_
}_x000D_
},_x000D_
actions: {_x000D_
getUserLogin({ commit }) {_x000D_
axios({_x000D_
method: 'get',_x000D_
url: 'http://localhost:3000/users',_x000D_
headers: {_x000D_
token: localStorage.getItem('token')_x000D_
}_x000D_
})_x000D_
.then(({ data }) => {_x000D_
// console.log(data)_x000D_
commit('SET_USERS', data)_x000D_
})_x000D_
.catch(err => {_x000D_
console.log(err)_x000D_
})_x000D_
},_x000D_
addItem({ dispatch }, payload) {_x000D_
let formData = new FormData()_x000D_
formData.append('name', payload.name)_x000D_
formData.append('file', payload.file)_x000D_
formData.append('category', payload.category)_x000D_
formData.append('price', payload.price)_x000D_
formData.append('stock', payload.stock)_x000D_
formData.append('description', payload.description)_x000D_
axios({_x000D_
method: 'post',_x000D_
url: 'http://localhost:3000/products',_x000D_
data: formData,_x000D_
headers: {_x000D_
token: localStorage.getItem('token')_x000D_
}_x000D_
})_x000D_
.then(({ data }) => {_x000D_
// console.log('data hasbeen created ', data)_x000D_
dispatch('getAllItem')_x000D_
})_x000D_
.catch(err => {_x000D_
console.log(err)_x000D_
})_x000D_
},_x000D_
getAllItem({ commit }) {_x000D_
axios({_x000D_
method: 'get',_x000D_
url: 'http://localhost:3000/products'_x000D_
})_x000D_
.then(({ data }) => {_x000D_
// console.log(data)_x000D_
commit('SET_ALLITEM', data)_x000D_
})_x000D_
.catch(err => {_x000D_
console.log(err)_x000D_
})_x000D_
},_x000D_
addUserCart({ dispatch }, { payload, productId }) {_x000D_
let newCart = {_x000D_
count: payload_x000D_
}_x000D_
// console.log('ini dari store nya', productId)_x000D_
_x000D_
axios({_x000D_
method: 'post',_x000D_
url: `http://localhost:3000/transactions/${productId}`,_x000D_
data: newCart,_x000D_
headers: {_x000D_
token: localStorage.getItem('token')_x000D_
}_x000D_
})_x000D_
.then(({ data }) => {_x000D_
dispatch('getUserCart')_x000D_
// console.log('cart hasbeen added ', data)_x000D_
})_x000D_
.catch(err => {_x000D_
console.log(err)_x000D_
})_x000D_
},_x000D_
getUserCart({ commit }) {_x000D_
axios({_x000D_
method: 'get',_x000D_
url: 'http://localhost:3000/transactions/user',_x000D_
headers: {_x000D_
token: localStorage.getItem('token')_x000D_
}_x000D_
})_x000D_
.then(({ data }) => {_x000D_
// console.log(data)_x000D_
commit('SET_USERCART', data)_x000D_
})_x000D_
.catch(err => {_x000D_
console.log(err)_x000D_
})_x000D_
},_x000D_
cartCheckout({ commit, dispatch }, transactionId) {_x000D_
let count = null_x000D_
axios({_x000D_
method: 'post',_x000D_
url: `http://localhost:3000/transactions/checkout/${transactionId}`,_x000D_
headers: {_x000D_
token: localStorage.getItem('token')_x000D_
},_x000D_
data: {_x000D_
sesuatu: 'sesuatu'_x000D_
}_x000D_
})_x000D_
.then(({ data }) => {_x000D_
count = data.count_x000D_
console.log(count, data)_x000D_
_x000D_
dispatch('getUserCart')_x000D_
})_x000D_
.catch(err => {_x000D_
console.log(err)_x000D_
})_x000D_
},_x000D_
deleteTransactions({ dispatch }, transactionId) {_x000D_
axios({_x000D_
method: 'delete',_x000D_
url: `http://localhost:3000/transactions/${transactionId}`,_x000D_
headers: {_x000D_
token: localStorage.getItem('token')_x000D_
}_x000D_
})_x000D_
.then(({ data }) => {_x000D_
console.log('success delete')_x000D_
_x000D_
dispatch('getUserCart')_x000D_
})_x000D_
.catch(err => {_x000D_
console.log(err)_x000D_
})_x000D_
}_x000D_
},_x000D_
modules: {}_x000D_
})
_x000D_
_x000D_
_x000D_
Regex (grep) for multi-line search needed
I am not very good in grep. But your problem can be solved using AWK command.
Just see
awk '/select/,/from/' *.sql
The above code will result from first occurence of select
till first sequence of from
. Now you need to verify whether returned statements are having customername
or not. For this you can pipe the result. And can use awk or grep again.