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

Regular expression to match sets of numbers that are not equal nor reversed

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 am referring as a follow up on this question here: Regular expression to match two numbers that are not equal

Now my other question scenario is this:

P121324 - T  
P1212 - F - we got this covered in the message on link above (no same "sets")
P1221 - F - now new restriction -not even the reversed digits 12-21

But, the problem now is that the P string can be very long! – like this:

P121315162324

please notice this is ok since the “sets” are:

12131415162324

Now, I could make this in the code (PHP) by checking if there are repetitions, but I was wondering if this can be done with single regex command?

The answer, by Mark Byers, was:

Try this:

^P(?:([0-9])(?!\1)([0-9])(?!(?:..)*(?:\1\2|\2\1)))*$

If you want the digits to be restricted to [1-6] like in your previous question then change [0-9] to [1-6].

See it working online: rubular


Here is a breakdown of the regular expression:

^          Start of string/line.
P          Literal P
(?:<snip>) Non-capturing group that matches a distinct pair of digits. See below.
*          Zero or more pairs (use + if you want to require at least one pair).
$          End of string/line.

Explanation of ([0-9])(?!\1)([0-9])(?!(?:..)*(?:\1\2|\2\1)) – match one pair:

([0-9])    Match and capture the first digit. Later refered to as \1.
(?!\1)     Negative lookahead. The next character must not be the same as \1.
([0-9])    Match and capture a digit. Later refered to as \2.
(?!<snip>) Negative lookahead. Check that the pair doesn't occur again.

Explanation of (?:..)*(?:\1\2|\2\1) – try to find the same pair again:

(?:..)*       Match any number of pairs.
(?:\1\2|\2\1) Match either \1\2 or \2\1.
Stack Overflow

Best practice for C# calling PHP which then queries the database

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:

