The document provides specifications for a regular expression problem involving matching words from a dictionary to tile patterns containing wildcards. It specifies that the system should:
1) Find words from the dictionary that match patterns formed by 7 tiles, where blank tiles act as wildcards.
2) Perform the matching in O(n) time complexity to allow processing hundreds of tile sets efficiently.
3) Include test code that verifies the solution by exhaustively generating all permutations of tile patterns and matching them to words, for comparison with the algorithm's results.
Google interviewer asked for an algorithm to extract the k smallest elements from a set of ordered arrays. I suggested a vectorised bucket sort and merge sort approach. I took the problem offline and produced this analysis and C++.
Java 8 Stream API. A different way to process collections.David Gómez García
A look on one of the features of Java 8 hidden behind the lambdas. A different way to iterate Collections. You'll never see the Collecions the same way.
These are the slides I used on my talk at the "Tech Thursday" by Oracle in June in Madrid.
Google interviewer asked for an algorithm to extract the k smallest elements from a set of ordered arrays. I suggested a vectorised bucket sort and merge sort approach. I took the problem offline and produced this analysis and C++.
Java 8 Stream API. A different way to process collections.David Gómez García
A look on one of the features of Java 8 hidden behind the lambdas. A different way to iterate Collections. You'll never see the Collecions the same way.
These are the slides I used on my talk at the "Tech Thursday" by Oracle in June in Madrid.
This presentation considers certain specific features of C++11 and additions to STL library (uniform initialization, new containers and methods, move semantics).
Presentation by Taras Protsiv (Software Engineer, GlobalLogic), Kyiv, delivered at GlobalLogic C++ TechTalk in Lviv, September 18, 2014.
More details -
http://www.globallogic.com.ua/press-releases/lviv-cpp-techtalk-coverage
This presentation is about multitasking with std::future.
Presentation by Dmytro Gurin (Lead Software Engineer, GlobalLogic, Kyiv), delivered at GlobalLogic C++ TechTalk in Lviv, September 18, 2014.
More details -
http://www.globallogic.com.ua/press-releases/lviv-cpp-techtalk-coverage
After a recap of implicits I introduce the type class mechanics in Scala. Then I have a look at ways for good non-intrusive type class design. The main focus of this presentation are type classes in Scala. In the last chapter I show the Haskell implementation of my example.
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
Higher-order functions such as map(), flatmap(), filter() and reduce() have their origins in mathematics and ancient functional programming languages such as Lisp. But today they have entered the mainstream and are available in languages such as JavaScript, Scala and Java 8. They are well on their way to becoming an essential part of every developer’s toolbox.
In this talk you will learn how these and other higher-order functions enable you to write simple, expressive and concise code that solve problems in a diverse set of domains. We will describe how you use them to process collections in Java and Scala. You will learn how functional Futures and Rx (Reactive Extensions) Observables simplify concurrent code. We will even talk about how to write big data applications in a functional style using libraries such as Scalding.
An Introduction to Part of C++ STL for OI. Introduced the common use of STL algorithms and containers, especially those are helpful to OI.
Also with some examples.
This presentation considers certain specific features of C++11 and additions to STL library (uniform initialization, new containers and methods, move semantics).
Presentation by Taras Protsiv (Software Engineer, GlobalLogic), Kyiv, delivered at GlobalLogic C++ TechTalk in Lviv, September 18, 2014.
More details -
http://www.globallogic.com.ua/press-releases/lviv-cpp-techtalk-coverage
This presentation is about multitasking with std::future.
Presentation by Dmytro Gurin (Lead Software Engineer, GlobalLogic, Kyiv), delivered at GlobalLogic C++ TechTalk in Lviv, September 18, 2014.
More details -
http://www.globallogic.com.ua/press-releases/lviv-cpp-techtalk-coverage
After a recap of implicits I introduce the type class mechanics in Scala. Then I have a look at ways for good non-intrusive type class design. The main focus of this presentation are type classes in Scala. In the last chapter I show the Haskell implementation of my example.
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
Higher-order functions such as map(), flatmap(), filter() and reduce() have their origins in mathematics and ancient functional programming languages such as Lisp. But today they have entered the mainstream and are available in languages such as JavaScript, Scala and Java 8. They are well on their way to becoming an essential part of every developer’s toolbox.
In this talk you will learn how these and other higher-order functions enable you to write simple, expressive and concise code that solve problems in a diverse set of domains. We will describe how you use them to process collections in Java and Scala. You will learn how functional Futures and Rx (Reactive Extensions) Observables simplify concurrent code. We will even talk about how to write big data applications in a functional style using libraries such as Scalding.
An Introduction to Part of C++ STL for OI. Introduced the common use of STL algorithms and containers, especially those are helpful to OI.
Also with some examples.
Assignment 13/assg-13.cppAssignment 13/assg-13.cpp/**
* @author Jane Programmer
* @cwid 123 45 678
* @class COSC 2336, Spring 2019
* @ide Visual Studio Community 2017
* @date April 8, 2019
* @assg Assignment 13
*
* @description Assignment 13 Dictionaries and Hash table
* implementations.
*/
#include<cassert>
#include<iostream>
#include"KeyValuePair.hpp"
#include"Employee.hpp"
#include"HashDictionary.hpp"
usingnamespace std;
/** main
* The main entry point for this program. Execution of this program
* will begin with this main function.
*
* @param argc The command line argument count which is the number of
* command line arguments provided by user when they started
* the program.
* @param argv The command line arguments, an array of character
* arrays.
*
* @returns An int value indicating program exit status. Usually 0
* is returned to indicate normal exit and a non-zero value
* is returned to indicate an error condition.
*/
int main(int argc,char** argv)
{
// -----------------------------------------------------------------------
cout <<"----- testing Employee record and KeyValuePair class -----------"<< endl;
KeyValuePair<int, string> pair(42,"blue");
cout <<"test key: "<< pair.key()<< endl;
assert(pair.key()==42);
cout <<"test value: "<< pair.value()<< endl;
assert(pair.value()=="blue");
int id =3;
Employee e(id,"Derek Harter","1234 Main Street, Commerce TX",12345.67);
cout << e << endl;
assert(e.getId()==3);
assert(e.getName()=="Derek Harter");
cout << endl;
// -----------------------------------------------------------------------
cout <<"-------------- testing quadratic probing -----------------------"<< endl;
constint TABLE_SIZE =7;
HashDictionary<int,Employee> dict(TABLE_SIZE, EMPTY_EMPLOYEE_ID);
cout <<"Newly created hash dictionary should be empty, size: "<< dict.size()<< endl;
assert(dict.size()==0);
int probeIndex =0;
//cout << "probe index: " << probeIndex
// << " returned probe value: " << dict.probe(id, probeIndex)
// << endl;
//assert(dict.probe(id, probeIndex) == 2);
probeIndex =1;
//cout << "probe index: " << probeIndex
// << " returned probe value: " << dict.probe(id, probeIndex)
// << endl;
//assert(dict.probe(id, probeIndex) == 5);
probeIndex =5;
//cout << "probe index: " << probeIndex
// << " returned probe value: " << dict.probe(id, probeIndex)
// << endl;
//assert(dict.probe(id, probeIndex) == 37);
cout << endl;
// -----------------------------------------------------------------------
cout <<"-------------- testing mid-square hashing ----------------------"<< endl;
// the following asserts will only work for 32 bit ints, leave asserts
// commented out if you have 64 bit asserts
cout <<"Assuming 32 bit (4 byte) ints for these tests: "<<sizeof(int)<< endl;
assert(sizeof(int)==4);
//id = 3918;
//cout << "hash key: " << id
// << " returned hash value: " << dict.hash(id)
// << endl; ...
String Function
1. charAt():
This method returns the character from the specified index.Characters in a string are indexed from left to right. The index of the first character is 0, and the index of the last character in a string called stringName is stringName.length - 1.
Syntax:
string.charAt(index);
Return Value:
Returns the character from the specified index.
Example:
<html>
<head>
<title>JavaScript String charAt() Method</title>
</head>
<body>
</body>
</html>
Output:
str.charAt(0) is:T
2. concat():
Description:
This method adds two or more strings and returns a new single string.
Syntax:
string.concat(string2, string3[, ..., stringN]);
parameters:
string2...stringN : These are the strings to be concatenated.
Return Value:
Returns a single concatenated string.
Example:
<html>
<head>
<title>JavaScript String concat() Method</title>
</head>
<body>
</body>
</html>
Output:
Concatenated String :This is string oneThis is string two.
3. indexOf():
Description:
This method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found.
Syntax:
string.indexOf(searchValue[, fromIndex])
Parameters:
searchValue : A string representing the value to search for.
fromIndex : The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0.
Return Value:
Returns the index of the found occurrence otherwise -1 if not found.
Example:
<html>
<head>
<title>JavaScript String indexOf() Method</title>
</head>
<body>
<br />");
var index = str1.indexOf( "one" );
document.write("indexOf found String :" + index );
</body></html>
Oputput:
indexOf found String :8
indexOf found String :15
4. lastIndexOf():
Description:
This method returns the index within the calling String object of the last occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found.
Syntax:
string.lastIndexOf(searchValue[, fromIndex])
Parameters:
searchValue : A string representing the value to search for.
fromIndex : The location within the calling string to start the search from. It can be any integer between 0 and the length of the string. The default value is 0.
Return Value:
Returns the index of the last found occurrence otherwise -1 if not found.
Example:
<html>
<head>
<title>JavaScri
For this lab, you will write the following filesAbstractDataCalc.pdfalokindustries1
For this lab, you will write the following files:
AbstractDataCalc
AverageDataCalc
MaximumDataCalc
MinimumDataCalc
MUST USE ALL 6 FILES PROVIDED
AbstractDataCalc is an abstract class, that AverageDataCalc, MaximumDataCalc and
MinimumDataCalc all inherit.
The following files are provided
CSVReader
To help read CSV Files.
DataSet
This file uses CSVReader to read the data into a List> type structure. Think of this as a Matrix
using ArrayLists. The important methods for you are rowCount() and getRow(int i) - Between
CSVReader and DataSet - all your data is loaded for you!
Main
This contains a public static void String[] args. You are very free to completely change this main
(and you should!). We don't test your main, but instead your methods directly. However, it will
give you an idea of how the following output is generated.
Sample Input / Output
Given the following CSV file
The output of the provided main is:
Note: the extra line between Set results is optional and not graded. All other spacing must be
exact!
Specifications
You will need to implement the following methods at a minimum. You are free to add additional
methods.
AbstractDataCalc
public AbstractDataCalc(DataSet set) - Your constructor that sets your dataset to an instance
variable, and runCalculations() based on the dataset if the passed in set is not null. (hint: call
setAndRun)
public void setAndRun(DataSet set) - sets the DataSet to an instance variable, and if the passed
in value is not null, runCalculations on that data
private void runCalculations() - as this is private, technically it is optional, but you are going to
want it (as compared to putting it all in setAndRun). This builds an array (or list) of doubles,
with an item for each row in the dataset. The item is the result returned from calcLine.
public String toString() - Override toString, so it generates the format seen above. Method is the
type returned from get type, row counting is the more human readable - starting at 1, instead of
0.
public abstract String getType() - see below
public abstract double calcLine(List line) - see below
AverageDataCalc
Extends AbstractDataCalc. Will implement the required constructor and abstract methods only.
public abstract String getType() - The type returned is "AVERAGE"
public abstract double calcLine(List line) - runs through all items in the line and returns the
average value (sum / count).
MaximumDataCalc
Extends AbstractDataCalc. Will implement the required constructor and abstract methods only.
public abstract String getType() - The type returned is "MAX"
public abstract double calcLine(List line) - runs through all items, returning the largest item in
the list.
MinimumDataCalc
Extends AbstractDataCalc. Will implement the required constructor and abstract methods only.
public abstract String getType() - The type returned is "MIN"
public abstract double calcLine(List line) - runs through all items, returning the smallest item in
the list.
MaximumDataCalc.java------ write code .
Using Regular Expressions and Staying SaneCarl Brown
Presentation I gave to the local http://www.cocoacoder.org/ meeting on using Regular Expression in Cocoa code (although much of it applies to other languages as well).
An O(n+m) in time and O(1) in space search-algorithm for substr, length m, in target string, length n. Simpler than trie or Knuth-Morris-Pratt. Can be reduced to O(n) using Group Theoretic O(1)-updatable hash that replaces the cumulative sum, which requires an O(m) verification step because "+" is commutative and cannot distinguish between anagrams: a+b+c = a+c+b = c+a+b etc. I am not uploading the hash, because it means giving away R&D I do in quantum simulations.
Kernel Recipes 2019 - GNU poke, an extensible editor for structured binary dataAnne Nicolas
GNU poke is a new interactive editor for binary data. Not limited to editing basic ntities such as bits and bytes, it provides a full-fledged procedural, interactive programming language designed to describe data structures and to operate on them. Once a user has defined a structure for binary data (usually matching some file format) she can search, inspect, create, shuffle and modify abstract entities such as ELF relocations, MP3 tags, DWARF expressions, partition table entries, and so on, with primitives resembling simple editing of bits and bytes. The program comes with a library of already written descriptions (or “pickles” in poke parlance) for many binary formats.
GNU poke is useful in many domains. It is very well suited to aid in the development of programs that operate on binary files, such as assemblers and linkers. This was in fact the primary inspiration that brought me to write it: easily injecting flaws into ELF files in order to reproduce toolchain bugs. Also, due to its flexibility, poke is also very useful for reverse engineering, where the real structure of the data being edited is discovered by experiment, interactively. It is also good for the fast development of prototypes for programs like linkers, compressors or filters, and it provides a convenient foundation to write other utilities such as diff and patch tools for binary files.
This talk (unlike Gaul) is divided into four parts. First I will introduce the program and show what it does: from simple bits/bytes editing to user-defined structures. Then I will show some of the internals, and how poke is implemented. The third block will cover the way of using Poke to describe user data, which is to say the art of writing “pickles”. The presentation ends with a status of the project, a call for hackers, and a hint at future works.
Jose E. Marchesi
I am Moffat K. I am a C++ Programming Homework Expert at cpphomeworkhelp.com. I hold a Masters in Programming from London, UK. I have been helping students with their homework for the past 6 years. I solve homework related to C++ Programming.
Visit cpphomeworkhelp.com or email info@cpphomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with C++ Programming Homework.
The Morse code (see Table 6.10 in book) is a common code that is use.pdfbhim1213
The Morse code (see Table 6.10 in book) is a common code that is used to encode messages
consisted of letters and digits. Each letter consists of a series of dots and dashes; for example, the
code for the letter a is *- and the code for the letter b is -***. Store each letter of the alphabet in a
node of a binary tree of level 5. The root node is at level 1 and stores no letter. The left node at
level 2 stores the letter e (code is *), and the right node stores letter t (code is -). The 4 nodes at
level 3 store the letters with codes (**, *-, -*, --). To build the tree (see Figure 6.38 in book),
read a file in which each line consists of a letter followed by its code. The letters should be
ordered by tree level. To find the position for a letter in the tree, scan the code and branch left for
a dot and branch right for a dash. Encode a message by replacing each letter by its code symbol.
Then decode the message using the Morse code tree. Make sure you use a delimiter symbol
between coded letters.
Implementation Notes: You will need to complete the generic implementation of the BinaryTree
data structure first (see slides). Once it is complete, solve the problem above (note that the book
uses dots and dashes, we will use the asterisk (*) as the dot, hyphen (-) as a dash, and space ( ) as
the delimiter symbol between coded letters). Provide a menu program that asks the user to 1) test
output for all morse code letters with their respective translated alphabet letters (make sure you
are using the binary tree to do the actual translation, output as a nicely formatted table), 2) enter
an input file name to decode morse code and output the translated text to the screen, or 3) enter
in a line of morse code through the console to decode morse code and output the translated text
to the screen
relevenat picture of both the tree diagram and the table of morse code
Solution
JAVA CODE:
import java.io.*;
import java.util.*;
public class MorseCoder implements MorseCodeInterface {
private MorseNode root;
/**
* constructor to build the tree
*/
public MorseCoder() {
root = new MorseNode();
readTreeInfo();
}
/**
* reads in the tree info from the text file (helper method)
*/
private void readTreeInfo() {
Scanner input = null;
try {
input = new Scanner(new File(\"encodings.txt\"));
} catch (FileNotFoundException exception) {
System.out.println(\"File not found!\");
}
while (input.hasNextLine()) {
String data = input.nextLine().trim();
if (data.length() > 0) {
add(data.substring(1).trim(), data.charAt(0));
}
}
input.close();
}
/**
* adds the letter to the tree based on the mcode string (helper method)
* @param mcode the string being fed in
* @param ltr the letter being added at the node
*/
private void add(String mcode, char ltr) {
MorseNode current = root;
String signal = \" \";
for (int i = 0; i < mcode.length(); i++) {
signal = mcode.substring(i, i + 1);
if (signal.equals(\".\")) {
if (current.getLeft() != null) {
current = current.getLeft();
} else {
current.set.
I have question in c++ program I need the answer as soon as possible.docxdelciegreeks
I have question in c++ program I need the answer as soon as possible
I attached the file
1.1
Nested Loops – Lab3C.cpp
Loops often have loops inside them. These are called “nested” loops. In this exercise you will finish a nested loop that reads lines of numbers from a file and computes and prints out the sum of each line.
//C++ Lab3C.cpp
//
//
//
//1. [include required header files]//
using namespace std;
int main()
{
[2. Declare required variables]
try
{
//3> put your file name & Open file as an input mode
ifstream Openfile(" “);
//4> If file doesn't exist then throw error number
if(Openfile.good())
{
while( getline(Openfile, sLine)) //Outer While Loop Condition
{
cout << "The Contents of line sLine" << sLine << "\n";
stringstream Str(sLine);
while (Str >> temp ) //Inner While Loop Condition
{
cout << "String ~to double" << temp;
}// Inner while Loop
} //Outer While Loop
Openfile.close();
//3> Catch the error number and display message
}
else {
throw 10;
}
} //if
catch(int e)
{
cout << "File Not found " << e << endl;
}
//system("pause"); //Pause
return 0;
}//main
1.2
Once you have completed the program, run it on the input file below:
Lab4C.in
10 20 30 40 50
60 70 80 90.0
11 13.0
20 40 70 19.0
Lab4C.out or Lab4C.doc with screen shot
Read Line 0 10.0 Sum 10.0
Read Line 0 20.0 Sum 30.0
Read Line 0 30.0 Sum 60.0
Read Line 0 40.0 Sum 100.0
Read Line 0 50.0 Sum 150.0
…..
Read Line 3 20.0 Sum 20.0
Read Line 3 40.0 Sum 60.0
Read Line 3 70.0 Sum 130.0
Read Line 3 19.0 Sum 149.0
1.3
Upload your four files (Lab3A.cpp, Lab3B.cpp, Lab3C.cpp and Lab3C.doc) as one single zip file named “Lab3ABC.zip”)
2.
Lab3D – Two Dimensional Arrays
2.1
Declaring 2D arrays
In C++, to make a 2D array, we simply declare an array where the type is an array. To see how this works, first look at how we create an int array with 10 elements. One might type
int arr1D[ 10] ;
What the above code actually does is create a new “int Array” that reserves enough space to store 10 integers. For creating a 2D arrays, we can make an array of them, by appending another set of square brackets:
int arr2D[3][7];
This declares a two dimensional array of ints with 3 rows and 7 columns. By convention, we think of the array as being indexed in “Row Major Order”, which means that the row (y value) comes before the column (x value).
Thus, visually, the array looks like this:
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
The top left element is at position [0][0], and the bottom right element is at position [2][6]. The array elements are initialized just as in the 1D case ( Numerics are set to 0, and object types are set to null). To access one of the elements of a 2D array, we use double bracket notation again, so we can write
arr2D[0][1] = 1;
arr2D[2][3] = 4;
This would give us the array:
0 1 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 4 0 0 0
If we want to visit or process every ele ...
I am Arnold H. I am a C++ Programming Homework Expert at cpphomeworkhelp.com. I hold a Masters in Programming from The University of Sheffield, UK. I have been helping students with their homework for the past 6 years. I solve homework related to C++ Programming.
Visit cpphomeworkhelp.com or email info@cpphomeworkhelp.com. You can also call on +1 678 648 4277 for any assistance with C++ Programming Homework.
1.1 Nested Loops – Lab3C.cppLoops often have loops inside .docxchristiandean12115
1.1 Nested Loops – Lab3C.cpp
Loops often have loops inside them. These are called “nested” loops. In this exercise you will finish a nested loop that reads lines of numbers from a file and computes and prints out the sum of each line.
//C++ Lab3C.cpp
// <Your Name>
// <Your Section>
// <Your student id>
//1. [include required header files]//
using namespace std;
int main()
{
[2. Declare required variables]
try
{
//3> put your file name & Open file as an input mode
ifstream Openfile(" “);
//4> If file doesn't exist then throw error number
if(Openfile.good())
{
while( getline(Openfile, sLine)) //Outer While Loop Condition
{
cout << "The Contents of line sLine" << sLine << "\n";
stringstream Str(sLine);
while (Str >> temp ) //Inner While Loop Condition
{
cout << "String ~to double" << temp;
}// Inner while Loop
} //Outer While Loop
Openfile.close();
//3> Catch the error number and display message
}
else {
throw 10;
}
} //if
catch(int e)
{
cout << "File Not found " << e << endl;
}
//system("pause"); //Pause
return 0;
}//main
1.2 Once you have completed the program, run it on the input file below:
Lab4C.in
10 20 30 40 50
60 70 80 90.0
11 13.0
20 40 70 19.0
Lab4C.out or Lab4C.doc with screen shot
Read Line 0 10.0 Sum 10.0
Read Line 0 20.0 Sum 30.0
Read Line 0 30.0 Sum 60.0
Read Line 0 40.0 Sum 100.0
Read Line 0 50.0 Sum 150.0
…..
Read Line 3 20.0 Sum 20.0
Read Line 3 40.0 Sum 60.0
Read Line 3 70.0 Sum 130.0
Read Line 3 19.0 Sum 149.0
1.3 Upload your four files (Lab3A.cpp, Lab3B.cpp, Lab3C.cpp and Lab3C.doc) as one single zip file named “Lab3ABC.zip”)
2. Lab3D – Two Dimensional Arrays
2.1 Declaring 2D arrays
In C++, to make a 2D array, we simply declare an array where the type is an array. To see how this works, first look at how we create an int array with 10 elements. One might type
int arr1D[ 10] ;
What the above code actually does is create a new “int Array” that reserves enough space to store 10 integers. For creating a 2D arrays, we can make an array of them, by appending another set of square brackets:
int arr2D[3][7];
This declares a two dimensional array of ints with 3 rows and 7 columns. By convention, we think of the array as being indexed in “Row Major Order”, which means that the row (y value) comes before the column (x value).
Thus, visually, the array looks like this:
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 0 0 0 0
The top left element is at position [0][0], and the bottom right element is at position [2][6]. The array elements are initialized just as in the 1D case ( Numerics are set to 0, and object types are set to null). To access one of the elements of a 2D array, we use double bracket notation again, so we can write
arr2D[0][1] = 1;
arr2D[2][3] = 4;
This would give us the array:
0 1 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 4 0 0 0
If.
Lab Assignment 4 CSE330 Spring 2014 Skeleton Code for ex.docxMARRY7
/* Lab Assignment 4 CSE330 Spring 2014 */
/* Skeleton Code for ex0 of lab4 */
/* No code will be provided for ex1 of lab4 */
#include <stdio.h> /* for NULL */
#include <ctype.h> /* for atoi() */
#include <errno.h> /* for perror() */
#include <signal.h> /* for sigvec() etc. */
#include <sys/types.h> /* for <arpa/inet.h> */
#include <sys/socket.h> /* for PF_INET, etc. */
#include <netinet/in.h> /* for struct sockaddr_in */
#include <arpa/inet.h> /* for inet_addr() */
#include <sys/time.h>
#include "lab4.h"
/* this is in netinet/in.h; included here for reference only.
struct sockaddr_in {
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
*/
/***************************************************************************/
#define LINESIZE 80
#define TYPE0TIMEOUT 3
#define TYPE1TIMEOUT 30
/* You should give a long timeout, like 30sec, otherwise */
/* duplicated responses from the server may cause some problem */
#define MAXRETRY 3
/***************************************************************************/
static char *RCSId="$Id: client2.c,v 4 2014/04/20 03:15:07 cse3300 Exp $";
/***************************************************************************/
/* some functions you may find useful if you implement them */
extern int stringToAddress(char *s, struct sockaddr_in *a);
extern int msgok(LABMSG *);
extern u_short msgchecksum(u_short *);
extern void alarmCatcher(void);
extern int tries; /* for retransmission routines */
int numtries;
/***** this will die ****/
FILE *logFile;
void die(char *s)
{
perror(s);
exit(2);
}
void startTimer(int secs)
{
alarm(secs);
}
void stopTimer(void)
{
alarm(0);
}
/* should change it by yourself if needed!!! */
void printResponse(LABMSG *mp, int ck)
{
int type;
mp->courseEtc = ntohs(mp->courseEtc);
type = ( (mp->courseEtc & MESSAGETYPE) !=0)?1:0;
printf("course=%d, Type=%d\n", mp->courseEtc&0x3fff,type);
if (ntohl(mp->cookie) != ck)
printf("Cookies don't match: sent %x received %x\n",mp->cookie,ck);
if (mp->courseEtc & REQRESP)
printf("response ");
else {
printf("request??\n");
return;
}
mp->result = ntohs(mp->result);
/*printf(" result = %x: ",mp->result);*/
if (mp->result&TRANSOUTCOME) { /* Check outcome */
printf("error: ");
switch (mp->result & 0x7fff) {
case ERROR_CHECKSUM:
printf("checksum failure\n");
break;
case ERROR_SYNTAX:
printf("syntax error\n");
break;
case ERROR_UNKSSN:
printf("unknown SSN %d\n", ntohl(mp->reqSSN) );
break;
case ERROR_SERVER:
printf("Unspecified Server Error\n");
default:
printf("Unknown Error.\n");
} /* case switch */
} else { /* successful transaction */
if(type)printf("Test succeeded.");
if (!type) /* Type 0 -- print SSN and Response */
printf(": %d -> %d\n", ntohl(mp->reqSSN), mp->result&0x7fff);
else
printf("\n"); /* XXX print number of responses */
}
}
/*-----------------------------------*/
/* added by ZXC:
this fun ...
This is the user guide for the quantum simulator I have developed. It includes tutorials on advanced quantum mechanics, quantum algorithms and geometric algebra, together with examples of using the simulator do quantum mechanics, Special Relativity, geometric algebra and quantum computing.
O(n) in time, O(1) in space substr-search algorithm, using O(1)-updatable hash derived using Group Theory. Hash function is greyed out, to prevent IP-theft. Algorithm is far simpler than trie or Knuth-Morris-Pratt. Very surprised it has not been discovered by others.
O(n) in time, O(1) in space substr-search algorithm, using O(1)-updatable hash derived using Group Theory. Hash function is greyed out, to prevent IP-theft. Algorithm is far simpler than trie or Knuth-Morris-Pratt. Very surprised it has not been discovered by others.
O(n) in time, O(1) in space substr-search algorithm, using O(1)-updatable hash derived using Group Theory. Hash function is greyed out, to prevent IP-theft. Algorithm is far simpler than trie or Knuth-Morris-Pratt. Very surprised it has not been discovered by others.
This is a roughly O(n) algorithm that generates the kth lexicographically ordered permutation of an n-element array from the integer k. Example, for a three-element
array:
0 --> 0 1 2
1 --> 0 2 1
2 --> 1 0 2
3 --> 1 2 0
4 --> 2 0 1
5 --> 2 1 0
This is a roughly O(n) algorithm that generates the kth lexicographically ordered permutation of an n-element array from the integer k. Example, for a three-element array:
0 --> 0 1 2
1 --> 0 2 1
2 --> 1 0 2
3 --> 1 2 0
4 --> 2 0 1
5 --> 2 1 0
A class that automates conversion from a C++ recursive function to an iterative function. It allow the recursive function to preserve its structure by reproducing the "call stack" on an std::stack. The examples use combinatorics to illustrate usage.
Dirac demo (quantum mechanics with C++). Please note: There is a problem with...Russell Childs
Simple demo of a framework I wrote for doing quantum mechanics in C++. It uses Dirac bras, kets, inner & tensor products, operators and so forth for the linear algebra of QM.
UML design for C++11 written to solve a problem at interview, please also see "Interview C++11 code". The UML design can be zoomed to render it more legible.
Example of Dynamic Programming to achieve O(n).
Interview question: N houses, each with weighting on value of goods. How can a burglar maximise profit if they are not allowed to visit neighbouring houses?
Solution: optimum(i) = max( optimum(i-1)-w(i-1)+w(i) , optimum(i-2)+w(i) )
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
Code reviews are vital for ensuring good code quality. They serve as one of our last lines of defense against bugs and subpar code reaching production.
Yet, they often turn into annoying tasks riddled with frustration, hostility, unclear feedback and lack of standards. How can we improve this crucial process?
In this session we will cover:
- The Art of Effective Code Reviews
- Streamlining the Review Process
- Elevating Reviews with Automated Tools
By the end of this presentation, you'll have the knowledge on how to organize and improve your code review proces
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
Unleash Unlimited Potential with One-Time Purchase
BoxLang is more than just a language; it's a community. By choosing a Visionary License, you're not just investing in your success, you're actively contributing to the ongoing development and support of BoxLang.
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamtakuyayamamoto1800
In this slide, we show the simulation example and the way to compile this solver.
In this solver, the Helmholtz equation can be solved by helmholtzFoam. Also, the Helmholtz equation with uniformly dispersed bubbles can be simulated by helmholtzBubbleFoam.
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
COVID-19 had an unprecedented impact on scientific collaboration. The pandemic and its broad response from the scientific community has forged new relationships among public health practitioners, mathematical modelers, and scientific computing specialists, while revealing critical gaps in exploiting advanced computing systems to support urgent decision making. Informed by our team’s work in applying high-performance computing in support of public health decision makers during the COVID-19 pandemic, we present how Globus technologies are enabling the development of an open science platform for robust epidemic analysis, with the goal of collaborative, secure, distributed, on-demand, and fast time-to-solution analyses to support public health.
Your Digital Assistant.
Making complex approach simple. Straightforward process saves time. No more waiting to connect with people that matter to you. Safety first is not a cliché - Securely protect information in cloud storage to prevent any third party from accessing data.
Would you rather make your visitors feel burdened by making them wait? Or choose VizMan for a stress-free experience? VizMan is an automated visitor management system that works for any industries not limited to factories, societies, government institutes, and warehouses. A new age contactless way of logging information of visitors, employees, packages, and vehicles. VizMan is a digital logbook so it deters unnecessary use of paper or space since there is no requirement of bundles of registers that is left to collect dust in a corner of a room. Visitor’s essential details, helps in scheduling meetings for visitors and employees, and assists in supervising the attendance of the employees. With VizMan, visitors don’t need to wait for hours in long queues. VizMan handles visitors with the value they deserve because we know time is important to you.
Feasible Features
One Subscription, Four Modules – Admin, Employee, Receptionist, and Gatekeeper ensures confidentiality and prevents data from being manipulated
User Friendly – can be easily used on Android, iOS, and Web Interface
Multiple Accessibility – Log in through any device from any place at any time
One app for all industries – a Visitor Management System that works for any organisation.
Stress-free Sign-up
Visitor is registered and checked-in by the Receptionist
Host gets a notification, where they opt to Approve the meeting
Host notifies the Receptionist of the end of the meeting
Visitor is checked-out by the Receptionist
Host enters notes and remarks of the meeting
Customizable Components
Scheduling Meetings – Host can invite visitors for meetings and also approve, reject and reschedule meetings
Single/Bulk invites – Invitations can be sent individually to a visitor or collectively to many visitors
VIP Visitors – Additional security of data for VIP visitors to avoid misuse of information
Courier Management – Keeps a check on deliveries like commodities being delivered in and out of establishments
Alerts & Notifications – Get notified on SMS, email, and application
Parking Management – Manage availability of parking space
Individual log-in – Every user has their own log-in id
Visitor/Meeting Analytics – Evaluate notes and remarks of the meeting stored in the system
Visitor Management System is a secure and user friendly database manager that records, filters, tracks the visitors to your organization.
"Secure Your Premises with VizMan (VMS) – Get It Now"
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Modern design is crucial in today's digital environment, and this is especially true for SharePoint intranets. The design of these digital hubs is critical to user engagement and productivity enhancement. They are the cornerstone of internal collaboration and interaction within enterprises.
Why React Native as a Strategic Advantage for Startup Innovation.pdfayushiqss
Do you know that React Native is being increasingly adopted by startups as well as big companies in the mobile app development industry? Big names like Facebook, Instagram, and Pinterest have already integrated this robust open-source framework.
In fact, according to a report by Statista, the number of React Native developers has been steadily increasing over the years, reaching an estimated 1.9 million by the end of 2024. This means that the demand for this framework in the job market has been growing making it a valuable skill.
But what makes React Native so popular for mobile application development? It offers excellent cross-platform capabilities among other benefits. This way, with React Native, developers can write code once and run it on both iOS and Android devices thus saving time and resources leading to shorter development cycles hence faster time-to-market for your app.
Let’s take the example of a startup, which wanted to release their app on both iOS and Android at once. Through the use of React Native they managed to create an app and bring it into the market within a very short period. This helped them gain an advantage over their competitors because they had access to a large user base who were able to generate revenue quickly for them.
Why React Native as a Strategic Advantage for Startup Innovation.pdf
Interview C++11 code
1. /**
* @mainpage
* @anchor mainpage
* @brief
* @details
* @copyright Russell John Childs, PhD, 2016
* @author Russell John Childs, PhD
* @date 2016-05-07
*
* This file contains classes: ExtendedRegExp, Parser
*
* Problem statement:
* You are given a dictionary (dictionary.txt), containing a list of words, one
* per line. Imagine you have seven tiles. Each tile is either blank or contains
* a single lowercase letter (a-z).
*
* Please list all the words from the dictionary that can be produced by using
* some or all of the seven tiles, in any order. A blank tile is a wildcard,
* and can be used in place of any letter.
*
* Try to use a minimal amount of memory.
*
* 1. Find all of the words that can be formed if you don't have to deal with
* blank tiles. (You may skip this step and go straight to step 2).
*
* 2. Find all of the words that can be formed, including those where blank
* tiles are used as wildcards.
*
* 3. Would you do things differently if you had to process several hundred
* tile sets with the same dictionary?
*
* Expectations:
*
* a) Please write down the reasoning or the explanation behind your solution in
* plain English or pseudo-code.
*
* b) Please provide the source code of your implementation. Only 1 and 2 need
* source code.
*
* c) Please include instructions on how to compile and run your code.
*
* d) Bonus points for source code in C/C++/C#.
*
*
* Solution: Use a bucket sort array,
* e.g. "bbbaa " -> bsa[0]=2, bsa[1]=3, bsa[size]=4;
* Iterate through chars in string to be matched:
*
* (1) If chr != wildcard, decrement bsa[chr] iff bsa[chr] > 0
*
* (2) if chr == wildcard or bsa[chr]<0, decrement bsa[size]
*
* (3) if bsa[size] < 0, there is no match.
*
* Specifications:
*
* (1) C shall denote a range of contiguous ASCII characters
*and shall defalut to ['a','z'].
*[This is the specification relating to "tiles"]
*
* (2) W shall denote a "wildcard" character, W.
* [This is the specification relating to "blank tiles"]
*
* (3) The user shall use the single-space ' ' for W.
* [This is the specification relating to "blank tiles"]
* (4) The system shall maintain an internal value for
* W of char(127) so that it is greater than the non-wildcard characters.
*
* (5) R shall denote the regular expression [CW]{n}, where n shall be
2. * specified by the user and default to 7
* [This is the specification relating to "7 tiles"]
*
* (6) S shall denote the set of all permutations of R,
* i.e. the set of all regular expressions that may be formed by
* permuting the characters in R.
*
(7) D shall be a set of strings delimited by the newline character.
* [This is the specification relating to "dictionary"]
*
* (8) No string in D shall contain the wildcard character ' ',
* i.e. no string shall contain a single space.
*
* (9) The system shall list all strings from D for which a match against
* any element in the set S, or a substr of the element,
* exists, in the order in which they appear in D.
* [This is the specification relating to requirements (1) and (2). (1) & (2)
* may be reduced to 1 requirement by deleting " " in regex,
* eg: "abc" <--> "a b c"]
*
* (10) The list specified in (8) shall be returned one string at a time and
* shall not be stored as an internal list of matching strings.
* [This is the specification relating to "minimal memory"]
*
* (11) Matching on a string in D shall be O(n) in complexity.
* [This is the specification relating to requirement (3)]
*
*
* (12) [Next release]. The sytem shall be multithreaded and shall divide
* dictionary.tmp into thread data and shall implement a multithreaded
* bucket-sort [This is the specification relating to requirement (3)].
*
* Compiled and tested under Linux Mint, using g++ 4.8.
*
* g++ options: -O0 -g3 -Wall -O0 -fopenmp -mavx -m64 -g -Wall -c
* -fmessage-length=0 -fno-omit-frame-pointer --fast-math
* -std=c++11 -I/opt/intel/vtune_amplifier_xe_2013/include/
*
* Linker options: -Wl,--no-as-needed -fopenmp
* -L/opt/intel/vtune_amplifier_xe_2013/lib64/
*
* Cmd line options: -lpthread -latomic -littnotify -ldl
*
* Documentation: Doxygen comments for interfaces, normal for impl.
*
* Usage: Place this cpp and unit_test.hpp in the same directory and compile.
* After compiling, run and specify choices at the prompts:
*
* "Please specify the pattern to be matched"
*
* "Please specify the fully-qualified dictionary filename"
*
* "Please specify the fully-qualified filename for the results"
*
* The binary will send:
* n
* (1) test results to stdout
*
* (2) results to results file
*
* (3) Temporary dictionary file to "./tmp_dictionary"
*
* Inputs and outputs:
*
* Input: dictionary file
*
* Input/output: tmp_dictionary file
*
* Output: results file
3. *
* The file unit_test.hpp is required for the tests and must be requested from
* author.
*
* @file dimensional_mechanics.cpp
* @see
* @ref mainpage
*/
#include <string>
#include <fstream>
#include <regex>
#include <algorithm>
#include<set>
#include<random>
#include "unit_test.hpp"
//Unit test framework is written for Linux. This #define ports it to
//Visual Studio 2013
//#define __PRETTY_FUNCTION__ __FUNCSIG__
/**
* addtogroup RegexpProblem
* @{
*/
namespace RegexpProblem
{
/**
* This class implements an O(n) algorithm that determines whether a match can
* be found between any permutation of the characters in a regular expression
*(including wildcard characters).
*
* The algorithm uses bucket sort array that counts the number of occurrences of
* each char in the regex, with the number of wildcards recorded at the end
* of the array.
*
* Example: ".a.bb." - bsa[0]=1, bsa[1]=2, bsa[sizeof(bsa)]=3
*
* Having built the array, the string to be matched is examined.
* Each char found in the string is used to decrement the corresponding
* entry in the array. Example "a" -> bsa[1]=2 ---> bsa[1]=1
*
* When a particular entry is 0, then the entry for the wildcard is decremented
* instead to signify it is being used in place of the character.
*
* Finally, if the entry for the wildcard goes negative, it must mean there is
* no match.
*
* This class is intended to be a replaceable helper class that supplements
* the std::regex lib.
*
*/
class ExtendedRegExp
{
public:
/**
* @param regexp {const std::string&} - A regex, e.g. ".a.b.c"
* @param wildcard {char} - Thr char used as a wildcard, e.g. ' ', '.', '?'
* @param bucket_sort_size {unsigned} - The size for the bucket sort array
*/
ExtendedRegExp(const std::string& regexp, char wildcard=' ',
unsigned bucket_sort_size=28) try :
m_regexp(regexp),
m_buckets(bucket_sort_size, 0),
m_wildcard(127),
m_begin(127)
{
//Initialise bucket sort
4. std::replace(m_regexp.begin(), m_regexp.end(), ' ', char(127));
m_begin = *std::min_element(m_regexp.begin(), m_regexp.end());
for (auto chr : m_regexp)
{
++m_buckets[chr != m_wildcard ? index(chr) : bucket_sort_size - 1];
}
}
catch (std::exception& except)
{
//Print any excpetion thrown
std::cout << "Exception initialising bucket sort in constructor: "
<< except.what()
<< std::endl;
}
/**
* Dtor
*/
~ExtendedRegExp(void)
{
}
/**
* This returns the index of a char relative to the smallest char in the
* regex
*
* Example: If the smallest char in the regex is 'a' then the index
* of 'c' will be 3
*
* @param chr {char} - the char whose relative "ascii" index is to be found
*
* @return {unsigned} - The relative index
*/
unsigned index(char chr)
{
return unsigned((unsigned char)chr) - unsigned((unsigned char)m_begin);
};
/**
* This matches a string against all permutations of the regex used to
* initialise the class object. It uses the bucket sort array described
* in the documentation for this class. Blank strings are a match and
* strings matched against a substr of regex are also a match.
*
* @param word {const std::string&} - the char whose relative "ascii" index
* is to be found
*
* @return {unsigned} - The relative index
*/
bool operator==(const std::string& word)
{
bool ret_val = false;
auto buckets = m_buckets;
auto size = buckets.size();
//Only consider words short enough to be spanned by regecp
auto len = word.length();
if ((0 < len) && (len <= m_regexp.length()))
{
//Loop over chars in word
for (auto chr : word)
{
//Decrement corresponding non-wildcard count in regexcp
if ((index(chr) < (size-1)) && (buckets[index(chr)]>0))
{
//Decrement char count
ret_val = ((--buckets[index(chr)]) >= 0);
}
else //use wildcard if 0 non-wildcards left or not non-wildcard
{
5. //Decrement wildcard count
ret_val = ((--buckets[size-1]) >= 0);
}
//Only continue if we have not encountered a non-match
if (ret_val == false)
{
break;
}
}
}
return ((len > 0) ? ret_val : true);
}
/**
* This returns the length of the regex used to initialise this class object.
*
* @return {unsigned} - The length of the rexgex.
*/
unsigned size(void)
{
return m_regexp.size();
}
private:
std::string m_regexp;
std::vector<int> m_buckets;
char m_wildcard;
char m_begin;
};
/**
* This class iterates over the lines in a dictionary file seeking those that
* match the regegular epxression provided.
*
* @tparam RegExp - The regular expression matching engine to be used.
* The default is ExtendedRegExp. Any user-defined class must provide the
* same public interface as ExtendedRegExp.
*
*/
template<typename RegExp = ExtendedRegExp >
class Parser
{
public:
/**
* This defines the "no-match" string pattern.
*
* @return {const std::string&} - The "no-match" pattern.
*/
static const std::string& no_match(void)
{
static const std::string no_match("!£$%^&&^%$££$%^&");
return no_match;
}
/**
* @param dictionary {const std::string&} - The dictionary file to be parsed
* @param regexp {const RegExp&} - The regular expression to be used for
* matching
*/
Parser(const std::string& dictionary, const RegExp& regexp) :
m_dictionary(dictionary),
m_regexp(regexp)
{
}
/**
* Dtor
6. */
~Parser(void)
{
}
/**
* This resets the dictionary file and regular expression.
*
* @param dictionary {const std::string&} - The dictionary file to be parsed
* @param regexp {const RegExp&} - The regular expression to be used for
* matching
*/
void reset(const std::string& dictionary, const RegExp& regexp)
{
m_dictionary.close();
m_dictionary = std::ifstream(dictionary);
m_regexp = regexp;
}
/**
* This returns the next line in the dictionary file that is successfully
* matched against the regular expression used to initiliase this class
* object.
*
* @return {std::string} - The next line matched
*/
std::string get_next_match(void)
{
//Buffer for dictionary string and return value
std::string ret_val = no_match();
bool ret = false;
//Get length of regexp
unsigned length = m_regexp.size();
//Verify file is good
if (m_dictionary && (m_dictionary.eof() == false))
{
//Loop over strings in file until next match is found
std::getline(m_dictionary, ret_val);
ret = (m_regexp == ret_val);
while ((ret == false) && (m_dictionary.eof() == false))
{
std::getline(m_dictionary, ret_val);
ret = (m_regexp == ret_val);
}
}
//Return the match
return ret ? ret_val : no_match();
}
private:
std::ifstream m_dictionary;
RegExp m_regexp;
};
}
/**
* @}
*/
/**
* addtogroup Tests
* @{
*/
namespace Tests
{
/**
7. * Wrapper class for std::vector converting {a, b, c, ...} to "a b c ..."
*/
struct PrintVector
{
PrintVector(const std::vector<std::string>& vec) :
m_vec(vec)
{
}
std::string str()
{
std::stringstream ss;
for (auto elem : m_vec)
{
ss << elem << " ";
}
return ss.str();
}
std::vector<std::string> m_vec;
};
/**
*
* =========
*
* Test plan
*
* =========
*
* 1. Extract n random lines from dictionary.txt, store in tmp_dictionary.txt.
* n=500.
*
* 2. Randomly select k=0<= k < tmp_dictionary.size for several values of k
*
* 3. For each k, extract kth line from tmp_dictionary.txt and use as
* pattern to ne matched (regex)
*
* 4. For each k, replace 0, 1, 2, ... all chars in regex with " ",
* to test wildcard substitution to give regex'.
*
* 5. For each regex' extract all matching lines in tmp_dictionary and
* store in "results" vector.
*
* 6. For each regex' iterate over all permutations of the characters.
*
* 7 For each permutation of regex' extract all matching lines from
* tmp_dictionary.txt using std::regex_match and store in "control" vector.
*
* 8. Validate that results ==control.
*
* NB: It is unnecessary to consider all permutations of locations to
* place the wildcards, (e.g. "..aa", ".a.a"), since the test already considers
* all permutations of regex and thus covers this equivalence partition.
*
* @param dictionary_file {const std::string&} - Fully-qualified filename
* for dictionary
*
*/
void tests(const std::string& dictionary_file)
{
typedef std::vector<std::string> sv;
//Namespaces for unit test framework and parser.
using namespace UnitTest;
using namespace RegexpProblem;
//Vectors for results of parser algorithm
// "control" generated by exhaustive search
sv results;
sv control;
8. //The regexp to be matched and the matching lines from dictionary
std::string regexp;
std::string match;
//Lambda to access file as file(line_number)
std::string buffer;
unsigned counter = 0;
auto get_line = [&](std::fstream& stream, unsigned index)
{
while (counter != index)
{
std::getline(stream, buffer);
++counter;
}
return buffer;
};
//Create small dictionary with random entries from original to speed tests.
//Create set of random numbers to extract random lines from dictionary file
const unsigned tmp_dictionary_size = 500;
std::fstream dictionary(dictionary_file);
std::fstream tmp_dictionary("tmp_dictionary.txt");
auto size = std::count(std::istreambuf_iterator<char>(dictionary),
std::istreambuf_iterator<char>(), 'n');
dictionary.seekg(0);
std::set<unsigned> random_lines;
//std::random_device dev;
std::mt19937 generator(0);
std::uniform_int_distribution<> distr(1, size);
for (int i = 1; i <= tmp_dictionary_size; ++i)
{
random_lines.insert(distr(generator));
}
//Create temporary dictionary file using the random numbers
for (auto random_line : random_lines)
{
get_line(dictionary, random_line);
if (counter == random_line)
{
tmp_dictionary << buffer << std::endl;
}
}
//Lmabda to perform exhaustive matching over all permuations of regex
//to verify algorithm
auto exhaustive_match = [&](std::string regexp)
{
std::cout << std::endl
<< "Verification requires exhaustive search, please wait";
//Loop over dictionary words while file is good
while (tmp_dictionary && (tmp_dictionary.eof() == false))
{
std::cout << ".";
std::string buffer;
std::getline(tmp_dictionary, buffer);
std::string padded = (buffer.length() >= regexp.length() ? buffer :
buffer + regexp.substr(buffer.length(), regexp.length()));
std::string truncated = regexp.substr(0, buffer.length());
bool is_found = std::regex_match(buffer, std::regex(truncated));
//Sort regexp and remove duplicate chars for std::next_permuation
// (it took me two hours to track down this this silly bug).
unsigned count = 126;
std::string tmp = regexp;
for (auto& chr : tmp)
{
if (chr == '.')
9. {
chr = count;
--count;
}
}
std::sort(tmp.begin(), tmp.end());
//Loop over permutations of regex until match found or exhausted
while ((buffer.length() <= regexp.length()) &&
(is_found == false) &&
std::next_permutation(tmp.begin(), tmp.end()))
{
//Undo the elimination of duplicates for std::next_permutation
//and put them back in
std::string tmp_1 = tmp;
std::replace_if(tmp_1.begin(), tmp_1.end(),
[&](char chr) {return (chr > count); }, '.');
std::string truncated = tmp_1.substr(0, buffer.length());
is_found = std::regex_match(buffer, std::regex(truncated));
}
//Add matches to list of "control" values used for verification
if (is_found)
{
control.push_back(buffer);
}
}
std::cout << std::endl;
};
//Create instances of parser with regexp = tmp_dictionary[random]
unsigned trials = 1;
for (unsigned trial = 1; trial <= trials; ++trial)
{
//Reset dictionary
tmp_dictionary.seekg(0);
counter = 0;
//Get radnwom line from dictionary to act as regexp
std::uniform_int_distribution<> rand_distr(1, tmp_dictionary_size);
unsigned random = rand_distr(generator);
regexp = get_line(tmp_dictionary, random);
//Loop over num of wildcards to use (0 to all chars).
//NB All-wildcards should match all strings of length=regexp.length
auto num_wildcards = regexp.size();
for (unsigned num = 0; num <= num_wildcards; ++num)
{
results.clear();
control.clear();
//Replace relevant char with wildcard
if (num > 0)
{
regexp.replace(num - 1, 1, " ");
}
//Reset dictionary
//tmp_dictionary.seekg(0);
tmp_dictionary.close();
counter = 0;
//Create parser and loop over matches found
Parser<> parser("tmp_dictionary.txt", ExtendedRegExp(regexp, ' '));
while ((match = parser.get_next_match()) != Parser<>::no_match())
{
results.push_back(match);
}
//Perform exhaustive match search for verification
tmp_dictionary.close();
tmp_dictionary.open("tmp_dictionary.txt");
counter = 0;
//for regex - replace ' ' with '.' as wildcard
10. auto tmp_regexp = regexp;
//std::cout << "regex before= " << regexp << std::endl;
std::replace(tmp_regexp.begin(), tmp_regexp.end(), ' ', '.');
//std::cout << "regex after= " << regexp << std::endl;
exhaustive_match(tmp_regexp);
//Verify algorithm against exhaustive match search
VERIFY(std::string("Regexp = ") + """ + tmp_regexp + """,
PrintVector(results).str()) == PrintVector(control).str();
}
}
}
}
/**
* @}
*/
int main(void)
{
using namespace Tests;
using namespace UnitTest;
using namespace RegexpProblem;
/*
//This struct pauses at the end of tests to print out results
struct BreakPointAfterMainExits
{
BreakPointAfterMainExits(void)
{
static BreakPointAfterMainExits tmp;
}
~BreakPointAfterMainExits(void)
{
unsigned set_bp_here_for_test_results = 0;
}
} dummy;
*/
std::string pattern;
std::cout << "Please specify the pattern to be matched" << std::endl;
std::getline(std::cin, pattern, 'n');
std::cout << pattern << std::endl;
std::string dictionary;
std::cout << "Please specify the fully-qualified dictionary filename"
<< std::endl;
std::cin >> dictionary;
std::cout << dictionary << std::endl;
std::string results_file;
std::cout << "Please specify the fully-qualified filename for the results"
<< std::endl;
std::cin >> results_file;
std::cout << results_file << std::endl;
//Run tests
char yes_no;
std::cout << "Do you wish to run the tests (they run slowly on Windows "
<< "and quickly under Linux)? - (y/n):";
std::cin >> yes_no;
if (yes_no == 'y' || yes_no == 'Y')
{
tests(dictionary);
Verify<Results> results;
}
//Match dictionary.tmp against " carnage", send results to results.txt
std::cout << "matching strings in dictionary.txt against " "
11. << pattern
<< " " "
<< " Results will be sent to "
<< results_file
<< ". Please wait ..."
<< std::endl;
Parser<> parser(dictionary, ExtendedRegExp(pattern, ' '));
std::string match;
std::ofstream output(results_file);
while ((match = parser.get_next_match()) != Parser<>::no_match())
{
output << match << std::endl;
}
return 0;
}