Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Home
Daily Thoughts
Ionic
Stack Overflow
Books
About me
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Nikola Brežnjak blog - Tackling software development with a dose of humor
Stack Overflow

How to detect the item has been dropped in the same sortable list in jQuery UI

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My quesiton was:

I have two connected sortable lists. My code works fine for when I drag one element from the list on the left side to the one on the right side, but can you tell me what event should I be looking for if I want to know the order of items in the left list when an item gets dragged and dropped in the same list (basically reorder the items in the same list, not dragging and dropping to the other list but to the same).

Here is the link to the code: http://jsfiddle.net/Hitman666/WEa3g/1/

So, as you will see I have an alert when items are dragged and dropped in oposite lists, but I need an event also for when the list (for example the green one) gets reordered. Then I would need to alert the order, for example: 4,3,2,1

HTML:

<ul id="sortable1" class="connectedSortable">
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
</ul>

<ul id="sortable2" class="connectedSortable">
    <li>Item 5</li>    
    <li>Item 6</li>
    <li>Item 7</li>
    <li>Item 8</li>    
</ul>

CSS:

#sortable1, #sortable2 { list-style-type: none; margin: 0; padding: 0; float: left; margin-right: 10px; }#sortable1 li, #sortable2 li { margin: 0 5px 5px 5px; padding: 5px; font-size: 1.2em; width: 120px; }#sortable1 li{background: green;}#sortable2 li{background: yellow;}

JavaScript:

$(function() {
    $("#sortable1, #sortable2").sortable({
        connectWith: ".connectedSortable",
        receive: myFunc
    }).disableSelection();

    function myFunc(event, ui) {
        alert(ui.item.html());
    }
});

 

The answer, by user yoelp was:

You need to use the update event. Here is my example (notice that I made 2 extra function calls to sort since you needed the evt only on the left list):

$(function(){
    $( "#sortable1" ).sortable({
        connectWith: ".connectedSortable",
        update: myFunc
    }).disableSelection();

    $( "#sortable2" ).sortable({
        connectWith: ".connectedSortable",  // deactivate:myFunc
    }).disableSelection();

    function myFunc(event, ui){
        var b = $("#sortable1 li"); // array of sorted elems
        for (var i = 0, a = ""; i < b.length; i++)
        {
            var j=i+1; // an increasing num.
            a = a + j + ") " + $(b[i]).html() + '\n ' //putting together the items in order
        }
        alert(a)                 
    }
});
Stack Overflow

PHP memory_get_peak_usage and ini_set(‘memory_limit’, ‘-1’)

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

My quesiton was:

I recently ran into memory allocation problems, so I started experimenting with the ini_set('memory_limit', value); directive where I tried to enter values incrementaly. Now, searching through the web (and SO) I found out that I can put -1 as the value. So, I did and now the script runs fully to the end without breaking (before I used to get the memory allocation error).

What I don’t understand, however, is that given these two lines at the end of the script’s file:

$mem = memory_get_peak_usage(true);         
echo "Peak mem. usage: <b>". round($mem /1024/10124,2)."</b> MB";

produce around 10.8MB and when I look into the /var/log/messages I can see this line:

Nov2113:52:26 mail suhosin[1153]: ALERT-SIMULATION - script tried to increase  
memory_limit to 4294967295 bytes which is above the allowed value (attacker  
'xx.xxx.xxx.xxx', file '/var/www/html/file.php', line 5)

which means the script tried to alocate 4096MB!

How can this be? And also, what interest me the most is why didn’t the script execution stop in this case? Is it because of the ini_set('memory_limit', '-1');? I mean, I did read that putting -1 as the valueis not recomended and I know where the problem lies in the script (reading too big amount of data at once in the memory), and I will go and fix it with sequential reading, but I’m just baffled about these data differences, so I would be gratefull if someone can shed some light on it.

The answer, by user Sverri M. Olsen was:

It is because the suhosin patch uses its own “hard” maximum memory limit, suhosin.memory_limit.

From the configuration reference:

Suhosin […] disallows setting the memory_limit to a value greater than the one the script started with, when this option is left at 0.

In other words, if you change the memory_limit so that it is bigger than suhosin’s upper limit then it will simply assume that you are an “attacker” trying to do something suspicious

