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

Merge two sorted arrays and the resulting array should also be sorted

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 question was:

Let’s say you have two arrays of arrays with the same structure but different count of arrays in them:

$arr1 = array(array(1,"b"), array(2,"a"), array(5,"c"));  
$arr2 = array(array(3,"e"));

Now, the data in the $arr1 and $arr2 is sorted, and now what I would like it to merge these two arrays, so I did this:

$res = array_merge($arr1, $arr2);

And then I get an output like this:

1-b  
2-a
5-c  
3-e

But, I would like to have a sorted $res also like this:

1-b  
2-a
3-e  
5-c

I wonder if there’s a function in PHP to do this automatically, without me having to write my own function? Or, please advise me on which is the best approach for this if I want to (later on) add sorting by the next parameter so the output would be like this

2-a  
1-b
5-c  
3-e

 

The answer, by user fieg, was:

You can first merge the arrays and then sort the final array.

You are probably looking for a multi-sort function. I usually use this function (I found this functions somewhere on the internet years ago, credits go to the original author):

/*
 * sort a multi demensional array on a column
 *
 * @param array $array array with hash array
 * @param mixed $column key that you want to sort on
 * @param enum $order asc or desc
 */
function array_qsort2 (&$array, $column=0, $order="ASC") {
    $oper = ($order == "ASC")?">":"<";
    if(!is_array($array)) return;
    usort($array, create_function('$a,$b',"return (\$a['$column'] $oper \$b['$column']);")); 
    reset($array);
}

You can use it like this:

array_qsort2($res, 0, "ASC");
Stack Overflow

.htaccess – subdomain not working with www

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 question was:

I have a domain www.example.com and I have set .htaccess file to redirect all example.com to www.example.com

Now, I made (through my plesk 10 interface) a subdomain abc.example.com and what I would like is to also have www.abc.example.com so I entered (also in plesk) this:

www.abc.example.com.    CNAME   abc.example.com.

But it’s not working. Do I need to reload/restart dns?(if so, please tell me how?) Or do I just need to wait certain time for this until it propagates?

Since my mentioned CNAME didn’t work, I also added the .htaccess (which might be wrong (I know, not much of a server person 🙁 )) in the abc folder which looks like this:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^abc.example.com$
RewriteRule ^(.*)$ http://abc.example.com/$1 [R=301]

but with no luck, so please shed some light.

I found the solution myself in the end:

In Plesk I made one subdomain.domain.com pointing to lets say abc folder, and then I added the www.subdomain.domain.com also through Plesk but pointed it to the same abc folder. Then I added the .htaccess file inside this abc folder (where all other files for this subdomain reside) which now guarantees that all requests to subdomain.domain.com get redirected to www.subdomain.domain.com. Here is my .htaccess file:

RewriteEngine On    
RewriteCond %{HTTP_HOST} !^www.subdomain.domain.com$ [NC]    
RewriteRule ^(.*)$ http://www.subdomain.domain.com/$1 [R=301,L]

Hope this will help someone beginning with this stuff like me.

Just to note, the credit for the idea of pointingthe www.subdomain inside the same folder goes to user Bryan White on serverfault

Stack Overflow

Javascript regex match for string “game_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 question was:

I just can’t get this thing to work in javascript. So, I have a text “game_1” without the quotes and now i want to get that number out of it and I tried this:

var idText = "game_1";
re = /game_(.*?)/;
found = idText.match(re);

var ajdi = found[1];
alert( ajdi );

But it doesn’t work – please point out where am I going wrong.

 The answer, by Naltharial, was:

If you’re only matching a number, you may want to try

/game_([0-9]+)/

as your regular expression. That will match at least one number, which seems to be what you need. You entered a regexp that allows for 0 characters (*) and let it select the shortest possible result (?), which may be a problem (and match you 0 characters), depending on the regex engine.

Stack Overflow

How to reconfigure setTimeout on the fly

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 question was:

I was wondering if there is a way to set the setTimeout function to different timeout on the fly.

So, for example I check something every 1 second, but if I don’t get an expected result in like 10 seconds I want to “reconfigure” this setTimeout to wait 3 seconds instead of 1.

Here is my code:

var br = 0;
var waitInterval = 1000;
var sleepInterval = 2000;

var waitForNewRace = setInterval(
function checkForNewRace(){
    if ( $("#data").html() == "1"){        
        $("#res").html("got it!");
    }
    else{
        $("#counter").html(br);
        if (br++ > 9)
            waitInterval = 3000;            
    }                   

    $("#tst").html(waitInterval);
},
waitInterval
);

If you want to check it out here is the mentioned code on jsfiddle: http://jsfiddle.net/Hitman666/Vyczj/2/

 The answer, by KooiInc, was:

