Programs & Examples On #Databound lists

Right pad a string with variable number of spaces

Based on KMier's answer, addresses the comment that this method poses a problem when the field to be padded is not a field, but the outcome of a (possibly complicated) function; the entire function has to be repeated.

Also, this allows for padding a field to the maximum length of its contents.

WITH
cte AS (
  SELECT 'foo' AS value_to_be_padded
  UNION SELECT 'foobar'
),
cte_max AS (
  SELECT MAX(LEN(value_to_be_padded)) AS max_len
)
SELECT
  CONCAT(SPACE(max_len - LEN(value_to_be_padded)), value_to_be_padded AS left_padded,
  CONCAT(value_to_be_padded, SPACE(max_len - LEN(value_to_be_padded)) AS right_padded;

No ConcurrentList<T> in .Net 4.0?

ConcurrentList (as a resizeable array, not a linked list) is not easy to write with nonblocking operations. Its API doesn't translate well to a "concurrent" version.

How to create a Multidimensional ArrayList in Java?

Credit goes for JAcob Tomao for the code. I only added some comments to help beginners like me understand it. I hope it helps.

// read about Generic Types In Java & the use of class<T,...> syntax
// This class will Allow me to create 2D Arrays that do not have fixed sizes    
class TwoDimArrayList<T> extends ArrayList<ArrayList<T>> {
    public void addToInnerArray(int index, T element) {
        while (index >= this.size()) {
            // Create enough Arrays to get to position = index
            this.add(new ArrayList<T>()); // (as if going along Vertical axis)
        }
        // this.get(index) returns the Arraylist instance at the "index" position
        this.get(index).add(element); // (as if going along Horizontal axis)
    }

    public void addToInnerArray(int index, int index2, T element) {
        while (index >= this.size()) {
            this.add(new ArrayList<T>());// (as if going along Vertical
        }
        //access the inner ArrayList at the "index" position.
        ArrayList<T> inner = this.get(index);
        while (index2 >= inner.size()) {
            //add enough positions containing "null" to get to the position index 2 ..
            //.. within the inner array. (if the requested position is too far)
            inner.add(null); // (as if going along Horizontal axis)
        }
        //Overwrite "null" or "old_element" with the new "element" at the "index 2" ..
        //.. position of the chosen(index) inner ArrayList
        inner.set(index2, element); // (as if going along Horizontal axis)
    }
}

How to auto-indent code in the Atom editor?

This works for me:

'atom-workspace atom-text-editor':
    'ctrl-alt-a': 'editor:auto-indent'

You have to select all with ctrl-a first.

Bash scripting missing ']'

add a space before the close bracket

How to use Class<T> in Java?

Following on @Kire Haglin's answer, a further example of generics methods can be seen in the documentation for JAXB unmarshalling:

public <T> T unmarshal( Class<T> docClass, InputStream inputStream )
         throws JAXBException {
  String packageName = docClass.getPackage().getName();
  JAXBContext jc = JAXBContext.newInstance( packageName );
  Unmarshaller u = jc.createUnmarshaller();
  JAXBElement<T> doc = (JAXBElement<T>)u.unmarshal( inputStream );
  return doc.getValue();
}

This allows unmarshal to return a document of an arbitrary JAXB content tree type.

jQuery plugin returning "Cannot read property of undefined"

Usually that problem is that in the last iteration you have an empty object or undefine object. use console.log() inside you cicle to check that this doent happend.

Sometimes a prototype in some place add an extra element.

How to create a GUID/UUID in Python

This function is fully configurable and generates unique uid based on the format specified

eg:- [8, 4, 4, 4, 12] , this is the format mentioned and it will generate the following uuid

LxoYNyXe-7hbQ-caJt-DSdU-PDAht56cMEWi

 import random as r

 def generate_uuid():
        random_string = ''
        random_str_seq = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
        uuid_format = [8, 4, 4, 4, 12]
        for n in uuid_format:
            for i in range(0,n):
                random_string += str(random_str_seq[r.randint(0, len(random_str_seq) - 1)])
            if n != 12:
                random_string += '-'
        return random_string

Set a request header in JavaScript

@gnarf answer is right . wanted to add more information .

Mozilla Bug Reference : https://bugzilla.mozilla.org/show_bug.cgi?id=627942

Terminate these steps if header is a case-insensitive match for one of the following headers:

Accept-Charset
Accept-Encoding
Access-Control-Request-Headers
Access-Control-Request-Method
Connection
Content-Length
Cookie
Cookie2
Date
DNT
Expect
Host
Keep-Alive
Origin
Referer
TE
Trailer
Transfer-Encoding
Upgrade
User-Agent
Via

Source : https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-setrequestheader

Reading from file using read() function

fgets would work for you. here is very good documentation on this :-
http://www.cplusplus.com/reference/cstdio/fgets/

If you don't want to use fgets, following method will work for you :-

int readline(FILE *f, char *buffer, size_t len)
{
   char c; 
   int i;

   memset(buffer, 0, len);

   for (i = 0; i < len; i++)
   {   
      int c = fgetc(f); 

      if (!feof(f)) 
      {   
         if (c == '\r')
            buffer[i] = 0;
         else if (c == '\n')
         {   
            buffer[i] = 0;

            return i+1;
         }   
         else
            buffer[i] = c; 
      }   
      else
      {   
         //fprintf(stderr, "read_line(): recv returned %d\n", c);
         return -1; 
      }   
   }   

   return -1; 
}

Removing elements from an array in C

There are really two separate issues. The first is keeping the elements of the array in proper order so that there are no "holes" after removing an element. The second is actually resizing the array itself.

Arrays in C are allocated as a fixed number of contiguous elements. There is no way to actually remove the memory used by an individual element in the array but the elements can be shifted to fill the hole made by removing an element. For example:

void remove_element(array_type *array, int index, int array_length)
{
   int i;
   for(i = index; i < array_length - 1; i++) array[i] = array[i + 1];
}

Statically allocated arrays can not be resized. Dynamically allocated arrays can be resized with realloc(). This will potentially move the entire array to another location in memory, so all pointers to the array or to its elements will have to be updated. For example:

remove_element(array, index, array_length);  /* First shift the elements, then reallocate */
array_type *tmp = realloc(array, (array_length - 1) * sizeof(array_type) );
if (tmp == NULL && array_length > 1) {
   /* No memory available */
   exit(EXIT_FAILURE);
}
array_length = array_length - 1;
array = tmp;

realloc will return a NULL pointer if the requested size is 0, or if there is an error. Otherwise it returns a pointer to the reallocated array. The temporary pointer is used to detect errors when calling realloc because instead of exiting it is also possible to just leave the original array as it was. When realloc fails to reallocate an array it does not alter the original array.

Note that both of these operations will be fairly slow if the array is large or if a lot of elements are removed. There are other data structures like linked lists and hashes that can be used if efficient insertion and deletion is a priority.

How to fix ReferenceError: primordials is not defined in node

For anyone having same error for the same reason in ADOS CI Build:

This question was the first I found when looking for help. I have an ADOS CI build pipeline where first Node.js tool installer task is used to install Node. Then npm task is used to install gulp (npm install -g gulp). Then the following Gulp task runs default-task from gulpfile.js. There's some gulp-sass stuff in it.

When I changed the Node.js tool to install 12.x latest node instead of an older one and the latest gulp version was 4.0.2. The result was the same error as described in the question.

What worked for me in this case was to downgrade node.js to latest 11.x version as was already suggested by Alphonse R. Dsouza and Aymen Yaseen. In this case though there's no need to use any commands they suggested, but rather just set the Node.js tool installer version spec to latest Node version from 11.x.

enter image description here

The exact version of Node.js that got installed and is working was 11.15.0. I didn't have to downgrade the Gulp.

Send and receive messages through NSNotificationCenter in Objective-C?

if you're using NSNotificationCenter for updating your view, don't forget to send it from the main thread by calling dispatch_async:

dispatch_async(dispatch_get_main_queue(),^{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"my_notification" object:nil];
});

Running Selenium Webdriver with a proxy in Python

My solution:

def my_proxy(PROXY_HOST,PROXY_PORT):
        fp = webdriver.FirefoxProfile()
        # Direct = 0, Manual = 1, PAC = 2, AUTODETECT = 4, SYSTEM = 5
        print PROXY_PORT
        print PROXY_HOST
        fp.set_preference("network.proxy.type", 1)
        fp.set_preference("network.proxy.http",PROXY_HOST)
        fp.set_preference("network.proxy.http_port",int(PROXY_PORT))
        fp.set_preference("general.useragent.override","whater_useragent")
        fp.update_preferences()
        return webdriver.Firefox(firefox_profile=fp)

Then call in your code:

my_proxy(PROXY_HOST,PROXY_PORT)

I had issues with this code because I was passing a string as a port #:

 PROXY_PORT="31280"

This is important:

int("31280")

You must pass an integer instead of a string or your firefox profile will not be set to a properly port and connection through proxy will not work.

How to find when a web page was last updated

There is another way to find the page update which could be useful for some occasions (if works:).

If the page has been indexed by Google, or by Wayback Machine you can try to find out what date(s) was(were) saved by them (these methods do not work for any page, and have some limitations, which are extensively investigated in this webmasters.stackexchange question's answers. But in many cases they can help you to find out the page update date(s):

  1. Google way: Go by link https://www.google.com.ua/search?q=site%3Awww.example.com&biw=1855&bih=916&source=lnt&tbs=cdr%3A1%2Ccd_min%3A1%2F1%2F2000%2Ccd_max%3A&tbm=
    • You can change text in search field by any page URL you want.
    • For example, the current stackoverflow question page search gives us as a result May 14, 2014 - which is the question creation date: enter image description here
  2. Wayback machine way: Go by link https://web.archive.org/web/*/www.example.com
    • for this stackoverflow page wayback machine gives us more results: Saved 6 times between June 7, 2014 and November 23, 2016., and you can view all saved copies for each date

Creating the checkbox dynamically using JavaScript?

The last line should read

cbh.appendChild(document.createTextNode(cap));

Appending the text (label?) to the same container as the checkbox, not the checkbox itself

Split string into string array of single characters

string input = "this is a test";
string[] afterSplit = input.Split();

foreach (var word in afterSplit)
    Console.WriteLine(word);

Result:

this
is
a
test

Android M Permissions: onRequestPermissionsResult() not being called

You have the checkPermissions function for pre Marshmallow devices in FragmentCompat. I use like this:

FragmentCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);

background-size in shorthand background property (CSS3)

  1. Your jsfiddle uses background-image instead of background
  2. It seems to be a case of "not supported by this browser yet".

This works in Opera : http://jsfiddle.net/ZNsbU/5/
But it doesn't work in FF5 nor IE8. (yay for outdated browsers :D )

Code :

body {
  background:url(http://www.google.com/intl/en_com/images/srpr/logo3w.png) 400px 200px / 600px 400px no-repeat;
}

You could do it like this :

body {
    background:url(http://www.google.com/intl/en_com/images/srpr/logo3w.png) 400px 400px no-repeat;
    background-size:20px 20px
}

Which works in FF5 and Opera but not in IE8.

Stacking DIVs on top of each other?

To add to Dave's answer:

div { position: relative; }
div div { position: absolute; top: 0; left: 0; }

How to center a checkbox in a table cell?

My problem was that there was a parent style with position: absolute !important which I was not allowed to edit.

So I gave my specific checkbox position: relative !important and it fixed the vertical misalignment issue.

Convert Long into Integer

In java ,there is a rigorous way to convert a long to int

not only lnog can convert into int,any type of class extends Number can convert to other Number type in general,here I will show you how to convert a long to int,other type vice versa.

Long l = 1234567L;
int i = org.springframework.util.NumberUtils.convertNumberToTargetClass(l, Integer.class);

Convert String to Double - VB

Try looking at Double.TryParse() if you are using .NET 1.1/2.0/3.0/3.5/4.0/4.5

How to check if a given directory exists in Ruby

File.exist?("directory")

Dir[] returns an array, so it will never be nil. If you want to do it your way, you could do

Dir["directory"].empty?

which will return true if it wasn't found.

JavaScript property access: dot notation vs. brackets?

Case where [] notation is helpful :

If your object is dynamic and there could be some random values in keys like number and []or any other special character, for example -

var a = { 1 : 3 };

Now if you try to access in like a.1 it will through an error, because it is expecting an string over there.

C++ performance vs. Java/C#

I like Orion Adrian's answer, but there is another aspect to it.

The same question was posed decades ago about assembly language vs. "human" languages like FORTRAN. And part of the answer is similar.

Yes, a C++ program is capable of being faster than C# on any given (non-trivial?) algorithm, but the program in C# will often be as fast or faster than a "naive" implementation in C++, and an optimized version in C++ will take longer to develop, and might still beat the C# version by a very small margin. So, is it really worth it?

You'll have to answer that question on a one-by-one basis.

That said, I'm a long time fan of C++, and I think it's an incredibly expressive and powerful language -- sometimes underappreciated. But in many "real life" problems (to me personally, that means "the kind I get paid to solve"), C# will get the job done sooner and safer.

The biggest penalty you pay? Many .NET and Java programs are memory hogs. I have seen .NET and Java apps take "hundreds" of megabytes of memory, when C++ programs of similar complexity barely scratch the "tens" of MBs.

How to stop asynctask thread in android?

declare your asyncTask in your activity:

private YourAsyncTask mTask;

instantiate it like this:

mTask = new YourAsyncTask().execute();

kill/cancel it like this:

mTask.cancel(true);

failed to open stream: HTTP wrapper does not support writeable connections

you could use fopen() function.

some example:

$url = 'http://doman.com/path/to/file.mp4';
$destination_folder = $_SERVER['DOCUMENT_ROOT'].'/downloads/';


    $newfname = $destination_folder .'myfile.mp4'; //set your file ext

    $file = fopen ($url, "rb");

    if ($file) {
      $newf = fopen ($newfname, "a"); // to overwrite existing file

      if ($newf)
      while(!feof($file)) {
        fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );

      }
    }

    if ($file) {
      fclose($file);
    }

    if ($newf) {
      fclose($newf);
    }

How to Change color of Button in Android when Clicked?

Try This

    final Button button = (Button) findViewById(R.id.button_id);
    button.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_UP) {
                button.setBackgroundColor(Color.RED);
            } else if(event.getAction() == MotionEvent.ACTION_DOWN) {
                button.setBackgroundColor(Color.BLUE);
            }
            return false;
        }

    });

How to create a temporary table in SSIS control flow task and then use it in data flow task?

I'm late to this party but I'd like to add one bit to user756519's thorough, excellent answer. I don't believe the "RetainSameConnection on the Connection Manager" property is relevant in this instance based on my recent experience. In my case, the relevant point was their advice to set "ValidateExternalMetadata" to False.

I'm using a temp table to facilitate copying data from one database (and server) to another, hence the reason "RetainSameConnection" was not relevant in my particular case. And I don't believe it is important to accomplish what is happening in this example either, as thorough as it is.

What's the difference between a POST and a PUT HTTP REQUEST?

To give examples of REST-style resources:

POST /books with a bunch of book information might create a new book, and respond with the new URL identifying that book: /books/5.

PUT /books/5 would have to either create a new book with the id of 5, or replace the existing book with ID 5.

In non-resource style, POST can be used for just about anything that has a side effect. One other difference is that PUT should be idempotent - multiple PUTs of the same data to the same URL should be fine, whereas multiple POSTs might create multiple objects or whatever it is your POST action does.

Convert date to another timezone in JavaScript

If you don't want to import some big library you could just use Intl.DateTimeFormat to convert Date objects to different timezones.

_x000D_
_x000D_
// Specifying timeZone is what causes the conversion, the rest is just formatting
const options = {
  year: '2-digit', month: '2-digit', day: '2-digit',
  hour: '2-digit', minute: '2-digit', second: '2-digit',
  timeZone: 'Asia/Jakarta',
  timeZoneName: 'short'
}
const formatter = new Intl.DateTimeFormat('sv-SE', options)
const startingDate = new Date("2012/04/10 10:10:30 +0000")

const dateInNewTimezone = formatter.format(startingDate) 
console.log(dateInNewTimezone) // 12-04-10 17:10:30 GMT+7
_x000D_
_x000D_
_x000D_

Offsets, daylight saving, and changes in the past will be taken care of for you.

How to prevent a click on a '#' link from jumping to top of page?

I've always used:

<a href="#?">Some text</a>

when trying to prevent the page jump. Not sure if this is the best, but it seems to have been working well for years.

Getting Database connection in pure JPA setup

if you use EclipseLink: You should be in a JPA transaction to access the Connection

entityManager.getTransaction().begin();
java.sql.Connection connection = entityManager.unwrap(java.sql.Connection.class);
...
entityManager.getTransaction().commit();

How to terminate process from Python using pid?

I wanted to do the same thing as, but I wanted to do it in the one file.

So the logic would be:

  • if a script with my name is running, kill it, then exit
  • if a script with my name is not running, do stuff

I modified the answer by Bakuriu and came up with this:

from os import getpid
from sys import argv, exit
import psutil  ## pip install psutil

myname = argv[0]
mypid = getpid()
for process in psutil.process_iter():
    if process.pid != mypid:
        for path in process.cmdline():
            if myname in path:
                print "process found"
                process.terminate()
                exit()

## your program starts here...

Running the script will do whatever the script does. Running another instance of the script will kill any existing instance of the script.

I use this to display a little PyGTK calendar widget which runs when I click the clock. If I click and the calendar is not up, the calendar displays. If the calendar is running and I click the clock, the calendar disappears.

Check Whether a User Exists

I like this nice one line solution

getent passwd username > /dev/null 2&>1 && echo yes || echo no

and in script:

#!/bin/bash

if [ "$1" != "" ]; then
        getent passwd $1 > /dev/null 2&>1 && (echo yes; exit 0) || (echo no; exit 2)
else
        echo "missing username"
        exit -1
fi

use:

[mrfish@yoda ~]$ ./u_exists.sh root
yes
[mrfish@yoda ~]$ echo $?
0

[mrfish@yoda ~]$ ./u_exists.sh
missing username
[mrfish@yoda ~]$ echo $?
255

[mrfish@yoda ~]$ ./u_exists.sh aaa
no
[mrfish@indegy ~]$ echo $?
2

Convert JSON to DataTable

One doesn't always know the type into which to deserialize. So it would be handy to be able to take any JSON (that contains some array) and dynamically produce a table from that.

An issue can arise however, where the deserializer doesn't know where to look for the array to tabulate. When this happens, we get an error message similar to the following:

Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1.

Even if we give it come encouragement or prepare our json accordingly, then "object" types within the array can still prevent tabulation from occurring, where the deserializer doesn't know how to represent the objects in terms of rows, etc. In this case, errors similar to the following occur:

Unexpected JSON token when reading DataTable: StartObject. Path '[0].__metadata', line 3, position 19.

The below example JSON includes both of these problematic features:

{
  "results":
  [
    {
      "Enabled": true,
      "Id": 106,
      "Name": "item 1",
    },
    {
      "Enabled": false,
      "Id": 107,
      "Name": "item 2",
      "__metadata": { "Id": 4013 }
    }
  ]
}

So how can we resolve this, and still maintain the flexibility of not knowing the type into which to derialize?

Well here is a simple approach I came up with (assuming you are happy to ignore the object-type properties, such as __metadata in the above example):

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;
using System.Linq;
...

public static DataTable Tabulate(string json)
{
    var jsonLinq = JObject.Parse(json);

    // Find the first array using Linq
    var srcArray = jsonLinq.Descendants().Where(d => d is JArray).First();
    var trgArray = new JArray();
    foreach (JObject row in srcArray.Children<JObject>())
    {
        var cleanRow = new JObject();
        foreach (JProperty column in row.Properties())
        {
            // Only include JValue types
            if (column.Value is JValue)
            {
                cleanRow.Add(column.Name, column.Value);
            }
        }

        trgArray.Add(cleanRow);
    }

    return JsonConvert.DeserializeObject<DataTable>(trgArray.ToString());
}

I know this could be more "LINQy" and has absolutely zero exception handling, but hopefully the concept is conveyed.

We're starting to use more and more services at my work that spit back JSON, so freeing ourselves of strongly-typing everything, is my obvious preference because I'm lazy!

"Use the new keyword if hiding was intended" warning

The parent function needs the virtual keyword, and the child function needs the override keyword in front of the function definition.

Capturing a single image from my webcam in Java or Python

import cv2
camera = cv2.VideoCapture(0)
while True:
    return_value,image = camera.read()
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    cv2.imshow('image',gray)
    if cv2.waitKey(1)& 0xFF == ord('s'):
        cv2.imwrite('test.jpg',image)
        break
camera.release()
cv2.destroyAllWindows()

How to decode jwt token in javascript without using a library?

Working unicode text JWT parser function:

function parseJwt (token) {
    var base64Url = token.split('.')[1];
    var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));

    return JSON.parse(jsonPayload);
};

VS 2012: Scroll Solution Explorer to current file

Yes, you can find that under

Tools - > Options - > Projects and Solutions - > Track Active Item in Solution Explorer

It's off by default (as you've noticed), but once it's on, Solution Explorer will expand folders and highlight the current document as you switch between files.

Python math module

add:

import math

at beginning. and then use:

math.sqrt(num)  # or any other function you deem neccessary

How to execute Python scripts in Windows?

Found an incredibly useful answer here: How to run different python versions in cmd?

I would suggest using the Python Launcher for Windows utility that introduced was into Python 3.3 a while ago. You can also manually download and install it directly from the author's website for use with earlier versions of Python 2 and 3.

Regardless of how you obtain it, after installation it will have associated itself with all the standard Python file extensions (i.e. .py, .pyw, .pyc, and .pyo files). You'll not only be able to explicitly control which version is used at the command-prompt, but also on a script-by-script basis by adding Linux/Unix-y shebang #!/usr/bin/env pythonX comments at the beginning of your Python scripts.

As J.F. Sebastian suggests, Python Launcher for Windows is the best and default choice for launching different version of Python in Windows. It used to be a third-party tool, but now it is officially supported since Python 3.3.

New in version 3.3.

The Python launcher for Windows is a utility which aids in the location and execution of different Python versions. It allows scripts (or the command-line) to indicate a preference for a specific Python version, and will locate and execute that version.

This is a great tool just use it!

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

In eclipse, Go to Project->Properties->Java build Path->Order and Export. If you are using multiple JREs, try like jdk and ibm. Order should start with jdk and then IBM. This is how my issue was resolved.

How do I get the last character of a string?

Simple solution is:

public String frontBack(String str) {
  if (str == null || str.length() == 0) {
    return str;
  }
  char[] cs = str.toCharArray();
  char first = cs[0];
  cs[0] = cs[cs.length -1];
  cs[cs.length -1] = first;
  return new String(cs);
}

Using a character array (watch out for the nasty empty String or null String argument!)

Another solution uses StringBuilder (which is usually used to do String manupilation since String itself is immutable.

public String frontBack(String str) {
  if (str == null || str.length() == 0) {
    return str;
  }
  StringBuilder sb = new StringBuilder(str);  
  char first = sb.charAt(0);
  sb.setCharAt(0, sb.charAt(sb.length()-1));
  sb.setCharAt(sb.length()-1, first);
  return sb.toString();
}

Yet another approach (more for instruction than actual use) is this one:

public String frontBack(String str) {
  if (str == null || str.length() < 2) {
    return str;
  }
  StringBuilder sb = new StringBuilder(str);
  String sub = sb.substring(1, sb.length() -1);
  return sb.reverse().replace(1, sb.length() -1, sub).toString();
}

Here the complete string is reversed and then the part that should not be reversed is replaced with the substring. ;)

How to loop through an associative array and get the key?

Use $key => $val to get the keys:

<?php

$arr = array(
    1 => "Value1",
    2 => "Value2",
    10 => "Value10",
);

foreach ($arr as $key => $val) {
   print "$key\n";
}

?>

How to make an introduction page with Doxygen

Following syntax may help for adding a main page and related subpages for doxygen:

/*! \mainpage Drawing Shapes
 *
 * This project helps user to draw shapes.
 * Currently two types of shapes can be drawn:
 * - \subpage drawingRectanglePage "How to draw rectangle?"
 *
 * - \subpage drawingCirclePage "How to draw circle?"
 *
 */ 

/*! \page drawingRectanglePage How to draw rectangle?
 *
 * Lorem ipsum dolor sit amet
 *
 */

/*! \page drawingCirclePage How to draw circle?
 *
 * This page is about how to draw a circle.
 * Following sections describe circle:
 * - \ref groupCircleDefinition "Definition of Circle"
 * - \ref groupCircleClass "Circle Class"
 */

Creating groups as following also help for designing pages:

/** \defgroup groupCircleDefinition Circle Definition
 * A circle is a simple shape in Euclidean geometry.
 * It is the set of all points in a plane that are at a given distance from a given point, the centre;
 * equivalently it is the curve traced out by a point that moves so that its distance from a given point is constant.
 * The distance between any of the points and the centre is called the radius.
 */

An example can be found here

Convert string to decimal, keeping fractions

The value is the same even though the printed representation is not what you expect:

decimal d = (decimal )1200.00;
Console.WriteLine(Decimal.Parse("1200") == d); //True

Can't access RabbitMQ web management interface after fresh install

If on Windows and installed using chocolatey make sure firewall is allowing the default ports for it:

netsh advfirewall firewall add rule name="RabbitMQ Management" dir=in action=allow protocol=TCP localport=15672
netsh advfirewall firewall add rule name="RabbitMQ" dir=in action=allow protocol=TCP localport=5672

for the remote access.

PHP Header redirect not working

If I understand correctly, something has already sent out from header.php (maybe some HTML) so the headers have been set. You may need to recheck your header.php file for any part that may output HTML or spaces before your first

EDIT: I am now sure that it is caused from header.php since you have those HTML output. You can fix this by remove the "include('header.php');" line and copy the following code to your file instead.

include('class.user.php');
include('class.Connection.php');

        $date = date('Y-m-j');

DTO pattern: Best way to copy properties between two objects

You can use Apache Commmons Beanutils. The API is

org.apache.commons.beanutils.PropertyUtilsBean.copyProperties(Object dest, Object orig).

It copies property values from the "origin" bean to the "destination" bean for all cases where the property names are the same.

Now I am going to off topic. Using DTO is mostly considered an anti-pattern in EJB3. If your DTO and your domain objects are very alike, there is really no need to duplicate codes. DTO still has merits, especially for saving network bandwidth when remote access is involved. I do not have details about your application architecture, but if the layers you talked about are logical layers and does not cross network, I do not see the need for DTO.

Converting HTML files to PDF

If you have the funding, nothing beats Prince XML as this video shows

Converting ArrayList to HashMap

Using a supposed name property as the map key:

for (Product p: productList) { s.put(p.getName(), p); }

Simple conversion between java.util.Date and XMLGregorianCalendar

From XMLGregorianCalendar to java.util.Date you can simply do:

java.util.Date dt = xmlGregorianCalendarInstance.toGregorianCalendar().getTime();  

Checking if a string is empty or null in Java

This way you check if the string is not null and not empty, also considering the empty spaces:

boolean isEmpty = str == null || str.trim().length() == 0;
if (isEmpty) {
    // handle the validation
}

Call method when home button pressed

I found that when I press the button HOME the onStop() method is called.You can use the following piece of code to monitor it:

@Override
    protected void onStop() 
    {
        super.onStop();
        Log.d(tag, "MYonStop is called");
        // insert here your instructions
    }

How to scanf only integer?

A possible solution is to think about it backwards: Accept a float as input and reject the input if the float is not an integer:

int n;
float f;
printf("Please enter an integer: ");
while(scanf("%f",&f)!=1 || (int)f != f)
{
    ...
}
n = f;

Though this does allow the user to enter something like 12.0, or 12e0, etc.

How to extract numbers from string in c?

You can do it with strtol, like this:

char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process...
    if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
        // Found a number
        long val = strtol(p, &p, 10); // Read number
        printf("%ld\n", val); // and print it.
    } else {
        // Otherwise, move on to the next character.
        p++;
    }
}

Link to ideone.

WPF button click in C# code

Button btn = new Button();
btn.Name = "btn1";
btn.Click += btn1_Click;

private void btn1_Click(object sender, RoutedEventArgs e)
{
    // do something
}

Error importing Seaborn module in Python

Problem may not be associated with Seaborn but Utils package which may not be installed

sudo pip uninstall requests

and reinstalling, it no longer would work at all. Luckily, dnf install python-requests fixed the whole thing...

Also check for utils package is installed or not

You can install package using

sudo pip install utils

Check this link Python ImportError: cannot import name utils

How to build a DataTable from a DataGridView?

Well, you can do

DataTable data = (DataTable)(dgvMyMembers.DataSource);

and then use

data.Columns.Remove(...);

I think it's the fastest way. This will modify data source table, if you don't want it, then copy of table is reqired. Also be aware that DataGridView.DataSource is not necessarily of DataTable type.

How to print an unsigned char in C?

Because char is by default signed declared that means the range of the variable is

-127 to +127>

your value is overflowed. To get the desired value you have to declared the unsigned modifier. the modifier's (unsigned) range is:

 0 to 255

to get the the range of any data type follow the process 2^bit example charis 8 bit length to get its range just 2 ^(power) 8.

How do I add a ToolTip to a control?

ToolTip in C# is very easy to add to almost all UI controls. You don't need to add any MouseHover event for this.

This is how to do it-

  1. Add a ToolTip object to your form. One object is enough for the entire form. ToolTip toolTip = new ToolTip();

  2. Add the control to the tooltip with the desired text.

    toolTip.SetToolTip(Button1,"Click here");

Create an Array of Arraylists

This works, array of ArrayList. Give it a try to understand how it works.

import java.util.*;

public class ArrayOfArrayList {
    public static void main(String[] args) {

        // Put the length of the array you need
        ArrayList<String>[] group = new ArrayList[15];
        for (int x = 0; x < group.length; x++) {
            group[x] = new ArrayList<>();
        }

        //Add some thing to first array
        group[0].add("Some");
        group[0].add("Code");

        //Add some thing to Secondarray
        group[1].add("In here");

        //Try to output 'em
        System.out.println(group[0]);
        System.out.println(group[1]);
    }
}

Credits to Kelvincer for some of codes.

Get the (last part of) current directory name in C#

var lastFolderName = Path.GetFileName(
    path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));

This works if the path happens to contain forward slash separators or backslash separators.

How can I fix MySQL error #1064?

For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.

For example, Before it was:

DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;

After putting DELIMITER it was like this:

DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;
$$
DELIMITER ;

Cannot authenticate into mongo, "auth fails"

Authentication is managed at a database level. When you try to connect to the system using a database, mongo actually checks for the credentials you provide in the collection <database>.system.users. So, basically when you are trying to connect to "test", it looks for the credentials in test.system.users and returns an error because it cannot find them (as they are stored in admin.system.users). Having the right to read and write from all db doesn't mean you can directly connect to them.

You have to connect to the database holding the credentials first. Try:

mongo admin -u admin -p SECRETPASSWORD

For more info, check this http://docs.mongodb.org/manual/reference/privilege-documents/

Zoom to fit all markers in Mapbox or Leaflet

Leaflet also has LatLngBounds that even has an extend function, just like google maps.

http://leafletjs.com/reference.html#latlngbounds

So you could simply use:

var latlngbounds = new L.latLngBounds();

The rest is exactly the same.

How to sort an array of ints using a custom comparator?

Here is a helper method to do the job.

First of all you'll need a new Comparator interface, as Comparator doesn't support primitives:

public interface IntComparator{
    public int compare(int a, int b);
}

(You could of course do it with autoboxing / unboxing but I won't go there, that's ugly)

Then, here's a helper method to sort an int array using this comparator:

public static void sort(final int[] data, final IntComparator comparator){
    for(int i = 0; i < data.length + 0; i++){
        for(int j = i; j > 0
            && comparator.compare(data[j - 1], data[j]) > 0; j--){
            final int b = j - 1;
            final int t = data[j];
            data[j] = data[b];
            data[b] = t;
        }
    }
}

And here is some client code. A stupid comparator that sorts all numbers that consist only of the digit '9' to the front (again sorted by size) and then the rest (for whatever good that is):

final int[] data =
    { 4343, 544, 433, 99, 44934343, 9999, 32, 999, 9, 292, 65 };
sort(data, new IntComparator(){

    @Override
    public int compare(final int a, final int b){
        final boolean onlyNinesA = this.onlyNines(a);
        final boolean onlyNinesB = this.onlyNines(b);
        if(onlyNinesA && !onlyNinesB){
            return -1;
        }
        if(onlyNinesB && !onlyNinesA){
            return 1;
        }

        return Integer.valueOf(a).compareTo(Integer.valueOf(b));
    }

    private boolean onlyNines(final int candidate){
        final String str = String.valueOf(candidate);
        boolean nines = true;
        for(int i = 0; i < str.length(); i++){
            if(!(str.charAt(i) == '9')){
                nines = false;
                break;
            }
        }
        return nines;
    }
});

System.out.println(Arrays.toString(data));

Output:

[9, 99, 999, 9999, 32, 65, 292, 433, 544, 4343, 44934343]

The sort code was taken from Arrays.sort(int[]), and I only used the version that is optimized for tiny arrays. For a real implementation you'd probably want to look at the source code of the internal method sort1(int[], offset, length) in the Arrays class.

Reading multiple Scanner inputs

If every input asks the same question, you should use a for loop and an array of inputs:

Scanner dd = new Scanner(System.in);
int[] vars = new int[3];

for(int i = 0; i < vars.length; i++) {
  System.out.println("Enter next var: ");
  vars[i] = dd.nextInt();
}

Or as Chip suggested, you can parse the input from one line:

Scanner in = new Scanner(System.in);
int[] vars = new int[3];

System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
  vars[i] = in.nextInt();

You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

On top of all the answers i found one nice solution. Actually The issue related to network connection fail for iOS 12 onword is because there is a bug in the iOS 12.0 onword. And it Yet to resolved. I had gone through the git hub community for AFNetworking related issue when app came from background and tries to do network call and fails on connection establish. I spend 3 days on this and tries many things to get to the root cause for this and found nothing. Finally i got some light in the dark when i red this blog https://github.com/AFNetworking/AFNetworking/issues/4279

It is saying that there is a bug in the iOS 12. Basically you cannot expect a network call to ever complete if the app os not in foreground. And due to this bug the network calls get dropped and we get network fails in logs.

My best suggestion to you is provide some delay when your app are coming from background to foreground and there is network call. Make that network call in the dispatch async with some delay. You'll never get network call drop or connection loss.

Do not wait for Apple to let this issue solve for iOS 12 as its still yet to fix. You may go with this workaround by providing some delay for your network request being its NSURLConnection, NSURLSession or AFNetworking or ALAMOFIRE. Cheers :)

HTML tag inside JavaScript

This is what I used for my countdown clock:

</SCRIPT>
<center class="auto-style19" style="height: 31px">
<Font face="blacksmith" size="large"><strong>
<SCRIPT LANGUAGE="JavaScript">
var header = "You have <I><font color=red>" 
+ getDaysUntilICD10() + "</font></I>&nbsp; "
header += "days until ICD-10 starts!"
document.write(header)
</SCRIPT>

The HTML inside of my script worked, though I could not explain why.

Regular expression for checking if capital letters are found consecutively in a string?

Aside from tchrists excellent post concerning unicode, I think you don't need the complex solution with a negative lookahead... Your definition requires an Uppercase-letter followed by at least one group of (a lowercase letter optionally followed by an Uppercase-letter)

^
[A-Z]    // Start with an uppercase Letter
(        // A Group of:
  [a-z]  // mandatory lowercase letter
  [A-Z]? // an optional Uppercase Letter at the end
         // or in between lowercase letters
)+       // This group at least one time
$

Just a bit more compact and easier to read I think...

Plot a legend outside of the plotting area in base graphics?

Adding another simple alternative that is quite elegant in my opinion.

Your plot:

plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")

Legend:

legend("bottomright", c("group A", "group B"), pch=c(1,2), lty=c(1,2),
       inset=c(0,1), xpd=TRUE, horiz=TRUE, bty="n"
       )

Result:

picture with legend

Here only the second line of the legend was added to your example. In turn:

  • inset=c(0,1) - moves the legend by fraction of plot region in (x,y) directions. In this case the legend is at "bottomright" position. It is moved by 0 plotting regions in x direction (so stays at "right") and by 1 plotting region in y direction (from bottom to top). And it so happens that it appears right above the plot.
  • xpd=TRUE - let's the legend appear outside of plotting region.
  • horiz=TRUE - instructs to produce a horizontal legend.
  • bty="n" - a style detail to get rid of legend bounding box.

Same applies when adding legend to the side:

par(mar=c(5,4,2,6))
plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")

legend("topleft", c("group A", "group B"), pch=c(1,2), lty=c(1,2),
       inset=c(1,0), xpd=TRUE, bty="n"
       )

Here we simply adjusted legend positions and added additional margin space to the right side of the plot. Result:

picture with legend 2

Get the ID of a drawable in ImageView

I think if I understand correctly this is what you are doing.

ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        ImageView imageView = (ImageView) view;
        assert(R.id.someImage == imageView.getId());

        switch(getDrawableId(imageView)) {
            case R.drawable.foo:
                imageView.setDrawableResource(R.drawable.bar);
                break;
            case R.drawable.bar:
            default:
                imageView.setDrawableResource(R.drawable.foo);
            break;
        }
    });

Right? So that function getDrawableId() doesn't exist. You can't get a the id that a drawable was instantiated from because the id is just a reference to the location of data on the device on how to construct a drawable. Once the drawable is constructed it doesn't have a way to get back the resourceId that was used to create it. But you could make it work something like this using tags

ImageView view = (ImageView) findViewById(R.id.someImage);
view.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        ImageView imageView = (ImageView) view;
        assert(R.id.someImage == imageView.getId());

        // See here
        Integer integer = (Integer) imageView.getTag();
        integer = integer == null ? 0 : integer;

        switch(integer) {
        case R.drawable.foo:
            imageView.setDrawableResource(R.drawable.bar);
            imageView.setTag(R.drawable.bar);
            break;
        case R.drawable.bar:
        default:
            imageView.setDrawableResource(R.drawable.foo);
            imageView.setTag(R.drawable.foo);
            break;
        }
    });

how to change any data type into a string in python

str is meant to produce a string representation of the object's data. If you're writing your own class and you want str to work for you, add:

def __str__(self):
    return "Some descriptive string"

print str(myObj) will call myObj.__str__().

repr is a similar method, which generally produces information on the class info. For most core library object, repr produces the class name (and sometime some class information) between angle brackets. repr will be used, for example, by just typing your object into your interactions pane, without using print or anything else.

You can define the behavior of repr for your own objects just like you can define the behavior of str:

def __repr__(self):
    return "Some descriptive string"

>>> myObj in your interactions pane, or repr(myObj), will result in myObj.__repr__()

Draw a line in a div

Its working for me

_x000D_
_x000D_
 .line{_x000D_
width: 112px;_x000D_
height: 47px;_x000D_
border-bottom: 1px solid black;_x000D_
position: absolute;_x000D_
}
_x000D_
<div class="line"></div>
_x000D_
_x000D_
_x000D_

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

Seriously, the top answer is not working for me. tried cxf.version 2.4.1 and 3.0.10. and generate absolute path with wsdlLocation every times.

My solution is to use the wsdl2java command in the apache-cxf-3.0.10\bin\ with -wsdlLocation classpath:wsdl/QueryService.wsdl.

Detail:

    wsdl2java -encoding utf-8 -p com.jeiao.boss.testQueryService -impl -wsdlLocation classpath:wsdl/testQueryService.wsdl http://127.0.0.1:9999/platf/testQueryService?wsdl

Count number of iterations in a foreach loop

foreach ($array as $value)
{       
    if(!isset($counter))
    {
        $counter = 0;
    }
    $counter++;
}

//Sorry if the code isn't shown correctly. :P

//I like this version more, because the counter variable is IN the foreach, and not above.

Convert date to UTC using moment.js

Don't you need something to compare and then retrieve the milliseconds?

For instance:

let enteredDate = $("#txt-date").val(); // get the date entered in the input
let expires = moment.utc(enteredDate); // convert it into UTC

With that you have the expiring date in UTC. Now you can get the "right-now" date in UTC and compare:

var rightNowUTC = moment.utc(); // get this moment in UTC based on browser
let duration = moment.duration(rightNowUTC.diff(expires)); // get the diff
let remainingTimeInMls = duration.asMilliseconds();

How can I set the default timezone in node.js?

The solution env TZ='Europe/Amsterdam' node server.js from @uhef works in cases where your app doesn't work with forked process, but when you are working with forked process, specially when you launch your app with a building tool like gulp , the command gulp will take the env values, but the process created by gulp not (your app).

To solve this, you have to do:

$ export TZ="Europe/Amsterdam"; gulp myTask

This will set the TZ environment variable for all the process started in the console you are working on, included all the subsequents process executed after the gulp command in the same console without the need to execute them with the prefix export TZ="Europe/Amsterdam"; again.

Java - How to create a custom dialog box?

If you use the NetBeans IDE (latest version at this time is 6.5.1), you can use it to create a basic GUI java application using File->New Project and choose the Java category then Java Desktop Application.

Once created, you will have a simple bare bones GUI app which contains an about box that can be opened using a menu selection. You should be able to adapt this to your needs and learn how to open a dialog from a button click.

You will be able to edit the dialog visually. Delete the items that are there and add some text areas. Play around with it and come back with more questions if you get stuck :)

How to solve "Fatal error: Class 'MySQLi' not found"?

install phpXX-extension by PHP. In my FreeBSD's case:

pkg install php74-extensions

How to push changes to github after jenkins build completes?

I followed the below Steps. It worked for me.

In Jenkins execute shell under Build, creating a file and trying to push that file from Jenkins workspace to GitHub.

enter image description here

Download Git Publisher Plugin and Configure as shown below snapshot.

enter image description here

Click on Save and Build. Now you can check your git repository whether the file was pushed successfully or not.

database attached is read only

First make sure that the folder in which your .mdf file resides is not read only. If it is, un-check that option and make sure it reflects to folders and files within that folder.

Once that is done, Open Management Studio, in the Object Explorer right click on the Database which is read only and select Properties. In the Options Menu, check that the Read-Only property is false.

enter image description here

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

The only solution I have found is not to set the index to a previous frame and wait (then OpenCV stops reading frames, anyway), but to initialize the capture one more time. So, it looks like this:

cap = cv2.VideoCapture(camera_url)
while True:
    ret, frame = cap.read()

    if not ret:
        cap = cv.VideoCapture(camera_url)
        continue

    # do your processing here

And it works perfectly!

Pandas DataFrame to List of Lists

I wanted to preserve the index, so I adapted the original answer to this solution:

list_df = df.reset_index().values.tolist()

Now you can paste it somewhere else (e.g. to paste into a Stack Overflow question) and latter recreate it:

pd.Dataframe(list_df, columns=['name1', ...])
pd.set_index(['name1'], inplace=True)

How do I reset the setInterval timer?

Once you clear the interval using clearInterval you could setInterval once again. And to avoid repeating the callback externalize it as a separate function:

var ticker = function() {
    console.log('idle');
};

then:

var myTimer = window.setInterval(ticker, 4000);

then when you decide to restart:

window.clearInterval(myTimer);
myTimer = window.setInterval(ticker, 4000);

Center the nav in Twitter Bootstrap

For Bootstrap v4 check this:

https://v4-alpha.getbootstrap.com/components/pagination/#alignment

only add class to ul.pagination:

<nav">
  <ul class="pagination justify-content-center">
    <li class="page-item disabled">
      <a class="page-link" href="#" tabindex="-1">Previous</a>
    </li>
    <li class="page-item"><a class="page-link" href="#">1</a></li>
    <li class="page-item"><a class="page-link" href="#">2</a></li>
    <li class="page-item"><a class="page-link" href="#">3</a></li>
    <li class="page-item">
      <a class="page-link" href="#">Next</a>
    </li>
  </ul>
</nav>

Create a batch file to run an .exe with an additional parameter

in batch file abc.bat

cd c:\user\ben_dchost\documents\
executible.exe -flag1 -flag2 -flag3 

I am assuming that your executible.exe is present in c:\user\ben_dchost\documents\ I am also assuming that the parameters it takes are -flag1 -flag2 -flag3

Edited:

For the command you say you want to execute, do:

cd C:\Users\Ben\Desktop\BGInfo\
bginfo.exe dc_bginfo.bgi
pause

Hope this helps

How can I find the latitude and longitude from address?

Ud_an's solution with updated API's

Note: LatLng class is part of Google Play Services.

Mandatory:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<uses-permission android:name="android.permission.INTERNET"/>

Update: If you have target SDK 23 and above, make sure you take care of runtime permission for location.

public LatLng getLocationFromAddress(Context context,String strAddress) {

    Geocoder coder = new Geocoder(context);
    List<Address> address;
    LatLng p1 = null;

    try {
        // May throw an IOException
        address = coder.getFromLocationName(strAddress, 5);
        if (address == null) {
            return null;
        }

        Address location = address.get(0);
        p1 = new LatLng(location.getLatitude(), location.getLongitude() );

    } catch (IOException ex) {

        ex.printStackTrace();
    }

    return p1;
}

How to get TimeZone from android mobile?

I needed the offset that not only included day light savings time but as a numerial. Here is the code that I used in case someone is looking for an example.

I get a response of "3.5" (3:30') which is what I would expect in Tehran , Iran in winter and "4.5" (4:30') for summer .

I also needed it as a string so I could post it to a server so you may not need the last line.

for getting currect time zone :

TimeZone tz = TimeZone.getDefault();
Date now = new Date();
//Import part : x.0 for double number
double offsetFromUtc = tz.getOffset(now.getTime()) / 3600000.0;
String m2tTimeZoneIs = Double.parseDouble(offsetFromUtc);

How do I resolve "Cannot find module" error using Node.js?

If all other methods are not working for you... Try

npm link package_name

e.g

npm link webpack
npm link autoprefixer

e.t.c

C# ListView Column Width Auto

You can use something like this, passing the ListView you want in param

    private void AutoSizeColumnList(ListView listView)
    {
        //Prevents flickering
        listView.BeginUpdate();

        Dictionary<int, int> columnSize = new Dictionary<int,int>();

        //Auto size using header
        listView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);

        //Grab column size based on header
        foreach(ColumnHeader colHeader in listView.Columns )
            columnSize.Add(colHeader.Index, colHeader.Width);

        //Auto size using data
        listView.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);

        //Grab comumn size based on data and set max width
        foreach (ColumnHeader colHeader in listView.Columns)
        {
            int nColWidth;
            if (columnSize.TryGetValue(colHeader.Index, out nColWidth))
                colHeader.Width = Math.Max(nColWidth, colHeader.Width);
            else
                //Default to 50
                colHeader.Width = Math.Max(50, colHeader.Width);
        }

        listView.EndUpdate();
    }

Search a string in a file and delete it from this file by Shell Script

Try the vim-way:

ex -s +"g/foo/d" -cwq file.txt

Filter Pyspark dataframe column with None value

Try to just use isNotNull function.

df.filter(df.dt_mvmt.isNotNull()).count()

"Insufficient Storage Available" even there is lot of free space in device memory

I kept having this problem, and I cleaned up the Dalvik cache using Titanium Backup. You'll need to have your phone rooted. As soon as I did that I was able to update Swiftkey and Beautiful Widgets.

How to find the path of the local git repository when I am possibly in a subdirectory

git rev-parse --show-toplevel

could be enough if executed within a git repo.
From git rev-parse man page:

--show-toplevel

Show the absolute path of the top-level directory.

For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":

git rev-parse --git-dir

That would give the path of the .git directory.


The OP mentions:

git rev-parse --show-prefix

which returns the local path under the git repo root. (empty if you are at the git repo root)


Note: for simply checking if one is in a git repo, I find the following command quite expressive:

git rev-parse --is-inside-work-tree

And yes, if you need to check if you are in a .git git-dir folder:

git rev-parse --is-inside-git-dir

How to input automatically when running a shell over SSH?

There definitely is... Use the spawn, expect, and send commands:

spawn test.sh
expect "Are you sure you want to continue connecting (yes/no)?"
send "yes"

There are more examples all over Stack Overflow, see: Help with Expect within a bash script

You may need to install these commands first, depending on your system.

How to get user name using Windows authentication in asp.net?

Username you get like this:

var userName = HttpContext.Current.Request.LogonUserIdentity?.Name;

"Least Astonishment" and the Mutable Default Argument

You can get round this by replacing the object (and therefore the tie with the scope):

def foo(a=[]):
    a = list(a)
    a.append(5)
    return a

Ugly, but it works.

How to test if parameters exist in rails

Just pieced this together for the same problem:

before_filter :validate_params

private

def validate_params
  return head :bad_request unless params_present?
end

def params_present?  
  Set.new(%w(one two three)) <= (Set.new(params.keys)) &&
  params.values.all?
end

the first line checks if our target keys are present in the params' keys using the <= subset? operator. Enumerable.all? without block per default returns false if any value is nil or false.

Standard way to embed version into python package?

Not directly an answer to your question, but you should consider naming it __version__, not version.

This is almost a quasi-standard. Many modules in the standard library use __version__, and this is also used in lots of 3rd-party modules, so it's the quasi-standard.

Usually, __version__ is a string, but sometimes it's also a float or tuple.

Edit: as mentioned by S.Lott (Thank you!), PEP 8 says it explicitly:

Module Level Dunder Names

Module level "dunders" (i.e. names with two leading and two trailing underscores) such as __all__, __author__, __version__, etc. should be placed after the module docstring but before any import statements except from __future__ imports.

You should also make sure that the version number conforms to the format described in PEP 440 (PEP 386 a previous version of this standard).

VC++ fatal error LNK1168: cannot open filename.exe for writing

This can also be a problem from the improper use of functions like FindNextFile when a FindClose is never executed. The process of the built file is terminated, and the build itself can be deleted, but LNK1168 will prevent a rebuild because of the open handle. This can create a handle leak in Explorer which can be addressed by terminating and restarting Explorer, but in many cases an immediate reboot is necessary.

How can I set the Secure flag on an ASP.NET Session Cookie?

There are two ways, one httpCookies element in web.config allows you to turn on requireSSL which only transmit all cookies including session in SSL only and also inside forms authentication, but if you turn on SSL on httpcookies you must also turn it on inside forms configuration too.

Edit for clarity: Put this in <system.web>

<httpCookies requireSSL="true" />

Changing a specific column name in pandas DataFrame

_x000D_
_x000D_
size = 10
df.rename(columns={df.columns[i]: someList[i] for i in range(size)}, inplace = True)
_x000D_
_x000D_
_x000D_

How to apply font anti-alias effects in CSS?

here you go Sir :-)

1

.myElement{
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-rendering: optimizeLegibility;
}

2

.myElement{
    text-shadow: rgba(0,0,0,.01) 0 0 1px;
}

clear cache of browser by command line

You can run Rundll32.exe for IE Options control panel applet and achieve following tasks.


Deletes ALL History - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255

Deletes History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1

Deletes Cookies Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2

Deletes Temporary Internet Files Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8

Deletes Form Data Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16

Deletes Password History Only - RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32

How can I convert ArrayList<Object> to ArrayList<String>?

If you want to do it the dirty way, try this.

@SuppressWarnings("unchecked")
public ArrayList<String> convert(ArrayList<Object> a) {
   return (ArrayList) a;
}

Advantage: here you save time by not iterating over all objects.

Disadvantage: may produce a hole in your foot.

Javascript format date / time

Please do not reinvent the wheel. There are many open-source & COTS solutions that already exist to solve this problem.

Please take a look at the following JavaScript libraries:


Demo

I wrote a one-liner using Moment.js below. You can check out the demo here: JSFiddle.

moment('2014-08-20 15:30:00').format('MM/DD/YYYY h:mm a'); // 08/20/2014 3:30 pm

Where to get "UTF-8" string literal in Java?

You can use Charset.defaultCharset() API or file.encoding property.

But if you want your own constant, you'll need to define it yourself.

How do I install ASP.NET MVC 5 in Visual Studio 2012?

There are a few installs you may need to apply for ASP.NET MVC 5 support in Visual Studio 2012. Update 4 seems to include the Web Tools update now.

You don't have to install the full Windows 8.1 SDK if you are just looking for the option to build web applications, just the .NET Framework 4.5.1 option in the installer. The full install is about 1.1 GB, but just the .NET installer is only 72 MB.

Make a link open a new window (not tab)

You can try this:-

   <a href="some.htm" target="_blank">Link Text</a>

and you can try this one also:-

  <a href="some.htm" onclick="if(!event.ctrlKey&&!window.opera){alert('Hold the Ctrl Key');return false;}else{return true;}" target="_blank">Link Text</a>

Spring Resttemplate exception handling

Spring abstracts you from the very very very large list of http status code. That is the idea of the exceptions. Take a look into org.springframework.web.client.RestClientException hierarchy:

You have a bunch of classes to map the most common situations when dealing with http responses. The http codes list is really large, you won't want write code to handle each situation. But for example, take a look into the HttpClientErrorException sub-hierarchy. You have a single exception to map any 4xx kind of error. If you need to go deep, then you can. But with just catching HttpClientErrorException, you can handle any situation where bad data was provided to the service.

The DefaultResponseErrorHandler is really simple and solid. If the response status code is not from the family of 2xx, it just returns true for the hasError method.

What is the difference between Select and Project Operations

The difference between the project operator (p) in relational algebra and the SELECT keyword in SQL is that if the resulting table/set has more than one occurrences of the same tuple, then p will return only one of them, while SQL SELECT will return all.

How to upper case every first letter of word in a string?

    String s = "java is an object oriented programming language.";      
    final StringBuilder result = new StringBuilder(s.length());    
    String words[] = s.split("\\ "); // space found then split it  
    for (int i = 0; i < words.length; i++) 
         {
    if (i > 0){
    result.append(" ");
    }   
    result.append(Character.toUpperCase(words[i].charAt(0))).append(
                words[i].substring(1));   
    }  
    System.out.println(result);  

Output: Java Is An Object Oriented Programming Language.

TimeSpan to DateTime conversion

TimeSpan can be added to a fresh DateTime to achieve this.

TimeSpan ts="XXX";
DateTime dt = new DateTime() + ts;

But as mentioned before, it is not strictly logical without a valid start date. I have encountered a use-case where i required only the time aspect. will work fine as long as the logic is correct.

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

T-SQL: Opposite to string concatenation - how to split string into multiple records

Here's a Split function that is compatible with SQL Server versions prior to 2005.

CREATE FUNCTION dbo.Split(@data nvarchar(4000), @delimiter nvarchar(100))  
RETURNS @result table (Id int identity(1,1), Data nvarchar(4000)) 
AS  
BEGIN 
    DECLARE @pos   INT
    DECLARE @start INT
    DECLARE @len   INT
    DECLARE @end   INT

    SET @len   = LEN('.' + @delimiter + '.') - 2
    SET @end   = LEN(@data) + 1
    SET @start = 1
    SET @pos   = 0

    WHILE (@pos < @end)
    BEGIN
        SET @pos = CHARINDEX(@delimiter, @data, @start)
        IF (@pos = 0) SET @pos = @end

        INSERT @result (data) SELECT SUBSTRING(@data, @start, @pos - @start)
        SET @start = @pos + @len
    END

    RETURN
END

Meaning of "487 Request Terminated"

The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.

15.1.2 UAS Behavior==> BYE Handling in RFC 3261

The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.

How can I get the status code from an http error in Axios?

There is a new option called validateStatus in request config. You can use it to specify to not throw exceptions if status < 100 or status > 300 (default behavior). Example:

const {status} = axios.get('foo.com', {validateStatus: () => true})

How do I declare a 2d array in C++ using new?

Start by defining the array using pointers (Line 1):

int** a = new int* [x];     //x is the number of rows
for(int i = 0; i < x; i++)
    a[i] = new int[y];     //y is the number of columns

APT command line interface-like yes/no input?

A very simple (but not very sophisticated) way of doing this for a single choice would be:

msg = 'Shall I?'
shall = input("%s (y/N) " % msg).lower() == 'y'

You could also write a simple (slightly improved) function around this:

def yn_choice(message, default='y'):
    choices = 'Y/n' if default.lower() in ('y', 'yes') else 'y/N'
    choice = input("%s (%s) " % (message, choices))
    values = ('y', 'yes', '') if choices == 'Y/n' else ('y', 'yes')
    return choice.strip().lower() in values

Note: On Python 2, use raw_input instead of input.

Add class to <html> with Javascript?

document.documentElement.classList.add('myCssClass');

classList is supported since ie10: https://caniuse.com/#search=classlist

Soft Edges using CSS?

You can use CSS gradient - although there are not consistent across browsers so You would have to code it for every one

Like that: CSS3 Transparency + Gradient

Gradient should be more transparent on top or on top right corner (depending on capabilities)

How to center body on a page?

For those that do know the width, you could do something like

div {
     max-width: ???px; //px,%
     margin-left:auto;
     margin-right:auto;
}

I also agree about not setting text-align:center on the body because it can mess up the rest of your code and you might have to individually set text-align:left on a lot of things either then or in the future.

PHP to write Tab Characters inside a file?

Use \t and enclose the string with double-quotes:

$chunk = "abc\tdef\tghi";

How to delete a whole folder and content?

Yet another (modern) way to solve it.

public class FileUtils {
    public static void delete(File fileOrDirectory) {
        if(fileOrDirectory != null && fileOrDirectory.exists()) {
            if(fileOrDirectory.isDirectory() && fileOrDirectory.listFiles() != null) {      
                Arrays.stream(fileOrDirectory.listFiles())
                      .forEach(FileUtils::delete);
            }
            fileOrDirectory.delete();
        }
    }
}

On Android since API 26

public class FileUtils {

    public static void delete(File fileOrDirectory)  {
        if(fileOrDirectory != null) {
            delete(fileOrDirectory.toPath());
        }
    }

    public static void delete(Path path)  {
        try {
            if(Files.exists(path)) {
                Files.walk(path)
                        .sorted(Comparator.reverseOrder())
                        .map(Path::toFile)
//                      .peek(System.out::println)
                        .forEach(File::delete);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

CSS - how to make image container width fixed and height auto stretched

What you're looking for is min-height and max-height.

img {
    max-width: 100%;
    height: auto;
}

.item {
    width: 120px;
    min-height: 120px;
    max-height: auto;
    float: left;
    margin: 3px;
    padding: 3px;
}

pip cannot install anything

I had that problem too, after I tried to reset my network settings. it solves problem.

C++ calling base class constructors

Why the base class' default constructor is called? Turns out it's not always be the case. Any constructor of the base class (with different signatures) can be invoked from the derived class' constructor. In your case, the default constructor is called because it has no parameters so it's default.

When a derived class is created, the order the constructors are called is always Base -> Derived in the hierarchy. If we have:

class A {..}
class B : A {...}
class C : B {...}
C c;

When c is create, the constructor for A is invoked first, and then the constructor for B, and then the constructor for C.

To guarantee that order, when a derived class' constructor is called, it always invokes the base class' constructor before the derived class' constructor can do anything else. For that reason, the programmer can manually invoke a base class' constructor in the only initialisation list of the derived class' constructor, with corresponding parameters. For instance, in the following code, Derived's default constructor will invoke Base's constructor Base::Base(int i) instead of the default constructor.

Derived() : Base(5)
{      
}

If there's no such constructor invoked in the initialisation list of the derived class' constructor, then the program assumes a base class' constructor with no parameters. That's the reason why a constructor with no parameters (i.e. the default constructor) is invoked.

MongoDB or CouchDB - fit for production?

We are currently using MongoDB in production as the caching layer as well as storage engine for product importing and manipulating product data. We are an eCommerce company managing over two million products (100+ million attributes), spanning 10+ distributors and without MongoDB, this task would be nearing impossible.

Batch script: how to check for admin rights

The cleanest way to check for admin privileges using a CMD script, that I have found, is something like this:

@echo off

REM  Calling verify with no args just checks the verify flag,
REM   we use this for its side effect of setting errorlevel to zero
verify >nul

REM  Attempt to read a particular system directory - the DIR
REM   command will fail with a nonzero errorlevel if the directory is
REM   unreadable by the current process.  The DACL on the
REM   c:\windows\system32\config\systemprofile directory, by default,
REM   only permits SYSTEM and Administrators.
dir %windir%\system32\config\systemprofile >nul 2>nul

REM  Use IF ERRORLEVEL or %errorlevel% to check the result
if not errorlevel 1 echo has Admin privs
if     errorlevel 1 echo has only User privs

This method only uses CMD.exe builtins, so it should be very fast. It also checks for the actual capabilities of the process rather than checking for SIDs or group memberships, so the effective permission is tested. And this works as far back as Windows 2003 and XP. Normal user processes or nonelevated processes fail the directory probe, where as Admin or elevated processes succeed.

Python Requests throwing SSLError

As mentioned by @Rafael Almeida, the problem you are having is caused by an untrusted SSL certificate. In my case, the SSL certificate was untrusted by my server. To get around this without compromising security, I downloaded the certificate, and installed it on the server (by simply double clicking on the .crt file and then Install Certificate...).

How to convert a ruby hash object to JSON?

You can also use JSON.generate:

require 'json'

JSON.generate({ foo: "bar" })
=> "{\"foo\":\"bar\"}"

Or its alias, JSON.unparse:

require 'json'

JSON.unparse({ foo: "bar" })
=> "{\"foo\":\"bar\"}"

How to set max width of an image in CSS

The problem is that img tag is inline element and you can't restrict width of inline element.

So to restrict img tag width first you need to convert it into a inline-block element

img.Image{
    display: inline-block;
}

Python __call__ special method practical example

Class-based decorators use __call__ to reference the wrapped function. E.g.:

class Deco(object):
    def __init__(self,f):
        self.f = f
    def __call__(self, *args, **kwargs):
        print args
        print kwargs
        self.f(*args, **kwargs)

There is a good description of the various options here at Artima.com

How to display a range input slider vertically

You can do this with css transforms, though be careful with container height/width. Also you may need to position it lower:

_x000D_
_x000D_
input[type="range"] {_x000D_
   position: absolute;_x000D_
   top: 40%;_x000D_
   transform: rotate(270deg);_x000D_
}
_x000D_
<input type="range"/>
_x000D_
_x000D_
_x000D_


or the 3d transform equivalent:

input[type="range"] {
   transform: rotateZ(270deg);
}

You can also use this to switch the direction of the slide by setting it to 180deg or 90deg for horizontal or vertical respectively.

BigDecimal to string

// Convert BigDecimal number To String by using below method //

public static String RemoveTrailingZeros(BigDecimal tempDecimal)
{
    tempDecimal = tempDecimal.stripTrailingZeros();
    String tempString = tempDecimal.toPlainString();
    return tempString;
}

// Recall RemoveTrailingZeros
BigDecimal output = new BigDecimal(0);
String str = RemoveTrailingZeros(output);

Update Fragment from ViewPager

Because none of the above answers did the trick for me, here is my solution:

I combined the POSITION_NONE with loading on setUserVisibleHint(boolean isVisibleToUser) instead of onStart()

As seen here: https://stackoverflow.com/a/25676323/497366

In the Fragment:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // load data here
    }else{
       // fragment is no longer visible
    }
}

and in the FragmentStatePagerAdapter as seen in the top answer here from Simon Dorociak https://stackoverflow.com/a/18088509/497366:

@Override
public int getItemPosition(@NonNull Object object) {
    return POSITION_NONE;
}

Now the fragments reload the data into their views everytime they are shown to the user.

How to use querySelectorAll only for elements that have a specific attribute set?

You can use querySelectorAll() like this:

var test = document.querySelectorAll('input[value][type="checkbox"]:not([value=""])');

This translates to:

get all inputs with the attribute "value" and has the attribute "value" that is not blank.

In this demo, it disables the checkbox with a non-blank value.

Android Service needs to run always (Never pause or stop)

You can implement startForeground for the service and even if it dies you can restart it by using START_STICKY on startCommand(). Not sure though this is the right implementation.

Rails Model find where not equal

Rails 4:

If you want to use both not equal and equal, you can use:

user_id = 4
group_id = 27
GroupUser.where(group_id: group_id).where.not(user_id: user_id)

If you want to use a variety of operators (ie. >, <), at some point you may want to switch notations to the following:

GroupUser.where("group_id > ? AND user_id != ?", group_id, user_id)

Check if a String contains a special character

//without using regular expression........

    String specialCharacters=" !#$%&'()*+,-./:;<=>?@[]^_`{|}~0123456789";
    String name="3_ saroj@";
    String str2[]=name.split("");

    for (int i=0;i<str2.length;i++)
    {
    if (specialCharacters.contains(str2[i]))
    {
        System.out.println("true");
        //break;
    }
    else
        System.out.println("false");
    }

Typing Greek letters etc. in Python plots

Not only can you add raw strings to matplotlib but you can also specify the font in matplotlibrc or locally with:

from matplotlib import rc

rc('font', **{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)

This would change your serif latex font. You can also specify the sans-serif Helvetica like so

rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})

Other options are cursive and monospace with their respective font names. Your label would then be

fig.gca().set_xlabel(r'wavelength $5000 \AA$')

If the font doesn't supply an Angstrom symbol you can try using \mathring{A}

Node.js setting up environment specific configs to be used with everyauth

In brief

This kind of a setup is simple and elegant :

env.json

{
  "development": {
      "facebook_app_id": "facebook_dummy_dev_app_id",
      "facebook_app_secret": "facebook_dummy_dev_app_secret",
  }, 
  "production": {
      "facebook_app_id": "facebook_dummy_prod_app_id",
      "facebook_app_secret": "facebook_dummy_prod_app_secret",
  }
}

common.js

var env = require('env.json');

exports.config = function() {
  var node_env = process.env.NODE_ENV || 'development';
  return env[node_env];
};

app.js

var common = require('./routes/common')
var config = common.config();

var facebook_app_id = config.facebook_app_id;
// do something with facebook_app_id

To run in production mode : $ NODE_ENV=production node app.js


In detail

This solution is from : http://himanshu.gilani.info/blog/2012/09/26/bootstraping-a-node-dot-js-app-for-dev-slash-prod-environment/, check it out for more detail.

What is the current directory in a batch file?

In a batch file, %cd% is the most commonly used command for the current directory, although you can set your own variable:

set mypath=%cd%
echo %mypath% (where %mypath% is the current directory that the batch file is sitting in)

So say you were wanting to open Myprog.exe. If it was in the same folder, you would use the command:

start %mypath%\Myprog.exe

That would open Myprog from the current folder.

The other option is to make a directory in C: called AutomatePrograms. Then, you transfer your files to that folder then you can open them using the following command:

start "" "C:\AutomatePrograms\Myprog1.exe"
start "" "C:\AutomatePrograms\Myprog2.exe"
start "" "C:\AutomatePrograms\Myprog3.exe"

PHPDoc type hinting for array of objects?

Use:

/* @var $objs Test[] */
foreach ($objs as $obj) {
    // Typehinting will occur after typing $obj->
}

when typehinting inline variables, and

class A {
    /** @var Test[] */
    private $items;
}

for class properties.

Previous answer from '09 when PHPDoc (and IDEs like Zend Studio and Netbeans) didn't have that option:

The best you can do is say,

foreach ($Objs as $Obj)
{
    /* @var $Obj Test */
    // You should be able to get hinting after the preceding line if you type $Obj->
}

I do that a lot in Zend Studio. Don't know about other editors, but it ought to work.

Writing JSON object to a JSON file with fs.writeFileSync

When sending data to a web server, the data has to be a string (here). You can convert a JavaScript object into a string with JSON.stringify(). Here is a working example:

var fs = require('fs');

var originalNote = {
  title: 'Meeting',
  description: 'Meeting John Doe at 10:30 am'
};

var originalNoteString = JSON.stringify(originalNote);

fs.writeFileSync('notes.json', originalNoteString);

var noteString = fs.readFileSync('notes.json');

var note = JSON.parse(noteString);

console.log(`TITLE: ${note.title} DESCRIPTION: ${note.description}`);

Hope it could help.

Cross Domain Form POSTing

The same origin policy is applicable only for browser side programming languages. So if you try to post to a different server than the origin server using JavaScript, then the same origin policy comes into play but if you post directly from the form i.e. the action points to a different server like:

<form action="http://someotherserver.com">

and there is no javascript involved in posting the form, then the same origin policy is not applicable.

See wikipedia for more information

Remove duplicates from an array of objects in JavaScript

The simplest way is use filter:

_x000D_
_x000D_
var uniq = {}_x000D_
var arr  = [{"id":"1"},{"id":"1"},{"id":"2"}]_x000D_
var arrFiltered = arr.filter(obj => !uniq[obj.id] && (uniq[obj.id] = true));_x000D_
console.log('arrFiltered', arrFiltered)
_x000D_
_x000D_
_x000D_

redistributable offline .NET Framework 3.5 installer for Windows 8

You don't have to copy everything to C:\dotnet35. Usually all the files are already copied to the folder C:\Windows\WinSxS. Then the command becomes (assuming Windows was installed to C:): "Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:C:\Windows\WinSxS /LimitAccess" If not you can also point the command to the DVD directly. Then the command becomes (assuming DVD is mounted to D:): "Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:D:\sources\sxs /LimitAccess".

Test for array of string type in TypeScript

Try this:

if (value instanceof Array) {
alert('value is Array!');
} else {
alert('Not an array');
}

How do you make a LinearLayout scrollable?

<ScrollView 
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/scroll" 
      android:layout_width="match_parent"
      android:layout_height="wrap_content">

      <LinearLayout 
            android:id="@+id/container"
            android:orientation="vertical" 
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
      </LinearLayout>

 </ScrollView>

How to output a comma delimited list in jinja python template?

you could also use the builtin "join" filter (http://jinja.pocoo.org/docs/templates/#join like this:

{{ users|join(', ') }}

How to refer to relative paths of resources when working with a code repository

In Python, paths are relative to the current working directory, which in most cases is the directory from which you run your program. The current working directory is very likely not as same as the directory of your module file, so using a path relative to your current module file is always a bad choice.

Using absolute path should be the best solution:

import os
package_dir = os.path.dirname(os.path.abspath(__file__))
thefile = os.path.join(package_dir,'test.cvs')

How to get UTC value for SYSDATE on Oracle

You can use

SELECT SYS_EXTRACT_UTC(TIMESTAMP '2000-03-28 11:30:00.00 -02:00') FROM DUAL;

You may also need to change your timezone

ALTER SESSION SET TIME_ZONE = 'Europe/Berlin';

Or read it

SELECT SESSIONTIMEZONE, CURRENT_TIMESTAMP FROM dual;

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

This is a problem for users who live in a country that is banned by Google (like Iran). for this reason we need to remove these restrictions by a proxy. follow me :

file->settings->Appearance&Behavior->System Setting-> Http Proxy-> Manual proxy configuration ->HTTP -> Host name : fodev.org ->Port : 8118 .

and click Ok Button. then go to file-> Invalidate Caches/Restart . . . Use and enjoy the correct execution without error ;)

Twig: in_array or similar possible within if statement?

Try this

{% if var in ['foo', 'bar', 'beer'] %}
    ...
{% endif %}

Anyway to prevent the Blue highlighting of elements in Chrome when clicking quickly?

But, sometimes, even with user-select and touch-callout turned off, cursor: pointer; may cause this effect, so, just set cursor: default; and it'll work.

Java collections convert a string to a list of characters

The lack of a good way to convert between a primitive array and a collection of its corresponding wrapper type is solved by some third party libraries. Guava, a very common one, has a convenience method to do the conversion:

List<Character> characterList = Chars.asList("abc".toCharArray());
Set<Character> characterSet = new HashSet<Character>(characterList);

Encode URL in JavaScript?

The best answer is to use encodeURIComponent on values in the query string (and nowhere else).

However, I find that many APIs want to replace " " with "+" so I've had to use the following:

const value = encodeURIComponent(value).replace('%20','+');
const url = 'http://example.com?lang=en&key=' + value

escape is implemented differently in different browsers and encodeURI doesn't encode many characters (like # and even /) -- it's made to be used on a full URI/URL without breaking it – which isn't super helpful or secure.

And as @Jochem points out below, you may want to use encodeURIComponent() on a (each) folder name, but for whatever reason these APIs don't seem to want + in folder names so plain old encodeURIComponent works great.

Example:

const escapedValue = encodeURIComponent(value).replace('%20','+');
const escapedFolder = encodeURIComponent('My Folder'); // no replace
const url = `http://example.com/${escapedFolder}/?myKey=${escapedValue}`;

How to develop or migrate apps for iPhone 5 screen resolution?

Using xCode 5, select "Migrate to Asset Catalog" on Project>General.

Then use "Show in finder" to find your launch image, you can dummy-edit it to be 640x1136, then drag it into the asset catalog as shown in the image below.

Make sure that both iOS7 and iOS6 R4 section has an image that is 640x1136. Next time you launch the app, the black bars will disappear, and your app will use 4 inch screen

enter image description here

Angularjs $q.all

$http is a promise too, you can make it simpler:

return $q.all(tasks.map(function(d){
        return $http.post('upload/tasks',d).then(someProcessCallback, onErrorCallback);
    }));

How to check ASP.NET Version loaded on a system?

Here is some code that will return the installed .NET details:

<%@ Page Language="VB" Debug="true" %>
<%@ Import namespace="System" %>
<%@ Import namespace="System.IO" %>
<% 
Dim cmnNETver, cmnNETdiv, aspNETver, aspNETdiv As Object
Dim winOSver, cmnNETfix, aspNETfil(2), aspNETtxt(2), aspNETpth(2), aspNETfix(2) As String

winOSver = Environment.OSVersion.ToString
cmnNETver = Environment.Version.ToString
cmnNETdiv = cmnNETver.Split(".")
cmnNETfix = "v" & cmnNETdiv(0) & "." & cmnNETdiv(1) & "." & cmnNETdiv(2)

For filndx As Integer = 0 To 2
  aspNETfil(0) = "ngen.exe"
  aspNETfil(1) = "clr.dll"
  aspNETfil(2) = "KernelBase.dll"

  If filndx = 2   
    aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), aspNETfil(filndx))
  Else
    aspNETpth(filndx) = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Microsoft.NET\Framework64", cmnNETfix, aspNETfil(filndx))
  End If

  If File.Exists(aspNETpth(filndx)) Then
    aspNETver = Diagnostics.FileVersionInfo.GetVersionInfo(aspNETpth(filndx))
    aspNETtxt(filndx) = aspNETver.FileVersion.ToString
    aspNETdiv = aspNETtxt(filndx).Split(" ")
    aspNETfix(filndx) = aspNETdiv(0)
  Else
    aspNETfix(filndx) = "Path not found... No version found..."
  End If
Next

Response.Write("Common MS.NET Version (raw): " & cmnNETver & "<br>")
Response.Write("Common MS.NET path: " & cmnNETfix & "<br>")
Response.Write("Microsoft.NET full path: " & aspNETpth(0) & "<br>")
Response.Write("Microsoft.NET Version (raw): " & aspNETtxt(0) & "<br>")
Response.Write("<b>Microsoft.NET Version: " & aspNETfix(0) & "</b><br>")
Response.Write("ASP.NET full path: " & aspNETpth(1) & "<br>")
Response.Write("ASP.NET Version (raw): " & aspNETtxt(1) & "<br>")
Response.Write("<b>ASP.NET Version: " & aspNETfix(1) & "</b><br>")
Response.Write("OS Version (system): " & winOSver & "<br>")
Response.Write("OS Version full path: " & aspNETpth(2) & "<br>")
Response.Write("OS Version (raw): " & aspNETtxt(2) & "<br>")
Response.Write("<b>OS Version: " & aspNETfix(2) & "</b><br>")
%>

Here is the new output, cleaner code, more output:

Common MS.NET Version (raw): 4.0.30319.42000
Common MS.NET path: v4.0.30319
Microsoft.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\ngen.exe
Microsoft.NET Version (raw): 4.6.1586.0 built by: NETFXREL2
Microsoft.NET Version: 4.6.1586.0
ASP.NET full path: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\clr.dll
ASP.NET Version (raw): 4.7.2110.0 built by: NET47REL1LAST
ASP.NET Version: 4.7.2110.0
OS Version (system): Microsoft Windows NT 10.0.14393.0
OS Version full path: C:\Windows\system32\KernelBase.dll
OS Version (raw): 10.0.14393.1715 (rs1_release_inmarket.170906-1810)
OS Version: 10.0.14393.1715

How to get history on react-router v4?

If you are using redux and redux-thunk the best solution will be using react-router-redux

// then, in redux actions for example
import { push } from 'react-router-redux'

dispatch(push('/some/path'))

It's important to see the docs to do some configurations.

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

First off, your code is a bit off. aes() is an argument in ggplot(), you don't use ggplot(...) + aes(...) + layers

Second, from the help file ?geom_bar:

By default, geom_bar uses stat="count" which makes the height of the bar proportion to the number of cases in each group (or if the weight aethetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use stat="identity" and map a variable to the y aesthetic.

You want the second case, where the height of the bar is equal to the conversion_rate So what you want is...

data_country <- data.frame(country = c("China", "Germany", "UK", "US"), 
            conversion_rate = c(0.001331558,0.062428188, 0.052612025, 0.037800687))
ggplot(data_country, aes(x=country,y = conversion_rate)) +geom_bar(stat = "identity")

Result:

enter image description here

How can I run MongoDB as a Windows service?

mongod --config "C:\Program Files\MongoDB\Server\3.6\mongod_primary.cfg" --install --serviceName "MongoDB_Primary" --serviceDisplayName "MongoDB Primary"

ASP.NET Core Get Json Array using IConfiguration

To get all values of all sections from appsettings.json

        public static string[] Sections = { "LogDirectory", "Application", "Email" };
        Dictionary<string, string> sectionDictionary = new Dictionary<string, string>();

        List<string> sectionNames = new List<string>(Sections);
        
        sectionNames.ForEach(section =>
        {
            List<KeyValuePair<string, string>> sectionValues = configuration.GetSection(section)
                    .AsEnumerable()
                    .Where(p => p.Value != null)
                    .ToList();
            foreach (var subSection in sectionValues)
            {
                sectionDictionary.Add(subSection.Key, subSection.Value);
            }
        });
        return sectionDictionary;

Jquery check if element is visible in viewport

You can see this example.

// Is this element visible onscreen?
var visible = $(#element).visible( detectPartial );

detectPartial :

  • True : the entire element is visible
  • false : part of the element is visible

visible is boolean variable which indicates if the element is visible or not.

How to loop through Excel files and load them into a database using SSIS package?

Here is one possible way of doing this based on the assumption that there will not be any blank sheets in the Excel files and also all the sheets follow the exact same structure. Also, under the assumption that the file extension is only .xlsx

Following example was created using SSIS 2008 R2 and Excel 2007. The working folder for this example is F:\Temp\

In the folder path F:\Temp\, create an Excel 2007 spreadsheet file named States_1.xlsx with two worksheets.

Sheet 1 of States_1.xlsx contained the following data

States_1_Sheet_1

Sheet 2 of States_1.xlsx contained the following data

States_1_Sheet_2

In the folder path F:\Temp\, create another Excel 2007 spreadsheet file named States_2.xlsx with two worksheets.

Sheet 1 of States_2.xlsx contained the following data

States_2_Sheet_1

Sheet 2 of States_2.xlsx contained the following data

States_2_Sheet_2

Create a table in SQL Server named dbo.Destination using the below create script. Excel sheet data will be inserted into this table.

CREATE TABLE [dbo].[Destination](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [State] [nvarchar](255) NULL,
    [Country] [nvarchar](255) NULL,
    [FilePath] [nvarchar](255) NULL,
    [SheetName] [nvarchar](255) NULL,
CONSTRAINT [PK_Destination] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

The table is currently empty.

Empty table

Create a new SSIS package and on the package, create the following 4 variables. FolderPath will contain the folder where the Excel files are stored. FilePattern will contain the extension of the files that will be looped through and this example works only for .xlsx. FilePath will be assigned with a value by the Foreach Loop container but we need a valid path to begin with for design time and it is currently populated with the path F:\Temp\States_1.xlsx of the first Excel file. SheetName will contain the actual sheet name but we need to populate with initial value Sheet1$ to avoid design time error.

Variables

In the package's connection manager, create an ADO.NET connection with the following configuration and name it as ExcelSchema.

Select the provider Microsoft Office 12.0 Access Database Engine OLE DB Provider under .Net Providers for OleDb. Provide the file path F:\Temp\States_1.xlsx

ExcelSchema 1

Click on the All section on the left side and set the property Extended Properties to Excel 12.0 to denote the version of Excel. Here in this case 12.0 denotes Excel 2007. Click on the Test Connection to make sure that the connection succeeds.

ExcelSchema 2

Create an Excel connection manager named Excel as shown below.

Excel

Create an OLE DB Connection SQL Server named SQLServer. So, we should have three connections on the package as shown below.

Connections

We need to do the following connection string changes so that the Excel file is dynamically changed as the files are looped through.

On the connection ExcelSchema, configure the expression ServerName to use the variable FilePath. Click on the ellipsis button to configure the expression.

ExcelSchema ServerName

Similarly on the connection Excel, configure the expression ServerName to use the variable FilePath. Click on the ellipsis button to configure the expression.

Excel ServerName

On the Control Flow, place two Foreach Loop containers one within the other. The first Foreach Loop container named Loop files will loop through the files. The second Foreach Loop container will through the sheets within the container. Within the inner For each loop container, place a Data Flow Task that will read the Excel files and load data into SQL

Control Flow

Configure the first Foreach loop container named Loop files as shown below:

Foreach Loop 1 Collection

Foreach Loop 1 Variable Mappings

Configure the first Foreach loop container named Loop sheets as shown below:

Foreach Loop 2 Collection

Foreach Loop 2 Variable Mappings

Inside the data flow task, place an Excel Source, Derived Column and OLE DB Destination as shown below:

Data Flow Task

Configure the Excel Source to read the appropriate Excel file and the sheet that is currently being looped through.

Excel Source Connection Manager

Excel Source Columns

Configure the derived column to create new columns for file name and sheet name. This is just to demonstrate this example but has no significance.

Derived column

Configure the OLE DB destination to insert the data into the SQL table.

OLE DB Destination Connection Manager

OLE DB Destination Columns

Below screenshot shows successful execution of the package.

Execution successful

Below screenshot shows that data from the 4 workbooks in 2 Excel spreadsheets that were creating in the beginning of this answer is correctly loaded into the SQL table dbo.Destination.

SQL table

Hope that helps.

Assembly code vs Machine code vs Object code?

8B 5D 32 is machine code

mov ebx, [ebp+32h] is assembly

lmylib.so containing 8B 5D 32 is object code

Finding absolute value of a number without using Math.abs()

Although this shouldn't be a bottle neck as branching issues on modern processors isn't normally a problem, but in the case of integers you could go for a branch-less solution as outlined here: http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs.

(x + (x >> 31)) ^ (x >> 31);

This does fail in the obvious case of Integer.MIN_VALUE however, so this is a use at your own risk solution.

How to convert BigInteger to String in java

To reverse

byte[] bytemsg=msg.getBytes(); 

you can use

String text = new String(bytemsg); 

using a BigInteger just complicates things, in fact it not clear why you want a byte[]. What are planing to do with the BigInteger or byte[]? What is the point?

Java constructor/method with optional parameters?

Java doesn't have the concept of optional parameters with default values either in constructors or in methods. You're basically stuck with overloading. However, you chain constructors easily so you don't need to repeat the code:

public Foo(int param1, int param2)
{
    this.param1 = param1;
    this.param2 = param2;
}

public Foo(int param1)
{
    this(param1, 2);
}

How to specify a local file within html using the file: scheme?

The file: URL scheme refers to a file on the client machine. There is no hostname in the file: scheme; you just provide the path of the file. So, the file on your local machine would be file:///~User/2ndFile.html. Notice the three slashes; the hostname part of the URL is empty, so the slash at the beginning of the path immediately follows the double slash at the beginning of the URL. You will also need to expand the user's path; ~ does no expand in a file: URL. So you would need file:///home/User/2ndFile.html (on most Unixes), file:///Users/User/2ndFile.html (on Mac OS X), or file:///C:/Users/User/2ndFile.html (on Windows).

Many browsers, for security reasons, do not allow linking from a file that is loaded from a server to a local file. So, you may not be able to do this from a page loaded via HTTP; you may only be able to link to file: URLs from other local pages.

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

Use:

$data = DB::select('select * from users where id = :id', ['id' => 1]);
print_r($data);

Output will like below:

Array ( [0] => stdClass Object ( [id] => 1 [name] => parisa [last] => naderi [username] => png [password] => 2132 [role] => 0 ) )

Email validation using jQuery

jQuery Function to Validate Email

I really don’t like to use plugins, especially when my form only has one field that needs to be validated. I use this function and call it whenever I need to validate an email form field.

 function validateEmail($email) {
  var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
  return emailReg.test( $email );
}

and now to use this

if( !validateEmail(emailaddress)) { /* do stuff here */ }

Cheers!

How do you connect to multiple MySQL databases on a single webpage?

Try below code:

    $conn = mysql_connect("hostname","username","password");
    mysql_select_db("db1",$conn);
    mysql_select_db("db2",$conn);

    $query1 = "SELECT * FROM db1.table";
    $query2 = "SELECT * FROM db2.table";

You can fetch data of above query from both database as below

$rs = mysql_query($query1);
while($row = mysql_fetch_assoc($rs)) {
    $data1[] = $row;
}

$rs = mysql_query($query2);
while($row = mysql_fetch_assoc($rs)) {
    $data2[] = $row;
}

print_r($data1);
print_r($data2);

Automatically size JPanel inside JFrame

If the BorderLayout option provided by our friends doesnot work, try adding ComponentListerner to the JFrame and implement the componentResized(event) method. When the JFrame object will be resized, this method will be called. So if you write the the code to set the size of the JPanel in this method, you will achieve the intended result.

Ya, I know this 'solution' is not good but use it as a safety net. ;)

An efficient way to Base64 encode a byte array?

Based on your edit and comments.. would this be what you're after?

byte[] newByteArray = UTF8Encoding.UTF8.GetBytes(Convert.ToBase64String(currentByteArray));

html5 input for money/currency

Using javascript's Number.prototype.toLocaleString:

_x000D_
_x000D_
var currencyInput = document.querySelector('input[type="currency"]')
var currency = 'GBP' // https://www.currency-iso.org/dam/downloads/lists/list_one.xml

 // format inital value
onBlur({target:currencyInput})

// bind event listeners
currencyInput.addEventListener('focus', onFocus)
currencyInput.addEventListener('blur', onBlur)


function localStringToNumber( s ){
  return Number(String(s).replace(/[^0-9.-]+/g,""))
}

function onFocus(e){
  var value = e.target.value;
  e.target.value = value ? localStringToNumber(value) : ''
}

function onBlur(e){
  var value = e.target.value

  var options = {
      maximumFractionDigits : 2,
      currency              : currency,
      style                 : "currency",
      currencyDisplay       : "symbol"
  }
  
  e.target.value = (value || value === 0) 
    ? localStringToNumber(value).toLocaleString(undefined, options)
    : ''
}
_x000D_
input{
  padding: 10px;
  font: 20px Arial;
  width: 70%;
}
_x000D_
<input type='currency' value="123" placeholder='Type a number & click outside' />
_x000D_
_x000D_
_x000D_

Here's a very simple demo illustrating the above method (HTML-only)


I've made a tiny React component if anyone's interested

Linq to SQL .Sum() without group ... into

you can:

itemsCart.Select(c=>c.Price).Sum();

To hit the db only once do:

var itemsInCart = (from o in db.OrderLineItems
                  where o.OrderId == currentOrder.OrderId
                  select new { o.OrderLineItemId, ..., ..., o.WishListItem.Price}
                  ).ToList();
var sum = itemsCart.Select(c=>c.Price).Sum();

The extra round-trip saved is worth it :)

Add a user control to a wpf window

You probably need to add the namespace:

<Window x:Class="UserControlTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:UserControlTest"
    Title="User Control Test" Height="300" Width="300">
    <local:UserControl1 />
</Window>

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

Logger slf4j advantages of formatting with {} instead of string concatenation

Since, String is immutable in Java, so the left and right String have to be copied into the new String for every pair of concatenation. So, better go for the placeholder.

Is there a simple, elegant way to define singletons?

The Singleton Pattern implemented with Python courtesy of ActiveState.

It looks like the trick is to put the class that's supposed to only have one instance inside of another class.

Java for loop syntax: "for (T obj : objects)"

That's the for each loop syntax. It is looping through each object in the collection returned by objectListing.getObjectSummaries().

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

Yes, it is security issue. Check folder permissions and service account under which SQL server 2008 starts.

Where does Internet Explorer store saved passwords?

Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.

Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.

You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.

To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.

A typical C++ code will be:

hVaultLib = LoadLibrary(L"vaultcli.dll");

if (hVaultLib != NULL) 
{
    pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
    pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
    pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
    pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
    pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");

    bStatus = (pVaultEnumerateVaults != NULL)
        && (pVaultFree != NULL)
        && (pVaultGetItemW7 != NULL)
        && (pVaultGetItemW8 != NULL)
        && (pVaultOpenVault != NULL)
        && (pVaultCloseVault != NULL)
        && (pVaultEnumerateItems != NULL);
}

Then you enumerate all stored credentials by calling

VaultEnumerateVaults

Then you go over the results.

How to verify static void method has been called with power mockito

If you are mocking the behavior (with something like doNothing()) there should really be no need to call to verify*(). That said, here's my stab at re-writing your test method:

@PrepareForTest({InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest { //Note the renaming of the test class.
   public void testProcessOrder() {
        //Variables
        InternalService is = new InternalService();
        Order order = mock(Order.class);

        //Mock Behavior
        when(order.isSuccessful()).thenReturn(true);
        mockStatic(Internalutils.class);
        doNothing().when(InternalUtils.class); //This is the preferred way
                                               //to mock static void methods.
        InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

        //Execute
        is.processOrder(order);            

        //Verify
        verifyStatic(InternalUtils.class); //Similar to how you mock static methods
                                           //this is how you verify them.
        InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
   }
}

I grouped into four sections to better highlight what is going on:

1. Variables

I choose to declare any instance variables / method arguments / mock collaborators here. If it is something used in multiple tests, consider making it an instance variable of the test class.

2. Mock Behavior

This is where you define the behavior of all of your mocks. You're setting up return values and expectations here, prior to executing the code under test. Generally speaking, if you set the mock behavior here you wouldn't need to verify the behavior later.

3. Execute

Nothing fancy here; this just kicks off the code being tested. I like to give it its own section to call attention to it.

4. Verify

This is when you call any method starting with verify or assert. After the test is over, you check that the things you wanted to have happen actually did happen. That is the biggest mistake I see with your test method; you attempted to verify the method call before it was ever given a chance to run. Second to that is you never specified which static method you wanted to verify.

Additional Notes

This is mostly personal preference on my part. There is a certain order you need to do things in but within each grouping there is a little wiggle room. This helps me quickly separate out what is happening where.

I also highly recommend going through the examples at the following sites as they are very robust and can help with the majority of the cases you'll need:

Java, List only subdirectories from a directory, not files

@Mohamed Mansour you were almost there... the "dir" argument from that you were using is actually the curent path, so it will always return true. In order to see if the child is a subdirectory or not you need to test that child.

File file = new File("/path/to/directory");
String[] directories = file.list(new FilenameFilter() {
  @Override
  public boolean accept(File current, String name) {
    return new File(current, name).isDirectory();
  }
});
System.out.println(Arrays.toString(directories));

php string to int

Use str_replace to remove the spaces first ?

How to recover closed output window in netbeans?

shorter way: 1-Alt + Shift + R 2-Ctrl + 4 second way:(in menus of netBeans) 1-go to window tab 2-go to IDE tools 3-click on Test Result 4-again in window tab click on Output

How to run a bash script from C++ program

StackOverflow: How to execute a command and get output of command within C++?

StackOverflow: (Using fork,pipe,select): ...nobody does things the hard way any more...

Also if you know how to make user become the super-user that would be nice also. Thanks!

sudo. su. chmod 04500. (setuid() & seteuid(), but they require you to already be root. E..g. chmod'ed 04***.)

Take care. These can open "interesting" security holes...

Depending on what you are doing, you may not need root. (For instance: I'll often chmod/chown /dev devices (serial ports, etc) (under sudo root) so I can use them from my software without being root. On the other hand, that doesn't work so well when loading/unloading kernel modules...)