Stack Overflow

jQuery Themeroller Gallery for Mobile

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

This question is one of very few that still hasn’t got an answer, so if you do, please help:

Is there a gallery of existing premade themes ready for download for jQuery Mobile just as they are for jQuery UI? I did look around jQuery Mobile Themeroller but couldn’t find it (I know you can drag&drop the colors from Adobe kuler swatches but I’m not keen on that too much).

Stack Overflow

How to create a table based on few columns of another table, but also add some additional columns

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

So, my question was as follows:

I know I can do something like this:

CREATETABLE new_table AS(SELECT field1, field2, field3
    FROM my_table
)

I’m wondering how do I add more columns to this create table SQL, that are not from my_table, but instead ones that I would write my self and which would be unique to this new_table only.

I know I could just make the table with the above SQL and then additionaly (after the command is completed) add the necessary columns, but am wondering if this all could be done in one command, maybe something like this (tried it like that, but didn’t work):

CREATETABLE new_table AS((SELECT field1, field2, field3
    FROM my_table),
    additional_field1 INTEGER NOTNULLDEFAULT1,
    additional_field2 VARCHAR(20)NOTNULLDEFAULT1)

The answer, by user Omesh, was this:

You can also explicitly specify the data type for a generated column:

See Create Table Select Manual

CREATETABLE new_table
(
 additional_field1 INTEGER NOTNULLDEFAULT1,
 additional_field2 VARCHAR(20)NOTNULLDEFAULT1)AS(SELECT id, val,1AS additional_field1,1AS additional_field2
 FROM my_table
);

Example: SQLFiddle

Stack Overflow

Need a replacement for jQuery datatables plugin as it’s too slow

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

So, my question was as follows:

I’ve been using jQuery datatables plugin for about two years now and it worked great so far. The problem occured now when I need to load about 45000 records at once (you click the button and wait for the page with the data to load) – the loading time is just too big to wait.

Here are the tests I made using Chrome web browser (the data is from it’s Network tab using ):

datatables plugin turned on:
5476 records:
24 requests ❘ 256.26KB transferred ❘ 19.80s
(onload: 19.80s, DOMContentLoaded: 18.58s)

45071 records:
34 requests ❘ 1.85MB transferred ❘ 11.1min
(onload: 11.1min, DOMContentLoaded: 11.0min)

datatables plugin turned off (the jQuery datatables initialization is comented out):
5476 records:
21 requests ❘ 255.84KB transferred ❘ 6.57s
(onload: 13.26s, DOMContentLoaded: 13.28s)

45071 records:
31 requests ❘ 1.84MB transferred ❘ 2.0min
(onload: 2.0min, DOMContentLoaded: 2.0min)

The increase in load time that datatables make is over 80% for the 45k rows, and almost 40% for the 5k rows.

So I was wondering if you guys know of any similar plugin that handles alot of rows (45000+) faster, or am I just missing the point by trying to load all 45000+ records in “one go”?

Any suggestions are appreciated!

The answer, by user Allan Jardine, was this:

From the DataTables FAQs ( http://datatables.net/faqs#speed ):

  • Client-side processing – DOM sourced data: ~5’000 rows. Speed options: bSortClasses
  • Client-side processing – Ajax sourced data: ~50’000 rows. Speed options: bDeferRender
  • Server-side processing: millions of rows.

If you aren’t using deferred rendering at the moment, with your 45’000 rows, I would most certainly suggest that. Failing that, for DataTables options, you might need to look at server-side processing.

Stack Overflow

Wait for images to load and then execute all other code

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

So, my question was as follows:

What I want to do is: wait until all images are preloaded and only then execute all other javascript code. As far as I’m concerned it can (but not a must) have a “loading…” message.

The fact is that I have a pretty big image in the body background and 2 other images which are also bigger, and so I would like to preload them so that then they would show instantly and would not have that ugly “loading” image effect.

This is what I’m using now but it’s not good:

$(document).ready(function()
{    
     preloadImages();
     ...some other code...

    function preloadImages(){
         imagePreloader([
            'images/1.png',
            'images/2.jpg',
            'images/3.png',                
         ]);
     } 

     function imagePreloader(arrayOfImages) {
         $(arrayOfImages).each(function(){
             (new Image()).src = this;
         });
     }   
}

I don’t know, maybe I should call this preloader somewhere out of the .ready()? or something like that? Btw, yes, I also read this post and I don’t know why but .ready() works faster for me.

The answer, by user Kevin Ennis, was this:

Instead of trying to preload, you could just execute your script on…

window.onload =function(){..}

That doesn’t fire until all images have been loaded.

My own solution was this:

Ok, so finally I got this thing to work. My problem? I was setting the waiting div wrong. This is my code now: I have the loading div which I show above everything and then when all images load (using $(window).load(function(){…}); as suggested I, hide that div.

<divid="loading"><divid="waiting"><imgclass="loadingGif"src="images/loading.gif"></div></div>

#loading
{
   background-size: 100%;
   background-color:#000;
   width: 100%;
   height: 100%;
   margin: 0px;
   padding: 0px;
   z-index:999;
}  

#waiting
{
   margin-left: auto;
   margin-right: auto;    
   position:absolute;
   top: 39%;
   left: 27.81%;
   width: 45%;
   height: 150px;    
   background-color: #FFF;
   border: 12px solid #FF771C;
   text-align: center;
}

And my jQuery code is this:

$(window).load(function(){    
    $('#loading').addClass('hidden');...}

Additionally, user Alex had a great answer too:

I  have a plugin named waitForImages that lets you attach a callback when descendent images have loaded.

In your case, if you wanted to wait for all assets to download, $(window).load() may be fine. But you could do it a bit cooler with my plugin 🙂

var loading = $('#loading');

$('body').waitForImages(function(){    
    loading.addClass('hidden');},function(loaded, total){
    loading.html(loaded +' of '+ total);});
Stack Overflow

Is there a PHP function to evaluate string like “2-1” as arithmetic 2-1=1

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

So, my question was if there is a PHP function which would take the string like “2-1” and produce the arithmetic result of it (1)? Or will I have to do this manually with explode() to get the values left and right of the arithmetic operator?

The answer, by user Jon, was quite elaborating:

I know this question is old, but I came across it last night while searching for something that wasn’t quite related, and every single answer here is bad. Not just bad, very bad. The examples I give here will be from a class that I created back in 2005 and spent the past few hours updating for PHP5 because of this question. Other systems do exist, and were around before this question was posted, so it baffles me why every answer here tells you to use eval, when the caution from PHP is:

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

Before I jump in to the example, the places to get the class I will be using is on either PHPClasses orGitHub. Both the eos.class.php and stack.class.php are required, but can be combined in to the same file.

The reason for using a class like this is that it includes and infix to postfix(RPN) parser, and then an RPN Solver. With these, you never have to use the eval function and open your system up to vulnerabilities. Once you have the classes, the following code is all that is needed to solve a simple (to more complex) equation such as your 2-1 example.

require_once "eos.class.php";
$equation ="2-1";
$eq =new eqEOS();
$result = $eq->solveIF($equation);

That’s it! You can use a parser like this for most equations, however complicated and nested without ever having to resort to the ‘evil eval‘.

Because I really don’t want this only only to have my class in it, here are some other options. I am just familiar with my own since I’ve been using it for 8 years. ^^

Wolfram|Alpha API
Sage
A fairly bad parser
phpdicecalc

Not quite sure what happened to others that I had found previously – came across another one on GitHub before as well, unfortunately I didn’t bookmark it, but it was related to large float operations that included a parser as well.

Anyways, I wanted to make sure an answer to solving equations in PHP on here wasn’t pointing all future searchers to eval as this was at the top of a google search.

Stack Overflow

How to add three dots in a multiline span

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

So, my question was that I actually found the solution to this in another StackOverflow question, and that the solution is pretty simple. The link to the jsFiddle for the example is here, and also copied here for reference. HTML code:

<span>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen look</span>​

CSS code:

span{
    display:inline-block;
    width:180px;
    white-space: nowrap;
    overflow:hidden !important;
    text-overflow: ellipsis;
}

And it works like expected, it prints: Lorem Ipsum is simply du…

However, when I tried this in another example. JsFiddle is here. HTML code:

<div class="textContainer">                
    <img src="#" class="image" alt="the_image">
    <span class="text">"The quick brown fox jumps over the lazy dog" is an english-language pangram, that is, a phrase that contains all of the letters of the English alphabet. It has been used to test typewriters and computer keyboards, and in other applications involving all of the letters in the English alphabet. Owing to its brevity and coherence, it has become widely known.</span>
</div>

CSS code:

.textContainer{
    width: 430px;
    float: left;
    margin-top: 10px;
    border: 1px solid black;                
}

.text {
    font-size: 24px;
    line-height: 24px;
    font-weight: bold;
    color: #047F04;
    display: block;
    white-space: normal;
    overflow: hidden !important;
    text-overflow: ellipsis;
    height: 99px;
}

.image {
    float: right;
    position: absolute;
    top: 85px;
    right: 10px;
    width: 108px;
    height: 42px;
}

So my question was how could I achieve to put … on the end of the string in my example?

The answer, by user devundef, was:

The specification for the text-overflow property says that this is not possible for multiline text:

This property specifies rendering when inline content overflows its block container element (“the block”) in its inline progression direction that has ‘overflow’ other than ‘visible’. Text can overflow for example when it is prevented from wrapping (e.g. due to ‘white-space:nowrap’ or a single word is too long to fit).

In other words, only works on single line text blocks.

source: http://dev.w3.org/csswg/css3-ui/#text-overflow

EDIT This fiddle has a workaround using jquery: http://jsfiddle.net/k5VET/ (source: Cross browsers mult-lines text overflow with ellipsis appended within a width&height fixed div?)

Stack Overflow

Serialize form not working in jQuery

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

So, my question was if, for example, we have this HTML form code:

<form action="#" id="gamesForm">
    <p>                                                        
        <input id="gName" type="text" class="medium" />
        <span class="notification information">Game name</span>
    </p>

    <p>                            
        <span class="notification information">Enabled:</span>
        <input id="gEnabled" type="checkbox" />              
    </p>


    <br />
    <!--Additional data for extra type-->
    <div id="extraAdditionalData" class="hidden">                            
        <p>
            <input id="rRacers" type="text" class="medium" />
            <span class="notification information">Racers</span>
        </p>

        <p>
            <input id="rVideoSet" type="text" class="medium" />
            <span class="notification information">Video set</span>
        </p>                                                         
     </div>                
</form>

<a href="#" id="saveConfiguration" class="graybuttonBig">Save everything!</a>

And this js code:

$(document).ready(function(){
    $("#saveConfiguration").click(function(){
        alert( $("form").serialize() );   
    });
});

How come that all I get in the alert is an empty string?

The answer, by user Felix Kling, was:

You have to give your form elements names!

This is independent of jQuery. Every form element must have a name to be considered for form submission as successful control:

A successful control is “valid” for submission. Every successful control has its control name paired with its current value as part of the submitted form data set. A successful control must be defined within a FORM element and must have a control name.

jQuery just ignores those elements that don’t have a name (or, depending on how it gets the elements, it might not even see them as the form itself has no reference to them).

Stack Overflow

How to replace text between quotes in vi or vim?

profile for Nikola at Stack Overflow, Q&A for professional and enthusiast programmers
I’m a big fan of Stack Overflow and I tend to contribute regularly (am currently in the top 0.X%). In this category (stackoverflow) of posts I will will be posting my top rated questions and answers. This, btw, is allowed as explained in the meta thread here.

So, my question was if for example we have this line of code:

$query = "SELECT * FROM table";

is there a command in vi/vim which can instantly delete everything between quotes and position the cursor between them so I can start typing immediatelly?

The answer, by user eugene y, was:

Use ci", which means: change what’s inside the double quotes.

You can also manipulate other text objects in a similar way, e.g.:

  • ciw – change inside a word
  • ci( – change inside parentheses
  • dit – delete inside an HTML tag, etc.

More about different vim text objects here.

Page 8 of 9« First...«6789»

Recent posts

  • Discipline is also a talent
  • Play for the fun of it
  • The importance of failing
  • A fresh start
  • Perseverance

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (35)
  • Daily Thoughts (77)
  • Go (3)
  • iOS (5)
  • JavaScript (127)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (2)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (77)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (40)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (81)
  • Unity3D (9)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak