lunes, 13 de agosto de 2018

[Java] Convert float[] to double[]

Typically when you have a float array in java, you cannot simply cast it to a double array like you do with other types.

here is a nice and simple function to convert a float array into a double array without loosing precision.


     public double[] floatToDouble(final float[] aFloatArray) {
         
        DoubleStream doubleStream = IntStream.range(0, aFloatArray.length)
                .mapToDouble(i -> aFloatArray[i]);
        
        return doubleStream.toArray();
     }

So in summary you could use it like this:


     public void aMethod(){
        final float[] aFloatArray = new float[]{
                1.02f,
                2.39f,
                13.0884f
        };
        
        final double[] aDoubleArray = floatToDouble(aFloatArray);
     }


And there it is! A simple and elegant way to convert your float arrays to double arrays.

lunes, 6 de agosto de 2018

[jQuery] How to cancel an on-click event

Suppose you have the following html button



<button type="submit" class="btn" id="cancel_me">
  Cant Click Me!
</button>


And you want to prevent the default behaviour using jQuery in order to perform some other action

Here is the code that you need to do:


$(function() {
    $("#cancel_me").click(function(e) {
        e.preventDefault();
        /*Do Things*/
    });
})


And where it says "Do Things" insert the new behaviour you want to override with.

The preventDefault() method does the magic trick!

[Java] Printing Array List To Text File

Suppose you have a unidimensional list of Strings. And you want to write that list placing one item of the list in one line of a file.

First you have the list


        List sample = new ArrayList<>();
        sample.add("foo");
        sample.add("bar");
        sample.add("bizz");
        sample.add("bazz");


Then we define a BufferWriter with a FileWriter pointing to where the file will be


 BufferedWriter writer = new BufferedWriter(new FileWriter("out.txt"));

Then we do some streams and forEach to write the file.


       sample.stream().forEach(s -> {
            System.out.println(s);
            try {
                writer.write(s + '\n');
            } catch (IOException e) {
                e.printStackTrace();
            }
        });

And finally we close the buffer as good citizens.


  writer.close();

All together now:

package com.sourcecodecenter;



import java.util.*;
import java.io.*;

