Skip to main content

Posts

React useState returns distinct state values per call

    The React doc states clearly that useState hook returns distinct values, but I still see some devs confused about whether they are working with a shared/global state, when useState is placed inside a custom hook   I put together a very simple codepen to illustrate that each call to the use hook function does indeed get you a distinct piece of state, which is nice! If you really want shared state, hello Redux (or ahem, Context) ! https://codepen.io/binodpanta/pen/vYWdxMd Have fun with React! ⌣

Two cool ways to center content in CSS

You may have seen this question, center a div, or whatever, in interviews or other places. I am sure there are other approaches than I am sharing here, but I found these two cool ideas from multiple places (see refs at the end). These are not my original ideas so I will be sure to share where I learned these from:   Using display:flex  Make sure you know how flex works, but to do centering with flex, it's ridiculously simple: div .container { display : flex ; justify-content : center ; /* horizontal alignment */ align-items : center ; /* vertical alignment */ flex-direction : column ; /* since we are doing a vertical column */ padding : 1rem 3rem ; /* not related to centering */ }  Now everything inside <div class="container"> </div> will be centered in both directions! Using display:grid  You are so going to thank for me this one, you are welcome. This one is so simple it does not even need an explanation does it?   div .conta...

CSS: em vs rem font sizes

 When do you use em and when do you use rem? If you have ever asked this, you are like me :) So welcome. Basically, to save you time here it is: - If you want your font-size relative to the container's font-size, use em - If you want your font-size relative to the 'root' (or html) element's font-size, use rem! If you just stop reading now that might be sufficient, but if you are more curious, go on. Example companion codepen: https://codepen.io/binodpanta/pen/RwLWRra Basically your page should ideally always have a default font-size specified for the root, such as  :root { font-size: 1em; } This typically becomes 16px default for the base font size. Now, if you use rems in your elements' styles you get a consistent scaling wrt this number! so if you do div.someclass { font-size: 0.5rem; } you are going to always get a nice scaled font size regardless of screen size. So all your fonts will scale relatively throughout the app!  If you had used 0.5em, your calculated ...

How to use function closure to capture common arguments in python

Sometimes you need a function that already 'captures' some information you don't want to repeat when calling it. For example, logging may require you to pass in a lot of contextual information for each call. Instead you can capture the common/unchanging contextual information in a function (using its clsoosure) then call the resulting function with less args (only those that are changing in each call site)   class AClass:   def __init__(self):     self.make_log_msg = lambda m: f"a={self.a}, b={self.b}, message={m}"  def do_something(self):     doStuff();     logger.info(self.make_log_msg('test message')) In the absence of the make_log_msg() function you would need to pass all of a,b,c into every logging function call as in self.make_log_msg(self.a, self.b, message) .  This is possible because make_log_msg returns a function (lambda function in this case) that already captures the values self.a and self.b in its closure at the t...

Remote debugging of python code in Visual Studio Code

Remote debugging with python and visual studio Code In terminal install debugpy into your environment with something like     python -m pip install debugpy Create a visual studio launch configuration and add following to it following (or just use vs code create configuraiton button to easily create it choose type Python and select from the list, 'Remote attach') { "name" : "Python: Remote Attach" , "type" : "python" , "request" : "attach" , "port" : 5678 , "host" : "localhost" , "pathMappings" : [{ "localRoot" : "${workspaceFolder}" , "remoteRoot" : "." }] }, Run this in the command line to start a debugging server with your script runner python3 -m debugpy --listen 1.2.3.4:5678 --wait-for-client Yourscript.py Now run the launch configuration from vs code to attach to this debugger

How to write and test Node.JS code that performs mutiple async tasks

This is currently WIP, I will fill in more details but it's a good starting version that is still hopefully useful to the reader... Recently I worked on a project that involved scheduling a number of tasks in parallel in Node.js. Running mutiple tasks I used the await-the library to do this. https://github.com/olono/await-the/blob/master/lib/result.js There are multiple ways to solve this kind of problem. Mainly you have to understand the Node.js is a single threaded environment (See Event loop) and how callbacks operate with a library like async or await-the. Basically, here idea was that you write a function that has a callback as its last argument ```   const doTask = async (arg1, callback) {    const results = await doStuffWith(arg1) ;    callback(results); } ``` Then perform this action on multiple inputs in parallel such as by using the excellent async.mapLimit function if you want to limit how many tasks in parallel you want to to...

Sending Form data to a backend REST API using Axios

