Programs & Examples On #Evc4

Python base64 data decode

i used chardet to detect possible encoding of this data ( if its text ), but get {'confidence': 0.0, 'encoding': None}. Then i tried to use pickle.load and get nothing again. I tried to save this as file , test many different formats and failed here too. Maybe you tell us what type have this 16512 bytes of mysterious data?

Python group by

Python's built-in itertools module actually has a groupby function , but for that the elements to be grouped must first be sorted such that the elements to be grouped are contiguous in the list:

from operator import itemgetter
sortkeyfn = itemgetter(1)
input = [('11013331', 'KAT'), ('9085267', 'NOT'), ('5238761', 'ETH'), 
 ('5349618', 'ETH'), ('11788544', 'NOT'), ('962142', 'ETH'), ('7795297', 'ETH'), 
 ('7341464', 'ETH'), ('9843236', 'KAT'), ('5594916', 'ETH'), ('1550003', 'ETH')] 
input.sort(key=sortkeyfn)

Now input looks like:

[('5238761', 'ETH'), ('5349618', 'ETH'), ('962142', 'ETH'), ('7795297', 'ETH'),
 ('7341464', 'ETH'), ('5594916', 'ETH'), ('1550003', 'ETH'), ('11013331', 'KAT'),
 ('9843236', 'KAT'), ('9085267', 'NOT'), ('11788544', 'NOT')]

groupby returns a sequence of 2-tuples, of the form (key, values_iterator). What we want is to turn this into a list of dicts where the 'type' is the key, and 'items' is a list of the 0'th elements of the tuples returned by the values_iterator. Like this:

from itertools import groupby
result = []
for key,valuesiter in groupby(input, key=sortkeyfn):
    result.append(dict(type=key, items=list(v[0] for v in valuesiter)))

Now result contains your desired dict, as stated in your question.

You might consider, though, just making a single dict out of this, keyed by type, and each value containing the list of values. In your current form, to find the values for a particular type, you'll have to iterate over the list to find the dict containing the matching 'type' key, and then get the 'items' element from it. If you use a single dict instead of a list of 1-item dicts, you can find the items for a particular type with a single keyed lookup into the master dict. Using groupby, this would look like:

result = {}
for key,valuesiter in groupby(input, key=sortkeyfn):
    result[key] = list(v[0] for v in valuesiter)

result now contains this dict (this is similar to the intermediate res defaultdict in @KennyTM's answer):

{'NOT': ['9085267', '11788544'], 
 'ETH': ['5238761', '5349618', '962142', '7795297', '7341464', '5594916', '1550003'], 
 'KAT': ['11013331', '9843236']}

(If you want to reduce this to a one-liner, you can:

result = dict((key,list(v[0] for v in valuesiter)
              for key,valuesiter in groupby(input, key=sortkeyfn))

or using the newfangled dict-comprehension form:

result = {key:list(v[0] for v in valuesiter)
              for key,valuesiter in groupby(input, key=sortkeyfn)}

How to search for a string inside an array of strings

You can use Array.prototype.find function in javascript. Array find MDN.

So to find string in array of string, the code becomes very simple. Plus as browser implementation, it will provide good performance.

Ex.

var strs = ['abc', 'def', 'ghi', 'jkl', 'mno'];
var value = 'abc';
strs.find(
    function(str) {
        return str == value;
    }
);

or using lambda expression it will become much shorter

var strs = ['abc', 'def', 'ghi', 'jkl', 'mno'];
var value = 'abc';
strs.find((str) => str === value);

How to only get file name with Linux 'find'?

If you are using GNU find

find . -type f -printf "%f\n"

Or you can use a programming language such as Ruby(1.9+)

$ ruby -e 'Dir["**/*"].each{|x| puts File.basename(x)}'

If you fancy a bash (at least 4) solution

shopt -s globstar
for file in **; do echo ${file##*/}; done

jQuery class within class selector

is just going to look for a div with class="outer inner", is that correct?

No, '.outer .inner' will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner' (no space) would give the results you're thinking of.

'.outer > .inner' will look for immediate children of an element with the .outer class for elements with the .inner class.

Both '.outer .inner' and '.outer > .inner' should work for your example, although the selectors are fundamentally different and you should be wary of this.

Converting an object to a string

maybe you are looking for

JSON.stringify(JSON.stringify(obj))


"{\"id\":30}"

Copy mysql database from remote server to local computer

This answer is not remote server but local server. The logic should be the same. To copy and backup my local machine MAMP database to my local desktop machine folder, go to console then

mysqldump -h YourHostName -u YourUserNameHere -p YourDataBaseNameHere > DestinationPath/xxxwhatever.sql

In my case YourHostName was localhost. DestinationPath is the path to the download; you can drag and drop your desired destination folder and it will paste the path in.

Then password may be asked:

Enter password: xxxxxxxx

Plotting a 2D heatmap with Matplotlib

For a 2d numpy array, simply use imshow() may help you:

import matplotlib.pyplot as plt
import numpy as np


def heatmap2d(arr: np.ndarray):
    plt.imshow(arr, cmap='viridis')
    plt.colorbar()
    plt.show()


test_array = np.arange(100 * 100).reshape(100, 100)
heatmap2d(test_array)

The heatmap of the example code

This code produces a continuous heatmap.

You can choose another built-in colormap from here.

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

Static linking vs dynamic linking

Static linking includes the files that the program needs in a single executable file.

Dynamic linking is what you would consider the usual, it makes an executable that still requires DLLs and such to be in the same directory (or the DLLs could be in the system folder).

(DLL = dynamic link library)

Dynamically linked executables are compiled faster and aren't as resource-heavy.

How to add,set and get Header in request of HttpClient?

You can use HttpPost, there are methods to add Header to the Request.

DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);

httpPost.addHeader("header-name" , "header-value");

HttpResponse response = httpclient.execute(httpPost);

Kendo grid date column not formatting

just need putting the datatype of the column in the datasource

dataSource: {
      data: empModel.Value,
      pageSize: 10,
      schema:  {
                model: {
                    fields: {
                        DOJ: { type: "date" }
                            }
                       }
               }  
           }

and then your statement column:

 columns: [
    {
        field: "Name",
        width: 90,
        title: "Name"
    },

    {
        field: "DOJ",
        width: 90,
        title: "DOJ",
        type: "date",
        format:"{0:MM-dd-yyyy}" 
    }
]

How do I pass data to Angular routed components?

use a shared service to store data with a custom index. then send that custom index with queryParam. this approach is more flexible.

// component-a : typeScript :
constructor( private DataCollector: DataCollectorService ) {}

ngOnInit() {
    this.DataCollector['someDataIndex'] = data;
}

// component-a : html :
<a routerLink="/target-page" 
   [queryParams]="{index: 'someDataIndex'}"></a>

.

// component-b : typeScript :
public data;

constructor( private DataCollector: DataCollectorService ) {}

ngOnInit() {
    this.route.queryParams.subscribe(
        (queryParams: Params) => {
            this.data = this.DataCollector[queryParams['index']];
        }
    );
}

How to create dictionary and add key–value pairs dynamically?

I ran into this problem.. but within a for loop. The top solution did not work (when using variables (and not strings) for the parameters of the push function), and the others did not account for key values based on variables. I was surprised this approach (which is common in php) worked..

  // example dict/json                  
  var iterateDict = {'record_identifier': {'content':'Some content','title':'Title of my Record'},
    'record_identifier_2': {'content':'Some  different content','title':'Title of my another Record'} };

  var array = [];

  // key to reduce the 'record' to
  var reduceKey = 'title';

  for(key in iterateDict)
   // ultra-safe variable checking...
   if(iterateDict[key] !== undefined && iterateDict[key][reduceKey] !== undefined)
    // build element to new array key
     array[key]=iterateDict[key][reduceKey];

What's the environment variable for the path to the desktop?

This is not a solution but I hope it helps: This comes close except that when the KEY = %userprofile%\desktop the copy fails even though zdesktop=%userprofile%\desktop. I think because the embedded %userprofile% is not getting translated.

REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop>z.out
for /f "tokens=3 skip=4" %%t in (z.out) do set zdesktop=%%t
copy myicon %zdesktop%
set zdesktop=
del z.out

So it sucessfully parses out the REG key but if the key contains an embedded %var% it doesn't get translated during the copy command.

How to set default value for HTML select?

You first need to add values to your select options and for easy targetting give the select itself an id.

Let's make option b the default:

<select id="mySelect">
    <option>a</option>
    <option selected="selected">b</option>
    <option>c</option>
</select>

Now you can change the default selected value with JavaScript like this:

<script>
var temp = "a";
var mySelect = document.getElementById('mySelect');

for(var i, j = 0; i = mySelect.options[j]; j++) {
    if(i.value == temp) {
        mySelect.selectedIndex = j;
        break;
    }
}
</script>

See it in action on codepen.

How to submit a form on enter when the textarea has focus?

Why do you want a textarea to submit when you hit enter?

A "text" input will submit by default when you press enter. It is a single line input.

<input type="text" value="...">

A "textarea" will not, as it benefits from multi-line capabilities. Submitting on enter takes away some of this benefit.

<textarea name="area"></textarea>

You can add JavaScript code to detect the enter keypress and auto-submit, but you may be better off using a text input.

What does the exclamation mark do before the function?

It returns whether the statement can evaluate to false. eg:

!false      // true
!true       // false
!isValid()  // is not valid

You can use it twice to coerce a value to boolean:

!!1    // true
!!0    // false

So, to more directly answer your question:

var myVar = !function(){ return false; }();  // myVar contains true

Edit: It has the side effect of changing the function declaration to a function expression. E.g. the following code is not valid because it is interpreted as a function declaration that is missing the required identifier (or function name):

function () { return false; }();  // syntax error

How to detect the OS from a Bash script?

Detecting operating system and CPU type is not so easy to do portably. I have a sh script of about 100 lines that works across a very wide variety of Unix platforms: any system I have used since 1988.

The key elements are

  • uname -p is processor type but is usually unknown on modern Unix platforms.

  • uname -m will give the "machine hardware name" on some Unix systems.

  • /bin/arch, if it exists, will usually give the type of processor.

  • uname with no arguments will name the operating system.

Eventually you will have to think about the distinctions between platforms and how fine you want to make them. For example, just to keep things simple, I treat i386 through i686 , any "Pentium*" and any "AMD*Athlon*" all as x86.

My ~/.profile runs an a script at startup which sets one variable to a string indicating the combination of CPU and operating system. I have platform-specific bin, man, lib, and include directories that get set up based on that. Then I set a boatload of environment variables. So for example, a shell script to reformat mail can call, e.g., $LIB/mailfmt which is a platform-specific executable binary.

If you want to cut corners, uname -m and plain uname will tell you what you want to know on many platforms. Add other stuff when you need it. (And use case, not nested if!)

Read Session Id using Javascript

The following can be used to retrieve JSESSIONID:

function getJSessionId(){
    var jsId = document.cookie.match(/JSESSIONID=[^;]+/);
    if(jsId != null) {
        if (jsId instanceof Array)
            jsId = jsId[0].substring(11);
        else
            jsId = jsId.substring(11);
    }
    return jsId;
}

Switching the order of block elements with CSS

Update: Two lightweight CSS solutions:

Using flex, flex-flow and order:

Example1: Demo Fiddle

    body{
        display:flex;
        flex-flow: column;
    }
    #blockA{
        order:4;
    }
    #blockB{
        order:3;
    }
    #blockC{
        order:2;
    }

Alternatively, reverse the Y scale:

Example2: Demo Fiddle

body{
    -webkit-transform: scaleY(-1);
    transform: scaleY(-1);
}
div{
    -webkit-transform: scaleY(-1);
    transform: scaleY(-1);
}

How to view an HTML file in the browser with Visual Studio Code

@InvisibleDev - to get this working on a mac trying using this:

{
    "version": "0.1.0",
    "command": "Chrome",
    "osx": {
        "command": "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
    },
    "args": [
        "${file}"
    ]
}

If you have chrome already open, it will launch your html file in a new tab.

How to download/checkout a project from Google Code in Windows?

If you have a github account and don't want to download software, you can export to github, then download a zip from github.

How to add New Column with Value to the Existing DataTable?

//Data Table

 protected DataTable tblDynamic
        {
            get
            {
                return (DataTable)ViewState["tblDynamic"];
            }
            set
            {
                ViewState["tblDynamic"] = value;
            }
        }
//DynamicReport_GetUserType() function for getting data from DB


System.Data.DataSet ds = manage.DynamicReport_GetUserType();
                tblDynamic = ds.Tables[13];

//Add Column as "TypeName"

                tblDynamic.Columns.Add(new DataColumn("TypeName", typeof(string)));

//fill column data against ds.Tables[13]


                for (int i = 0; i < tblDynamic.Rows.Count; i++)
                {

                    if (tblDynamic.Rows[i]["Type"].ToString()=="A")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Apple";
                    }
                    if (tblDynamic.Rows[i]["Type"].ToString() == "B")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Ball";
                    }
                    if (tblDynamic.Rows[i]["Type"].ToString() == "C")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Cat";
                    }
                    if (tblDynamic.Rows[i]["Type"].ToString() == "D")
                    {
                        tblDynamic.Rows[i]["TypeName"] = "Dog;
                    }
                }

Create instance of generic type in Java?

If you want not to type class name twice during instantiation like in:

new SomeContainer<SomeType>(SomeType.class);

You can use factory method:

<E> SomeContainer<E> createContainer(Class<E> class); 

Like in:

public class Container<E> {

    public static <E> Container<E> create(Class<E> c) {
        return new Container<E>(c);
    }

    Class<E> c;

    public Container(Class<E> c) {
        super();
        this.c = c;
    }

    public E createInstance()
            throws InstantiationException,
            IllegalAccessException {
        return c.newInstance();
    }

}

How to add SHA-1 to android application

Alternatively you can use command line to get your SHA-1 fingerprint:

for your debug certificate you should use:

keytool -list -v -keystore C:\Users\user\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android

you should change "c:\Users\user" with the path to your windows user directory

if you want to get the production SHA-1 for your own certificate, replace "C:\Users\user\.android\debug.keystore" with your custom KeyStore path and use your KeystorePass and Keypass instead of android/android.

Than declare the SHA-1 fingerprints you get to your firebase console as Damini said

React-router v4 this.props.history.push(...) not working

You need to bind handleCustomerClick:

class Customers extends Component {
  constructor() {
    super();
    this.handleCustomerClick = this.handleCustomerClick(this)
  }

Base table or view not found: 1146 Table Laravel 5

Check your migration file, maybe you are using Schema::table, like this:

Schema::table('table_name', function ($table)  {
    // ...
});

If you want to create a new table you must use Schema::create:

Schema::create('table_name', function ($table)  {
    // ...
});

New Line Issue when copying data from SQL Server 2012 to Excel

In order to be able to copy and paste results from SQL Server Management Studio 2012 to Excel or to export to Csv with list separators you must first change the query option.

  1. Click on Query then options.

  2. Under Results click on the Grid.

  3. Check the box next to:

    Quote strings containing list separators when saving .csv results.

This should solve the problem.

How do I iterate over the words of a string?

I have just written a fine example of how to split a char by symbol, which then places each array of chars (words seperated by your symbol) into a vector. For simplicity i made the vector type of std string.

I hope this helps and is readable to you.

#include <vector>
#include <string>
#include <iostream>

void push(std::vector<std::string> &WORDS, std::string &TMP){
    WORDS.push_back(TMP);
    TMP = "";
}
std::vector<std::string> mySplit(char STRING[]){
        std::vector<std::string> words;
        std::string s;
        for(unsigned short i = 0; i < strlen(STRING); i++){
            if(STRING[i] != ' '){
                s += STRING[i];
            }else{
                push(words, s);
            }
        }
        push(words, s);//Used to get last split
        return words;
}

int main(){
    char string[] = "My awesome string.";
    std::cout << mySplit(string)[2];
    std::cin.get();
    return 0;
}

How to truncate milliseconds off of a .NET DateTime

To round down to the second:

dateTime.AddTicks(-dateTime.Ticks % TimeSpan.TicksPerSecond)

Replace with TicksPerMinute to round down to the minute.


If your code is performance sensitive, be cautious about

new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second)

My app was spending 12% of CPU time in System.DateTime.GetDatePart.

Convert DataTable to IEnumerable<T>

There's also a DataSetExtension method called "AsEnumerable()" (in System.Data) that takes a DataTable and returns an Enumerable. See the MSDN doc for more details, but it's basically as easy as:

dataTable.AsEnumerable()

The downside is that it's enumerating DataRow, not your custom class. A "Select()" LINQ call could convert the row data, however:

private IEnumerable<TankReading> ConvertToTankReadings(DataTable dataTable)
{
    return dataTable.AsEnumerable().Select(row => new TankReading      
            {      
                TankReadingsID = Convert.ToInt32(row["TRReadingsID"]),      
                TankID = Convert.ToInt32(row["TankID"]),      
                ReadingDateTime = Convert.ToDateTime(row["ReadingDateTime"]),      
                ReadingFeet = Convert.ToInt32(row["ReadingFeet"]),      
                ReadingInches = Convert.ToInt32(row["ReadingInches"]),      
                MaterialNumber = row["MaterialNumber"].ToString(),      
                EnteredBy = row["EnteredBy"].ToString(),      
                ReadingPounds = Convert.ToDecimal(row["ReadingPounds"]),      
                MaterialID = Convert.ToInt32(row["MaterialID"]),      
                Submitted = Convert.ToBoolean(row["Submitted"]),      
            });
}

How can I fetch all items from a DynamoDB table without specifying the primary key?

Hi you can download using boto3. In python

import boto3
from boto3.dynamodb.conditions import Key, Attr

dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('Table')
response = table.scan()
items = response['Items']
while 'LastEvaluatedKey' in response:
    print(response['LastEvaluatedKey'])
    response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
    items.extend(response['Items'])

What's the difference between Invoke() and BeginInvoke()

Delegate.BeginInvoke() asynchronously queues the call of a delegate and returns control immediately. When using Delegate.BeginInvoke(), you should call Delegate.EndInvoke() in the callback method to get the results.

Delegate.Invoke() synchronously calls the delegate in the same thread.

MSDN Article

How to set div width using ng-style

ngStyle accepts a map:

$scope.myStyle = {
    "width" : "900px",
    "background" : "red"
};

Fiddle

How to increase Maximum Upload size in cPanel?

Login to your WHM panel if you have access to

Then go to Software -> MultiPHP INI Editor

Then select the php version from the dropdown, then scroll down for the upload_max_filesize which will be 2M by default, now increase it according to your need.

Also enable the file_uploads for HTTP file uploads for convenience.

If you don't have access to WHM, then follow the .htaccess method.

Bash: infinite sleep (infinite blocking)

This approach will not consume any resources for keeping process alive.

while :; do sleep 1; done & kill -STOP $! && wait $!

Breakdown

  • while :; do sleep 1; done & Creates a dummy process in background
  • kill -STOP $! Stops the background process
  • wait $! Wait for the background process, this will be blocking forever, cause background process was stopped before

How could I convert data from string to long in c#

You won't be able to convert it directly to long because of the decimal point i think you should convert it into decimal and then convert it into long something like this:

String strValue[i] = "1100.25";
long l1 = Convert.ToInt64(Convert.ToDecimal(strValue));

hope this helps!

Fastest Convert from Collection to List<T>

As long as ManagementObjectCollection implements IEnumerable<ManagementObject> you can do:

List<ManagementObject> managementList = new List<ManagementObjec>(managementObjects);

If it doesn't, then you are stuck doing it the way that you are doing it.

Adding Text to DataGridView Row Header

I had the same(?) problem. Couldn't get header column to display row header data (a simple row number) with my data bound grid. Once I moved the code to the event "DataBindingComplete" it worked.

Sorry for the extra code. I wanted to provide a working example but don't have time to cut it all down so just cut and pasted some of my app and fixed it up to run for you. Here you go:

using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        private List<DataPoint> pts = new List<DataPoint>();

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            InsertPoint(10, 20);
            InsertPoint(12, 40);
            InsertPoint(16, 60);
            InsertPoint(20, 77);
            InsertPoint(92, 80);

            MakeGrid();
        }

        public void InsertPoint(int parameterValue, int commandValue)
        {
            DataPoint pt = new DataPoint();
            pt.XValue = commandValue;
            pt.YValues[0] = parameterValue;
            pts.Add(pt);
        }

        private void MakeGrid()
        {
            dgv1.SuspendLayout();
            DataTable dt = new DataTable();
            dt.Columns.Clear();
            dt.Columns.Add("Parameter");
            dt.Columns.Add("Command");

            //*** Add Data to DataTable
            for (int i = 0; i <= pts.Count - 1; i++)
            {
                dt.Rows.Add(pts[i].XValue, pts[i].YValues[0]);
            }
            dgv1.DataSource = dt;

            //*** Formatting for the grid is performed in event dgv1_DataBindingComplete.
            //*** If its performed here, the changes appear to get wiped in the grid control.
        }

        private void dgv1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            DataGridViewCellStyle style = new DataGridViewCellStyle();
            style.Alignment = DataGridViewContentAlignment.MiddleRight;

            //*** Add row number to each row
            foreach (DataGridViewRow row in dgv1.Rows)
            {
                row.HeaderCell.Value = (row.Index + 1).ToString();
                row.HeaderCell.Style = style;
                row.Resizable = DataGridViewTriState.False;
            }
            dgv1.ClearSelection();
            dgv1.CurrentCell = null;
            dgv1.ResumeLayout();
        }
    }
}

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

Apparently this is by design. When Safari (OS X or iOS) is in private browsing mode, it appears as though localStorage is available, but trying to call setItem throws an exception.

store.js line 73
"QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

What happens is that the window object still exposes localStorage in the global namespace, but when you call setItem, this exception is thrown. Any calls to removeItem are ignored.

I believe the simplest fix (although I haven't tested this cross browser yet) would be to alter the function isLocalStorageNameSupported() to test that you can also set some value.

https://github.com/marcuswestin/store.js/issues/42

function isLocalStorageNameSupported() 
{
    var testKey = 'test', storage = window.sessionStorage;
    try 
    {
        storage.setItem(testKey, '1');
        storage.removeItem(testKey);
        return localStorageName in win && win[localStorageName];
    } 
    catch (error) 
    {
        return false;
    }
}

finding multiples of a number in Python

Based on mathematical concepts, I understand that:

  • all natural numbers that, divided by n, having 0 as remainder, are all multiples of n

Therefore, the following calculation also applies as a solution (multiples between 1 and 100):

>>> multiples_5 = [n for n in range(1, 101) if n % 5 == 0]
>>> multiples_5
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]

For further reading:

Merging two images with PHP

The GD Image Manipulation Library in PHP is probably the best for working with images in PHP. Try one of the imagecopy functions (imagecopy, imagecopymerge, ...). Each of them combine 2 images in different ways. See the php documentation on imagecopy for more information.

What is the best way to programmatically detect porn images?

There is software that detects the probability for porn, but this is not an exact science, as computers can't recognize what is actually on pictures (pictures are only a big set of values on a grid with no meaning). You can just teach the computer what is porn and what not by giving examples. This has the disadvantage that it will only recognize these or similar images.

Given the repetitive nature of porn you have a good chance if you train the system with few false positives. For example if you train the system with nude people it may flag pictures of a beach with "almost" naked people as porn too.

A similar software is the facebook software that recently came out. It's just specialized on faces. The main principle is the same.

Technically you would implement some kind of feature detector that utilizes a bayes filtering. The feature detector may look for features like percentage of flesh colored pixels if it's a simple detector or just computes the similarity of the current image with a set of saved porn images.

This is of course not limited to porn, it's actually more a corner case. I think more common are systems that try to find other things in images ;-)

const char* concatenation

If you are using C++, why don't you use std::string instead of C-style strings?

std::string one="Hello";
std::string two="World";

std::string three= one+two;

If you need to pass this string to a C-function, simply pass three.c_str()

java: HashMap<String, int> not working

You can't use primitive types as generic arguments in Java. Use instead:

Map<String, Integer> myMap = new HashMap<String, Integer>();

With auto-boxing/unboxing there is little difference in the code. Auto-boxing means you can write:

myMap.put("foo", 3);

instead of:

myMap.put("foo", new Integer(3));

Auto-boxing means the first version is implicitly converted to the second. Auto-unboxing means you can write:

int i = myMap.get("foo");

instead of:

int i = myMap.get("foo").intValue();

The implicit call to intValue() means if the key isn't found it will generate a NullPointerException, for example:

int i = myMap.get("bar"); // NullPointerException

The reason is type erasure. Unlike, say, in C# generic types aren't retained at runtime. They are just "syntactic sugar" for explicit casting to save you doing this:

Integer i = (Integer)myMap.get("foo");

To give you an example, this code is perfectly legal:

Map<String, Integer> myMap = new HashMap<String, Integer>();
Map<Integer, String> map2 = (Map<Integer, String>)myMap;
map2.put(3, "foo");

How to disable CSS in Browser for testing purposes

Firefox (Win and Mac)

  • Via the menu toolbar, choose: "View" > "Page Style" > "No Style"
  • Via the Web Developer Toolbar, choose: "CSS" > "Disable Styles" > "All Styles"

If the Web Dev Toolbar is installed, people can use this keyboard shortcuts: Command + Shift + S (Mac) and Control + Shift + S (Win)

  • Safari (Mac): Via the menu toolbar, choose "Develop" > "Disable Styles"
  • Opera (Win): Via the menu, choose "Page" > "Style" > "User Mode"
  • Chrome (Win): Via the gear icon, choose the "CSS" tab > "Disable All Styles"
  • Internet Explorer 8: Via the menu toolbar, choose "View" > "Style" > "No Style"
  • Internet Explorer 7: via the IE Developer Toolbar menu: Disable > All CSS
  • Internet Explorer 6: Via the Web Accessibility Toolbar, choose "CSS" > "Disable CSS"

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

MongoDB has a simple web based administrative port at 28017 by default.

There is no HTTP access at the default port of 27017 (which is what the error message is trying to suggest). The default port is used for native driver access, not HTTP traffic.

To access MongoDB, you'll need to use a driver like the MongoDB native driver for NodeJS. You won't "POST" to MongoDB directly (but you might create a RESTful API using express which uses the native drivers). Instead, you'll use a wrapper library that makes accessing MongoDB convenient. You might also consider using Mongoose (which uses the native driver) which adds an ORM-like model for MongoDB in NodeJS.

If you can't get to the web interface, it may be disabled. Normally, I wouldn't expect that you'd need it for doing development unless you're checking logs and such.

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

Here's how you can do it with Markdown:

![Image of Yaktocat](https://octodex.github.com/images/yaktocat.png)

download csv file from web api in angular js

Try it like :

File.save(csvInput, function (content) {
    var hiddenElement = document.createElement('a');

    hiddenElement.href = 'data:attachment/csv,' + encodeURI(content);
    hiddenElement.target = '_blank';
    hiddenElement.download = 'myFile.csv';
    hiddenElement.click();
});

based on the most excellent answer in this question

How to add an UIViewController's view as subview

Thanks to this guys I did it http://highoncoding.com/Articles/848_Creating_iPad_Dashboard_Using_UIViewController_Containment.aspx

Add UIView, connect it to header:

@property (weak, nonatomic) IBOutlet UIView *addViewToAddPlot;

In - (void)viewDidLoad do this:

ViewControllerToAdd *nonSystemsController = [[ViewControllerToAdd alloc] initWithNibName:@"ViewControllerToAdd" bundle:nil];
    nonSystemsController.view.frame = self.addViewToAddPlot.bounds;
    [self.addViewToAddPlot addSubview:nonSystemsController.view];
    [self addChildViewController:nonSystemsController];
    [nonSystemsController didMoveToParentViewController:self];

Enjoy

Eclipse EGit Checkout conflict with files: - EGit doesn't want to continue

  1. After closing the Conflict Error Dialog; from the Project Explorer, right click on the head of the project -> Team -> Stashes -> Stash Changes
  2. Enter a name for your stash. E.G. "Conflict"
  3. Try Pulling again. Hopefully there are no errors this time.
  4. From the Git Repository view, expand your repository -> Stashed Commits
  5. Right Click on the stash you created in step 2 -> Apply Stashed Changes
  6. This brings up the merge tool if it can't automatically merge it.
  7. Manually resolve the merge conflicts in the file/s.
  8. Right Click on the file editor -> Team -> Add To Index
  9. If you are not ready to commit the file or just don't want it in the Index, right click on the file editor -> Team -> Remove from Index.
  10. Cleanup: From the Git Repository view, right Click on the stash you created in step 2 -> Delete Stashed Commit

Your local working directory file should be be merged

Why doesn't Git ignore my specified file?

Another possible reasona few instances of git clients running at the same time. For example "git shell" + "GitHub Desktop", etc.


This happened to me, I was using "GitHub Desktop" as the main client and it was ignoring some new .gitignore settings: commit after commit:

  1. You commit something.
  2. Next, commit: it ignores .gitignore settings. Commit includes lots of temp files mentioned in the .gitignore.
  3. Clear git cache; check whether .gitignore is UTF8; remove files -> commit -> move files back; skip 1 commit – nothing helped.

Reason: the Visual Studio Code editor was running in the background with the same opened repository. VS Code has built-in git control, and this makes some conflicts.

Solution: double-check multiple, hidden git clients and use only one git client at once, especially while clearing git cache.

How to load a jar file at runtime

I googled a bit, and found this code here:

File file = getJarFileToLoadFrom();   
String lcStr = getNameOfClassToLoad();   
URL jarfile = new URL("jar", "","file:" + file.getAbsolutePath()+"!/");    
URLClassLoader cl = URLClassLoader.newInstance(new URL[] {jarfile });   
Class loadedClass = cl.loadClass(lcStr);   

Can anyone share opinions/comments/answers regarding this approach?

Where is the Keytool application?

keytool is a tool to manage (public/private) security keys and certificates and store them in a Java KeyStore file (stored_file_name.jks).
It is provided with any standard JDK/JRE distributions.
You can find it under the following folder %JAVA_HOME%\bin.

changing source on html5 video tag

Using JavaScript and jQuery:

<script src="js/jquery.js"></script>
...
<video id="vid" width="1280" height="720" src="v/myvideo01.mp4" controls autoplay></video>
...
function chVid(vid) {
    $("#vid").attr("src",vid);
}
...
<div onclick="chVid('v/myvideo02.mp4')">See my video #2!</div>

Converting XML to JSON using Python?

My answer addresses the specific (and somewhat common) case where you don't really need to convert the entire xml to json, but what you need is to traverse/access specific parts of the xml, and you need it to be fast, and simple (using json/dict-like operations).

Approach

For this, it is important to note that parsing an xml to etree using lxml is super fast. The slow part in most of the other answers is the second pass: traversing the etree structure (usually in python-land), converting it to json.

Which leads me to the approach I found best for this case: parsing the xml using lxml, and then wrapping the etree nodes (lazily), providing them with a dict-like interface.

Code

Here's the code:

from collections import Mapping
import lxml.etree

class ETreeDictWrapper(Mapping):

    def __init__(self, elem, attr_prefix = '@', list_tags = ()):
        self.elem = elem
        self.attr_prefix = attr_prefix
        self.list_tags = list_tags

    def _wrap(self, e):
        if isinstance(e, basestring):
            return e
        if len(e) == 0 and len(e.attrib) == 0:
            return e.text
        return type(self)(
            e,
            attr_prefix = self.attr_prefix,
            list_tags = self.list_tags,
        )

    def __getitem__(self, key):
        if key.startswith(self.attr_prefix):
            return self.elem.attrib[key[len(self.attr_prefix):]]
        else:
            subelems = [ e for e in self.elem.iterchildren() if e.tag == key ]
            if len(subelems) > 1 or key in self.list_tags:
                return [ self._wrap(x) for x in subelems ]
            elif len(subelems) == 1:
                return self._wrap(subelems[0])
            else:
                raise KeyError(key)

    def __iter__(self):
        return iter(set( k.tag for k in self.elem) |
                    set( self.attr_prefix + k for k in self.elem.attrib ))

    def __len__(self):
        return len(self.elem) + len(self.elem.attrib)

    # defining __contains__ is not necessary, but improves speed
    def __contains__(self, key):
        if key.startswith(self.attr_prefix):
            return key[len(self.attr_prefix):] in self.elem.attrib
        else:
            return any( e.tag == key for e in self.elem.iterchildren() )


def xml_to_dictlike(xmlstr, attr_prefix = '@', list_tags = ()):
    t = lxml.etree.fromstring(xmlstr)
    return ETreeDictWrapper(
        t,
        attr_prefix = '@',
        list_tags = set(list_tags),
    )

This implementation is not complete, e.g., it doesn't cleanly support cases where an element has both text and attributes, or both text and children (only because I didn't need it when I wrote it...) It should be easy to improve it, though.

Speed

In my specific use case, where I needed to only process specific elements of the xml, this approach gave a suprising and striking speedup by a factor of 70 (!) compared to using @Martin Blech's xmltodict and then traversing the dict directly.

Bonus

As a bonus, since our structure is already dict-like, we get another alternative implementation of xml2json for free. We just need to pass our dict-like structure to json.dumps. Something like:

def xml_to_json(xmlstr, **kwargs):
    x = xml_to_dictlike(xmlstr, **kwargs)
    return json.dumps(x)

If your xml includes attributes, you'd need to use some alphanumeric attr_prefix (e.g. "ATTR_"), to ensure the keys are valid json keys.

I haven't benchmarked this part.

How do I enumerate the properties of a JavaScript object?

Python's dict has 'keys' method, and that is really useful. I think in JavaScript we can have something this:

function keys(){
    var k = [];
    for(var p in this) {
        if(this.hasOwnProperty(p))
            k.push(p);
    }
    return k;
}
Object.defineProperty(Object.prototype, "keys", { value : keys, enumerable:false });

EDIT: But the answer of @carlos-ruana works very well. I tested Object.keys(window), and the result is what I expected.

EDIT after 5 years: it is not good idea to extend Object, because it can conflict with other libraries that may want to use keys on their objects and it will lead unpredictable behavior on your project. @carlos-ruana answer is the correct way to get keys of an object.

Could not resolve com.android.support:appcompat-v7:26.1.0 in Android Studio new project

Your android studio may be forgot to put : buildToolsVersion "26.0.0" you need 'buildTools' to develop related design and java file. And if there is no any buildTools are installed in Android->sdk->build-tools directory then download first.

ipad safari: disable scrolling, and bounce effect?

Solution tested, works on iOS 12.x

This is problem I was encountering :

<body> <!-- the whole body can be scroll vertically -->
  <article>

    <my_gallery> <!-- some picture gallery, can be scroll horizontally -->
    </my_gallery>

  </article>
</body>

While I scrolling my gallery, the body always scrolling itself (human swipe aren't really horizontal), that makes my gallery useless.

Here's what I did while my gallery start scrolling

var html=jQuery('html');
html.css('overflow-y', 'hidden');
//above code works on mobile Chrome/Edge/Firefox
document.ontouchmove=function(e){e.preventDefault();} //Add this only for mobile Safari

And when my gallery end its scrolling...

var html=jQuery('html');
html.css('overflow-y', 'scroll');
document.ontouchmove=function(e){return true;}

Hope this helps~

Best way to do multiple constructors in PHP

For php7, I compare parameters type as well, you can have two constructors with same number of parameters but different type.

trait GenericConstructorOverloadTrait
{
    /**
     * @var array Constructors metadata
     */
    private static $constructorsCache;
    /**
     * Generic constructor
     * GenericConstructorOverloadTrait constructor.
     */
    public function __construct()
    {
        $params = func_get_args();
        $numParams = func_num_args();

        $finish = false;

        if(!self::$constructorsCache){
            $class = new \ReflectionClass($this);
            $constructors =  array_filter($class->getMethods(),
                function (\ReflectionMethod $method) {
                return preg_match("/\_\_construct[0-9]+/",$method->getName());
            });
            self::$constructorsCache = $constructors;
        }
        else{
            $constructors = self::$constructorsCache;
        }
        foreach($constructors as $constructor){
            $reflectionParams = $constructor->getParameters();
            if(count($reflectionParams) != $numParams){
                continue;
            }
            $matched = true;
            for($i=0; $i< $numParams; $i++){
                if($reflectionParams[$i]->hasType()){
                    $type = $reflectionParams[$i]->getType()->__toString();
                }
                if(
                    !(
                        !$reflectionParams[$i]->hasType() ||
                        ($reflectionParams[$i]->hasType() &&
                            is_object($params[$i]) &&
                            $params[$i] instanceof $type) ||
                        ($reflectionParams[$i]->hasType() &&
                            $reflectionParams[$i]->getType()->__toString() ==
                            gettype($params[$i]))
                    )
                ) {
                    $matched = false;
                    break;
                }

            }

            if($matched){
                call_user_func_array(array($this,$constructor->getName()),
                    $params);
                $finish = true;
                break;
            }
        }

        unset($constructor);

        if(!$finish){
            throw new \InvalidArgumentException("Cannot match construct by params");
        }
    }

}

To use it:

class MultiConstructorClass{

    use GenericConstructorOverloadTrait;

    private $param1;

    private $param2;

    private $param3;

    public function __construct1($param1, array $param2)
    {
        $this->param1 = $param1;
        $this->param2 = $param2;
    }

    public function __construct2($param1, array $param2, \DateTime $param3)
    {
        $this->__construct1($param1, $param2);
        $this->param3 = $param3;
    }

    /**
     * @return \DateTime
     */
    public function getParam3()
    {
        return $this->param3;
    }

    /**
     * @return array
     */
    public function getParam2()
    {
        return $this->param2;
    }

    /**
     * @return mixed
     */
    public function getParam1()
    {
        return $this->param1;
    }
}

How to check version of a CocoaPods framework

You can figure out version of Cocoapods by using below command :

pod —-version

o/p : 1.2.1

Now if you want detailed version of Gems and Cocoapods then use below command :

gem which cocoapods (without sudo)

o/p : /Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.1/lib/cocoapods.rb

sudo gem which cocoapods (with sudo)

o/p : /Library/Ruby/Gems/2.0.0/gems/cocoapods-1.2.1/lib/cocoapods.rb

Screenshot 1

Now if you want to get specific version of Pod present in Podfile then simply use command pod install in terminal. This will show list of pod being used in project along with version.

Screenshot 2

Jquery checking success of ajax post

The documentation is here: http://docs.jquery.com/Ajax/jQuery.ajax

But, to summarize, the ajax call takes a bunch of options. the ones you are looking for are error and success.

You would call it like this:

$.ajax({
  url: 'mypage.html',
  success: function(){
    alert('success');
  },
  error: function(){
    alert('failure');
  }
});

I have shown the success and error function taking no arguments, but they can receive arguments.

The error function can take three arguments: XMLHttpRequest, textStatus, and errorThrown.

The success function can take two arguments: data and textStatus. The page you requested will be in the data argument.

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

Oracle will try to recompile invalid objects as they are referred to. Here the trigger is invalid, and every time you try to insert a row it will try to recompile the trigger, and fail, which leads to the ORA-04098 error.

You can select * from user_errors where type = 'TRIGGER' and name = 'NEWALERT' to see what error(s) the trigger actually gets and why it won't compile. In this case it appears you're missing a semicolon at the end of the insert line:

INSERT INTO Users (userID, firstName, lastName, password)
VALUES ('how', 'im', 'testing', 'this trigger')

So make it:

CREATE OR REPLACE TRIGGER newAlert
AFTER INSERT OR UPDATE ON Alerts
  BEGIN
        INSERT INTO Users (userID, firstName, lastName, password)
        VALUES ('how', 'im', 'testing', 'this trigger');
  END;           
/

If you get a compilation warning when you do that you can do show errors if you're in SQL*Plus or SQL Developer, or query user_errors again.

Of course, this assumes your Users tables does have those column names, and they are all varchar2... but presumably you'll be doing something more interesting with the trigger really.

Trim specific character from a string

to keep this question up to date:

here is an approach i'd choose over the regex function using the ES6 spread operator.

function trimByChar(string, character) {
  const first = [...string].findIndex(char => char !== character);
  const last = [...string].reverse().findIndex(char => char !== character);
  return string.substring(first, string.length - last);
}

Improved version after @fabian 's comment (can handle strings containing the same character only)

_x000D_
_x000D_
function trimByChar1(string, character) {
  const arr = Array.from(string);
  const first = arr.findIndex(char => char !== character);
  const last = arr.reverse().findIndex(char => char !== character);
  return (first === -1 && last === -1) ? '' : string.substring(first, string.length - last);
}
_x000D_
_x000D_
_x000D_

Cast a Double Variable to Decimal

Well this is an old question and I indeed made use of some of the answers shown here. Nevertheless, in my particular scenario it was possible that the double value that I wanted to convert to decimal was often bigger than decimal.MaxValue. So, instead of handling exceptions I wrote this extension method:

    public static decimal ToDecimal(this double @double) => 
        @double > (double) decimal.MaxValue ? decimal.MaxValue : (decimal) @double;

The above approach works if you do not want to bother handling overflow exceptions and if such a thing happen you want just to keep the max possible value(my case), but I am aware that for many other scenarios this would not be the expected behavior and may be the exception handling will be needed.

How do I access my SSH public key?

On a Mac, you can do this to copy it to your clipboard (like cmd + c shortcut)
cat ~/Desktop/ded.html | pbcopy
pbcopy < ~/.ssh/id_rsa.pub

and to paste pbpaste > ~Documents/id_rsa.txt

or, use cmd + v shorcut to paste it somewhere else.

~/.ssh is the same path as /Users/macbook-username/.ssh
You can use Print work directory: pwd command on terminal to get the path to your current directory.

Running Selenium Webdriver with a proxy in Python

My solution:

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

Then call in your code:

my_proxy(PROXY_HOST,PROXY_PORT)

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

 PROXY_PORT="31280"

This is important:

int("31280")

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

TypeError: unsupported operand type(s) for /: 'str' and 'str'

There is another error with the forwars=d slash.

if we get this : def get_x(r): return path/'train'/r['fname']
is the same as def get_x(r): return path + 'train' + r['fname']

How to convert rdd object to dataframe in spark

Assuming your RDD[row] is called rdd, you can use:

val sqlContext = new SQLContext(sc) 
import sqlContext.implicits._
rdd.toDF()

How to fetch data from local JSON file on react native?

The following ways to fetch local JSON file-

ES6 version:

import customData from './customData.json'; or import customData from './customData';

If it's inside .js file instead of .json then import like -

import { customData } from './customData';

for more clarification/understanding refer example - Live working demo

Updating the list view when the adapter data changes

I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      // Edit object data that is represented in Viewat at list's "position"
      view = mAdapter.getView(position, view, parent);
    }
});

Stop and Start a service via batch or cmd file?

SC can do everything with services... start, stop, check, configure, and more...

How to read until EOF from cin in C++

Probable simplest and generally efficient:

#include <iostream>
int main()
{
    std::cout << std::cin.rdbuf();
}

If needed, use stream of other types like std::ostringstream as buffer instead of standard output stream here.

How can I put an icon inside a TextInput in React Native?

In case is useful I share what I find a clean solution:

<View style={styles.inputContainer}>
  <TextInput
    style={styles.input}
    onChangeText={(text) => onChange(text)}
    value={value}
  />
  <Icon style={styles.icon} name="your-icon" size={20} />
</View>

and then in your css

 inputContainer: {
    justifyContent: 'center',
  },
  input: {
    height: 50,
  },
  icon: {
    position: 'absolute',
    right: 10,
  }

Python ImportError: No module named wx

If you do not have wx installed on windows you can use :

 pip install wx

how to use sqltransaction in c#

First you don't need a transaction since you are just querying select statements and since they are both select statement you can just combine them into one query separated by space and use Dataset to get the all the tables retrieved. Its better this way since you made only one transaction to the database because database transactions are expensive hence your code is faster. Second of you really have to use a transaction, just assign the transaction to the SqlCommand like

sqlCommand.Transaction = transaction;

And also just use one SqlCommand don't declare more than one, since variables consume space and we are also on the topic of making your code more efficient, do that by assigning commandText to different query string and executing them like

sqlCommand.CommandText = "select * from table1";
sqlCommand.ExecuteNonQuery();
sqlCommand.CommandText = "select * from table2";
sqlCommand.ExecuteNonQuery();

Create a Cumulative Sum Column in MySQL

Using a correlated query:


  SELECT t.id,
         t.count,
         (SELECT SUM(x.count)
            FROM TABLE x
           WHERE x.id <= t.id) AS cumulative_sum
    FROM TABLE t
ORDER BY t.id

Using MySQL variables:


  SELECT t.id,
         t.count,
         @running_total := @running_total + t.count AS cumulative_sum
    FROM TABLE t
    JOIN (SELECT @running_total := 0) r
ORDER BY t.id

Note:

  • The JOIN (SELECT @running_total := 0) r is a cross join, and allows for variable declaration without requiring a separate SET command.
  • The table alias, r, is required by MySQL for any subquery/derived table/inline view

Caveats:

  • MySQL specific; not portable to other databases
  • The ORDER BY is important; it ensures the order matches the OP and can have larger implications for more complicated variable usage (IE: psuedo ROW_NUMBER/RANK functionality, which MySQL lacks)

Command for restarting all running docker containers?

Run this as root permission otherwise this might not work

  docker restart $(docker ps -a -q)

with root permissions

sudo docker restart $(sudo docker ps -a -q)

Typescript Type 'string' is not assignable to type

When you do this:

export type Fruit = "Orange" | "Apple" | "Banana"

...you are creating a type called Fruit that can only contain the literals "Orange", "Apple" and "Banana". This type extends String, hence it can be assigned to String. However, String does NOT extend "Orange" | "Apple" | "Banana", so it cannot be assigned to it. String is less specific. It can be any string.

When you do this:

export type Fruit = "Orange" | "Apple" | "Banana"

const myString = "Banana";

const myFruit: Fruit = myString;

...it works. Why? Because the actual type of myString in this example is "Banana". Yes, "Banana" is the type. It is extends String so it's assignable to String. Additionally, a type extends a Union Type when it extends any of its components. In this case, "Banana", the type, extends "Orange" | "Apple" | "Banana" because it extends one of its components. Hence, "Banana" is assignable to "Orange" | "Apple" | "Banana" or Fruit.

libclntsh.so.11.1: cannot open shared object file.

Cron does not load the user's profile when running a task and you have to include the profile in your shell script explicitly.

Example documentation

How to parse XML using shellscript?

There's also xmlstarlet (which is available for Windows as well).

http://xmlstar.sourceforge.net/doc/xmlstarlet.txt

Can't use SURF, SIFT in OpenCV

None of the above suggested solutions worked for me. I use Anaconda and found that opencv version 3.3.1 still had Sift enabled. If you want to test in isolated conda environment, try the following inspired from @A.Ametov's answer above

conda create -n testenv opencv=3.3.1     
conda activate testenv

conda activate myenv
python
#Check version of opencv being used
>>> import cv2
>>> cv2.__version__
#Check if Sift is available
>>> cv2.xfeatures2d.SIFT_create()
<xfeatures2d_SIFT 000002A3478655B0>

How to iterate object in JavaScript?

Here's all the options you have:

1. for...of (ES2015)

_x000D_
_x000D_
var dictionary = {_x000D_
    "data": [_x000D_
        {"id":"0","name":"ABC"},_x000D_
        {"id":"1","name":"DEF"}_x000D_
    ],_x000D_
    "images": [_x000D_
        {"id":"0","name":"PQR"},_x000D_
        {"id":"1","name":"xyz"}_x000D_
    ]_x000D_
};_x000D_
_x000D_
for (const entry of dictionary.data) {_x000D_
  console.log(JSON.stringify(entry))_x000D_
}
_x000D_
_x000D_
_x000D_

2. Array.prototype.forEach (ES5)

_x000D_
_x000D_
var dictionary = {_x000D_
    "data": [_x000D_
        {"id":"0","name":"ABC"},_x000D_
        {"id":"1","name":"DEF"}_x000D_
    ],_x000D_
    "images": [_x000D_
        {"id":"0","name":"PQR"},_x000D_
        {"id":"1","name":"xyz"}_x000D_
    ]_x000D_
};_x000D_
_x000D_
dictionary.data.forEach(function(entry) {_x000D_
  console.log(JSON.stringify(entry))_x000D_
})
_x000D_
_x000D_
_x000D_

3. for() (ES1)

_x000D_
_x000D_
var dictionary = {_x000D_
    "data": [_x000D_
        {"id":"0","name":"ABC"},_x000D_
        {"id":"1","name":"DEF"}_x000D_
    ],_x000D_
    "images": [_x000D_
        {"id":"0","name":"PQR"},_x000D_
        {"id":"1","name":"xyz"}_x000D_
    ]_x000D_
};_x000D_
_x000D_
for (let i = 0; i < dictionary.data.length; i++) {_x000D_
  console.log(JSON.stringify(dictionary.data[i]))_x000D_
}
_x000D_
_x000D_
_x000D_

Getting last month's date in php

If you want to get first date of previous month , Then you can use as like following ... $prevmonth = date('M Y 1', strtotime('-1 months')); what? first date will always be 1 :D

Why does Java have an "unreachable statement" compiler error?

It is Nanny. I feel .Net got this one right - it raises a warning for unreachable code, but not an error. It is good to be warned about it, but I see no reason to prevent compilation (especially during debugging sessions where it is nice to throw a return in to bypass some code).

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

First drop your foreign key and try your above command, put add constraint instead of modify constraint. Now this is the command:

ALTER TABLE child_table_name 
  ADD CONSTRAINT fk_name 
  FOREIGN KEY (child_column_name) 
  REFERENCES parent_table_name(parent_column_name) 
  ON DELETE CASCADE;

Get selected value in dropdown list using JavaScript

Just use

  • $('#SelectBoxId option:selected').text(); for getting the text as listed

  • $('#SelectBoxId').val(); for getting the selected index value

What are the differences between Visual Studio Code and Visual Studio?

Visual Studio (full version) is a "full-featured" and "convenient" development environment.

Visual Studio (free "Express" versions - only until 2017) are feature-centered and simplified versions of the full version. Feature-centered meaning that there are different versions (Visual Studio Web Developer, Visual Studio C#, etc.) depending on your goal.

Visual Studio (free Community edition - since 2015) is a simplified version of the full version and replaces the separated express editions used before 2015.

Visual Studio Code (VSCode) is a cross-platform (Linux, Mac OS, Windows) editor that can be extended with plugins to your needs.

For example, if you want to create an ASP.NET application using Visual Studio Code you need to perform several steps on your own to setup the project. There is a separate tutorial for each OS.

How to get height and width of device display in angular2 using typescript?

Keep in mind if you are wanting to test this component you will want to inject the window. Use the @Inject() function to inject the window object by naming it using a string token like detailed in this duplicate

how to implement Interfaces in C++?

Interface are nothing but a pure abstract class in C++. Ideally this interface class should contain only pure virtual public methods and static const data. For example:

class InterfaceA
{
public:
  static const int X = 10;

  virtual void Foo() = 0;
  virtual int Get() const = 0;
  virtual inline ~InterfaceA() = 0;
};
InterfaceA::~InterfaceA () {}

Setting network adapter metric priority in Windows 7

Windows has two different settings in which priority is established. There is the metric value which you have already set in the adapter settings, and then there is the connection priority in the network connections settings.

To change the priority of the connections:

  • Open your Adapter Settings (Control Panel\Network and Internet\Network Connections)
  • Click Alt to pull up the menu bar
  • Select Advanced -> Advanced Settings
  • Change the order of the connections so that the connection you want to have priority is top on the list

With CSS, use "..." for overflowed block of multi-lines

display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical; 

see more click here

Enabling HTTPS on express.js

This is how its working for me. The redirection used will redirect all the normal http as well.

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
var request = require('request');
//For https
const https = require('https');
var fs = require('fs');
var options = {
  key: fs.readFileSync('certificates/private.key'),
  cert: fs.readFileSync('certificates/certificate.crt'),
  ca: fs.readFileSync('certificates/ca_bundle.crt')
};

// API file for interacting with MongoDB
const api = require('./server/routes/api');

// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));

// API location
app.use('/api', api);

// Send all other requests to the Angular app
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.use(function(req,resp,next){
  if (req.headers['x-forwarded-proto'] == 'http') {
      return resp.redirect(301, 'https://' + req.headers.host + '/');
  } else {
      return next();
  }
});


http.createServer(app).listen(80)
https.createServer(options, app).listen(443);

How to create a directory in Java?

Well to create Directory/folder in java we have two methods

Here makedirectory method creates single directory if it does not exist.

File dir = new File("path name");
boolean isCreated = dir.mkdir();

And

File dir = new File("path name");
boolean isCreated = dir.mkdirs();

Here makedirectories method will create all directories that are missing in the path which the file object represent.

For example refer link below (explained very well). Hope it helps!! https://www.flowerbrackets.com/create-directory-java-program/

nuget 'packages' element is not declared warning

You can always make simple xsd schema for 'packages.config' to get rid of this warning. To do this, create file named "packages.xsd":

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
      targetNamespace="urn:packages" xmlns="urn:packages">
  <xs:element name="packages">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="package" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attribute name="id" type="xs:string" use="required" />
            <xs:attribute name="version" type="xs:string" use="required" />
            <xs:attribute name="targetFramework" type="xs:string" use="optional" />
            <xs:attribute name="allowedVersions" type="xs:string" use="optional" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Location of this file (two options)

  • In the same folder as 'packages.config' file,
  • If you want to share packages.xsd across multiple projects, move it to the Visual Studio Schemas folder (the path may slightly differ, it's D:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas for me).

Then, edit <packages> tag in packages.config file (add xmlns attribute):

<packages xmlns="urn:packages">

Now the warning should disappear (even if packages.config file is open in Visual Studio).

How to downgrade or install an older version of Cocoapods

Note that your pod specs will remain, and are located at ~/.cocoapods/ . This directory may also need to be removed if you want a completely fresh install.

They can be removed using pod spec remove SPEC_NAME then pod setup

It may help to do pod spec remove master then pod setup

Undoing accidental git stash pop

Try using How to recover a dropped stash in Git? to find the stash you popped. I think there are always two commits for a stash, since it preserves the index and the working copy (so often the index commit will be empty). Then git show them to see the diff and use patch -R to unapply them.

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

PHP: How to handle <![CDATA[ with SimpleXMLElement?

The LIBXML_NOCDATA is optional third parameter of simplexml_load_file() function. This returns the XML object with all the CDATA data converted into strings.

$xml = simplexml_load_file($this->filename, 'SimpleXMLElement', LIBXML_NOCDATA);
echo "<pre>";
print_r($xml);
echo "</pre>";


Fix CDATA in SimpleXML

What is the difference between an annotated and unannotated tag?

The big difference is perfectly explained here.

Basically, lightweight tags are just pointers to specific commits. No further information is saved; on the other hand, annotated tags are regular objects, which have an author and a date and can be referred because they have their own SHA key.

If knowing who tagged what and when is relevant for you, then use annotated tags. If you just want to tag a specific point in your development, no matter who and when did that, then lightweight tags are good enough.

Normally you'd go for annotated tags, but it is really up to the Git master of the project.

Can't change z-index with JQuery

$(this).parent().css('z-index',3000);

Regular expression to remove HTML tags from a string

You should not attempt to parse HTML with regex. HTML is not a regular language, so any regex you come up with will likely fail on some esoteric edge case. Please refer to the seminal answer to this question for specifics. While mostly formatted as a joke, it makes a very good point.


The following examples are Java, but the regex will be similar -- if not identical -- for other languages.


String target = someString.replaceAll("<[^>]*>", "");

Assuming your non-html does not contain any < or > and that your input string is correctly structured.

If you know they're a specific tag -- for example you know the text contains only <td> tags, you could do something like this:

String target = someString.replaceAll("(?i)<td[^>]*>", "");

Edit: Omega brought up a good point in a comment on another post that this would result in multiple results all being squished together if there were multiple tags.

For example, if the input string were <td>Something</td><td>Another Thing</td>, then the above would result in SomethingAnother Thing.

In a situation where multiple tags are expected, we could do something like:

String target = someString.replaceAll("(?i)<td[^>]*>", " ").replaceAll("\\s+", " ").trim();

This replaces the HTML with a single space, then collapses whitespace, and then trims any on the ends.

Explanation of the UML arrows

enter image description here

enter image description here

I think these pictures are understandable.

Is the buildSessionFactory() Configuration method deprecated in Hibernate

It's as simple as this: the JBoss docs are not 100% perfectly well-maintained. Go with what the JavaDoc says: buildSessionFactory(ServiceRegistry serviceRegistry).

How to use *ngIf else?

In Angular 4, 5 and 6

We can simply create a template reference variable [2] and link that to the else condition inside an *ngIf directive

The possible Syntaxes [1] are:

<!-- Only If condition -->
<div *ngIf="condition">...</div>
<!-- or -->
<ng-template [ngIf]="condition"><div>...</div></ng-template>


<!-- If and else conditions -->
<div *ngIf="condition; else elseBlock">...</div>
<!-- or -->
<ng-template #elseBlock>...</ng-template>

<!-- If-then-else -->
<div *ngIf="condition; then thenBlock else elseBlock"></div>
<ng-template #thenBlock>...</ng-template>
<ng-template #elseBlock>...</ng-template>


<!-- If and else conditions (storing condition value locally) -->
<div *ngIf="condition as value; else elseBlock">{{value}}</div>
<ng-template #elseBlock>...</ng-template>

DEMO: https://stackblitz.com/edit/angular-feumnt?embed=1&file=src/app/app.component.html

Sources:

  1. https://angular.io/api/common/NgIf#syntax
  2. https://angular.io/guide/template-syntax#template-reference-variables--var-

Call static method with reflection

Class that will call the methods:

namespace myNamespace
{
    public class myClass
    {
        public static void voidMethodWithoutParameters()
        {
            // code here
        }
        public static string stringReturnMethodWithParameters(string param1, string param2)
        {
            // code here
            return "output";
        }
    }
}

Calling myClass static methods using Reflection:

var myClassType = Assembly.GetExecutingAssembly().GetType(GetType().Namespace + ".myClass");
                    
// calling my void Method that has no parameters.
myClassType.GetMethod("voidMethodWithoutParameters", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);

// calling my string returning Method & passing to it two string parameters.
Object methodOutput = myClassType.GetMethod("stringReturnMethodWithParameters", BindingFlags.Public | BindingFlags.Static).Invoke(null, new object[] { "value1", "value1" });
Console.WriteLine(methodOutput.ToString());

Note: I don't need to instantiate an object of myClass to use it's methods, as the methods I'm using are static.

Great resources:

Figure out size of UILabel based on String in Swift

extension String{

    func widthWithConstrainedHeight(_ height: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: CGFloat.greatestFiniteMagnitude, height: height)

        let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

        return ceil(boundingBox.width)
    }

    func heightWithConstrainedWidth(_ width: CGFloat, font: UIFont) -> CGFloat? {
        let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

        return ceil(boundingBox.height)
    }

}

How to read a configuration file in Java

Create a configuration file and put your entries there.

SERVER_PORT=10000     
THREAD_POOL_COUNT=3     
ROOT_DIR=/home/   

You can load this file using Properties.load(fileName) and retrieved values you get(key);

Maven and adding JARs to system scope

mvn install:install-file -DgroupId=com.paic.maven -DartifactId=tplconfig-maven-plugin -Dversion=1.0 -Dpackaging=jar -Dfile=tplconfig-maven-plugin-1.0.jar -DgeneratePom=true

Install the jar to local repository.

Why isn't my Pandas 'apply' function referencing multiple columns working?

If you just want to compute (column a) % (column b), you don't need apply, just do it directly:

In [7]: df['a'] % df['c']                                                                                                                                                        
Out[7]: 
0   -1.132022                                                                                                                                                                    
1   -0.939493                                                                                                                                                                    
2    0.201931                                                                                                                                                                    
3    0.511374                                                                                                                                                                    
4   -0.694647                                                                                                                                                                    
5   -0.023486                                                                                                                                                                    
Name: a

XCOPY: Overwrite all without prompt in BATCH

The solution is the /Y switch:

xcopy "C:\Users\ADMIN\Desktop\*.*" "D:\Backup\" /K /D /H /Y

What exactly does += do in python?

Remember when you used to sum, for example 2 & 3, in your old calculator and every time you hit the = you see 3 added to the total, the += does similar job. Example:

>>> orange = 2
>>> orange += 3
>>> print(orange)
5
>>> orange +=3
>>> print(orange)
8

Stack smashing detected

Stack Smashing here is actually caused due to a protection mechanism used by gcc to detect buffer overflow errors. For example in the following snippet:

#include <stdio.h>

void func()
{
    char array[10];
    gets(array);
}

int main(int argc, char **argv)
{
    func();
}

The compiler, (in this case gcc) adds protection variables (called canaries) which have known values. An input string of size greater than 10 causes corruption of this variable resulting in SIGABRT to terminate the program.

To get some insight, you can try disabling this protection of gcc using option -fno-stack-protector while compiling. In that case you will get a different error, most likely a segmentation fault as you are trying to access an illegal memory location. Note that -fstack-protector should always be turned on for release builds as it is a security feature.

You can get some information about the point of overflow by running the program with a debugger. Valgrind doesn't work well with stack-related errors, but like a debugger, it may help you pin-point the location and reason for the crash.

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

VBA using ubound on a multidimensional array

In addition to the already excellent answers, also consider this function to retrieve both the number of dimensions and their bounds, which is similar to John's answer, but works and looks a little differently:

Function sizeOfArray(arr As Variant) As String
    Dim str As String
    Dim numDim As Integer

    numDim = NumberOfArrayDimensions(arr)
    str = "Array"

    For i = 1 To numDim
        str = str & "(" & LBound(arr, i) & " To " & UBound(arr, i)
        If Not i = numDim Then
            str = str & ", "
        Else
            str = str & ")"
        End If
    Next i

    sizeOfArray = str
End Function


Private Function NumberOfArrayDimensions(arr As Variant) As Integer
' By Chip Pearson
' http://www.cpearson.com/excel/vbaarrays.htm
Dim Ndx As Integer
Dim Res As Integer
On Error Resume Next
' Loop, increasing the dimension index Ndx, until an error occurs.
' An error will occur when Ndx exceeds the number of dimension
' in the array. Return Ndx - 1.
    Do
        Ndx = Ndx + 1
        Res = UBound(arr, Ndx)
    Loop Until Err.Number <> 0
NumberOfArrayDimensions = Ndx - 1
End Function

Example usage:

Sub arrSizeTester()
    Dim arr(1 To 2, 3 To 22, 2 To 9, 12 To 18) As Variant
    Debug.Print sizeOfArray(arr())
End Sub

And its output:

Array(1 To 2, 3 To 22, 2 To 9, 12 To 18)

Serving static web resources in Spring Boot & Spring Security application

If you are using webjars. You need to add this in your configure method: http.authorizeRequests().antMatchers("/webjars/**").permitAll();

Make sure this is the first statement. For example:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/webjars/**").permitAll();
        http.authorizeRequests().anyRequest().authenticated();
         http.formLogin()
         .loginPage("/login")
         .failureUrl("/login?error")
         .usernameParameter("email")
         .permitAll()
         .and()
         .logout()
         .logoutUrl("/logout")
         .deleteCookies("remember-me")
         .logoutSuccessUrl("/")
         .permitAll()
         .and()
         .rememberMe();
    }

You will also need to have this in order to have webjars enabled:

@Configuration
    public class MvcConfig extends WebMvcConfigurerAdapter {
        ...
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
        ...
    }

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

The error message says what You should do.

// TEXTVIEW
if(tv.getParent() != null) {
    ((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}
layout.addView(tv); //  <==========  ERROR IN THIS LINE DURING 2ND RUN
// EDITTEXT

How to check if a character is upper-case in Python?

Use list(str) to break into chars then import string and use string.ascii_uppercase to compare against.

Check the string module: http://docs.python.org/library/string.html

How to monitor network calls made from iOS Simulator

A man-in-the-middle proxy, like suggested by other answers, is a good solution if you only want to see HTTP/HTTPS traffic. Burp Suite is pretty good. It may be a pain to configure though. I'm not sure how you would convince the simulator to talk to it. You might have to set the proxy on your local Mac to your instance of a proxy server in order for it to intercept, since the simulator will make use of your local Mac's environment.

The best solution for packet sniffing (though it only works for actual iOS devices, not the simulator) I've found is to use rvictl. This blog post has a nice writeup. Basically you do:

rvictl -s <iphone-uid-from-xcode-organizer>

Then you sniff the interface it creates with with Wireshark (or your favorite tool), and when you're done shut down the interface with:

rvictl -x <iphone-uid-from-xcode-organizer>

This is nice because if you want to packet sniff the simulator, you're having to wade through traffic to your local Mac as well, but rvictl creates a virtual interface that just shows you the traffic from the iOS device you've plugged into your USB port.

Get values from a listbox on a sheet

Take selected value:

worksheet name = ordls
form control list box name = DEPDB1

selectvalue = ordls.Shapes("DEPDB1").ControlFormat.List(ordls.Shapes("DEPDB1").ControlFormat.Value)

get the value of DisplayName attribute

var propInfo = typeof(Class1).GetProperty("Name");
var displayNameAttribute = propInfo.GetCustomAttributes(typeof(DisplayNameAttribute), false);
var displayName = (displayNameAttribute[0] as DisplayNameAttribute).DisplayName;

displayName variable now holds the property's value.

How to style CSS role

please use :

 #content[role=main]{
   your style here
}

Build tree array from flat array in javascript

This is an old thread but I figured an update never hurts, with ES6 you can do:

_x000D_
_x000D_
const data = [{
    id: 1,
    parent_id: 0
}, {
    id: 2,
    parent_id: 1
}, {
    id: 3,
    parent_id: 1
}, {
    id: 4,
    parent_id: 2
}, {
    id: 5,
    parent_id: 4
}, {
    id: 8,
    parent_id: 7
}, {
    id: 9,
    parent_id: 8
}, {
    id: 10,
    parent_id: 9
}];

const arrayToTree = (items=[], id = null, link = 'parent_id') => items.filter(item => id==null ? !items.some(ele=>ele.id===item[link]) : item[link] === id ).map(item => ({ ...item, children: arrayToTree(items, item.id) }))
const temp1=arrayToTree(data)
console.log(temp1)

const treeToArray = (items=[], key = 'children') => items.reduce((acc, curr) => [...acc, ...treeToArray(curr[key])].map(({ [`${key}`]: child, ...ele }) => ele), items);
const temp2=treeToArray(temp1)

console.log(temp2)
_x000D_
_x000D_
_x000D_

hope it helps someone

Best practice for REST token-based authentication with JAX-RS and Jersey

How token-based authentication works

In token-based authentication, the client exchanges hard credentials (such as username and password) for a piece of data called token. For each request, instead of sending the hard credentials, the client will send the token to the server to perform authentication and then authorization.

In a few words, an authentication scheme based on tokens follow these steps:

  1. The client sends their credentials (username and password) to the server.
  2. The server authenticates the credentials and, if they are valid, generate a token for the user.
  3. The server stores the previously generated token in some storage along with the user identifier and an expiration date.
  4. The server sends the generated token to the client.
  5. The client sends the token to the server in each request.
  6. The server, in each request, extracts the token from the incoming request. With the token, the server looks up the user details to perform authentication.
    • If the token is valid, the server accepts the request.
    • If the token is invalid, the server refuses the request.
  7. Once the authentication has been performed, the server performs authorization.
  8. The server can provide an endpoint to refresh tokens.

Note: The step 3 is not required if the server has issued a signed token (such as JWT, which allows you to perform stateless authentication).

What you can do with JAX-RS 2.0 (Jersey, RESTEasy and Apache CXF)

This solution uses only the JAX-RS 2.0 API, avoiding any vendor specific solution. So, it should work with JAX-RS 2.0 implementations, such as Jersey, RESTEasy and Apache CXF.

It is worthwhile to mention that if you are using token-based authentication, you are not relying on the standard Java EE web application security mechanisms offered by the servlet container and configurable via application's web.xml descriptor. It's a custom authentication.

Authenticating a user with their username and password and issuing a token

Create a JAX-RS resource method which receives and validates the credentials (username and password) and issue a token for the user:

@Path("/authentication")
public class AuthenticationEndpoint {

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response authenticateUser(@FormParam("username") String username, 
                                     @FormParam("password") String password) {

        try {

            // Authenticate the user using the credentials provided
            authenticate(username, password);

            // Issue a token for the user
            String token = issueToken(username);

            // Return the token on the response
            return Response.ok(token).build();

        } catch (Exception e) {
            return Response.status(Response.Status.FORBIDDEN).build();
        }      
    }

    private void authenticate(String username, String password) throws Exception {
        // Authenticate against a database, LDAP, file or whatever
        // Throw an Exception if the credentials are invalid
    }

    private String issueToken(String username) {
        // Issue a token (can be a random String persisted to a database or a JWT token)
        // The issued token must be associated to a user
        // Return the issued token
    }
}

If any exceptions are thrown when validating the credentials, a response with the status 403 (Forbidden) will be returned.

If the credentials are successfully validated, a response with the status 200 (OK) will be returned and the issued token will be sent to the client in the response payload. The client must send the token to the server in every request.

When consuming application/x-www-form-urlencoded, the client must to send the credentials in the following format in the request payload:

username=admin&password=123456

Instead of form params, it's possible to wrap the username and the password into a class:

public class Credentials implements Serializable {

    private String username;
    private String password;

    // Getters and setters omitted
}

And then consume it as JSON:

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response authenticateUser(Credentials credentials) {

    String username = credentials.getUsername();
    String password = credentials.getPassword();

    // Authenticate the user, issue a token and return a response
}

Using this approach, the client must to send the credentials in the following format in the payload of the request:

{
  "username": "admin",
  "password": "123456"
}

Extracting the token from the request and validating it

The client should send the token in the standard HTTP Authorization header of the request. For example:

Authorization: Bearer <token-goes-here>

The name of the standard HTTP header is unfortunate because it carries authentication information, not authorization. However, it's the standard HTTP header for sending credentials to the server.

JAX-RS provides @NameBinding, a meta-annotation used to create other annotations to bind filters and interceptors to resource classes and methods. Define a @Secured annotation as following:

@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface Secured { }

The above defined name-binding annotation will be used to decorate a filter class, which implements ContainerRequestFilter, allowing you to intercept the request before it be handled by a resource method. The ContainerRequestContext can be used to access the HTTP request headers and then extract the token:

@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    private static final String REALM = "example";
    private static final String AUTHENTICATION_SCHEME = "Bearer";

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {

        // Get the Authorization header from the request
        String authorizationHeader =
                requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

        // Validate the Authorization header
        if (!isTokenBasedAuthentication(authorizationHeader)) {
            abortWithUnauthorized(requestContext);
            return;
        }

        // Extract the token from the Authorization header
        String token = authorizationHeader
                            .substring(AUTHENTICATION_SCHEME.length()).trim();

        try {

            // Validate the token
            validateToken(token);

        } catch (Exception e) {
            abortWithUnauthorized(requestContext);
        }
    }

    private boolean isTokenBasedAuthentication(String authorizationHeader) {

        // Check if the Authorization header is valid
        // It must not be null and must be prefixed with "Bearer" plus a whitespace
        // The authentication scheme comparison must be case-insensitive
        return authorizationHeader != null && authorizationHeader.toLowerCase()
                    .startsWith(AUTHENTICATION_SCHEME.toLowerCase() + " ");
    }

    private void abortWithUnauthorized(ContainerRequestContext requestContext) {

        // Abort the filter chain with a 401 status code response
        // The WWW-Authenticate header is sent along with the response
        requestContext.abortWith(
                Response.status(Response.Status.UNAUTHORIZED)
                        .header(HttpHeaders.WWW_AUTHENTICATE, 
                                AUTHENTICATION_SCHEME + " realm=\"" + REALM + "\"")
                        .build());
    }

    private void validateToken(String token) throws Exception {
        // Check if the token was issued by the server and if it's not expired
        // Throw an Exception if the token is invalid
    }
}

If any problems happen during the token validation, a response with the status 401 (Unauthorized) will be returned. Otherwise the request will proceed to a resource method.

Securing your REST endpoints

To bind the authentication filter to resource methods or resource classes, annotate them with the @Secured annotation created above. For the methods and/or classes that are annotated, the filter will be executed. It means that such endpoints will only be reached if the request is performed with a valid token.

If some methods or classes do not need authentication, simply do not annotate them:

@Path("/example")
public class ExampleResource {

    @GET
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response myUnsecuredMethod(@PathParam("id") Long id) {
        // This method is not annotated with @Secured
        // The authentication filter won't be executed before invoking this method
        ...
    }

    @DELETE
    @Secured
    @Path("{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Response mySecuredMethod(@PathParam("id") Long id) {
        // This method is annotated with @Secured
        // The authentication filter will be executed before invoking this method
        // The HTTP request must be performed with a valid token
        ...
    }
}

In the example shown above, the filter will be executed only for the mySecuredMethod(Long) method because it's annotated with @Secured.

Identifying the current user

It's very likely that you will need to know the user who is performing the request agains your REST API. The following approaches can be used to achieve it:

Overriding the security context of the current request

Within your ContainerRequestFilter.filter(ContainerRequestContext) method, a new SecurityContext instance can be set for the current request. Then override the SecurityContext.getUserPrincipal(), returning a Principal instance:

final SecurityContext currentSecurityContext = requestContext.getSecurityContext();
requestContext.setSecurityContext(new SecurityContext() {

        @Override
        public Principal getUserPrincipal() {
            return () -> username;
        }

    @Override
    public boolean isUserInRole(String role) {
        return true;
    }

    @Override
    public boolean isSecure() {
        return currentSecurityContext.isSecure();
    }

    @Override
    public String getAuthenticationScheme() {
        return AUTHENTICATION_SCHEME;
    }
});

Use the token to look up the user identifier (username), which will be the Principal's name.

Inject the SecurityContext in any JAX-RS resource class:

@Context
SecurityContext securityContext;

The same can be done in a JAX-RS resource method:

@GET
@Secured
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod(@PathParam("id") Long id, 
                         @Context SecurityContext securityContext) {
    ...
}

And then get the Principal:

Principal principal = securityContext.getUserPrincipal();
String username = principal.getName();

Using CDI (Context and Dependency Injection)

If, for some reason, you don't want to override the SecurityContext, you can use CDI (Context and Dependency Injection), which provides useful features such as events and producers.

Create a CDI qualifier:

@Qualifier
@Retention(RUNTIME)
@Target({ METHOD, FIELD, PARAMETER })
public @interface AuthenticatedUser { }

In your AuthenticationFilter created above, inject an Event annotated with @AuthenticatedUser:

@Inject
@AuthenticatedUser
Event<String> userAuthenticatedEvent;

If the authentication succeeds, fire the event passing the username as parameter (remember, the token is issued for a user and the token will be used to look up the user identifier):

userAuthenticatedEvent.fire(username);

It's very likely that there's a class that represents a user in your application. Let's call this class User.

Create a CDI bean to handle the authentication event, find a User instance with the correspondent username and assign it to the authenticatedUser producer field:

@RequestScoped
public class AuthenticatedUserProducer {

    @Produces
    @RequestScoped
    @AuthenticatedUser
    private User authenticatedUser;

    public void handleAuthenticationEvent(@Observes @AuthenticatedUser String username) {
        this.authenticatedUser = findUser(username);
    }

    private User findUser(String username) {
        // Hit the the database or a service to find a user by its username and return it
        // Return the User instance
    }
}

The authenticatedUser field produces a User instance that can be injected into container managed beans, such as JAX-RS services, CDI beans, servlets and EJBs. Use the following piece of code to inject a User instance (in fact, it's a CDI proxy):

@Inject
@AuthenticatedUser
User authenticatedUser;

Note that the CDI @Produces annotation is different from the JAX-RS @Produces annotation:

Be sure you use the CDI @Produces annotation in your AuthenticatedUserProducer bean.

The key here is the bean annotated with @RequestScoped, allowing you to share data between filters and your beans. If you don't wan't to use events, you can modify the filter to store the authenticated user in a request scoped bean and then read it from your JAX-RS resource classes.

Compared to the approach that overrides the SecurityContext, the CDI approach allows you to get the authenticated user from beans other than JAX-RS resources and providers.

Supporting role-based authorization

Please refer to my other answer for details on how to support role-based authorization.

Issuing tokens

A token can be:

  • Opaque: Reveals no details other than the value itself (like a random string)
  • Self-contained: Contains details about the token itself (like JWT).

See details below:

Random string as token

A token can be issued by generating a random string and persisting it to a database along with the user identifier and an expiration date. A good example of how to generate a random string in Java can be seen here. You also could use:

Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);

JWT (JSON Web Token)

JWT (JSON Web Token) is a standard method for representing claims securely between two parties and is defined by the RFC 7519.

It's a self-contained token and it enables you to store details in claims. These claims are stored in the token payload which is a JSON encoded as Base64. Here are some claims registered in the RFC 7519 and what they mean (read the full RFC for further details):

  • iss: Principal that issued the token.
  • sub: Principal that is the subject of the JWT.
  • exp: Expiration date for the token.
  • nbf: Time on which the token will start to be accepted for processing.
  • iat: Time on which the token was issued.
  • jti: Unique identifier for the token.

Be aware that you must not store sensitive data, such as passwords, in the token.

The payload can be read by the client and the integrity of the token can be easily checked by verifying its signature on the server. The signature is what prevents the token from being tampered with.

You won't need to persist JWT tokens if you don't need to track them. Althought, by persisting the tokens, you will have the possibility of invalidating and revoking the access of them. To keep the track of JWT tokens, instead of persisting the whole token on the server, you could persist the token identifier (jti claim) along with some other details such as the user you issued the token for, the expiration date, etc.

When persisting tokens, always consider removing the old ones in order to prevent your database from growing indefinitely.

Using JWT

There are a few Java libraries to issue and validate JWT tokens such as:

To find some other great resources to work with JWT, have a look at http://jwt.io.

Handling token revocation with JWT

If you want to revoke tokens, you must keep the track of them. You don't need to store the whole token on server side, store only the token identifier (that must be unique) and some metadata if you need. For the token identifier you could use UUID.

The jti claim should be used to store the token identifier on the token. When validating the token, ensure that it has not been revoked by checking the value of the jti claim against the token identifiers you have on server side.

For security purposes, revoke all the tokens for a user when they change their password.

Additional information

  • It doesn't matter which type of authentication you decide to use. Always do it on the top of a HTTPS connection to prevent the man-in-the-middle attack.
  • Take a look at this question from Information Security for more information about tokens.
  • In this article you will find some useful information about token-based authentication.

Can't install APK from browser downloads

It shouldn't be HTTP headers if the file has been downloaded successfully and it's the same file that you can open from OI.

A shot in the dark, but could it be that you are not allowing installation from unknown sources, and that OI is somehow bypassing that?

Settings > Applications > Unknown sources...

Edit

Answer extracted from comments which worked. Ensure the Content-Type is set to application/vnd.android.package-archive

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

In clean Ubuntu 16.04 LTS, MariaDB root login for localhost changed from password style to sudo login style...

so, just do

sudo mysql -u root

since we want to login with password, create another user 'user'

in MariaDB console... (you get in MariaDB console with 'sudo mysql -u root')

use mysql
CREATE USER 'user'@'localhost' IDENTIFIED BY 'yourpassword';
\q

then in bash shell prompt,

mysql-workbench

and you can login with 'user' with 'yourpassword' on localhost

Vue.js img src concatenate variable and text

just try

_x000D_
_x000D_
<img :src="require(`${imgPreUrl}img/logo.png`)">
_x000D_
_x000D_
_x000D_

How to remove focus from single editText

Did you try to use old good View.clearFocus()

Objective-C for Windows

Get GNUStep here

Get MINGW here

Install MINGW Install GNUStep Then Test

check null,empty or undefined angularjs

if($scope.test == null || $scope.test == undefined || $scope.test == "" ||    $scope.test.lenght == 0){

console.log("test is not defined");
}
else{
console.log("test is defined ",$scope.test); 
}

How to give a Linux user sudo access?

Edit /etc/sudoers file either manually or using the visudo application. Remember: System reads /etc/sudoers file from top to the bottom, so you could overwrite a particular setting by putting the next one below. So to be on the safe side - define your access setting at the bottom.

How to remove backslash on json_encode() function?

If you using PHP 5.2, json_encode just expect only 1 parameter when call it. This is an alternative to unescape slash of json values:

stripslashes(json_encode($array))

Don't use it if your data is complicated.

"RangeError: Maximum call stack size exceeded" Why?

Here it fails at Array.apply(null, new Array(1000000)) and not the .map call.

All functions arguments must fit on callstack(at least pointers of each argument), so in this they are too many arguments for the callstack.

You need to the understand what is call stack.

Stack is a LIFO data structure, which is like an array that only supports push and pop methods.

Let me explain how it works by a simple example:

function a(var1, var2) {
    var3 = 3;
    b(5, 6);
    c(var1, var2);
}
function b(var5, var6) {
    c(7, 8);
}
function c(var7, var8) {
}

When here function a is called, it will call b and c. When b and c are called, the local variables of a are not accessible there because of scoping roles of Javascript, but the Javascript engine must remember the local variables and arguments, so it will push them into the callstack. Let's say you are implementing a JavaScript engine with the Javascript language like Narcissus.

We implement the callStack as array:

var callStack = [];

Everytime a function called we push the local variables into the stack:

callStack.push(currentLocalVaraibles);

Once the function call is finished(like in a, we have called b, b is finished executing and we must return to a), we get back the local variables by poping the stack:

currentLocalVaraibles = callStack.pop();

So when in a we want to call c again, push the local variables in the stack. Now as you know, compilers to be efficient define some limits. Here when you are doing Array.apply(null, new Array(1000000)), your currentLocalVariables object will be huge because it will have 1000000 variables inside. Since .apply will pass each of the given array element as an argument to the function. Once pushed to the call stack this will exceed the memory limit of call stack and it will throw that error.

Same error happens on infinite recursion(function a() { a() }) as too many times, stuff has been pushed to the call stack.

Note that I'm not a compiler engineer and this is just a simplified representation of what's going on. It really is more complex than this. Generally what is pushed to callstack is called stack frame which contains the arguments, local variables and the function address.

Printing with "\t" (tabs) does not result in aligned columns

As mentioned by other folks, the variable length of the string is the issue.

Rather than reinventing the wheel, Apache Commons has a nice, clean solution for this in StringUtils.

StringUtils.rightPad("String to extend",100); //100 is the length you want to pad out to.

Difference between Constructor and ngOnInit

The first one (constructor) is related to the class instantiation and has nothing to do with Angular2. I mean a constructor can be used on any class. You can put in it some initialization processing for the newly created instance.

The second one corresponds to a lifecycle hook of Angular2 components:

Quoted from official angular's website:

  • ngOnChanges is called when an input or output binding value changes
  • ngOnInit is called after the first ngOnChanges

So you should use ngOnInit if initialization processing relies on bindings of the component (for example component parameters defined with @Input), otherwise the constructor would be enough...

Why does Maven have such a bad rep?

I looked into maven about six months ago. We were starting a new project, and didn't have any legacy to support. That said:

  • Maven is all-or-nothing. Or at least as far as I could tell from the documentation. You can't easily use maven as a drop-in replacement for ant, and gradually adopt more advanced features.
  • According to the documentation, Maven is transcendental happiness that makes all your wildest dreams come true. You just have to meditate on the manual for 10 years before you become enlightened.
  • Maven makes your build process dependent on your network connection.
  • Maven has useless error messages. Compare ant's "Target x does not exist in the project y" to mvn's "Invalid task 'run': you must specify a valid lifecycle phase, or a goal in the format plugin:goal or pluginGroupId:pluginArtifactId:pluginVersion:goal" Helpfully, it suggests I run mvn with -e for more information, which means that it will print the same message, then a stack trace for a BuildFailureException.

A large part of my dislike for maven can be explained by the following excerpt from Better Builds with Maven:

When someone wants to know what Maven is, they will usually ask “What exactly is Maven?”, and they expect a short, sound-bite answer. “Well it is a build tool or a scripting framework” Maven is more than three boring, uninspiring words. It is a combination of ideas, standards, and software, and it is impossible to distill the definition of Maven to simply digested sound-bites. Revolutionary ideas are often difficult to convey with words.

My suggestion: if you can't convey the ideas with words, you should not attempt to write a book on the subject, because I'm not going to telepathically absorb the ideas.

PHP-FPM and Nginx: 502 Bad Gateway

If you met the problem after upgrading php-fpm like me, try this: open /etc/php5/fpm/pool.d/www.conf uncomment the following lines:

listen.owner = www-data
listen.group = www-data
listen.mode = 0666

then restart php-fpm.

How to execute UNION without sorting? (SQL)

I notice this question gets quite a lot of views so I'll first address a question you didn't ask!

Regarding the title. To achieve a "Sql Union All with “distinct”" then simply replace UNION ALL with UNION. This has the effect of removing duplicates.

For your specific question, given the clarification "The first query should have "priority", so duplicates should be removed from bottom" you can use

SELECT col1,
       col2,
       MIN(grp) AS source_group
FROM   (SELECT 1 AS grp,
               col1,
               col2
        FROM   t1
        UNION ALL
        SELECT 2 AS grp,
               col1,
               col2
        FROM   t2) AS t
GROUP  BY col1,
          col2
ORDER  BY MIN(grp),
          col1  

Can't compile C program on a Mac after upgrade to Mojave

TL;DR

Make sure you have downloaded the latest 'Command Line Tools' package and run this from a terminal (command line):

open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

For some information on Catalina, see Can't compile a C program on a Mac after upgrading to Catalina 10.15.


Extracting a semi-coherent answer from rather extensive comments…

Preamble

Very often, xcode-select --install has been the correct solution, but it does not seem to help this time. Have you tried running the main Xcode GUI interface? It may install some extra software for you and clean up. I did that after installing Xcode 10.0, but a week or more ago, long before upgrading to Mojave.

I observe that if your GCC is installed in /usr/local/bin, you probably aren't using the GCC from Xcode; that's normally installed in /usr/bin.

I too have updated to macOS 10.14 Mojave and Xcode 10.0. However, both the system /usr/bin/gcc and system /usr/bin/clang are working for me (Apple LLVM version 10.0.0 (clang-1000.11.45.2) Target: x86_64-apple-darwin18.0.0 for both.) I have a problem with my home-built GCC 8.2.0 not finding headers in /usr/include, which is parallel to your problem with /usr/local/bin/gcc not finding headers either.

I've done a bit of comparison, and my Mojave machine has no /usr/include at all, yet /usr/bin/clang is able to compile OK. A header (_stdio.h, with leading underscore) was in my old /usr/include; it is missing now (hence my problem with GCC 8.2.0). I ran xcode-select --install and it said "xcode-select: note: install requested for command line developer tools" and then ran a GUI installer which showed me a licence which I agreed to, and it downloaded and installed the command line tools — or so it claimed.

I then ran Xcode GUI (command-space, Xcode, return) and it said it needed to install some more software, but still no /usr/include. But I can compile with /usr/bin/clang and /usr/bin/gcc — and the -v option suggests they're using

InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

Working solution

Then Maxxx noted:

I've found a way. If we are using Xcode 10, you will notice that if you navigate to the /usr in the Finder, you will not see a folder called 'include' any more, which is why the terminal complains of the absence of the header files which is contained inside the 'include' folder. In the Xcode 10.0 Release Notes, it says there is a package:

/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg 

and you should install that package to have the /usr/include folder installed. Then you should be good to go.

When all else fails, read the manual or, in this case, the release notes. I'm not dreadfully surprised to find Apple wanting to turn their backs on their Unix heritage, but I am disappointed. If they're careful, they could drive me away. Thank you for the information.

Having installed the package using the following command at the command line, I have /usr/include again, and my GCC 8.2.0 works once more.

open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

Downloading Command Line Tools

As Vesal points out in a valuable comment, you need to download the Command Line Tools package for Xcode 10.1 on Mojave 10.14, and you can do so from:

You need to login with an Apple ID to be able to get the download. When you've done the download, install the Command Line Tools package. Then install the headers as described in the section 'Working Solution'.

This worked for me on Mojave 10.14.1. I must have downloaded this before, but I'd forgotten by the time I was answering this question.

Upgrade to Mojave 10.14.4 and Xcode 10.2

On or about 2019-05-17, I updated to Mojave 10.14.4, and the Xcode 10.2 command line tools were also upgraded (or Xcode 10.1 command line tools were upgraded to 10.2). The open command shown above fixed the missing headers. There may still be adventures to come with upgrading the main Xcode to 10.2 and then re-reinstalling the command line tools and the headers package.

Upgrade to Xcode 10.3 (for Mojave 10.14.6)

On 2019-07-22, I got notice via the App Store that the upgrade to Xcode 10.3 is available and that it includes SDKs for iOS 12.4, tvOS 12.4, watchOS 5.3 and macOS Mojave 10.14.6. I installed it one of my 10.14.5 machines, and ran it, and installed extra components as it suggested, and it seems to have left /usr/include intact.

Later the same day, I discovered that macOS Mojave 10.14.6 was available too (System Preferences ? Software Update), along with a Command Line Utilities package IIRC (it was downloaded and installed automatically). Installing the o/s update did, once more, wipe out /usr/include, but the open command at the top of the answer reinstated it again. The date I had on the file for the open command was 2019-07-15.

Upgrade to XCode 11.0 (for Catalina 10.15)

The upgrade to XCode 11.0 ("includes Swift 5.1 and SDKs for iOS 13, tvOS 13, watchOS 6 and macOS Catalina 10.15") was released 2019-09-21. I was notified of 'updates available', and downloaded and installed it onto machines running macOS Mojave 10.14.6 via the App Store app (updates tab) without problems, and without having to futz with /usr/include. Immediately after installation (before having run the application itself), I tried a recompilation and was told:

Agreeing to the Xcode/iOS license requires admin privileges, please run “sudo xcodebuild -license” and then retry this command.

Running that (sudo xcodebuild -license) allowed me to run the compiler. Since then, I've run the application to install extra components it needs; still no problem. It remains to be seen what happens when I upgrade to Catalina itself — but my macOS Mojave 10.14.6 machines are both OK at the moment (2019-09-24).

ping: google.com: Temporary failure in name resolution

If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8 into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.

comparing two strings in SQL Server

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables

Django request.GET

def search(request):
if 'q' in request.GET.keys():
    message = 'You submitted: %r' % request.GET['q']
else:
    message = 'You submitted nothing!'

return HttpResponse(message)

you can use if ... in too.

My Application Could not open ServletContext resource

The file name u used spring-dispatcher-servlet.xml
kindly check in web.xml
servlet name as spring-dispatcher at both tag  <servlet> and <servlet-mapping>
in your case it should be

<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class></servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern></url-pattern>
</servlet-mapping>

submitting a form when a checkbox is checked

Yes, this is possible.

<form id="formName" action="<?php echo $_SERVER['PHP_SELF'];?>" method="get">
    <input type ="checkbox" name="cBox[]" value = "3" onchange="document.getElementById('formName').submit()">3</input>
    <input type ="checkbox" name="cBox[]" value = "4" onchange="document.getElementById('formName').submit()">4</input>
    <input type ="checkbox" name="cBox[]" value = "5" onchange="document.getElementById('formName').submit()">5</input>
    <input type="submit" name="submit" value="Search" />
</form>

By adding onchange="document.getElementById('formName').submit()" to each checkbox, you'll submit any time a checkbox is changed.

If you're OK with jQuery, it's even easier (and unobtrusive):

$(document).ready(function(){
    $("#formname").on("change", "input:checkbox", function(){
        $("#formname").submit();
    });
});

For any number of checkboxes in your form, when the "change" event happens, the form is submitted. This will even work if you dynamically create more checkboxes thanks to the .on() method.

Concatenation of strings in Lua

As other answers have said, the string concatenation operator in Lua is two dots.

Your simple example would be written like this:

filename = "checkbook"
filename = filename .. ".tmp"

However, there is a caveat to be aware of. Since strings in Lua are immutable, each concatenation creates a new string object and copies the data from the source strings to it. That makes successive concatenations to a single string have very poor performance.

The Lua idiom for this case is something like this:

function listvalues(s)
    local t = { }
    for k,v in ipairs(s) do
        t[#t+1] = tostring(v)
    end
    return table.concat(t,"\n")
end

By collecting the strings to be concatenated in an array t, the standard library routine table.concat can be used to concatenate them all up (along with a separator string between each pair) without unnecessary string copying.

Update: I just noticed that I originally wrote the code snippet above using pairs() instead of ipairs().

As originally written, the function listvalues() would indeed produce every value from the table passed in, but not in a stable or predictable order. On the other hand, it would include values who's keys were not positive integers in the span of 1 to #s. That is what pairs() does: it produces every single (key,value) pair stored in the table.

In most cases where you would be using something like listvaluas() you would be interested in preserving their order. So a call written as listvalues{13, 42, 17, 4} would produce a string containing those value in that order. However, pairs() won't do that, it will itemize them in some order that depends on the underlying implementation of the table data structure. It is known that the order not only depends on the keys, but also on the order in which the keys were inserted and other keys removed.

Of course ipairs() isn't a perfect answer either. It only enumerates those values of the table that form a "sequence". That is, those values who's keys form an unbroken block spanning from 1 to some upper bound, which is (usually) also the value returned by the # operator. (In many cases, the function ipairs() itself is better replaced by a simpler for loop that just counts from 1 to #s. This is the recommended practice in Lua 5.2 and in LuaJIT where the simpler for loop can be more efficiently implemented than the ipairs() iterator.)

If pairs() really is the right approach, then it is usually the case that you want to print both the key and the value. This reduces the concerns about order by making the data self-describing. Of course, since any Lua type (except nil and the floating point NaN) can be used as a key (and NaN can also be stored as a value) finding a string representation is left as an exercise for the student. And don't forget about trees and more complex structures of tables.

C# Change A Button's Background Color

// WPF

// Defined Color
button1.Background = Brushes.Green;

// Color from RGB
button2.Background = new SolidColorBrush(Color.FromArgb(255, 0, 255, 0));

How can I generate Javadoc comments in Eclipse?

You mean menu Project -> Generate Javadoc ?

Java Does Not Equal (!=) Not Working?

== and != work on object identity. While the two Strings have the same value, they are actually two different objects.

use !"success".equals(statusCheck) instead.

how to read all files inside particular folder

If you are looking to copy all the text files in one folder to merge and copy to another folder, you can do this to achieve that:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace HowToCopyTextFiles
{
  class Program
  {
    static void Main(string[] args)
    {
      string mydocpath=Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);     
      StringBuilder sb = new StringBuilder();
      foreach (string txtName in Directory.GetFiles(@"D:\Links","*.txt"))
      {
        using (StreamReader sr = new StreamReader(txtName))
        {
          sb.AppendLine(txtName.ToString());
          sb.AppendLine("= = = = = =");
          sb.Append(sr.ReadToEnd());
          sb.AppendLine();
          sb.AppendLine();   
        }
      }
      using (StreamWriter outfile=new StreamWriter(mydocpath + @"\AllTxtFiles.txt"))
      {    
        outfile.Write(sb.ToString());
      }   
    }
  }
}

How to change target build on Android project?

The file default.properties is by default read only, changing that worked for me.

How to navigate through textfields (Next / Done Buttons)

There is a much more elegant solution which blew me away the first time I saw it. Benefits:

  • Closer to OSX textfield implementation where a textfield knows where the focus should go next
  • Does not rely on setting or using tags -- which are, IMO fragile for this use case
  • Can be extended to work with both UITextField and UITextView controls -- or any keyboard entry UI control
  • Doesn't clutter your view controller with boilerplate UITextField delegate code
  • Integrates nicely with IB and can be configured through the familiar option-drag-drop to connect outlets.

Create a UITextField subclass which has an IBOutlet property called nextField. Here's the header:

@interface SOTextField : UITextField

@property (weak, nonatomic) IBOutlet UITextField *nextField; 

@end

And here's the implementation:

@implementation SOTextField

@end

In your view controller, you'll create the -textFieldShouldReturn: delegate method:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if ([textField isKindOfClass:[SOTextField class]]) {
        UITextField *nextField = [(SOTextField *)textField nextField];

        if (nextField) {
            dispatch_async(dispatch_get_current_queue(), ^{
                [nextField becomeFirstResponder];
            });
        }
        else {
            [textField resignFirstResponder];
        }
    }

    return YES;
}

In IB, change your UITextFields to use the SOTextField class. Next, also in IB, set the delegate for each of the 'SOTextFields'to 'File's Owner' (which is right where you put the code for the delegate method - textFieldShouldReturn). The beauty of this design is that now you can simply right-click on any textField and assign the nextField outlet to the next SOTextField object you want to be the next responder.

Assigning nextField in IB

Moreover, you can do cool things like loop the textFields so that after the last one loses focus, the first one will receive focus again.

This can easily be extended to automatically assign the returnKeyType of the SOTextField to a UIReturnKeyNext if there is a nextField assigned -- one less thing manually configure.

Batch files - number of command line arguments

The function :getargc below may be what you're looking for.

@echo off
setlocal enableextensions enabledelayedexpansion
call :getargc argc %*
echo Count is %argc%
echo Args are %*
endlocal
goto :eof

:getargc
    set getargc_v0=%1
    set /a "%getargc_v0% = 0"
:getargc_l0
    if not x%2x==xx (
        shift
        set /a "%getargc_v0% = %getargc_v0% + 1"
        goto :getargc_l0
    )
    set getargc_v0=
    goto :eof

It basically iterates once over the list (which is local to the function so the shifts won't affect the list back in the main program), counting them until it runs out.

It also uses a nifty trick, passing the name of the return variable to be set by the function.

The main program just illustrates how to call it and echos the arguments afterwards to ensure that they're untouched:

C:\Here> xx.cmd 1 2 3 4 5
    Count is 5
    Args are 1 2 3 4 5
C:\Here> xx.cmd 1 2 3 4 5 6 7 8 9 10 11
    Count is 11
    Args are 1 2 3 4 5 6 7 8 9 10 11
C:\Here> xx.cmd 1
    Count is 1
    Args are 1
C:\Here> xx.cmd
    Count is 0
    Args are
C:\Here> xx.cmd 1 2 "3 4 5"
    Count is 3
    Args are 1 2 "3 4 5"

Angular JS update input field after change

I'm guessing that when you enter a value into the totals field that value expression somehow gets overwritten.

However, you can take an alternative approach: Create a field for the total value and when either one or two changes update that field.

<li>Total <input type="text" ng-model="total">{{total}}</li>

And change the javascript:

function TodoCtrl($scope) {
    $scope.$watch('one * two', function (value) {
        $scope.total = value;
    });
}

Example fiddle here.

How to extract closed caption transcript from YouTube video?

There is a free python tool called YouTube transcript API

You can use it in scripts or as a command line tool:

pip install youtube_transcript_api

How to see remote tags?

You can list the tags on remote repository with ls-remote, and then check if it's there. Supposing the remote reference name is origin in the following.

git ls-remote --tags origin

And you can list tags local with tag.

git tag

You can compare the results manually or in script.

ArrayIndexOutOfBoundsException when using the ArrayList's iterator

List<String> arrayList = new ArrayList<String>();
for (String s : arrayList) {
    if(s.equals(value)){
        //do something
    }
}

or

for (int i = 0; i < arrayList.size(); i++) {
    if(arrayList.get(i).equals(value)){
        //do something
    }
}

But be carefull ArrayList can hold null values. So comparation should be

value.equals(arrayList.get(i))

when you are sure that value is not null or you should check if given element is null.

How to remove class from all elements jquery

$(".edgetoedge>li").removeClass("highlight");

how to insert value into DataGridView Cell?

You can access any DGV cell as follows :

dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;

But usually it's better to use databinding : you bind the DGV to a data source (DataTable, collection...) through the DataSource property, and only work on the data source itself. The DataGridView will automatically reflect the changes, and changes made on the DataGridView will be reflected on the data source

How to log SQL statements in Spring Boot?

According to documentation it is:

spring.jpa.show-sql=true # Enable logging of SQL statements.

How to use __doPostBack()

This is also a good way to get server-side controls to postback inside FancyBox and/or jQuery Dialog. For example, in FancyBox-div:

   <asp:Button OnClientClick="testMe('param1');" ClientIDMode="Static"  ID="MyButton"  runat="server" Text="Ok" >
</asp:Button>

JavaScript:

function testMe(params) {
    var btnID= '<%=MyButton.ClientID %>';          
    __doPostBack(btnID, params);
}

Server-side Page_Load:

 string parameter = Request["__EVENTARGUMENT"];
 if (parameter == "param1")
     MyButton_Click(sender, e);

Import .bak file to a database in SQL server

.bak files are database backups. You can restore the backup with the method below:

How to: Restore a Database Backup (SQL Server Management Studio)

Lookup City and State by Zip Google Geocode Api

function getCityState($zip, $blnUSA = true) {
    $url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $zip . "&sensor=true";

    $address_info = file_get_contents($url);
    $json = json_decode($address_info);
    $city = "";
    $state = "";
    $country = "";
    if (count($json->results) > 0) {
        //break up the components
        $arrComponents = $json->results[0]->address_components;

        foreach($arrComponents as $index=>$component) {
            $type = $component->types[0];

            if ($city == "" && ($type == "sublocality_level_1" || $type == "locality") ) {
                $city = trim($component->short_name);
            }
            if ($state == "" && $type=="administrative_area_level_1") {
                $state = trim($component->short_name);
            }
            if ($country == "" && $type=="country") {
                $country = trim($component->short_name);

                if ($blnUSA && $country!="US") {
                    $city = "";
                    $state = "";
                    break;
                }
            }
            if ($city != "" && $state != "" && $country != "") {
                //we're done
                break;
            }
        }
    }
    $arrReturn = array("city"=>$city, "state"=>$state, "country"=>$country);

    die(json_encode($arrReturn));
}

How to handle AssertionError in Python and find out which line or statement it occurred on?

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

How to do an update + join in PostgreSQL?

For those wanting to do a JOIN that updates ONLY the rows your join returns use:

UPDATE a
SET price = b_alias.unit_price
FROM      a AS a_alias
LEFT JOIN b AS b_alias ON a_alias.b_fk = b_alias.id
WHERE a_alias.unit_name LIKE 'some_value' 
AND a.id = a_alias.id
--the below line is critical for updating ONLY joined rows
AND a.pk_id = a_alias.pk_id;

This was mentioned above but only through a comment..Since it's critical to getting the correct result posting NEW answer that Works

javascript date to string

A little bit simpler using regex and toJSON().

var now = new Date();
var timeRegex = /^.*T(\d{2}):(\d{2}):(\d{2}).*$/
var dateRegex = /^(\d{4})-(\d{2})-(\d{2})T.*$/
var dateData = dateRegex.exec(now.toJSON());
var timeData = timeRegex.exec(now.toJSON());
var myFormat = dateData[1]+dateData[2]+dateData[3]+timeData[1]+timeData[2]+timeData[3]

Which at the time of writing gives you "20151111180924".

The good thing of using toJSON() is that everything comes already padded.

Disable button in WPF?

You could subscribe to the TextChanged event on the TextBox and if the text is empty set the Button to disabled. Or you could bind the Button.IsEnabled property to the TextBox.Text property and use a converter that returns true if there is any text and false otherwise.

ImportError: No module named site on Windows

Are you trying to run Windows Python from Cygwin? I'm having the same problem. Python in Cygwin fails to import site. Python in Cmd works.

It looks like you need to make sure you run PYTHONHOME and PYTHONPATH through cygwin -aw to make them Windows paths. Also, python seems to be using some incorrect paths.

I think I'll need to install python through cygwin to get it working.

Keyboard shortcut to change font size in Eclipse?

Eclipse Neon (4.6)

Zoom In

Ctrl++

or

Ctrl+=

Zoom Out

Ctrl+-

This feature is described here:

In text editors, you can now use Zoom In (Ctrl++ or Ctrl+=) and Zoom Out (Ctrl+-) commands to increase and decrease the font size. Like a change in the General > Appearance > Colors and Fonts preference page, the commands persistently change the font size in all editors of the same type. If the editor type's font is configured to use a default font, then that default font will be zoomed.

So, the font size change is not limited to the current file and the new value of the font size is available here Window > Preferences > General > Appearance > Colors and Fonts.

How to get the text node of an element?

ES6 version that return the first #text node content

const extract = (node) => {
  const text = [...node.childNodes].find(child => child.nodeType === Node.TEXT_NODE);
  return text && text.textContent.trim();
}

How to get the public IP address of a user in C#

Combination of all of these suggestions, and the reasons behind them. Feel free to add more test cases too. If getting the client IP is of utmost importance, than you might wan to get all of theses are run some comparisons on which result might be more accurate.

Simple check of all suggestions in this thread plus some of my own code...

    using System.IO;
    using System.Net;

    public string GetUserIP()
    {
        string strIP = String.Empty;
        HttpRequest httpReq = HttpContext.Current.Request;

        //test for non-standard proxy server designations of client's IP
        if (httpReq.ServerVariables["HTTP_CLIENT_IP"] != null)
        {
            strIP = httpReq.ServerVariables["HTTP_CLIENT_IP"].ToString();
        }
        else if (httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        {
            strIP = httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        //test for host address reported by the server
        else if
        (
            //if exists
            (httpReq.UserHostAddress.Length != 0)
            &&
            //and if not localhost IPV6 or localhost name
            ((httpReq.UserHostAddress != "::1") || (httpReq.UserHostAddress != "localhost"))
        )
        {
            strIP = httpReq.UserHostAddress;
        }
        //finally, if all else fails, get the IP from a web scrape of another server
        else
        {
            WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
            using (WebResponse response = request.GetResponse())
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                strIP = sr.ReadToEnd();
            }
            //scrape ip from the html
            int i1 = strIP.IndexOf("Address: ") + 9;
            int i2 = strIP.LastIndexOf("</body>");
            strIP = strIP.Substring(i1, i2 - i1);
        }
        return strIP;
    }

How to get the current time in Python

Why not ask the U.S. Naval Observatory, the official timekeeper of the United States Navy?

import requests
from lxml import html

page = requests.get('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
tree = html.fromstring(page.content)
print(tree.xpath('//html//body//h3//pre/text()')[1])

If you live in the D.C. area (like me) the latency might not be too bad...

PHP date() with timezone?

Not mentioned above. You could also crate a DateTime object by providing a timestamp as string in the constructor with a leading @ sign.

$dt = new DateTime('@123456789');
$dt->setTimezone(new DateTimeZone('America/New_York'));
echo $dt->format('F j, Y - G:i');

See the documentation about compound formats: https://www.php.net/manual/en/datetime.formats.compound.php

Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code

After trying all the solutions, I was missing is to enable this option in:

Targets -> Build Phases -> Embedded pods frameworks

In newer versions it may be listed as:

Targets -> Build Phases -> Bundle React Native code and images

  • Run script only when installing

Build Phases

How to convert an ASCII character into an int in C

Are you searching for this:

int c = some_ascii_character;

Or just converting without assignment:

(int)some_aschii_character;

How to calculate a Mod b in Casio fx-991ES calculator

mod formula Note: Math error means a mod m = 0

How do I provide a username and password when running "git clone [email protected]"?

The user@host:path/to/repo format tells Git to use ssh to log in to host with username user. From git help clone:

An alternative scp-like syntax may also be used with the ssh protocol:

[user@]host.xz:path/to/repo.git/

The part before the @ is the username, and the authentication method (password, public key, etc.) is determined by ssh, not Git. Git has no way to pass a password to ssh, because ssh might not even use a password depending on the configuration of the remote server.

Use ssh-agent to avoid typing passwords all the time

If you don't want to type your ssh password all the time, the typical solution is to generate a public/private key pair, put the public key in your ~/.ssh/authorized_keys file on the remote server, and load your private key into ssh-agent. Also see Configuring Git over SSH to login once, GitHub's help page on ssh key passphrases, gitolite's ssh documentation, and Heroku's ssh keys documentation.

Choosing between multiple accounts at GitHub (or Heroku or...)

If you have multiple accounts at a place like GitHub or Heroku, you'll have multiple ssh keys (at least one per account). To pick which account you want to log in as, you have to tell ssh which private key to use.

For example, suppose you had two GitHub accounts: foo and bar. Your ssh key for foo is ~/.ssh/foo_github_id and your ssh key for bar is ~/.ssh/bar_github_id. You want to access [email protected]:foo/foo.git with your foo account and [email protected]:bar/bar.git with your bar account. You would add the following to your ~/.ssh/config:

Host gh-foo
    Hostname github.com
    User git
    IdentityFile ~/.ssh/foo_github_id
Host gh-bar
    Hostname github.com
    User git
    IdentityFile ~/.ssh/bar_github_id

You would then clone the two repositories as follows:

git clone gh-foo:foo/foo.git  # logs in with account foo
git clone gh-bar:bar/bar.git  # logs in with account bar

Avoiding ssh altogether

Some services provide HTTP access as an alternative to ssh:

WARNING: Adding your password to the clone URL will cause Git to store your plaintext password in .git/config. To securely store your password when using HTTP, use a credential helper. For example:

git config --global credential.helper cache
git config --global credential.https://github.com.username foo
git clone https://github.com/foo/repository.git

The above will cause Git to ask for your password once every 15 minutes (by default). See git help credentials for details.

How to find the remainder of a division in C?

Use the modulus operator %, it returns the remainder.

int a = 5;
int b = 3;

if (a % b != 0) {
   printf("The remainder is: %i", a%b);
}

How do I specify local .gem files in my Gemfile?

I found it easiest to run my own gem server using geminabox

See these simple instructions.

Copy directory contents into a directory with python

The python libs are obsolete with this function. I've done one that works correctly:

import os
import shutil

def copydirectorykut(src, dst):
    os.chdir(dst)
    list=os.listdir(src)
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)

    fitx.close()

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
        else:
            if not os.path.exists(dst+'/'+line[:-1]):
                os.makedirs(dst+'/'+line[:-1])
                copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
            copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
    f.close()
    os.remove(nom)
    os.chdir('..')

Printing a 2D array in C

Is this any help?

#include <stdio.h>

#define MAX 10

int main()
{
    char grid[MAX][MAX];
    int i,j,row,col;

    printf("Please enter your grid size: ");
    scanf("%d %d", &row, &col);


    for (i = 0; i < row; i++) {
        for (j = 0; j < col; j++) {
            grid[i][j] = '.';
            printf("%c ", grid[i][j]);
        }
        printf("\n");
    }

    return 0;
}

how to auto select an input field and the text in it on page load

From http://www.codeave.com/javascript/code.asp?u_log=7004:

_x000D_
_x000D_
var input = document.getElementById('myTextInput');_x000D_
input.focus();_x000D_
input.select();
_x000D_
<input id="myTextInput" value="Hello world!" />
_x000D_
_x000D_
_x000D_

Checking if date is weekend PHP

Here:

function isweekend($year, $month, $day)
{
    $time = mktime(0, 0, 0, $month, $day, $year);
    $weekday = date('w', $time);
    return ($weekday == 0 || $weekday == 6);
}

No route matches "/users/sign_out" devise rails 3

See if your routes.rb has a "resource :users" before a "devise_for :users" then try swapping them:

  1. Works

    • devise_for :users
    • resources :users
  2. Fails

    • resources :users
    • devise_for :users

Adding minutes to date time in PHP

one line mysql datetime format

$mysql_date_time = (new DateTime())->modify('+15 minutes')->format("Y-m-d H:i:s");

Are HTTPS URLs encrypted?

It is now 2019 and the TLS v1.3 has been released. According to Cloudflare, the server name indication (SNI aka the hostname) can be encrypted thanks to TLS v1.3. So, I told myself great! Let's see how it looks within the TCP packets of cloudflare.com So, I caught a "client hello" handshake packet from a response of the cloudflare server using Google Chrome as browser & wireshark as packet sniffer. I still can read the hostname in plain text within the Client hello packet as you can see below. It is not encrypted.

enter image description here

So, beware of what you can read because this is still not an anonymous connection. A middleware application between the client and the server could log every domain that are requested by a client.

So, it looks like the encryption of the SNI requires additional implementations to work along with TLSv1.3

UPDATE June 2020: It looks like the Encrypted SNI is initiated by the browser. Cloudflare has a page for you to check if your browser supports Encrypted SNI:

https://www.cloudflare.com/ssl/encrypted-sni/

At this point, I think Google chrome does not support it. You can activate Encrypted SNI in Firefox manually. When I tried it for some reason, it didn't work instantly. I restarted Firefox twice before it worked:

Type: about:config in the URL field.

Check if network.security.esni.enabled is true. Clear your cache / restart

Go to the website, I mentioned before.

As you can see VPN services are still useful today for people who want to ensure that a coffee shop owner does not log the list of websites that people visit.

Connect to Active Directory via LDAP

DC is your domain. If you want to connect to the domain example.com than your dc's are: DC=example,DC=com

You actually don't need any hostname or ip address of your domain controller (There could be plenty of them).

Just imagine that you're connecting to the domain itself. So for connecting to the domain example.com you can simply write

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");

And you're done.

You can also specify a user and a password used to connect:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com", "username", "password");

Also be sure to always write LDAP in upper case. I had some trouble and strange exceptions until I read somewhere that I should try to write it in upper case and that solved my problems.

The directoryEntry.Path Property allows you to dive deeper into your domain. So if you want to search a user in a specific OU (Organizational Unit) you can set it there.

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
directoryEntry.Path = "LDAP://OU=Specific Users,OU=All Users,OU=Users,DC=example,DC=com";

This would match the following AD hierarchy:

  • com
    • example
      • Users
        • All Users
          • Specific Users

Simply write the hierarchy from deepest to highest.

Now you can do plenty of things

For example search a user by account name and get the user's surname:

DirectoryEntry directoryEntry = new DirectoryEntry("LDAP://example.com");
DirectorySearcher searcher = new DirectorySearcher(directoryEntry) {
    PageSize = int.MaxValue,
    Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=AnAccountName))"
};

searcher.PropertiesToLoad.Add("sn");

var result = searcher.FindOne();

if (result == null) {
    return; // Or whatever you need to do in this case
}

string surname;

if (result.Properties.Contains("sn")) {
    surname = result.Properties["sn"][0].ToString();
}

Spring's overriding bean

Whether can we declare the same bean id in other xml for other reference e.x.

Servlet-Initialize.xml

<bean id="inheritedTestBean"   class="org.springframework.beans.TestBean">
  <property name="name" value="parent"/>
  <property name="age" value="1"/>
</bean>

Other xml (Document.xml)

<bean id="inheritedTestBean"  class="org.springframework.beans.Document">
  <property name="name" value="document"/>
  <property name="age" value="1"/>
</bean>

How do I select between the 1st day of the current month and current day in MySQL?

select * from table_name 
where (date between  DATE_ADD(LAST_DAY(DATE_SUB(CURDATE(), interval 30 day), interval 1 day) AND CURDATE() )

Or better :

select * from table_name 
where (date between  DATE_FORMAT(NOW() ,'%Y-%m-01') AND NOW() )

Allow scroll but hide scrollbar

Try this:

HTML:

<div id="container">
    <div id="content">
        // Content here
    </div>
</div>

CSS:

#container{
    height: 100%;
    width: 100%;
    overflow: hidden;
}

#content{
    width: 100%;
    height: 99%;
    overflow: auto;
    padding-right: 15px;
}

html, body{
    height: 99%;
    overflow:hidden;
}

JSFiddle Demo

Tested on FF and Safari.

Where do I call the BatchNormalization function in Keras?

It's almost become a trend now to have a Conv2D followed by a ReLu followed by a BatchNormalization layer. So I made up a small function to call all of them at once. Makes the model definition look a whole lot cleaner and easier to read.

def Conv2DReluBatchNorm(n_filter, w_filter, h_filter, inputs):
    return BatchNormalization()(Activation(activation='relu')(Convolution2D(n_filter, w_filter, h_filter, border_mode='same')(inputs)))

Python JSON serialize a Decimal object

I tried switching from simplejson to builtin json for GAE 2.7, and had issues with the decimal. If default returned str(o) there were quotes (because _iterencode calls _iterencode on the results of default), and float(o) would remove trailing 0.

If default returns an object of a class that inherits from float (or anything that calls repr without additional formatting) and has a custom __repr__ method, it seems to work like I want it to.

import json
from decimal import Decimal

class fakefloat(float):
    def __init__(self, value):
        self._value = value
    def __repr__(self):
        return str(self._value)

def defaultencode(o):
    if isinstance(o, Decimal):
        # Subclass float with custom repr?
        return fakefloat(o)
    raise TypeError(repr(o) + " is not JSON serializable")

json.dumps([10.20, "10.20", Decimal('10.20')], default=defaultencode)
'[10.2, "10.20", 10.20]'

How do I get the find command to print out the file size with the file name?

a simple solution is to use the -ls option in find:

find . -name \*.ear -ls

That gives you each entry in the normal "ls -l" format. Or, to get the specific output you seem to be looking for, this:

find . -name \*.ear -printf "%p\t%k KB\n"

Which will give you the filename followed by the size in KB.

Vertical Menu in Bootstrap

The "nav nav-list" class of Twiter Bootstrap 2.0 is handy for building a side bar.

You can see a lot of documentation at http://www.w3resource.com/twitter-bootstrap/nav-tabs-and-pills-tutorial.php

What is the difference between %g and %f in C?

As Unwind points out f and g provide different default outputs.

Roughly speaking if you care more about the details of what comes after the decimal point I would do with f and if you want to scale for large numbers go with g. From some dusty memories f is very nice with small values if your printing tables of numbers as everything stays lined up but something like g is needed if you stand a change of your numbers getting large and your layout matters. e is more useful when your numbers tend to be very small or very large but never near ten.

An alternative is to specify the output format so that you get the same number of characters representing your number every time.

Sorry for the woolly answer but it is a subjective out put thing that only gets hard answers if the number of characters generated is important or the precision of the represented value.

How can I check if a string contains ANY letters from the alphabet?

How about:

>>> string_1 = "(555).555-5555"
>>> string_2 = "(555) 555 - 5555 ext. 5555"
>>> any(c.isalpha() for c in string_1)
False
>>> any(c.isalpha() for c in string_2)
True

SQL Server 2008 - Case / If statements in SELECT Clause

The most obvious solutions are already listed. Depending on where the query is sat (i.e. in application code) you can't always use IF statements and the inline CASE statements can get painful where lots of columns become conditional. Assuming Col1 + Col3 + Col7 are the same type, and likewise Col2, Col4 + Col8 you can do this:

SELECT Col1, Col2 FROM tbl WHERE @Var LIKE 'xyz'
UNION ALL
SELECT Col3, Col4 FROM tbl WHERE @Var LIKE 'zyx'
UNION ALL
SELECT Col7, Col8 FROM tbl WHERE @Var NOT LIKE 'xyz' AND @Var NOT LIKE 'zyx'

As this is a single command there are several performance benefits with regard to plan caching. Also the Query Optimiser will quickly eliminate those statements where @Var doesn't match the appropriate value without touching the storage engine.

Eclipse shows errors but I can't find them

This happens from time to time in Eclipse. In the "Project" menu there's a "Clean" option, that usually takes care of the problem.