devxlogo

We are an award-winning tech entrepreneurship website where trusted experts can provide value globally.

Since 1998, DevX has helped people start businesses, build websites, and provide enterprise technology to people globally. Interviewing the likes of Microsoft’s co-founder, Steve Ballmer, the publication brings comprehensive, reliable, and accessible insights to the Internet.

devxlogo

Trusted for 26 years

Over 30K Articles

1M+ Readers

Expert-reviewed

10K+ Tech Terms

As seen in:

microsoft logo
business_insider_logo
wired_logo
berkley
arstechnica_logo
hackernoon

The Latest

data scientist

Microsoft XNA: Ready for Prime Time?

No longer constrained to enterprise systems, database-driven applications or web service layers, with XNA, .NET developers can now spread their digital wings and let their pixelized imagination run wild. Their

The rapid growth of the gig economy has produced massive changes in the way peer-to-peer enterprises around the world do business.

Tech Trends in the Gig Economy

As our modern world continues to evolve, the relationship between technology and business is adapting constantly. The rapid growth of the gig economy has produced massive changes in the way

Understanding FULLTEXT Searches

In MySQL, there is a provision to search based on natural mode. Let us consider the following example to understand this in detail. Creation of the table: CREATE TABLE ‘PROP_TBL’

How to Use the Spring Example API

First, define a probe (an instance of the entity class): User user = new User();user.setName(“Ana”);user.setEmail(“[email protected]”); Next create a probe: Example userExample = Example.of(user); Next, define a repository that extends QueryByExampleExecutor

How to log transactions details in Spring Boot

To log transactions details in a Spring Boot application simply add the following settings in application.properties: logging.level.ROOT=INFO logging.level.org.springframework.orm.jpa=DEBUG logging.level.org.springframework.transaction=DEBUG logging.level.org.hibernate.engine.transaction.internal.TransactionImpl=DEBUG

How to log HikariCP details in Spring Boot

To log HikariCP details simply add in application.properties the following settings: logging.level.com.zaxxer.hikari.HikariConfig=DEBUG logging.level.com.zaxxer.hikari=DEBUG  If you need a deeper level of details then replace DEBUG with TRACE.

Explore More Methods in the java.lang.Math Package

The java.lang.Math package is very powerful. Understand more methods in this package that are related to the Euler’s number named e. public class MathMethods{ public static void main(String args[]) { MathMethods

Retrieving a file from a jar file

JAR file in Java is a compressed format and is used for packaging of the deliverables. At times, you may want to manipulate this file.Below example indicates a scenario for the same. import java.util.jar.*;import java.io.*; public class RetrievingJarEntry{   public static void main(String args[])   {      RetrievingJarEntry retrievingJarEntry = new RetrievingJarEntry();      retrievingJarEntry.proceed();   }      private void proceed()   {      String sourceJarFile = “files/contacts.jar”;      String sourceFile = “2.txt”;      String destFile = “files/new2.txt”;      try{                  JarFile jarFile = new JarFile(sourceJarFile);         JarEntry jarEntry = jarFile.getJarEntry(sourceFile);         System.out.println(“Found entry: ” + jarEntry);         if ( jarEntry != null)         {            //Getting the jarEntry into the inputStream            InputStream inputStream = jarFile.getInputStream(jarEntry);             //Creating a output stream to a new file of our choice            FileOutputStream fileOutputStream = new java.io.FileOutputStream(destFile);            System.out.println(“Attempting to create file: ” + destFile);            while (inputStream.available()  0)             {                 fileOutputStream.write(inputStream.read());            }            System.out.println(“Created file: ” + destFile);            fileOutputStream.close();            inputStream.close();         }      }catch(IOException ioe)      {         System.out.println(“Exception: ” + ioe);      }   }} /* Expected output: [root@mypc]# java RetrievingJarEntryFound entry: 2.txtAttempting to create file: files/new2.txtCreated file: files/new2.txt */ //Please note: You have to create a folder with name files and a jar file contacts.jar which has files 1.txt, 2.txt and 3.txt

Navigating an enum

Enums are predefined place holders in Java. Knowing the contents of an enum will be handy in many instancesLet us look at how to navigate the elements of an enum public class NavigatingAnEnum{   public static void main(String args[])   {      NavigatingAnEnum navigatingAnEnum = new NavigatingAnEnum();      navigatingAnEnum.proceed();   }      enum Criteria {      LOW,      MEDIUM,      HIGH   }      private void proceed()   {      System.out.println(“Elements of the enum Criteria…”);      for (Criteria criteria : Criteria.values()) {         System.out.println(criteria);      }   }} /* Expected output: [root@mypc]# java NavigatingAnEnumElements of the enum Criteria…LOWMEDIUMHIGH */

Understandng java.net.PasswordAuthentication

PasswordAuthentication holds the data that will be used by the Authenticator. The username and password are stored in the PasswordAuthentication object. The methods getUserName() and getPassword() are made available that return the userName and password respectively. import java.net.PasswordAuthentication; public class UnderstandingPasswordAuthentication{   public static void main(String args[])   {      UnderstandingPasswordAuthentication understandingPasswordAuthentication = new UnderstandingPasswordAuthentication();      understandingPasswordAuthentication.proceed();   }      private void proceed()   {      //Initializing the user name      String userName = “devUser”;      //Initializing the password – This is a char array since the PasswordAuthentication supports this argument      char[] password = {‘d’,’e’,’v’,’U’,’s’,’e’,’r’};            PasswordAuthentication passwordAuthentication = new PasswordAuthentication(userName, password);      System.out.println(“Details being retrieved from PasswordAuthentication object post initializing”);      System.out.println(“UserName: ” + passwordAuthentication.getUserName());      //The below getPassword actually returns the reference to the password as per the Java API documentation.      System.out.println(“Password: ” + passwordAuthentication.getPassword());      //You can get the password in normal string       System.out.println(“Password: ” + String.copyValueOf(passwordAuthentication.getPassword()));   }} /* Expected output: [root@mypc]# java UnderstandingPasswordAuthenticationDetails being retrieved from PasswordAuthentication object post initializingUserName: devUserPassword: [C@15db9742Password: devUser */

Understandng HashMap.getOrDefault() method

HashMap is a class which which facilitates storing data in the form a key value pair. One thing to note of HashMap is that this is not synchronized and has to be used with caution in multi threaded environment. We may find cases where the key is not present and we maybe trying to perform operations using the key. Following method will help us in using a default value when the key in question is not available in the avaialble set of data. import java.util.HashMap; public class UnderstandingHashmapGetOrDefault{   public static void main(String args[])   {      UnderstandingHashmapGetOrDefault understandingHashmapGetOrDefault = new UnderstandingHashmapGetOrDefault();      understandingHashmapGetOrDefault.proceed();   }      private void proceed()   {      HashMap hashMap = initHashMap();      int currencyId = 12;      System.out.println(“Value of currency ” + currencyId + ” is ” + hashMap.getOrDefault(currencyId, “Unknown”));      currencyId = 100;      System.out.println(“Value of currency ” + currencyId + ” is ” + hashMap.getOrDefault(currencyId, “Unknown”));   }    private HashMap initHashMap() {      //HashMap declaration with 2 arguments (Integer and String)      HashMap hashMapCurrency = new HashMap();      //Adding predefined contents to the HashMap      hashMapCurrency.put(10, “Ten Dollars”);      hashMapCurrency.put(20, “Twenty Dollars”);      hashMapCurrency.put(50, “Fifty Dollars”);      hashMapCurrency.put(100, “Hundred Dollars”);      hashMapCurrency.put(200, “Two Hundred Dollars”);      return hashMapCurrency;   }   } /* Expected output: [root@mypc]# java UnderstandingHashmapGetOrDefaultValue of currency 12 is UnknownValue of currency 100 is Hundred Dollars */

Understandng toExactInt method in java.lang.Math package

java.lang.Math has numerous methods and our interest here is toIntExact() method.Consider the following example public class MathExact{   public static void main(String args[])   {      MathExact mathExact = new MathExact();      mathExact.proceed();   }      private void proceed()   {      long l = 100000000;      int i = (int) l;       System.out.println(“i: ” + i);            System.out.println(“Math.toIntExact(“+l+”);: ” + Math.toIntExact(l));   }} /* Expected output: [root@mypc]# java MathExacti: 100000000Math.toIntExact(100000000);: 100000000 */

Get the First Day of the Current Month

To get the first date of the current month, you could a query similar to the following: SELECT CONVERT(VARCHAR(25),DATEADD(DAY,-(DAY(GETDATE())) +1, GETDATE()), 105) Day1;

Find error log location

It is quite easy to find the error log location through a quick query such as : SELECT SERVERPROPERTY(‘ErrorLogFileName’) AS ‘Error log file location’   This shows where your Error log file is stored

DBCC SHRINKDATABASE

DBCC SHRINKDATABASE The command shrinks the size of the data and log files in a database. Here is a small example: DBCC SHRINKDATABASE (Database_Name, 10);  –This allows for 10 percent free space in the database.

Monitor Log space in SQL Server quickly

You can use the following command to monitor all your databases’ log file’s free space DBCC SQLPERF (‘LOGSPACE’)

How to Trigger a Synchronous GET Request

For triggering a synchronous GET request we can rely on HTTP Client API as follows: HttpClient client = HttpClient.newHttpClient();HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(“https://reqres.in/api/users/2”)) .build();HttpResponse response = client.send(request, BodyHandlers.ofString());

Check for finite numbers in Python

Use the math module???s isfinite method to determine if a value is finite or not.  If it is not a number, the function returns false.  See below for an example:math.isfinite(10) returns True

How to detect Python version at runtime

At times, we want to run our code only if the version of Python engine is above a certain version. See below for sample code. Import sysversion = sys.version

Return multiple values from a function in python

Python can return multiple values at a time. See below for a simple example. def multipleValueFunc():     z = 11     b = 22    return z, b  j,k  = multipleValueFunc () print(j, k) 

Reverse a string in Python

Its pretty ease to reverse a string in Python. ???Devx Jan???[::-1]  gives ???naJ xveD???

Simplifying Null Check in Java

To avoid null exceptions, we usually validate against null and emptiness as shown: if(object != null && !object.equals(“”)) {} We can simplify this as below: if(!””.equals(object)){}

Using Find_in_Set in MySQL

MySQL has various ways to search for or lookup a given string. One such powerful mechanism is by using FIND_IN_SET. This function enables a lookup for a given string in

Get All the Tables with a Count of Their Records

Get all the tables with a count of their records with the following query: CREATE TABLE #Temp ( TableName VARCHAR(MAX), Rows INT ); EXEC sp_MSForEachTable @command1 = ‘INSERT INTO #Temp(TableName,

Use the Namespace Alias for Better Readability

For better readability, C# provides a way to shorten the namespaces with an alias. Please see below for an example: using ExcelInterop = Microsoft.Office.Interop.Excel;var excelInteropApplication = new ExcelInterop.Application();

How to Compute the Fibonacci Number Recursively

The following code shows you how to compute the n Fibonacci number recursively: int fibonacci(int k) { if (k return k; } return fibonacci(k – 2) + fibonacci(k – 1);}

Using AUTO_INCREMENT in MySQL

We know that AUTO_INCREMENT is used to have a sequential value auto incremented by itself for the records that we insert. CREATE TABLE AUTO_TABLE (ID INT NOT NULL AUTO_INCREMENT,PRIMARY KEY