# [ANDROID] How to create a background shape with a double border / rounded border with a drop shadow

Usually we use <shape> objects in our .xml drawables meant for the backgrounds of buttons or other View objects.

I came across a situation where such object should appear as if it had been previously selected, and the graphic design choice was to put a thick rounded stroke around the container, while at the same time showing a hint of a dropped shadow.

Android <shape>’s only allow us to define rectangles, curve their <corners>, fill them up with <solid> colors, and to give them a single <stroke> around (dashed or solid). Therefore we can’t think of using 2 strokes.

Luckily drawable resources to be used as View backgrounds can be created using not just shapes, or bitmaps, but <layer-list>’s.

For creating the selected button below

this is what I did (after over an hour of playing around until I was happy, for some reason UI code takes me the longest to get it right, am I the only one?)

# [TUTORIAL] HOW TO PAUSE AN AWS ELASTIC BEANSTALK ENVIRONMENT USING THE DASHBOARD

So you have set up a test elastic beanstalk environment because you don’t want to put at risk your production elastic bean.
You don’t want to pay for the time you’re not using it, and there’s no freaking “Pause Environment” option.

all you can do is “Terminate Environment”? but then to crete the damn environment it takes forever to configure (if you’re using the dashboard), so we don’t want to do that.

If you try to terminate the associated EC2 instance, the Elastic Beanstalk environment will automatically provision a new machine for you, so that doesn’t work. What do you do?

Open the Elastic Bean environment you want to pause and go to “Configuration”

On the Scaling card, click on the Gear icon to change its settings

in the “Auto Scaling” options, set the “Minimum instance count” to 0, and the “Maximum instance count” to 0

Hit “Apply”

Wait for your environment to apply the new configuration

Now your health status has switched to gray. It’s now paused and you won’t be paying for the test ec2 instance while you’re not working on it.

If you are curious and you check the ec2 instances associated to the environment, it/them should be terminated now, but now the environment won’t try to provision new ones.

# [SYSADMIN] Serve your WordPress cached pages directly with lighttpd and not PHP

If you don’t configure your wordpress virtual host properly in lighttpd, your wordpress cache will still make use of PHP.

Wouldn’t it be nice if all those cached requests were served directy from the webserver as the static files that they are, bypassing the CPU/memory load PHP can have, and use those resources for otherthings?

# Install and Enable mod_magnet

For this to occur with lighttpd, you will need mod_magnet, so assuming you’re on a Ubuntu/Debian based linux distro let’s make sure we have it installed.

sudo apt-get install lighttpd-mod-magnet

Then let’s make sure it’s enabled, you can do this manually on your lighttpd.conf by adding “mod_magnet” to the list of enabled modules…

server.modules = (
"mod_fastcgi",
"mod_access",
"mod_alias",
"mod_accesslog",
"mod_compress",
"mod_rewrite",
"mod_redirect",
"mod_status",
"mod_proxy",
"mod_setenv",
"mod_magnet"
)


or you can do it the lighty way:

sudo lighty-enable-mod magnet

(this simply makes a symlink to the 10-magnet.conf file inside /etc/lighttpd/conf-enabled which lighty will check upon startup)

# The cache logic script that will be executed by lighttpd

Now, on your wordpress directory, create a file called rewrite.lua and paste the following script in it:

function log(str)
-- wanna tail -f a log to see what's happening
fp = io.open("/path/to/some/lua.log","a+")
fp:write(str .. "\n")
fp:flush()
fp:close()
end

function serve_html(cached_page)
if (lighty.stat(cached_page)) then
lighty.env["physical.path"] = cached_page
return true
else
return false
end
end

function serve_gzip(cached_page)
if (lighty.stat(cached_page .. ".gz")) then
lighty.env["physical.path"] = cached_page .. ".gz"
return true
else
return false
end
end

if (lighty.env["uri.scheme"] == "http") then
ext = ".html"
else
ext = "-https.html"
end

cached_page = lighty.env["physical.doc-root"] .. "/wp-content/cache/supercache/" .. lighty.request["Host"] .. lighty.env["request.orig-uri"]
cached_page = string.gsub(cached_page, "//", "/")
cached_page = string.gsub(cached_page, lighty.request["Host"] .. "/index.php", lighty.request["Host"])

attr = lighty.stat(cached_page)

