/ Gists

Gists

On gists

Bash CheatSheet for UNIX Systems --> UPDATED VERSION --> https://github.com/LeCoupa/awesome-cheatsheets

Cheatsheets

bash-cheatsheet.sh #

#!/bin/bash
#####################################################
# Name: Bash CheatSheet for Mac OSX
# 
# A little overlook of the Bash basics
#
# Usage:
#
# Author: J. Le Coupanec
# Date: 2014/11/04
#####################################################


# 0. Shortcuts.


CTRL+A  # move to beginning of line
CTRL+B  # moves backward one character
CTRL+C  # halts the current command
CTRL+D  # deletes one character backward or logs out of current session, similar to exit
CTRL+E  # moves to end of line
CTRL+F  # moves forward one character
CTRL+G  # aborts the current editing command and ring the terminal bell
CTRL+J  # same as RETURN
CTRL+K  # deletes (kill) forward to end of line
CTRL+L  # clears screen and redisplay the line
CTRL+M  # same as RETURN
CTRL+N  # next line in command history
CTRL+O  # same as RETURN, then displays next line in history file
CTRL+P  # previous line in command history
CTRL+R  # searches backward
CTRL+S  # searches forward
CTRL+T  # transposes two characters
CTRL+U  # kills backward from point to the beginning of line
CTRL+V  # makes the next character typed verbatim
CTRL+W  # kills the word behind the cursor
CTRL+X  # lists the possible filename completefions of the current word
CTRL+Y  # retrieves (yank) last item killed
CTRL+Z  # stops the current command, resume with fg in the foreground or bg in the background

DELETE  # deletes one character backward
!!      # repeats the last command
exit    # logs out of current session


# 1. Bash Basics.


export              # displays all environment variables

echo $SHELL         # displays the shell you're using
echo $BASH_VERSION  # displays bash version

bash                # if you want to use bash (type exit to go back to your normal shell)
whereis bash        # finds out where bash is on your system

clear               # clears content on window (hide displayed lines)


# 1.1. File Commands.


ls                            # lists your files
ls -l                         # lists your files in 'long format', which contains the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified
ls -a                         # lists all files, including hidden files
ln -s <filename> <link>       # creates symbolic link to file
touch <filename>              # creates or updates your file
cat > <filename>              # places standard input into file
more <filename>               # shows the first part of a file (move with space and type q to quit)
head <filename>               # outputs the first 10 lines of file
tail <filename>               # outputs the last 10 lines of file (useful with -f option)
emacs <filename>              # lets you create and edit a file
mv <filename1> <filename2>    # moves a file
cp <filename1> <filename2>    # copies a file
rm <filename>                 # removes a file
diff <filename1> <filename2>  # compares files, and shows where they differ
wc <filename>                 # tells you how many lines, words and characters there are in a file
chmod -options <filename>     # lets you change the read, write, and execute permissions on your files
gzip <filename>               # compresses files
gunzip <filename>             # uncompresses files compressed by gzip
gzcat <filename>              # lets you look at gzipped file without actually having to gunzip it
lpr <filename>                # print the file
lpq                           # check out the printer queue
lprm <jobnumber>              # remove something from the printer queue
genscript                     # converts plain text files into postscript for printing and gives you some options for formatting
dvips <filename>              # print .dvi files (i.e. files produced by LaTeX)
grep <pattern> <filenames>    # looks for the string in the files
grep -r <pattern> <dir>       # search recursively for pattern in directory


# 1.2. Directory Commands.


mkdir <dirname>  # makes a new directory
cd               # changes to home
cd <dirname>     # changes directory
pwd              # tells you where you currently are


# 1.3. SSH, System Info & Network Commands.


ssh user@host            # connects to host as user
ssh -p <port> user@host  # connects to host on specified port as user
ssh-copy-id user@host    # adds your ssh key to host for user to enable a keyed or passwordless login

whoami                   # returns your username
passwd                   # lets you change your password
quota -v                 # shows what your disk quota is
date                     # shows the current date and time
cal                      # shows the month's calendar
uptime                   # shows current uptime
w                        # displays whois online
finger <user>            # displays information about user
uname -a                 # shows kernel information
man <command>            # shows the manual for specified command
df                       # shows disk usage
du <filename>            # shows the disk usage of the files and directories in filename (du -s give only a total)
last <yourUsername>      # lists your last logins
ps -u yourusername       # lists your processes
kill <PID>               # kills (ends) the processes with the ID you gave
killall <processname>    # kill all processes with the name
top                      # displays your currently active processes
bg                       # lists stopped or background jobs ; resume a stopped job in the background
fg                       # brings the most recent job in the foreground
fg <job>                 # brings job to the foreground

ping <host>              # pings host and outputs results
whois <domain>           # gets whois information for domain
dig <domain>             # gets DNS information for domain
dig -x <host>            # reverses lookup host
wget <file>              # downloads file


# 2. Basic Shell Programming.


# 2.1. Variables.


varname=value                # defines a variable
varname=value command        # defines a variable to be in the environment of a particular subprocess
echo $varname                # checks a variable's value
echo $$                      # prints process ID of the current shell
echo $!                      # prints process ID of the most recently invoked background job
echo $?                      # displays the exit status of the last command
export VARNAME=value         # defines an environment variable (will be available in subprocesses)

array[0] = val               # several ways to define an array
array[1] = val
array[2] = val
array=([2]=val [0]=val [1]=val)
array(val val val)

${array[i]}                  # displays array's value for this index. If no index is supplied, array element 0 is assumed
${#array[i]}                 # to find out the length of any element in the array
${#array[@]}                 # to find out how many values there are in the array

declare -a                   # the variables are treaded as arrays
declare -f                   # uses funtion names only
declare -F                   # displays function names without definitions
declare -i                   # the variables are treaded as integers
declare -r                   # makes the variables read-only
declare -x                   # marks the variables for export via the environment

${varname:-word}             # if varname exists and isn't null, return its value; otherwise return word
${varname:=word}             # if varname exists and isn't null, return its value; otherwise set it word and then return its value
${varname:?message}          # if varname exists and isn't null, return its value; otherwise print varname, followed by message and abort the current command or script
${varname:+word}             # if varname exists and isn't null, return word; otherwise return null
${varname:offset:length}     # performs substring expansion. It returns the substring of $varname starting at offset and up to length characters

${variable#pattern}          # if the pattern matches the beginning of the variable's value, delete the shortest part that matches and return the rest
${variable##pattern}         # if the pattern matches the beginning of the variable's value, delete the longest part that matches and return the rest
${variable%pattern}          # if the pattern matches the end of the variable's value, delete the shortest part that matches and return the rest
${variable%%pattern}         # if the pattern matches the end of the variable's value, delete the longest part that matches and return the rest
${variable/pattern/string}   # the longest match to pattern in variable is replaced by string. Only the first match is replaced
${variable//pattern/string}  # the longest match to pattern in variable is replaced by string. All matches are replaced

${#varname}                  # returns the length of the value of the variable as a character string

*(patternlist)               # matches zero or more occurences of the given patterns
+(patternlist)               # matches one or more occurences of the given patterns
?(patternlist)               # matches zero or one occurence of the given patterns
@(patternlist)               # matches exactly one of the given patterns
!(patternlist)               # matches anything except one of the given patterns

$(UNIX command)              # command substitution: runs the command and returns standard output


# 2.2. Functions.
# The function refers to passed arguments by position (as if they were positional parameters), that is, $1, $2, and so forth.
# $@ is equal to "$1" "$2"... "$N", where N is the number of positional parameters. $# holds the number of positional parameters.


functname() {
  shell commands
}

unset -f functname  # deletes a function definition
declare -f          # displays all defined functions in your login session


# 2.3. Flow Control.


statement1 && statement2  # and operator
statement1 || statement2  # or operator

-a                        # and operator inside a test conditional expression
-o                        # or operator inside a test conditional expression

str1=str2                 # str1 matches str2
str1!=str2                # str1 does not match str2
str1<str2                 # str1 is less than str2
str1>str2                 # str1 is greater than str2
-n str1                   # str1 is not null (has length greater than 0)
-z str1                   # str1 is null (has length 0)

-a file                   # file exists
-d file                   # file exists and is a directory
-e file                   # file exists; same -a
-f file                   # file exists and is a regular file (i.e., not a directory or other special type of file)
-r file                   # you have read permission
-r file                   # file exists and is not empty
-w file                   # your have write permission
-x file                   # you have execute permission on file, or directory search permission if it is a directory
-N file                   # file was modified since it was last read
-O file                   # you own file
-G file                   # file's group ID matches yours (or one of yours, if you are in multiple groups)
file1 -nt file2           # file1 is newer than file2
file1 -ot file2           # file1 is older than file2

-lt                       # less than
-le                       # less than or equal
-eq                       # equal
-ge                       # greater than or equal
-gt                       # greater than
-ne                       # not equal

if condition
then
  statements
[elif condition
  then statements...]
[else
  statements]
fi

for x := 1 to 10 do
begin
  statements
end

for name [in list]
do
  statements that can use $name
done

for (( initialisation ; ending condition ; update ))
do
  statements...
done

case expression in
  pattern1 )
    statements ;;
  pattern2 )
    statements ;;
  ...
esac

select name [in list]
do
  statements that can use $name
done

while condition; do
  statements
done

until condition; do
  statements
done


# 3. Command-Line Processing Cycle.


# The default order for command lookup is functions, followed by built-ins, with scripts and executables last.
# There are three built-ins that you can use to override this order: `command`, `builtin` and `enable`.

command  # removes alias and function lookup. Only built-ins and commands found in the search path are executed
builtin  # looks up only built-in commands, ignoring functions and commands found in PATH
enable   # enables and disables shell built-ins

eval     # takes arguments and run them through the command-line processing steps all over again


# 4. Input/Output Redirectors.


cmd1|cmd2  # pipe; takes standard output of cmd1 as standard input to cmd2
> file     # directs standard output to file
< file     # takes standard input from file
>> file    # directs standard output to file; append to file if it already exists
>|file     # forces standard output to file even if noclobber is set
n>|file    # forces output to file from file descriptor n even if noclobber is set
<> file    # uses file as both standard input and standard output
n<>file    # uses file as both input and output for file descriptor n
<<label    # here-document
n>file     # directs file descriptor n to file
n<file     # takes file descriptor n from file
n>>file    # directs file description n to file; append to file if it already exists
n>&        # duplicates standard output to file descriptor n
n<&        # duplicates standard input from file descriptor n
n>&m       # file descriptor n is made to be a copy of the output file descriptor
n<&m       # file descriptor n is made to be a copy of the input file descriptor
&>file     # directs standard output and standard error to file
<&-        # closes the standard input
>&-        # closes the standard output
n>&-       # closes the ouput from file descriptor n
n<&-       # closes the input from file descripor n


# 5. Process Handling.


# To suspend a job, type CTRL+Z while it is running. You can also suspend a job with CTRL+Y.
# This is slightly different from CTRL+Z in that the process is only stopped when it attempts to read input from terminal.
# Of course, to interupt a job, type CTRL+C.

myCommand &  # runs job in the background and prompts back the shell

jobs         # lists all jobs (use with -l to see associated PID)

fg           # brings a background job into the foreground
fg %+        # brings most recently invoked background job
fg %-        # brings second most recently invoked background job
fg %N        # brings job number N
fg %string   # brings job whose command begins with string
fg %?string  # brings job whose command contains string

kill -l      # returns a list of all signals on the system, by name and number
kill PID     # terminates process with specified PID

ps           # prints a line of information about the current running login shell and any processes running under it
ps -a        # selects all processes with a tty except session leaders

trap cmd sig1 sig2  # executes a command when a signal is received by the script
trap "" sig1 sig2   # ignores that signals
trap - sig1 sig2    # resets the action taken when the signal is received to the default

disown <PID|JID>    # removes the process from the list of jobs

wait                # waits until all background jobs have finished


# 6. Tips and Tricks.


# set an alias
cd; nano .bash_profile
> alias gentlenode='ssh admin@gentlenode.com -p 3404'  # add your alias in .bash_profile

# to quickly go to a specific directory
cd; nano .bashrc
> shopt -s cdable_vars
> export websites="/Users/mac/Documents/websites"

source .bashrc
cd websites


# 7. Debugging Shell Programs.


bash -n scriptname  # don't run commands; check for syntax errors only
set -o noexec       # alternative (set option in script)

bash -v scriptname  # echo commands before running them
set -o verbose      # alternative (set option in script)

bash -x scriptname  # echo commands after command-line processing
set -o xtrace       # alternative (set option in script)

trap 'echo $varname' EXIT  # useful when you want to print out the values of variables at the point that your script exits

function errtrap {
  es=$?
  echo "ERROR line $1: Command exited with status $es."
}

trap 'errtrap $LINENO' ERR  # is run whenever a command in the surrounding script or function exists with non-zero status 

function dbgtrap {
  echo "badvar is $badvar"
}

trap dbgtrap DEBUG  # causes the trap code to be executed before every statement in a function or script
# ...section of code in which the problem occurs...
trap - DEBUG  # turn off the DEBUG trap

function returntrap {
  echo "A return occured"
}

trap returntrap RETURN  # is executed each time a shell function or a script executed with the . or source commands finishes executing


On gists

XPath Cheatsheet --> https://github.com/LeCoupa/awesome-cheatsheets

Cheatsheets PHP-PHPDOM

xpath-cheatsheet.js #

// XPath CheatSheet
// To test XPath in your Chrome Debugger: $x('/html/body')
// http://www.jittuu.com/2012/2/14/Testing-XPath-In-Chrome/


// 0. XPath Examples.
// More: http://xpath.alephzarro.com/content/cheatsheet.html


'//hr[@class="edge" and position()=1]'                // every first hr of 'edge' class
'//table[count(tr)=1 and count(tr/td)=2]'             // all tables with 1 row and 2 cols
'//div/form/parent::*'                                // all divs that have form
'./div/b'                                             // a relative path
'//table[parent::div[@class="pad"] and not(@id)]//a'  // any anchor in a table without id, contained in a div of "pad" class
'/html/body/div/*[preceding-sibling::h4]'             // give me whatever after h4
'//tr/td[font[@class="head" and text()="TRACK"]]'     // all td that has font of a "head" class and text "TRACK"
'./table/tr[last()]'                                  // the last row of a table
'//rdf:Seq/rdf:li/em:id'                              // using namespaces
'//a/@href'                                           // hrefs of all anchors
'//*[count(*)=3]'                                     // all nodes with 3 children
'//var|//acronym'                                     // all vars and acronyms


// 1. General.


'/html'                     // whole web page (css: html)
'/html/body'                // whole web page body (css: body)
'//text()'                  // all text nodes of web page
'/html/body/.../.../.../E'  // element <E> by absolute reference (css: body > … > … > … > E)


// 2. Tag.


'//E'                                        // element <E> by relative reference (css: E)
'(//E)[2]'                                   // second <E> element anywhere on page
'//img'                                      // image element (css: img)
'//E[@A]'                                    // element <E> with attribute A (css: E[A])
'//E[@A="t"]'                                // element <E> with attribute A containing text 't' exactly (css: E[A='t'])
'//E[contains(@A,"t")]'                      // element <E> with attribute A containing text 't' (css: E[A*='t'])
'//E[starts-with(@A, "t")]'                  // element <E> whose attribute A begins with 't' (css: E[A^='t'])
'//E[ends-with(@A, "t")]'                    // element <E> whose attribute A ends with 't' (css: E[A$='t'])
'//E[contains(concat(" ", @A, " "), " w ")'  // element <E> with attribute A containing word 'w' (css: E[A~='w'])
'//E[matches(@A, "r")]'                      // element <E> with attribute A matching regex ‘r’
'//E1[@id=I1] | //E2[@id=I2]'                // element <E1> with id I1 or element <E2> with id I2 (css: E1#I1, E2#I2)
'//E1[@id=I1 or @id=I2]'                     // element <E1> with id I1 or id I2 (css: E1#I1, E1#I2)


// 3. Attribute.


'//E/@A'                    // attribute A of element <E> (css: E@A)
'//*/@A'                    // attribute A of any element (css: *@A)
'//E[@A2="t"]/@A1'          // attribute A1 of element <E> where attribute A2 is 't' exactly (css: E[A2='t']@A1)
'//E[contains(@A,"t")]/@A'  // attribute A of element <E> where A contains 't' (css: E[A*='t']@A)


// 4. ID & Name.


'//*[@id="I"]'                // element with id I (css: #I)
'//E[@id="I"]'                // element <E> with id I (css: E#I)
'//*[@name="N"]'              // element with name (css: [name='N'])
'//E[@name="N"]'              // element <E> with name (css: E[name='N'])
'//*[@id="X" or @name="X"]'   // element with id X or, failing that, a name X
'//*[@name="N"][v+1]'         // element with name N & specified 0-based index ‘v’ (css: [name='N']:nth-child(v+1))
'//*[@name="N"][@value="v"]'  // element with name N & specified value ‘v’ (css: *[name='N'][value='v’])


// 5. Lang & Class.


'//E[@lang="L" or starts-with(@lang, concat("L", "-"))]'  // element <E> is explicitly in language L or subcode (css: E[lang|=L])
'//*[contains(concat(" ", @class, " "), " C ")]'          // element with a class C (css: .C)
'//E[contains(concat(" ", @class, " "), " C ")]'          // element <E> with a class C (css: E.C)


// 6. Text & Link.


'//*[.="t"]'                  // element containing text 't' exactly
'//E[contains(text(), "t")]'  // element <E> containing text 't' (css: E:contains('t'))
'//a'                         // link element (css: a)
'//a[.="t"]'                  // element <a> containing text 't' exactly
'//a[contains(text(), "t")]'  // element <a> containing text 't' (css: a:contains('t'))
'//a[@href="url"]'            // <a> with target link 'url' (css: a[href='url'])
'//a[.="t"]/@href'            // link URL labeled with text 't' exactly


// 7. Parent & Child.


'//E/*[1]'                                                        // first child of element <E> (css: E > *:first-child)
'//E[1]'                                                          // first <E> child (css: E:first-of-type)
'//E/*[last()]'                                                   // last child of element E (css: E *:last-child)
'//E[last()]'                                                     // last <E> child (css: E:last-of-type)
'//E[2]'                                                          // second <E> child (css: E:nth-of-type(2))
'//*[2][name()="E"]'                                              // second child that is an <E> element (css: E:nth-child(2))
'//E[last()-1]'                                                   // second-to-last <E> child (css: E:nth-last-of-type(2))
'//*[last()-1][name()="E"]'                                       // second-to-last child that is an <E> element (css: E:nth-last-child(2))
'//E1/[E2 and not( *[not(self::E2)])]'                            // element <E1> with only <E2> children
'//E/..'                                                          // parent of element <E>
'//*[@id="I"]/.../.../.../E'                                      // descendant <E> of element with id I using specific path (css: #I > … > … > … > E)
'//*[@id="I"]//E'                                                 // descendant <E> of element with id I using unspecified path (css: #I E)
'//E[count(*)=0]'                                                 // element <E> with no children (E:empty)
'//E[count(*)=1]'                                                 // element <E> with an only child
'//E[count(preceding-sibling::*)+count(following-sibling::*)=0]'  // element <E> that is an only child (css: E:only-child)
'//E[count(../E) = 1]'                                            // element <E> with no <E> siblings (css: E:only-of-type)
'//E[position() mod N = M + 1]'                                   // every Nth element starting with the (M+1)th (css: E:nth-child(Nn+M))


// 8. Sibling.


'//E2/following-sibling::E1'                 // element <E1> following some sibling <E2> (css: E2 ~ E1)
'//E2/following-sibling::*[1][name()="E1"]'  // element <E1> immediately following sibling <E2> (css: E2 + E1)
'//E2/following-sibling::*[2][name()="E1"]'  // element <E1> following sibling <E2> with one intermediary (css: E2 + * + E1)
'//E/following-sibling::*'                   // sibling element immediately following <E> (css: E + *)
'//E2/preceding-sibling::E1'                 // element <E1> preceding some sibling <E2>
'//E2/preceding-sibling::*[1][name()="E1"]'  // element <E1> immediately preceding sibling <E2>
'//E2/preceding-sibling::*[2][name()="E1"]'  // element <E1> preceding sibling <E2> with one intermediary
'//E/preceding-sibling::*[1]'                // sibling element immediately preceding <E>


// 9. Table Cell.


'//*[@id="TestTable"]//tr[3]//td[2]'          // cell by row and column (e.g. 3rd row, 2nd column) (css: #TestTable tr:nth-child(3) td:nth-child(2))
'//td[preceding-sibling::td="t"]'             // cell immediately following cell containing 't' exactly
'td[preceding-sibling::td[contains(.,"t")]]'  // cell immediately following cell containing 't' (css: td:contains('t') ~ td)


// 10. Dynamic.


'//E[@disabled]'       // user interface element <E> that is disabled (css: E:disabled)
'//*[not(@disabled)]'  // user interface element that is enabled (css: E:enabled)
'//*[@checked]'        // checkbox (or radio button) that is checked (css: *:checked)


// 11. XPath Functions.
// https://developer.mozilla.org/en-US/docs/Web/XPath/Functions


// 11.1. Conversion.


boolean(expression)  // evaluates an expression and returns true or false.
string([object])     // converts the given argument to a string.
number([object])     // converts an object to a number and returns the number.


// 11.2. Math.


ceiling(number)  // evaluates a decimal number and returns the smallest integer greater than or equal to the decimal number.
floor(number)    // evaluates a decimal number and returns the largest integer less than or equal to the decimal number.
round(decimal)   // returns a number that is the nearest integer to the given number.
sum(node-set)    // returns a number that is the sum of the numeric values of each node in a given node-set.


// 11.3. Logic.


true()           // returns a boolean value of true.
false()          // returns boolean false.
not(expression)  // evaluates a boolean expression and returns the opposite value.


// 11.4. Node.


lang(string)               // determines whether the context node matches the given language and returns boolean true or false.
name([node-set])           // returns a string representing the QName of the first node in a given node-set.
namespace-uri([node-set])  // returns a string representing the namespace URI of the first node in a given node-set.


// 11.5. Context.


count(node-set)           // counts the number of nodes in a node-set and returns an integer.
function-available(name)  // determines if a given function is available and returns boolean true or false.
last()                    // returns a number equal to the context size from the expression evaluation context.
position()                // returns a number equal to the context position from the expression evaluation context.


// 11.6. String.


contains(haystack-string, needle-string)  // determines whether the first argument string contains the second argument string and returns boolean true or false.
concat(string1, string2 [stringn]*)       // concatenates two or more strings and returns the resulting string.
normalize-space(string)                   // strips leading and trailing white-space from a string, replaces sequences of whitespace characters by a single space, and returns the resulting string.
starts-with(haystack, needle)             // checks whether the first string starts with the second string and returns true or false.
string-length([string])                   // returns a number equal to the number of characters in a given string.
substring(string, start [length])         // returns a part of a given string.
substring-after(haystack, needle)         // returns a string that is the rest of a given string after a given substring.
substring-before(haystack, needle)        // returns a string that is the rest of a given string before a given substring.
translate(string, abc, XYZ)               // evaluates a string and a set of characters to translate and returns the translated string.


// 12. XPath Axes.

ancestor            // indicates all the ancestors of the context node beginning with the parent node and traveling through to the root node.
ancestor-or-self    // indicates the context node and all of its ancestors, including the root node.
attribute (@)       // indicates the attributes of the context node. Only elements have attributes. This axis can be abbreviated with the at sign (@).
child (/)           // indicates the children of the context node. If an XPath expression does not specify an axis, this is understood by default. Since only the root node or element nodes have children, any other use will select nothing.
descendant (//)     // indicates all of the children of the context node, and all of their children, and so forth. Attribute and namespace nodes are not included - the parent of an attribute node is an element node, but attribute nodes are not the children of their parents.
descendant-or-self  // indicates the context node and all of its descendants. Attribute and namespace nodes are not included - the parent of an attribute node is an element node, but attribute nodes are not the children of their parents.
following           // indicates all the nodes that appear after the context node, except any descendant, attribute, and namespace nodes.
following-sibling   // indicates all the nodes that have the same parent as the context node and appear after the context node in the source document.
parent(..)          // indicates the single node that is the parent of the context node. It can be abbreviated as two periods (..).
preceding           // indicates all the nodes that precede the context node in the document except any ancestor, attribute and namespace nodes.
preceding-sibling   // indicates all the nodes that have the same parent as the context node and appear before the context node in the source document.
self (.)            // indicates the context node itself. It can be abbreviated as a single period (.).

On gists

Xpath - ukázky

PHP-PHPDOM

readme.txt #

@url: https://funkcionalne.k47.cz/2015/01/xpath-co-proc-a-hlavne-jak.html
@url: https://funkcionalne.k47.cz/2014/05/php-dom-simplexml-a-matcher.html

================================================================

/html – Vybere ele­ment html, který je ko­ře­no­vým ele­men­tem stromu.

/html/body - Odpovídá všem elementům body, které jsou přímými potomky kořenového elementu html`.

//h2 – Všechny ele­menty h2, které se v do­ku­mentu vy­sky­tují, včetně vlast­ních pod­stromů. Pokud jeden h2 kde­koli v sobě ob­sa­huje jiný ele­ment h2, vý­sled­kem budou všechny tyto ele­menty.

//div/span//a – Se­lek­tory je možno li­bo­volně ře­tě­zit a tento najde všechny a jako po­tomky span, které jsou přímými po­tomky li­bo­vol­ného divu.

./div nebo div – Vybere všechny ele­menty div které jsou přímými po­tomky právě ak­tiv­ního ele­mentu. Jde o re­la­tivní polohu a ne o polohu fi­xo­va­nou ke kořenu do­ku­mentu.

.//div – To samé jako před­chozí výraz, ale při­pouští i ne­přímé po­tomky.

div[@class="asdf"] – div, jehož atri­but class je „asdf“. XPath ne­pod­po­ruje CSS třídy a k obsahu atri­butů při­stu­puje jako ke strin­gům a proto, tento výraz není stejný jako css se­lek­tor div.asdf. XPath pod­mínce @class="asdf" vyhoví jen ty ele­menty je­jichž atri­but class je jen a pouze string „asdf“. Na toto je si třeba dávat pozor, pro­tože jde o nej­větší od­chylku od cho­vání, které by čekal člověk od­ko­jený CSS se­lek­tory.

div[@class != "asdf"] nebo div[not(@class = "asdf")] – Od­po­vídá divům je­jichž třída není „asdf“.

div[contains(@class, "asdf")] – divy je­jichž atri­but class ob­sa­huje string „asdf“. Na­pří­klad: Třída „xasdfy“ také vy­ho­vuje tomuto pre­di­kátu.

div[starts-with(@class, "asdf")] – divy je­jichž atri­but class začíná na „asdf“.

div[contains(concat(" ", normalize-space(@class), " "), " asdf ")] – Tento výraz má stejný význam jako CSS se­lek­tor div.asdf (tedy kromě toho, že CSS ne­při­hlíží v ve­li­kosti písmen a XPath ano). Na­štěstí takové kon­strukce nejsou skoro nikdy po­třeba, pro­tože vět­ši­nou stačí jed­no­du­ché @class="asdf" nebo funkce contains().

div[@class] – divy, které mají nějaký atri­but class

div[span] – divy, které mají jako pří­mého po­tomka span

div[.//span] – divy, které ob­sa­hují span

div[span[@class]] – divy, které mají pří­mého po­tomka span, který má na­sta­ve­nou li­bo­vol­nou třídu

div[@class and span] – divy, které mají na­sta­ven atri­but class a zá­ro­veň ob­sa­hují span jako po­tomka. Stejně jako and se dá použít i lo­gické or nebo funkce not().

div[1] – První div v pořadí v jakém se vy­sky­tuje v do­ku­mentu.

div[last()] – Po­slední div.

div[position() mod 2 = 0] – Každý sudý div.

Na pořadí pre­di­kátů v hra­na­tých zá­vor­kách záleží:

div[@class="asdf"][1] – Vybere všechny divy s třídou „asdf“ a z nich pak vybere ten první. Pokud exis­tují nějaké divy s touto třídou, vý­sled­kem bude vždycky první z nich.

div[1][@class="asdf"] – Vybere první div a ten ve vý­sledné mno­žině po­ne­chá jen pokud má třídu „asdf“. Když exis­tují divy s touto třídou, ale první ji nemá, vý­sled­kem je prázdná mno­žina.

div/text()[1] – Z divu vybere první kus textu, který není ob­sa­žen v žádném jiném ele­mentu.

preceding-sibling::h2 – Vybere ele­menty h2, které před­chá­zejí ak­tiv­nímu ele­mentu a zá­ro­veň jsou jeho sou­ro­zenci (tj. jsou přímými po­tomky stej­ného ele­mentu jako ak­tivní ele­ment).

a[@class="active"]/following-sibling::a[1] – Vybere první odkaz, který ná­sle­duje (a je sou­ro­ze­nec) po odkazu s třídou „active“.


On gists

Ukázka parsování stringu - PHP DOM

PHP-PHPDOM

example.php #

<?php
// ukazky https://github.com/kaja47/Matcher

$htmlString = '
    <div class="post" id="prvni">
        <div class="date">DNES</div>
        <h2>prvni nadpis</h2>
    </div>
    <div class="post" id="druhy">
        <div class="date">ZITRA</div>
        <h2>druhy nadpis</h2>
    </div>

    <textarea name="message"></textarea>
';

$dom = new DOMDocument;
$dom->loadHTML($htmlString);
$xpath = new \DOMXpath($dom);
$nodes = $xpath->query('//div[@class="post"]');
$res = [];
foreach ($nodes as $node) {
  $res[] = [
    'id'    => $xpath->query('@id', $node)->item(0)->textContent,
    'date'  => $xpath->query('div[@class="date"]', $node)->item(0)->textContent,
    'title' => $xpath->query('h2', $node)->item(0)->textContent,
  ];
}

$res['textarea'] = $xpath->query('//textarea/@name')->item(0)->textContent;


print_R($res);

/*

Array
(
    [0] => Array
        (
            [id] => prvni
            [date] => DNES
            [title] => prvni nadpis
        )

    [1] => Array
        (
            [id] => druhy
            [date] => ZITRA
            [title] => druhy nadpis
        )

    [textarea] => message
)


*/

On gists

Csv to UTF-8

PHP

csv.php #

<?php

	$csv = file_get_contents(INDEX_DIR . '/../temp/slozky-csv.csv');
	$csv = iconv("windows-1250//TRANSLIT//IGNORE", 'utf-8', $csv);
	$csv = explode("\n", $csv);

On gists

Ajax dependent selectbox

Nette Nette-Forms

example.php #

<?php
// https://forum.nette.org/cs/27213-dependent-form-select-with-ajax-chyba-please-select-a-valid-option
// https://forum.nette.org/cs/32545-jak-na-vicekrokovy-formular#p207046

protected function createComponentSelectForm($name)
{
    $firstItems = [
        1 => 'First option 1',
        2 => 'First option 2'
    ];

    // Je důležité předávat formuláři $this a $name jinak by nefungovalo níže použité $firstSelect->getValue()
    $form = new \Nette\Application\UI\Form($this, $name);
    $firstSelect = $form->addSelect('first', 'First select:', $firstItems)
        ->setPrompt('Select');

    $secondItems = [0 => 'Select from first'];

    if ($firstSelect->getValue()) {
        $secondItems = [
            0 => 'Select',
            1 => 'First option ' . $value . ' - second option 1',
            2 => 'First option ' . $value . ' - second option 2'
        ];
    }

    $form->addSelect('second', 'Second select:')
         ->setItems($secondItems);

    $form->addSubmit('send', 'Submit');

    $form->onSuccess[] = [$this, 'processSelectForm'];

    return $form;
}

On gists

Multiplier multiple

Nette Nette-Forms

multiplier.php #

<?php

return new Multiplier(function ($id) {
    return new Multiplier(function ($id2) use ($id) {

    });
});

On gists

Recursive array walk with replace

PHP

recursive.php #

<?php

	protected function parseQueryData(&$array, $data) 
	{
		array_walk_recursive($array, function(&$item, $key) use ($data) 
		{
			if(substr($item, 0, 1) == '%') 
			{
				$item = $data[substr($item, 1)];
			}
		});
	}

On gists

Factory - elastic

AW

factory.php #

<?php

namespace Andweb\Model;

use Nette,
	Andweb,
	Andweb\Database\Context;

use Andweb\Model\ElasticSearch;
use Andweb\Model\ElasticSearchResponse;

class ElasticSearchWrapperFactory  
{
	use Nette\SmartObject;

	/**
	 * @var ElasticSearch
	 */
	protected $elasticSearch;


	/**
	 * @var Nette\DI\Container
	 */
	protected $dic;


	public function __construct(ElasticSearch $elasticSearch, Nette\DI\Container $dic) 
	{
		$this->elasticSearch = $elasticSearch;
		$this->dic = $dic;
	}


	/**
	 * @param string $langName
	 * @return Andweb\Model\ElasticSearchWrapper
	 */
	public function create($langName)
	{
		$parameters = $this->dic->getParameters();
		return new ElasticSearchWrapper($parameters["searchQuery-$langName"], $parameters["searchIndex-$langName"], $this->elasticSearch);
		
	}
	
}

On gists

References in class

AW

fastadmintablepresenter.php #

<?php

	protected function & getTable()
	{
		return $this->table;
	}

	protected function & getStructure()
	{
		return $this->structure;
	}