Programs & Examples On #Systems programming

System programming is the activity of computer programming system software. The primary distinguishing characteristic of systems programming when compared to application programming is that application programming aims to produce software which provides services to the user, whereas systems programming aims to produce software which provides services to the computer hardware.

How to upload files to server using JSP/Servlet?

I am Using common Servlet for every Html Form whether it has attachments or not. This Servlet returns a TreeMap where the keys are jsp name Parameters and values are User Inputs and saves all attachments in fixed directory and later you rename the directory of your choice.Here Connections is our custom interface having connection object. I think this will help you

public class ServletCommonfunctions extends HttpServlet implements
        Connections {

    private static final long serialVersionUID = 1L;

    public ServletCommonfunctions() {}

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException,
            IOException {}

    public SortedMap<String, String> savefilesindirectory(
            HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        // Map<String, String> key_values = Collections.synchronizedMap( new
        // TreeMap<String, String>());
        SortedMap<String, String> key_values = new TreeMap<String, String>();
        String dist = null, fact = null;
        PrintWriter out = response.getWriter();
        File file;
        String filePath = "E:\\FSPATH1\\2KL06CS048\\";
        System.out.println("Directory Created   ????????????"
            + new File(filePath).mkdir());
        int maxFileSize = 5000 * 1024;
        int maxMemSize = 5000 * 1024;
        // Verify the content type
        String contentType = request.getContentType();
        if ((contentType.indexOf("multipart/form-data") >= 0)) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            factory.setRepository(new File(filePath));
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);
            try {
                // Parse the request to get file items.
                @SuppressWarnings("unchecked")
                List<FileItem> fileItems = upload.parseRequest(request);
                // Process the uploaded file items
                Iterator<FileItem> i = fileItems.iterator();
                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    if (!fi.isFormField()) {
                        // Get the uploaded file parameters
                        String fileName = fi.getName();
                        // Write the file
                        if (fileName.lastIndexOf("\\") >= 0) {
                            file = new File(filePath
                                + fileName.substring(fileName
                                        .lastIndexOf("\\")));
                        } else {
                            file = new File(filePath
                                + fileName.substring(fileName
                                        .lastIndexOf("\\") + 1));
                        }
                        fi.write(file);
                    } else {
                        key_values.put(fi.getFieldName(), fi.getString());
                    }
                }
            } catch (Exception ex) {
                System.out.println(ex);
            }
        }
        return key_values;
    }
}

Guid is all 0's (zeros)?

Try doing:

Guid foo = Guid.NewGuid();

How do I represent a time only value in .NET?

You can use timespan

TimeSpan timeSpan = new TimeSpan(2, 14, 18);
Console.WriteLine(timeSpan.ToString());     // Displays "02:14:18".

[Edit]
Considering the other answers and the edit to the question, I would still use TimeSpan. No point in creating a new structure where an existing one from the framework suffice.
On these lines you would end up duplicating many native data types.

PostgreSQL: How to change PostgreSQL user password?

This was the first result on google, when I was looking how to rename a user, so:

ALTER USER <username> WITH PASSWORD '<new_password>';  -- change password
ALTER USER <old_username> RENAME TO <new_username>;    -- rename user

A couple of other commands helpful for user management:

CREATE USER <username> PASSWORD '<password>' IN GROUP <group>;
DROP USER <username>;

Move user to another group

ALTER GROUP <old_group> DROP USER <username>;
ALTER GROUP <new_group> ADD USER <username>;

Identify duplicates in a List

Compact generified version of the top answer, also added empty check and preallocated Set size:

public static final <T> Set<T> findDuplicates(final List<T> listWhichMayHaveDuplicates) {
    final Set<T> duplicates = new HashSet<>();
    final int listSize = listWhichMayHaveDuplicates.size();
    if (listSize > 0) {
      final Set<T> tempSet = new HashSet<>(listSize);
      for (final T element : listWhichMayHaveDuplicates) {
        if (!tempSet.add(element)) {
          duplicates.add(element);
        }
      }
    }
    return duplicates;
  }

How to force Chrome browser to reload .css file while debugging in Visual Studio?

I know it's an old question, but if anyone is still looking how to reload just a single external css/js file, the easiest way now in Chrome is:

  1. Go to Network tab in DevTools
  2. Right click on the resource and select Replay XHR to repeat the request

Make sure that the Disable cache option is selected to force the reload.

Using CSS how to change only the 2nd column of a table

You can use the :nth-child pseudo class like this:

.countTable table table td:nth-child(2)

Note though, this won't work in older browsers (or IE), you'll need to give the cells a class or use javascript in that case.

Entity Framework is Too Slow. What are my options?

If you're purely fetching data, it's a big help to performance when you tell EF to not keep track of the entities it fetches. Do this by using MergeOption.NoTracking. EF will just generate the query, execute it and deserialize the results to objects, but will not attempt to keep track of entity changes or anything of that nature. If a query is simple (doesn't spend much time waiting on the database to return), I've found that setting it to NoTracking can double query performance.

See this MSDN article on the MergeOption enum:

Identity Resolution, State Management, and Change Tracking

This seems to be a good article on EF performance:

Performance and the Entity Framework

Detect if PHP session exists

The original code is from Sabry Suleiman.

Made it a bit prettier:

function is_session_started() {

    if ( php_sapi_name() === 'cli' )
        return false;

    return version_compare( phpversion(), '5.4.0', '>=' )
        ? session_status() === PHP_SESSION_ACTIVE
        : session_id() !== '';
}

First condition checks the Server API in use. If Command Line Interface is used, the function returns false.

Then we return the boolean result depending on the PHP version in use.

In ancient history you simply needed to check session_id(). If it's an empty string, then session is not started. Otherwise it is.

Since 5.4 to at least the current 8.0 the norm is to check session_status(). If it's not PHP_SESSION_ACTIVE, then either the session isn't started yet (PHP_SESSION_NONE) or sessions are not available altogether (PHP_SESSION_DISABLED).

Calling a Sub in VBA

For anyone still coming to this post, the other option is to simply omit the parentheses:

Sub SomeOtherSub(Stattyp As String)
    'Daty and the other variables are defined here

    CatSubProduktAreakum Stattyp, Daty + UBound(SubCategories) + 2

End Sub

The Call keywords is only really in VBA for backwards compatibilty and isn't actually required.

If however, you decide to use the Call keyword, then you have to change your syntax to suit.

'// With Call
Call Foo(Bar)

'// Without Call
Foo Bar

Both will do exactly the same thing.


That being said, there may be instances to watch out for where using parentheses unnecessarily will cause things to be evaluated where you didn't intend them to be (as parentheses do this in VBA) so with that in mind the better option is probably to omit the Call keyword and the parentheses

set default schema for a sql query

A quick google pointed me to this page. It explains that from sql server 2005 onwards you can set the default schema of a user with the ALTER USER statement. Unfortunately, that means that you change it permanently, so if you need to switch between schemas, you would need to set it every time you execute a stored procedure or a batch of statements. Alternatively, you could use the technique described here.

If you are using sql server 2000 or older this page explains that users and schemas are then equivalent. If you don't prepend your table name with a schema\user, sql server will first look at the tables owned by the current user and then the ones owned by the dbo to resolve the table name. It seems that for all other tables you must prepend the schema\user.

What is the difference between concurrent programming and parallel programming?

Different people talk about different kinds of concurrency and parallelism in many different specific cases, so some abstractions to cover their common nature are needed.

The basic abstraction is done in computer science, where both concurrency and parallelism are attributed to the properties of programs. Here, programs are formalized descriptions of computing. Such programs need not to be in any particular language or encoding, which is implementation-specific. The existence of API/ABI/ISA/OS is irrelevant to such level of abstraction. Surely one will need more detailed implementation-specific knowledge (like threading model) to do concrete programming works, the spirit behind the basic abstraction is not changed.

A second important fact is, as general properties, concurrency and parallelism can coexist in many different abstractions.

For the general distinction, see the relevant answer for the basic view of concurrency v. parallelism. (There are also some links containing some additional sources.)

Concurrent programming and parallel programming are techniques to implement such general properties with some systems which expose programmability. The systems are usually programming languages and their implementations.

A programming language may expose the intended properties by built-in semantic rules. In most cases, such rules specify the evaluations of specific language structures (e.g. expressions) making the computation involved effectively concurrent or parallel. (More specifically, the computational effects implied by the evaluations can perfectly reflect these properties.) However, concurrent/parallel language semantics are essentially complex and they are not necessary to practical works (to implement efficient concurrent/parallel algorithms as the solutions of realistic problems). So, most traditional languages take a more conservative and simpler approach: assuming the semantics of evaluation totally sequential and serial, then providing optional primitives to allow some of the computations being concurrent and parallel. These primitives can be keywords or procedural constructs ("functions") supported by the language. They are implemented based on the interaction with hosted environments (OS, or "bare metal" hardware interface), usually opaque (not able to be derived using the language portably) to the language. Thus, in this particular kind of high-level abstractions seen by the programmers, nothing is concurrent/parallel besides these "magic" primitives and programs relying on these primitives; the programmers can then enjoy less error-prone experience of programming when concurrency/parallelism properties are not so interested.

Although primitives abstract the complex away in the most high-level abstractions, the implementations still have the extra complexity not exposed by the language feature. So, some mid-level abstractions are needed. One typical example is threading. Threading allows one or more thread of execution (or simply thread; sometimes it is also called a process, which is not necessarily the concept of a task scheduled in an OS) supported by the language implementation (the runtime). Threads are usually preemptively scheduled by the runtime, so a thread needs to know nothing about other threads. Thus, threads are natural to implement parallelism as long as they share nothing (the critical resources): just decompose computations in different threads, once the underlying implementation allows the overlapping of the computation resources during the execution, it works. Threads are also subject to concurrent accesses of shared resources: just access resources in any order meets the minimal constraints required by the algorithm, and the implementation will eventually determine when to access. In such cases, some synchronization operations may be necessary. Some languages treat threading and synchronization operations as parts of the high-level abstraction and expose them as primitives, while some other languages encourage only relatively more high-level primitives (like futures/promises) instead.

Under the level of language-specific threads, there come multitasking of the underlying hosting environment (typically, an OS). OS-level preemptive multitasking are used to implement (preemptive) multithreading. In some environments like Windows NT, the basic scheduling units (the tasks) are also "threads". To differentiate them with userspace implementation of threads mentioned above, they are called kernel threads, where "kernel" means the kernel of the OS (however, strictly speaking, this is not quite true for Windows NT; the "real" kernel is the NT executive). Kernel threads are not always 1:1 mapped to the userspace threads, although 1:1 mapping often reduces most overhead of mapping. Since kernel threads are heavyweight (involving system calls) to create/destroy/communicate, there are non 1:1 green threads in the userspace to overcome the overhead problems at the cost of the mapping overhead. The choice of mapping depending on the programming paradigm expected in the high-level abstraction. For example, when a huge number of userspace threads expected being concurrently executed (like Erlang), 1:1 mapping is never feasible.

The underlying of OS multitasking is ISA-level multitasking provided by the logical core of the processor. This is usually the most low-level public interface for programmers. Beneath this level, there may exist SMT. This is a form of more low-level multithreading implemented by the hardware, but arguably, still somewhat programmable - though it is usually only accessible by the processor manufacturer. Note the hardware design is apparently reflecting parallelism, but there is also concurrent scheduling mechanism to make the internal hardware resources being efficiently used.

In each level of "threading" mentioned above, both concurrency and parallelism are involved. Although the programming interfaces vary dramatically, all of them are subject to the properties revealed by the basic abstraction at the very beginning.

String.Replace ignoring case

Extending Petrucio's answer with Regex.Escape on the search string, and escaping matched group as suggested in Steve B's answer (and some minor changes to my taste):

public static class StringExtensions
{
    public static string ReplaceIgnoreCase(this string str, string from, string to)
    {
        return Regex.Replace(str, Regex.Escape(from), to.Replace("$", "$$"), RegexOptions.IgnoreCase);
    }
}

Which will produce the following expected results:

Console.WriteLine("(heLLo) wOrld".ReplaceIgnoreCase("(hello) world", "Hi $1 Universe")); // Hi $1 Universe
Console.WriteLine("heLLo wOrld".ReplaceIgnoreCase("(hello) world", "Hi $1 Universe"));   // heLLo wOrld

However without performing the escapes you would get the following, which is not an expected behaviour from a String.Replace that is just case-insensitive:

Console.WriteLine("(heLLo) wOrld".ReplaceIgnoreCase_NoEscaping("(hello) world", "Hi $1 Universe")); // (heLLo) wOrld
Console.WriteLine("heLLo wOrld".ReplaceIgnoreCase_NoEscaping("(hello) world", "Hi $1 Universe"));   // Hi heLLo Universe

Counting number of characters in a file through shell script

#!/bin/sh

wc -m $1 | awk '{print $1}'

wc -m counts the number of characters; the awk command prints the number of characters only, omitting the filename.

wc -c would give you the number of bytes (which can be different to the number of characters, as depending on the encoding you may have a character encoded on several bytes).

Return current date plus 7 days

This code works for me:

<?php
$date = "21.12.2015";
$newDate = date("d.m.Y",strtotime($date."+2 day"));
echo $newDate; // print 23.12.2015
?>

Remove IE10's "clear field" X button on certain inputs?

To hide arrows and cross in a "time" input :

#inputId::-webkit-outer-spin-button,
#inputId::-webkit-inner-spin-button,
#inputId::-webkit-clear-button{
    -webkit-appearance: none;
    margin: 0;
}

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

This Error hit me after installing RVM correctly. Solution: re-boot Terminal.

Reference RailsCast's RVM Install tutorial.

Why does Math.Round(2.5) return 2 instead of 3?

You should check MSDN for Math.Round:

The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding.

You can specify the behavior of Math.Round using an overload:

Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // gives 3

Math.Round(2.5, 0, MidpointRounding.ToEven); // gives 2

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

Way to get number of digits in an int?

I wrote this function after looking Integer.java source code.

private static int stringSize(int x) {
    final int[] sizeTable = {9, 99, 999, 9_999, 99_999, 999_999, 9_999_999,
            99_999_999, 999_999_999, Integer.MAX_VALUE};
    for (int i = 0; ; ++i) {
        if (x <= sizeTable[i]) {
            return i + 1;
        }
    }
}

Python convert csv to xlsx

Adding an answer that exclusively uses the pandas library to read in a .csv file and save as a .xlsx file. This example makes use of pandas.read_csv (Link to docs) and pandas.dataframe.to_excel (Link to docs).

The fully reproducible example uses numpy to generate random numbers only, and this can be removed if you would like to use your own .csv file.

import pandas as pd
import numpy as np

# Creating a dataframe and saving as test.csv in current directory
df = pd.DataFrame(np.random.randn(100000, 3), columns=list('ABC'))
df.to_csv('test.csv', index = False)

# Reading in test.csv and saving as test.xlsx

df_new = pd.read_csv('test.csv')
writer = pd.ExcelWriter('test.xlsx')
df_new.to_excel(writer, index = False)
writer.save()

When and why to 'return false' in JavaScript?

Er ... how about in a boolean function to indicate 'not true'?

Example of AES using Crypto++

Official document of Crypto++ AES is a good start. And from my archive, a basic implementation of AES is as follows:

Please refer here with more explanation, I recommend you first understand the algorithm and then try to understand each line step by step.

#include <iostream>
#include <iomanip>

#include "modes.h"
#include "aes.h"
#include "filters.h"

int main(int argc, char* argv[]) {

    //Key and IV setup
    //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256-   
    //bit). This key is secretly exchanged between two parties before communication   
    //begins. DEFAULT_KEYLENGTH= 16 bytes
    CryptoPP::byte key[ CryptoPP::AES::DEFAULT_KEYLENGTH ], iv[ CryptoPP::AES::BLOCKSIZE ];
    memset( key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH );
    memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );

    //
    // String and Sink setup
    //
    std::string plaintext = "Now is the time for all good men to come to the aide...";
    std::string ciphertext;
    std::string decryptedtext;

    //
    // Dump Plain Text
    //
    std::cout << "Plain Text (" << plaintext.size() << " bytes)" << std::endl;
    std::cout << plaintext;
    std::cout << std::endl << std::endl;

    //
    // Create Cipher Text
    //
    CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv );

    CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( ciphertext ) );
    stfEncryptor.Put( reinterpret_cast<const unsigned char*>( plaintext.c_str() ), plaintext.length() );
    stfEncryptor.MessageEnd();

    //
    // Dump Cipher Text
    //
    std::cout << "Cipher Text (" << ciphertext.size() << " bytes)" << std::endl;

    for( int i = 0; i < ciphertext.size(); i++ ) {

        std::cout << "0x" << std::hex << (0xFF & static_cast<CryptoPP::byte>(ciphertext[i])) << " ";
    }

    std::cout << std::endl << std::endl;

    //
    // Decrypt
    //
    CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
    CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption( aesDecryption, iv );

    CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink( decryptedtext ) );
    stfDecryptor.Put( reinterpret_cast<const unsigned char*>( ciphertext.c_str() ), ciphertext.size() );
    stfDecryptor.MessageEnd();

    //
    // Dump Decrypted Text
    //
    std::cout << "Decrypted Text: " << std::endl;
    std::cout << decryptedtext;
    std::cout << std::endl << std::endl;

    return 0;
}

For installation details :

sudo apt-get install libcrypto++-dev libcrypto++-doc libcrypto++-utils

geom_smooth() what are the methods available?

The se argument from the example also isn't in the help or online documentation.

When 'se' in geom_smooth is set 'FALSE', the error shading region is not visible

What is causing "Unable to allocate memory for pool" in PHP?

Monitor your Cached Files Size (you can use apc.php from apc pecl package) and increase apc.shm_size according to your needs.

This solves the problem.

Why is textarea filled with mysterious white spaces?

Please make sure there is no linebreak or space after , it's to make sure there is no whitespace or tab, just copy and paste this code :) I had fix it for you

<textarea style="width:350px; height:80px;" cols="42" rows="5" name="sitelink"><?php if($siteLink_val) echo trim($siteLink_val);?></textarea>

Accessing localhost of PC from USB connected Android mobile device

I very much liked John's answer, but I'd like to give it with some changes to those that want to test some client//server configuration by running a client TCP on the USB connected Mobile and a server on the local PC.

First it's quite obvious that the 10.0.2.2 won't work because this is a REAL hardware mobile and not a simulator.

So Follow John's instructions:

  • Unplug all network cables on PC and turn off wifi.
  • Turn off wifi on the android device
  • Connect android device to pc via USB
  • Turn on the "USB Tethering" (USB Modem/ USB Cellular Modem / USB ????? ????? ??????) in the android menu. (Under networks->more...->Tethering and portable hotspot")

    • This USB connection will act as a DHCP server for you single PC connection, so it'll assign your PC a dedicated (dynamic) IP in its local USB network. Now all you have to do is tell the client application this IP and port.
  • Get the IP of your PC (that has been assigned by the USB tether cable.) (open command prompt and type "ipconfig" then look for the IP that the USB network adapter has assigned, in Linux its ifconfig or Ubuntu's "Connection information" etc..)

  • Tell the application to connect to that IP (i.e. 192.168.42.87) with something like (Java - client side):

    String        serverIP      = "192.168.42.87";
    int           serverPort    = 5544;
    InetAddress   serverAddress = InetAddress.getByName(serverIP);
    Socket        socket         = new Socket(serverAddress, serverPort);
    ...
    

    Enjoy..

How to fix the error "Windows SDK version 8.1" was not found?

I realize this post is a few years old, but I just wanted to extend this to anyone still struggling through this issue.

The company I work for still uses VS2015 so in turn I still use VS2015. I recently started working on a RPC application using C++ and found the need to download the Win32 Templates. Like many others I was having this "SDK 8.1 was not found" issue. i took the following corrective actions with no luck.

  • I found the SDK through Micrsoft at the following link https://developer.microsoft.com/en-us/windows/downloads/sdk-archive/ as referenced above and downloaded it.
  • I located my VS2015 install in Apps & Features and ran the repair.
  • I completely uninstalled my VS2015 and reinstalled it.
  • I attempted to manually point my console app "Executable" and "Include" directories to the C:\Program Files (x86)\Microsoft SDKs\Windows Kits\8.1 and C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools.

None of the attempts above corrected the issue for me...

I then found this article on social MSDN https://social.msdn.microsoft.com/Forums/office/en-US/5287c51b-46d0-4a79-baad-ddde36af4885/visual-studio-cant-find-windows-81-sdk-when-trying-to-build-vs2015?forum=visualstudiogeneral

Finally what resolved the issue for me was:

  • Uninstalling and reinstalling VS2015.
  • Locating my installed "Windows Software Development Kit for Windows 8.1" and running the repair.
  • Checked my "C:\Program Files (x86)\Microsoft SDKs\Windows Kits\8.1" to verify the "DesignTime" folder was in fact there.
  • Opened VS created a Win32 Console application and comiled with no errors or issues

I hope this saves anyone else from almost 3 full days of frustration and loss of productivity.

How can I get the last 7 characters of a PHP string?

For simplicity, if you do not want send a message, try this

$new_string = substr( $dynamicstring, -min( strlen( $dynamicstring ), 7 ) );

Mongoose delete array element in document and save

You can also do the update directly in MongoDB without having to load the document and modify it using code. Use the $pull or $pullAll operators to remove the item from the array :

Favorite.updateOne( {cn: req.params.name}, { $pullAll: {uid: [req.params.deleteUid] } } )

(you can also use updateMany for multiple documents)

http://docs.mongodb.org/manual/reference/operator/update/pullAll/

Creating a Menu in Python

def my_add_fn():
   print "SUM:%s"%sum(map(int,raw_input("Enter 2 numbers seperated by a space").split()))

def my_quit_fn():
   raise SystemExit

def invalid():
   print "INVALID CHOICE!"

menu = {"1":("Sum",my_add_fn),
        "2":("Quit",my_quit_fn)
       }
for key in sorted(menu.keys()):
     print key+":" + menu[key][0]

ans = raw_input("Make A Choice")
menu.get(ans,[None,invalid])[1]()

how do I give a div a responsive height

For the height of a div to be responsive, it must be inside a parent element with a defined height to derive it's relative height from.

If you set the height of the container holding the image and text box on the right, you can subsequently set the heights of its two children to be something like 75% and 25%.

However, this will get a bit tricky when the site layout gets narrower and things will get wonky. Try setting the padding on .contentBg to something like 5.5%.

My suggestion is to use Media Queries to tweak the padding at different screen sizes, then bump everything into a single column when appropriate.

How to determine if a number is odd in JavaScript

Using % will help you to do this...

You can create couple of functions to do it for you... I prefer separte functions which are not attached to Number in Javascript like this which also checking if you passing number or not:

odd function:

var isOdd = function(num) {
  return 'number'!==typeof num ? 'NaN' : !!(num % 2);
};

even function:

var isEven = function(num) {
  return isOdd(num)==='NaN' ? isOdd(num) : !isOdd(num);
};

and call it like this:

isOdd(5); // true
isOdd(6); // false
isOdd(12); // false
isOdd(18); // false
isEven(18); // true
isEven('18'); // 'NaN'
isEven('17'); // 'NaN'
isOdd(null); // 'NaN'
isEven('100'); // true

NumPy first and last element from array

You can simply use take method and index of element (Last index can be -1).

arr = np.array([1,2,3])

last = arr.take(-1)
# 3

C# Pass Lambda Expression as Method Parameter

You should use a delegate type and specify that as your command parameter. You could use one of the built in delegate types - Action and Func.

In your case, it looks like your delegate takes two parameters, and returns a result, so you could use Func:

List<IJob> GetJobs(Func<FullTimeJob, Student, FullTimeJob> projection)

You could then call your GetJobs method passing in a delegate instance. This could be a method which matches that signature, an anonymous delegate, or a lambda expression.

P.S. You should use PascalCase for method names - GetJobs, not getJobs.

How to execute mongo commands through shell scripts?

You can also evaluate a command using the --eval flag, if it is just a single command.

mongo --eval "printjson(db.serverStatus())"

Please note: if you are using Mongo operators, starting with a $ sign, you'll want to surround the eval argument in single quotes to keep the shell from evaluating the operator as an environment variable:

mongo --eval 'db.mycollection.update({"name":"foo"},{$set:{"this":"that"}});' myDbName

Otherwise you may see something like this:

mongo --eval "db.test.update({\"name\":\"foo\"},{$set:{\"this\":\"that\"}});"
> E QUERY    SyntaxError: Unexpected token :

Add two textbox values and display the sum in a third textbox automatically

In below code i have done operation of sum and subtraction: because of using JavaScript if you want to call function, then you have to put your below code outside of document.ready(function{ }); and outside the script end tag.

I have taken one another script tag for this operation.And put below code between script starting tag // your code // script ending tag.

 function operation() 

 {

   var txtFirstNumberValue = parseInt(document.getElementById('basic').value);
   var txtSecondNumberValue =parseInt(document.getElementById('hra').value);
   var txtThirdNumberValue =parseInt(document.getElementById('transport').value);
   var txtFourthNumberValue =parseInt(document.getElementById('pt').value);
   var txtFiveNumberValue = parseInt(document.getElementById('pf').value);

   if (txtFirstNumberValue == "")
       txtFirstNumberValue = 0;
   if (txtSecondNumberValue == "")
       txtSecondNumberValue = 0;
   if (txtThirdNumberValue == "")
       txtThirdNumberValue = 0;
   if (txtFourthNumberValue == "")
       txtFourthNumberValue = 0;
   if (txtFiveNumberValue == "")
       txtFiveNumberValue = 0;



   var result = ((txtFirstNumberValue + txtSecondNumberValue + 
  txtThirdNumberValue) - (txtFourthNumberValue + txtFiveNumberValue));
   if (!isNaN(result)) {
       document.getElementById('total').value = result;
   }
 }

And put onkeyup="operation();" inside all 5 textboxes in your html form. This code running in both Firefox and Chrome.

Maven plugin in Eclipse - Settings.xml file is missing

Working on Mac I followed the answer of Sean Patrick Floyd placing a settings.xml like above in my user folder /Users/user/.m2/

But this did not help. So I opened a Terminal and did a ls -la on the folder. This was showing

-rw-r--r--@

thus staff and everone can at least read the file. So I wondered if the message isn't wrong and if the real cause is the lack of write permissions. I set the file to:

-rw-r--rw-@

This did it. The message disappeared.

Convert JsonObject to String

you can use

JsonObject.getString("msg"); 

How to automatically reload a page after a given period of inactivity

And finally the most simple solution:

With alert confirmation:

<script type="text/javascript">
    // Set timeout variables.
    var timoutWarning = 3000; // Display warning in 1Mins.
    var timoutNow = 4000; // Timeout in 2 mins.

    var warningTimer;
    var timeoutTimer;

    // Start timers.
    function StartTimers() {
        warningTimer = setTimeout("IdleWarning()", timoutWarning);
        timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
    }

    // Reset timers.
    function ResetTimers() {
        clearTimeout(warningTimer);
        clearTimeout(timeoutTimer);
        StartTimers();
        $("#timeout").dialog('close');
    }

    // Show idle timeout warning dialog.
    function IdleWarning() {
        var answer = confirm("Session About To Timeout\n\n       You will be automatically logged out.\n       Confirm to remain logged in.")
            if (answer){

                ResetTimers();
            }
            else{
                IdleTimeout();
            }
    }       

    // Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
    function IdleTimeout() {
        window.open(self.location,'_top');
    }
</script>

Without alert confirmation:

<script type="text/javascript">
    // Set timeout variables.
    var timoutWarning = 3000; // Display warning in 1Mins.
    var timoutNow = 4000; // Timeout in 2 mins.

    var warningTimer;
    var timeoutTimer;

    // Start timers.
    function StartTimers() {
        warningTimer = setTimeout(timoutWarning);
        timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
    }

    // Reset timers.
    function ResetTimers() {
        clearTimeout(warningTimer);
        clearTimeout(timeoutTimer);
        StartTimers();
        $("#timeout").dialog('close');
    }

    // Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
    function IdleTimeout() {
        window.open(self.location,'_top');
    }
</script>

Body code is the SAME for both solutions

<body onload="StartTimers();" onmousemove="ResetTimers();" onKeyPress="ResetTimers();">

Copy an entire worksheet to a new worksheet in Excel 2010

It is simpler just to run an exact copy like below to put the copy in as the last sheet

Sub Test()
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Master")
ws1.Copy ThisWorkbook.Sheets(Sheets.Count)
End Sub

Detect encoding and make everything UTF-8

This version is for German language but you can modifiy the $CHARSETS and the $TESTCHARS

class CharsetDetector
{
private static $CHARSETS = array(
"ISO_8859-1",
"ISO_8859-15",
"CP850"
);
private static $TESTCHARS = array(
"€",
"ä",
"Ä",
"ö",
"Ö",
"ü",
"Ü",
"ß"
);
public static function convert($string)
{
    return self::__iconv($string, self::getCharset($string));
}
public static function getCharset($string)
{
    $normalized = self::__normalize($string);
    if(!strlen($normalized))return "UTF-8";
    $best = "UTF-8";
    $charcountbest = 0;
    foreach (self::$CHARSETS as $charset) {
        $str = self::__iconv($normalized, $charset);
        $charcount = 0;
        $stop   = mb_strlen( $str, "UTF-8");

        for( $idx = 0; $idx < $stop; $idx++)
        {
            $char = mb_substr( $str, $idx, 1, "UTF-8");
            foreach (self::$TESTCHARS as $testchar) {

                if($char == $testchar)
                {

                    $charcount++;
                    break;
                }
            }
        }
        if($charcount>$charcountbest)
        {
            $charcountbest=$charcount;
            $best=$charset;
        }
        //echo $text."<br />";
    }
    return $best;
}
private static function __normalize($str)
{

$len = strlen($str);
$ret = "";
for($i = 0; $i < $len; $i++){
    $c = ord($str[$i]);
    if ($c > 128) {
        if (($c > 247)) $ret .=$str[$i];
        elseif ($c > 239) $bytes = 4;
        elseif ($c > 223) $bytes = 3;
        elseif ($c > 191) $bytes = 2;
        else $ret .=$str[$i];
        if (($i + $bytes) > $len) $ret .=$str[$i];
        $ret2=$str[$i];
        while ($bytes > 1) {
            $i++;
            $b = ord($str[$i]);
            if ($b < 128 || $b > 191) {$ret .=$ret2; $ret2=""; $i+=$bytes-1;$bytes=1; break;}
            else $ret2.=$str[$i];
            $bytes--;
        }
    }
}
return $ret; 
}
private static function __iconv($string, $charset)
{
    return iconv ( $charset, "UTF-8" , $string );
}
}

Ignore invalid self-signed ssl certificate in node.js with https.request?

In your request options, try including the following:

   var req = https.request({ 
      host: '192.168.1.1', 
      port: 443,
      path: '/',
      method: 'GET',
      rejectUnauthorized: false,
      requestCert: true,
      agent: false
    },

Undo a merge by pull request?

To undo a github pull request with commits throughout that you do not want to delete, you have to run a:

git reset --hard --merge <commit hash>

with the commit hash being the commit PRIOR to merging the pull request. This will remove all commits from the pull request without influencing any commits within the history.

A good way to find this is to go to the now closed pull request and finding this field:

Pull Request Image Pull Request Image

After you run the git reset, run a:

git push origin --force <branch name>

This should revert the branch back before the pull request WITHOUT affecting any commits in the branch peppered into the commit history between commits from the pull request.

EDIT:

If you were to click the revert button on the pull request, this creates an additional commit on the branch. It DOES NOT uncommit or unmerge. This means that if you were to hit the revert button, you cannot open a new pull request to re-add all of this code.

Parse JSON object with string and value only

You need to get a list of all the keys, loop over them and add them to your map as shown in the example below:

    String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
    JSONObject jObject  = new JSONObject(s);
    JSONObject  menu = jObject.getJSONObject("menu");

    Map<String,String> map = new HashMap<String,String>();
    Iterator iter = menu.keys();
    while(iter.hasNext()){
        String key = (String)iter.next();
        String value = menu.getString(key);
        map.put(key,value);
    }

Finding blocking/locking queries in MS SQL (mssql)

I found this query which helped me find my locked table and query causing the issue.

SELECT  L.request_session_id AS SPID, 
        DB_NAME(L.resource_database_id) AS DatabaseName,
        O.Name AS LockedObjectName, 
        P.object_id AS LockedObjectId, 
        L.resource_type AS LockedResource, 
        L.request_mode AS LockType,
        ST.text AS SqlStatementText,        
        ES.login_name AS LoginName,
        ES.host_name AS HostName,
        TST.is_user_transaction as IsUserTransaction,
        AT.name as TransactionName,
        CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
        JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
        JOIN sys.objects O ON O.object_id = P.object_id
        JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
        JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
        JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
        JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
        CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

(Mac) -bash: __git_ps1: command not found

At least with Xcode 6, you already have git-completion.bash. It's inside the Xcode app bundle.

Just add this to your .bashrc:

source `xcode-select -p`/usr/share/git-core/git-completion.bash

NSString property: copy or retain?

For attributes whose type is an immutable value class that conforms to the NSCopying protocol, you almost always should specify copy in your @property declaration. Specifying retain is something you almost never want in such a situation.

Here's why you want to do that:

NSMutableString *someName = [NSMutableString stringWithString:@"Chris"];

Person *p = [[[Person alloc] init] autorelease];
p.name = someName;

[someName setString:@"Debajit"];

The current value of the Person.name property will be different depending on whether the property is declared retain or copy — it will be @"Debajit" if the property is marked retain, but @"Chris" if the property is marked copy.

Since in almost all cases you want to prevent mutating an object's attributes behind its back, you should mark the properties representing them copy. (And if you write the setter yourself instead of using @synthesize you should remember to actually use copy instead of retain in it.)

Padding or margin value in pixels as integer using jQuery

PLEASE don't go loading another library just to do something that's already natively available!

jQuery's .css() converts %'s and em's to their pixel equivalent to begin with, and parseInt() will remove the 'px' from the end of the returned string and convert it to an integer:

http://jsfiddle.net/BXnXJ/

$(document).ready(function () {
    var $h1 = $('h1');
    console.log($h1);
    $h1.after($('<div>Padding-top: ' + parseInt($h1.css('padding-top')) + '</div>'));
    $h1.after($('<div>Margin-top: ' + parseInt($h1.css('margin-top')) + '</div>'));
});

Maven skip tests

I have another approach for Intellij users, and it is working very fine for me:

  1. Click on the "Skip Test" button

enter image description here

  1. Hold the "CTRL" button
  2. Select "clean" and "install"

enter image description here

  1. Click on the "Run" button in the maven pannel

enter image description here

What is a void pointer in C++?

A void* can point to anything (it's a raw pointer without any type info).

update listview dynamically with adapter

If you create your own adapter, there is one notable abstract function:

public void registerDataSetObserver(DataSetObserver observer) {
    ...
}

You can use the given observers to notify the system to update:

private ArrayList<DataSetObserver> observers = new ArrayList<DataSetObserver>();

public void registerDataSetObserver(DataSetObserver observer) {
    observers.add(observer);
}
public void notifyDataSetChanged(){
    for (DataSetObserver observer: observers) {
        observer.onChanged();
    }
}

Though aren't you glad there are things like the SimpleAdapter and ArrayAdapter and you don't have to do all that?

Rails server says port already used, how to kill that process?

One line solution:

kill -9 $(ps aux | grep 'rails s' | awk {'print$2'}); rails s

html button to send email

You can use mailto, here is the HTML code:

<a href="mailto:EMAILADDRESS">

Replace EMAILADDRESS with your email.

"A referral was returned from the server" exception when accessing AD from C#

In my case I was seeing referrals when I was accessing AD via SSO with an account in a trusted domain. The problem went away when I connected with explicit credentials in the local domain.

i.e. I replaced

DirectoryEntry de = new DirectoryEntry("blah.com");

with

DirectoryEntry de = new DirectoryEntry("blah.com", "[email protected]", "supersecret");

and the problem went away.

A field initializer cannot reference the nonstatic field, method, or property

You need to put that code into the constructor of your class:

private Reminders reminder = new Reminders();
private dynamic defaultReminder;

public YourClass()
{
    defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}

The reason is that you can't use one instance variable to initialize another one using a field initializer.

How to convert flat raw disk image to vmdk for virtualbox or vmplayer?

Since the question mentions VirtualBox, this one works currently:

VBoxManage convertfromraw imagefile.dd vmdkname.vmdk --format VMDK

Run it without arguments for a few interesting details (notably the --variant flag):

VBoxManage convertfromraw

Getting input values from text box

// NOTE: Using "this.pass" and "this.name" will create a global variable even though it is inside the function, so be weary of your naming convention

function submit()
{
    var userPass = document.getElementById("pass").value;
    var userName = document.getElementById("user").value;
    this.pass = userPass;
    this.name = userName; 
    alert("whatever you want to display"); 
}

What's the difference between dependencies, devDependencies and peerDependencies in npm package.json file?

Dependencies vs dev dependencies

Dev dependencies are modules which are only required during development whereas dependencies are required at runtime. If you are deploying your application, dependencies has to be installed, or else your app simply will not work. Libraries that you call from your code that enables the program to run can be considered as dependencies.

Eg- React , React - dom

Dev dependency modules need not be installed in the production server since you are not gonna develop in that machine .compilers that covert your code to javascript , test frameworks and document generators can be considered as dev-dependencies since they are only required during development .

Eg- ESLint , Babel , webpack

@FYI,

mod-a
  dev-dependents:
    - mod-b
  dependents:
    - mod-c

mod-d
?  dev-dependents:
    - mod-e
  dependents:
    - mod-a

----

npm install mod-d

installed modules:
  - mod-d
  - mod-a
  - mod-c

----

checkout the mod-d code repository

npm install

installed modules:
  - mod-a
  - mod-c
  - mod-e

If you are publishing to npm, then it is important that you use the correct flag for the correct modules. If it is something that your npm module needs to function, then use the "--save" flag to save the module as a dependency. If it is something that your module doesn't need to function but it is needed for testing, then use the "--save-dev" flag.

# For dependent modules
?npm install dependent-module --save

?# For dev-dependent modules
np?m install development-module --save-dev

Checking if a file is a directory or just a file

Normally you want to perform this check atomically with using the result, so stat() is useless. Instead, open() the file read-only first and use fstat(). If it's a directory, you can then use fdopendir() to read it. Or you can try opening it for writing to begin with, and the open will fail if it's a directory. Some systems (POSIX 2008, Linux) also have an O_DIRECTORY extension to open which makes the call fail if the name is not a directory.

Your method with opendir() is also good if you want a directory, but you should not close it afterwards; you should go ahead and use it.

Publish to IIS, setting Environment Variable

Similar to other answers, I wanted to ensure my ASP.NET Core 2.1 environment setting persisted across deployments, but also only applied to the specific site.

According to Microsoft's documentation, it is possible to set the environment variable on the app pool using the following PowerShell command in IIS 10:

$appPoolName = "AppPool"
$envName = "Development"
cd "$env:SystemRoot\system32\inetsrv"
.\appcmd.exe set config -section:system.applicationHost/applicationPools /+"[name='$appPoolName'].environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='$envName']" /commit:apphost

I unfortunately still have to use IIS 8.5 and thought I was out of luck. However, it is still possible to run a simple PowerShell script to set a site-specific environment variable value for ASPNETCORE_ENVIRONMENT:

Import-Module -Name WebAdministration
$siteName = "Site"
$envName = "Development"
Set-WebConfigurationProperty -PSPath IIS:\ -Location $siteName -Filter /system.webServer/aspNetCore/environmentVariables -Name . -Value @{ Name = 'ASPNETCORE_ENVIRONMENT'; Value = $envName }

Drawing a line/path on Google Maps

It is really easy with Google Maps Android API v2

Just copy the example from Developer documentation

(of course you have to init your map first)

GoogleMap map;
 // ... get a map.
 // Add a thin red line from London to New York.
 Polyline line = map.addPolyline(new PolylineOptions()
     .add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
     .width(5)
     .color(Color.RED));

How to get coordinates of an svg element?

I use the consolidate function, like so:

 element.transform.baseVal.consolidate()

The .e and .f values correspond to the x and y coordinates

How to dump only specific tables from MySQL?

If you're in local machine then use this command

/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

For remote machine, use below one

/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

mongodb service is not starting up

Here's a weird one, make sure you have consistent spacing in the config file.

For example:

processManagement:
  timeZoneInfo: /usr/share/zoneinfo

security:
    authorization: 'enabled'

If the authorization key has 4 spaces before it, like above and the rest are 2 spaces then it won't work.

Disable all table constraints in Oracle

This is another way for disabling constraints (it came from https://asktom.oracle.com/pls/asktom/f?p=100:11:2402577774283132::::P11_QUESTION_ID:399218963817)

WITH qry0 AS
       (SELECT    'ALTER TABLE '
               || child_tname
               || ' DISABLE CONSTRAINT '
               || child_cons_name
                 disable_fk
              ,   'ALTER TABLE '
               || parent_tname
               || ' DISABLE CONSTRAINT '
               || parent.parent_cons_name
                 disable_pk
          FROM (SELECT a.table_name child_tname
                      ,a.constraint_name child_cons_name
                      ,b.r_constraint_name parent_cons_name
                      ,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) child_columns
                  FROM user_cons_columns a
                      ,user_constraints b
                 WHERE a.constraint_name = b.constraint_name AND b.constraint_type = 'R'
                GROUP BY a.table_name, a.constraint_name
                        ,b.r_constraint_name) child
              ,(SELECT a.constraint_name parent_cons_name
                      ,a.table_name parent_tname
                      ,LISTAGG ( column_name, ',') WITHIN GROUP (ORDER BY position) parent_columns
                  FROM user_cons_columns a
                      ,user_constraints b
                 WHERE a.constraint_name = b.constraint_name AND b.constraint_type IN ('P', 'U')
                GROUP BY a.table_name, a.constraint_name) parent
         WHERE child.parent_cons_name = parent.parent_cons_name
           AND (parent.parent_tname LIKE 'V2_%' OR child.child_tname LIKE 'V2_%'))
SELECT DISTINCT disable_pk
  FROM qry0
UNION
SELECT DISTINCT disable_fk
  FROM qry0;

works like a charm

SQL update fields of one table from fields of another one

You can use the non-standard FROM clause.

UPDATE b
SET column1 = a.column1,
  column2 = a.column2,
  column3 = a.column3
FROM a
WHERE a.id = b.id
AND b.id = 1

Objective-C: Calling selectors with multiple arguments

Your method signature is:

- (void) myTest:(NSString *)

withAString happens to be the parameter (the name is misleading, it looks like it is part of the selector's signature).

If you call the function in this manner:

[self performSelector:@selector(myTest:) withObject:myString];

It will work.

But, as the other posters have suggested, you may want to rename the method:

- (void)myTestWithAString:(NSString*)aString;

And call:

[self performSelector:@selector(myTestWithAString:) withObject:myString];

How to move screen without moving cursor in Vim?

zEnter does exactly what this question asks for.

It works where strangely zz would not work (vim 7.4.1689 on Ubuntu 2016.04 LTS with no special .vimrc)

Unit Tests not discovered in Visual Studio 2017

Removing old .dll should help. Clearing temp files located in the %TEMP% directory at C:\Users(yourusername)\AppData\Local\Temp

How to get duration, as int milli's and float seconds from <chrono>?

In AAA style using the explicitly typed initializer idiom:

#include <chrono>
#include <iostream>

int main(){
  auto start = std::chrono::high_resolution_clock::now();
  // Code to time here...
  auto end = std::chrono::high_resolution_clock::now();

  auto dur = end - start;
  auto i_millis = std::chrono::duration_cast<std::chrono::milliseconds>(dur);
  auto f_secs = std::chrono::duration_cast<std::chrono::duration<float>>(dur);
  std::cout << i_millis.count() << '\n';
  std::cout << f_secs.count() << '\n';
}

Which MIME type to use for a binary file that's specific to my program?

According to the spec RFC 2045 #Syntax of the Content-Type Header Field application/myappname is not allowed, but application/x-myappname is allowed and sounds most appropriate for you're application to me.

Eclipse: "'Periodic workspace save.' has encountered a pro?blem."

This was simple for me -

Solution

  1. (pre) the listed directory is not present, see pic
  2. Run Eclipse, see the error shown in pic below. Close Eclipse
  3. Create the directory (RemoteSystemsTempFiles) where it is looking

    • note: ignore the items in this folder (e.g. .markers), they are auto-generated
  4. Restart Eclipse, problem solved!

Example Problem Message

enter image description here

Not sure why this took me so long to resolve, but quite easy now, and quite obvious in retrospect! ;)...

Drawing an image from a data URL to a canvas

in javascript , using jquery for canvas id selection :

 var Canvas2 = $("#canvas2")[0];
        var Context2 = Canvas2.getContext("2d");
        var image = new Image();
        image.src = "images/eye.jpg";
        Context2.drawImage(image, 0, 0);

html5:

<canvas id="canvas2"></canvas>

Pandas DataFrame to List of Dictionaries

If you are interested in only selecting one column this will work.

df[["item1"]].to_dict("records")

The below will NOT work and produces a TypeError: unsupported type: . I believe this is because it is trying to convert a series to a dict and not a Data Frame to a dict.

df["item1"].to_dict("records")

I had a requirement to only select one column and convert it to a list of dicts with the column name as the key and was stuck on this for a bit so figured I'd share.

How to restart a single container with docker-compose

Following command

docker-compose restart worker

will just STOP and START the container. i.e without loading any changes from the docker-compose.xml

STOP is similar to hibernating in PC . Hence stop/start will not look for any changes made in configuration file . To reload from the recipe of container (docker-compose.xml) we need to remove and create the container (Similar analogy to rebooting the PC )

So commands will be as following

docker-compose stop worker       // go to hibernate
docker-compose rm worker        // shutdown the PC 
docker-compose create worker     // create the container from image and put it in hibernate

docker-compose start worker //bring container to life from hibernation

Get Specific Columns Using “With()” Function in Laravel Eloquent

Note that if you only need one column from the table then using 'lists' is quite nice. In my case i am retrieving a user's favourite articles but i only want the article id's:

$favourites = $user->favourites->lists('id');

Returns an array of ids, eg:

Array
(
    [0] => 3
    [1] => 7
    [2] => 8
)

More than 1 row in <Input type="textarea" />

Although <input> ignores the rows attribute, you can take advantage of the fact that <textarea> doesn't have to be inside <form> tags, but can still be a part of a form by referencing the form's id:

<form method="get" id="testformid">
    <input type="submit" />
</form> 
<textarea form ="testformid" name="taname" id="taid" cols="35" wrap="soft"></textarea>

Of course, <textarea> now appears below "submit" button, but maybe you'll find a way to reposition it.

How to pass dictionary items as function arguments in python?

If you want to use them like that, define the function with the variable names as normal:

def my_function(school, standard, city, name):
    schoolName  = school
    cityName = city
    standardName = standard
    studentName = name

Now you can use ** when you call the function:

data = {'school':'DAV', 'standard': '7', 'name': 'abc', 'city': 'delhi'}

my_function(**data)

and it will work as you want.

P.S. Don't use reserved words such as class.(e.g., use klass instead)

Split a string by a delimiter in python

You can use the str.split method: string.split('__')

>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']

Ruby get object keys as array

An alternative way if you need something more (besides using the keys method):

hash = {"apple" => "fruit", "carrot" => "vegetable"}
array = hash.collect {|key,value| key }

obviously you would only do that if you want to manipulate the array while retrieving it..

Is it possible to move/rename files in Git and maintain their history?

I would like to rename/move a project subtree in Git moving it from

/project/xyz

to

/components/xyz

If I use a plain git mv project components, then all the commit history for the xyz project gets lost.

No (8 years later, Git 2.19, Q3 2018), because Git will detect the directory rename, and this is now better documented.

See commit b00bf1c, commit 1634688, commit 0661e49, commit 4d34dff, commit 983f464, commit c840e1a, commit 9929430 (27 Jun 2018), and commit d4e8062, commit 5dacd4a (25 Jun 2018) by Elijah Newren (newren).
(Merged by Junio C Hamano -- gitster -- in commit 0ce5a69, 24 Jul 2018)

That is now explained in Documentation/technical/directory-rename-detection.txt:

Example:

When all of x/a, x/b and x/c have moved to z/a, z/b and z/c, it is likely that x/d added in the meantime would also want to move to z/d by taking the hint that the entire directory 'x' moved to 'z'.

But they are many other cases, like:

one side of history renames x -> z, and the other renames some file to x/e, causing the need for the merge to do a transitive rename.

To simplify directory rename detection, those rules are enforced by Git:

a couple basic rules limit when directory rename detection applies:

  1. If a given directory still exists on both sides of a merge, we do not consider it to have been renamed.
  2. If a subset of to-be-renamed files have a file or directory in the way (or would be in the way of each other), "turn off" the directory rename for those specific sub-paths and report the conflict to the user.
  3. If the other side of history did a directory rename to a path that your side of history renamed away, then ignore that particular rename from the other side of history for any implicit directory renames (but warn the user).

You can see a lot of tests in t/t6043-merge-rename-directories.sh, which also point out that:

  • a) If renames split a directory into two or more others, the directory with the most renames, "wins".
  • b) Avoid directory-rename-detection for a path, if that path is the source of a rename on either side of a merge.
  • c) Only apply implicit directory renames to directories if the other side of history is the one doing the renaming.

Android Color Picker

I know the question is old, but if someone is looking for a great new android color picker that use material design I have forked an great project from github and made a simple-to-use android color picker dialog.

This is the project: Android Color Picker

Android Color Picker dialog

enter image description here

HOW TO USE IT

Adding the library to your project

The aar artifact is available at the jcenter repository. Declare the repository and the dependency in your build.gradle.

(root)

repositories {
    jcenter()
}

(module)

dependencies {
    compile 'com.pes.materialcolorpicker:library:1.0.2'
}

Use the library

Create a color picker dialog object

final ColorPicker cp = new ColorPicker(MainActivity.this, defaultColorR, defaultColorG, defaultColorB);

defaultColorR, defaultColorG, defaultColorB are 3 integer ( value 0-255) for the initialization of the color picker with your custom color value. If you don't want to start with a color set them to 0 or use only the first argument

Then show the dialog (when & where you want) and save the selected color

/* Show color picker dialog */
cp.show();

/* On Click listener for the dialog, when the user select the color */
Button okColor = (Button)cp.findViewById(R.id.okColorButton);

okColor.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
            
        /* You can get single channel (value 0-255) */
        selectedColorR = cp.getRed();
        selectedColorG = cp.getGreen();
        selectedColorB = cp.getBlue();
            
        /* Or the android RGB Color (see the android Color class reference) */
        selectedColorRGB = cp.getColor();

        cp.dismiss();
    }
});

That's all :)

Why I've got no crontab entry on OS X when using vim?

I did 2 things to solve this problem.

  1. I touched the crontab file, described in this link coderwall.com/p/ry9jwg (Thanks @Andy).
  2. Used Emacs instead of my default vim: EDITOR=emacs crontab -e (I have no idea why vim does not work)

crontab -lnow prints the cronjobs. Now I only need to figure out why the cronjobs are still not running ;-)

Shell script - remove first and last quote (") from a variable

My version

strip_quotes() {
    while [[ $# -gt 0 ]]; do
        local value=${!1}
        local len=${#value}
        [[ ${value:0:1} == \" && ${value:$len-1:1} == \" ]] && declare -g $1="${value:1:$len-2}"
        shift
    done
}

The function accepts variable name(s) and strips quotes in place. It only strips a matching pair of leading and trailing quotes. It doesn't check if the trailing quote is escaped (preceded by \ which is not itself escaped).

In my experience, general-purpose string utility functions like this (I have a library of them) are most efficient when manipulating the strings directly, not using any pattern matching and especially not creating any sub-shells, or calling any external tools such as sed, awk or grep.

var1="\"test \\ \" end \""
var2=test
var3=\"test
var4=test\"
echo before:
for i in var{1,2,3,4}; do
    echo $i="${!i}"
done
strip_quotes var{1,2,3,4}
echo
echo after:
for i in var{1,2,3,4}; do
    echo $i="${!i}"
done

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

Had the same issue then I used the connection string without ./ (like DESKTOP-E53DUML instead of this ./DESKTOP-E53DUML)

How to calculate age in T-SQL with years, months, and days

DECLARE @DoB AS DATE = '1968-10-24'
DECLARE @cDate AS DATE = CAST('2000-10-23' AS DATE)

SELECT 
--Get Year difference
DATEDIFF(YEAR,@DoB,@cDate) -
--Cases where year difference will be augmented
CASE 
    --If Date of Birth greater than date passed return 0
    WHEN YEAR(@DoB) - YEAR(@cDate) >= 0 THEN DATEDIFF(YEAR,@DoB,@cDate)

    --If date of birth month less than date passed subtract one year
    WHEN MONTH(@DoB) - MONTH(@cDate) > 0 THEN 1 

    --If date of birth day less than date passed subtract one year
    WHEN MONTH(@DoB) - MONTH(@cDate) = 0 AND DAY(@DoB) - DAY(@cDate) > 0 THEN 1 

    --All cases passed subtract zero
    ELSE 0
END

How to find a parent with a known class in jQuery?

Assuming that this is .d, you can write

$(this).closest('.a');

The closest method returns the innermost parent of your element that matches the selector.

validate a dropdownlist in asp.net mvc

I just can't believe that there are people still using ViewData/ViewBag in ASP.NET MVC 3 instead of having strongly typed views and view models:

public class MyViewModel
{
    [Required]
    public string CategoryId { get; set; }

    public IEnumerable<Category> Categories { get; set; }
}

and in your controller:

public class HomeController: Controller
{
    public ActionResult Index()
    {
        var model = new MyViewModel
        {
            Categories = Repository.GetCategories()
        }
        return View(model);
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        if (!ModelState.IsValid)
        {
            // there was a validation error =>
            // rebind categories and redisplay view
            model.Categories = Repository.GetCategories();
            return View(model);
        }
        // At this stage the model is OK => do something with the selected category
        return RedirectToAction("Success");
    }
}

and then in your strongly typed view:

@Html.DropDownListFor(
    x => x.CategoryId, 
    new SelectList(Model.Categories, "ID", "CategoryName"), 
    "-- Please select a category --"
)
@Html.ValidationMessageFor(x => x.CategoryId)

Also if you want client side validation don't forget to reference the necessary scripts:

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

Create, read, and erase cookies with jQuery

Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie

Is there a link to the "latest" jQuery library on Google APIs?

What about this one?

http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js

I think this is always the latest version - Correct me, if I'm wrong.

Change Row background color based on cell value DataTable

Callback for whenever a TR element is created for the table's body.

$('#example').dataTable( {
      "createdRow": function( row, data, dataIndex ) {
        if ( data[4] == "A" ) {
          $(row).addClass( 'important' );
        }
      }
    } );

https://datatables.net/reference/option/createdRow

JavaScript split String with white space

Using regex:

var str   = "my car is red";
var stringArray = str.split(/(\s+)/);

console.log(stringArray); // ["my", " ", "car", " ", "is", " ", "red"] 

\s matches any character that is a whitespace, adding the plus makes it greedy, matching a group starting with characters and ending with whitespace, and the next group starts when there is a character after the whitespace etc.

Encoding an image file with base64

import base64
from PIL import Image
from io import BytesIO

with open("image.jpg", "rb") as image_file:
    data = base64.b64encode(image_file.read())

im = Image.open(BytesIO(base64.b64decode(data)))
im.save('image1.png', 'PNG')

Returning Promises from Vuex actions

Just for an information on a closed topic: you don’t have to create a promise, axios returns one itself:

Ref: https://forum.vuejs.org/t/how-to-resolve-a-promise-object-in-a-vuex-action-and-redirect-to-another-route/18254/4

Example:

    export const loginForm = ({ commit }, data) => {
      return axios
        .post('http://localhost:8000/api/login', data)
        .then((response) => {
          commit('logUserIn', response.data);
        })
        .catch((error) => {
          commit('unAuthorisedUser', { error:error.response.data });
        })
    }

Another example:

    addEmployee({ commit, state }) {       
      return insertEmployee(state.employee)
        .then(result => {
          commit('setEmployee', result.data);
          return result.data; // resolve 
        })
        .catch(err => {           
          throw err.response.data; // reject
        })
    }

Another example with async-await

    async getUser({ commit }) {
        try {
            const currentUser = await axios.get('/user/current')
            commit('setUser', currentUser)
            return currentUser
        } catch (err) {
            commit('setUser', null)
            throw 'Unable to fetch current user'
        }
    },

What do Clustered and Non clustered index actually mean?

Find below some characteristics of clustered and non-clustered indexes:

Clustered Indexes

  1. Clustered indexes are indexes that uniquely identify the rows in an SQL table.
  2. Every table can have exactly one clustered index.
  3. You can create a clustered index that covers more than one column. For example: create Index index_name(col1, col2, col.....).
  4. By default, a column with a primary key already has a clustered index.

Non-clustered Indexes

  1. Non-clustered indexes are like simple indexes. They are just used for fast retrieval of data. Not sure to have unique data.

convert string into array of integers

let idsArray = ids.split(',').map((x) => parseInt(x));

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

Here is another way using WebRequest, I hope it will work for you

$user = 'whatever'
$pass = 'whatever'
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$headers = @{ Authorization = "Basic Zm9vOmJhcg==" }  
Invoke-WebRequest -Credential $credential -Headers $headers -Uri "https://dc01.test.local/"

Greyscale Background Css Images

You don't need to use complicated coding really!

Greyscale Hover:

-webkit-filter: grayscale(100%);

Greyscale "Hover-out":

-webkit-filter: grayscale(0%);


I simply made my css class have a separate hover class and added in the second greyscale. It's really simple if you really don't like complexity.

Select elements by attribute

simply:

$('input[name*="value"]')

more info: official docs

join list of lists in python

Or a recursive operation:

def flatten(input):
    ret = []
    if not isinstance(input, (list, tuple)):
        return [input]
    for i in input:
        if isinstance(i, (list, tuple)):
            ret.extend(flatten(i))
        else:
            ret.append(i)
    return ret

Searching a string in eclipse workspace

At the top level menus, select 'Search' -> 'File Search' Then near the bottom (in the scope) there is a choice to select the entire workspace.

For your "File search has encountered a problem", you need to refresh the files in your workspace, in the Project/Package Explorer, right click and select "Refresh" at any level (project, folder, file). This will sync your workspace with the underlying file system and prevent the problem.

append to url and refresh page

location.href = location.href + "&parameter=" + value;

How do I install imagemagick with homebrew?

The quickest fix for me was doing the following:

cd /usr/local
git reset --hard FETCH_HEAD

Then I retried brew install imagemagick and it correctly pulled the package from the new mirror, instead of adamv.

If that does not work, ensure that /Library/Caches/Homebrew does not contain any imagemagick files or folders. Delete them if it does.

Try/catch does not seem to have an effect

Adding "-EA Stop" solved this for me.

Count number of times value appears in particular column in MySQL

select email, count(*) as c FROM orders GROUP BY email

SQL Server Convert Varchar to Datetime

Try the below

select Convert(Varchar(50),yourcolumn,103) as Converted_Date from yourtbl

Javascript change font color

You can use the HTML tag in order to apply font size, font color in one line on JavaScript, as well as you can use .fontcolor() method to define color, .fontsize() method to define the font size, .bold() method to define bold, etc. These are called JavaScript Built-in Functions.

  • Here is a list of some JavaScript built-in functions:

    .big()
    .small()
    .italics()
    .fixed()
    .strike()
    .sup()

  • The below built-in functions require parameters:

    .fontsize() //e.g.: the size to be applied in number .fontsize(4)

    .fontcolor("") //e.g.: the color to be applied in string .fontcolor("red")

    .txt.link("") //e.g.: the url to be linkable as string .link("www.test.com")

    .toUpperCase() //e.g.: the converted to uppercase to be applied in string .toUpperCase()

  • Remember the syntax is: string.functionName() e.g.:

    var txt = "Hello World!"; txt.bold();

  • This also can be done in one line:

    var txt = "Hello World!".bold();

    The result will be: Hello World!

  • You can use multiple built-in functions in one line, adding one next to the other. e.g.:

    "10/22/2018".fontcolor("red").fontsize(4).bold()

  • The following is an example how I used it on my JavaScript code to change font (color, size, bold) using both HTML tags and JavaScript functions:

vForm.message = "<HTML><font size = 4 color = 'red'><b> Application Deadline was </b></font></HTML> " + "10/22/2018".fontcolor("red").fontsize(4).bold(); /* setting HTML font color, size, bold and combined them with JavaScript functions to change font color, size, bold in JavaScript code */

  • Here is the result:

Application Deadline was  10/22/2018

How to get the hostname of the docker host from inside a docker container on that host without env vars

Another option that worked for me was to bind the network namespace of the host to the docker.

By adding:

docker run --net host

Using json_encode on objects in PHP (regardless of scope)

I usually include a small function in my objects which allows me to dump to array or json or xml. Something like:

public function exportObj($method = 'a')
{
     if($method == 'j')
     {
         return json_encode(get_object_vars($this));
     }
     else
     {
         return get_object_vars($this);
     }
}

either way, get_object_vars() is probably useful to you.

You don't have write permissions for the /var/lib/gems/2.3.0 directory

Ubuntu 20.04:

Option 1 - set up a gem installation directory for your user account

For bash (for zsh, we would use .zshrc of course)

echo '# Install Ruby Gems to ~/gems' >> ~/.bashrc
echo 'export GEM_HOME="$HOME/gems"' >> ~/.bashrc
echo 'export PATH="$HOME/gems/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc

Option 2 - use snap

Uninstall the apt-version (ruby-full) and reinstall it with snap

sudo apt-get remove ruby
sudo snap install ruby --classic

Multiline TextView in Android?

for me non of the solutions did not work. I know it is not a complete answer for this question, but sometimes it can help.

I put 4 textviews in a vertical linearlayout.

<Linearlayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation:"vertical"

    ...>
    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text:"line1"
       .../>
    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text:"line2"
       .../>
    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text:"line3"
       .../>
    <TextView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text:"line4"
       .../>
</LinearLayout>

This solution is good for cases that the text view text is constant, like labels.

strange error in my Animation Drawable

Looks like whatever is in your Animation Drawable definition is too much memory to decode and sequence. The idea is that it loads up all the items and make them in an array and swaps them in and out of the scene according to the timing specified for each frame.

If this all can't fit into memory, it's probably better to either do this on your own with some sort of handler or better yet just encode a movie with the specified frames at the corresponding images and play the animation through a video codec.

ggplot legends - change labels, order and title

You need to do two things:

  1. Rename and re-order the factor levels before the plot
  2. Rename the title of each legend to the same title

The code:

dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))

library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha = 0.35, linetype=0)+ 
  geom_line(aes(linetype=model), size = 1) +       
  geom_point(aes(shape=model), size=4)  +      
  theme(legend.position=c(.6,0.8)) +
  theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
  scale_linetype_discrete("Model 1") +
  scale_shape_discrete("Model 1") +
  scale_colour_discrete("Model 1")

enter image description here

However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha=0.2, colour=NA)+ 
  geom_line() +       
  geom_point()  +      
  facet_wrap(~model)

enter image description here

How to fix "unable to open stdio.h in Turbo C" error?

First check whether the folder name is right or wrong since while you copying to one folder from other accidently it takes other folder address eg it take C instead of F So from OPTION>DIRECTORY change the folder name

Struct with template variables in C++

The Standard says (at 14/3. For the non-standard folks, the names following a class definition body (or the type in a declaration in general) are "declarators")

In a template-declaration, explicit specialization, or explicit instantiation the init-declarator-list in the dec-laration shall contain at most one declarator. When such a declaration is used to declare a class template, no declarator is permitted.

Do it like Andrey shows.

make script execution to unlimited

You'll have to set it to zero. Zero means the script can run forever. Add the following at the start of your script:

ini_set('max_execution_time', 0);

Refer to the PHP documentation of max_execution_time

Note that:

set_time_limit(0);

will have the same effect.

What is the best Java library to use for HTTP POST, GET etc.?

I want to mention the Ning Async Http Client Library. I've never used it but my colleague raves about it as compared to the Apache Http Client, which I've always used in the past. I was particularly interested to learn it is based on Netty, the high-performance asynchronous i/o framework, with which I am more familiar and hold in high esteem.

How to do a GitHub pull request

In order to make a pull request you need to do the following steps:

  1. Fork a repository (to which you want to make a pull request). Just click the fork button the the repository page and you will have a separate github repository preceded with your github username.
  2. Clone the repository to your local machine. The Github software that you installed on your local machine can do this for you. Click the clone button beside the repository name.
  3. Make local changes/commits to the files
  4. sync the changes
  5. go to your github forked repository and click the "Compare & Review" green button besides the branch button. (The button has icon - no text)
  6. A new page will open showing your changes and then click the pull request link, that will send the request to the original owner of the repository you forked.

It took me a while to figure this, hope this will help someone.

How do I convert a dictionary to a JSON String in C#?

In Asp.net Core use:

using Newtonsoft.Json

var obj = new { MyValue = 1 };
var json = JsonConvert.SerializeObject(obj);
var obj2 = JsonConvert.DeserializeObject(json);

Inline JavaScript onclick function

you can use Self-Executing Anonymous Functions. this code will work:

<a href="#" onClick="(function(){
    alert('Hey i am calling');
    return false;
})();return false;">click here</a>

