#Find All Substrings of a Given String In C
Explore tagged Tumblr posts
Text
Find All Substrings of a Given String In C#
Find All Substrings of a Given String In C#
Find All Substrings of a Given String In C# Console.Write(“Enter a String : “);string inputString = Console.ReadLine(); Console.WriteLine(“All substrings for given string are : “); for (int i = 0; i < inputString.Length; ++i){StringBuilder subString = new StringBuilder(inputString.Length – i);for (int j = i; j < inputString.Length; ++j){subString.Append(inputString[j]);Console.Write(subString…
View On WordPress
#.NET#c#Coding#Find All Substrings of a Given String#Find All Substrings of a Given String In C#java#Program#program in c#Programming#Technology
0 notes
Text
Grep manual

When the -c or –count option is also used, grep does not output a count greater than NUM. When grep stops after NUM matching lines, it outputs any trailing context lines. This enables a calling process to resume a search. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. ) -m NUM, –max-count= NUM Stop reading a file after NUM matching lines. The scanning will stop on the first match. l, –files-with-matches Suppress normal output instead print the name of each input file from which output would normally have been printed. L, –files-without-match Suppress normal output instead print the name of each input file from which no output would normally have been printed. The deprecated environment variable GREP_COLOR is still supported, but its setting does not have priority. The colors are defined by the environment variable GREP_COLORS. ) –color, –colour Surround the matched (non-empty) strings, matching lines, context lines, file names, line numbers, byte offsets, and separators (for fields and groups of context lines) with escape sequences to display them in color on the terminal. With the -v, –invert-match option (see below), count non-matching lines. General Output Control -c, –count Suppress normal output instead print a count of matching lines for each input file. x, –line-regexp Select only those matches that exactly match the whole line. Word-constituent characters are letters, digits, and the underscore. Similarly, it must be either at the end of the line or followed by a non-word constituent character. The test is that the matching substring must either be at the beginning of the line, or preceded by a non-word constituent character. ) -w, –word-regexp Select only those lines containing matches that form whole words. ) -v, –invert-match Invert the sense of matching, to select non-matching lines. ) -i, –ignore-case Ignore case distinctions in both the PATTERN and the input files. The empty file contains zero patterns, and therefore matches nothing. ) -f FILE, –file= FILE Obtain patterns from FILE, one per line. This is useful to protect patterns beginning with hyphen-minus ( –). Matching Control -e PATTERN, –regexp= PATTERN Use PATTERN as the pattern. This is highly experimental and grep -P may warn of unimplemented features. P, –perl-regexp Interpret PATTERN as a Perl regular expression. ) -G, –basic-regexp Interpret PATTERN as a basic regular expression (BRE, see below). ) -F, –fixed-strings Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched. Matcher Selection -E, –extended-regexp Interpret PATTERN as an extended regular expression (ERE, see below). This version number should be included in all bug reports (see below). V, –version Print the version number of grep to the standard output stream. Options Generic Program Information –help Print a usage message briefly summarizing these command-line options and the bug-reporting address, then exit. Direct invocation as either egrep or fgrep is deprecated, but is provided to allow historical applications that rely on them to run unmodified. In addition, three variant programs egrep, fgrep and rgrep are available. By default, grep prints the matching lines. Grep searches the named input FILEs (or standard input if no files are named, or if a single hyphen-minus ( –) is given as file name) for lines containing a match to the given PATTERN. You will have to remove those if your input contains more than just the addresses.Grep, egrep, fgrep, rgrep – print lines matching a pattern Synopsis Note however that some of the expressions are used to match only the IP address and therefore contain beginning- ( ^) and end-of-line ( $) characters. You can find lots of IP address regular expressions on the web, see for example this StackOverflow question. grep -o 192.1.* zĪny line starting with 1921 will be matched, and only the matching part will be printed because of the -o switch.* matches anything up to the end of the line, including the empty string. Only 1921 will be matched, and only the matching part will be printed because of the -o switch. Your input does not contain data where this makes any difference. will be matched, and only the matching part will be printed because of the -o switch.

0 notes
Text
Normal Expressions With JavaScript

advent
regular expressions (RegExp) are a very useful and powerful part of JavaScript. The purpose of a RegExp is to determine whether or not a given string fee is valid, based on a set of rules.
Too many tutorials don't really educate you the way to write ordinary expressions. They certainly provide you with a few examples, most of which might be unluckily very tough to understand, after which never give an explanation for the details of ways the RegExp works. in case you've been pissed off through this as nicely, you then've come to the right vicinity! these days, you're going to virtually discover ways to write everyday expressions.
To find out how they work, we are going to begin with a completely simple example after which usually upload to the rules of the RegExp. With every rule that we upload, i can provide an explanation for the brand new rule and what it provides to the RegExp.
A RegExp is clearly a fixed of regulations to decide whether a string is valid. permit's count on that we've got an internet page where our customers enter their date of delivery. we can use a JSON Formatter ordinary expression in JavaScript to validate whether or not the date that they input is in a valid date layout. after all, we don't need them to enter some thing that is not a date.
Substring search
initially, allow's write a RegExp that requires our customers to go into a date that includes this cost: "MAR-sixteen-1981". word that they can input something they need, so long as the cost consists of MAR-16-1981 someplace within the value. for instance, this would also be legitimate with this expression: take a look at-MAR-16-1981-greater.
below is the HTML and JavaScript for a web page with a shape that lets in our customers to go into their date of birth.
characteristic validateDateFormat(inputString) {
var rxp = new RegExp(/MAR-sixteen-1981/);
var result = rxp.test(inputString);
if (end result == false) {
alert("Invalid Date format");
}
return end result;
}
be aware of the following key pieces of this code:
1. when the post button is clicked, our JavaScript function is called. If the price fails our take a look at, we display an alert pop-up container with an blunders message. on this state of affairs, the characteristic also returns a fake value. This guarantees that the form doesn't get submitted.
2. note that we're the usage of the RegExp JavaScript item. This item provides us with a "check" method to determine if the cost passes our ordinary expression rules.
precise suit search
The RegExp above lets in any cost that consists of MAR-sixteen-1981. subsequent, permit's expand on our regular expression to best allow values that same MAR-16-1981 precisely. There are matters we need to feature to our normal expression. the primary is a caret ^ at the start of the everyday expression. the second one is a dollar signal $ on the quit of the expression. The caret ^ calls for that the value we are testing cannot have any characters preceding the MAR-sixteen-1981 value. The dollar signal $ requires that the cost can't have any trailing characters after the MAR-sixteen-1981 value. right here's how our regular expression seems with those new rules. This ensures that the price entered have to be exactly MAR-16-1981.
/^MAR-sixteen-1981$/
man or woman Matching
we have already discovered a way to validate string values that either contain a certain substring or are equal to a sure price with a normal expression. however, for our HTML shape, we likely do not want to require our clients to enter an actual date. it's much more likely that we need them to go into any date, as long as it meets positive layout regulations. to start with, let's have a look at editing the RegExp in order that any 3 letters may be entered (not just "MAR"). let's additionally require that these letters be entered in uppercase. here's how this rule seems whilst added to our everyday expression.
/^[A-Z]{3}-sixteen-1981$/
All we've carried out is changed "MAR" with [A-Z]{three} which says that any letter between A and Z may be entered three instances. allow's examine a few versions of the character matching rules to learn about a few different approaches that we are able to in shape patterns of characters.
the rule of thumb above simplest allows 3 uppercase characters. What if you desired to permit 3 characters that could be uppercase or lowercase (i.e. case-insensitive)? here's how that rule could appearance in a regular expression.
/^[A-Za-z]{3}-sixteen-1981$/
next, let's alter our rule to allow three or extra characters. The {3} quantifier says that precisely three characters need to be entered for the month. we will allow three or extra characters via converting this quantifier to {3,}.
/^[A-Za-z]{3,}-16-1981$/
If we want to allow one or greater characters, we will virtually use the plus-signal + quantifier.
/^[A-Za-z]+-sixteen-1981$/
degrees
till now, we've got exact degrees of letters [A-Z] and numbers [0-9]. There are a selection of techniques for writing stages inside everyday expressions. you could specify more than a few [abc] to fit a or b or c. you can also specify a number of [^abc] to healthy anything that is not an a or b or c.
1 note
·
View note
Text
What is RegEx? Regular Expression in Python & Meta Characters
What is RegEx?
A regular expression (regex, regexp, or re) is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. Regular expression patterns are assembled into a set of byte codes which are then executed by a matching engine written in C. Regular expressions are widely used in the world of UNIX.
Now let’s understand simple basic regular expression through the following image.
The caret sign (^) serves two purposes. Here, in this figure, it’s checking for the string that doesn’t contain upper case, lower case, digits, underscore and space in the strings. In short, we can say that it is simply matching for special characters in the given string. If we use caret outside the square brackets, it will simply check for the starting of the string.
An example of a "proper" email-matching regex (like the one in the exercise), see below:
import re input_user = input("enter your email address: ") m = re.match( '(?=.*\d)(?=.*[a-z])(?=.*\W)',input_user) if m: print("Email is valid:") else: print("email is not valid:")
The most common usages of regular expressions are:
Search a string (search and match)
Finding a string (findall)
Break string into substrings (split)
Replace part of a string (sub)
'Re' Module
The module 're' gives full assistance for Perl-like regular expressions in Python. The re module raises the exception re.error if an error occurs while compiling or using a regular expression.
Now if we talk about the 're' module, the re module gives an interface to the regular expression engine, that permits you to arrange REs into objects and then perform with the matches. A regular expression is simply a sequence of characters that define a search pattern. Pythons’ built-in 're' module provides excellent support for the regular expressions with a modern and complete regex flavor.
Now, let’s understand everything about regular expressions and how they can be implemented in python. The very first step would be to import 're' module which provides all the necessary functionalities to play with. It can be done by the following statement in any of the IDE’s.
import re
Meta Characters
Metacharacters are characters or we can say it's a sequence of such characters, that holds a unique meaning specifically in a computing application. These characters have special meaning just like a '*' in wild cards. Some set of characters might be used to represent other characters, like an unprintable character or any logical operation. They are also known as “operators” and are mostly used to give rise to an expression that can represent a required character in a string or a file.
Below is the list of the metacharacters, and how to use such characters in the regular expression or regex like;
. ^ $ * + ? { } [ ] \ | ( )
Initially, the metacharacters we are going to explain are [ and ]. It’s used for specifying the class of the character which is a set of characters that you wish to match.
Characters can be listed individually here, or the range of characters can be indicated by giving two characters and separating them by a '-'. For instance, [abc] will match any of the characters a, b, or c; we can say in another way to express the same set of characters i.e. [a-c]. If you wanted to match only lowercase letters, your RE would be [a-z].
Let’s understand what these characters illuminate:
Here, [abc] will match if the string you are trying to match contains any of the a, b or c.
You can also specify a range of characters using - inside square brackets.
[a-e] is the same as [abcde].
[1-4] is the same as [1234].
[0-9] is the same as [0123---9]
You can complement (invert) the character set by using the caret ^ symbol at the start of a square-bracket.
[^abc] means any character except a or b or c.
[^0-9] means any non-digit character.
The basic usages of commonly used metacharacters are shown in the following table:
For example, \$a match if a string contains $ followed by a. Here, $ is not interpreted by a RegEx engine in a special way.
s = re.search('\w+$','789Welcome67 to python') Output: 'python'
\ is used to match a character having special meaning. For example: '.' matches '.', '+'matches '+' etc.
We need to use '\' to match. Regex recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.
The following code example will show you the regex '.' function:
s = re.match('........[a-zA-Z0-9]','Welcome to python') Output: 'Welcome t'
Other Special Sequences
There are some Special sequences that make commonly used patterns easier to write. Below is a list of such special sequences:
Understanding special sequences with examples
\A - Matches if the specified characters are at the start of a string.
s = re.search('\A\d','789Welcome67 to python') Output: '7'
\b - Matches if the specified characters are at the beginning or end of a word.
a = re.findall(r'\baa\b', "bbb aa \\bash\baaa") Output: ['aa']
\B - Opposite of \b. Matches if the specified characters are not at the beginning or end of a word.
a = re.findall('[\B]+', "BBB \\Bash BaBe BasketBall") Output: ['BBB', 'B', 'B', 'B', 'B', 'B']
\d - Matches any decimal digit. Equivalent to [0-9]
a = re.match('\d','1Welco+me to python11') Output: '1'
\D - Matches any non-decimal digit. Equivalent to [^0-9]
a = re.match('\D','Wel12co+me to python11') Output: 'W'
\s - Matches where a string contains any white space character. Equivalent to [ \t\n\r\f\v].
a = re.match('\s',' Wel12co+me to python11') Output: ' '
\S - Matches where a string contains any non-white space character. Equivalent to [^ \t\n\r\f\v].
a = re.match('/S','W el12co+me to python11') Output: 'W'
\w - Matches any alphanumeric character (digits and alphabets). Equivalent to [a-zA-Z0-9_]. By the way, underscore _ is also considered an alphanumeric character.
a = re.match('[\w]','1Welco+me to python11') Output: '1'
\W - Matches any non-alphanumeric character. Equivalent to [^a-zA-Z0-9_]
s = re.match('[\W]','@@Welcome to python') Output: '@'
\Z - Matches if the specified characters are at the end of a string.
s = re.search('\w\Z','789Welcome67 to python') Output: 'n'
Module- Level Functions
'Re' module provides so many top level functions & among them primarily used functions are: match(), search(), findall(), sub(), split(), compile().
These functions are responsible for taking arguments, primarily, regular expression pattern as the first argument and the string where regex has to be applied to be the second. It returns either None or a match object instance. They store the compiled object in a cache for the purpose of making future calls using the same regular expressions and avoiding the need to parse the pattern again and again.
We will explain some of these functions in the below section.
1. re.match() - The match() function is used to match the beginning of the string. In the following example, the match() function will match the first letter of the given string whether it is a digit, lowercase or uppercase letter (underscores included).
a = re.match('[0-9_a-zA-Z-]','Welcome to programming') Output: 'W'
If we add ‘+' outside the character set, it will check for the repeatability of the given characters in 'RE'. In the following example, '+' checks about one or more repetitions of uppercase, lowercase, and digits (underscore included, white spaces excluded).
a = re.match('[_0-9A-Za-z-]+','Welcome to programming') Output: 'Welcome'
'*' is a quantifier that is responsible for matching the regex preceding it 0 or more times. In short, we can say it matches any character zero or more times. Let's understand via the below given example. In the given string ('Welcome to programming'), '*' will match for characters given in the regex as long as possible.
a = re.match('[_A-Z0-9a-z-]*','Welcome to programming') Output: 'Welcome'
If we add '*' inside the character set, the regex will check for the presence of '*' at the beginning of the string. Since in the following example '*' is not present at the beginning of the string, so it will result in 'W'.
a = re.match('[_A-Z0-9a-z-*]','Welcome to programming') Output: 'W'
Using quantifier '?' matches zero or one of whatever precedes it. In the following example '?' matches uppercase or lowercase characters including underscore as well at the beginning of the string.
a = re.match('[_A-Za-z-]?','Welcome to programming') Output: 'W'
There's 're' module function that offers you the set of functions that mainly allows you to search a string for a match. Let’s understand what these functions perform.
2. re. search()- It is mainly used to search the pattern in a text. The function re. search() takes a regex pattern and a string and searches for that particular pattern within the string. In that case, if the search is successful, search() returns a match object or None otherwise. The syntax of re. search is as follows:
a = re.search(pattern, string)
You can better understand the following example.
a = re.search('come', 'welcome to programming') Output: <_sre.SRE_Match object; span=(3, 7), match='come'>
3. re. findall()- Returns a list containing all matches. The function re. findall() is used when you want to iterate over the lines of a file or string, it will return a list of all the matches in a single step. The string is scanned left-to-right, and matches are returned in the order that found. The syntax of re. findall() is as follows:
a = re.findall(pattern, string)
Below is an example of re. findall() function.
a = re.findall('prog','welcome to programming') Output: ['prog']
4. re. split () - Returns a list where the string has been split at each match. Split string by the occurrences of pattern. The syntax of re. split is given below:
a = re.split(pattern, string)
Look at the following example re. split() function:
a = re.split('[\W]+','welcome to programming') Output: ['welcome', 'to', 'programming
a = re.split('\s','Hello how are you') Output: ['Hello', 'how', 'are', 'you']
b = re.split('\d','hello1i am fine') Output: 'hello', 'i am fine']
5. re. sub() - It replaces one or many matches with a string. It is used to replace sub strings and it will replace the matches in string with replacing value. The syntax of re. sub() is as follows:
a = re.sub(pattern, replacing value, string)
The following example replaces all the digits in the given string with an empty string.
m = re.sub('[0-9]','','Welcome to python1234. Coding3456.') Output: 'Welcome to python. Coding.'
6. re. compile() - We can compile pattern into the pattern objects all with the help of function re.compile(), and which contains various methods for operations such as searching for pattern matches or performing string substitutions.
In the following example, the compile function compiles the regex function mentioned and then the code asks the user to enter a name. If the user types/inputs any digit or other special characters, the compile results won't match and it will again ask the user for input. It will continue doing this unless and until the user inputs a name containing characters only.
name_check = re.compile(r"[^A-Za-zs.]") name = input("Please, enter your name: ") while name_check.search(name): print("please enter your name correctly!") name = input("Please, enter your name: ")
The output of the following code is as follows:
Please, enter your name: 1234 please enter your name correctly! Please, enter your name: 5678 Name is provided correctly please enter your name correctly! Please, enter your name: john Name is provided correctly
Wrapping Up
Now that we have a rough understanding of what RegEx is, how regex works in python, further we can move onto something more technical. It's time to get a small project up and running.
0 notes
Text
Security Everywhere! Implementing cyclic() from pwntools (Part 1 of 3) - the de Bruijn Sequence
About a week or so ago, my tutor Jazz demonstrated some buffer overflow attacks in C, using a function from pwntools called cyclic(). Cyclic() generates a sequence of length(input) where each individual subsequence was unique such that:
This meant that the sequence it produced could be inserted into the buffer and, when it overflowed onto the $ra, the segfault would leak information about where the overflow occurred. Since each 4 letters of the sequence cyclic() provided was unique, we can take the attempted $ra jump and put it into cyclic_find(), where it would return the exact offset of where the $ra was.
The reason cyclic() was used was because, while we didn’t know the exact address of the $ra (due to ASLR), we could figure out the relative address from the buffer. Once we figure out where the $ra is, we could do more interesting stuff.
So how do we generate this sequence? Well, there’s an interesting sequence which already exists called the De Bruijn (dB) sequence which does just that – generate a string given a domain string d and a subsequence length n. A more general explanation of what it does is:
In combinatorial mathematics, a de Bruijn sequence of order n on a size-k alphabet A is a cyclic sequence in which every possible length-n string on A occurs exactly once as a substring (i.e., as a contiguous subsequence).
Before I try to explain how to generate a dB sequence, lets first define a few terms.
A Lyndon word is a nonempty string that is strictly smaller in lexicographic order than all of its rotations.
An inverse Burrows—Wheeler (BW) transform on a word w generates a multi-set of equivalence classes consisting of strings and their rotations, each with a Lyndon word as a minimum element.
So by performing a BW transform, we’re guaranteed to generate a set of Lyndon words, and by arranging these Lyndon words in order (sorting them), we get dB(d, n) in lexicographic order.
If you didn’t catch that, don’t worry. Here’s a method, and hopefully it’s easier to understand:
1) Find w. This can be done by finding len(d) and taking that to the power of n, and then repeating the domain string until it fits 2) Find w`. This is done by sorting w. 3) Put w’ on top of w for standard permutation. 4) Write this permutation in cycle notation. 5) For each cycle, replace each number with the corresponding letter from w’ and map the cycles
For a concrete example, let’s try dB(“ab”, 4):
1) Find w This is quite simple. Len(d) ^ 4 = 2^4 = 16, so the length is 16. Now we just repeat “ab” until it’s 16 characters long, so it’s abababababababab
2) Find w’. Once again quite t r i v i a l. Apply sort(w) so its: aaaaaaaabbbbbbbb
3) and 4) can be seen in the diagram below
5) Now we just need to make this a de Bruijn sequence. We can do this my mapping the cycles. Starting from the left, the cycles are: (1) (2 3 5 9) (4 7 13 10) (6 11) (8 15 14 12) (16)
Now replace them with the corresponding letter from w’ yielding (a)(aaab)(aabb)(ab)(abbb)(b)
Which makes the final sequence: aaaabaabbababbbb (after removing brackets) Notice that each 4 letter substring inside is unique.
Now, if we inserted this sequence into buffer where the return address comes <12 characters in, we will always be able to tell how many bytes our overflow is! For example, if we overflowed at 0x3d3e3e3d we know that the sequence must have been 61 62 62 61 which is “abba”, and that’s 6 bytes into the buffer!
0 notes
Photo
Learn Computer Science With JavaScript: Part 1, The Basics
Introduction
JavaScript is a language that we can use to write programs that run in a browser or on a server using Node. Because of Node, you can use JavaScript to build full web applications like Twitter or games like Agar.io.
This is the first lesson in a four-part series where I will teach you the programming fundamentals you will need so you can learn to build your own apps. In part 1, I will introduce you to the syntax of JavaScript and ES6. ES6 stands for ECMAScript 6, which is a version of JavaScript.
Contents
Installation and setup
Designing a program
Syntax
Variables
Data types
Review
Resources
Installation and Setup
First, we will set up our development environment so that we can run our code on our own computer. Alternatively, you can test code examples on an online editor like repl.it. I prefer you get started writing and running code on your computer so you can feel like a real programmer. Plus, I want you using Node so you can put it on your resume and impress your employer.
First, you will need a text editor to write your code in. I recommend Sublime Text. Next, download and install Node to your computer. You can get the software on the Node.js website. Confirm the installation worked by typing the command node -v from your terminal. If everything is fine, you will see the version number of your Node installation.
One of the things you can do with Node is run JavaScript code from within your terminal. This takes place in what is called a REPL. To try it out, enter the command node in your terminal.
Next, let's print the message “Hello, World”. Type the following into the terminal:
> console.log("Hello, World");
To exit the REPL, press Control-C twice. Using the REPL comes in handy when you want to test simple statements like the example above. This can prove more convenient than saving code to a file—especially if you’re writing throwaway code.
To execute a program you have written in a file, in your terminal run the command node filename, where filename is replaced with the name of your JavaScript file. You do not have to type the js extension of the filename to run the script. And you must be in the root directory where the file lives.
Let’s try an example. Create a file named hello.js. Inside, we will put the following code:
console.log("Hello, World");
Run the code from the terminal:
$ node hello
If all is well, you will see the text "Hello, World" output to the terminal. From now on, you can test the code examples from this tutorial either by using the Node REPL or by saving to a file.
Designing a Program
Before you write any code, you should take the time to understand the problem. What data do you need? What is the outcome? What tests does your program need to pass?
When you understand the requirements of the program, then you can write the steps to solve it. The steps are your algorithm. Your algorithm is not code. It is plain English (replace English with your native language) instructions for solving the problem. For example, if you want to write an algorithm for cooking top ramen, it might look like this:
Remove top from cup.
Empty seasoning pack into cup.
Fill cup with water.
Microwave on high for 2 minutes.
Cool for 1 minute.
Yes, I was hungry when I thought of this. And no, this is not something you would actually be given as a programming problem. Here is an example of a problem that is more practical. It is an algorithm to calculate the average of a list of numbers.
Calculate the sum all of the numbers.
Get the total number of numbers.
Divide the sum by the total.
Return the result.
Understanding the problem and coming up with an algorithm are the most important steps in programming. When you feel confident in your algorithm, then you should write some test cases. The tests will show how your code should behave. Once you have your tests, then you write code and tweak it until your tests pass. Depending on how complex your problem is, each one of the steps in your algorithm may need to be broken down further.
Task
Write an algorithm to calculate the factorial of a number. The factorial of a number *n* is the product of all integers from 1 to *n*. For example, 4! (4 factorial) is 1 x 2 x 3 x 4 = 24.
Syntax
A program is similar to the language we speak with. The only difference is a programming language is meant to communicate with the computer (and other programmers who have to use it). The rules for constructing the program are its syntax. Programs consist of statements. A statement can be thought of as a sentence. In JavaScript, you must put a semicolon at the end of a statement. Example:
a = 2 + 2;
Statements consist of expressions. Expressions are like the subject/predicate parts of a sentence. In a programming language, expressions have a value. Expressions consist of keywords like var and for which are the built-in vocabulary of the language; data like a number or string; and operators like + and =. Example:
2+2
Here is a list of arithmetic operators:
+ - Addition
- - Subtraction
* - Exponentiation
* - Multiplication
/ - Division
% - Remainder
++ - Increment
-- - Decrement
The remainder operator returns the remainder after dividing two numbers. For example, 4 % 2 returns 0, and 5 % 3 returns 2. The remainder operator is commonly used to find out if a value is even or odd. Even values will have a remainder 0.
Task
Find the value of the following expressions. Write down your answers first, and then check them in your REPL.
9 % 3
3 % 9
3 % 6
3 % 4
3 % 3
3 % 2
Variables
A variable is a name that represents a value in the computer’s memory. Any value we would like to store or to use over and over should be placed in a variable. One way of creating variables is with the var keyword. But the preferred way is to use the let or const keywords. Here are some examples of using let to create variables:
Declaring a variable:
let a;
Declaring and initializing a variable:
let a = 1;
Reassigning a variable:
a = 2;
Constants are variables that cannot change. They can only be assigned once. Constants that have objects or arrays as values can still be modified because they are assigned by reference. The variables do not hold a value; instead, they point to the location of the object. Example:
const a = {foo:1,bar:2}; a.baz = 3; console.log( a ); // displays { foo: 1, bar: 2, baz: 3 }
However, this will give you an error:
const a = {foo:1,bar:2}; a = {}; console.log( a );
Data Types
Data types have rules for how they can be operated on. For example, if we add two numbers, we get their sum. But if we add a number with a string, we get a string. Here is a list of the different data types:
Undefined: a variable that has not been assigned a value
Null: no value
Boolean: an entity that has the value true or false
String: a sequence of characters
Symbol: a unique, unchanging key
Number: integer and decimal values
Object: a collection of properties
A string is a data type that consists of characters. A string will be surrounded with single quotes or double quotes. Strings also have methods you can use to perform actions on them. The following are some examples of actions you can perform on strings.
Determine if a string begins with a substring:
"Hello, World".startsWith("hello"); //true
Determine if a string ends with a substring:
"Hello, World".endsWith("World"); //true
Determine if a substring is located anywhere in a string:
"Hello, World".includes("World"); //true
Repeat a string a specified number of times:
"Hello".repeat(3); //HelloHelloHello
We can turn a string into an array with the spread operator: ...
let str = [..."hello"]; console.log(str); //[ 'h', 'e', 'l', 'l', 'o' ]
Template literals are a special kind of string that use backticks: ` `. We can use them to insert variables within a string like this:
let name = "World"; let greeting = `Hello, ${name}`; console.log(greeting); //Hello, World
We can create multiline strings like this:
` <div> <h1>Hello, World</h1> </div> `
Review
We have seen how to set up our development environment using Node. The first step to programming is writing the steps to solve the problem. This is called the algorithm. The actual code will consist of many statements. Statements are the program’s instructions and are made up of expressions. Expressions are useful in our program if we assign them to variables. Variables are created with the let or const keyword.
In part 2, I will explain conditionals.
Resources
repl.it
Sublime Text
Node.js
ES6 specification
You Don’t Know JS: ES6 and Beyond
by Alberta Williams via Envato Tuts+ Code http://ift.tt/2yAR1vD
0 notes
Text
PHP interview questions and Openings for freshers
PHP interview questions and answers for freshers
Welcome !!!. In this section we are providing you some frequently asked PHP Interview Questions which will help you to win interview session easily. Candidates must read this section,Then by heart the questions and answers. Also, review sample answers and advice on how to answer these typical interview questions. PHP is an important part of the web world, and every web developer should have the basic knowledge in PHP.Common PHP interview questions, which should help you become a best PHP codder. We hope you find these questions useful. If you are an interviewer, Take the time to read the common interview questions you will most likely be asked.
For more information about placement and interviews visit us at - https://www.datacouncil.in/
or Walk in to our institute at karvenagar, Pune.
What is PHP?PHP is a server side scripting language commonly used for web applications. PHP has many frameworks and cms for creating websites.Even a non technical person can cretae sites using its CMS.WordPress,osCommerce are the famus CMS of php.It is also an object oriented programming language like java,C-sharp etc.It is very eazy for learning
What is the use of "echo" in php?It is used to print a data in the webpage, Example: , The following code print the text in the webpage
How to include a file to a php page?We can include a file using "include() " or "require()" function with file path as its parameter.
What's the difference between include and require?If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.
require_once(), require(), include().What is difference between them?require() includes and evaluates a specific file, while require_once() does that only if it has not been included before (on the same page). So, require_once() is recommended to use when you want to include a file where you have a lot of functions for example. This way you make sure you don't include the file more times and you will not get the "function re-declared" error.
Differences between GET and POST methods ?We can send 1024 bytes using GET method but POST method can transfer large amount of data and POST is the secure method than GET method .
How to declare an array in php?Eg : var $arr = array('apple', 'grape', 'lemon');
What is the use of 'print' in php?This is not actually a real function, It is a language construct. So you can use with out parentheses with its argument list. Example print('PHP Interview questions'); print 'Job Interview ');
What is use of in_array() function in php ?in_array used to checks if a value exists in an array
What is use of count() function in php ?count() is used to count all elements in an array, or something in an object
What's the difference between include and require?It's how they handle failures. If the file is not found by require(), it will cause a fatal error and halt the execution of the script. If the file is not found by include(), a warning will be issued, but execution will continue.
What is the difference between Session and Cookie?The main difference between sessions and cookies is that sessions are stored on the server, and cookies are stored on the user's computers in the text file format. Cookies can't hold multiple variable while session can hold multiple variables..We can set expiry for a cookie,The session only remains active as long as the browser is open.Users do not have access to the data you stored in Session,Since it is stored in the server.Session is mainly used for login/logout purpose while cookies using for user activity tracking
How to set cookies in PHP?Setcookie("sample", "ram", time()+3600);
How to Retrieve a Cookie Value?eg : echo $_COOKIE["user"];
How to create a session? How to set a value in session ? How to Remove data from a session?Create session : session_start(); Set value into session : $_SESSION['USER_ID']=1; Remove data from a session : unset($_SESSION['USER_ID'];
what types of loops exist in php?for,while,do while and foreach (NB: You should learn its usage)
MYSQL
How to create a mysql connection?mysql_connect(servername,username,password);
How to select a database?mysql_select_db($db_name);
How to execute an sql query? How to fetch its result ?$my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; "); $result = mysql_fetch_array($my_qry); echo $result['First_name'];
Write a program using while loop$my_qry = mysql_query("SELECT * FROM `users` WHERE `u_id`='1'; "); while($result = mysql_fetch_array($my_qry)) { echo $result['First_name'.]." "; }
How we can retrieve the data in the result set of MySQL using PHP?
What is the use of explode() function ?Syntax : array explode ( string $delimiter , string $string [, int $limit ] ); This function breaks a string into an array. Each of the array elements is a substring of string formed by splitting it on boundaries formed by the string delimiter.
What is the difference between explode() and split() functions?Split function splits string into array by regular expression. Explode splits a string into array by string.
What is the use of mysql_real_escape_string() function?It is used to escapes special characters in a string for use in an SQL statement
Write down the code for save an uploaded file in php.if ($_FILES["file"]["error"] == 0) { move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); echo "Stored in: " . "upload/" . $_FILES["file"]["name"]; }
How to create a text file in php?$filename = "/home/user/guest/newfile.txt"; $file = fopen( $filename, "w" ); if( $file == false ) { echo ( "Error in opening new file" ); exit(); } fwrite( $file, "This is a simple test\n" ); fclose( $file );
How to strip whitespace (or other characters) from the beginning and end of a string ?The trim() function removes whitespaces or other predefined characters from both sides of a string.
What is the use of header() function in php ?The header() function sends a raw HTTP header to a client browser.Remember that this function must be called before sending the actual out put.For example, You do not print any HTML element before using this function.
How to redirect a page in php?The following code can be used for it, header("Location:index.php");
How stop the execution of a php scrip ?exit() function is used to stop the execution of a page
How to set a page as a home page in a php based site ?index.php is the default name of the home page in php based sites
How to find the length of a string?strlen() function used to find the length of a string
what is the use of rand() in php?It is used to generate random numbers.If called without the arguments it returns a pseudo-random integer between 0 and getrandmax(). If you want a random number between 6 and 12 (inclusive), for example, use rand(6, 12).This function does not generate cryptographically safe values, and should not be used for cryptographic uses. If you want a cryptographically secure value, consider using openssl_random_pseudo_bytes() instead.
what is the use of isset() in php?This function is used to determine if a variable is set and is not NULL
What is the difference between mysql_fetch_array() and mysql_fetch_assoc() ?mysql_fetch_assoc function Fetch a result row as an associative array, While mysql_fetch_array()fetches an associative array, a numeric array, or both
What is mean by an associative array?Associative arrays are arrays that use string keys is called associative arrays.
What is the importance of "method" attribute in a html form?"method" attribute determines how to send the form-data into the server.There are two methods, get and post. The default method is get.This sends the form information by appending it on the URL.Information sent from a form with the POST method is invisible to others and has no limits on the amount of information to send.
What is the importance of "action" attribute in a html form?The action attribute determines where to send the form-data in the form submission.
What is the use of "enctype" attribute in a html form?The enctype attribute determines how the form-data should be encoded when submitting it to the server. We need to set enctype as "multipart/form-data" when we are using a form for uploading files
How to create an array of a group of items inside an HTML form ?We can create input fields with same name for "name" attribute with squire bracket at the end of the name of the name attribute, It passes data as an array to PHP. For instance :
Define Object-Oriented MethodologyObject orientation is a software/Web development methodology that is based on the modeling a real world system.An object is the core concept involved in the object orientation. An object is the copy of the real world enity.An object oriented model is a collection of objects and its inter-relationships
How do you define a constant?Using define() directive, like define ("MYCONSTANT",150)
How send email using php?To send email using PHP, you use the mail() function.This mail() function accepts 5 parameters as follows (the last 2 are optional). You need webserver, you can't send email from localhost. eg : mail($to,$subject,$message,$headers);
How to find current date and time?The date() function provides you with a means of retrieving the current date and time, applying the format integer parameters indicated in your script to the timestamp provided or the current local time if no timestamp is given. In simplified terms, passing a time parameter is optional - if you don't, the current timestamp will be used.
Difference between mysql_connect and mysql_pconnect?There is a good page in the php manual on the subject, in short mysql_pconnect() makes a persistent connection to the database which means a SQL link that do not close when the execution of your script ends. mysql_connect()provides only for the databasenewconnection while using mysql_pconnect , the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection... the connection to the SQL server will not be closed when the execution of the script ends. Instead, the link will remain open for future use.
What is the use of "ksort" in php?It is used for sort an array by key in reverse order.
What is the difference between $var and $$var?They are both variables. But $var is a variable with a fixed name. $$var is a variable who's name is stored in $var. For example, if $var contains "message", $$var is the same as $message.
What are the encryption techniques in PHPMD5 PHP implements the MD5 hash algorithm using the md5 function, eg : $encrypted_text = md5 ($msg);mcrypt_encrypt :- string mcrypt_encrypt ( string $cipher , string $key , string $data , string $mode [, string $iv ] ); Encrypts plaintext with given parameters
What is the use of the function htmlentities?htmlentities Convert all applicable characters to HTML entities This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.
How to delete a file from the systemUnlink() deletes the given file from the file system.
How to get the value of current session id?session_id() function returns the session id for the current session.
What are the differences between mysql_fetch_array(), mysql_fetch_object(), mysql_fetch_row()?
What are the different types of errors in PHP ?Here are three basic types of runtime errors in PHP:
what is sql injection ?SQL injection is a malicious code injection technique.It exploiting SQL vulnerabilities in Web applications
What is x+ mode in fopen() used for?Read/Write. Creates a new file. Returns FALSE and an error if file already exists
How to find the position of the first occurrence of a substring in a stringstrpos() is used to find the position of the first occurrence of a substring in a string
What is PEAR?PEAR is a framework and distribution system for reusable PHP components.The project seeks to provide a structured library of code, maintain a system for distributing code and for managing code packages, and promote a standard coding style.PEAR is broken into three classes: PEAR Core Components, PEAR Packages, and PECL Packages. The Core Components include the base classes of PEAR and PEAR_Error, along with database, HTTP, logging, and e-mailing functions. The PEAR Packages include functionality providing for authentication, networking, and file system features, as well as tools for working with XML and HTML templates.
Distinguish between urlencode and urldecode?This method is best when encode a string to used in a query part of a url. it returns a string in which all non-alphanumeric characters except -_. have replece with a percentege(%) sign . the urldecode->Decodes url to encode string as any %and other symbole are decode by the use of the urldecode() function.
What are the different errors in PHP?In PHP, there are three types of runtime errors, they are:Warnings: These are important errors. Example: When we try to include () file which is not available. These errors are showed to the user by default but they will not result in ending the script. Notices: These errors are non-critical and trivial errors that come across while executing the script in PHP. Example: trying to gain access the variable which is not defined. These errors are not showed to the users by default even if the default behavior is changed. Fatal errors: These are critical errors. Example: instantiating an object of a class which does not exist or a non-existent function is called. These errors results in termination of the script immediately and default behavior of PHP is shown to them when they take place. Twelve different error types are used to represent these variations internally.
1. mysql_fetch_row
2. mysql_fetch_array
3. mysql_fetch_object
4. mysql_fetch_assoc
Mysql_fetch_array Fetch a result row as an associative array, a numeric array, or both.
mysql_fetch_object ( resource result ) Returns an object with properties that correspond to the fetched row and moves the internal data pointer ahead. Returns an object with properties that correspond to the fetched row, or FALSE if there are no more rows
mysql_fetch_row() fetches one row of data from the result associated with the specified result identifier. The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
1. Notices: These are trivial, non-critical errors that PHP encounters while executing a script - for example, accessing a variable that has not yet been defined. By default, such errors are not displayed to the user at all - although you can change this default behavior.
2. Warnings: These are more serious errors - for example, attempting to include() a file which does not exist. By default, these errors are displayed to the user, but they do not result in script termination.
3. Fatal errors: These are critical errors - for example, instantiating an object of a non-existent class, or calling a non-existent function. These errors cause the immediate termination of the script, and PHP's default behavior is to display them to the user when they take place.
For more information about placement and interviews visit us at - https://www.datacouncil.in/
or Walk in to our institute at karvenagar, Pune.
0 notes