You have to stop the interval and restart it. See this fork of your jsfiddle.

EDIT: I’ve copied your code here in case something happens with your jsfiddle code:

var br = 0;
var waitInterval = 1000;
var sleepInterval = 2000;


function checkForNewRace(){
    if ( $("#data").html() == "1"){        
        $("#res").html("got it!");
    }
    else{
        $("#counter").html(br);
        if (br++ > 5){
            clearInterval(waitForNewRace);
            waitInterval += 1000;
            if (waitInterval > 10000)
                waitInterval = 10000;

            waitForNewRace = setInterval(
                 checkForNewRace,
                 waitInterval
            );  
        }
    }                   
    $("#tst").html(waitInterval);
}

var waitForNewRace = setInterval(
    checkForNewRace,
    waitInterval
);
Stack Overflow

New shiny StackOverflow profile page

StackOverflow updated the users profile pages, which now look awesome:

newSOprofile

It’s way cleaner now. All in all, thumbs up from me, and as it seem, most of the community. You can read more about it on their blog.

Stack Overflow

Is it possible in SQL to return a first row that has attribute names and then values

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 question was:

I am wondering if there is a way to write the SQL so that it would return me a result as usual but now, on the first row that would return also the attribute names.

To explain what I mean:

say you have a table “test” which has 2 attributes “id” and “name”:

id name
1  nik
2  tst

query:

SELECT*FROM test;

produces:

1 nik
2 tst

but what I want it to return is this:

id name
1 nik
2 tst

Is this possible?

edit: I am using PostreSQL

 The answer, by a_horse_with_no_name, was:

You cannot return the names and the actual column values in a single result unless you give up on the real datatypes (which is probably not what you want).

Your example mixes character data and numeric data in the id column and Postgres will (rightfully) refuse to return such a result set.

Edit:
I tested the “union” solution given e.g. by JNK and it fails (as expected) on Postgres, Oracle and SQL Server precisely because of the non-matching datatypes. MySQL follows it’s usual habits of not throwing errors and simply converts everything to characters.

Stack Overflow

Regular expression to match two numbers that are not equal

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 question was:

I was wondering how can I match two digits but which are not the same. So, it would be fine to match 12, but not 11.

What I have till now is: I have to match strings like “P12”, and I’ve done it with this regex:

^P([1-6]{1})([1-6]{1})$

But now my problem is how to match only strings like P12 or P32 where the numbers do not repeat.

Any help or guidance to reading materials will be grateful.

edit:  this is what worked:

^P([1-6]{1})(?!\1)([1-6]{1})$

 The answer, by Ignacio Vazquez-Abrams, was:

Use this:

^P((1[2-6])|(2[13-6])|(3[124-6])|(4[1-356])|(5[1-46])|(6[1-5]))$
Stack Overflow

Can I put star (★) in my email subject?

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 question was:

I got a request from my client that they want to add stars (★) to their email subject (They send these mails through the application we made as a part of bigger CRM for them).

I tried to send a test mail, and the email title is displayed nicely in my Gmail account, and I must agree with my client that it is eye catching, but what came to my mind is that this may be a spam magnet, so I googled about it but I can’t find the actual “don’t do this”.

Generaly, my oppinion would be not to use it, but now I have to explain to the client why. My best explanation whould be there is a probability your emails will be treated as spam but I don’t have the background for this statement.

Do you have any suggestions about what should I do?

 The rather extensive answer, by Kibbee, was:

The only information I could find is on the SpamAssassin page of how to avoid false positives. The only relevant part I found was this part.

Do not use “cute” spellings, Don’t S.P.A.C.E out your words, don’t put str@nge |etters 0r characters into your emails.

SpamAssassin is a very widely used spam filtering tool. However, simply breaking one of the rules (strange characters) alone wouldn’t get an email marked as spam. But combined with some other problems could lead to your email being considered spam. That being said, if your email is a completely legitimate business email, it’s likely that few other rules are triggered, and using the special characters wouldn’t create a huge problem. That being said, you should probably try out a couple test emails on SpamAssassin and a couple other spam filtering tools in order to come to a better conclusion on the emails you plan to send out.

Additionally, there was also a good answer from Nathan White:

Simply explain to your client as you have explained to SO: you stated that the star made it eye catching: this doesn’t directly mean that it will be treated as spam, but you could explain how that concept COULD be considered spam.

If the star is part of their branding, however, this could be quite a nice way in which your client expresses themselves.

Spam emails are becoming more and more like what one would consider ‘normal’, so I think they have trial it internally, test the concept.

Talk it over with your client – there is going to be no basis in hard fact with things like this, purely social perception.

And also by lukeA:

More and more retailers are using unicode symbols in their subject lines since a few months. Of course it’s in order to gain more attention in cluttered inboxes. Until now, there has been absolutely no evidence that such symbols increase the likelihood of failing spam filter tests. However, keep in mind that rare symbols might not render (correctly) across all mail user agents. Especially keep an eye on Android and Blackberry smartphones, but also on Outlook. In addition, due to a Hotmail bug symbols will render much bigger in subect lines and in the email body within the web front end. In fact, they are beeing replaced by images. All in all, the star shouldn’t make any problems. At least, if it’s encoded correctly in the subject line. So, go for it.

Stack Overflow

Options found in locals object in ejs

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 question was:

I got the following error when running the project from GitHub: “options found in locals object. The option(s) is copied to the option object. This behavior is deprecated and will be removed in EJS 3”

I tried to update the ejs and express modules to the newest versions but the notice persists. I googled, ofc, and the only thread about it is this, but it doesn’t help.

Does anyone know more about this?

For reference, here is the whole important code:

app/views/index.ejs

<!DOCTYPE html>
<html>
<head>
    <title><%= title %></title>
</head>

<body>
    <h1><%= title %></h1>
    <img src="img/logo.jpg" alt="Hack Hands logo">
</body>
</html>

app/controllers/index.server.controller.js

exports.render = function(req, res) {
    res.render('index', {
        title: 'MEAN MVC'
    });
};

app/routes/index.server.route.js

module.exports = function(app) {
    var index = require('../controllers/index.server.controller');
    app.get('/', index.render);
};

app/config/express.js

var express = require('express');
module.exports = function() {
    var app = express();

    app.set('views', './app/views');
    app.set('view engine', 'ejs');

    require('../app/routes/index.server.routes.js')(app);

    app.use(express.static('./public'));

    return app;
};

server.js

var port = 1337;
var express = require('./config/express');
var app = express();
app.listen(port);
module.exports = app;
console.log('Server running at http://localhost:' + port);

The answer, by Timothy Gu, was:

tl;dr: Upgrade to the latest version of EJS. It removes all warnings about options and locals.

whoami

I’m a collaborator (or the collaborator in @micnic’s comment above) in EJS v2. I only started maintaining EJS after version 2.0.3 (or something like that) was released, so I don’t know a lot about how the API changes took place.

History

EJS v2’s renderFile function, used by Express.js, now has the signature

function(path[, options[, locals]], cb)

But for compatibility with and Express.js, which calls all functions as

function(path, locals, cb)

with options mixed into the locals object, EJS automatically picks out the locals with option-y names and treat them as options.

But because the Express.js signature is also the function signature of EJS v1, we also print a warning if any option in locals is copied to options, urging developers to use the new signature with locals and options separated (it was actually me who added the warning).

However, Express.js users do not have a choice in terms of calling convention, so the warning is always present in Express.js.

Some users did complain: #34 #36.

At first, @mde (who is the main maintainer of EJS) pushed a fix, which correctly disables warnings on Express.js, and Express.js only.

But then, the person in #36 still complained, as he was using filename as the name of a local, and when the optiony local is copied to options a warning is printed.

At last, @mde was like “f*** this shit” and removed all the deprecation warnings, including an uncontroversial and legitimate one, and released version 2.2.4 (the legitimate warning was restored by me after the release).

Future

@dougwilson (an Express.js maintainer) said he was interested in a separation of options and locals in Express.js v5, just like in EJS v2. I did volunteer to make that change, but then I got busy so yeah.

Stack Overflow

Group by hour in mysql but include the first value from the hour+1 also

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 question was:

Say you have data like this:

  time  value
  10:00   5
  10:15   12
  10:30   15
  10:45   27
  11:00   29

And a query like this:

SELECT MAX(value)- MIN(value), HOUR(time)FROM mytable GROUP BY HOUR(time);

You will get:

 value  time
   22   10

But, I would need it to include the value at 11:00, thus the result being 24 (29-5), and not 22. Is there a way to do this in SQL or do I have no other choice than to do this manually in the code level (so, without the grouping, just fetching the data and manually substracting).

The answer, by ATP_JD, was:

Depending on how consistent your data is, you might be able to do this with a self join, like so:

SELECT HOUR(a.`time`)AS grouper,
GREATEST(MAX(a.value),IFNULL(MIN(b.value),0))- MIN(a.value)AS diff
FROM mytable a
LEFTJOIN mytable b ONIF(HOUR(a.time)<=23, HOUR(a.time)+1,0)= HOUR(b.time)GROUP BY grouper

The LEFT JOIN on the same table allows you to get the next hour’s value for comparison purposes.

http://sqlfiddle.com/#!9/fe72a/16

Page 5 of 9« First...«4567»...Last »

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