see JSfiddle

How to get 30 days prior to current date?

If you aren't inclined to momentjs, you can use this:

let x = new Date()

x.toISOString(x.setDate(x.getDate())).slice(0, 10)

Basically it gets the current date (numeric value of date of current month) and then sets the value. Then it converts into ISO format from which I slice down the pure numeric date (i.e. 2019-09-23)

Hope it helps someone.

XML shape drawable not rendering desired color

In drawable I use this xml code to define the border and background:

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
  <stroke android:width="4dp" android:color="#D8FDFB" /> 
  <padding android:left="7dp" android:top="7dp" 
    android:right="7dp" android:bottom="7dp" /> 
  <corners android:radius="4dp" /> 
  <solid android:color="#f0600000"/> 
</shape> 

Check if date is in the past Javascript

_x000D_
_x000D_
$('#datepicker').datepicker().change(evt => {_x000D_
  var selectedDate = $('#datepicker').datepicker('getDate');_x000D_
  var now = new Date();_x000D_
  now.setHours(0,0,0,0);_x000D_
  if (selectedDate < now) {_x000D_
    console.log("Selected date is in the past");_x000D_
  } else {_x000D_
    console.log("Selected date is NOT in the past");_x000D_
  }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>_x000D_
<input type="text" id="datepicker" name="event_date" class="datepicker">
_x000D_
_x000D_
_x000D_

Subset data to contain only columns whose names match a condition

This worked for me:

df[,names(df) %in% colnames(df)[grepl(str,colnames(df))]]

How can I download a file from a URL and save it in Rails?

Check out Net::HTTP in the standard library. The documentation provides several examples on how to download documents using HTTP.

Line Break in HTML Select Option?

You can use a library called select2

You also can look at this Stackoverflow Question & Answer

<select id="selectBox" style="width: 500px">
  <option value="1" data-desc="this is my <br> multiple line 1">option 1</option>
  <option value="2" data-desc="this is my <br> multiple line 2">option 2</option>
</select>

In javascript

$(function(){
  $("#selectBox").select2({
    templateResult: formatDesc
  });

  function formatDesc (opt) {
   var optdesc = $(opt.element).attr('data-desc'); 
    var $opt = $(
      '<div><strong>' + opt.text + '</strong></div><div>' + optdesc + '</div>'
    );
    return $opt;
  };
});

Postman - How to see request with headers and body data with variables substituted

If, like me, you are still using the browser version (which will be deprecated soon), have you tried the "Code" button?

enter image description here

This should generate a snippet which contains the entire request Postman is firing. You can even choose the language for the snippet. I find it quite handy when I need to debug stuff.

Hope this helps.

Preloading CSS Images

When there is no way to modify CSS code and preload images with CSS rules for :before or :after pseudo elements another approach with JavaScript code traversing CSS rules of loaded stylesheets can be used. In order to make it working scripts should be included after stylesheets in HTML, for example, before closing body tag or just after stylesheets.

getUrls() {
    const urlRegExp = /url\(('|")?([^'"()]+)('|")\)?/;

    let urls = [];
    for (let i = 0; i < document.styleSheets.length; i++) {
        let cssRules = document.styleSheets[i].cssRules;
        for (let j = 0; j < cssRules.length; j++) {
            let cssRule = cssRules[j];
            if (!cssRule.selectorText) {
                continue;
            }

            for (let k = 0; k < cssRule.style.length; k++) {
                let property = cssRule.style[k],
                    urlMatch = cssRule.style[property].match(urlRegExp);
                if (urlMatch !== null) {
                    urls.push(urlMatch[2]);
                }
            }
        }
    }
    return urls;
}

preloadImages() {
    return new Promise(resolve => {
        let urls = getUrls(),
            loadedCount = 0;

        const onImageLoad = () => {
            loadedCount++;
            if (urls.length === loadedCount) {
                resolve();
            }
        };

        for (var i = 0; i < urls.length; i++) {
            let image = new Image();
            image.src = urls[i];
            image.onload = onImageLoad;
        }
    });
}

document.addEventListener('DOMContentLoaded', () => {
    preloadImages().then(() => {
        // CSS images are loaded here
    });
});

How to add reference to a method parameter in javadoc?

As you can see in the Java Source of the java.lang.String class:

/**
 * Allocates a new <code>String</code> that contains characters from
 * a subarray of the character array argument. The <code>offset</code>
 * argument is the index of the first character of the subarray and
 * the <code>count</code> argument specifies the length of the
 * subarray. The contents of the subarray are copied; subsequent
 * modification of the character array does not affect the newly
 * created string.
 *
 * @param      value    array that is the source of characters.
 * @param      offset   the initial offset.
 * @param      count    the length.
 * @exception  IndexOutOfBoundsException  if the <code>offset</code>
 *               and <code>count</code> arguments index characters outside
 *               the bounds of the <code>value</code> array.
 */
public String(char value[], int offset, int count) {
    if (offset < 0) {
        throw new StringIndexOutOfBoundsException(offset);
    }
    if (count < 0) {
        throw new StringIndexOutOfBoundsException(count);
    }
    // Note: offset or count might be near -1>>>1.
    if (offset > value.length - count) {
        throw new StringIndexOutOfBoundsException(offset + count);
    }

    this.value = new char[count];
    this.count = count;
    System.arraycopy(value, offset, this.value, 0, count);
}

Parameter references are surrounded by <code></code> tags, which means that the Javadoc syntax does not provide any way to do such a thing. (I think String.class is a good example of javadoc usage).

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

What is a CSRF token? What is its importance and how does it work?

The root of it all is to make sure that the requests are coming from the actual users of the site. A csrf token is generated for the forms and Must be tied to the user's sessions. It is used to send requests to the server, in which the token validates them. This is one way of protecting against csrf, another would be checking the referrer header.

Google drive limit number of download

This limit is indeed not specified, however their TOS mentions that: "FOR EXAMPLE, WE DON’T MAKE ANY COMMITMENTS ABOUT THE CONTENT WITHIN THE SERVICES, THE SPECIFIC FUNCTIONS OF THE SERVICES, OR THEIR RELIABILITY, AVAILABILITY, OR ABILITY TO MEET YOUR NEEDS. WE PROVIDE THE SERVICES “AS IS”. "

This means to me that the download limit is calculated based on a set of factors that describe the user and is subject to change from one to another.

Maybe using the TOR network may help you do your job.

Unicode, UTF, ASCII, ANSI format differences

Going down your list:

  • "Unicode" isn't an encoding, although unfortunately, a lot of documentation imprecisely uses it to refer to whichever Unicode encoding that particular system uses by default. On Windows and Java, this often means UTF-16; in many other places, it means UTF-8. Properly, Unicode refers to the abstract character set itself, not to any particular encoding.
  • UTF-16: 2 bytes per "code unit". This is the native format of strings in .NET, and generally in Windows and Java. Values outside the Basic Multilingual Plane (BMP) are encoded as surrogate pairs. These used to be relatively rarely used, but now many consumer applications will need to be aware of non-BMP characters in order to support emojis.
  • UTF-8: Variable length encoding, 1-4 bytes per code point. ASCII values are encoded as ASCII using 1 byte.
  • UTF-7: Usually used for mail encoding. Chances are if you think you need it and you're not doing mail, you're wrong. (That's just my experience of people posting in newsgroups etc - outside mail, it's really not widely used at all.)
  • UTF-32: Fixed width encoding using 4 bytes per code point. This isn't very efficient, but makes life easier outside the BMP. I have a .NET Utf32String class as part of my MiscUtil library, should you ever want it. (It's not been very thoroughly tested, mind you.)
  • ASCII: Single byte encoding only using the bottom 7 bits. (Unicode code points 0-127.) No accents etc.
  • ANSI: There's no one fixed ANSI encoding - there are lots of them. Usually when people say "ANSI" they mean "the default locale/codepage for my system" which is obtained via Encoding.Default, and is often Windows-1252 but can be other locales.

There's more on my Unicode page and tips for debugging Unicode problems.

The other big resource of code is unicode.org which contains more information than you'll ever be able to work your way through - possibly the most useful bit is the code charts.

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

@GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

@GetMapping is the newer annotaion. It supports consumes

Consume options are :

consumes = "text/plain"
consumes = {"text/plain", "application/*"}

For Further details see: GetMapping Annotation

or read: request mapping variants

RequestMapping supports consumes as well

GetMapping we can apply only on method level and RequestMapping annotation we can apply on class level and as well as on method level

Facebook Javascript SDK Problem: "FB is not defined"

I had the same problem and I've found the cause.

I have avast! antivirus installed in my computer, and it asked me to install the update for chrome plugin. The new avast! plugin for chrome has the functionality to block ads and tracking, and, by default, it blocks the facebook access. I have solved my problem simply allowing facebook in the avast! chrome plugin for the website I needed.

Since this question is very old, I think that some people might have the same cause as me, the new avast! chrome plugin.

Recommended website resolution (width and height)?

Alright, I see alot of misinformation here. For starters, creating a web page using a certain resolution, say 800x600 for example, makes that page render properly using that resolution only! When that same page is displayed on someone else's laptop, or home PC monitor, the page will be displayed using that screen's current resolution, NOT the resolution you used when designing the page. Don't create web pages for one specific resolution! There are too many different aspect ratios and screen resolutions to expect a "one size fits all" scenario, that with web design does not exist. Here's the solution: Use CSS3 Media Queries to create resolution adaptable code. Here's an example:

@media screen and (max-width: 800px) {
styles
}
@media screen and (max-width: 1024px) {
styles
}
@media screen and (max-width: 1280px) {
styles
}

See, what we just did was specify 3 sets of styles that render at different resolutions. In the case of our example, if a screen's resolution is larger than 800px, the CSS for 1024 will be executed instead. Likewise, if the screen displaying the content was 1224px, the 1280 would be executed since 1224 is larger than 1024. The site I'm working on now functions at all resolutions 800x600 to 1920x1080. Another thing to keep in mind is that not all monitors with the same resolution have the same size screens. You could put 15.4 laptops side by side, while both look the same, both could have drastically different resolutions, since not all pixels are the same size on different LCD screens. So, use media queries, and start creating your website with a laptop screen with high resolution, particularly 1280+. Also, create each media query using a different resolution on your laptop. You could use your resolution settings in Windows to adjust down 800x600 and creating a media query at that res, and then switch to 1024x768 and create another media query at that res. I could go on and on, but I think you guys should get the point.

UPDATE: Here's a link to using media queries that will help explain more, Innovative Web Design for Mobile Devices with Media Queries

That tutorial will show you how to design for all devices. There's also tutorials for Media Queries specifically. I developed the entire site to render on all devices, all screens, and all resolutions using no subdomains, and only CSS! I am still working on support for tablets and smart phones. The site renders perfectly on any laptop, or your 50inch LCD TV, and many pages work perfectly on all mobile devices. If you put all your code on page, then your pages will load lightening fast! Also, be sure to pay attention to discussion in that article about the CSS "background-size: cover;" or "contain" properties, they will make your background graphics fluid and able to render perfectly at all resolutions.

Follow the sites tutorials and you can make a single web page that renders on everything and anything!

How to wait until an element is present in Selenium?

Let me recommend you using Selenide library. It allows writing much more concise and readable tests. It can wait for presence of elements with much shorter syntax:

$("#elementId").shouldBe(visible);

Here is a sample project for testing Google search: https://github.com/selenide-examples/google

Pass Array Parameter in SqlCommand

Passing an array of items as a collapsed parameter to the WHERE..IN clause will fail since query will take form of WHERE Age IN ("11, 13, 14, 16").

But you can pass your parameter as an array serialized to XML or JSON:

Using nodes() method:

StringBuilder sb = new StringBuilder();

foreach (ListItem item in ddlAge.Items)
  if (item.Selected)
    sb.Append("<age>" + item.Text + "</age>"); // actually it's xml-ish

sqlComm.CommandText = @"SELECT * from TableA WHERE Age IN (
    SELECT Tab.col.value('.', 'int') as Age from @Ages.nodes('/age') as Tab(col))";
sqlComm.Parameters.Add("@Ages", SqlDbType.NVarChar);
sqlComm.Parameters["@Ages"].Value = sb.ToString();

Using OPENXML method:

using System.Xml.Linq;
...
XElement xml = new XElement("Ages");

foreach (ListItem item in ddlAge.Items)
  if (item.Selected)
    xml.Add(new XElement("age", item.Text);

sqlComm.CommandText = @"DECLARE @idoc int;
    EXEC sp_xml_preparedocument @idoc OUTPUT, @Ages;
    SELECT * from TableA WHERE Age IN (
    SELECT Age from OPENXML(@idoc, '/Ages/age') with (Age int 'text()')
    EXEC sp_xml_removedocument @idoc";
sqlComm.Parameters.Add("@Ages", SqlDbType.Xml);
sqlComm.Parameters["@Ages"].Value = xml.ToString();

That's a bit more on the SQL side and you need a proper XML (with root).

Using OPENJSON method (SQL Server 2016+):

using Newtonsoft.Json;
...
List<string> ages = new List<string>();

foreach (ListItem item in ddlAge.Items)
  if (item.Selected)
    ages.Add(item.Text);

sqlComm.CommandText = @"SELECT * from TableA WHERE Age IN (
    select value from OPENJSON(@Ages))";
sqlComm.Parameters.Add("@Ages", SqlDbType.NVarChar);
sqlComm.Parameters["@Ages"].Value = JsonConvert.SerializeObject(ages);

Note that for the last method you also need to have Compatibility Level at 130+.

How to determine if a list of polygon points are in clockwise order?

This is my solution using the explanations in the other answers:

def segments(poly):
    """A sequence of (x,y) numeric coordinates pairs """
    return zip(poly, poly[1:] + [poly[0]])

def check_clockwise(poly):
    clockwise = False
    if (sum(x0*y1 - x1*y0 for ((x0, y0), (x1, y1)) in segments(poly))) < 0:
        clockwise = not clockwise
    return clockwise

poly = [(2,2),(6,2),(6,6),(2,6)]
check_clockwise(poly)
False

poly = [(2, 6), (6, 6), (6, 2), (2, 2)]
check_clockwise(poly)
True

Bootstrap 3.0 Popovers and tooltips

For some reason the only way I was able to get my code to work is by switching couple of things. If nothing worked for you so far, please give a whirl to this:

$('body').popover({ 
    selector: '[data-toggle="popover"]', 
    trigger: 'hover',
    placement: 'right'
});

How do a LDAP search/authenticate against this LDAP in Java

You can also use the following code :

package com.agileinfotech.bsviewer.ldap;

import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class LDAPLoginAuthentication {
    public LDAPLoginAuthentication() {
        // TODO Auto-generated constructor
    }

    ResourceBundle resBundle = ResourceBundle.getBundle("settings");

    @SuppressWarnings("unchecked")
    public String authenticateUser(String username, String password) {
        String strUrl = "success";
        Hashtable env = new Hashtable(11);
        boolean b = false;
        String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
        env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
        env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
        env.put(Context.SECURITY_CREDENTIALS, password);

        try {
            // Create initial context
            DirContext ctx = new InitialDirContext(env);
            // Close the context when we're done
            b = true;
            ctx.close();

        } catch (NamingException e) {
            b = false;
        } finally {
            if (b) {
                strUrl = "success";
            } else {
                strUrl = "failer";
            }
        }
        return strUrl;
    }
}

Difference between File.separator and slash in paths

Although using File.separator to reference a file name is overkill (for those who imagine far off lands, I imagine their JVM implementation would replace a / with a : just like the windows jvm replaces it with a \).

However, sometimes you are getting the file reference, not creating it, and you need to parse it, and to be able to do that, you need to know the separator on the platform. File.separator helps you do that.

Set the value of a variable with the result of a command in a Windows batch file

Here are two approaches:

@echo off

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "[[=>"#" 2>&1&set/p "&set "]]==<# & del /q # >nul 2>&1" &::
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning chcp command output to %code-page% variable
chcp %[[%code-page%]]%
echo 1: %code-page%

::assigning whoami command output to %its-me% variable
whoami %[[%its-me%]]%
echo 2: %its-me%


::::::::::::::::::::::::::::::::::::::::::::::::::
;;set "{{=for /f "tokens=* delims=" %%# in ('" &::
;;set "--=') do @set ""                        &::
;;set "}}==%%#""                               &::
::::::::::::::::::::::::::::::::::::::::::::::::::

:: --examples

::assigning ver output to %win-ver% variable
%{{% ver %--%win-ver%}}%
echo 3: %win-ver%


::assigning hostname output to %my-host% variable
%{{% hostname %--%my-host%}}%
echo 4: %my-host%

Validating email addresses using jQuery and regex

This is my solution:

function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
    // alert( pattern.test(emailAddress) );
    return pattern.test(emailAddress);
};

Found that RegExp over here: http://mdskinner.com/code/email-regex-and-validation-jquery

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

I know this is an old post, but a good time to use PrimaryKeyColumn would be if you wanted a unidirectional relationship or had multiple tables all sharing the same id.

In general this is a bad idea and it would be better to use foreign key relationships with JoinColumn.

Having said that, if you are working on an older database that used a system like this then that would be a good time to use it.

Getting an error "fopen': This function or variable may be unsafe." when compling

This is a warning for usual. You can either disable it by

#pragma warning(disable:4996)

or simply use fopen_s like Microsoft has intended.

But be sure to use the pragma before other headers.

Downloading a picture via urllib and python

Using requests

import requests
import shutil,os

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
currentDir = os.getcwd()
path = os.path.join(currentDir,'Images')#saving images to Images folder

def ImageDl(url):
    attempts = 0
    while attempts < 5:#retry 5 times
        try:
            filename = url.split('/')[-1]
            r = requests.get(url,headers=headers,stream=True,timeout=5)
            if r.status_code == 200:
                with open(os.path.join(path,filename),'wb') as f:
                    r.raw.decode_content = True
                    shutil.copyfileobj(r.raw,f)
            print(filename)
            break
        except Exception as e:
            attempts+=1
            print(e)

if __name__ == '__main__':
    ImageDl(url)