public class ListToFile {
    public static void main(String []args) throws Exception {
        List sample = new ArrayList<>();
        sample.add("foo");
        sample.add("bar");
        sample.add("bizz");
        sample.add("bazz");

        BufferedWriter writer = new BufferedWriter(new FileWriter("out.txt"));
        sample.stream().forEach(s -> {
            System.out.println(s);
            try {
                writer.write(s + '\n');
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        writer.close();
    }
}

sábado, 5 de mayo de 2012

Check if record exists in MySQL table with php

So Hello again,

this time I come with a little nice code snippet, that will help you to easily check if a record exists in a MySQL table, so for example I will take the task "check if a username exists in the users table"

for this you will need two functions:


function connect(){ 
  include('config.php'); //where you have your db stuff saved
  $link = mysql_connect($db_host, $db_user, $db_pass);
  if(!$link){
   die('ERROR: 001');
  }
  return $link;
 }


this can be replaced by your favourite way to connect to the database, so next function:



function check($table, $fields, $values) { 
  if((count($fields) > count($values)) || count($values) > count($fields)) die('ERROR 004');
  include('config.php');
  $link = connect();
  mysql_select_db($db_name);
  $check_query = 'SELECT ';
  for($i=0;$i<count($fields);$i++){
   $check_query .= $fields[$i].',';
  }

  $check_query = rtrim($check_query, ',');
  $check_query .= ' FROM '.$table.' WHERE ';

  for($i=0;$i<count($fields);$i++){
   $check_query .= $fields[$i].'=' .$values[$i] . ' AND ';
  }

  $check_query = substr($check_query, 0, -4).';';
  $result = mysql_query($check_query);
  if(!$result){
   die('ERROR: 005 ');
  }

  $count = mysql_num_rows($result);
  if($count > 0) die('username taken!');
}

here there are 3 parameters:

  • Table: the table name you want to query
  • Fields: the fields you want to query
  • Value: the values you want to query
notice that fields and values must have the same count() otherwise it wont work!

so the usage should be:


check('users', array('username'), array('\''.$username.'\''));

if you want to compare more values, just make the arrays bigger and dont forget the " ' " in varchar or texts.

this is an easy way to kill the pain of writting querys over and over again. I hope it helps you out.

Happy codding.


sábado, 19 de noviembre de 2011

Extremely large data bulk via php

Hello,

after a long time without posting anything here, I come with a post that might result usefull to some people.

The thing is that I found myself with a xls sheet with about 50,000 registers, that my client needed uploaded to his personal server, he gave extra-restricted access to a ftp server and phpMyAdmin, and he just wont understand how hard is to upload that amount of registers without seeing a "fatal error" about memory limits or timeouts.

Maiking it quick and to the point, if you have a large execution php script, and by large I mean by size and time, this two codelines can save your life:


ini_set('memory_limit', '-1');
set_time_limit(0);


yes, you gussed it, the first line is to override and set no memory limit, and the second one is to override the time limit.

you need to be responsable using this, because depending on the power of your server your site can slow down significantly while processing the bulk load.

the other option is to get navicat pro this little badass will transform your xls sheets to a MySQL valid file, oh yeah!, then you can use phpMyAdmin, to upload it, for this I recomend to zip the generated script, and use the import option, of course you will get a timeout, memory exausted and shit, BUT the cool thing about phpMyAdmin is that it will automatically continue where it left if you upload the file again without navigating to other page.

Well, I hope you can migrate your data succesfully :)

Happy Coding!

jueves, 11 de agosto de 2011

[C#] Simple Slpash Screen

What I'm doing here is a very simple splash screen, must clients wnats their applications to have a splash screen, even when there is really nothing that worth preloading, so if this is the case keep reading, if not go and find another post.

So basically what we do is, create a new Thread that will wrap a method called wait();
in the form_load, like this:


private void Form1_Load(object sender, EventArgs e)
{
ThreadStart ts = new ThreadStart(wait);
Thread t = new Thread(ts);
t.Start();
}


and then we create a method that will trigger the main form or application after a little wait, this gives the idea of "preloading" but without actually preloading anything.


public void wait()
{
Thread.Sleep(5000); //time to wait in milliseconds
MessageBox.Show("done loading"); // actions to take when the wait is done
}


and that's it.

Happy Coding!

viernes, 24 de junio de 2011

Printing Rich TextBox Without PrintDialog [C#]

So I was in need to print the contents of a rich TextBox, but scince the PrintDialog buttons are so small, and I'm working on a touchscreen application I needed to make it automatic, so I spent like 4 hours fooling around msdn with gigantic ass complex tutorials, but I insist on keeping things Simple. So after tons of googling I finally found this awesome code snipet that saved the day :)

23.51.1.Basic Printing

Dont know who is the author but thanks man! :)

so I've added a few lines to print the images in the text box, notice I saved the images in data structures first and then print out. So my version of this wonderfull codesnipet is:


/*the button to do the magic no-PrintDialog thing*/
private void button12_Click(object sender, EventArgs e) {
    PrintDocument pd = new PrintDocument();
    pd.PrintPage += new PrintPageEventHandler(PrintPageEvent);
    pd.Print();
}

/*and the PrintPage Event Handler where the magic happens.*/
private void PrintPageEvent(object sender, PrintPageEventArgs ev) {
    string contents = "Date: " + DateTime.Now.ToShortDateString() + Environment.NewLine;
    contents += txtTicket.Text;
    contents = contents.Normalize();
    Font oFont = new Font("Arial", 10);

    /*the next two lines are commented because they add a margin to the page (I dont want that)
    Rectangle marginRect = ev.MarginBounds;
    ev.Graphics.DrawRectangle(new Pen(System.Drawing.Color.Black), marginRect);*/

    /*Here I print the Image(s) with the DrawImage Method of the handler*/
    ev.Graphics.DrawImage(global::MyProgram.Properties.Resources.Header3, 10, 10);

    /*and now the string.  */
    ev.Graphics.DrawString(contents, oFont, new SolidBrush(System.Drawing.Color.Black), 10, 90);
}

this is it :)
Happy Coding!
P.S:
Remember folks: