After an earlier question relating to this error.
Error: unable to get value of the property ‘split’: object is null or undefined
An answer was offered to add the following code:
/* Cross-Browser Split 1.0.1
(c) Steven Levithan <stevenlevithan.com>; MIT License
An ECMA-compliant, uniform cross-browser split method */
var cbSplit;
// avoid running twice, which would break `cbSplit._nativeSplit`'s reference to the native `split`
if (!cbSplit) {
cbSplit = function (str, separator, limit) {
// if `separator` is not a regex, use the native `split`
if (Object.prototype.toString.call(separator) !== "[object RegExp]") {
return cbSplit._nativeSplit.call(str, separator, limit);
}
var output = [],
lastLastIndex = 0,
flags = (separator.ignoreCase ? "i" : "") +
(separator.multiline ? "m" : "") +
(separator.sticky ? "y" : ""),
separator = RegExp(separator.source, flags + "g"), // make `global` and avoid `lastIndex` issues by working with a copy
separator2, match, lastIndex, lastLength;
str = str + ""; // type conversion
if (!cbSplit._compliantExecNpcg) {
separator2 = RegExp("^" + separator.source + "$(?!\\s)", flags); // doesn't need /g or /y, but they don't hurt
}
/* behavior for `limit`: if it's...
- `undefined`: no limit.
- `NaN` or zero: return an empty array.
- a positive number: use `Math.floor(limit)`.
- a negative number: no limit.
- other: type-convert, then use the above rules. */
if (limit === undefined || +limit < 0) {
limit = Infinity;
} else {
limit = Math.floor(+limit);
if (!limit) {
return [];
}
}
while (match = separator.exec(str)) {
lastIndex = match.index + match[0].length; // `separator.lastIndex` is not reliable cross-browser
if (lastIndex > lastLastIndex) {
output.push(str.slice(lastLastIndex, match.index));
// fix browsers whose `exec` methods don't consistently return `undefined` for nonparticipating capturing groups
if (!cbSplit._compliantExecNpcg && match.length > 1) {
match[0].replace(separator2, function () {
for (var i = 1; i < arguments.length - 2; i++) {
if (arguments[i] === undefined) {
match[i] = undefined;
}
}
});
}
if (match.length > 1 && match.index < str.length) {
Array.prototype.push.apply(output, match.slice(1));
}
lastLength = match[0].length;
lastLastIndex = lastIndex;
if (output.length >= limit) {
break;
}
}
if (separator.lastIndex === match.index) {
separator.lastIndex++; // avoid an infinite loop
}
}
if (lastLastIndex === str.length) {
if (lastLength || !separator.test("")) {
output.push("");
}
} else {
output.push(str.slice(lastLastIndex));
}
return output.length > limit ? output.slice(0, limit) : output;
};
cbSplit._compliantExecNpcg = /()??/.exec("")[1] === undefined; // NPCG: nonparticipating capturing group
cbSplit._nativeSplit = String.prototype.split;
} // end `if (!cbSplit)`
// for convenience...
String.prototype.split = function (separator, limit) {
return cbSplit(this, separator, limit);
};
After trialling the code above and deleting caches it was found to do nothing...can anyone help at all, kind regards in advance.
Thanks EdoDodo for the above code but can you offer any further help as I am almost tearing my hair out and it did not work in the end, one point to note, the linked in button on the home page (if commented out) makes that site work for the home page and the error goes away but I really want the linked in buttons for each post excerpt on the home page.
site is:
www.mobileinquirer.com
Firefox shows me a script error on line 913 in this part of your script:
<script type="text/javascript">
// <![CDATA[
var disqus_shortname = 'mobileinquirer';
var disqus_domain = 'disqus.com';
(function () {
var nodes = document.getElementsByTagName('span');
for (var i = 0, url; i < nodes.length; i++) {
if (nodes[i].className.indexOf('dsq-postid') != -1) {
nodes[i].parentNode.setAttribute('data-disqus-identifier', nodes[i].getAttribute('rel'));
url = nodes[i].parentNode.href.split('#', 1);
if (url.length == 1) url = url[0];
else url = url[1]
nodes[i].parentNode.href = url + '#disqus_thread';
}
}
var s = document.createElement('script'); s.async = true;
s.type = 'text/javascript';
s.src = 'http://' + disqus_domain + '/forums/' + disqus_shortname + '/count.js';
(document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s);
}());
//]]>
</script>
The specific error is on this line:
url = nodes[i].parentNode.href.split('#', 1);
and it's because parentNode does not have an href. This error has nothing to do with the split function. The code is trying to obtain the value of the href attribute on the parentNode, but there is no href attribute so that resolves to undefined so the call to split fails. It has nothing to do with the split function. The issue is that your markup is apparently wrong and what I think is disqus code is expecting an tag around a tag, but it isn't finding that.
If you look at line 664-665 in the mobilinquirer.com HTML source, you will find this sequence at that line and then several times following:
<p><span
class="dsq-postid">8 Comments</span></p>
This code causes the error. The <span class="dsq-postid"> tag must have an <a href="xxx"> tag as it's parent or you will get this error. I see this same problem several problems in your HTML.
This problem has NOTHING to do with the split function. To make this error go away, you need to fix your HTML so that it is what the disqus code is expecting or remove the offending disqus code (which you don't seem to need) or both.
Related
My Questions is Find a 7 letter string of characters that contains only letters from
acegikoprs
such that the gen_hash(the_string) is
675217408078
if hash is defined by the following pseudo-code:
Int64 gen_hash (String s) {
Int64 h = 7
String letters = "acegikoprs"
for(Int32 i = 0; i < s.length; i++) {
h = (h * 37 + letters.indexOf(s[i]))
}
return h
}
For example, if we were trying to find the 7 letter string where gen_hash(the_string) was 677850704066, the answer would be "kppracg".
Solution
test1.php
I did that question solve in php, I am unable to run this code I am in php i don't have that much knowledge regarding php class and their function, Can any one solve this code and describe me. thanks in advance i will be very great full if anyone help me.
<?php
$set = "acdegilmnoprstuw";
$CONST_HASH = 7.0;
$CONST_MULT = 37.0;
$hash = new Func(function($string = null) use (&$CONST_HASH, &$CONST_MULT, &$set) {
$_hash = $CONST_HASH;
for ($i = 0.0; $i < get($string, "length"); $i++) {
$_hash = _plus(to_number($_hash) * to_number($CONST_MULT), call_method($set, "indexOf", get($string, $i)));
}
return $_hash;
});
$decode = new Func(function($_hash = null) use (&$CONST_MULT, &$Math, &$set) {
$decoded = ""; $positionsInSet = new Arr();
for ($i = 0.0; $_hash > $CONST_MULT; $i++) {
set($positionsInSet, $i, call_method($Math, "floor", (float)(to_number($_hash) % to_number($CONST_MULT))));
$_hash /= 37.0;
}
for ($i = to_number(get($positionsInSet, "length")) - 1.0; $i >= 0.0; $i--) {
$decoded = _plus($decoded, get($set, get($positionsInSet, $i)));
}
return $decoded;
});
I realize that this question was asked well over a year ago and I'm only just stumbling on it right now but seeing as there hasn't been an answer I figured I'd answer it.
You used a third party JavaScript to PHP converter utility and expected the demo to work out of the box. You should have read up on it's usage as it clearly states in the ReadMe.md that, ...this tool is using esprima JavaScript parser with rocambole to walk the AST and escope to figure out the variable scope, hoist function declarations and so on...
The developer goes on to say, After AST manipulation tools/codegen.js generates the PHP code by walking the tree. Now here's where it gets good. Pay attention now..
Various constructs get wrapped in helper functions, for instance,
property access, method calls and + operator. The runtime helpers
can be found in php/helper and there are a bunch of classes in
php/classes for Array, RegExp and such. All this PHP gets packaged
into your output file, or you can save it to a standalone runtime and
reference that from your output file like so:
js2php --runtime-only > runtime.php
js2php --runtime runtime.php example.js > example.php
You can also specify the output file using -o or --out and you can
compile multiple input files into one output file like so:
js2php -o example.php file1.js file2.js
So as you can see my friend, to get your code to work you merely need to include the runtime helpers functions so your converted script can be interpreted. I'm not sure as to which files it'll take to get your script to parse correctly, however now that I've pointed you in the right direction I'm confident you'll be able work it out yourself.
Happy coding..
=)
Instead of assigning the inline function with new operator to variable, create a separate functions encode and decode where you can do the hashing and matching the hash code.
Let me give you the snippet of how to do it. I am assuming that your using plain PHP.
/* Call to function encode which returns you the encoded value and store in $encode variable */
$encode = encode($par1, $par2);
/* Call to function decode which returns you the decoded value and store in $decode variable */
$decode = decode($par1, $par2);
/* Function to encode your code */
function encode($par1, $par2){
return $encode_value
}
/* Function to decode your code */
function decode($par1, $par2){
return $decode_value
}
I have written this in Javascript to generate both Hash String and Number
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var gen = gen_hash('kppracg');
document.write("kppracg hash value is ", gen);
document.write('<br><br>');
var gen = gen_hash('iorocks');
document.write("iorocks hash value is ", gen);
var hash = 675217408078;
var gen_rev = gen_hash_rev(hash);
document.write('<br><br>');
document.write("675217408078 hash value is ", gen_rev);
function gen_hash(s) {
var h = 7;
var acegikoprs = "acegikoprs";
for(var i = 0; i < s.length; i++) {
h = (h * 37 + acegikoprs.indexOf(s[i]));
}
return h;
}
function gen_hash_rev(hash) {
var arr_values = ['a','c','e','g','i','k','o','p','r','s'];
var min = 0;
var max = 99999999;
while (min <= max) {
var final_result = "";
var tempInt = parseInt(((max - min) / 2) + min);
var arr_tempInt = num_array(tempInt);
for(var i = 0; i < arr_tempInt.length; i++) {
final_result = final_result + arr_values[arr_tempInt[i]];
}
var result = gen_hash(final_result);
if(result < hash) {
min = tempInt + 1;
}
else if( result > hash) {
max = tempInt - 1;
}
else {
return final_result;
}
}
}
function num_array(num){
var output = [],
sNumber = num.toString();
for (var i = 0, len = sNumber.length; i < len; i += 1) {
output.push(+sNumber.charAt(i));
}
return output;
}
</script>
</body>
</html>
Ok so i have paid a coder to code me a walk around map script were users can press up and down on the keyboard and walk aroud a map using jquery. But now im trying to make it so i have a up and down image and then on click it will call the up and down function. So the suer can use the up and down keys plus clicking the images.
Here is the up function im using for when the user presses the up key on the keyboard. But now some how i need to call the same function when a image is clicked..
function move(d)
{
if(d == "UP")
{
var top = (parseInt(document.getElementById('move').style.top) - 10);
var left = parseInt(document.getElementById('move').style.left);
if(canMove(new xy(left,top)))
{
document.getElementById('move').style.top = (parseInt(document.getElementById('move').style.top) - 10) + 'px';
document.player.src = "maps/sprites/playerUp.png";
//if(lastStep != "UP") clearTimeouts();
//setTimeout('document.player.src="playerUp.png"', 500);
//lastStep = "UP";
reloadF();
}
}
How would i do about doing that ??
Im guessing i just need to call function move(d) and set it to up some how ?? On click of image ?
var keynum = 0;
if(window.event) { keynum = e.keyCode; } // for IE
else if(e.which) { keynum = e.which; } // for others browsers
if(keynum === 38) { // up
//if KEY UP
}
if(keynum === 40) { // down
//if KEY DOWN
}
I hope this help...
I'm trying to get a grasp on using $.getJSON with an array from PHP.
Here's a simple example where all I want to do is output the requested info. Should the alert(data) return the array object? I am not alerting anything.
PHP file (account.php):
$arr = array('items' => 5,'others' => 6);
echo $arr = json_encode($arr)
HTML file:
$("#unsubscribe").click(function() {
$.getJSON("account.php?", function(data) {
alert(data);
});
});
First of all, it's probably a good idea if you try to load account.php in your browser. You should expect to see:
{"items":5,"others":6}
However, you won't see this. You will instead see a Parse Error, expected ;. Because you forgot it on the echo line.
This is why you see no alert. A PHP error is clearly not valid JSON, and viewing the browser's error console would tell you this ;)
In my projects I am using dump function for viewing json returned array.
Here it is:
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "'"+"\\n";
if (level < 0)
dumped_text += dump(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => '" + value + "'"+"\\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
I use TinyMCE for various projects. The problem I'm having ATM is that a lot of users copy&paste content form sources like Word or OpenOffice into the TinyMCE input. This results often in bloated code (e.g. things like <span lang="EN-GB"> being taken over from OpenOffice). TinyMCE's cleanup doesn't seem to remove those tags. Is there a way to strip all formating befor the text is pasted into the TinyMCE input area? Or is there another way to prevent such bloated code, for example by filtring it server side with PHP?
I know this is an opd question but for the benefit of others who may be searching for an answer to this (like I was!), TinyMCE now includes the ability to control what is pasted into the textbox.
In the init call, add the "paste" plugin and then set whatever options you require, e.g.
tinyMCE.init({
...
plugins: "paste",
paste_auto_cleanup_on_paste : true,
paste_remove_styles: true,
paste_remove_styles_if_webkit: true,
paste_strip_class_attributes: "all",
paste_remove_spans : true,
...
});
You can see all options in the tinyMCE wiki
I remove all tags using the followingc function on_preprocess:
strip_tags = function (str, allowed_tags) {
var key = '', allowed = false;
var matches = []; var allowed_array = [];
var allowed_tag = '';
var i = 0;
var k = '';
var html = '';
var replacer = function (search, replace, str) {
return str.split(search).join(replace);
};
// Build allowes tags associative array
if (allowed_tags) {
allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
}
str += '';
// Match tags
matches = str.match(/(<\/?[\S][^>]*>)/gi);
// Go through all HTML tags
for (key in matches) {
if (isNaN(key)) {
// IE7 Hack
continue; }
// Save HTML tag
html = matches[key].toString();
// Is tag not in allowed list? Remove from str!
allowed = false;
// Go through all allowed tags
for (k in allowed_array) { // Init
allowed_tag = allowed_array[k];
i = -1;
if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag) ;}
// Determine
if (i == 0) { allowed = true;
break;
}
}
if (!allowed) {
str = replacer(html, "", str); // Custom replace. No regexing
}
}
return str;
};
In the tinymce init i place
paste_preprocess : function(pl, o) {
// remove Clipboard header on MAC
var pos_sel = o.content.search("EndSelection:");
var pos_fra = o.content.search("EndFragment:");
var mac_header_found = false;
if (o.content.search("Version:") == 0 && pos_sel < 135 && pos_sel > 120){
o.content = o.content.substring(pos_sel+23);
mac_header_found = true;
}
else if (o.content.search("Version:") == 0 && pos_fra < 80 && pos_fra > 75){
o.content = o.content.substring(pos_fra+23);
mac_header_found = true;
}
// Copy from Word oder OpenOffice (MAC) - remove header
if (o.wordContent || mac_header_found) {
// first style tag + content to be removed
var pos_start_style = o.content.search('<style');
var pos_end_style = o.content.search('</style>');
if (pos_start_style > 0 && pos_end_style > pos_start_style) {
o.content = o.content.substring(0, pos_start_style).concat(o.content.substring(pos_end_style + 8));
}
// complete Worddokument gets pasted
else {
var pos_start_p = o.content.search('<p');
if (pos_start_p) o.content = o.content.substring(pos_start_p);
}
}
o.content = ir.im.strip_tags( o.content, '' );
// NO-Break Zero-width space if empty
if (o.content == '') {
o.content = '';
}
},
Ok, I've been banging my head up against the wall on this and I have no clue why it isn't creating the element. Maybe something very small that I overlooked here. Basically, there is this Javascript code that is in a PHP document being outputted, like somewhere in the middle of when the page gets loaded, NOW, unfortunately it can't go into the header. Though I'm not sure that that is the problem anyways, but perhaps it is... hmmmmm.
// Setting the variables needed to be set.
echo '
<script type="text/javascript" src="' . $settings['default_theme_url'] . '/scripts/shoutbox.js"></script>';
echo '
<script type="text/javascript">
var refreshRate = ', $params['refresh_rate'], ';
createEventListener(window);
window.addEventListener("load", loadShouts, false);
function loadShouts()
{
var alldivs = document.getElementsByTagName(\'div\');
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
var is_counted = 0;
divName = alldivs[i].getAttribute(\'name\');
if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
else if(divName == "undefined")
continue;
else
{
if (divName.indexOf(\'dp_Reserved_Counted\') == 0)
{
is_counted = 0;
shoutCount++;
continue;
}
else
{
shoutCount++;
is_counted = 1;
}
}
// Empty out the name attr.
alldivs[i].name = \'dp_Reserved_Counted\';
var shoutId = \'shoutbox_area\' + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement(\'div\');
shoutHolder.setAttribute(\'id\', [shoutId]);
shoutHolder.setAttribute(\'class\', \'dp_control_flow\');
shoutHolder.style.cssText = \'padding-right: 6px;\';
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
if (is_counted == 1)
{
startShouts(refreshRate, shoutId);
break;
}
}
}
</script>';
Also, I'm sure the other functions that I'm linking to within these functions work just fine. The problem here is that within this function, the div never gets created at all and I can't understand why? Furthermore Firefox, FireBug is telling me that the variable divName is undefined, even though I have attempted to take care of this within the function, though not sure why.
Anyways, I need the created div element to be inserted just before the following HTML:
echo '
<div name="dp_Reserved_Shoutbox" style="padding-bottom: 9px;"></div>';
I'm using name here instead of id because I don't want duplicate id values which is why I'm changing the name value and incrementing, since this function may be called more than 1 time. For example if there are 3 shoutboxes on the same page (Don't ask why...lol), I need to skip the other names that I already changed to "dp_Reserved_Counted", which I believe I am doing correctly. In any case, if I could I would place this into the header and have it called just once, but this isn't possible as these are loaded and no way of telling which one's they are, so it's directly hard-coded into the actual output on the page of where the shoutbox is within the HTML. Basically, not sure if that is the problem or not, but there must be some sort of work-around, unless the problem is within my code above... arrg
Please help me. Really what I need is a second set of eyes on this.
Thanks :)
When you're testing divName, switch the order of your conditions from this
divName = alldivs[i].getAttribute(\'name\');
if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
else if(divName == "undefined")
continue;
to this:
var divName = alldivs[i].getAttribute(\'name\');
if (!divName) // this is sufficient, by the way
continue;
else if (divName.indexOf(\'dp_Reserved_Shoutbox\') < 0 && divName.indexOf(\'dp_Reserved_Counted\') < 0)
continue;
The problem is that when the script finds a div without a name, it tries to call the indexOf property of a non-existent value and therefore throws an error.
There were a number of issues in the loadShouts method. First being the comparison of a string "undefined" instead of a straight boolean check, which will match. I also removed a bunch of un-needed logic. Beyond this, the id attribute being assigned to the new shoutHolder was being passed in as an array, instead of a direct property assignment.. See if the following works better.
function loadShouts()
{
var alldivs = document.getElementsByTagName("div");
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
divName = alldivs[i].getAttribute("name");
if (!divName)
continue;
if (divName.indexOf("dp_Reserved_Shoutbox") < 0 && divName.indexOf("dp_Reserved_Counted") < 0)
continue;
shoutCount++;
if (divName.indexOf("dp_Reserved_Counted") == 0)
continue;
// Empty out the name attr.
alldivs[i].setAttribute("name", "dp_Reserved_Counted");
var shoutId = "shoutbox_area" + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement("div");
shoutHolder.setAttribute("id", shoutId);
shoutHolder.setAttribute("class", "dp_control_flow");
shoutHolder.style.cssText = "padding-right: 6px;";
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
startShouts(refreshRate, shoutId);
break;
}
}
Ok, just wanted to let you know how it went. And I thank both you greatly Tracker1 and Casey Hope. Especially Tracker for the excellent rewrite of the function. You all ROCK. Here's the final function that I'm using bytheway, just a tiny bit of editing to Tracker1's Answer, which is why you got my vote hands down!
echo '
<script type="text/javascript">
var refreshRate = ' . $params['refresh_rate'] . ';
createEventListener(window);
window.addEventListener("load", loadShouts, false);
function loadShouts()
{
var alldivs = document.getElementsByTagName("div");
var shoutCount = 0;
var divName = "undefined";
for (var i = 0; i<alldivs.length; i++)
{
divName = alldivs[i].getAttribute("name");
if (!divName)
continue;
if (divName.indexOf("dp_Reserved_Shoutbox") < 0 && divName.indexOf("dp_Reserved_Counted") < 0)
continue;
shoutCount++;
if (divName.indexOf("dp_Reserved_Counted") == 0)
continue;
// Empty out the name attr.
alldivs[i].setAttribute("name", "dp_Reserved_Counted");
var shoutId = "shoutbox_area" + shoutCount;
// Build the div to be inserted.
var shoutHolder = document.createElement("div");
shoutHolder.setAttribute("id", shoutId);
shoutHolder.setAttribute("class", "dp_control_flow");
shoutHolder.style.cssText = "padding-right: 6px;";
alldivs[i].parentNode.insertBefore(shoutHolder, alldivs[i]);
startShouts(refreshRate, shoutId);
break;
}
}
</script>';
Thanks Again, you are the BEST!