Programs & Examples On #Sparklines

A jQuery plugin that generates sparklines (small inline charts).

Laravel 5 - artisan seed [ReflectionException] Class SongsTableSeeder does not exist

If our CustomTableSeeder is in same directory with DatabaseSeeder we should use like below:

$this->call('database\seeds\CustomTableSeeder');

in our DatabaseSeeder File; then another error will be thrown that says: 'DB Class not found' then we should add our DB facade to our CustomTableSeeder File like below:

use Illuminate\Support\Facades\DB;

it worked for me!

How do I convert a String object into a Hash object?

Quick and dirty method would be

eval("{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, :key_b => { :key_1b => 'value_1b' } }") 

But it has severe security implications.
It executes whatever it is passed, you must be 110% sure (as in, at least no user input anywhere along the way) it would contain only properly formed hashes or unexpected bugs/horrible creatures from outer space might start popping up.

Print out the values of a (Mat) matrix in OpenCV C++

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <iomanip>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    double data[4] = {-0.0000000077898273846583732, -0.03749374753019832, -0.0374787251930463, -0.000000000077893623846343843};
    Mat src = Mat(1, 4, CV_64F, &data);
    for(int i=0; i<4; i++)
        cout << setprecision(3) << src.at<double>(0,i) << endl;

    return 0;
}

C++ array initialization

Note that the '=' is optional in C++11 universal initialization syntax, and it is generally considered better style to write :

char myarray[ARRAY_SIZE] {0}

How to create custom button in Android using XML Styles

<gradient android:startColor="#ffdd00"
    android:endColor="@color/colorPrimary"
    android:centerColor="#ffff" />

<corners android:radius="33dp"/>

<padding
    android:bottom="7dp"
    android:left="7dp"
    android:right="7dp"
    android:top="7dp"
    />

Imported a csv-dataset to R but the values becomes factors

You can set this globally for all read.csv/read.* commands with options(stringsAsFactors=F)

Then read the file as follows: my.tab <- read.table( "filename.csv", as.is=T )

adb doesn't show nexus 5 device

What you need to do is this:

Settings | About Phone

Scroll to the bottom to build number. Tap on build number about 7 times. Each time you will get a popup message saying you are x steps away from being a developer

When you get to the final step you will get a message saying now you are a developer

Go back into settings and you will see a new setting Developer options there you will see a lot of options for developers. Enable USB debugging

Re-connect you phone to the usb, and you should see you device under adb devices.

I hope this answer helps someone else.

typeof !== "undefined" vs. != null

_x000D_
_x000D_
var bar = null;_x000D_
console.log(typeof bar === "object"); //true yes _x000D_
//because null a datatype of object_x000D_
_x000D_
var barf = "dff";_x000D_
console.log(typeof barf.constructor);//function_x000D_
_x000D_
_x000D_
console.log(Array.isArray(bar));//falsss_x000D_
_x000D_
_x000D_
console.log((bar !== null) && (bar.constructor === Object)); //false_x000D_
_x000D_
console.log((bar !== null) && (typeof bar === "object"));  // logs false_x000D_
//because bar!==null, bar is a object_x000D_
_x000D_
_x000D_
console.log((bar !== null) && ((typeof bar === "object") || (typeof bar === "function"))); //false_x000D_
_x000D_
console.log(typeof bar === typeof object); //false_x000D_
console.log(typeof bar2 === typeof undefined); //true_x000D_
console.log(typeof bar3 === typeof undefinedff); //true_x000D_
console.log(typeof bar2 == typeof undefined); //true_x000D_
_x000D_
console.log((bar !== null) && (typeof bar === "object") && (toString.call(bar) !== "[object Array]")); //false
_x000D_
_x000D_
_x000D_

Batch file to perform start, run, %TEMP% and delete all

@echo off
del /s /f /q c:\windows\temp\*.*
rd /s /q c:\windows\temp
md c:\windows\temp
del /s /f /q C:\WINDOWS\Prefetch
del /s /f /q %temp%\*.*
rd /s /q %temp%
md %temp%
deltree /y c:\windows\tempor~1
deltree /y c:\windows\temp
deltree /y c:\windows\tmp
deltree /y c:\windows\ff*.tmp
deltree /y c:\windows\history
deltree /y c:\windows\cookies
deltree /y c:\windows\recent
deltree /y c:\windows\spool\printers
del c:\WIN386.SWP
cls

EnterKey to press button in VBA Userform

Here you can simply use:

SendKeys "{ENTER}" at the end of code linked to the Username field.

And so you can skip pressing ENTER Key once (one time).
And as a result, the next button ("Log In" button here) will be activated. And when you press ENTER once (your desired outcome), It will run code which is linked with "Log In" button.

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

Absolute XPath: It is the direct way to find the element, but the disadvantage of the absolute XPath is that if there are any changes made in the path of the element then that XPath gets failed.

The key characteristic of XPath is that it begins with the single forward slash(/) ,which means you can select the element from the root node.

Below is the example of an absolute xpath.

/html/body/div[1]/section/div/div[2]/div/form/div[2]/input[3]

Relative Xpath: Relative Xpath starts from the middle of HTML DOM structure. It starts with double forward slash (//). It can search elements anywhere on the webpage, means no need to write a long xpath and you can start from the middle of HTML DOM structure. Relative Xpath is always preferred as it is not a complete path from the root element.

Below is the example of a relative XPath.

//input[@name=’email’]

Android studio takes too much memory

I fond this YouTube video from Google where are some tips and tricks for it. The video also includes advantages and disadvantages of suggested changes.

Improving Android Studio Performance on Memory-Constrained Machines

What does operator "dot" (.) mean?

The dot itself is not an operator, .^ is.

The .^ is a pointwise¹ (i.e. element-wise) power, as .* is the pointwise product.

.^ Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. The sizes of A and B must be the same or be compatible.

C.f.

¹) Hence the dot.

Call one constructor from another

Constructor chaining i.e you can use "Base" for Is a relationship and "This" you can use for same class, when you want call multiple Constructor in single call.

  class BaseClass
{
    public BaseClass():this(10)
    {
    }
    public BaseClass(int val)
    {
    }
}
    class Program
    {
        static void Main(string[] args)
        {
            new BaseClass();
            ReadLine();
        }
    }

in_array multiple values

IMHO Mark Elliot's solution's best one for this problem. If you need to make more complex comparison operations between array elements AND you're on PHP 5.3, you might also think about something like the following:

<?php

// First Array To Compare
$a1 = array('foo','bar','c');

// Target Array
$b1 = array('foo','bar');


// Evaluation Function - we pass guard and target array
$b=true;
$test = function($x) use (&$b, $b1) {
        if (!in_array($x,$b1)) {
                $b=false;
        }
};


// Actual Test on array (can be repeated with others, but guard 
// needs to be initialized again, due to by reference assignment above)
array_walk($a1, $test);
var_dump($b);

This relies on a closure; comparison function can become much more powerful. Good luck!

currently unable to handle this request HTTP ERROR 500

Your site is serving a 500 Internal Server Error. This can be caused by a number of things, such as:

  • File Permissions
  • Fatal Code Errors
  • Web Server Issues

EDIT

As you have highlighted it is a permission issue. You need to ensure that your files are executable by the web server user

Please see below article for some guidance on proper file permissions. https://www.digitalocean.com/community/questions/proper-permissions-for-web-server-s-directory

How to implement a tree data-structure in Java?

    // TestTree.java
// A simple test to see how we can build a tree and populate it
//
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;

public class TestTree extends JFrame {

  JTree tree;
  DefaultTreeModel treeModel;

  public TestTree( ) {
    super("Tree Test Example");
    setSize(400, 300);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }

  public void init( ) {
    // Build up a bunch of TreeNodes. We use DefaultMutableTreeNode because the
    // DefaultTreeModel can use it to build a complete tree.
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    DefaultMutableTreeNode subroot = new DefaultMutableTreeNode("SubRoot");
    DefaultMutableTreeNode leaf1 = new DefaultMutableTreeNode("Leaf 1");
    DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode("Leaf 2");

    // Build our tree model starting at the root node, and then make a JTree out
    // of it.
    treeModel = new DefaultTreeModel(root);
    tree = new JTree(treeModel);

    // Build the tree up from the nodes we created.
    treeModel.insertNodeInto(subroot, root, 0);
    // Or, more succinctly:
    subroot.add(leaf1);
    root.add(leaf2);

    // Display it.
    getContentPane( ).add(tree, BorderLayout.CENTER);
  }

  public static void main(String args[]) {
    TestTree tt = new TestTree( );
    tt.init( );
    tt.setVisible(true);
  }
}

Creating a very simple linked list

I've created the following LinkedList code with many features. It is available for public under the CodeBase github public repo.

Classes: Node and LinkedList

Getters and Setters: First and Last

Functions: AddFirst(data), AddFirst(node), AddLast(data), RemoveLast(), AddAfter(node, data), RemoveBefore(node), Find(node), Remove(foundNode), Print(LinkedList)

using System;
using System.Collections.Generic;

namespace Codebase
{
    public class Node
    {
        public object Data { get; set; }
        public Node Next { get; set; }

        public Node()
        {
        }

        public Node(object Data, Node Next = null)
        {
            this.Data = Data;
            this.Next = Next;
        }
    }

    public class LinkedList
    {
        private Node Head;
        public Node First
        {
            get => Head;
            set
            {
                First.Data = value.Data;
                First.Next = value.Next;
            }
        }

        public Node Last
        {
            get
            {
                Node p = Head;
                //Based partially on https://en.wikipedia.org/wiki/Linked_list
                while (p.Next != null)
                    p = p.Next; //traverse the list until p is the last node.The last node always points to NULL.

                return p;
            }
            set
            {
                Last.Data = value.Data;
                Last.Next = value.Next;
            }
        }

        public void AddFirst(Object data, bool verbose = true)
        {
            Head = new Node(data, Head);
            if (verbose) Print();
        }

        public void AddFirst(Node node, bool verbose = true)
        {
            node.Next = Head;
            Head = node;
            if (verbose) Print();
        }

        public void AddLast(Object data, bool Verbose = true)
        {
            Last.Next = new Node(data);
            if (Verbose) Print();
        }

        public Node RemoveFirst(bool verbose = true)
        {
            Node temp = First;
            Head = First.Next;
            if (verbose) Print();
            return temp;
        }

        public Node RemoveLast(bool verbose = true)
        {
            Node p = Head;
            Node temp = Last;

            while (p.Next != temp)
                p = p.Next;

            p.Next = null;
            if (verbose) Print();

            return temp;
        }

        public void AddAfter(Node node, object data, bool verbose = true)
        {
            Node temp = new Node(data);
            temp.Next = node.Next;
            node.Next = temp;

            if (verbose) Print();
        }

        public void AddBefore(Node node, object data, bool verbose = true)
        {
            Node temp = new Node(data);

            Node p = Head;

            while (p.Next != node) //Finding the node before
            {
                p = p.Next;
            }

            temp.Next = p.Next; //same as  = node
            p.Next = temp;

            if (verbose) Print();
        }

        public Node Find(object data)
        {
            Node p = Head;

            while (p != null)
            {
                if (p.Data == data)
                    return p;

                p = p.Next;
            }
            return null;
        }

        public void Remove(Node node, bool verbose = true)
        {
            Node p = Head;

            while (p.Next != node)
            {
                p = p.Next;
            }

            p.Next = node.Next;
            if (verbose) Print();
        }

        public void Print()
        {
            Node p = Head;
            while (p != null) //LinkedList iterator
            {
                Console.Write(p.Data + " ");
                p = p.Next; //traverse the list until p is the last node.The last node always points to NULL.
            }
            Console.WriteLine();
        }
    }
}

Using @yogihosting answer when she used the Microsoft built-in LinkedList and LinkedListNode to answer the question, you can achieve the same results:

using System;
using System.Collections.Generic;
using Codebase;

namespace Cmd
{
    static class Program
    {
        static void Main(string[] args)
        {
            var tune = new LinkedList(); //Using custom code instead of the built-in LinkedList<T>
            tune.AddFirst("do"); // do
            tune.AddLast("so"); // do - so
            tune.AddAfter(tune.First, "re"); // do - re- so
            tune.AddAfter(tune.First.Next, "mi"); // do - re - mi- so
            tune.AddBefore(tune.Last, "fa"); // do - re - mi - fa- so
            tune.RemoveFirst(); // re - mi - fa - so
            tune.RemoveLast(); // re - mi - fa
            Node miNode = tune.Find("mi"); //Using custom code instead of the built in LinkedListNode
            tune.Remove(miNode); // re - fa
            tune.AddFirst(miNode); // mi- re - fa
 }
}

How to change language settings in R

For mac users, I found this on the R for Mac FAQ

If you use a non-standard setup (e.g. different language than formats), you can override the auto-detection performed by setting `force.LANG' defaults setting, such as for example

 defaults write org.R-project.R force.LANG en_US.UTF-8 

when run in Terminal it will enforce US-english setting regardless of the system setting. If you don't know what Terminal is you can use this R command instead:

 system("defaults write org.R-project.R force.LANG en_US.UTF-8") 

but do not forget to quit R and start R.app again afterwards. Please note that you must always use `.UTF-8' version of the locale, otherwise R.app will not work properly.

This helped me to change my console language from Chinese to English.

how to check the version of jar file?

Just to complete the above answer.

Manifest file is located inside jar at META-INF\MANIFEST.MF path.

You can examine jar's contents in any archiver that supports zip.

Is it possible to change a UIButtons background color?

Another possibility (the best and most beautiful imho):

Create a UISegmentedControl with 2 segments in the required background color in Interface Builder. Set the type to 'bar'. Then, change it to having only one segment. Interface builder does not accept one segment so you have to do that programmatically.

Therefore, create an IBOutlet for this button and add this to the viewDidLoad of your view:

[segmentedButton removeSegmentAtIndex:1 animated:NO];

Now you have a beautiful glossy, colored button with the specified background color. For actions, use the 'value changed' event.

(I have found this on http://chris-software.com/index.php/2009/05/13/creating-a-nice-glass-buttons/). Thanks Chris!

PostgreSQL how to see which queries have run

While using Django with postgres 10.6, logging was enabled by default, and I was able to simply do:

tail -f /var/log/postgresql/*

Ubuntu 18.04, django 2+, python3+

Difference between char* and const char*?

Actually, char* name is not a pointer to a constant, but a pointer to a variable. You might be talking about this other question.

What is the difference between char * const and const char *?

Search an Oracle database for tables with specific column names?

To find all tables with a particular column:

select owner, table_name from all_tab_columns where column_name = 'ID';

To find tables that have any or all of the 4 columns:

select owner, table_name, column_name
from all_tab_columns
where column_name in ('ID', 'FNAME', 'LNAME', 'ADDRESS');

To find tables that have all 4 columns (with none missing):

select owner, table_name
from all_tab_columns
where column_name in ('ID', 'FNAME', 'LNAME', 'ADDRESS')
group by owner, table_name
having count(*) = 4;

Spring Data: "delete by" is supported?

@Query(value = "delete from addresses u where u.ADDRESS_ID LIKE %:addressId%", nativeQuery = true)
void deleteAddressByAddressId(@Param("addressId") String addressId);

using batch echo with special characters

the escape character ^ also did not work for me. The single quotes worked for me (using ansible scripting)

shell: echo  '{{ jobid.content }}'

output:

 {
    "changed": true,
    "cmd": "echo  '<response status=\"success\" code=\"19\"><result><msg><line>query job enqueued with jobid 14447</line></msg><job>14447</job></result></response>'",
    "delta": "0:00:00.004943",
    "end": "2020-07-31 08:45:05.645672",
    "invocation": {
        "module_args": {
            "_raw_params": "echo  '<response status=\"success\" code=\"19\"><result><msg><line>query job enqueued with jobid 14447</line></msg><job>14447</job></result></response>'",
            "_uses_shell": true,
            "argv": null,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "stdin": null,
            "stdin_add_newline": true,
            "strip_empty_ends": true,
            "warn": true
        }
    },
    "rc": 0,
    "start": "2020-07-31 08:45:05.640729",
    "stderr": "",
    "stderr_lines": [],
    "stdout": "<response status=\"success\" code=\"19\"><result><msg><line>query job enqueued with jobid 14447</line></msg><job>14447</job></result></response>",
    "stdout_lines": [
        "<response status=\"success\" code=\"19\"><result><msg><line>query job enqueued with jobid 14447</line></msg><job>14447</job></result></response>"
    ]

What jsf component can render a div tag?

In JSF 2.2 it's possible to use passthrough elements:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:jsf="http://xmlns.jcp.org/jsf">
    ...
    <div jsf:id="id1" />
    ...
</html>

The requirement is to have at least one attribute in the element using jsf namespace.

C# switch statement limitations - why?

I don't see any reason why the switch statement has to succomb to static analysis only

True, it doesn't have to, and many languages do in fact use dynamic switch statements. This means however that reordering the "case" clauses can change the behaviour of the code.

There's some interesting info behind the design decisions that went into "switch" in here: Why is the C# switch statement designed to not allow fall-through, but still require a break?

Allowing dynamic case expressions can lead to monstrosities such as this PHP code:

switch (true) {
    case a == 5:
        ...
        break;
    case b == 10:
        ...
        break;
}

which frankly should just use the if-else statement.

Converting java.util.Properties to HashMap<String,String>

First thing,

Properties class is based on Hashtable and not Hashmap. Properties class basically extends Hashtable

There is no such constructor in HashMap class which takes a properties object and return you a hashmap object. So what you are doing is NOT correct. You should be able to cast the object of properties to hashtable reference.

How to set a DateTime variable in SQL Server 2008?

You want to make the format/style explicit and don't rely on interpretation based on local settings (which may vary among your clients infrastructure).

DECLARE @Test AS DATETIME
SET @Test = CONVERT(DATETIME, '2011-02-15 00:00:00', 120) -- yyyy-MM-dd hh:mm:ss
SELECT @Test

While there is a plethora of styles, you may want to remember few

  • 126 (ISO 8601): yyyy-MM-ddThh:mm:ss(.mmm)
  • 120: yyyy-MM-dd hh:mm:ss
  • 112: yyyyMMdd

Note that the T in the ISO 8601 is actually the letter T and not a variable.

How to remove listview all items

ListView operates based on the underlying data in the Adapter. In order to clear the ListView you need to do two things:

  1. Clear the data that you set from adapter.
  2. Refresh the view by calling notifyDataSetChanged

For example, see the skeleton of SampleAdapter below that extends the BaseAdapter


public class SampleAdapter extends BaseAdapter {

    ArrayList<String> data;

    public SampleAdapter() {
        this.data = new ArrayList<String>();
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return data.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        // your View
        return null;
    }
}

Here you have the ArrayList<String> data as the data for your Adapter. While you might not necessary use ArrayList, you will have something similar in your code to represent the data in your ListView

Next you provide a method to clear this data, the implementation of this method is to clear the underlying data structure


public void clearData() {
    // clear the data
    data.clear();
}

If you are using any subclass of Collection, they will have clear() method that you could use as above.

Once you have this method, you want to call clearData and notifyDataSetChanged on your onClick thus the code for onClick will look something like:


// listView is your instance of your ListView
SampleAdapter sampleAdapter = (SampleAdapter)listView.getAdapter();
sampleAdapter.clearData();

// refresh the View
sampleAdapter.notifyDataSetChanged();

Calculate age given the birth date in the format YYYYMMDD

Alternate solution, because why not:

function calculateAgeInYears (date) {
    var now = new Date();
    var current_year = now.getFullYear();
    var year_diff = current_year - date.getFullYear();
    var birthday_this_year = new Date(current_year, date.getMonth(), date.getDate());
    var has_had_birthday_this_year = (now >= birthday_this_year);

    return has_had_birthday_this_year
        ? year_diff
        : year_diff - 1;
}

How to recognize vehicle license / number plate (ANPR) from an image?

It maybe work looking at Character recoqnition software as there are many libraries out there that perform the same thing. I reading an image and storing it. Micrsoft office is able to read tiff files and return alphanumerics

Only detect click event on pseudo-element

My answer will work for anyone wanting to click a definitive area of the page. This worked for me on my absolutely-positioned :after

Thanks to this article, I realized (with jQuery) I can use e.pageY and e.pageX instead of worrying about e.offsetY/X and e.clientY/X issue between browsers.

Through my trial and error, I started to use the clientX and clientY mouse coordinates in the jQuery event object. These coordinates gave me the X and Y offset of the mouse relative to the top-left corner of the browser's view port. As I was reading the jQuery 1.4 Reference Guide by Karl Swedberg and Jonathan Chaffer, however, I saw that they often referred to the pageX and pageY coordinates. After checking the updated jQuery documentation, I saw that these were the coordinates standardized by jQuery; and, I saw that they gave me the X and Y offset of the mouse relative to the entire document (not just the view port).

I liked this event.pageY idea because it would always be the same, as it was relative to the document. I can compare it to my :after's parent element using offset(), which returns its X and Y also relative to the document.

Therefore, I can come up with a range of "clickable" region on the entire page that never changes.


Here's my demo on codepen.


or if too lazy for codepen, here's the JS:

* I only cared about the Y values for my example.

var box = $('.box');
// clickable range - never changes
var max = box.offset().top + box.outerHeight();
var min = max - 30; // 30 is the height of the :after

var checkRange = function(y) {
  return (y >= min && y <= max);
}

box.click(function(e){
  if ( checkRange(e.pageY) ) {
    // do click action
    box.toggleClass('toggle');
  }
});

Visual Studio 2015 or 2017 does not discover unit tests

I had the same problem. I just cleaned and rebuilt the project and I was able to see the tests that were missing.

Send data from javascript to a mysql database

You will have to submit this data to the server somehow. I'm assuming that you don't want to do a full page reload every time a user clicks a link, so you'll have to user XHR (AJAX). If you are not using jQuery (or some other JS library) you can read this tutorial on how to do the XHR request "by hand".

The way to check a HDFS directory's size?

To get the size of the directory hdfs dfs -du -s -h /$yourDirectoryName can be used. hdfs dfsadmin -report can be used to see a quick cluster level storage report.

What does the colon (:) operator do?

There are several places colon is used in Java code:

1) Jump-out label (Tutorial):

label: for (int i = 0; i < x; i++) {
    for (int j = 0; j < i; j++) {
        if (something(i, j)) break label; // jumps out of the i loop
    }
} 
// i.e. jumps to here

2) Ternary condition (Tutorial):

int a = (b < 4)? 7: 8; // if b < 4, set a to 7, else set a to 8

3) For-each loop (Tutorial):

String[] ss = {"hi", "there"}
for (String s: ss) {
    print(s); // output "hi" , and "there" on the next iteration
}

4) Assertion (Guide):

int a = factorial(b);
assert a >= 0: "factorial may not be less than 0"; // throws an AssertionError with the message if the condition evaluates to false

5) Case in switch statement (Tutorial):

switch (type) {
    case WHITESPACE:
    case RETURN:
        break;
    case NUMBER:
        print("got number: " + value);
        break;
    default:
        print("syntax error");
}

6) Method references (Tutorial)

class Person {
   public static int compareByAge(Person a, Person b) {
       return a.birthday.compareTo(b.birthday);
   }}
}

Arrays.sort(persons, Person::compareByAge);

How do you make Git work with IntelliJ?

git.exe is common for any git based applications like GitHub, Bitbucket etc. Some times it is possible that you have already installed another git based application so git.exe will be present in the bin folder of that application.

For example if you installed bitbucket before github in your PC, you will find git.exe in C:\Users\{username}\AppData\Local\Atlassian\SourceTree\git_local\bin instead of C:\Users\{username}\AppData\Local\GitHub\PortableGit.....\bin.

How do I login and authenticate to Postgresql after a fresh install?

The error your are getting is because your-ubuntu-username is not a valid Postgres user.

You need to tell psql what database username to use

psql -U postgres

You may also need to specify the database to connect to

psql -U postgres -d <dbname>

Is it possible to use Visual Studio on macOS?

Yes, you can! There's a Visual Studio for macs and there's Visual Studio Code if you only need a text editor like Sublime Text.

How to open Android Device Monitor in latest Android Studio 3.1

Android Device Monitor was deprecated in Android Studio 3.1 and removed from Android Studio 3.2

Use Android Profiler introduced in Android Studio 3.0 to measure the cpu utilisation, network, memory etc,. To open Android Profiler: View -> Tool Windows -> Profiler.

Android Device Monitor has been replaced by some new feature which you can find here.

npm ERR! registry error parsing json - While trying to install Cordova for Ionic Framework in Windows 8

My npm install worked fine, but I had this problem with npm update. To fix it, I had to run npm cache clean and then npm cache clear.

Asynchronous Requests with Python requests

async is now an independent module : grequests.

See here : https://github.com/kennethreitz/grequests

And there: Ideal method for sending multiple HTTP requests over Python?

installation:

$ pip install grequests

usage:

build a stack:

import grequests

urls = [
    'http://www.heroku.com',
    'http://tablib.org',
    'http://httpbin.org',
    'http://python-requests.org',
    'http://kennethreitz.com'
]

rs = (grequests.get(u) for u in urls)

send the stack

grequests.map(rs)

result looks like

[<Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>, <Response [200]>]

grequests don't seem to set a limitation for concurrent requests, ie when multiple requests are sent to the same server.

openssl s_client using a proxy

Even with openssl v1.1.0 I had some problems passing our proxy, e.g. s_client: HTTP CONNECT failed: 400 Bad Request That forced me to write a minimal Java-class to show the SSL-Handshake

    public static void main(String[] args) throws IOException, URISyntaxException {
    HttpHost proxy = new HttpHost("proxy.my.company", 8080);
    DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
    CloseableHttpClient httpclient = HttpClients.custom()
            .setRoutePlanner(routePlanner)
            .build();
    URI uri = new URIBuilder()
            .setScheme("https")
            .setHost("www.myhost.com")
            .build();
    HttpGet httpget = new HttpGet(uri);
    httpclient.execute(httpget);
}

With following dependency:

    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.2</version>
        <type>jar</type>
    </dependency>

you can run it with Java SSL Logging turned on

This should produce nice output like

trustStore provider is :
init truststore
adding as trusted cert:
  Subject: CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
  Issuer:  CN=Equifax Secure Global eBusiness CA-1, O=Equifax Secure Inc., C=US
  Algorithm: RSA; Serial number: 0xc3517
  Valid from Mon Jun 21 06:00:00 CEST 1999 until Mon Jun 22 06:00:00 CEST 2020

adding as trusted cert:
  Subject: CN=SecureTrust CA, O=SecureTrust Corporation, C=US
  Issuer:  CN=SecureTrust CA, O=SecureTrust Corporation, C=US
(....)

Change border-bottom color using jquery?

to modify more css property values, you may use css object. such as:

hilight_css = {"border-bottom-color":"red", 
               "background-color":"#000"};
$(".msg").css(hilight_css);

but if the modification code is bloated. you should consider the approach March suggested. do it this way:

first, in your css file:

.hilight { border-bottom-color:red; background-color:#000; }
.msg { /* something to make it notifiable */ }

second, in your js code:

$(".msg").addClass("hilight");
// to bring message block to normal
$(".hilight").removeClass("hilight");

if ie 6 is not an issue, you can chain these classes to have more specific selectors.

"The operation is not valid for the state of the transaction" error and transaction scope

After doing some research, it seems I cannot have two connections opened to the same database with the TransactionScope block. I needed to modify my code to look like this:

public void MyAddUpdateMethod()
{
    using (TransactionScope Scope = new TransactionScope(TransactionScopeOption.RequiresNew))
    {
        using(SQLServer Sql = new SQLServer(this.m_connstring))
        {
            //do my first add update statement            
        }

        //removed the method call from the first sql server using statement
        bool DoesRecordExist = this.SelectStatementCall(id)
    }
}

public bool SelectStatementCall(System.Guid id)
{
    using(SQLServer Sql = new SQLServer(this.m_connstring))
    {
        //create parameters
    }
}

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

The 'best' way to do this would be to set a property on a view object once the update is successful. You can then access this property in the view and inform the user accordingly.

Having said that it would be possible to trigger an alert from the controller code by doing something like this -

public ActionResult ActionName(PostBackData postbackdata)
{
    //your DB code
    return new JavascriptResult { Script = "alert('Successfully registered');" };
}

You can find further info in this question - How to display "Message box" using MVC3 controller

how to find my angular version in my project?

You can also find dependencies version details in package.json file as following:

enter image description here

Logical Operators, || or OR?

I know it's an old topic but still. I've just met the problem in the code I am debugging at work and maybe somebody may have similar issue...

Let's say the code looks like this:

$positions = $this->positions() || [];

You would expect (as you are used to from e.g. javascript) that when $this->positions() returns false or null, $positions is empty array. But it isn't. The value is TRUE or FALSE depends on what $this->positions() returns.

If you need to get value of $this->positions() or empty array, you have to use:

$positions = $this->positions() or [];

EDIT:

The above example doesn't work as intended but the truth is that || and or is not the same... Try this:

<?php

function returnEmpty()
{
  //return "string";
  //return [1];
  return null;
}

$first = returnEmpty() || [];
$second = returnEmpty() or [];
$third = returnEmpty() ?: [];

var_dump($first);
var_dump($second);
var_dump($third);
echo "\n";

This is the result:

bool(false)
NULL
array(0) {
}

So, actually the third option ?: is the correct solution when you want to set returned value or empty array.

$positions = $this->positions() ?: [];

Tested with PHP 7.2.1

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

Here are a few ways to create a list with N of continuous natural numbers starting from 1.

1 range:

def numbers(n): 
    return range(1, n+1);

2 List Comprehensions:

def numbers(n):
    return [i for i in range(1, n+1)]

You may want to look into the method xrange and the concepts of generators, those are fun in python. Good luck with your Learning!

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

How to convert a python numpy array to an RGB image with Opencv 2.4?

The size of your image is not sufficient to see in a naked eye. So please try to use atleast 50x50

import cv2 as cv
import numpy as np

black_screen = np.zeros([50,50,3])

black_screen[:, :, 2] = np.ones([50,50])*64/255.0
cv.imshow("Simple_black", black_screen)
cv.waitKey(0)
cv.displayAllWindows()

How do you enable auto-complete functionality in Visual Studio C++ express edition?

It's enabled by default. Probably you just tried on an expression that failed to autocomplete.

In case you deactivated it somehow... you can enable it in the Visual Studio settings. Just browse to the Editor settings, then to the subgroup C/C++ and activate it again... should read something like "List members automatically" or "Auto list members" (sorry, I have the german Visual Studio).

Upon typing something like std::cout. a dropwdownlist with possible completitions should pop up.

What is the most efficient way to get first and last line of a text file?

docs for io module

with open(fname, 'rb') as fh:
    first = next(fh).decode()

    fh.seek(-1024, 2)
    last = fh.readlines()[-1].decode()

The variable value here is 1024: it represents the average string length. I choose 1024 only for example. If you have an estimate of average line length you could just use that value times 2.

Since you have no idea whatsoever about the possible upper bound for the line length, the obvious solution would be to loop over the file:

for line in fh:
    pass
last = line

You don't need to bother with the binary flag you could just use open(fname).

ETA: Since you have many files to work on, you could create a sample of couple of dozens of files using random.sample and run this code on them to determine length of last line. With an a priori large value of the position shift (let say 1 MB). This will help you to estimate the value for the full run.

Remove all special characters from a string

Here, check out this function:

function seo_friendly_url($string){
    $string = str_replace(array('[\', \']'), '', $string);
    $string = preg_replace('/\[.*\]/U', '', $string);
    $string = preg_replace('/&(amp;)?#?[a-z0-9]+;/i', '-', $string);
    $string = htmlentities($string, ENT_COMPAT, 'utf-8');
    $string = preg_replace('/&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);/i', '\\1', $string );
    $string = preg_replace(array('/[^a-z0-9]/i', '/[-]+/') , '-', $string);
    return strtolower(trim($string, '-'));
}

LINQ equivalent of foreach for IEnumerable<T>

I took Fredrik's method and modified the return type.

This way, the method supports deferred execution like other LINQ methods.

EDIT: If this wasn't clear, any usage of this method must end with ToList() or any other way to force the method to work on the complete enumerable. Otherwise, the action would not be performed!

public static IEnumerable<T> ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
    foreach (T item in enumeration)
    {
        action(item);
        yield return item;
    }
}

And here's the test to help see it:

[Test]
public void TestDefferedExecutionOfIEnumerableForEach()
{
    IEnumerable<char> enumerable = new[] {'a', 'b', 'c'};

    var sb = new StringBuilder();

    enumerable
        .ForEach(c => sb.Append("1"))
        .ForEach(c => sb.Append("2"))
        .ToList();

    Assert.That(sb.ToString(), Is.EqualTo("121212"));
}

If you remove the ToList() in the end, you will see the test failing since the StringBuilder contains an empty string. This is because no method forced the ForEach to enumerate.

Scrollable Menu with Bootstrap - Menu expanding its container when it should not

i hope this code is work well,try this.

add css file.

.scrollbar {
    height: auto;
    max-height: 180px;
    overflow-x: hidden;
}

HTML code:

<div class="col-sm-2  scrollable-menu" role="menu">
    <div>
   <ul>
  <li><a class="active" href="#home">Tutorials</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>

    </ul>
   </div>
   </div>

iOS Launching Settings -> Restrictions URL Scheme

Yep, saw this (and many more), even implemented it in a test application. Really need to get the definitive word from Apple, but the community consensus opinion is Apple disallowed it in 5.1 after it was publicly "discovered/published", so applications containing it won't be accepted.

08/01/12 Update: Asked Apple through my developer account if there is a way to programmatically launch the WiFi Settings dialog. Here is the response:

"Our engineers have reviewed your request and have concluded that there is no supported way to achieve the desired functionality given the currently shipping system configurations."

Rails: Check output of path helper from console

In the Rails console, the variable app holds a session object on which you can call path and URL helpers as instance methods.

app.users_path

How to clear all input fields in a specific div with jQuery?

Just had to delete all inputs within a div & using the colon in front of the input when targeting gets most everything.

$('#divId').find(':input').val('');

What does yield mean in PHP?

simple example

<?php
echo '#start main# ';
function a(){
    echo '{start[';
    for($i=1; $i<=9; $i++)
        yield $i;
    echo ']end} ';
}
foreach(a() as $v)
    echo $v.',';
echo '#end main#';
?>

output

#start main# {start[1,2,3,4,5,6,7,8,9,]end} #end main#

advanced example

<?php
echo '#start main# ';
function a(){
    echo '{start[';
    for($i=1; $i<=9; $i++)
        yield $i;
    echo ']end} ';
}
foreach(a() as $k => $v){
    if($k === 5)
        break;
    echo $k.'=>'.$v.',';
}
echo '#end main#';
?>

output

#start main# {start[0=>1,1=>2,2=>3,3=>4,4=>5,#end main#

How to create range in Swift?

If anyone want to create NSRange object can create as:

let range: NSRange = NSRange.init(location: 0, length: 5)

this will create range with position 0 and length 5

close vs shutdown socket?

in my test.

close will send fin packet and destroy fd immediately when socket is not shared with other processes

shutdown SHUT_RD, process can still recv data from the socket, but recv will return 0 if TCP buffer is empty.After peer send more data, recv will return data again.

shutdown SHUT_WR will send fin packet to indicate the Further sends are disallowed. the peer can recv data but it will recv 0 if its TCP buffer is empty

shutdown SHUT_RDWR (equal to use both SHUT_RD and SHUT_WR) will send rst packet if peer send more data.

Android Studio installation on Windows 7 fails, no JDK found

Sometimes you can resolve this type of issue by setting environment variables so the process looks for the JDK in the right spot.

Another approach is to figure out where the process is looking, then put your JDK there.

I've had lots of success using Process Monitor from Sysinternals:

  1. Start -> Run -> procmon
  2. Go to the Filter menu, then select Filter...
  3. Set Event Class is File System then Include
  4. Add, then OK

This will filter down to all the file system operations taking place on your machine.

You could try filtering based on the result of the File System operation:

  • Right click on the Result column, then Exclude 'SUCCESS'

You can also quite easily filter based on the process name, either from the Filter... menu option or by right clicking on the Process Name column and selecting Include 'process.exe'.

Once you find the file system operation that's failing, the Path column will tell you where to put your JDK.

I've found this to be very empowering. Especially compared to the frustrating process of changing environment variables by trial and error.

Remove 'b' character do in front of a string literal in Python 3

Here u Go

f = open('test.txt','rb+')
ch=f.read(1)
ch=str(ch,'utf-8')
print(ch)

How to perform mouseover function in Selenium WebDriver using Java?

None of these answers work when trying to do the following:

  1. Hover over a menu item.
  2. Find the hidden element that is ONLY available after the hover.
  3. Click the sub-menu item.

If you insert a 'perform' command after the moveToElement, it moves to the element, and the sub-menu item shows for a brief period, but that is not a hover. The hidden element immediately disappears before it can be found resulting in a ElementNotFoundException. I tried two things:

Actions builder = new Actions(driver);
builder.moveToElement(hoverElement).perform();
builder.moveToElement(clickElement).click().perform();

This did not work for me. The following worked for me:

Actions builder = new Actions(driver);
builder.moveToElement(hoverElement).perform();
By locator = By.id("clickElementID");
driver.click(locator);

Using the Actions to hover and the standard WebDriver click, I could hover and then click.

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

replace \n and \r\n with <br /> in java

This should work. You need to put in two slashes

str = str.replaceAll("(\\r\\n|\\n)", "<br />");

In this Reference, there is an example which shows

private final String REGEX = "\\d"; // a single digit

I have used two slashes in many of my projects and it seems to work fine!

Style input type file?

Follow these steps then you can create custom styles for your file upload form:

1.) This is the simple HTML form(please read the HTML comments I have written here bellow)

    <form action="#type your action here" method="POST" enctype="multipart/form-data">
    <div id="yourBtn" style="height: 50px; width: 100px;border: 1px dashed #BBB; cursor:pointer;" onclick="getFile()">Click to upload!</div>
    <!-- this is your file input tag, so i hide it!-->
    <div style='height: 0px;width: 0px; overflow:hidden;'><input id="upfile" type="file" value="upload"/></div>
    <!-- here you can have file submit button or you can write a simple script to upload the file automatically-->
    <input type="submit" value='submit' >
    </form>

2.) Then use this simple script to pass the click event to file input tag.

    function getFile(){
        document.getElementById("upfile").click();
    }

Now you can use any type of a styling without worrying how to change default styles. I know this very well, because I have been trying to change the default styles for month and a half. believe me it's very hard because different browsers have different upload input tag. So use this one to build your custom file upload forms.Here is the full AUTOMATED UPLOAD code.

<html>
<style>
#yourBtn{
   position: relative;
   top: 150px;
   font-family: calibri;
   width: 150px;
   padding: 10px;
   -webkit-border-radius: 5px;
   -moz-border-radius: 5px;
   border: 1px dashed #BBB; 
   text-align: center;
   background-color: #DDD;
   cursor:pointer;
  }
</style>
<script type="text/javascript">
 function getFile(){
   document.getElementById("upfile").click();
 }
 function sub(obj){
    var file = obj.value;
    var fileName = file.split("\\");
    document.getElementById("yourBtn").innerHTML = fileName[fileName.length-1];
    document.myForm.submit();
    event.preventDefault();
  }
</script>
<body>
<center>
<form action="#type your action here" method="POST" enctype="multipart/form-data" name="myForm">
<div id="yourBtn" onclick="getFile()">click to upload a file</div>
<!-- this is your file input tag, so i hide it!-->
<!-- i used the onchange event to fire the form submission-->
<div style='height: 0px; width: 0px;overflow:hidden;'><input id="upfile" type="file" value="upload" onchange="sub(this)"/></div>
<!-- here you can have file submit button or you can write a simple script to upload the file automatically-->
<!-- <input type="submit" value='submit' > -->
</form>
</center>
</body>
</html>

How to center and crop an image to always appear in square shape with CSS?

<div>
    <img class="crop" src="http://lorempixel.com/500/200"/>
</div>

<img src="http://lorempixel.com/500/200"/>




div {
    width: 200px;
    height: 200px;
    overflow: hidden;
    margin: 10px;
    position: relative;
}
.crop {
    position: absolute;
    left: -100%;
    right: -100%;
    top: -100%;
    bottom: -100%;
    margin: auto; 
    height: auto;
    width: auto;
}

http://jsfiddle.net/J7a5R/56/

How do I split an int into its digits?

Given the number 12345 :

5 is 12345 % 10
4 is 12345 / 10 % 10
3 is 12345 / 100 % 10
2 is 12345 / 1000 % 10
1 is 12345 / 10000 % 10

I won't provide a complete code as this surely looks like homework, but I'm sure you get the pattern.

"Continue" (to next iteration) on VBScript

I think you are intended to contain ALL YOUR LOGIC under your if statement. Basically:

' PRINTS EVERYTHING EXCEPT 4
For i = 0 To 10
  ' you want to say
  ' If i = 4 CONTINUE but VBScript has no continue
  If i <> 4 Then ' just invert the logic
    WSH.Echo( i )
  End If
Next

This can make the code a bit longer, but some people don't like break or continue anyway.

How to set or change the default Java (JDK) version on OS X?

Four easy steps using terminal for people who uses the default process.. :)

  1. echo $JAVA_HOME gives you current java home. For eg: /Library/Java/JavaVirtualMachines/jdk1.8.0_191.jdk/Contents/Home/

  2. cd /Library/Java/JavaVirtualMachines/ will take you to the folder where u normally install jdks (It might be different for your machines)

  3. ls shows you available folders (normally it will have the version numbers, for eg: jdk1.8.0_191.jdk openjdk-11.0.2.jdk)
  4. export JAVA_HOME='/Library/Java/JavaVirtualMachines/openjdk-11.0.2.jdk/Contents/Home' will change the java home..

AssertionError: View function mapping is overwriting an existing endpoint function: main

Your view names need to be unique even if they are pointing to the same view method, or you can add from functools import wraps and use @wraps https://docs.python.org/2/library/functools.html

What difference is there between WebClient and HTTPWebRequest classes in .NET?

WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. For instance, if you want to get the content out of an HttpWebResponse, you have to read from the response stream:

var http = (HttpWebRequest)WebRequest.Create("http://example.com");
var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

With WebClient, you just do DownloadString:

var client = new WebClient();
var content = client.DownloadString("http://example.com");

Note: I left out the using statements from both examples for brevity. You should definitely take care to dispose your web request objects properly.

In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.

How would I access variables from one class to another?

we can access/pass arguments/variables from one class to another class using object reference.

#Class1
class Test:
    def __init__(self):
        self.a = 10
        self.b = 20
        self.add = 0

    def calc(self):
        self.add = self.a+self.b

#Class 2
class Test2:
    def display(self):
        print('adding of two numbers: ',self.add)
#creating object for Class1
obj = Test()
#invoking calc method()
obj.calc()
#passing class1 object to class2
Test2.display(obj)

How do I make the text box bigger in HTML/CSS?

This will do it:

#signin input {
 background-color:#FFF;
 min-height:200px;

}

When to use Task.Delay, when to use Thread.Sleep?

My opinion,

Task.Delay() is asynchronous. It doesn't block the current thread. You can still do other operations within current thread. It returns a Task return type (Thread.Sleep() doesn't return anything ). You can check if this task is completed(use Task.IsCompleted property) later after another time-consuming process.

Thread.Sleep() doesn't have a return type. It's synchronous. In the thread, you can't really do anything other than waiting for the delay to finish.

As for real-life usage, I have been programming for 15 years. I have never used Thread.Sleep() in production code. I couldn't find any use case for it. Maybe that's because I mostly do web application development.

C# Foreach statement does not contain public definition for GetEnumerator

You don't show us the declaration of carBootSaleList. However from the exception message I can see that it is of type CarBootSaleList. This type doesn't implement the IEnumerable interface and therefore cannot be used in a foreach.

Your CarBootSaleList class should implement IEnumerable<CarBootSale>:

public class CarBootSaleList : IEnumerable<CarBootSale>
{
    private List<CarBootSale> carbootsales;

    ...

    public IEnumerator<CarBootSale> GetEnumerator()
    {
        return carbootsales.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return carbootsales.GetEnumerator();
    }
}

How to play a sound in C#, .NET

You could use:

System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"c:\mywavfile.wav");
player.Play();

SQL SELECT everything after a certain character

Try this in MySQL.

right(field,((CHAR_LENGTH(field))-(InStr(field,','))))

What's the most efficient way to erase duplicates and sort a vector?

If you don't want to modify the vector (erase, sort) then you can use the Newton library, In the algorithm sublibrary there is a function call, copy_single

template <class INPUT_ITERATOR, typename T>
    void copy_single( INPUT_ITERATOR first, INPUT_ITERATOR last, std::vector<T> &v )

so You can:

std::vector<TYPE> copy; // empty vector
newton::copy_single(first, last, copy);

where copy is the vector in where you want to push_back the copy of the unique elements. but remember you push_back the elements, and you don't create a new vector

anyway, this is faster because you don't erase() the elements (which takes a lot of time, except when you pop_back(), because of reassignment)

I make some experiments and it's faster.

Also, you can use:

std::vector<TYPE> copy; // empty vector
newton::copy_single(first, last, copy);
original = copy;

sometimes is still faster.

How to dismiss a Twitter Bootstrap popover by clicking outside?

The answer works very well, just to add a angular directive in case you are using angular like me:

app.directive('popover', ['$document', function($document) {
    return {
        restrict: 'EA',
        link: function(scope, elem, attrs) {
            $(document).ready(function() {
                $('[data-toggle="popover"]').popover();
            });

            elem.bind('click', function(e) {
                $('#notification').popover('toggle');
            })

            $('body').on('click', function (e) {
                //the 'is' for buttons that trigger popups
                //the 'has' for icons within a button that triggers a popup
                if (!elem.is(e.target)
                    && elem.has(e.target).length === 0
                    && $('.popover').has(e.target).length === 0) {
                    elem.popover('hide');
                }
            });
        }
    };
}]);

The html code:

<a popover tabindex="0" role="button"
   id="notification"
   data-toggle="popover" data-trigger="manual"
   data-container="body" data-placement="bottom"
   data-content="This is a popover">
   Popover button
</a>

It should have been as simple as use data-trigger='click focus', because according to bootstrap:

How popover is triggered - click | hover | focus | manual. You may pass multiple triggers; separate them with a space. manual cannot be combined with any other trigger.

However, use click and focus together doesn't work for me for unknown reason, instead I have to toggle it manually.

Rewrite left outer join involving multiple tables from Informix to Oracle

I'm guessing that you want something like

SELECT tab1.a, tab2.b, tab3.c, tab4.d
  FROM table1 tab1 
       JOIN table2 tab2 ON (tab1.fg = tab2.fg)
       LEFT OUTER JOIN table4 tab4 ON (tab1.ss = tab4.ss)
       LEFT OUTER JOIN table3 tab3 ON (tab4.xya = tab3.xya and tab3.desc = 'XYZ')
       LEFT OUTER JOIN table5 tab5 on (tab4.kk = tab5.kk AND
                                       tab3.dd = tab5.dd)

Detect if Visual C++ Redistributable for Visual Studio 2012 is installed

It depends on what version you are using. These two 2012 keys have worked well for me with their corresponding versions to download for Update 4. Please be aware that some of these reg locations may be OS-dependent. I collected this info from a Windows 10 x64 box. I'm just going to go ahead and dump all of these redist versions and the reg keys I search for to detect installation.:


Visual C++ 2005

Microsoft Visual C++ 2005 Redistributable (x64)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Products\1af2a8da7e60d0b429d7e6453b3d0182
Configuration: x64
Version: 6.0.2900.2180

Direct Download URL: https://download.microsoft.com/download/8/B/4/8B42259F-5D70-43F4-AC2E-4B208FD8D66A/vcredist_x64.EXE

Microsoft Visual C++ 2005 Redistributable (x86)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Products\c1c4f01781cc94c4c8fb1542c0981a2a 
Configuration: x86
Version: 6.0.2900.2180

Direct Download URL: https://download.microsoft.com/download/8/B/4/8B42259F-5D70-43F4-AC2E-4B208FD8D66A/vcredist_x86.EXE


Visual C++ 2008

Microsoft Visual C++ 2008 Redistributable - x64 9.0.30729.6161 (SP1)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Products\67D6ECF5CD5FBA732B8B22BAC8DE1B4D 
Configuration: x64
Version: 9.0.30729.6161 (Actual $Version data in registry: 0x9007809 [DWORD])

Direct Download URL: https://download.microsoft.com/download/2/d/6/2d61c766-107b-409d-8fba-c39e61ca08e8/vcredist_x64.exe

Microsoft Visual C++ 2008 Redistributable - x86 9.0.30729.6161 (SP1)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Products\6E815EB96CCE9A53884E7857C57002F0
Configuration: x86
Version: 9.0.30729.6161 (Actual $Version data in registry: 0x9007809 [DWORD])

Direct Download URL: https://download.microsoft.com/download/d/d/9/dd9a82d0-52ef-40db-8dab-795376989c03/vcredist_x86.exe


Visual C++ 2010

Microsoft Visual C++ 2010 Redistributable (x64)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Products\1926E8D15D0BCE53481466615F760A7F 
Configuration: x64
Version: 10.0.40219.325

Direct Download URL: https://download.microsoft.com/download/1/6/5/165255E7-1014-4D0A-B094-B6A430A6BFFC/vcredist_x64.exe

Microsoft Visual C++ 2010 Redistributable (x86)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Products\1D5E3C0FEDA1E123187686FED06E995A 
Configuration: x86
Version: 10.0.40219.325

Direct Download URL: https://download.microsoft.com/download/1/6/5/165255E7-1014-4D0A-B094-B6A430A6BFFC/vcredist_x86.exe


Visual C++ 2012

Microsoft Visual C++ 2012 Redistributable (x64)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Dependencies\{ca67548a-5ebe-413a-b50c-4b9ceb6d66c6} 
Configuration: x64
Version: 11.0.61030.0

Direct Download URL: https://download.microsoft.com/download/1/6/B/16B06F60-3B20-4FF2-B699-5E9B7962F9AE/VSU_4/vcredist_x64.exe

Microsoft Visual C++ 2012 Redistributable (x86)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Dependencies\{33d1fd90-4274-48a1-9bc1-97e33d9c2d6f} 
Configuration: x86
Version: 11.0.61030.0

Direct Download URL: https://download.microsoft.com/download/1/6/B/16B06F60-3B20-4FF2-B699-5E9B7962F9AE/VSU_4/vcredist_x86.exe

version caveat: Per user Wai Ha Lee's findings, "...the binaries that come with VC++ 2012 update 4 (11.0.61030.0) have version 11.0.60610.1 for the ATL and MFC binaries, and 11.0.51106.1 for everything else, e.g. msvcp110.dll and msvcr110.dll..."


Visual C++ 2013

Microsoft Visual C++ 2013 Redistributable (x64)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Dependencies\{050d4fc8-5d48-4b8f-8972-47c82c46020f} 
Configuration: x64
Version: 12.0.30501.0

Direct Download URL: https://download.microsoft.com/download/2/E/6/2E61CFA4-993B-4DD4-91DA-3737CD5CD6E3/vcredist_x64.exe

Microsoft Visual C++ 2013 Redistributable (x86)
Registry Key: HKLM\SOFTWARE\Classes\Installer\Dependencies\{f65db027-aff3-4070-886a-0d87064aabb1} 
Configuration: x86
Version: 12.0.30501.0

Direct Download URL: https://download.microsoft.com/download/2/E/6/2E61CFA4-993B-4DD4-91DA-3737CD5CD6E3/vcredist_x86.exe


Visual C++ 2015

Consider using the 2015-2019 bundle as an alternative

Microsoft Visual C++ 2015 Redistributable (x64) - 14.0.24215
Registry Key: HKLM\SOFTWARE\Classes\Installer\Dependencies\{d992c12e-cab2-426f-bde3-fb8c53950b0d}
Configuration: x64
Version: 14.0.24215.1

Direct Download URL: https://download.microsoft.com/download/6/A/A/6AA4EDFF-645B-48C5-81CC-ED5963AEAD48/vc_redist.x64.exe

Microsoft Visual C++ 2015 Redistributable (x86) - 14.0.24215
Registry Key: HKLM\SOFTWARE\Classes\Installer\Dependencies\{e2803110-78b3-4664-a479-3611a381656a}
Configuration: x86
Version: 14.0.24215.1

Direct Download URL: https://download.microsoft.com/download/6/A/A/6AA4EDFF-645B-48C5-81CC-ED5963AEAD48/vc_redist.x86.exe


Visual C++ 2017

Consider using the 2015-2019 bundle as an alternative

Caveat: There's either a new 2017 registry convention being used, or it hasn't been finalized, yet. As I'm guessing the upper-most keys of: [HKEY_CLASSES_ROOT\Installer\Dependencies\,,amd64,14.0,bundle] and [HKEY_CLASSES_ROOT\Installer\Dependencies\,,x86,14.0,bundle]

are subject to change, or at least have different nested GUIDs, I'm going to use list the key that ends with a GUID.

Microsoft Visual C++ 2017 Redistributable (x64) - 14.16.27012
Registry Key: [HKEY_CLASSES_ROOT\Installer\Dependencies\VC,redist.x64,amd64,14.16,bundle\Dependents\{427ada59-85e7-4bc8-b8d5-ebf59db60423}]
Configuration: x64
Version: 14.16.27012.6

Direct Download URL: https://download.visualstudio.microsoft.com/download/pr/9fbed7c7-7012-4cc0-a0a3-a541f51981b5/e7eec15278b4473e26d7e32cef53a34c/vc_redist.x64.exe

Microsoft Visual C++ 2017 Redistributable (x86) - 14.16.27012
Registry Key: [HKEY_CLASSES_ROOT\Installer\Dependencies\VC,redist.x86,x86,14.16,bundle\Dependents\{67f67547-9693-4937-aa13-56e296bd40f6}]
Configuration: x86
Version: 14.16.27012.6

Direct Download URL: https://download.visualstudio.microsoft.com/download/pr/d0b808a8-aa78-4250-8e54-49b8c23f7328/9c5e6532055786367ee61aafb3313c95/vc_redist.x86.exe


Visual C++ 2019 (2015-2019 bundle)

Caveat: There's another new registry convention being used for Visual C++ 2019. There also doesn't appear to be a standalone installer for Visual C++ 2019, only this bundle installer that is Visual C++ 2015 through 2019.

14.21.27702

Microsoft Visual C++ 2015-2019 Redistributable (x64) - 14.21.27702
Registry Key: [HKEY_CLASSES_ROOT\Installer\Dependencies\VC,redist.x64,amd64,14.21,bundle\Dependents\{f4220b74-9edd-4ded-bc8b-0342c1e164d8}]
Configuration: x64
Version: 14.21.27702  

Direct Download URL: https://download.visualstudio.microsoft.com/download/pr/9e04d214-5a9d-4515-9960-3d71398d98c3/1e1e62ab57bbb4bf5199e8ce88f040be/vc_redist.x64.exe

Microsoft Visual C++ 2015-2019 Redistributable (x86) - 14.21.27702
Registry Key: [HKEY_CLASSES_ROOT\Installer\Dependencies\VC,redist.x86,x86,14.21,bundle\Dependents\{49697869-be8e-427d-81a0-c334d1d14950}]
Configuration: x86
Version: 14.21.27702

Direct Download URL: https://download.visualstudio.microsoft.com/download/pr/c8edbb87-c7ec-4500-a461-71e8912d25e9/99ba493d660597490cbb8b3211d2cae4/vc_redist.x86.exe

14.22.27821

Microsoft Visual C++ 2015-2019 Redistributable (x86) - 14.22.27821
Registry Key: [HKEY_CLASSES_ROOT\Installer\Dependencies\VC,redist.x86,x86,14.22,bundle\Dependents\{5bfc1380-fd35-4b85-9715-7351535d077e}]
Configuration: x86
Version: 14.22.27821

Direct Download URL: https://download.visualstudio.microsoft.com/download/pr/0c1cfec3-e028-4996-8bb7-0c751ba41e32/1abed1573f36075bfdfc538a2af00d37/vc_redist.x86.exe

Microsoft Visual C++ 2015-2019 Redistributable (x86) - 14.22.27821
Registry Key: [HKEY_CLASSES_ROOT\Installer\Dependencies\VC,redist.x64,amd64,14.22,bundle\Dependents\{6361b579-2795-4886-b2a8-53d5239b6452}]
Configuration: x64
Version: 14.22.27821

Direct Download URL: https://download.visualstudio.microsoft.com/download/pr/cc0046d4-e7b4-45a1-bd46-b1c079191224/9c4042a4c2e6d1f661f4c58cf4d129e9/vc_redist.x64.exe


Changelog:
August 19th, 2019 -- Added a new version of 2015-2019 bundle version
June 13th, 2019 -- Added a new section for the 2015-2019 bundle version 14.21.27702 and added small notes to the 2015 and 2017 sections about considering the usage of the new bundle as an alternative.
December 14th, 2018 -- Updated MSVC2008 for Service Pack 1's 9.0.30729.6161 update per Jim Wolff's findings
November 27th, 2018 -- Updated info for MSVC2017 v. 14.16
September 12th, 2018 -- Added version caveat to 2012 Update 4 per Wai Ha Lee's findings
August 24th, 2018 -- Updated 2017's version for 14.15.26706, the updated Visual C++ dependencies packaged with VS 2017 15.8.1
May 16th, 2018 -- Updated 2017's version for 14.14.26405.0 as the new C++ 2017 entry
September 8th, 2017 -- Updated 2017's version for 14.11.25325.0 as the new Visual C++ 2017 entry
April 7th, 2017 -- Updated 2017's version of 14.10.25008.0 as the new Visual C++ 2017 entry
October 24th, 2016 -- Updated 2015's version info for 14.0.24215.1
August 18th, 2016 -- Updated 2015's version info for 14.0.24212
May 27th, 2016 -- Updated info for MSVC2015 Update 2

Please contact me here if any of these become outdated.

Java Initialize an int array in a constructor

why not simply

public Date(){
    data = new int[]{0,0,0};
}

the reason you got the error is because int[] data = ... declares a new variable and hides the field data

however it should be noted that the contents of the array are already initialized to 0 (the default value of int)

Serialize JavaScript object into JSON string

Below is another way by which we can JSON data with JSON.stringify() function

var Utils = {};
Utils.MyClass1 = function (id, member) {
    this.id = id;
    this.member = member;
}
var myobject = { MyClass1: new Utils.MyClass1("5678999", "text") };
alert(JSON.stringify(myobject));

Convert hours:minutes:seconds into total minutes in excel

Just use the formula

120 = (HOUR(A8)*3600+MINUTE(A8)*60+SECOND(A8))/60

how to add a day to a date using jquery datepicker

The datepicker('setDate') sets the date in the datepicket not in the input.

You should add the date and set it in the input.

var date2 = $('.pickupDate').datepicker('getDate');
var nextDayDate = new Date();
nextDayDate.setDate(date2.getDate() + 1);
$('input').val(nextDayDate);

Session variables not working php

Just talked to the hosting service, it was an issue at their end. he said " your account session.save_path was not set as a result issue arise. I set it for you now."

And it works fine after that :)

How to use Object.values with typescript?

I just hit this exact issue with Angular 6 using the CLI and workspaces to create a library using ng g library foo.

In my case the issue was in the tsconfig.lib.json in the library folder which did not have es2017 included in the lib section.

Anyone stumbling across this issue with Angular 6 you just need to ensure that you update you tsconfig.lib.json as well as your application tsconfig.json

PHP - include a php file and also send query parameters

I was in the same situation and I needed to include a page by sending some parameters... But in reality what I wanted to do is to redirect the page... if is the case for you, the code is:

<?php
   header("Location: http://localhost/planner/layout.php?page=dashboard"); 
   exit();
?>

What's the best way to store a group of constants that my program uses?

What I like to do is the following (but make sure to read to the end to use the proper type of constants):

internal static class ColumnKeys
{
    internal const string Date = "Date";
    internal const string Value = "Value";
    ...
}

Read this to know why const might not be what you want. Possible type of constants are:

  • const fields. Do not use across assemblies (public or protected) if value might change in future because the value will be hardcoded at compile-time in those other assemblies. If you change the value, the old value will be used by the other assemblies until they are re-compiled.
  • static readonly fields
  • static property without set

PHP validation/regex for URL

And there is your answer =) Try to break it, you can't!!!

function link_validate_url($text) {
$LINK_DOMAINS = 'aero|arpa|asia|biz|com|cat|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel|mobi|local';
  $LINK_ICHARS_DOMAIN = (string) html_entity_decode(implode("", array( // @TODO completing letters ...
    "&#x00E6;", // æ
    "&#x00C6;", // Æ
    "&#x00C0;", // À
    "&#x00E0;", // à
    "&#x00C1;", // Á
    "&#x00E1;", // á
    "&#x00C2;", // Â
    "&#x00E2;", // â
    "&#x00E5;", // å
    "&#x00C5;", // Å
    "&#x00E4;", // ä
    "&#x00C4;", // Ä
    "&#x00C7;", // Ç
    "&#x00E7;", // ç
    "&#x00D0;", // Ð
    "&#x00F0;", // ð
    "&#x00C8;", // È
    "&#x00E8;", // è
    "&#x00C9;", // É
    "&#x00E9;", // é
    "&#x00CA;", // Ê
    "&#x00EA;", // ê
    "&#x00CB;", // Ë
    "&#x00EB;", // ë
    "&#x00CE;", // Î
    "&#x00EE;", // î
    "&#x00CF;", // Ï
    "&#x00EF;", // ï
    "&#x00F8;", // ø
    "&#x00D8;", // Ø
    "&#x00F6;", // ö
    "&#x00D6;", // Ö
    "&#x00D4;", // Ô
    "&#x00F4;", // ô
    "&#x00D5;", // Õ
    "&#x00F5;", // õ
    "&#x0152;", // Œ
    "&#x0153;", // œ
    "&#x00FC;", // ü
    "&#x00DC;", // Ü
    "&#x00D9;", // Ù
    "&#x00F9;", // ù
    "&#x00DB;", // Û
    "&#x00FB;", // û
    "&#x0178;", // Ÿ
    "&#x00FF;", // ÿ 
    "&#x00D1;", // Ñ
    "&#x00F1;", // ñ
    "&#x00FE;", // þ
    "&#x00DE;", // Þ
    "&#x00FD;", // ý
    "&#x00DD;", // Ý
    "&#x00BF;", // ¿
  )), ENT_QUOTES, 'UTF-8');

  $LINK_ICHARS = $LINK_ICHARS_DOMAIN . (string) html_entity_decode(implode("", array(
    "&#x00DF;", // ß
  )), ENT_QUOTES, 'UTF-8');
  $allowed_protocols = array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal');

  // Starting a parenthesis group with (?: means that it is grouped, but is not captured
  $protocol = '((?:'. implode("|", $allowed_protocols) .'):\/\/)';
  $authentication = "(?:(?:(?:[\w\.\-\+!$&'\(\)*\+,;=" . $LINK_ICHARS . "]|%[0-9a-f]{2})+(?::(?:[\w". $LINK_ICHARS ."\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})*)?)?@)";
  $domain = '(?:(?:[a-z0-9' . $LINK_ICHARS_DOMAIN . ']([a-z0-9'. $LINK_ICHARS_DOMAIN . '\-_\[\]])*)(\.(([a-z0-9' . $LINK_ICHARS_DOMAIN . '\-_\[\]])+\.)*('. $LINK_DOMAINS .'|[a-z]{2}))?)';
  $ipv4 = '(?:[0-9]{1,3}(\.[0-9]{1,3}){3})';
  $ipv6 = '(?:[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7})';
  $port = '(?::([0-9]{1,5}))';

  // Pattern specific to external links.
  $external_pattern = '/^'. $protocol .'?'. $authentication .'?('. $domain .'|'. $ipv4 .'|'. $ipv6 .' |localhost)'. $port .'?';

  // Pattern specific to internal links.
  $internal_pattern = "/^(?:[a-z0-9". $LINK_ICHARS ."_\-+\[\]]+)";
  $internal_pattern_file = "/^(?:[a-z0-9". $LINK_ICHARS ."_\-+\[\]\.]+)$/i";

  $directories = "(?:\/[a-z0-9". $LINK_ICHARS ."_\-\.~+%=&,$'#!():;*@\[\]]*)*";
  // Yes, four backslashes == a single backslash.
  $query = "(?:\/?\?([?a-z0-9". $LINK_ICHARS ."+_|\-\.~\/\\\\%=&,$'():;*@\[\]{} ]*))";
  $anchor = "(?:#[a-z0-9". $LINK_ICHARS ."_\-\.~+%=&,$'():;*@\[\]\/\?]*)";

  // The rest of the path for a standard URL.
  $end = $directories .'?'. $query .'?'. $anchor .'?'.'$/i';

  $message_id = '[^@].*@'. $domain;
  $newsgroup_name = '(?:[0-9a-z+-]*\.)*[0-9a-z+-]*';
  $news_pattern = '/^news:('. $newsgroup_name .'|'. $message_id .')$/i';

  $user = '[a-zA-Z0-9'. $LINK_ICHARS .'_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\'\[\]]+';
  $email_pattern = '/^mailto:'. $user .'@'.'(?:'. $domain .'|'. $ipv4 .'|'. $ipv6 .'|localhost)'. $query .'?$/';

  if (strpos($text, '<front>') === 0) {
    return false;
  }
  if (in_array('mailto', $allowed_protocols) && preg_match($email_pattern, $text)) {
    return false;
  }
  if (in_array('news', $allowed_protocols) && preg_match($news_pattern, $text)) {
    return false;
  }
  if (preg_match($internal_pattern . $end, $text)) {
    return false;
  }
  if (preg_match($external_pattern . $end, $text)) {
    return false;
  }
  if (preg_match($internal_pattern_file, $text)) {
    return false;
  }

  return true;
}

Pyspark replace strings in Spark dataframe column

For scala

import org.apache.spark.sql.functions.regexp_replace
import org.apache.spark.sql.functions.col
data.withColumn("addr_new", regexp_replace(col("addr_line"), "\\*", ""))

Removing specific rows from a dataframe

DF[ ! ( ( DF$sub ==1 & DF$day==2) | ( DF$sub ==3 & DF$day==4) ) , ]   # note the ! (negation)

Or if sub is a factor as suggested by your use of quotes:

DF[ ! paste(sub,day,sep="_") %in% c("1_2", "3_4"), ]

Could also use subset:

subset(DF,  ! paste(sub,day,sep="_") %in% c("1_2", "3_4") )

(And I endorse the use of which in Dirk's answer when using "[" even though some claim it is not needed.)

How to use shared memory with Linux in C

Here's a mmap example:

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

/*
 * pvtmMmapAlloc - creates a memory mapped file area.  
 * The return value is a page-aligned memory value, or NULL if there is a failure.
 * Here's the list of arguments:
 * @mmapFileName - the name of the memory mapped file
 * @size - the size of the memory mapped file (should be a multiple of the system page for best performance)
 * @create - determines whether or not the area should be created.
 */
void* pvtmMmapAlloc (char * mmapFileName, size_t size, char create)  
{      
  void * retv = NULL;                                                                                              
  if (create)                                                                                         
  {                                                                                                   
    mode_t origMask = umask(0);                                                                       
    int mmapFd = open(mmapFileName, O_CREAT|O_RDWR, 00666);                                           
    umask(origMask);                                                                                  
    if (mmapFd < 0)                                                                                   
    {                                                                                                 
      perror("open mmapFd failed");                                                                   
      return NULL;                                                                                    
    }                                                                                                 
    if ((ftruncate(mmapFd, size) == 0))               
    {                                                                                                 
      int result = lseek(mmapFd, size - 1, SEEK_SET);               
      if (result == -1)                                                                               
      {                                                                                               
        perror("lseek mmapFd failed");                                                                
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               

      /* Something needs to be written at the end of the file to                                      
       * have the file actually have the new size.                                                    
       * Just writing an empty string at the current file position will do.                           
       * Note:                                                                                        
       *  - The current position in the file is at the end of the stretched                           
       *    file due to the call to lseek().  
              *  - The current position in the file is at the end of the stretched                    
       *    file due to the call to lseek().                                                          
       *  - An empty string is actually a single '\0' character, so a zero-byte                       
       *    will be written at the last byte of the file.                                             
       */                                                                                             
      result = write(mmapFd, "", 1);                                                                  
      if (result != 1)                                                                                
      {                                                                                               
        perror("write mmapFd failed");                                                                
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               
      retv  =  mmap(NULL, size,   
                  PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);                                     

      if (retv == MAP_FAILED || retv == NULL)                                                         
      {                                                                                               
        perror("mmap");                                                                               
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               
    }                                                                                                 
  }                                                                                                   
  else                                                                                                
  {                                                                                                   
    int mmapFd = open(mmapFileName, O_RDWR, 00666);                                                   
    if (mmapFd < 0)                                                                                   
    {                                                                                                 
      return NULL;                                                                                    
    }                                                                                                 
    int result = lseek(mmapFd, 0, SEEK_END);                                                          
    if (result == -1)                                                                                 
    {                                                                                                 
      perror("lseek mmapFd failed");                  
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                                 
    if (result == 0)                                                                                  
    {                                                                                                 
      perror("The file has 0 bytes");                           
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                              
    retv  =  mmap(NULL, size,     
                PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);                                       

    if (retv == MAP_FAILED || retv == NULL)                                                           
    {                                                                                                 
      perror("mmap");                                                                                 
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                                 

    close(mmapFd);                                                                                    

  }                                                                                                   
  return retv;                                                                                        
}                                                                                                     

How to change the href for a hyperlink using jQuery

This snippet invokes when a link of class 'menu_link' is clicked, and shows the text and url of the link. The return false prevents the link from being followed.

<a rel='1' class="menu_link" href="option1.html">Option 1</a>
<a rel='2' class="menu_link" href="option2.html">Option 2</a>

$('.menu_link').live('click', function() {
   var thelink = $(this);
   alert ( thelink.html() );
   alert ( thelink.attr('href') );
   alert ( thelink.attr('rel') );

   return false;
});

How to Empty Caches and Clean All Targets Xcode 4 and later

I found another way in addition to command+option+shift+K. In XCode 4.2 there is an organizer that can be opened from top-right icon. You can clean all archives and saved project options from there. This helped my situation (I was seeing old removed files in the mainBundle).

how to convert object into string in php

You can tailor how your object is represented as a string by implementing a __toString() method in your class, so that when your object is type cast as a string (explicit type cast $str = (string) $myObject;, or automatic echo $myObject) you can control what is included and the string format.

If you only want to display your object's data, the method above would work. If you want to store your object in a session or database, you need to serialize it, so PHP knows how to reconstruct your instance.

Some code to demonstrate the difference:

class MyObject {

  protected $name = 'JJ';

  public function __toString() {
    return "My name is: {$this->name}\n";
  }

}

$obj = new MyObject;

echo $obj;
echo serialize($obj);

Output:

My name is: JJ

O:8:"MyObject":1:{s:7:"*name";s:2:"JJ";}

C++, copy set to vector

set<T> s;
//....
vector<T> v;
v.assign(s.begin(), s.end());

How to print a float with 2 decimal places in Java?

OK - str to float.

package test;

import java.text.DecimalFormat;

public class TestPtz {
  public static void main(String[] args) {
    String preset0 = "0.09,0.20,0.09,0.07";
    String[] thisto = preset0.split(",");    
    float a = (Float.valueOf(thisto[0])).floatValue();
    System.out.println("[Original]: " + a);   
    a = (float) (a + 0.01);

    // Part 1 - for display / debug
    System.out.printf("[Local]: %.2f \n", a);
    // Part 2 - when value requires to be send as it is
    DecimalFormat df = new DecimalFormat();
    df.setMinimumFractionDigits(2);
    df.setMaximumFractionDigits(2);
    System.out.println("[Remote]: " + df.format(a));

  }
}

Output:

run:
[Original]: 0.09
[Local]: 0.10 
[Remote]: 0.10
BUILD SUCCESSFUL (total time: 0 seconds)

TextView - setting the text size programmatically doesn't seem to work

Text size 2 will be practically invisible. Try it with 14 at least. BTW, using xml has a lot of advantages and will make your life easier once you need to do anything more complex than 'Hello World'.

Get all directories within directory nodejs

Recursive solution

I came here in search of a way to get all of the subdirectories, and all of their subdirectories, etc. Building on the accepted answer, I wrote this:

const fs = require('fs');
const path = require('path');

function flatten(lists) {
  return lists.reduce((a, b) => a.concat(b), []);
}

function getDirectories(srcpath) {
  return fs.readdirSync(srcpath)
    .map(file => path.join(srcpath, file))
    .filter(path => fs.statSync(path).isDirectory());
}

function getDirectoriesRecursive(srcpath) {
  return [srcpath, ...flatten(getDirectories(srcpath).map(getDirectoriesRecursive))];
}

How to make Twitter Bootstrap menu dropdown on hover rather than click

This worked for me:

.dropdown:hover .dropdown-menu {
    display: block;
}

jQuery trigger event when click outside the element

try this one

    $(document).click(function(event) {

        if(event.target.id === 'xxx' )
            return false;
        else {
              // do some this here
        }

    });

How can I solve the error 'TS2532: Object is possibly 'undefined'?

With the release of TypeScript 3.7, optional chaining (the ? operator) is now officially available.

As such, you can simplify your expression to the following:

const data = change?.after?.data();

You may read more about it from that version's release notes, which cover other interesting features released on that version.

Run the following to install the latest stable release of TypeScript.

npm install typescript

That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null or undefined values

const data = change?.after?.data() ?? someOtherData();

Is there any way of configuring Eclipse IDE proxy settings via an autoproxy configuration script?

Here is what I do. All of these instructions are based on my minimal experiences with working PACs, so YMMV.

Download your pac file via your pac URL. It's plain text and should be easy to open in a text editor.

Near the bottom, there's probably a section that says something like: return "PROXY w.x.y.z:a" where "w.x.y.z" is an ip address or username and "a" is a port number.

Write these down.

In a recent version of eclipse :

  • Go to Window -> Preferences -> General -> Network Connections=
  • Change the provider to "Manual"
  • Select the "HTTP" line and click the edit button
  • Add the IP address and port number above to the http line
  • If you have to authenticate to use the proxy,
    • select "Requires Authentication"
    • type in your username. Note that if your authentication is on a Windows domain, you might have to prepend the domain name and a backslash (\) like: MYDOMAIN\MYUSERID
    • Type in your password
  • Click OK
  • Click Apply
  • Click OK

At this point, you should be able to browse using the internal web browser (at least on http URLs).

Good luck.

Edit: Just so you know, it's WAY easier to use Nexus, one set of <mirror> tags and a single proxy setup (inside Nexus) to manage the proxy issues of Maven inside a firewall.

C++ sorting and keeping track of indexes

Well, my solution uses residue technique. We can place the values under sorting in the upper 2 bytes and the indices of the elements - in the lower 2 bytes:

int myints[] = {32,71,12,45,26,80,53,33};

for (int i = 0; i < 8; i++)
   myints[i] = myints[i]*(1 << 16) + i;

Then sort the array myints as usual:

std::vector<int> myvector(myints, myints+8);
sort(myvector.begin(), myvector.begin()+8, std::less<int>());

After that you can access the elements' indices via residuum. The following code prints the indices of the values sorted in the ascending order:

for (std::vector<int>::iterator it = myvector.begin(); it != myvector.end(); ++it)
   std::cout << ' ' << (*it)%(1 << 16);

Of course, this technique works only for the relatively small values in the original array myints (i.e. those which can fit into upper 2 bytes of int). But it has additional benefit of distinguishing identical values of myints: their indices will be printed in the right order.

Docker: How to delete all local Docker images

  1. sudo docker images / docker images // list of images with id
  2. sudo docker rm image <image_id> / docker rm image <image_id>

MySQL: Enable LOAD DATA LOCAL INFILE

Replace the driver php5-mysql by the native driver

On debian

apt-get install php5-mysqlnd

how to split the ng-repeat data with three columns using bootstrap

This solution is very simple:

JSON:

[{id:"1",name:"testA"},{id:"2",name:"test B"},{id:"3",name:"test C"},{id:"4",name:"test D"},{id:"5",name:"test E"}]

HTML:

<div ng-controller="MyCtrl">
  <table>
    <tr ng-repeat="item in items" ng-switch on="$index % 3">
      <td ng-switch-when="0">
        {{items[$index].id}} {{items[$index].name}}
      </td>
      <td ng-switch-when="0">
        <span ng-show="items[$index+1]">
          {{items[$index+1].id}} {{items[$index+1].name}}
        </span>
      </td>
      <td ng-switch-when="0">
        <span ng-show="items[$index+2]">    
          {{items[$index+2].id}} {{items[$index+2].name}}
        </span>
      </td>
    </tr>
  </table>
</div>

DEMO in FIDDLE

enter image description here

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

foreach($array as $k => $v)

Where $k is the key and $v is the value

Or if you just need the keys use array_keys()

Write variable to file, including name

Is something like this what you're looking for?

def write_vars_to_file(f, **vars):
    for name, val in vars.items():
        f.write("%s = %s\n" % (name, repr(val)))

Usage:

>>> import sys
>>> write_vars_to_file(sys.stdout, dict={'one': 1, 'two': 2})
dict = {'two': 2, 'one': 1}

Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

Have you been trying to reference your custom MapFragment class in the layout file?

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

    <fragment
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/mapFragment"
        android:name="com.nfc.demo.MapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

Add "Appendix" before "A" in thesis TOC

You can easily achieve what you want using the appendix package. Here's a sample file that shows you how. The key is the titletoc option when calling the package. It takes whatever value you've defined in \appendixname and the default value is Appendix.

\documentclass{report}
\usepackage[titletoc]{appendix}
\begin{document}
\tableofcontents

\chapter{Lorem ipsum}
\section{Dolor sit amet}
\begin{appendices}
  \chapter{Consectetur adipiscing elit}
  \chapter{Mauris euismod}
\end{appendices}
\end{document}

The output looks like

enter image description here

.append(), prepend(), .after() and .before()

There is no extra advantage for each of them. It totally depends on your scenario. Code below shows their difference.

    Before inserts your html here
<div id="mainTabsDiv">
    Prepend inserts your html here
    <div id="homeTabDiv">
        <span>
            Home
        </span>
    </div>
    <div id="aboutUsTabDiv">
        <span>
            About Us
        </span>
    </div>
    <div id="contactUsTabDiv">
        <span>
            Contact Us
        </span>
    </div>
    Append inserts your html here
</div>
After inserts your html here

What is Gradle in Android Studio?

It's the new build tool that Google wants to use for Android. It's being used due to it being more extensible, and useful than ant. It is meant to enhance developer experience.

You can view a talk by Xavier Ducrohet from the Android Developer Team on Google I/O here.

There is also another talk on Android Studio by Xavier and Tor Norbye, also during Google I/O here.

What is IPV6 for localhost and 0.0.0.0?

For use in a /etc/hosts file as a simple ad blocking technique to cause a domain to fail to resolve, the 0.0.0.0 address has been widely used because it causes the request to immediately fail without even trying, because it's not a valid or routable address. This is in comparison to using 127.0.0.1 in that place, where it will at least check to see if your own computer is listening on the requested port 80 before failing with 'connection refused.' Either of those addresses being used in the hosts file for the domain will stop any requests from being attempted over the actual network, but 0.0.0.0 has gained favor because it's more 'optimal' for the above reason. "127" IPs will attempt to hit your own computer, and any other IP will cause a request to be sent to the router to try to route it, but for 0.0.0.0 there's nowhere to even send a request to.

All that being said, having any IP listed in your hosts file for the domain to be blocked is sufficient, and you wouldn't need or want to also put an ipv6 address in your hosts file unless -- possibly -- you don't have ipv4 enabled at all. I'd be really surprised if that was the case, though. And still though, I think having the host appear in /etc/hosts with a bad ipv4 address when you don't have ipv4 enabled would still give you the result you are looking for which is for it to fail, instead of looking up the real DNS of say, adserver-example.com and getting back either a v4 or v6 IP.

Sticky Header after scrolling down

This was not working for me in Firefox.

We added a conditional based on whether the code places the overflow at the html level. See Animate scrollTop not working in firefox.

  var $header = $("#header #menu-wrap-left"),
  $clone = $header.before($header.clone().addClass("clone"));

  $(window).on("scroll", function() {
    var fromTop = Array(); 
    fromTop["body"] = $("body").scrollTop();
    fromTop["html"] = $("body,html").scrollTop();

if (fromTop["body"]) 
    $('body').toggleClass("down", (fromTop["body"] > 650));

if (fromTop["html"]) 
    $('body,html').toggleClass("down", (fromTop["html"] > 650));

  });

Change UITableView height dynamically

There isn't a system feature to change the height of the table based upon the contents of the tableview. Having said that, it is possible to programmatically change the height of the tableview based upon the contents, specifically based upon the contentSize of the tableview (which is easier than manually calculating the height yourself). A few of the particulars vary depending upon whether you're using the new autolayout that's part of iOS 6, or not.

But assuming you're configuring your table view's underlying model in viewDidLoad, if you want to then adjust the height of the tableview, you can do this in viewDidAppear:

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self adjustHeightOfTableview];
}

Likewise, if you ever perform a reloadData (or otherwise add or remove rows) for a tableview, you'd want to make sure that you also manually call adjustHeightOfTableView there, too, e.g.:

- (IBAction)onPressButton:(id)sender
{
    [self buildModel];
    [self.tableView reloadData];

    [self adjustHeightOfTableview];
}

So the question is what should our adjustHeightOfTableview do. Unfortunately, this is a function of whether you use the iOS 6 autolayout or not. You can determine if you have autolayout turned on by opening your storyboard or NIB and go to the "File Inspector" (e.g. press option+command+1 or click on that first tab on the panel on the right):

enter image description here

Let's assume for a second that autolayout was off. In that case, it's quite simple and adjustHeightOfTableview would just adjust the frame of the tableview:

- (void)adjustHeightOfTableview
{
    CGFloat height = self.tableView.contentSize.height;
    CGFloat maxHeight = self.tableView.superview.frame.size.height - self.tableView.frame.origin.y;

    // if the height of the content is greater than the maxHeight of
    // total space on the screen, limit the height to the size of the
    // superview.

    if (height > maxHeight)
        height = maxHeight;

    // now set the frame accordingly

    [UIView animateWithDuration:0.25 animations:^{
        CGRect frame = self.tableView.frame;
        frame.size.height = height;
        self.tableView.frame = frame;

        // if you have other controls that should be resized/moved to accommodate
        // the resized tableview, do that here, too
    }];
}

If your autolayout was on, though, adjustHeightOfTableview would adjust a height constraint for your tableview:

- (void)adjustHeightOfTableview
{
    CGFloat height = self.tableView.contentSize.height;
    CGFloat maxHeight = self.tableView.superview.frame.size.height - self.tableView.frame.origin.y;

    // if the height of the content is greater than the maxHeight of
    // total space on the screen, limit the height to the size of the
    // superview.

    if (height > maxHeight)
        height = maxHeight;

    // now set the height constraint accordingly

    [UIView animateWithDuration:0.25 animations:^{
        self.tableViewHeightConstraint.constant = height;
        [self.view setNeedsUpdateConstraints];
    }];
}

For this latter constraint-based solution to work with autolayout, we must take care of a few things first:

  1. Make sure your tableview has a height constraint by clicking on the center button in the group of buttons here and then choose to add the height constraint:

    add height constraint

  2. Then add an IBOutlet for that constraint:

    add IBOutlet

  3. Make sure you adjust other constraints so they don't conflict if you adjust the size tableview programmatically. In my example, the tableview had a trailing space constraint that locked it to the bottom of the screen, so I had to adjust that constraint so that rather than being locked at a particular size, it could be greater or equal to a value, and with a lower priority, so that the height and top of the tableview would rule the day:

    adjust other constraints

    What you do here with other constraints will depend entirely upon what other controls you have on your screen below the tableview. As always, dealing with constraints is a little awkward, but it definitely works, though the specifics in your situation depend entirely upon what else you have on the scene. But hopefully you get the idea. Bottom line, with autolayout, make sure to adjust your other constraints (if any) to be flexible to account for the changing tableview height.

As you can see, it's much easier to programmatically adjust the height of a tableview if you're not using autolayout, but in case you are, I present both alternatives.

Command copy exited with code 4 when building - Visual Studio restart solves it

I had the same problem. A simple 'Clean Solution' in VS cleared the error, but it was a temporary solution.

Difference between Java SE/EE/ME?

The SE(JDK) has all the libraries you will ever need to cut your teeth on Java. I recommend the Netbeans IDE as this comes bundled with the SE(JDK) straight from Oracle. Don't forget to set "path" and "classpath" variables especially if you are going to try command line. With a 64 bit system insert the "System Path" e.g. C:\Program Files (x86)\Java\jdk1.7.0 variable before the C:\Windows\system32; to direct the system to your JDK.

hope this helps.

What's with the dollar sign ($"string")

String Interpolation

is a concept that languages like Perl have had for quite a while, and now we’ll get this ability in C# as well. In String Interpolation, we simply prefix the string with a $ (much like we use the @ for verbatim strings). Then, we simply surround the expressions we want to interpolate with curly braces (i.e. { and }):

It looks a lot like the String.Format() placeholders, but instead of an index, it is the expression itself inside the curly braces. In fact, it shouldn’t be a surprise that it looks like String.Format() because that’s really all it is – syntactical sugar that the compiler treats like String.Format() behind the scenes.

A great part is, the compiler now maintains the placeholders for you so you don’t have to worry about indexing the right argument because you simply place it right there in the string.

C# string interpolation is a method of concatenating,formatting and manipulating strings. This feature was introduced in C# 6.0. Using string interpolation, we can use objects and expressions as a part of the string interpolation operation.

Syntax of string interpolation starts with a ‘$’ symbol and expressions are defined within a bracket {} using the following syntax.

{<interpolatedExpression>[,<alignment>][:<formatString>]}  

Where:

  • interpolatedExpression - The expression that produces a result to be formatted
  • alignment - The constant expression whose value defines the minimum number of characters in the string representation of the result of the interpolated expression. If positive, the string representation is right-aligned; if negative, it's left-aligned.
  • formatString - A format string that is supported by the type of the expression result.

The following code example concatenates a string where an object, author as a part of the string interpolation.

string author = "Mohit";  
string hello = $"Hello {author} !";  
Console.WriteLine(hello);  // Hello Mohit !

Read more on C#/.NET Little Wonders: String Interpolation in C# 6

Declaring a boolean in JavaScript using just var

If you want IsLoggedIn to be treated as a boolean you should initialize as follows:

var IsLoggedIn=true;

If you initialize it with var IsLoggedIn=1; then it will be treated as an integer.

However at any time the variable IsLoggedIn could refer to a different data type:

 IsLoggedIn="Hello World";

This will not cause an error.

CSS background image to fit height, width should auto-scale in proportion

try

.something { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: -100;  
}

Custom Drawable for ProgressBar/ProgressDialog

Custom progress with scale!

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_no_smile_eyes_off"
            android:scaleGravity="center" />
    </item>
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_no_smile_eyes_on"
            android:scaleGravity="center" />
    </item>
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_smile_eyes_off"
            android:scaleGravity="center" />
    </item>
    <item android:duration="150">
        <scale
            android:drawable="@drawable/face_smile_eyes_on"
            android:scaleGravity="center" />
    </item>

</animation-list>

What is the use of a cursor in SQL Server?

In SQL server, a cursor is used when you need Instead of the T-SQL commands that operate on all the rows in the result set one at a time, we use a cursor when we need to update records in a database table in a singleton fashion, in other words row by row.to fetch one row at a time or row by row.

Working with cursors consists of several steps:

Declare - Declare is used to define a new cursor. Open - A Cursor is opened and populated by executing the SQL statement defined by the cursor. Fetch - When the cursor is opened, rows can be retrieved from the cursor one by one. Close - After data operations, we should close the cursor explicitly. Deallocate - Finally, we need to delete the cursor definition and release all the system resources associated with the cursor. Syntax

DECLARE cursor_name CURSOR [ LOCAL | GLOBAL ] [ FORWARD_ONLY | SCROLL ] [ STATIC | KEYSET | DYNAMIC | FAST_FORWARD ] [ READ_ONLY | SCROLL_LOCKS | OPTIMISTIC ] [ TYPE_WARNING] FOR select_statement [FOR UPDATE [ OF column_name [ ,...n ] ] ] [;]

npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"

For me worked install the component "VCBuild.exe", just dowload the wizard, install and them open the cmd again as administrator and try run again. Updated link to dowload the wizard here

Testing two JSON objects for equality ignoring child order in Java

I would do the following,

JSONObject obj1 = /*json*/;
JSONObject obj2 = /*json*/;

ObjectMapper mapper = new ObjectMapper();

JsonNode tree1 = mapper.readTree(obj1.toString());
JsonNode tree2 = mapper.readTree(obj2.toString());

return tree1.equals(tree2);

Why emulator is very slow in Android Studio?

I tend to load AVD through snapshot which can be setup in the AVD Manager > Choose AVD > Details... > Checking Emulator Options: Snapshot, and then to run the AVD, Select AVD in AVD Manager > Start... > Select Save To Snapshot and Launch from Snapshot. The first time, ensure that save to snapshot is chosen, as no snapshot exists to launch. The next time onwards choose launch from snapshot.

Slightly apprehensive to suggest this as well, but I have noticed a peculiar behavior when loading and running AVD. When I have the laptop battery being charged on my Lenovo laptop - 64 bit Windows 7, 4GB, 2.5GHz machine, the emulator loads and runs slightly faster and also lags less. I wonder if it is the configuration on my laptop to slow down high computational processes. Would be nice to know if someone else has noticed this behavior? Unplug the charger when the AVD is loaded and see if the AVD slows down.

SQL, Postgres OIDs, What are they and why are they useful?

OIDs being phased out

The core team responsible for Postgres is gradually phasing out OIDs.

Postgres 12 removes special behavior of OID columns

The use of OID as an optional system column on your tables is now removed from Postgres 12. You can no longer use:

  • CREATE TABLE … WITH OIDS command
  • default_with_oids (boolean) compatibility setting

The data type OID remains in Postgres 12. You can explicitly create a column of the type OID.

After migrating to Postgres 12, any optionally-defined system column oid will no longer be invisible by default. Performing a SELECT * will now include this column. Note that this extra “surprise” column may break naïvely written SQL code.

How to make return key on iPhone make keyboard disappear?

If you want to disappear keyboard when writing on alert box textfileds

[[alertController.textFields objectAtIndex:1] resignFirstResponder];

Provide static IP to docker containers via docker-compose

Note that I don't recommend a fixed IP for containers in Docker unless you're doing something that allows routing from outside to the inside of your container network (e.g. macvlan). DNS is already there for service discovery inside of the container network and supports container scaling. And outside the container network, you should use exposed ports on the host. With that disclaimer, here's the compose file you want:

version: '2'

services:
  mysql:
    container_name: mysql
    image: mysql:latest
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=root
    ports:
     - "3306:3306"
    networks:
      vpcbr:
        ipv4_address: 10.5.0.5

  apigw-tomcat:
    container_name: apigw-tomcat
    build: tomcat/.
    ports:
     - "8080:8080"
     - "8009:8009"
    networks:
      vpcbr:
        ipv4_address: 10.5.0.6
    depends_on:
     - mysql

networks:
  vpcbr:
    driver: bridge
    ipam:
     config:
       - subnet: 10.5.0.0/16
         gateway: 10.5.0.1

Maven: How to rename the war file for the project?

You can follow the below step to modify the .war file name if you are using maven project.

Open pom.xml file of your maven project and go to the tag <build></build>,

  1. In that give your desired name between this tag : <finalName></finalName>.

    ex. : <finalName>krutik</finalName>

    After deploying this .war you will be able to access url with:
    http://localhost:8080/krutik/

  2. If you want to access the url with slash '/' then you will have to specify then name as below:

    e.x. : <finalName>krutik#maheta</finalName>

    After deploying this .war you will be able to access url with:
    http://localhost:8080/krutik/maheta

MongoDB vs Firebase

Apples and oranges. Firebase is a Backend-as-a-Service containing identity management, realtime data views and a document database. It runs in the cloud.

MongoDB on the other hand is a full fledged database with a rich query language. In principle it runs on your own machine, but there are cloud providers.

If you are looking for the database component only MongoDB is much more mature and feature-rich.

Javascript change Div style

A simple switch statement should do the trick:

function abc() {
    var elem=document.getElementById('test'),color;
    switch(elem.style.color) {
        case('red'):
            color='black';
            break;
        case('black'):
        default:
            color='red';
    }
    elem.style.color=color;
}

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

  • Open Terminal.
  • Go to Edit -> Profile Preferences.
  • Select the Title & command Tab in the window opened.
  • Mark the checkbox Run command as login shell.
  • close the window and restart the Terminal.

Check this Official Linkenter image description here

IN vs OR in the SQL WHERE Clause

The best way to find out is looking at the Execution Plan.


I tried it with Oracle, and it was exactly the same.

CREATE TABLE performance_test AS ( SELECT * FROM dba_objects );

SELECT * FROM performance_test
WHERE object_name IN ('DBMS_STANDARD', 'DBMS_REGISTRY', 'DBMS_LOB' );

Even though the query uses IN, the Execution Plan says that it uses OR:

--------------------------------------------------------------------------------------    
| Id  | Operation         | Name             | Rows  | Bytes | Cost (%CPU)| Time     |    
--------------------------------------------------------------------------------------    
|   0 | SELECT STATEMENT  |                  |     8 |  1416 |   163   (2)| 00:00:02 |    
|*  1 |  TABLE ACCESS FULL| PERFORMANCE_TEST |     8 |  1416 |   163   (2)| 00:00:02 |    
--------------------------------------------------------------------------------------    

Predicate Information (identified by operation id):                                       
---------------------------------------------------                                       

   1 - filter("OBJECT_NAME"='DBMS_LOB' OR "OBJECT_NAME"='DBMS_REGISTRY' OR                
              "OBJECT_NAME"='DBMS_STANDARD')                                              

Safe Area of Xcode 9

The Safe Area Layout Guide helps avoid underlapping System UI elements when positioning content and controls.

The Safe Area is the area in between System UI elements which are Status Bar, Navigation Bar and Tool Bar or Tab Bar. So when you add a Status bar to your app, the Safe Area shrink. When you add a Navigation Bar to your app, the Safe Area shrinks again.

On the iPhone X, the Safe Area provides additional inset from the top and bottom screen edges in portrait even when no bar is shown. In landscape, the Safe Area is inset from the sides of the screens and the home indicator.

This is taken from Apple's video Designing for iPhone X where they also visualize how different elements affect the Safe Area.

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

I had the same error for quite a while, and here what fixed it for me.

I simply declared in service that i use what follows:

Description= Your node service description
After=network.target

[Service]
Type=forking
PIDFile=/tmp/node_pid_name.pid
Restart=on-failure
KillSignal=SIGQUIT
WorkingDirectory=/path/to/node/app/root/directory
ExecStart=/path/to/node /path/to/server.js

[Install]
WantedBy=multi-user.target

What should catch your attention here is "After=network.target". I spent days and days looking for fixes on nginx side, while the problem was just that. To be sure, stop running the node service you have, launch the ExecStart command directly and try to reproduce the bug. If it doesn't pop, it just means that your service has a problem. At least this is how i found my answer.

For everybody else, good luck!

Remove Blank option from Select Option with AngularJS

Also check whether you have any falsy value or not. Angularjs will insert an empty option if you do have falsy value. I struggled for 2 days just due to falsy value. I hope it will be helpful for someone.

I had options as [0, 1] and initially I was set the model to 0 due to that it was inserted empty option. Workaround for this was ["0" , "1"].

Why do symbols like apostrophes and hyphens get replaced with black diamonds on my website?

It's an encoding problem. You have to set the correct encoding in the HTML head via meta tag:

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

Replace "ISO-8859-1" with whatever your encoding is (e.g. 'UTF-8'). You must find out what encoding your HTML files are. If you're on an Unix system, just type file file.html and it should show you the encoding. If this is not possible, you should be able to find out somewhere what encoding your editor produces.

How add class='active' to html menu with php

  1. $page='one' should occur before you require_once() not after. After is too late- the code has already been required, and $nav has already been defined.

  2. You should use include('header.php'); and include('footer.php'); instead of setting a $nav variable early on. That increases flexibility.

  3. Make more functions. Something like this really makes things easier to follow:

    function maybe($x,$y){return $x?$y:'';}
    function aclass($k){return " class=\"$k\" "; }
    

    then you can write your "condition" like this:

    <a href="..." <?= maybe($page=='one',aclass('active')) ?>> ....
    

How to list only files and not directories of a directory Bash?

ls -p | grep -v /

ls -p lets you show / after the folder name, which acts as a tag for you to remove.

Fast way to discover the row count of a table in PostgreSQL

I did this once in a postgres app by running:

EXPLAIN SELECT * FROM foo;

Then examining the output with a regex, or similar logic. For a simple SELECT *, the first line of output should look something like this:

Seq Scan on uids  (cost=0.00..1.21 rows=8 width=75)

You can use the rows=(\d+) value as a rough estimate of the number of rows that would be returned, then only do the actual SELECT COUNT(*) if the estimate is, say, less than 1.5x your threshold (or whatever number you deem makes sense for your application).

Depending on the complexity of your query, this number may become less and less accurate. In fact, in my application, as we added joins and complex conditions, it became so inaccurate it was completely worthless, even to know how within a power of 100 how many rows we'd have returned, so we had to abandon that strategy.

But if your query is simple enough that Pg can predict within some reasonable margin of error how many rows it will return, it may work for you.

How to find whether a ResultSet is empty or not in Java?

Definitely this gives good solution,

ResultSet rs = stmt.execute("SQL QUERY");
// With the above statement you will not have a null ResultSet 'rs'.
// In case, if any exception occurs then next line of code won't execute.
// So, no problem if I won't check rs as null.

if (rs.next()) {
    do {
      // Logic to retrieve the data from the resultset.
      // eg: rs.getString("abc");
    } while(rs.next());
} else {
    // No data
}

The type arguments for method cannot be inferred from the usage

Get<S, T> takes two type arguments. When you call service.Get(new Signatur()); how does the compiler know what T is? You'll have to pass it explicitly or change something else about your type hierarchies. Passing it explicitly would look like:

service.Get<Signatur, bool>(new Signatur());

SQL subquery with COUNT help

This is probably the easiest way, not the prettiest though:

SELECT *,
    (SELECT Count(*) FROM eventsTable WHERE columnName = 'Business') as RowCount
    FROM eventsTable
    WHERE columnName = 'Business'

This will also work without having to use a group by

SELECT *, COUNT(*) OVER () as RowCount
    FROM eventsTables
    WHERE columnName = 'Business'

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

Segments of p

Assume p contains all possible finite number combinations. See math.stackexchange question

  1. Determine the number of digits needed from the size of the array.
  2. Use segments of p places as indexes to determine how to re-order the array. If a segment exceeds the size boundaries for this array, adjust the p decimal offset and start over.
  3. Check if the re-ordered array is sorted. If it is woot, else adjust the offset and start over.

How to split a dataframe string column into two columns?

df[['fips', 'row']] = df['row'].str.split(' ', n=1, expand=True)

Unit Testing C Code

LibU (http://koanlogic.com/libu) has an unit test module that allows explicit test suite/case dependencies, test isolation, parallel execution and a customizable report formatter (default formats are xml and txt).

The library is BSD licensed and contains many other useful modules - networking, debugging, commonly used data structures, configuration, etc. - should you need them in your projects ...

Where do I find the definition of size_t?

size_t is the unsigned integer type of the result of the sizeof operator (ISO C99 Section 7.17.)

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. The value of the result is implementation-de?ned, and its type (an unsigned integer type) is size_t (ISO C99 Section 6.5.3.4.)

Is it possible to use a batch file to establish a telnet session, send a command and have the output written to a file?

I figured out a way to telnet to a server and change a file permission. Then FTP the file back to your computer and open it. Hopefully this will answer your questions and also help FTP.

The filepath variable is setup so you always login and cd to the same directory. You can change it to a prompt so the user can enter it manually.

:: This will telnet to the server, change the permissions, 
:: download the file, and then open it from your PC. 

:: Add your username, password, servername, and file path to the file.
:: I have not tested the server name with an IP address.

:: Note - telnetcmd.dat and ftpcmd.dat are temp files used to hold commands

@echo off
SET username=
SET password=
SET servername=
SET filepath=

set /p id="Enter the file name: " %=%

echo user %username%> telnetcmd.dat
echo %password%>> telnetcmd.dat
echo cd %filepath%>> telnetcmd.dat
echo SITE chmod 777 %id%>> telnetcmd.dat
echo exit>> telnetcmd.dat
telnet %servername% < telnetcmd.dat


echo user %username%> ftpcmd.dat
echo %password%>> ftpcmd.dat
echo cd %filepath%>> ftpcmd.dat
echo get %id%>> ftpcmd.dat
echo quit>> ftpcmd.dat

ftp -n -s:ftpcmd.dat %servername%
del ftpcmd.dat
del telnetcmd.dat

When should I use GC.SuppressFinalize()?

Dispose(true);
GC.SuppressFinalize(this);

If object has finalizer, .net put a reference in finalization queue.

Since we have call Dispose(ture), it clear object, so we don't need finalization queue to do this job.

So call GC.SuppressFinalize(this) remove reference in finalization queue.

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

To know the exact sdk files in your directory, got to android studio, select tools>sdk

just copy and make sure it got double // in your path.

Hope it can help

Is there a jQuery unfocus method?

Based on your question, I believe the answer is how to trigger a blur, not just (or even) set the event:

 $('#textArea').trigger('blur');

C# ASP.NET Single Sign-On Implementation

There are several Identity providers with SSO support out of the box, also third-party** products.

** The only problem with third party products is that they charge per user/month, and it can be quite expensive.

Some of the tools available and with APIs for .NET are:

If you decide to go with your own implementation, you could use the frameworks below categorized by programming language.

  • C#

    • IdentityServer3 (OAuth/OpenID protocols, OWIN/Katana)
    • IdentityServer4 (OAuth/OpenID protocols, ASP.NET Core)
    • OAuth 2.0 by Okta
  • Javascript

    • passport-openidconnect (node.js)
    • oidc-provider (node.js)
    • openid-client (node.js)
  • Python

    • pyoidc
    • Django OIDC Provider

I would go with IdentityServer4 and ASP.NET Core application, it's easy configurable and you can also add your own authentication provider. It uses OAuth/OpenID protocols which are newer than SAML 2.0 and WS-Federation.

Use dynamic (variable) string as regex pattern in JavaScript

var string = "Hi welcome to stack overflow"
var toSearch = "stack"

//case insensitive search

var result = string.search(new RegExp(toSearch, "i")) > 0 ? 'Matched' : 'notMatched'

https://jsfiddle.net/9f0mb6Lz/

Hope this helps

How to set text size in a button in html

Belated. If need any fancy button than anyone can try this.

_x000D_
_x000D_
#startStopBtn {_x000D_
    font-size: 30px;_x000D_
    font-weight: bold;_x000D_
    display: inline-block;_x000D_
    margin: 0 auto;_x000D_
    color: #dcfbb4;_x000D_
    background-color: green;_x000D_
    border: 0.4em solid #d4f7da;_x000D_
    border-radius: 50%;_x000D_
    transition: all 0.3s;_x000D_
    box-sizing: border-box;_x000D_
    width: 4em;_x000D_
    height: 4em;_x000D_
    line-height: 3em;_x000D_
    cursor: pointer;_x000D_
    box-shadow: 0 0 0 rgba(0,0,0,0.1), inset 0 0 0 rgba(0,0,0,0.1);_x000D_
    text-align: center;_x000D_
}_x000D_
#startStopBtn:hover{_x000D_
    box-shadow: 0 0 2em rgba(0,0,0,0.1), inset 0 0 1em rgba(0,0,0,0.1);_x000D_
    background-color: #29a074;_x000D_
  }
_x000D_
<div id="startStopBtn" onclick="startStop()" class=""> Go!</div>
_x000D_
_x000D_
_x000D_

Matplotlib legends in subplot

This should work:

ax1.plot(xtr, color='r', label='HHZ 1')
ax1.legend(loc="upper right")
ax2.plot(xtr, color='r', label='HHN')
ax2.legend(loc="upper right")
ax3.plot(xtr, color='r', label='HHE')
ax3.legend(loc="upper right")

Does JavaScript pass by reference?

Function arguments are passed either by-value or by-sharing, but never ever by reference in JavaScript!

Call-by-Value

Primitive types are passed by-value:

_x000D_
_x000D_
var num = 123, str = "foo";

function f(num, str) {
  num += 1;
  str += "bar";
  console.log("inside of f:", num, str);
}

f(num, str);
console.log("outside of f:", num, str);
_x000D_
_x000D_
_x000D_

Reassignments inside a function scope are not visible in the surrounding scope.

This also applies to Strings, which are a composite data type and yet immutable:

_x000D_
_x000D_
var str = "foo";

function f(str) {
  str[0] = "b"; // doesn't work, because strings are immutable
  console.log("inside of f:", str);
}

f(str);
console.log("outside of f:", str);
_x000D_
_x000D_
_x000D_

Call-by-Sharing

Objects, that is to say all types that are not primitives, are passed by-sharing. A variable that holds a reference to an object actually holds merely a copy of this reference. If JavaScript would pursue a call-by-reference evaluation strategy, the variable would hold the original reference. This is the crucial difference between by-sharing and by-reference.

What are the practical consequences of this distinction?

_x000D_
_x000D_
var o = {x: "foo"}, p = {y: 123};

function f(o, p) {
  o.x = "bar"; // Mutation
  p = {x: 456}; // Reassignment
  console.log("o inside of f:", o);
  console.log("p inside of f:", p);
}

f(o, p);

console.log("o outside of f:", o);
console.log("p outside of f:", p);
_x000D_
_x000D_
_x000D_

Mutating means to modify certain properties of an existing Object. The reference copy that a variable is bound to and that refers to this object remains the same. Mutations are thus visible in the caller's scope.

Reassigning means to replace the reference copy bound to a variable. Since it is only a copy, other variables holding a copy of the same reference remain unaffected. Reassignments are thus not visible in the caller's scope like they would be with a call-by-reference evaluation strategy.

Further information on evaluation strategies in ECMAScript.

How to convert string to double with proper cultureinfo

You can convert the value user provides to a double and store it again as nvarchar, with the aid of FormatProviders. CultureInfo is a typical FormatProvider. Assuming you know the culture you are operating,

System.Globalization.CultureInfo EnglishCulture = new System.Globalization.CultureInfo("en-EN");
System.Globalization.CultureInfo GermanCulture = new System.Globalization.CultureInfo("de-de");

will suffice to do the neccesary transformation, like;

double val;
if(double.TryParse("65,89875", System.Globalization.NumberStyles.Float, GermanCulture,  out val))
{
    string valInGermanFormat = val.ToString(GermanCulture);
    string valInEnglishFormat = val.ToString(EnglishCulture);
}

if(double.TryParse("65.89875", System.Globalization.NumberStyles.Float, EnglishCulture,  out val))
{
    string valInGermanFormat = val.ToString(GermanCulture);
    string valInEnglishFormat = val.ToString(EnglishCulture);
}

How can I comment a single line in XML?

Not orthodox, but it works for me sometimes; set your comment as another attribute:

<node usefulAttr="foo" comment="Your comment here..."/>

How do I check if a cookie exists?

document.cookie.indexOf('cookie_name=');

It will return -1 if that cookie does not exist.

p.s. Only drawback of it is (as mentioned in comments) that it will mistake if there is cookie set with such name: any_prefix_cookie_name

(Source)

How to change a nullable column to not nullable in a Rails migration?

Rails 4:

def change
  change_column_null(:users, :admin, false )
end

How to "pretty" format JSON output in Ruby on Rails

Dumping an ActiveRecord object to JSON (in the Rails console):

pp User.first.as_json

# => {
 "id" => 1,
 "first_name" => "Polar",
 "last_name" => "Bear"
}

Spark - load CSV file as DataFrame?

In Java 1.8 This code snippet perfectly working to read CSV files

POM.xml

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.11</artifactId>
    <version>2.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-sql_2.10 -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.10</artifactId>
    <version>2.0.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.scala-lang/scala-library -->
<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-library</artifactId>
    <version>2.11.8</version>
</dependency>
<dependency>
    <groupId>com.databricks</groupId>
    <artifactId>spark-csv_2.10</artifactId>
    <version>1.4.0</version>
</dependency>

Java

SparkConf conf = new SparkConf().setAppName("JavaWordCount").setMaster("local");
// create Spark Context
SparkContext context = new SparkContext(conf);
// create spark Session
SparkSession sparkSession = new SparkSession(context);

Dataset<Row> df = sparkSession.read().format("com.databricks.spark.csv").option("header", true).option("inferSchema", true).load("hdfs://localhost:9000/usr/local/hadoop_data/loan_100.csv");

        //("hdfs://localhost:9000/usr/local/hadoop_data/loan_100.csv");
System.out.println("========== Print Schema ============");
df.printSchema();
System.out.println("========== Print Data ==============");
df.show();
System.out.println("========== Print title ==============");
df.select("title").show();

multiple conditions for filter in spark data frames

df2 = df1.filter("Status=2")
     .filter("Status=3");

How do I capture response of form.submit

You can event.preventDefault() in the click handler for your submit button to ensure that the HTML form default submit event doesn't fire (which is what leads to the page refreshing).

Another alternative would be to use hackier form markup: It's the use of <form> and type="submit" that is getting in the way of the desired behavior here; as these ultimately lead to click events refreshing the page.

If you want to still use <form>, and you don't want to write custom click handlers, you can use jQuery's ajax method, which abstracts the entire problem away for you by exposing promise methods for success, error, etc.


To recap, you can solve your problem by either:

• preventing default behavior in the handling function by using event.preventDefault()

• using elements that don't have default behavior (e.g. <form>)

• using jQuery ajax


(i just noticed this question is from 2008, not sure why it showed up in my feed; at any rate, hopefully this is a clear answer)

Python : List of dict, if exists increment a dict value, if not append a new dict

To do it exactly your way? You could use the for...else structure

for url in list_of_urls:
    for url_dict in urls:
        if url_dict['url'] == url:
            url_dict['nbr'] += 1
            break
    else:
        urls.append(dict(url=url, nbr=1))

But it is quite inelegant. Do you really have to store the visited urls as a LIST? If you sort it as a dict, indexed by url string, for example, it would be way cleaner:

urls = {'http://www.google.fr/': dict(url='http://www.google.fr/', nbr=1)}

for url in list_of_urls:
    if url in urls:
        urls[url]['nbr'] += 1
    else:
        urls[url] = dict(url=url, nbr=1)

A few things to note in that second example:

  • see how using a dict for urls removes the need for going through the whole urls list when testing for one single url. This approach will be faster.
  • Using dict( ) instead of braces makes your code shorter
  • using list_of_urls, urls and url as variable names make the code quite hard to parse. It's better to find something clearer, such as urls_to_visit, urls_already_visited and current_url. I know, it's longer. But it's clearer.

And of course I'm assuming that dict(url='http://www.google.fr', nbr=1) is a simplification of your own data structure, because otherwise, urls could simply be:

urls = {'http://www.google.fr':1}

for url in list_of_urls:
    if url in urls:
        urls[url] += 1
    else:
        urls[url] = 1

Which can get very elegant with the defaultdict stance:

urls = collections.defaultdict(int)
for url in list_of_urls:
    urls[url] += 1

How to keep Docker container running after starting services?

The reason it exits is because the shell script is run first as PID 1 and when that's complete, PID 1 is gone, and docker only runs while PID 1 is.

You can use supervisor to do everything, if run with the "-n" flag it's told not to daemonize, so it will stay as the first process:

CMD ["/usr/bin/supervisord", "-n"]

And your supervisord.conf:

[supervisord]
nodaemon=true

[program:startup]
priority=1
command=/root/credentialize_and_run.sh
stdout_logfile=/var/log/supervisor/%(program_name)s.log
stderr_logfile=/var/log/supervisor/%(program_name)s.log
autorestart=false
startsecs=0

[program:nginx]
priority=10
command=nginx -g "daemon off;"
stdout_logfile=/var/log/supervisor/nginx.log
stderr_logfile=/var/log/supervisor/nginx.log
autorestart=true

Then you can have as many other processes as you want and supervisor will handle the restarting of them if needed.

That way you could use supervisord in cases where you might need nginx and php5-fpm and it doesn't make much sense to have them apart.

How do I minimize the command prompt from my bat file

One option is to find one of the various utilities that can change the window state of the currently running console window and make a call to it from within the batch script.

You can run it as the first thing in your batch script. Here are two such tools:

min.exe http://www.paulsadowski.com/wsh/cmdprogs.htm

cmdow http://www.commandline.co.uk/cmdow/index.html

jQuery add image inside of div tag

my 2 cents:

$('#theDiv').prepend($('<img>',{id:'theImg',src:'theImg.png'}))

Read a file one line at a time in node.js?

With the carrier module:

var carrier = require('carrier');

process.stdin.resume();
carrier.carry(process.stdin, function(line) {
    console.log('got one line: ' + line);
});

windows batch file rename

I am assuming you know the length of the part before the _ and after the underscore, as well as the extension. If you don't it might be more complex than a simple substring.

cd C:\path\to\the\files
for /f %%a IN ('dir /b *.jpg') do (
set p=%a:~0,3%
set q=%a:~4,4%
set b=%p_%q.jpg
ren %a %b
)

I just came up with this script, and I did not test it. Check out this and that for more info.

IF you want to assume you don't know the positions of the _ and the lengths and the extension, I think you could do something with for loops to check the index of the _, then the last index of the ., wrap it in a goto thing and make it work. If you're willing to go through that trouble, I'd suggest you use WindowsPowerShell (or Cygwin) at least (for your own sake) or install a more advanced scripting language (think Python/Perl) you'll get more support either way.

What file uses .md extension and how should I edit them?

Yup, just GitHub flavored Markdown. Including a README file in your repository will help others quickly determine what it's about and how to install it. Very helpful to include in your repos.

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

I've been struggling with it for a day or so too, tried every solution. What helped me was to check that capital letters in app.config. I had PublicKeyToken instead of publicKeyToken, after changing it suddenly worked.

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

Creating all possible k combinations of n items in C++

In Python, this is implemented as itertools.combinations

https://docs.python.org/2/library/itertools.html#itertools.combinations

In C++, such combination function could be implemented based on permutation function.

The basic idea is to use a vector of size n, and set only k item to 1 inside, then all combinations of nchoosek could obtained by collecting the k items in each permutation. Though it might not be the most efficient way require large space, as combination is usually a very large number. It's better to be implemented as a generator or put working codes into do_sth().

Code sample:

#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>

using namespace std;

int main(void) {

  int n=5, k=3;

  // vector<vector<int> > combinations;
 vector<int> selected;
 vector<int> selector(n);
 fill(selector.begin(), selector.begin() + k, 1);
 do {
     for (int i = 0; i < n; i++) {
      if (selector[i]) {
            selected.push_back(i);
      }
     }
     //     combinations.push_back(selected);
         do_sth(selected);
     copy(selected.begin(), selected.end(), ostream_iterator<int>(cout, " "));
     cout << endl;
     selected.clear();
 }
 while (prev_permutation(selector.begin(), selector.end()));

  return 0;
}

and the output is

0 1 2 
0 1 3 
0 1 4 
0 2 3 
0 2 4 
0 3 4 
1 2 3 
1 2 4 
1 3 4 
2 3 4 

This solution is actually a duplicate with Generating combinations in c++

Call a React component method from outside

With React17 you can use useImperativeHandle hook.

useImperativeHandle customizes the instance value that is exposed to parent components when using ref. As always, imperative code using refs should be avoided in most cases. useImperativeHandle should be used with forwardRef:

function FancyInput(props, ref) {
    const inputRef = useRef();
    useImperativeHandle(ref, () => ({
        focus: () => {
            inputRef.current.focus();
        }
    }));

    return <input ref={inputRef} ... />;
}

FancyInput = forwardRef(FancyInput);

In this example, a parent component that renders would be able to call inputRef.current.focus().

Xcode Debugger: view value of variable

Your confusion stems from the fact that declared properties are not (necessarily named the same as) (instance) variables.

The expresion

indexPath.row

is equivalent to

[indexPath row]

and the assignment

delegate.myData = [myData objectAtIndex:indexPath.row];

is equivalent to

[delegate setMyData:[myData objectAtIndex:[indexPath row]]];

assuming standard naming for synthesised properties.

Furthermore, delegate is probably declared as being of type id<SomeProtocol>, i.e., the compiler hasn’t been able to provide actual type information for delegate at that point, and the debugger is relying on information provided at compile-time. Since id is a generic type, there’s no compile-time information about the instance variables in delegate.

Those are the reasons why you don’t see myData or row as variables.

If you want to inspect the result of sending -row or -myData, you can use commands p or po:

p (NSInteger)[indexPath row]
po [delegate myData]

or use the expressions window (for instance, if you know your delegate is of actual type MyClass *, you can add an expression (MyClass *)delegate, or right-click delegate, choose View Value as… and type the actual type of delegate (e.g. MyClass *).

That being said, I agree that the debugger could be more helpful:

  • There could be an option to tell the debugger window to use run-time type information instead of compile-time information. It'd slow down the debugger, granted, but would provide useful information;

  • Declared properties could be shown up in a group called properties and allow for (optional) inspection directly in the debugger window. This would also slow down the debugger because of the need to send a message/execute a method in order to get information, but would provide useful information, too.

Enabling refreshing for specific html elements only

Try this:

_x000D_
_x000D_
function reload(){_x000D_
    var container = document.getElementById("yourDiv");_x000D_
    var content = container.innerHTML;_x000D_
    container.innerHTML= content; _x000D_
    _x000D_
   //this line is to watch the result in console , you can remove it later _x000D_
    console.log("Refreshed"); _x000D_
}
_x000D_
<a href="javascript: reload()">Click to Reload</a>_x000D_
    <div id="yourDiv">The content that you want to refresh/reload</div>
_x000D_
_x000D_
_x000D_

Hope it works. Let me know

How do you change the character encoding of a postgres database?

Dumping a database with a specific encoding and try to restore it on another database with a different encoding could result in data corruption. Data encoding must be set BEFORE any data is inserted into the database.

Check this : When copying any other database, the encoding and locale settings cannot be changed from those of the source database, because that might result in corrupt data.

And this : Some locale categories must have their values fixed when the database is created. You can use different settings for different databases, but once a database is created, you cannot change them for that database anymore. LC_COLLATE and LC_CTYPE are these categories. They affect the sort order of indexes, so they must be kept fixed, or indexes on text columns would become corrupt. (But you can alleviate this restriction using collations, as discussed in Section 22.2.) The default values for these categories are determined when initdb is run, and those values are used when new databases are created, unless specified otherwise in the CREATE DATABASE command.


I would rather rebuild everything from the begining properly with a correct local encoding on your debian OS as explained here :

su root

Reconfigure your local settings :

dpkg-reconfigure locales

Choose your locale (like for instance for french in Switzerland : fr_CH.UTF8)

Uninstall and clean properly postgresql :

apt-get --purge remove postgresql\*
rm -r /etc/postgresql/
rm -r /etc/postgresql-common/
rm -r /var/lib/postgresql/
userdel -r postgres
groupdel postgres

Re-install postgresql :

aptitude install postgresql-9.1 postgresql-contrib-9.1 postgresql-doc-9.1

Now any new database will be automatically be created with correct encoding, LC_TYPE (character classification), and LC_COLLATE (string sort order).

Check if int is between two numbers

You are human, and therefore you understand what the term "10 < x < 20" suppose to mean. The computer doesn't have this intuition, so it reads it as: "(10 < x) < 20".

For example, if x = 15, it will calculate:

(10 < x) => TRUE

"TRUE < 20" => ???

In C programming, it will be worse, since there are no True\False values. If x = 5, the calculation will be:

10 < x => 0 (the value of False)

0 < 20 => non-0 number (True)

and therefore "10 < 5 < 20" will return True! :S

Returning binary file from controller in ASP.NET Web API

For anyone having the problem of the API being called more than once while downloading a fairly large file using the method in the accepted answer, please set response buffering to true System.Web.HttpContext.Current.Response.Buffer = true;

This makes sure that the entire binary content is buffered on the server side before it is sent to the client. Otherwise you will see multiple request being sent to the controller and if you do not handle it properly, the file will become corrupt.

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

My issue was due to version conflict. I resolved this issue by excluding byte-buddy dependency from springfox

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.7.0</version>
  <exclusions>
  <exclusion>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy</artifactId>
  </exclusion>
  </exclusions>
</dependency>

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.7.0</version>
  <exclusions>
  <exclusion>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy</artifactId>
  </exclusion>
</exclusions>
</dependency>

How do I convert a String to an int in Java?

This can work,

Integer.parseInt(yourString);

Get data from JSON file with PHP

Get the content of the JSON file using file_get_contents():

$str = file_get_contents('http://example.com/example.json/');

Now decode the JSON using json_decode():

$json = json_decode($str, true); // decode the JSON into an associative array

You have an associative array containing all the information. To figure out how to access the values you need, you can do the following:

echo '<pre>' . print_r($json, true) . '</pre>';

This will print out the contents of the array in a nice readable format. Note that the second parameter is set to true in order to let print_r() know that the output should be returned (rather than just printed to screen). Then, you access the elements you want, like so:

$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];

Or loop through the array however you wish:

foreach ($json['daily']['data'] as $field => $value) {
    // Use $field and $value here
}

Demo!

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

IIS Config Error - This configuration section cannot be used at this path

Heres what worked for me, had a similar problem on my new laptop which had windows 10.

  • Search for "Turn windows features on or off"
  • Check "Internet Information Services"
  • Check "World Wide Web Services"
  • Check "Application Development Features"
  • Enable all items under this

try again, now it should work.

Convert data file to blob

As pointed in the comments, file is a blob:

file instanceof Blob; // true

And you can get its content with the file reader API https://developer.mozilla.org/en/docs/Web/API/FileReader

Read more: https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications

_x000D_
_x000D_
var input = document.querySelector('input[type=file]');
var textarea = document.querySelector('textarea');

function readFile(event) {
  textarea.textContent = event.target.result;
  console.log(event.target.result);
}

function changeFile() {
  var file = input.files[0];
  var reader = new FileReader();
  reader.addEventListener('load', readFile);
  reader.readAsText(file);
}

input.addEventListener('change', changeFile);
_x000D_
<input type="file">
<textarea rows="10" cols="50"></textarea>
_x000D_
_x000D_
_x000D_

Alternating Row Colors in Bootstrap 3 - No Table

You can use this code :

.row :nth-child(odd){
  background-color:red;
}
.row :nth-child(even){
  background-color:green;
}

Demo : http://codepen.io/mouhammed/pen/rblsC

How do I put the image on the right side of the text in a UIButton?

Simplest solution:

iOS 10 & up, Swift:

button.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
button.titleLabel?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)
button.imageView?.transform = CGAffineTransform(scaleX: -1.0, y: 1.0)

Before iOS 10, Swift/Obj-C:

button.transform = CGAffineTransformMakeScale(-1.0, 1.0);
button.titleLabel.transform = CGAffineTransformMakeScale(-1.0, 1.0);
button.imageView.transform = CGAffineTransformMakeScale(-1.0, 1.0);

iOS 9 & up, Swift: (Recommended)

button.semanticContentAttribute = .forceRightToLeft

What is the difference between getText() and getAttribute() in Selenium WebDriver?

<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">

In above html tag we have different attributes like src, alt, width and height.

If you want to get the any attribute value from above html tag you have to pass attribute value in getAttribute() method

Syntax:

getAttribute(attributeValue)
getAttribute(src) you get w3schools.jpg
getAttribute(height) you get 142
getAttribute(width) you get 104 

format a Date column in a Data Frame

This should do it (where df is your dataframe)

df$JoiningDate <- as.Date(df$JoiningDate , format = "%m/%d/%y")

df[order(df$JoiningDate ),]