How to execute multiple commands in a single line

Googling gives me this:


Command A & Command B

Execute Command A, then execute Command B (no evaluation of anything)


Command A | Command B

Execute Command A, and redirect all its output into the input of Command B


Command A && Command B

Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B


Command A || Command B

Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B


How to set enum to null

Color? color = null;

or you can use

Color? color = new Color?();

example where assigning null wont work

color = x == 5 ? Color.Red : x == 9 ? Color.Black : null ; 

so you can use :

 color = x == 5 ? Color.Red : x == 9 ? Color.Black : new Color?(); 

Save and load MemoryStream to/from a file

You may use MemoryStream.WriteTo or Stream.CopyTo (supported in framework version 4.5.2, 4.5.1, 4.5, 4) methods to write content of memory stream to another stream.

memoryStream.WriteTo(fileStream);

Update:

fileStream.CopyTo(memoryStream);
memoryStream.CopyTo(fileStream);

How do I view the Explain Plan in Oracle Sql developer?

Explain only shows how the optimizer thinks the query will execute.

To show the real plan, you will need to run the sql once. Then use the same session run the following:

@yoursql 
select * from table(dbms_xplan.display_cursor()) 

This way can show the real plan used during execution. There are several other ways in showing plan using dbms_xplan. You can Google with term "dbms_xplan".

Getting last day of the month in a given string date

Java 8 and above:

import java.time.LocalDate;
import java.time.Year;

static int lastDayOfMonth(int Y, int M) {
    return LocalDate.of(Y, M, 1).getMonth().length(Year.of(Y).isLeap());
}

subject to Basil Bourque's comment

import java.time.YearMonth;

int lastDayOfMonth = YearMonth.of(Y, M).lengthOfMonth();

Get JSONArray without array name?

JSONArray has a constructor which takes a String source (presumed to be an array).

So something like this

JSONArray array = new JSONArray(yourJSONArrayAsString);

ALTER TABLE on dependent column

you can drop the Constraint which is restricting you. If the column has access to other table. suppose a view is accessing the column which you are altering then it wont let you alter the column unless you drop the view. and after making changes you can recreate the view.

enter image description here

How to stretch div height to fill parent div - CSS

B2 container position relative

Top position B2 + of remaining height

Height of B2 + height B1 or remaining height

Where is shared_ptr?

There are at least three places where you may find shared_ptr:

  1. If your C++ implementation supports C++11 (or at least the C++11 shared_ptr), then std::shared_ptr will be defined in <memory>.

  2. If your C++ implementation supports the C++ TR1 library extensions, then std::tr1::shared_ptr will likely be in <memory> (Microsoft Visual C++) or <tr1/memory> (g++'s libstdc++). Boost also provides a TR1 implementation that you can use.

  3. Otherwise, you can obtain the Boost libraries and use boost::shared_ptr, which can be found in <boost/shared_ptr.hpp>.

difference between System.out.println() and System.err.println()

System.out.println("wassup"); refers to when you have to output a certain result pertaining to the proper input given by the user whereas System.err.println("duh, that's wrong); is a reference to show that the input provided is wrong or there is some other error.

Most of the IDEs show this in red color (System.err.print).

How can I get form data with JavaScript/jQuery?

I wrote a function that takes care of multiple checkboxes and multiple selects. In those cases it returns an array.

function getFormData(formId) {
    return $('#' + formId).serializeArray().reduce(function (obj, item) {
        var name = item.name,
            value = item.value;

        if (obj.hasOwnProperty(name)) {
            if (typeof obj[name] == "string") {
                obj[name] = [obj[name]];
                obj[name].push(value);
            } else {
                obj[name].push(value);
            }
        } else {
            obj[name] = value;
        }
        return obj;
    }, {});
}

How to create a md5 hash of a string in C?

All of the existing answers use the deprecated MD5Init(), MD5Update(), and MD5Final().

Instead, use EVP_DigestInit_ex(), EVP_DigestUpdate(), and EVP_DigestFinal_ex(), e.g.

// example.c
//
// gcc example.c -lssl -lcrypto -o example

#include <openssl/evp.h>
#include <stdio.h>
#include <string.h>

void bytes2md5(const char *data, int len, char *md5buf) {
  // Based on https://www.openssl.org/docs/manmaster/man3/EVP_DigestUpdate.html
  EVP_MD_CTX *mdctx = EVP_MD_CTX_new();
  const EVP_MD *md = EVP_md5();
  unsigned char md_value[EVP_MAX_MD_SIZE];
  unsigned int md_len, i;
  EVP_DigestInit_ex(mdctx, md, NULL);
  EVP_DigestUpdate(mdctx, data, len);
  EVP_DigestFinal_ex(mdctx, md_value, &md_len);
  EVP_MD_CTX_free(mdctx);
  for (i = 0; i < md_len; i++) {
    snprintf(&(md5buf[i * 2]), 16 * 2, "%02x", md_value[i]);
  }
}

int main(void) {
  const char *hello = "hello";
  char md5[33]; // 32 characters + null terminator
  bytes2md5(hello, strlen(hello), md5);
  printf("%s\n", md5);
}

Resource u'tokenizers/punkt/english.pickle' not found

I got the solution:

import nltk
nltk.download()

once the NLTK Downloader starts

d) Download l) List u) Update c) Config h) Help q) Quit

Downloader> d

Download which package (l=list; x=cancel)? Identifier> punkt

Imply bit with constant 1 or 0 in SQL Server

cast (
  case
    when FC.CourseId is not null then 1 else 0
  end
as bit)

The CAST spec is "CAST (expression AS type)". The CASE is an expression in this context.

If you have multiple such expressions, I'd declare bit vars @true and @false and use them. Or use UDFs if you really wanted...

DECLARE @True bit, @False bit;
SELECT @True = 1, @False = 0;  --can be combined with declare in SQL 2008

SELECT
    case when FC.CourseId is not null then @True ELSE @False END AS ...

How can I jump to class/method definition in Atom text editor?

For Typescript users, the "atom-typescript" package adds a typescript aware symbols view, you can trigger it with Cmd+R, and it works great to jump to methods-

https://atom.io/packages/atom-typescript#alternative-to-symbols-view

powershell is missing the terminator: "

Look closely at the two dashes in

unzipRelease –Src '$ReleaseFile' -Dst '$Destination'

This first one is not a normal dash but an en-dash (&ndash; in HTML). Replace that with the dash found before Dst.

Find all elements with a certain attribute value in jquery

Use string concatenation. Try this:

$('div[imageId="'+imageN +'"]').each(function() {
    $(this);   
});

How can I show current location on a Google Map on Android Marshmallow?

For using FusedLocationProviderClient with Google Play Services 11 and higher:

see here: How to get current Location in GoogleMap using FusedLocationProviderClient

For using (now deprecated) FusedLocationProviderApi:

If your project uses Google Play Services 10 or lower, using the FusedLocationProviderApi is the optimal choice.

The FusedLocationProviderApi offers less battery drain than the old open source LocationManager API. Also, if you're already using Google Play Services for Google Maps, there's no reason not to use it.

Here is a full Activity class that places a Marker at the current location, and also moves the camera to the current position.

It also checks for the Location permission at runtime for Android 6 and later (Marshmallow, Nougat, Oreo). In order to properly handle the Location permission runtime check that is necessary on Android M/Android 6 and later, you need to ensure that the user has granted your app the Location permission before calling mGoogleMap.setMyLocationEnabled(true) and also before requesting location updates.

public class MapLocationActivity extends AppCompatActivity
        implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    GoogleMap mGoogleMap;
    SupportMapFragment mapFrag;
    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    Marker mCurrLocationMarker;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportActionBar().setTitle("Map Location Activity");

        mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFrag.getMapAsync(this);
    }

    @Override
    public void onPause() {
        super.onPause();

        //stop location updates when Activity is no longer active
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mGoogleMap=googleMap;
        mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                buildGoogleApiClient();
                mGoogleMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        }
        else {
            buildGoogleApiClient();
            mGoogleMap.setMyLocationEnabled(true);
        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {}

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {}

    @Override
    public void onLocationChanged(Location location)
    {
        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        //Place current location marker
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
        mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);

        //move map camera
        mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,11));

    }

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle("Location Permission Needed")
                        .setMessage("This app needs the Location permission, please accept to use location functionality")
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MapLocationActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION );
                            }
                        })
                        .create()
                        .show();


            } else {
                // No explanation needed, we can request the permission.
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        MY_PERMISSIONS_REQUEST_LOCATION );
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        if (mGoogleApiClient == null) {
                            buildGoogleApiClient();
                        }
                        mGoogleMap.setMyLocationEnabled(true);
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <fragment xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:map="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/map"
        tools:context=".MapLocationActivity"
        android:name="com.google.android.gms.maps.SupportMapFragment"/>

</LinearLayout>

Result:

Show permission explanation if needed using an AlertDialog (this happens if the user denies a permission request, or grants the permission and then later revokes it in the settings):

enter image description here

Prompt the user for Location permission by calling ActivityCompat.requestPermissions():

enter image description here

Move camera to current location and place Marker when the Location permission is granted:

enter image description here

difference between throw and throw new Exception()

Throw; Rethrow the original exception and keep the exception type.

Throw new exception(); Rethrow the original exception type and reset the exception stack trace

Throw ex; Reset the exception stack trace and reset the exception type

Why does using an Underscore character in a LIKE filter give me all the results?

Modify your WHERE condition like this:

WHERE mycolumn LIKE '%\_%' ESCAPE '\'

This is one of the ways in which Oracle supports escape characters. Here you define the escape character with the escape keyword. For details see this link on Oracle Docs.

The '_' and '%' are wildcards in a LIKE operated statement in SQL.

The _ character looks for a presence of (any) one single character. If you search by columnName LIKE '_abc', it will give you result with rows having 'aabc', 'xabc', '1abc', '#abc' but NOT 'abc', 'abcc', 'xabcd' and so on.

The '%' character is used for matching 0 or more number of characters. That means, if you search by columnName LIKE '%abc', it will give you result with having 'abc', 'aabc', 'xyzabc' and so on, but no 'xyzabcd', 'xabcdd' and any other string that does not end with 'abc'.

In your case you have searched by '%_%'. This will give all the rows with that column having one or more characters, that means any characters, as its value. This is why you are getting all the rows even though there is no _ in your column values.

How do you print in a Go test using the "testing" package?

t.Log and t.Logf do print out in your test but can often be missed as it prints on the same line as your test. What I do is Log them in a way that makes them stand out, ie

t.Run("FindIntercomUserAndReturnID should find an intercom user", func(t *testing.T) {

    id, err := ic.FindIntercomUserAndReturnID("[email protected]")
    assert.Nil(t, err)
    assert.NotNil(t, id)

    t.Logf("\n\nid: %v\n\n", *id)
})

which prints it to the terminal as,

=== RUN   TestIntercom
=== RUN   TestIntercom/FindIntercomUserAndReturnID_should_find_an_intercom_user
    TestIntercom/FindIntercomUserAndReturnID_should_find_an_intercom_user: intercom_test.go:34:

        id: 5ea8caed05a4862c0d712008

--- PASS: TestIntercom (1.45s)
    --- PASS: TestIntercom/FindIntercomUserAndReturnID_should_find_an_intercom_user (1.45s)
PASS
ok      github.com/RuNpiXelruN/third-party-delete-service   1.470s

How can we redirect a Java program console output to multiple files?

To solve the problem I use ${string_prompt} variable. It shows a input dialog when application runs. I can set the date/time manually at that dialog.

  1. Move cursor at the end of file path. enter image description here

  2. Click variables and select string_prompt enter image description here

  3. Select Apply and Run enter image description here enter image description here

Android Imagebutton change Image OnClick

To switch between different images when the ImageButton is clicked I used a boolean like this:

ImageButton imageButton;
boolean buttonOn;

imageButton.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         if (!buttonOn) {
             buttonOn = true;
             imageButton.setBackground(getResources().getDrawable(R.drawable.button_is_on)); 
         } else {
             buttonOn = false;
             imageButton.setBackground(getResources().getDrawable(R.drawable.button_is_off));
         }
     }
});

What does the arrow operator, '->', do in Java?

I believe, this arrow exists because of your IDE. IntelliJ IDEA does such thing with some code. This is called code folding. You can click at the arrow to expand it.

IF a cell contains a string

You can use OR() to group expressions (as well as AND()):

=IF(OR(condition1, condition2), true, false)

=IF(AND(condition1, condition2), true, false)

So if you wanted to test for "cat" and "22":

=IF(AND(SEARCH("cat",a1),SEARCH("22",a1)),"cat and 22","none")

Convert Long into Integer

long visitors =1000;

int convVisitors =(int)visitors;

Is there a java setting for disabling certificate validation?

It is very simple .In my opinion it is the best way for everyone

       Unirest.config().verifySsl(false);
       HttpResponse<String> response = null;
       try {
           Gson gson = new Gson();
           response = Unirest.post("your_api_url")
                   .header("Authorization", "Basic " + "authkey")
                   .header("Content-Type", "application/json")
                   .body("request_body")
                   .asString();
           System.out.println("------RESPONSE -------"+ gson.toJson(response.getBody()));
       } catch (Exception e) {
           System.out.println("------RESPONSE ERROR--");
           e.printStackTrace();
       }
   }

Get div height with plain JavaScript

Another option is to use the getBoundingClientRect function. Please note that getBoundingClientRect will return an empty rect if the element's display is 'none'.

Example:

var elem = document.getElementById("myDiv");
if(elem) {
  var rect = elem.getBoundingClientRect();
  console.log("height: " + rect.height);  
}

UPDATE: Here is the same code written in 2020:

const elem = document.querySelector("#myDiv");
if(elem) {
  const rect = elem.getBoundingClientRect();
  console.log(`height: ${rect.height}`);
}

Most efficient T-SQL way to pad a varchar on the left to a certain length?

I have one function that lpad with x decimals: CREATE FUNCTION [dbo].[LPAD_DEC] ( -- Add the parameters for the function here @pad nvarchar(MAX), @string nvarchar(MAX), @length int, @dec int ) RETURNS nvarchar(max) AS BEGIN -- Declare the return variable here DECLARE @resp nvarchar(max)

