2016-09-29

Java 8: Find First Match

Oh, how I love chainable methods, especially over a stream...

// Return first match in this List, or null.
return contents.stream().filter(c -> c.name.equals(fieldName)).findFirst().orElse(null);

<3 lambda <3

2016-09-27

Java 8: Not So Poor Man's Timing

import java.time.Duration;
import java.time.Instant;

// ...

Instant start = Instant.now();
// Timed operations come here
Instant stop = Instant.now();
System.out.println("Task ran for: " + Duration.between(start, stop));

I love it.

2016-08-02

C: Linux sysinfo loads interpretation

There's this handy syscall in Linux, the sysinfo (kernel source), which returns some metrics about the current process.

What immediately stands out, is the load averages array. They are long values, how to make them to be our beloved fractional numbers?

These three values are scaled up by 65536, or more precisely by SI_LOAD_SHIFT. So we just divide them:

#include <sys/sysinfo.h>

// ...

struct sysinfo memInfo;
sysinfo(&memInfo);
printf("sysinfo: load1 = %2.2f\n", (float)memInfo.loads[0] / (float)(1 << SI_LOAD_SHIFT) );

2016-08-01

C: How to Detect LD_PRELOAD

As I'm writing a lib to be preloaded under something heavy, I tried to detect if LD_PRELOAD is set or not. For fun.

The easiest way to check is...get the environment variable! It is so straightforward, that I feel the urge to write it down :-)

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
 char *env_val = getenv("LD_PRELOAD");
 if (env_val[0] != 0) // May be set but value is empty.
  printf("LD_PRELOAD active: \"%s\"\n", env_val);
 return 0;
}

Note, this only checks the existence of the variable, not that if it is actually loaded...

2016-07-27

C: Sorted Walk Through Directory Contents

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>

void walk_dir(const char *path)
{
 struct dirent **namelist;
 int i, n;

 n = scandir(path, &namelist, NULL/*filter*/, alphasort);
 if (n < 0)
 {
  perror("scandir");
 } else {
  for (i = 0; i < n; i++) {
   printf("Entry: %s\n", namelist[i]->d_name);
   free(namelist[i]);
  }
  free(namelist);
 }
}

int main(void)
{
 walk_dir("/tmp");
 return EXIT_SUCCESS;
}

C: Simple Walk Through Directory Contents

You can easily walk through the entries in a directory. Note, that it's unordered.

#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>

void walk_dir(const char *path)
{
 struct dirent *entry;
 DIR *dir = opendir(path);

 while ((entry = readdir(dir)) != NULL) {
  printf("Entry: %s\n", entry->d_name);
 }
}

int main(void)
{
 walk_dir("/tmp");
 return EXIT_SUCCESS;
}

2016-07-26

C: Prettyprinted Value aka Controlled Rounding

void fancy(long l, long nearest)
{
 char suffix[2] = "";
 long mod, val = l;
 float f;
 
 if(val < 1500) /* Too small to pretty print. */
 {
  printf("%li B", val);
 } else {
  mod = val % nearest;
  /* Where are we in the range? */
  if(mod >= (nearest - mod))
  { // hi - we are at or above the 50% of the [0-nearest[ range.
   // add the difference to reach upper nearest.
   val += (nearest - mod);
  } else { // lo
   // substract the difference to reach lower nearest.
   val -= mod;
  }
  
  if(val < 1100000L)
  {
   f = (float)val / 1000;
   suffix[0] = 'K';
   
  } else if(val < 1100000000L)
  {
   f = (float)val / 1000000;
   suffix[0] = 'M';
  } else {
   f = (float)val / 1000000000;
   suffix[0] = 'G';
  }
  
  printf("%.2f %sB", f, suffix); // Here you can play with the format.
 }
}

Usage:

 long size = 3141592535L;
 fancy(size, 1000);

2016-07-25

Some Hungarian laws #3

http://net.jogtar.hu/jr/gen/hjegy_doc.cgi?docid=A1200001.TV
2012. évi I. törvény
a munka törvénykönyvéről

7. § (1) Tilos a joggal való visszaélés. E törvény alkalmazásában joggal való visszaélés különösen, ha az mások jogos érdekeinek csorbítására, érdekérvényesítési lehetőségeinek korlátozására, zaklatására, véleménynyilvánításának elfojtására irányul vagy ehhez vezet.

Érdekesség, hogy az említett "mások jogos érdekei"-ben a "mások" vonatkozik a munkaerőpiac többi tagjára (pl. jelen és leendő munkavállalók, tehát en bloc a Piac), illetve a fizetés eltitkolása nem jogszerű érdeke a munkáltatónak, hisz az piackorlátozó hatású.

Azaz például (leendő) munkáltató nem korlátozhatja munkaszerződés-ajánlat nyilvánosságra hozását, ajánlott bér összegének továbbközlését; munkáltatóról (vagy bármi másról) vélemény formálását, mely nem tetszik a munkáltatónak, pl. felvételi folyamat kritizálása, vagy sima leírása (lásd: Glassdoor, fórumok), hiszen az nem a munkája során kerül tudomására.

A probléma az, hogy a jogalkalmazói gyakorlatban viszont a PTK üzleti titok definícióját alkalmazzák, ami szerint a munkabér kifejezetten üzleti titok.

Ám mivel a munkabérrel, kompenzációval kapcsolatban az alkalmazó és az alkalmazott is titokgazda, az alkalmazottak a saját bérezésükkel kapcsolatban nem jogosulatlan személyek, így az üzleti titoksértés nem állhat fent (nincs illetéktelenség).

A Munka Törvénykönyve szerint a munkaszerződés munkaviszonyra vonatkozó szabálytól csak a munkavállaló javára térhet el, így elvileg egy ilyen irányú tiltás alapvetően jogellenes.

Mi hát a megoldás eme szürke zónában Magyarországon? Kinek van jobb ügyvédje, ha a munkáltató pert indít...

2016-05-11

Note to self #4

Next time you screw up your default file extensions as I did (executing a .bat file resulted in an IE's View Downloads window -_- ...), look here for a fix: http://www.winhelponline.com/blog/file-asso-fixes-for-windows-7/

2016-05-09

c: How not to code #1

(gdb) bt
#0  0x00007f8ac115bebe in __lll_lock_wait_private () from /lib64/libc.so.6
#1  0x00007f8ac10f22be in _L_lock_9876 () from /lib64/libc.so.6
#2  0x00007f8ac10f05c1 in free () from /lib64/libc.so.6
#3  0x0000000000402649 in handle_sig (signo=<optimized out>, info=<optimized out>, context=<optimized out>) at lol.c:158
#4  <signal handler called>
#5  0x00007f8ac10edf03 in _int_malloc () from /lib64/libc.so.6
#6  0x00007f8ac10f06b7 in malloc () from /lib64/libc.so.6
#7  0x00000000004015ba in do_the_boogie (fd=3, gp=<optimized out>) at lol.c:715
#8  0x00000000004023cc in main (argc=5, argv=<optimized out>) at lol.c:810

LOL, it is deadlocked. The signal handler (frame #4) was invoked inside a malloc (frame #5), and the signal handler calls free in frame #3. Of course, the heap lock is held in frame #5 and both are in the same memory arena (see: break space), hence we are screwed.