Showing latex commands in text string using mathjax - php

I have a text string, for ex. 'A vehicle travels from A to B, distance {$d} km at constant speed. While returning back to A on same path it {$variation} its speed by {$v} km/hr. The total time of journey is {$t} hours. Find the original speed of vehicle.'
The variables in the curly brackets are to be replaced by appropriate latex equation. I'm using php's preg_replace to replace the variables with latex commands. Unfortunately, my latex commands are coming as it is. It is not processed by mathjax.
For ex, above text becomes 'A vehicle travels from A to B, distance 1 km at constant speed. While returning back to A on same path it increased its speed by (\frac{3}{2}) km/hr. The total time of journey is 1 hours. Find the original speed of vehicle.' The frac is shown as it is.
What is wrong here? Please ask me if you need any more info. Thanks

I'm guessing you aren't quoting the replacement text properly. Replacing just the first two variables, tested using spaweditor's regex tool:
<?php
$string = 'A vehicle travels from A to B, distance {$d} km at constant speed. While returning back to A on same path it {$variation} its speed by {$v} km/hr. The total time of journey is {$t} hours. Find the original speed of vehicle.';
$patns = array();
$patns[0] = '/\{\$d\}/';
$patns[1] = '/\{\$variation\}/';
$repns = array();
$repns[0] = '1 km';
$repns[1] = '\\(\\frac{3}{2}\\)';
echo preg_replace($patns, $repns, $string);
?>
If this doesn't work, show the full example of how you are embedding the text in the page.
Postscript The point being, the latex command for inline maths is \( ... \) - yours is missing the backslashes.

Related

Algorithm to reduce text based on word frequency

How to reduce a text based on word frequency in PHP?
For example, if I have this text:
house house house house book book book
it should be reduced to something like this (or any similar form):
house house book
so this way the most used word is still house by 2 and book by 1.
The question is actually interesting. As I understand it, it is not about compression but word frequency - and this my friend, is the field of natural language processing.
My first thought was: Recommend using NLTK (and learning Python if required) since there is no real PHP equivalent to it (the closest library is probably NlpTools). However, it turned out Dan Cardin, an early NlpTools contributor, created a separate library that deals with your very problem: yooper/php-text-analysis
PHP Text Analysis is a library for performing Information Retrieval
(IR) and Natural Language Processing (NLP) tasks using the PHP
language
Add PHP Text Analysis to your project
composer require yooper/php-text-analysis
Here is an example how to use it:
<?php
require_once('vendor/autoload.php');
$book = file_get_contents('pg74.txt'); // tom sawyer from the gutenberg project http://www.gutenberg.org/cache/epub/74/pg74.txt
// Create a tokenizer object to parse the book into a set of tokens
$tokenizer = new \TextAnalysis\Tokenizers\GeneralTokenizer();
$tokens = $tokenizer->tokenize($book);
$freqDist = new \TextAnalysis\Analysis\FreqDist($tokens);
//Get the top 10 most used words in Tom Sawyer
$top10 = array_splice($freqDist->getKeyValuesByFrequency(), 0, 10);
The call to freq_dist returns a FreqDist instance.
Then, you can then calculate the weights of words yourself (freq/numberOfAllTokens) or use the getKeyValuesByWeight() method.
$top10[0]/$freqDist->getTotalTokens();
$weights = $freqDist->getKeyValuesByWeight();
... or normalize the frequency of your selected words by the occurrence of your least frequent top word, e.g.
foreach ($top10 as $word => $freq) {
$relWeight[$word] = $freq/end($top10);
}
Depending on your input, you will find that your most frequent words are a, the, that, etc. This is why you want to remove stopwords. And we have only started..
Here are some more samples.
Compress & Uncompress a string in PHP: gzcompress,gzuncompress
Example:
$text = "house house house house book book book";
echo "Orignal text lenght : ". strlen($text)."<br>";
$compressed = gzcompress($text, 9);
echo "Compressed text: ".$compressed."<br>";
echo "Compress text length :". strlen($compressed);
echo "<br>";
echo "Uncompressed text :".$uncompressed = gzuncompress($compressed);
Output:
Orignal text length: 38
Compressed text: x���/-NU�� ����R
Compress text length: 22
Uncompressed text : house house house house book book book

Force a statement to visually write to a file slowly

I have a want to take a File.open('somefile', 'w+') and make it read a file, take one line of text at a time, and visually write it slowly in another file. The reason I ask this question is because I can find nothing that does this already in code, nor can I find anything that actually controls the speed of how fast a program writes on the computer. I know that this can be simulated in a program such as Adobe Aftereffects so long as you provide a cursor after a character and the visual effect doesn't take place too quickly, but I've got 4,000 lines of code that I want to iterate over and can't afford to do this manually. This effect can also be achieved with a Microsoft Macro, but this requires it to be manually entered into the macro with no option of copy and paste.
-solutions preferred in Python, Ruby, and PHP-
If I understood properly, what you are trying to achieve, here you go:
input = File.read('readfrom.txt', 'r')
File.open('writeto.txt', 'w+') do |f|
input.chars.each do |c|
f.print(c) # print 1 char
f.flush # flush the stream
sleep 1 # sleep
end
end
This is one quick and dirty way of doing it in Python.
from time import sleep
mystring= 'My short text with a newline here\nand then ensuing text'
dt = 0.2 #0.2 seconds
for ch in mystring:
with open('fn_out','w+') as f:
f.write(ch)
f.flush()
sleep(dt)
f.flush() will result in updating the file with the changes.
One could make this more elaborate by having a longer pause after each newline, or a variable timestep dt.
To watch the change one has to repeatedly reload the file, as pointed out by #Tom Lord so you could run something like this beforehand to watch it in the terminal:
watch -n 0.1 cat fn_out
After some serious testing, I have finally developed a piece of code that will do the very thing I want. Tom Lord gave me some new words to use in my search terms "simulate typing" and this led me to win32ole with its SendKeys function. Here is a code that will iterate over all the characters in a file and print them out exactly as they were saved while simulating typing. I will see about making this into a gem for future use.
require 'win32ole'
wsh = WIN32OLE.new("WScript.Shell")
wsh.Run("Notepad.exe")
while not wsh.AppActivate("Notepad")
sleep 1
end
def fileToArray(file)
x = []
File.foreach("#{file}") do |line|
x << line.split('')
end
return x.flatten!
end
tests = fileToArray("readfrom.txt")
x = 0
while x <= tests.length
send = tests[x]
wsh.SendKeys("#{send}")
x += 1
sleep 0.1
end

Getting different output for same PHP code

(Can't paste the exact question as the contest is over and I am unable to access the question. Sorry.)
Hello, recently I took part in a programming contest (PHP). I tested the code on my PC and got the desired output but when I checked my code on the contest website and ideone, I got wrong output. This is the 2nd time the same thing has happened. Same PHP code but different output.
It is taking input from command line. The purpose is to bring substrings that contact the characters 'A','B','C','a','b','c'.
For example: Consider the string 'AaBbCc' as CLI input.
Substrings: A,a,B,b,C,c,Aa,AaB,AaBb,AaBbC,AaBbCc,aB,aBb,aBbC,aBbCc,Bb,BbC,BbCc,bC,bCc,Cc.
Total substrings: 21 which is the correct output.
My machine:
Windows 7 64 Bit
PHP 5.3.13 (Wamp Server)
Following is the code:
<?php
$stdin = fopen('php://stdin', 'r');
while(true) {
$t = fread($stdin,3);
$t = trim($t);
$t = (int)$t;
while($t--) {
$sLen=0;
$subStringsNum=0;
$searchString="";
$searchString = fread($stdin,20);
$sLen=strlen($searchString);
$sLen=strlen(trim($searchString));
for($i=0;$i<$sLen;$i++) {
for($j=$i;$j<$sLen;$j++) {
if(preg_match("/^[A-C]+$/i",substr($searchString,$i,$sLen-$j))) {$subStringsNum++;}
}
}
echo $subStringsNum."\n";
}
die;
}
?>
Input:
2
AaBbCc
XxYyZz
Correct Output (My PC):
21
0
Ideone/Contest Website Output:
20
0
You have to keep in mind that your code is also processing the newline symbols.
On Windows systems, newline is composed by two characters, which escaped representation is \r\n.
On UNIX systems including Linux, only \n is used, and on MAC they use \r instead.
Since you are relying on the standard output, it will be susceptible to those architecture differences, and even if it was a file you are enforcing the architecture standard by using the flag "r" when creating the file handle instead of "rb", explicitly declaring you don't want to read the file in binary safe mode.
You can see in in this Ideone.com version of your code how the PHP script there will give the expected output when you enforce the newline symbols used by your home system, while in this other version using UNIX newlines it gives the "wrong" output.
I suppose you should be using fgets() to read each string separetely instead of fread() and then trim() them to remove those characters before processing.
I tried to analyse this code and that's what I know:
It seems there are no problems with input strings. If there were any it would be impossible to return result 20
I don't see any problem with loops, I usually use pre-incrementation but it shouldn't affect result at all
There are only 2 possibilities for me that cause unexpected result:
One of the loops iteration isn't executed - it could be only the last one inner loop (when $i == 5 and then $j == 5 because this loop is run just once) so it will match difference between 21 and 20.
preg_match won't match this string in one of occurrences (there are 21 checks of preg_match and one of them - possible the last one doesn't match).
If I had to choose I would go for the 1st possible cause. If I were you I would contact concepts author and ask them about version and possibility to test other codes. In this case the most important is how many times preg_match() is launched at all - 20 or 21 (using simple echo or extra counter would tell us that) and what are the strings that preg_match() checks. Only this way you can find out why this code doesn't work in my opinion.
It would be nice if you could put here any info when you find out something more.
PS. Of course I also get result 21 so it's hard to say what could be wrong

How to parse strings - detailed explanation and information on syntax

I would like to parse a sting of data in a shell script with a simple 1 line expression. But I do not know how or where to find any information describing how it is done. All the examples I can find just looks like an illegal math equations, and I can not find any documentation describing how it works.
First, what exactly is this form of parsing called so I know what I am talking about and what to search for. Secondly, where can I find what it all means so I can learn how to use it correctly and not just copy some one else's work with little understanding of how it works.
/\.(\w+)/*.[0-9]/'s/" /"\n/g;s/=/\n/gp
I recall learning about this in perl a couple decades ago, but have long since forgotten what it all means. I have spent days searching for information on what this all means. All I can find are specific examples with no explanations of what it is technically called and how it works!
I want to separate each field then extract the key name and numerical data in a shell script. I realize some forms of parsing are done differently in shell scripts as opposed to php or perl scripts. But I need to learn the parsing syntax used to filter out the specific data sets that I could use in both, shell and php.
Currently I need to parse a single line of data from a file in a shell script for a set of conditionals required by other support scripts.
#!/bin/sh
Line=`cat ./dump.txt`
#Line = "V:12.46 A:3.427 AV:6.08 D:57.32 S:LOAD CT:45.00 P:42.71 AH:2016.80"
# for each field parse data ("/[A-Z]:[0-9]/}" < $Line)
# $val[$1] = $2
# $val["V"] = "12.46"
# $val["AV"] = "6.08"
if $val["V"] < 11.4
then
~/controls/stop.sh
else
~/controls/start.sh
fi
if $val["AV"] > 10.7
then
echo $val["AV"] > ./source.txt
else
echo "DOWN" > ./source.txt
fi
I need to identify and separate the difference between "V:" and "AV:".
In php I can use foreach & explode into an array. But I am tired of writing half a page of code for some thing that can be done in a single line. I need to learn a simpler and more efficient way to parse data from a string and extract the data in to a usable variable.
$Line = file_get_contents("./dump.txt");
$field = explode (' ' , $Line);
foreach($field as $arg)
{
$val = explode (':' , $arg);
$data[$val[0]] = $val[1];
}
# $data["V"] = "12.46"
# $data["AV"] = "6.08"
A quick shell example is much appreciated, but I really need to know "HOW TO" do this my self. Please give me some links or search criteria to find the definitions and syntax to these parsing expressions.
Thank you in advance for your help.
The parsing patterns you're talking about are commonly referred to as regular expressions or regex.
For php you can find a lot of helpful information from http://au1.php.net/manual/en/book.pcre.php
Regex is quite hard especially for complex expressions so I usually google search for an online regex expression tester. Preferably one which highlights whats being matched. Javascript ones are especially good as the results are instant and the regex syntax is the same for PHP.
Special thanks to James T for leading me in the right direction.
After reading through the regular expressions I have figured out the search pattern I need. Also included is a brief script to test the output. Taking into account that BASH can not use decimal numbers we need to convert it to a whole number. The decimal intigers is always fixed at 2 or 3 places so conversion is easy, just drop the decimal. Also the order in which the fields are recorded remains constant so the order in which they are read will remain the same.
The regular expression that fits the search for each of the first 4 fields is:
\w+:([0-9]+)\.([0-9]+)\s
( ) = the items to search/parse; using 2 searches for each data set "V:12.46"
\w = for the word search and the " + " means any 1 or more letters
: = for the delimiter
( -search set 1:
[0-9] = search any numbers and the " + " means any 1 or more digits
) -end search set 1
\. = for the decimal point in the data
( -search set 2:
[0-9] = search any numbers and the " + " means any 1 or more ( second set after the decimal)
) -end search set 2
\s = white space (blank space)
Now duplicate the search 3 times for the first 3 fields, giving me 6 variables.
\w+:([0-9]+)\.([0-9]+)\s\w+:([0-9]+)\.([0-9]+)\s\w+:([0-9]+)\.([0-9]+)\s
And here is a simple script to test the output:
#!/bin/bash
Line="V:13.53 A:7.990 AV:13.65 D:100.00 S:BulkCharge CT:35.00 P:108.11 AH:2116.20"
regex="\w+:([0-9]+)\.([0-9]+)\s\w+:([0-9]+)\.([0-9]+)\s\w+:([0-9]+)\.([0-9]+)\s"
if [[ $Line =~ $regex ]]; then
echo "match found in $Line"
i=1
n=${#BASH_REMATCH[*]}
while [[ $i -lt $n ]]
do
echo " capture[$i]: ${BASH_REMATCH[$i]}"
let i++
done
Volt=${BASH_REMATCH[1]}${BASH_REMATCH[2]}
Amp=${BASH_REMATCH[3]}${BASH_REMATCH[4]}
AVG=${BASH_REMATCH[5]}${BASH_REMATCH[6]}
else
echo "$Line does not match"
fi
if [ $Volt -gt 1200 ]
then
echo "Voltage is $Volt"
fi
resulting with an output of:
match found in V:13.53 A:7.990 AV:13.65 D:100.00 S:BulkCharge CT:35.00 P:108.11 AH:2116.20
capture[1]: 13
capture[2]: 53
capture[3]: 7
capture[4]: 990
capture[5]: 13
capture[6]: 65
Voltage is 1353

What is Keyword Density and how to create a script in PHP?

I am working on a project where I have to find out the keyword density of thepage on the basis of URL of that page. I googled a lot but no help and scripts were found, I found a paid tool http://www.selfseo.com/store/_catalog/php_scripts/_keyword_density_checker_php_script
But I am not aware actually what "keyword Density of a page" actually means? and also please tell me how can we create a PHP script which will fetch the keyword density of a web page.
Thanks
"Keyword density" is simply the frequency that the word occurs given as a percentage of the total number of words. The following PHP code will output the density of each word in a string, $str. It demonstrates that keyword density is not a complex calculation, it can be done in a few lines of PHP:
<?php
$str = "I am working on a project where I have to find out the keyword density of the page on the basis of URL of that page. But I am not aware actually what \"keyword Density of a page\" actually means? and also please tell me how can we create a PHP script which will fetch the keyword density of a web page.";
// str_word_count($str,1) - returns an array containing all the words found inside the string
$words = str_word_count(strtolower($str),1);
$numWords = count($words);
// array_count_values() returns an array using the values of the input array as keys and their frequency in input as values.
$word_count = (array_count_values($words));
arsort($word_count);
foreach ($word_count as $key=>$val) {
echo "$key = $val. Density: ".number_format(($val/$numWords)*100)."%<br/>\n";
}
?>
Example output:
of = 5. Density: 8%
a = 4. Density: 7%
density = 3. Density: 5%
page = 3. Density: 5%
...
To fetch the content of a webpage you can use file_get_contents (or cURL). As an example, the following PHP code lists all keywords above 1% density on this webpage:
<?php
$str = strip_tags(file_get_contents("http://stackoverflow.com/questions/819166"));
$words = str_word_count(strtolower($str),1);
$word_count = array_count_values($words);
foreach ($word_count as $key=>$val) {
$density = ($val/count($words))*100;
if ($density > 1)
echo "$key - COUNT: $val, DENSITY: ".number_format($density,2)."%<br/>\n";
}
?>
I hope this helps.
Or you can try this: http://code.eyecatch-up.de/?p=155
Update: Relocated the class to http://code.google.com/p/php-class-keyword-density-check/
<?php
include 'class/class.keywordDensity.php'; // Include class
$obj = new KD(); // New instance
$obj->domain = 'http://code.eyecatch-up.de'; // Define Domain
print_r ($obj->result());
?>
above code returns:
Array
(
[0] => Array
(
[total words] => 231
)
[1] => Array
(
[keyword] => display
[count] => 14
[percent] => 6.06
)
and so on...
works with local and remote files.
keyword density is roughly:
(no. of times keyword appeared on the page)/(total no. of other keywords)
Keyword density just means the percentage that the keywords appear in the content versus rest of the text. In general, it's also a fairly useless metric for SEO. I wouldn't bother building a script for it as you'd be better off concentrating on other metrics. You might find this reference useful.
If the given keyword is "elephant walks", the keyword density would be how often the term "elephant walks" appears on any given web page in relation to other text. As VirtuosiMedia said, this is (broadly) useless information.
To measure it, you must strip all mark up from the text, count the words while keeping track of how often the keyword(s) appear.
At that point, you will know, xx.xx % of all words in this text are keywords. xx.xx % of the time , the key word(s) are used next to each other, therefore my keyword density for "elephant walks" is xx
Again, the only reason this is useful is to demonstrate pattern matching and string functions in php.

Categories