This need is incredibly common and useful, and hopefully will save you a lot of time when doing server side calls from your UI application (or even non UI clients like NodeJS applications) Example here is to send a POST request to an endoint /api/item/new (which will create a new item in the database). We will just assume tbhe backend is already setup (it's not relevant to this article). All we need to know is that we can do a POST /api/item/new and send it form data with two pieces of info     name, filter So, if you have a node.js application (I was using Vue-cli generated project, but it does not matter), install 'axios' (a most popular tool to make server calls these days) npm i axios --save OR yarn add axios (my preferred method) Now, in your service JS file (which is generally when I keep all my api calls) do something like this createNew ( name , filter ) { let formData = new FormData (); formData . append ( "name" , ...

Setting up a nice dev/prod workflow for Vue-CLI frontend apps using Spring backend

My current recipe which works not bad is setup spring at localhost:8082, vue-cli app on localhost:8080 setup proxy in devServer for webpack to point all /api calls to localhost:8082. So now any calls made from vue application to /api will be sent to the spring application at /api setup spring api endpoints at /api add a 'buildx' npm task to do the usual "vue-cli build && copy " over to spring src/main/resources/static area, mine usually looks like this in package.json "buildx" : "vue-cli-service build && copyfiles -u 1 dist/* dist/**/* ../build/resources/main/public && copyfiles -u 1 dist/* dist/**/* ../src/main/resources/public -V" ,   I usually copy to both build/ and src area, since build makes restart instantliy work in spring side, and src/ area makes bundle available in spring jar file created using bootJar task, for deployment setup devtools on spring to autorestart I can dev/test using jus...

Authenticating Spring Boot based application against secure LDAP/AD server

Authenticating against an Active Directory setup is quite common in organizations using Spring Boot / Spring Security can be a pain if you don't know exactly the requirements. I needed to add auth in my web app and secure some but not all endpoints of the application. My story was, I needed Spring security to authenticate against my company LDAP server which uses Active Directory I started by using the standard LDAP guide such as this which are all over the Internet, https://spring.io/guides/gs/authenticating-ldap/ and was able to setup the basic framework However, only test level LDAP auth was working for me, when I tried to auth against the company LDAP secure server, I had to resolve a few issues After 1 week and working with several devs at the company, I finally found why it was not working and the fix was easy Since I spent a week or so resolving this, I wanted to write this up in case someone finds this useful. Here is what I did (it was easy until the fourth ...

Use Service objects along with your controllers in Spring boot to cleanup code and testing

If you have Spring controller that uses repository objects, it can become a bit messy to write tests with mocks that have to mock various repository object methods like save() etc. Instead, you can use Here is an example controller that uses repository objects: @RestController public class StateManagerController { public StateManagerController(XRepository aRepository, YRespository yRepo) {   } public void aMethod() { // use xRepo, yRepo : e.g., xRepo.save() , yRepo.delete() etc. } ... } To test methods of this controller that use the repository objects, you will likely have to mock each repository collaborator object. Then you can get into lots of mocking details that make your tests ugly. Instead, I find that using the following pattern greatly simplifies both your code and tests. It's very simple but works great. 1. In your controller, only inject/depend on @Service objects. Don't use repository objects directly 2. Test your con...

Using actuator in Spring boot to analyze and monitor your application

Intro Spring boot offers a wonderful module called the actuator. It is somewhat similar to the tools offered by Rails or other frameworks to get a better view of your application. Basically when you enable it, you can browse to a url which by default is at /actuator (but can be configured), where you will find very interesting pieces of information about your Spring boot application. For example, if you built a MVC webapp where you wrote a number of @Controller or @RestController classes, then going to /actuator/mappings will list your endpoints along with which controller method serve which endpoint etc. But there is a whole lot more in actuator you will find useful. In this article, I will show you how to use it in your application, and also how to only enable it in your development profile. I would assume that you don't want soething like this enabled in your production deployment. We will use Spring profiles for this. Setup I am assuming you have a working Spri...

Using custom conditional logic to enable/disable Spring components

If you have a Spring component and you don't want it to load, you can use Spring's predefined conditionals as much as possible. For example, @Component   @ConditionalOnNotWebApplication   public class SchedulerEntryPoint implements ApplicationRunner { ...  } This will not load your component when running in non web application mode. Such as you may want to start the application but without any of the web framework using SpringApplicationBuilder. But sometimes you want to use custom conditions. It's pretty easy to do so, just use something like this @Component @Conditional (SchedulerCheck. class ) public class SchedulerEntryPoint implements ApplicationRunner { public static class SchedulerCheck implements Condition { @Override public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) { return System. getProperty ( "scheduler" ) != ...

Autoreloading your UI pages in the browser with each build, while developing web apps in Spring boot

I had been working on a simple gradle project where I use Spring boot to develop the backend and REST API using Spring data REST and Frontend using Vue.js + spring boot thymeleaf. Spring boot's controllers will handle the routing and all frontend work can be done in the html pages. I will post these other pieces separately. If you have done this, you may know that you can load your .html pages using Spring Boot's Thymeleaf rendering engine which comes configured by default. As long as you place them under src/main/resources/templates (default location for renderable templates) But once that page is rendered you can use any frontend framework on it. In my case, I am using Vue.js as the frontend framework (more on this in other posts) So if you have a spring boot project setup, you can install the spring boot devtools to your project. Once you do that, by default it will reload your spring boot application whenever your source code changes. However, normally your htm...

A simple recipe to use grunt watch to setup simple autorun workflow while developing any type of project

It is great to have a tool that watches changes and reruns code (like tests or server code etc) as you are saving your files. This idea here of course works great with any Node project but hey, even if you are not coding in Node (or even in language other than JS), you can still use this idea, it's very generic and will work for just about any type of project if you just set this basic setup once. While there are many approaches to doing this depending on the project type (like webpack's watch which is super-powerful for web projects, nodemon  for server restart cases, chokidar etc), my current favorite for a generic  method that will work with any type of project is based on grunt-watch. So read on! I setup this simple repository with a simple readme guide on how to do this. https://github.com/binodpanta/node-examples/tree/master/gruntwatch I think it will save you a lot of time when working on NodeJS projects. Even if you don't use Grunt for your ac...

Using a Java stream (Java 8+) to convert List collection into primitive data type arrays

You need to convert an ArrayList<Integer> to int, similar case for others like Long > long. Prior to Java 8, you would have to try something like int[] myarray =   ll.toArray(new Integer[size]); But this will fail to compile! So it forces you to use Integer[] instead of int[]. However, you may have client code that expect int[] and not Integer[]. So the only other way would be to iterate over the list and convert to array the traditional way by adding element by element. Fine, but not elegant. I discovered that the stream based method above works even for primitive data types like int. So converting an array list of integers to an array is quite straightforward with a mapToInt () intermediate Intstream (or LongStream for long) as follows ArrayList<Integer>  ll  =  new  ArrayList<Integer>();       int[] myarray =  ll .stream().mapToInt( c  ->  c ).toArray(); The c-...

How to interact with pre-deployed Ethereum Smart contracts in the Mist browser

How to view/watch pre-deployed Smart contracts in Mist Check out this git repo https://github.com/binodpanta/ethereum-examples/tree/master/predeployed-contracts-mist Here I have described how you can load up pre-deployed Smart contracts in the Mist browser, if you have deployed them using Truffle or other method This is useful if you want to view your already deployed contracts. Sometimes you don't want to have to re-run contract code from Mist if you have already used truffle to deploy the contract

Generating JavaScript mapping functions with custom arguments

I recently learned this trick which I am sure is not new, but I sort of discovered on my own The issue is you want your mapping function to be customizable, but the standard javascript mapping function only takes one arg, the value out of the thing being mapped so the trick is to generate your mapping function with all your arguments in the closure, meaning you write a function that returns the mapping function. your function will take all your args // here 'band' is the arg that we want to use to generate a custom mapping function var mapFuncGenerator = function(band) {                         return function(rawdata) {                             var ts = rawdata.ts;                             var compositeValue = rawdata[band][4];            ...

Bash shell: Reading information from files and adding dynamically generated content to files

Simply put, using the bash for loop and other standard commands it can be a quite powerful method to write custom content to files/databases etc For example #!/bin/bash list=$(cat somefile | grep jar | sed 's/aaa/bbb/g') # add each of the paths as a system scope dependency to the pom counter=1 for OUTPUT in $list do         pathvar=/$OUTPUT         echo "          <dependency>             <groupId>x</groupId>             <artifactId>$counter</artifactId>             <version>1.0</version>             <systemPath>$pathvar</systemPath>             <scope>system</scope>          </dependency>         " >> pom.xml  ...

Using asyncawait library in NodeJS to simplify async code

Often you find yourself using async code and handling delayed response in JavaScript There are two well known approaches that are often used * Callbacks. This is the conventional way, and is frankly annoying. I won't say much more about these. * Promises. Of course they are all the rage right now. They are lovely. doSomething().then(doAnother()) etc. The only issue is that when processing promise code you have to deal with creating and returns functions and callback-like syntax still, and soon code starts to look busy again So, if you are in NodeJS, you have a few options to use async..await pattern. Here I use the asycnawait library. Other options are co, async etc. The idea is quite simple. You write a function inside async(). Within the function, write code as if it's synchronous, and use await() to resolve promises. Example           let yourFunction = function() {               var result = await(functionT...

Using m4 macro processor to process templates via shell scripts

I recently had to develop a bash script in order to automate the submission of a job The job submission script could be run like this someTextOutput | thatCommand So 'thatCommand' can be piped input directly. My issue was that 'someTextOutput' for me needed to be template replaced with user provided inputs. For example I wanted to do this % aCommand var1 var2 This should replace values of tokens in a template file with var1 and var2 and the resulting output should become 'someTextOutput' I discovered the m4 template processor tool, and here was my solution, or close to it. Cool! #!/bin/bash # some input handling code ... # now send over template processed output to the target command cat /tmp/templateFile.txt | m4 -Dvar1="$1" -Dvar2="$2" | thatCommand I can use this in so many applications, all without having to resort to other tools/scripts when I don't need to. Happy scripting!