IF LEN(@string)=@length
BEGIN
    IF CHARINDEX('.',@string)>0
    BEGIN
        SELECT @resp = CASE SIGN(@string)
            WHEN -1 THEN
                -- Nros negativos grandes con decimales
                concat('-',SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec)))
            ELSE
                -- Nros positivos grandes con decimales
                concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(@string,@length,@dec)))                  
            END
    END
    ELSE
    BEGIN
        SELECT @resp = CASE SIGN(@string)
            WHEN -1 THEN
                --Nros negativo grande sin decimales
                concat('-',SUBSTRING(replicate(@pad,@length),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))
            ELSE
                -- Nros positivos grandes con decimales
                concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(@string,@length,@dec)))                  
            END                     
    END
END
ELSE
    IF CHARINDEX('.',@string)>0
    BEGIN
        SELECT @resp =CASE SIGN(@string)
            WHEN -1 THEN
                -- Nros negativos con decimales
                concat('-',SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec)))
            ELSE
                --Ntos positivos con decimales
                concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec))) 
            END
    END
    ELSE
    BEGIN
        SELECT @resp = CASE SIGN(@string)
            WHEN -1 THEN
                -- Nros Negativos sin decimales
                concat('-',SUBSTRING(replicate(@pad,@length-3),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))
            ELSE
                -- Nros Positivos sin decimales
                concat(SUBSTRING(replicate(@pad,@length),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))
            END
    END
RETURN @resp

END

Vertical Text Direction

h1{word-break:break-all;display:block;width:40px;} 

H E L L O

NOTE: Browser Supported - IE browser (8,9,10,11) - Firefox browser (38,39,40,41,42,43,44) - Chrome browser (44,45,46,47,48) - Safari browser (8,9) - Opera browser (Not Supported) - Android browser (44)

How do I pipe a subprocess call to a text file?

You could also just call the script from the terminal, outputting everything to a file, if that helps. This way:

$ /path/to/the/script.py > output.txt

This will overwrite the file. You can use >> to append to it.

If you want errors to be logged in the file as well, use &>> or &>.

How to change text and background color?

There is no (standard) cross-platform way to do this. On windows, try using conio.h. It has the:

textcolor(); // and
textbackground();

functions.

For example:

textcolor(RED);
cprintf("H");
textcolor(BLUE);
cprintf("e");
// and so on.

Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4

org.apache.maven.plugins:maven-source-plugin does not exist in the repository http://repo.maven.apache.org/maven2.

You have to download it from Maven central where it exists => maven-source-plugin

Verify your pom definition or your settings.xml file.

Why is my toFixed() function not working?

I tried function toFixed(2) many times. Every time console shows "toFixed() is not a function".

but how I resolved is By using Math.round()

eg:

if ($(this).attr('name') == 'time') {
    var value = parseFloat($(this).val());
    value = Math.round(value*100)/100; // 10 defines 1 decimals, 100 for 2, 1000 for 3
    alert(value);
}

this thing surely works for me and it might help you guys too...

How to update Pandas from Anaconda and is it possible to use eclipse with this last

The answer above did not work for me (python 3.6, Anaconda, pandas 0.20.3). It worked with

conda install -c anaconda pandas 

Unfortunately I do not know how to help with Eclipse.

ASP.NET Web API : Correct way to return a 401/unauthorised response

Just return the following:

return Unauthorized();

Create a new TextView programmatically then display it below another TextView

Try this code:

final String[] str = {"one","two","three","asdfgf"};
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
final TextView[] tv = new TextView[10];

for (int i=0; i<str.length; i++)
{
    tv[i] = new TextView(this); 
    RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams
         ((int)LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT);
    params.leftMargin = 50;
    params.topMargin  = i*50;
    tv[i].setText(str[i]);
    tv[i].setTextSize((float) 20);
    tv[i].setPadding(20, 50, 20, 50);
    tv[i].setLayoutParams(params);
    rl.addView(tv[i]);  
}

ggplot2 line chart gives "geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?"

You get this error because one of your variables is actually a factor variable . Execute

str(df) 

to check this. Then do this double variable change to keep the year numbers instead of transforming into "1,2,3,4" level numbers:

df$year <- as.numeric(as.character(df$year))

EDIT: it appears that your data.frame has a variable of class "array" which might cause the pb. Try then:

df <- data.frame(apply(df, 2, unclass))

and plot again?

Find everything between two XML tags with RegEx

It is not good to use this method but if you really want to split it with regex

<primaryAddress.*>((.|\n)*?)<\/primaryAddress>

the verified answer returns the tags but this just return the value between tags.

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

Here is how the default implementation (ASP.NET Framework or ASP.NET Core) works. It uses a Key Derivation Function with random salt to produce the hash. The salt is included as part of the output of the KDF. Thus, each time you "hash" the same password you will get different hashes. To verify the hash the output is split back to the salt and the rest, and the KDF is run again on the password with the specified salt. If the result matches to the rest of the initial output the hash is verified.

Hashing:

public static string HashPassword(string password)
{
    byte[] salt;
    byte[] buffer2;
    if (password == null)
    {
        throw new ArgumentNullException("password");
    }
    using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, 0x10, 0x3e8))
    {
        salt = bytes.Salt;
        buffer2 = bytes.GetBytes(0x20);
    }
    byte[] dst = new byte[0x31];
    Buffer.BlockCopy(salt, 0, dst, 1, 0x10);
    Buffer.BlockCopy(buffer2, 0, dst, 0x11, 0x20);
    return Convert.ToBase64String(dst);
}

Verifying:

public static bool VerifyHashedPassword(string hashedPassword, string password)
{
    byte[] buffer4;
    if (hashedPassword == null)
    {
        return false;
    }
    if (password == null)
    {
        throw new ArgumentNullException("password");
    }
    byte[] src = Convert.FromBase64String(hashedPassword);
    if ((src.Length != 0x31) || (src[0] != 0))
    {
        return false;
    }
    byte[] dst = new byte[0x10];
    Buffer.BlockCopy(src, 1, dst, 0, 0x10);
    byte[] buffer3 = new byte[0x20];
    Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
    using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
    {
        buffer4 = bytes.GetBytes(0x20);
    }
    return ByteArraysEqual(buffer3, buffer4);
}

How to write oracle insert script with one field as CLOB?

Keep in mind that SQL strings can not be larger than 4000 bytes, while Pl/SQL can have strings as large as 32767 bytes. see below for an example of inserting a large string via an anonymous block which I believe will do everything you need it to do.

note I changed the varchar2(32000) to CLOB

set serveroutput ON 
CREATE TABLE testclob 
  ( 
     id NUMBER, 
     c  CLOB, 
     d  VARCHAR2(4000) 
  ); 

DECLARE 
    reallybigtextstring CLOB := '123'; 
    i                   INT; 
BEGIN 
    WHILE Length(reallybigtextstring) <= 60000 LOOP 
        reallybigtextstring := reallybigtextstring 
                               || '000000000000000000000000000000000'; 
    END LOOP; 

    INSERT INTO testclob 
                (id, 
                 c, 
                 d) 
    VALUES     (0, 
                reallybigtextstring, 
                'done'); 

    dbms_output.Put_line('I have finished inputting your clob: ' 
                         || Length(reallybigtextstring)); 
END; 

/ 
SELECT * 
FROM   testclob; 


 "I have finished inputting your clob: 60030"

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

You can use less code, writing this:

    $users = DB::table('really_long_table_name')
       ->get(array('really_long_table_name.field_very_long_name as short_name'));

And of course if you want to select more fields, just write a "," and add more:

 $users = DB::table('really_long_table_name')
       ->get(array('really_long_table_name.field_very_long_name as short_name', 'really_long_table_name.another_field as other', 'and_another'));

This is very practical when you use a joins complex query

Python: tf-idf-cosine: to find document similarity

This should help you.

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity  

tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(train_set)
print tfidf_matrix
cosine = cosine_similarity(tfidf_matrix[length-1], tfidf_matrix)
print cosine

and output will be:

[[ 0.34949812  0.81649658  1.        ]]

Calling async method synchronously

Most of the answers on this thread are either complex or will result in deadlock.

Following method is simple and it will avoid deadlock because we are waiting for the task to finish and only then getting its result-

var task = Task.Run(() => GenerateCodeAsync()); 
task.Wait();
string code = task.Result;

Furthermore, here is a reference to MSDN article that talks about exactly same thing- https://blogs.msdn.microsoft.com/jpsanders/2017/08/28/asp-net-do-not-use-task-result-in-main-context/

How to get the CPU Usage in C#?

A little more than was requsted but I use the extra timer code to track and alert if CPU usage is 90% or higher for a sustained period of 1 minute or longer.

public class Form1
{

    int totalHits = 0;

    public object getCPUCounter()
    {

        PerformanceCounter cpuCounter = new PerformanceCounter();
        cpuCounter.CategoryName = "Processor";
        cpuCounter.CounterName = "% Processor Time";
        cpuCounter.InstanceName = "_Total";

                     // will always start at 0
        dynamic firstValue = cpuCounter.NextValue();
        System.Threading.Thread.Sleep(1000);
                    // now matches task manager reading
        dynamic secondValue = cpuCounter.NextValue();

        return secondValue;

    }


    private void Timer1_Tick(Object sender, EventArgs e)
    {
        int cpuPercent = (int)getCPUCounter();
        if (cpuPercent >= 90)
        {
            totalHits = totalHits + 1;
            if (totalHits == 60)
            {
                Interaction.MsgBox("ALERT 90% usage for 1 minute");
                totalHits = 0;
            }                        
        }
        else
        {
            totalHits = 0;
        }
        Label1.Text = cpuPercent + " % CPU";
        //Label2.Text = getRAMCounter() + " RAM Free";
        Label3.Text = totalHits + " seconds over 20% usage";
    }
}

Easy way of running the same junit test over and over?

With IntelliJ, you can do this from the test configuration. Once you open this window, you can choose to run the test any number of times you want,.

enter image description here

when you run the test, intellij will execute all tests you have selected for the number of times you specified.

Example running 624 tests 10 times: enter image description here

Check if table exists and if it doesn't exist, create it in SQL Server 2008

Let us create a sample database with a table by the below script:

CREATE DATABASE Test
GO
USE Test
GO
CREATE TABLE dbo.tblTest (Id INT, Name NVARCHAR(50))

Approach 1: Using INFORMATION_SCHEMA.TABLES view

We can write a query like below to check if a tblTest Table exists in the current database.

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = N'tblTest')
BEGIN
  PRINT 'Table Exists'
END

The above query checks the existence of the tblTest table across all the schemas in the current database. Instead of this if you want to check the existence of the Table in a specified Schema and the Specified Database then we can write the above query as below:

IF EXISTS (SELECT * FROM Test.INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = N'dbo'  AND TABLE_NAME = N'tblTest')
BEGIN
  PRINT 'Table Exists'
END

Pros of this Approach: INFORMATION_SCHEMA views are portable across different RDBMS systems, so porting to different RDBMS doesn’t require any change.

Approach 2: Using OBJECT_ID() function

We can use OBJECT_ID() function like below to check if a tblTest Table exists in the current database.

IF OBJECT_ID(N'dbo.tblTest', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END

Specifying the Database Name and Schema Name parts for the Table Name is optional. But specifying Database Name and Schema Name provides an option to check the existence of the table in the specified database and within a specified schema, instead of checking in the current database across all the schemas. The below query shows that even though the current database is MASTER database, we can check the existence of the tblTest table in the dbo schema in the Test database.

USE MASTER
GO
IF OBJECT_ID(N'Test.dbo.tblTest', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END

Pros: Easy to remember. One other notable point to mention about OBJECT_ID() function is: it provides an option to check the existence of the Temporary Table which is created in the current connection context. All other Approaches checks the existence of the Temporary Table created across all the connections context instead of just the current connection context. Below query shows how to check the existence of a Temporary Table using OBJECT_ID() function:

CREATE TABLE #TempTable(ID INT)
GO
IF OBJECT_ID(N'TempDB.dbo.#TempTable', N'U') IS NOT NULL
BEGIN
  PRINT 'Table Exists'
END
GO

Approach 3: Using sys.Objects Catalog View

We can use the Sys.Objects catalog view to check the existence of the Table as shown below:

IF EXISTS(SELECT 1 FROM sys.Objects WHERE  Object_id = OBJECT_ID(N'dbo.tblTest') AND Type = N'U')
BEGIN
  PRINT 'Table Exists'
END

Approach 4: Using sys.Tables Catalog View

We can use the Sys.Tables catalog view to check the existence of the Table as shown below:

IF EXISTS(SELECT 1 FROM sys.Tables WHERE  Name = N'tblTest' AND Type = N'U')
BEGIN
  PRINT 'Table Exists'
END

Sys.Tables catalog view inherits the rows from the Sys.Objects catalog view, Sys.objects catalog view is referred to as base view where as sys.Tables is referred to as derived view. Sys.Tables will return the rows only for the Table objects whereas Sys.Object view apart from returning the rows for table objects, it returns rows for the objects like: stored procedure, views etc.

Approach 5: Avoid Using sys.sysobjects System table

We should avoid using sys.sysobjects System Table directly, direct access to it will be deprecated in some future versions of the Sql Server. As per [Microsoft BOL][1] link, Microsoft is suggesting to use the catalog views sys.objects/sys.tables instead of sys.sysobjects system table directly.

IF EXISTS(SELECT name FROM sys.sysobjects WHERE Name = N'tblTest' AND xtype = N'U')
BEGIN
  PRINT 'Table Exists'
END

Reference: http://sqlhints.com/2014/04/13/how-to-check-if-a-table-exists-in-sql-server/

How to fetch Java version using single line command in Linux

Getting only the "major" build #:

java -version 2>&1 | head -n 1 | awk -F'["_.]' '{print $3}'

Getting multiple values with scanf()

Passable for getting multiple values with scanf()

int r,m,v,i,e,k;

scanf("%d%d%d%d%d%d",&r,&m,&v,&i,&e,&k);