if (attr) then
query_condition = not (lighty.env["uri.query"] and string.find(lighty.env["uri.query"], ".*s=.*"))

accept_encoding = lighty.request["Accept-Encoding"] or "no_acceptance"

if (string.find(accept_encoding, "gzip")) then
if not serve_gzip(cached_page) then
serve_html(cached_page)
end
else
serve_html(cached_page)
end
--log('cache-hit: ' .. cached_page)
end
else
--log('cache-miss: ' .. cached_page)
end


# Configuring your vhost in lighttpd for WordPress redirects and direct cache serves without php.

Then on your vhost configuration in lighttpd.conf add the following towards the end.
(Fix paths if you have to)

var.wp_blog = 1

magnet.attract-physical-path-to = ( server.document-root + "/rewrite.lua" )

url.rewrite-if-not-file = (
"^/(wp-.+).*/?" => "$0", "^/(sitemap.xml)" => "$0",
"^/(xmlrpc.php)" => "$0", "^/(.+)/?$" => "/index.php/$1" )  Restart your lighttpd sudo service lighttpd restart Now watch how your PHP processes breathe a lot better and you page loads are insanely faster. You’re welcome 🙂 # [ANDROID] How to set a custom title View on a DialogPreference extending class. So you have a FooDialogPreference class which extends DialogPreference, and one of the things you’d like to do to it, is to change the Dialog’s title. DialogPreference happens to be a bit of a bitch, you can’t just call getDialog() and start playing with its features before it is shown because the Dialog object is only created when DialogPreference.showDialog()is called. However, there’s ONE entry point where you can make your magic happen. If we look at the code of DialogPreference.showDialog() from the geniuses at the Android project, some gentle soul added a call to onPrepareDialogBuilder(mBuilder); which is a method you’re meant to override. Override this method, and then with the builder object you’ve received you will be able to call: builder.setCustomTitle(myCustomTitleView); However, there’s a couple of things you need to do: 1. Instantiate your myCustomTitleView object on the implementation of your onBindDialogView, and keep the reference as a private property of your FooDialogPreference class. 2. Make sure to detach it from it’s parent ViewGroup, otherwise you will get an IllegalStateException from android.view.ViewGroup.addViewInner() letting you know this view you’re trying to add, cannot have a parent. This is what I had to do: final ViewGroup parent = (ViewGroup) myCustomTitleView.getParent(); parent.removeView(myCustomTitleView); builder.setCustomTitle(myCustomTitleView); That’s all folks! # Things to think about when tuning libtorrent for high performance An user on the libtorrent mailing list had the following problem: I’m doing some testing for a libtorrent application that will use a small number of peers (often just 1 seed and 1 downloaded) and high bandwidth delay product links (in the hundreds of Mb/s and 100ms+ round trip). I’m unable to get more than 20Mbps with a single peer on a 140ms RTT link (simulated delay with no packet loss). If I take the network simulator delay down to 0, I can get almost a full 1000Mbps on the same system. I’ve tried playing with everything that sounded relevant in session_settings, but nothing seems to make any improvement at all. Is this the best that can be expected out of uTP on a high latency link? Or is there some combination of parameters that would improve the single peer throughput? Alternatively, is there a way to get libtorrent to make multiple connections between the same 2 peers? If you’re facing a similar situation here are some things you could adjust according to Arvid Norberg lead engineer of the libtorrent project. “Did you increase the socket buffer sizes on both ends?” int recv_socket_buffer_size; int send_socket_buffer_size;  “There’s also buffer sizes at the bittorrent level:” int send_buffer_low_watermark; int send_buffer_watermark; int send_buffer_watermark_factor;  “And there are buffers at the disk layer:” int max_queued_disk_bytes; int max_queued_disk_bytes_low_watermark;  If the performance issue happens with uTP but not TCP though, it’s probably just the first ones that matters. Also, the uTP implementation needs a system call for each packet sent and received (i.e. it does not use sendmmsg()/recvmmsg()) which also makes it more expensive than TCP, but that would primarily cause additional CPU usage, and only slow-downs once a CPU core is pegged. # command line speed test, see how fast is your server’s connection Save the following script in a file called speed_test #!/bin/bash # Requirements # sudo apt-get install lftp iperf lftp -e 'pget http://releases.ubuntu.com/14.04.3/ubuntu-14.04.3-desktop-amd64.iso; exit; '  make sure the file is executable: sudo chmod +x speed_test Once you have installed lftp and iperf make sure you have the script somewhere in your $PATH.

The output looks like this on a AWS m3.large instance:

$speed_test 1054871586 bytes transferred in 14 seconds (70.37M/s)  Multiply by 8 to convert 70.37M/s to Megabits per second = 562.96 Mbit/s AWS’s download speeds for m3.large instances is half a gigabit in January 2016. (or is that the upload speed of the Ubuntu ISO server?) # IntelliJ / Adroid Studio / CLion / GoLand / PyCharm / PHPStorm keymap shortcuts I can’t live without ## Download settings.jar (Import with File -> Import Settings) I got to IntelliJ after years of using Emacs and Eclipse. Here’s how my keymap looks now that I work with Jetbrains tools, these are the keyboard shortcuts I can’t live without as a programmer. Legend (Mac keyboard) ⌘ Command ⇧ Shift ⌘1 Show Intent Actions (Things like assign to local variable) ⌘- Decrease font size ⌘= Increase font size ⌘0 Reset font size ⌘↓ Scroll to botom ⌘↑ Scroll to top ⌘f Find in text ⌘. Find next highlighted error ^⇧F Find in path (searches in all files, like a grep) ⌘⇧G Find Usages (Find all Occurrences of selected symbol [variable, method, class, identifier]) ⌘I Show current function/method parameter info F3 Jump to source (go inside function’s code) ⌘E Show list of recent files ⌘B Build ⌘L Jump to line number ⌘[ Back ⌘] Forward ⌘T Show implementations of an interface. ⌘⇧F Format (selected) code ⌘⇧O Organize/Optimize imports ⌘⌥R Rename current symbol ^K Kill line ⌘D Duplicate line Ctrl+G on selected token – repeats selection and enables multiple cursors Alt+Up | Alt+Down – Move the current line up or down Debugger shortcuts F5 Step Into F6 Step Over F7 Step Out F9 Resume Program ^K Cut up to Line End. (Deletes everything to the right of where the text cursor or caret is) # How to create a list that holds different object types using void* in C. I remember being in school back around 1998 and not knowing enough about C to do this. After coding in other languages, then going back to C++ and understanding at a lower level how references and pointers work, this was pretty easy to figure out. In this exercise I store elements of different types in a forward linked list. In order to know what to dereference as I iterate through the list’s elements, I’ve put a “.type” field, which has an int value representing the type of the object stored. The “.value” is simply a void*, which lets me store a pointer of any kind, and it works pretty well. Here’s the code for your enjoyment, I hope this is useful to C apprentices. The example shows how you can store native types like int, or more complex char* or even a struct person* (which is the more useful probably to your purposes) It’s a good exercise to see the uses of the “address of” operator “&”, which is used to initialize pointers (the ‘&’ can also be used differently to create references, which I call in my mind as ‘aliases’, but this is not shown in this example) I also play with a not so popular syntax to access a pointer’s sub-fields: (*myPointer).structField == myPointer-&gt;structField to teach you that the -&gt; is a short hand for dereferencing a pointer and accessing one of its fields. // // An exercise to play with a struct that stores anything using a void* field. // #include <stdio.h> #define TRUE 1 int TYPE_INT = 0; int TYPE_STRING = 1; int TYPE_BOOLEAN = 2; int TYPE_PERSON = 3; struct node { struct node* next; int type; void* value; }; struct person { char* name; int age; }; int main(int args, char **argv) { struct person aPerson; aPerson.name = "Angel"; aPerson.age = 35; // Define a linked list of objects. // We use that .type field to know what we're dealing // with on every iteration. On .value we store our values. struct node nodes[] = { { .next = &nodes[1], .type = TYPE_INT , .value=1 }, { .next = &nodes[2], .type = TYPE_STRING , .value="anyfing, anyfing!" }, { .next = &nodes[3], .type = TYPE_PERSON , .value=&aPerson }, { .next = NULL , .type = TYPE_BOOLEAN, .value=TRUE } }; // We iterate through the list for ( struct node *currentNode = &nodes[0]; currentNode; currentNode = currentNode->next) { int currentType = (*currentNode).type; if (currentType == TYPE_INT) { printf("%s: %dn", "- INTEGER", (*currentNode).value); // just playing with syntax, same as currentNode->value } else if (currentType == TYPE_STRING) { printf("%s: %sn", "- STRING", currentNode->value); } else if (currentType == TYPE_BOOLEAN) { printf("%s: %dn", "- BOOLEAN (true:1, false:0)", currentNode->value); } else if (currentType == TYPE_PERSON) { // since we're using void*, we end up with a pointer to struct person, which we *dereference // into a struct in the stack. struct person currentPerson = *(struct person*) currentNode->value; printf("%s: %s (%d)n","- TYPE_PERSON", currentPerson.name, currentPerson.age); } } return 0; } The output is this: - INTEGER: 1 - STRING: anyfing, anyfing! - TYPE_PERSON: Angel (35) - BOOLEAN (true:1, false:0): 1  # How to make a “foreach” function in JavaScript I thought this would be a simple exercise in case of having to interview someone for a JavaScript position. “How would you make your own ‘foreach’ in JavaScript” I came up with the following solution: // // collection: A list of objects. // onElementIterationCallback: The function to be called on every element iterated // taking the following parameters: foo(collection : [T], currentIndex : int) function foreach(collection, onElementIterationCallback) { for (var i in collection) { if (collection.hasOwnProperty(i)) { onElementIterationCallback(collection[i], i); } } }  This is how you’d use it: var sumOfAges = 0; var people = [ {name:"Angel", age:35}, {name:"Paulina", age:33}, {name:"Nicole", age:16}] foreach(people, function (person, currentOffset) { console.log("("+ currentOffset + ") iterating on " + person.name + ", age: " + person.age); sumOfAges += person.age; }); console.log(sumOfAges);  The expected output would be: (0) iterating on Angel, age: 35 (1) iterating on Paulina, age: 33 (2) iterating on Nicole, age: 16 84  Hope you enjoyed, just a simple exercise of lists, creativity and callbacks. # # Things to remember when compiling/linking C/C++ software by Angel Leon. March 17, 2015. ## Include Paths On the compilation phase, you will usually need to specify the different include paths so that the interfaces (.h, .hpp) which define structs, classes, constans, and functions can be found. With gcc and llvm include paths are passed with -I/path/to/includes, you can pass as many -I as you need. In Windows, cl.exe takes include paths with the following syntax: /I"c:\path\to\includes\ you can also pass as many as you need. Some software uses macro definition variables that should be passed during compile time to decide what code to include. ## Compilation flags These compilation-time variables are passed using -D, e.g. -DMYSOFTWARE_COMPILATION_VARIABLE -DDO_SOMETHING=1 DDISABLE_DEPRECATED_FUNCTIONS=0 These compilation time flags are by convention usually put into a single variable named CXXFLAGS, which is then passed to the compiler as a parameter for convenience when you’re building your compilation/make script. ## Object files When you compile your .c, or .cpp files, you will end up with object files. These files usually have .o extensions in Linux, in Windows they might be under .obj extensions. You can create an .o file for a single or for many source files. ## Static Library files When you have several .o files, you can put them together as a library, a static library. In Linux/Mac these static libraries are simply archive files, or .a files. In windows, static library files exist under the .lib extension. They are created like this in Linux/Mac: ar -cvq libctest.a ctest1.o ctest2.o ctest3.o libctest.a will contain ctest1.o,ctest2.o and ctest2.o They are created like this in Windows: LIB.EXE /OUT:MYLIB.LIB FILE1.OBJ FILE2.OBJ FILE3.OBJ When you are creating an executable that needs to make use of a library, if you use these static libraries, the size of your executable will be the sum of all the object files statically linked by the executable. The code is right there along the executable, it’s easier to distribute, but again, the size of the executable can be bigger than it needs to… why? because, sometimes, many of the .o files, or even the entire .a file you’re linking against might be a standard library that many other programs need. ## Shared Libraries (Dynamic Libraries) So shared or dynamic libraries were invented so that different programs or libraries would make external (shared) references to them, since they’re “shared” the symbols defined in them don’t need to be part of your executable or library, your executable contain symbols whose entry points or offset addresses might point to somewhere within themselves, but they will also have symbols whose entry points are expected to exist on shared libraries which need only be loaded once in a single portion of the operating shared memory, thus not just making the size of your executable as small as it needs to be, but you won’t need to load the library for every process/program that needs its symbols. On Linux shared files exist under the .so (shared object) file extension, on Mac .dylib (dynamic library), and in Windows they’re called .dll (dynamic link libraries) Another cool thing about dynamic libraries, is that they can be linked during runtime, not just compile time. An example of runtime dynamic libraries are browser plugins. In Linux .so files are created like this: gcc -Wall -fPIC -c *.c gcc -shared -Wl,-soname,libctest.so.1 -o libctest.so.1.0 *.o  • -Wall enables all warnings. • -c means don’t run the linker. • -fPIC means “Position Independent Code”, a requirement for shared libraries in Linux. • -shared makes the object file created shareable by different executables. • -Wl passes a comma separated list of arguments to the linker. • -soname means “shared object name” to use. In Mac .dylib files are created like this: clang -dynamiclib -o libtest.dylib file1.o file2.o -L/some/library/path -lname_of_library_without_lib_prefix In Windows .dll files are created like this: LINK.EXE /DLL /OUT:MYLIB.DLL FILE1.OBJ FILE2.OBJ FILE3OBJ ## Linking to existing libraries When linking your software you may be faced with a situation on which you want to link against several standard shared libraries. If all the libraries you need exist in a single folder, you can set the LD_LIBRARY_PATH to that folder. By common standard all shared libraries are prefixed with the word lib. If a library exists in LD_LIBRARY_PATH and you want to link against it, you don’t need to pass the entire path to the library, you simply pass -lname and you will link your executable to the symbols of libname.so which should be somewhere inside LD_LIBRARY_PATH. Tip: You should probably stay away from altering your LD_LIBRARY_PATH, if you do, make sure you keep its original value, and when you’re done restore it, as you might screw the build processes of other software in the system which might depend on what’s on the LD_LIBRARY_PATH. If you have some other libbar.so library on another folder outside LD_LIBRARY_PATH you can explictly pass the full path to that library /path/to/that/other/library/libbar.so, or you can specify the folder that contains it -L/path/to/that/other/library and then the short hand form -lbar. This latter option makes more sense if the second folder contains several other libraries. ## Useful tools Sometimes you may be dealing with issues like undefined symbol errors, and you may want to inspect what symbols (functions) are defined in your library. On Mac there’s otool, on Linux/Mac there’s nm, on Windows there’s depends.exe (a GUI tool that can be used to see both dependencies and the symbol’s tables. Taking a look at the “Entry Point” column will help you understand clearly the difference between symbols linking to a shared library vs symbols linking statically to the same library) ### Useful command options See shared library dependencies on Mac with otool otool -L libjlibtorrent.dylib libjlibtorrent.dylib: libjlibtorrent.dylib (compatibility version 0.0.0, current version 0.0.0) /usr/lib/libc++.1.dylib (compatibility version 1.0.0, current version 120.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1213.0.0)  See shared symbols with nm (Linux/Mac) With nm, you can see the symbol’s name list. Familiarize yourself with the meaning of the symbol types: * T (text section symbol) * U (undefined – useful for those undefined symbol error), * I (indirect symbol). * If the symbol is local (non-external) the symbol type is presented in lowercase letters, for example a lowercase u represents an undefined reference to a private external in another module in the same library. nm‘s documentation says that if you’re working on Mac and you see that the symbol is preceeded by + or - it means it’s an ObjectiveC method, if you’re familiar with ObjectiveC you will know that + is for class methods and - is for instance methods, but in practice it seems to be a bit more explicit and you will often see objc or OBJC prefixed to those methods. nm is best used along with grep 😉 Find all Undefined symbols nm -u libMacOSXUtilsLeopard.jnilib _CFRelease _LSSharedFileListCopySnapshot _LSSharedFileListCreate _LSSharedFileListInsertItemURL _LSSharedFileListItemRemove _LSSharedFileListItemResolve _NSFullUserName _OBJC_CLASS_$_NSArray
_OBJC_CLASS_$_NSAutoreleasePool _OBJC_CLASS_$_NSDictionary
_OBJC_CLASS_$_NSMutableArray _OBJC_CLASS_$_NSMutableDictionary
_OBJC_CLASS_$_NSString _OBJC_CLASS_$_NSURL
__Block_copy
__NSConcreteGlobalBlock