For some reason I have to have a windows client application (written in C#) which communicates with the PHP files that are on my server. Windows application can’t be allowed to have SQL queries in the code because of the possible disassembling of the exe file. This is the main reason why this approach is used.

Basically it looks like this: from windows client i call getResult.php which then opens the connection to the database, queries the database, returns the result to the client and closes the database connection. Therefore windows client doesn’t have any code for querying the database, it just has calls to the PHP file.

My several questions follow:
1. What is the best way to send request from c# code to the PHP file? (Cause I need to send this php file some parameters like ID, etc… -> I know I can do it with GET like this getResult.php?id=123456, but is this same possible with POST? And also, one question: how to do this in code? http requests or?)

2.Since every time I call the PHP file (there will be more files which I will call, like getResult.php, getStatus.php, etc…) I will somehow need to send login information to that PHP file with which that PHP will query the database. My question here is how to do this securely, and plus: is it maybe somehow possible to call something like doLogin.php and send the login username and password one time, and after that call this (and all other) php files without the need to send the login information as a parameter to the function. I know I can use PHP sessions when the whole application is on the server, but the main difference here is that I am only calling some files, executing them and closing the connection.

My main question is: is this ok from conceptual point of view or are there any commonly known concepts for this, for which I don’t know about – please advise I’m willing to learn. I did some research and do believe this might have to be done with web services approach, but please do reply your thoughts on this.

The answer, by Steve Mayne, was:

Your PHP code is effectively serving as a RESTful data-access API. Run your PHP on a webserver over SSL (HTTPS) so that all your comms are encrypted.

You could either use trusted certificates to authenticate the client, or if you require different access levels, submitting a username/password to get an authorisation token for the data-access requests is not a bad idea.

Here is an example from Yahoo!: http://developer.yahoo.com/dotnet/howto-rest_cs.html

But, another good answer was from user Tom Glenn:

For a simple GET you can do:

var webClient =newWebClient();
webClient.DownloadString("http://someurl.com/somescript.php");

You could then return perhaps an XML or JSON formatted response from the PHP script? You can use WebClient for POST too.

As for the login, you can do that too. I do a similar thing in one of my applications. We send the login details to the script (ASP.NET not PHP) and the ASP page returns an XML response telling the C# app whether or not it was successful – the application can then decide whether it is allowed to continue or not.

Servers

VPS with 1GB of RAM for 19$ per year!?

The guys at WeLoveServers.com are having an anniversary sale. And a sale it is indeed! If someone knows of a better option please share it in the comments!

In order to use the sale, visit their site through my aff link: http://core.weloveservers.net/aff.php?aff=584 and after this click on any of the sale links below.

They’re offering the following two options:

  • LEB 1GB – the link to the sale is here
  • LEB1
  • LEB 2GB – link to the sale is here
    LEB2

So, basically, you get 1GB of RAM VPS for less than 19$ a year, and you get 2GB of RAM VPS for 48$ a year. Important thing to note is that I spoke with their sales representative and he told me that the price after this first year stays the same!?

Settings and additional options which you can set during the signup are:

WLSsettings

You can buy additional RAM, storage, bandwidth, IP addresses, and even set a location of your server (TX, CA, NY, FL, UK). True, originally you don’t get any admin panel, but they offer a cPanel for 14.95$ a month if you really need one.

Anyways, I got myself one of the LEB 2GB and so far I’m very pleased with it and I have to say kudos to the customer service.

The basic panel looks like this:

wlsPanel2

We’ll see how this goes in the future – of which I’ll update you on this blog.

Happy testing!

Stack Overflow

How to serialize everything but the checkbox elements in jQuery.serialize()?

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 if there is a way to serialize all form elements using serialize() function except the checkboxes?

The answer, by Simeon, was:

The .serialize() method can act on a jQuery object that has selected individual form elements, such as<input>, <textarea>, and <select>.

You could do this:

var s = $('#post-form').find('input, textarea, select').not(':checkbox').serialize()
Hacker Games, JavaScript

JavascriptBattle

Lately I’ve been playing at JavascriptBattle, which is

a fun and engaging web application intended to make artificial intelligence (AI) design accessible to all. Every day, your code will be pulled down from your “hero-starter” repository on Github. Your code (along with every other user’s code) will be run daily, behind the scenes, in our game engine.

Basically, you write JavaScript code for your hero in order to instruct him how to behave when for example his health drops to a certain level, or when enemies are close, etc. and then you participate in a daily battle. They have various stats, and as it turns out I’m currently on position #3 for average damage dealt, yay me!

JavascriptBattle

 

Anyways, it’s cool so feel free to check it out and take me down from the pedestal :P. If you happen to like these “hacker games” then do checkout the one I made for my university project back in the old days 1415131129_smiley-evil.

Hacker Games

Topcoder Scavenger Hunt

I just competed (and finished! – I’m Hitman666) a Topcoder Scavanger Hunt.

topcoderScavangerHunt

Anyways, you have the instructions on how to play on the link above. I’ve really missed these kind of “hacker games”, like back in the days I was very active on hackits.de, but that site is long down now. Anyone playing similar games today, which you can recommend? I made my own for the project on university: http://nikola-breznjak.com/challenge/.

The questions were quite cool (no, no answers here, you’ll have to research it yourself):

  • How many ‘Albert’ monkeys died in the US Space program?
  • What was the original name of Nintendo’s Super Mario?
  • How many female fighter pilots were there in the original Star Wars trilogy?
  • How many different combinations of coins are possible for the US dollar?
Stack Overflow

How to get Disk Space Usage and Monthly Bandwidth Transfer from cPanel to my website in PHP

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’m wondering how can I show (get) disk space usage and monthly bandwidth transfer on my website in the same way as it’s shown when I login to my cPanel account. Is there an api from cPanel for this or is this a general method to do so? I’m using PHP.

This answer, by user richsage, was:

cPanel/WHM has an API which offers access to both the elements you’re looking for. See the API docsfor more details. The bandwidth and disk usage modules in API 1 output HTML, however API 2 has anaccount summary method which will return the diskused parameter in the appropriate format (XML/JSON as requested).

JavaScript

JavaScript event loop video explanation

Awesome short video about JavaScript event loop

One cool thing I didn’t know is that you can defer something right after the end of the stack. So for example the code below in the setTimeout function would print to console “done”, right after “hi” and “testing”:

console.log("hi");

setTimeout(function(){
    console.log("done");
}, 0);

console.log("testing");

 

JavaScript

Converting a JavaScript switch statement into a function lookup

I just read a great post on WebTools Weekly newsletter about how to convert a JavaScript switch statement into a function lookup. Here’s the full content from there, so be sure to check it out if you like it (it’s one newsletter a week, and no – I’m not affiliated with them in any way).

Because of the problems inherent in using JavaScript’s switch statement, many developers and reference guides will recommend avoiding switch constructs and instead using something called amethod lookup (also referred to as a lookup table or even dispatch table). Let’s convert a switchstatement to a method lookup, so we can see how this is done. Here’s our switch:

function doSomething(condition) {
  switch (condition) {
    case 'one':
      return 'one';
    break;

    case 'two':
      return 'two';
    break;

    case 'three':
      return 'three';
    break;

    default:
      return 'default';
    break;
  }
}

(JS Bin example)

All of this is inside a doSomething() function, with a condition passed in. The possible values are ‘cased’, to define the return value. This is cleaner than a messy if-else construct, but can we clean it up even more? Here’s basically the same thing in the form of a method lookup:

function doSomething (condition) {
  var stuff = {
    'one': function () {
      return 'one';
    },

    'two': function () {
      return 'two';
    },

    'three': function () {
      return 'three';
    }
  };

  if (typeof stuff[condition] !== 'function') {
    return 'default';
  }


  return stuff[condition]();
}

(JS Bin example)

In the demo, you can see four logs in the console, one for each valid condition and then another one to demonstrate the default condition when the argument doesn’t match one of the methods.

You can see why people like this technique. It’s clean, elegant, and seems a little more sophisticated without being more complex. I’ve only scratched the surface on this, so here are a few good resources to read up more on this subject:

  • Don’t Use Switch in Programming JavaScript Applications by Eric Elliot.
  • Using Dispatch Tables to Avoid Conditionals in JavaScript by Josh Clanton
Stack Overflow

Is there an event just before the radio button is about the be checked?

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:

This is the part of the code for one of the radio buttons:

$("#new").click(function(){
    if( $('#new').is(':checked') )
        $.jGrowl("You already have this option selected!", life: 1500});
    else
        changeOption(1);
});

Now, I understand that the else part will never run, because the radio button will be already checked on click event. What I’m wondering is, is there an event which would let me capture the state of the radio button (which is about to be clicked) and therefor determine if he is not yet clicked, and if so change the option to this newly selected one.

The answer, by JOPLOmacedo, was:

Use the mouseup event instead.

$("#new").mouseup(function(){if( $('#new').is(':checked'))
        $.jGrowl("You already have this option selected!", life:1500});else
        changeOption(1);});

The fiddle.

Edit
Even though the mouseup event works, it seems more logical to use the mousedown event. Here’s that fiddle.

Page 44 of 51« First...102030«43444546»50...Last »

Recent posts

  • When espanso Breaks on Long Replacement Strings (and How to Fix It)
  • 2024 Top Author on dev.to
  • Hara hachi bun me
  • Discipline is also a talent
  • Play for the fun of it

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (36)
  • Daily Thoughts (78)
  • Go (3)
  • iOS (5)
  • JavaScript (128)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (3)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (78)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (41)
  • 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