Programs & Examples On #Semweb

SemWeb is a Semantic Web/RDF library written in C# for Mono or Microsoft's .NET. The library can be used for reading and writing RDF (XML, N3), keeping RDF in persistent storage (memory, MySQL, etc.), querying persistent storage via simple graph matching and SPARQL, and making SPARQL queries to remote endpoints. Limited RDFS and general-purpose inferencing is also possible. SemWeb's API is straight-forward and flexible.

Native query with named parameter fails with "Not all named parameters have been set"

I use EclipseLink. This JPA allows the following way for the native queries:

Query q = em.createNativeQuery("SELECT * FROM mytable where username = ?username");
q.setParameter("username", "test");
q.getResultList();

Adding up BigDecimals using Streams

Original answer

Yes, this is possible:

List<BigDecimal> bdList = new ArrayList<>();
//populate list
BigDecimal result = bdList.stream()
        .reduce(BigDecimal.ZERO, BigDecimal::add);

What it does is:

  1. Obtain a List<BigDecimal>.
  2. Turn it into a Stream<BigDecimal>
  3. Call the reduce method.

    3.1. We supply an identity value for addition, namely BigDecimal.ZERO.

    3.2. We specify the BinaryOperator<BigDecimal>, which adds two BigDecimal's, via a method reference BigDecimal::add.

Updated answer, after edit

I see that you have added new data, therefore the new answer will become:

List<Invoice> invoiceList = new ArrayList<>();
//populate
Function<Invoice, BigDecimal> totalMapper = invoice -> invoice.getUnit_price().multiply(invoice.getQuantity());
BigDecimal result = invoiceList.stream()
        .map(totalMapper)
        .reduce(BigDecimal.ZERO, BigDecimal::add);

It is mostly the same, except that I have added a totalMapper variable, that has a function from Invoice to BigDecimal and returns the total price of that invoice.

Then I obtain a Stream<Invoice>, map it to a Stream<BigDecimal> and then reduce it to a BigDecimal.

Now, from an OOP design point I would advice you to also actually use the total() method, which you have already defined, then it even becomes easier:

List<Invoice> invoiceList = new ArrayList<>();
//populate
BigDecimal result = invoiceList.stream()
        .map(Invoice::total)
        .reduce(BigDecimal.ZERO, BigDecimal::add);

Here we directly use the method reference in the map method.

Aggregate / summarize multiple variables per group (e.g. sum, mean)

Interestingly, base R aggregate's data.frame method is not showcased here, above the formula interface is used, so for completeness:

aggregate(
  x = df1[c("x1", "x2")],
  by = df1[c("year", "month")],
  FUN = sum, na.rm = TRUE
)

More generic use of aggregate's data.frame method:

Since we are providing a

  • data.frame as x and
  • a list (data.frame is also a list) as by, this is very useful if we need to use it in a dynamic manner, e.g. using other columns to be aggregated and to aggregate by is very simple
  • also with custom-made aggregation functions

For example like so:

colsToAggregate <- c("x1")
aggregateBy <- c("year", "month")
dummyaggfun <- function(v, na.rm = TRUE) {
  c(sum = sum(v, na.rm = na.rm), mean = mean(v, na.rm = na.rm))
}

aggregate(df1[colsToAggregate], by = df1[aggregateBy], FUN = dummyaggfun)

How to read a text file directly from Internet using Java?

Using Apache Commons IO:

import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public static String readURLToString(String url) throws IOException
{
    try (InputStream inputStream = new URL(url).openStream())
    {
        return IOUtils.toString(inputStream, StandardCharsets.UTF_8);
    }
}

Add a new line to a text file in MS-DOS

Maybe this is what you want?

echo foo > test.txt
echo. >> test.txt
echo bar >> test.txt

results in the following within test.txt:

foo

bar

What is an instance variable in Java?

Instance variable is the variable declared inside a class, but outside a method: something like:

class IronMan {

    /** These are all instance variables **/
    public String realName;
    public String[] superPowers;
    public int age;

    /** Getters and setters here **/
}

Now this IronMan Class can be instantiated in another class to use these variables. Something like:

class Avengers {

    public static void main(String[] a) {
        IronMan ironman = new IronMan();
        ironman.realName = "Tony Stark";
        // or
        ironman.setAge(30);
    }

}

This is how we use the instance variables. Shameless plug: This example was pulled from this free e-book here here.

JavaScript - onClick to get the ID of the clicked button

With pure javascript you can do the following:

var buttons = document.getElementsByTagName("button");
var buttonsCount = buttons.length;
for (var i = 0; i < buttonsCount; i += 1) {
    buttons[i].onclick = function(e) {
        alert(this.id);
    };
}?

check it On JsFiddle

Detect HTTP or HTTPS then force HTTPS in JavaScript

It is not good idea because you just temporary redirect user to https and browser doesn't save this redirect.

You describe task for web-server (apache, nginx etc) http 301, http 302

How to shift a block of code left/right by one space in VSCode?

There was a feature request for that in vscode repo. But it was marked as extension-candidate and closed. So, here is the extension: Indent One space

Unlike the answer below that tells you to use Ctrl+[ this extension indents code by ONE whtespace ???.

enter image description here

Convert a String In C++ To Upper Case

Based on Kyle_the_hacker's -----> answer with my extras.

Ubuntu

In terminal List all locales
locale -a

Install all locales
sudo apt-get install -y locales locales-all

Compile main.cpp
$ g++ main.cpp

Run compiled program
$ ./a.out

Results

Zoë Saldaña played in La maldición del padre Cardona. ëèñ a? óóChloë
Zoë Saldaña played in La maldición del padre Cardona. ëèñ a? óóChloë
ZOË SALDAÑA PLAYED IN LA MALDICIÓN DEL PADRE CARDONA. ËÈÑ ?O ÓÓCHLOË
ZOË SALDAÑA PLAYED IN LA MALDICIÓN DEL PADRE CARDONA. ËÈÑ ?O ÓÓCHLOË
zoë saldaña played in la maldición del padre cardona. ëèñ a? óóchloë
zoë saldaña played in la maldición del padre cardona. ëèñ a? óóchloë

Ubuntu Linux - WSL from VSCODE

Ubuntu Linux - WSL

Windows

In cmd run VCVARS developer tools
"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"

Compile main.cpp
> cl /EHa main.cpp /D "_DEBUG" /D "_CONSOLE" /D "_UNICODE" /D "UNICODE" /std:c++17 /DYNAMICBASE "kernel32.lib" "user32.lib" "gdi32.lib" "winspool.lib" "comdlg32.lib" "advapi32.lib" "shell32.lib" "ole32.lib" "oleaut32.lib" "uuid.lib" "odbc32.lib" "odbccp32.lib" /MTd

Compilador de optimización de C/C++ de Microsoft (R) versión 19.27.29111 para x64
(C) Microsoft Corporation. Todos los derechos reservados.

main.cpp
Microsoft (R) Incremental Linker Version 14.27.29111.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:main.exe
main.obj
kernel32.lib
user32.lib
gdi32.lib
winspool.lib
comdlg32.lib
advapi32.lib
shell32.lib
ole32.lib
oleaut32.lib
uuid.lib
odbc32.lib
odbccp32.lib

Run main.exe
>main.exe

Results

Zoë Saldaña played in La maldición del padre Cardona. ëèñ a? óóChloë
Zoë Saldaña played in La maldición del padre Cardona. ëèñ a? óóChloë
ZOË SALDAÑA PLAYED IN LA MALDICIÓN DEL PADRE CARDONA. ËÈÑ ?O ÓÓCHLOË
ZOË SALDAÑA PLAYED IN LA MALDICIÓN DEL PADRE CARDONA. ËÈÑ ?O ÓÓCHLOË
zoë saldaña played in la maldición del padre cardona. ëèñ a? óóchloë
zoë saldaña played in la maldición del padre cardona. ëèñ a? óóchloë

Windows

The code - main.cpp

This code was only tested on Windows x64 and Ubuntu Linux x64.

/*
 * Filename: c:\Users\x\Cpp\main.cpp
 * Path: c:\Users\x\Cpp
 * Filename: /home/x/Cpp/main.cpp
 * Path: /home/x/Cpp
 * Created Date: Saturday, October 17th 2020, 10:43:31 pm
 * Author: Joma
 *
 * No Copyright 2020
 */


#include <iostream>
#include <set>
#include <string>
#include <locale>

// WINDOWS
#if (_WIN32)
#include <Windows.h>
#include <conio.h>
#define WINDOWS_PLATFORM 1
#define DLLCALL STDCALL
#define DLLIMPORT _declspec(dllimport)
#define DLLEXPORT _declspec(dllexport)
#define DLLPRIVATE
#define NOMINMAX

//EMSCRIPTEN
#elif defined(__EMSCRIPTEN__)
#include <emscripten/emscripten.h>
#include <emscripten/bind.h>
#include <unistd.h>
#include <termios.h>
#define EMSCRIPTEN_PLATFORM 1
#define DLLCALL
#define DLLIMPORT
#define DLLEXPORT __attribute__((visibility("default")))
#define DLLPRIVATE __attribute__((visibility("hidden")))

// LINUX - Ubuntu, Fedora, , Centos, Debian, RedHat
#elif (__LINUX__ || __gnu_linux__ || __linux__ || __linux || linux)
#define LINUX_PLATFORM 1
#include <unistd.h>
#include <termios.h>
#define DLLCALL CDECL
#define DLLIMPORT
#define DLLEXPORT __attribute__((visibility("default")))
#define DLLPRIVATE __attribute__((visibility("hidden")))
#define CoTaskMemAlloc(p) malloc(p)
#define CoTaskMemFree(p) free(p)

//ANDROID
#elif (__ANDROID__ || ANDROID)
#define ANDROID_PLATFORM 1
#define DLLCALL
#define DLLIMPORT
#define DLLEXPORT __attribute__((visibility("default")))
#define DLLPRIVATE __attribute__((visibility("hidden")))

//MACOS
#elif defined(__APPLE__)
#include <unistd.h>
#include <termios.h>
#define DLLCALL
#define DLLIMPORT
#define DLLEXPORT __attribute__((visibility("default")))
#define DLLPRIVATE __attribute__((visibility("hidden")))
#include "TargetConditionals.h"
#if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
#define IOS_SIMULATOR_PLATFORM 1
#elif TARGET_OS_IPHONE
#define IOS_PLATFORM 1
#elif TARGET_OS_MAC
#define MACOS_PLATFORM 1
#else

#endif

#endif



typedef std::string String;
typedef std::wstring WString;

#define EMPTY_STRING u8""s
#define EMPTY_WSTRING L""s

using namespace std::literals::string_literals;

class Strings
{
public:
    static String WideStringToString(const WString& wstr)
    {
        if (wstr.empty())
        {
            return String();
        }
        size_t pos;
        size_t begin = 0;
        String ret;

#if WINDOWS_PLATFORM
        int size;
        pos = wstr.find(static_cast<wchar_t>(0), begin);
        while (pos != WString::npos && begin < wstr.length())
        {
            WString segment = WString(&wstr[begin], pos - begin);
            size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &segment[0], segment.size(), NULL, 0, NULL, NULL);
            String converted = String(size, 0);
            WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &segment[0], segment.size(), &converted[0], converted.size(), NULL, NULL);
            ret.append(converted);
            ret.append({ 0 });
            begin = pos + 1;
            pos = wstr.find(static_cast<wchar_t>(0), begin);
        }
        if (begin <= wstr.length())
        {
            WString segment = WString(&wstr[begin], wstr.length() - begin);
            size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &segment[0], segment.size(), NULL, 0, NULL, NULL);
            String converted = String(size, 0);
            WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, &segment[0], segment.size(), &converted[0], converted.size(), NULL, NULL);
            ret.append(converted);
        }
#elif LINUX_PLATFORM || MACOS_PLATFORM || EMSCRIPTEN_PLATFORM
        size_t size;
        pos = wstr.find(static_cast<wchar_t>(0), begin);
        while (pos != WString::npos && begin < wstr.length())
        {
            WString segment = WString(&wstr[begin], pos - begin);
            size = wcstombs(nullptr, segment.c_str(), 0);
            String converted = String(size, 0);
            wcstombs(&converted[0], segment.c_str(), converted.size());
            ret.append(converted);
            ret.append({ 0 });
            begin = pos + 1;
            pos = wstr.find(static_cast<wchar_t>(0), begin);
        }
        if (begin <= wstr.length())
        {
            WString segment = WString(&wstr[begin], wstr.length() - begin);
            size = wcstombs(nullptr, segment.c_str(), 0);
            String converted = String(size, 0);
            wcstombs(&converted[0], segment.c_str(), converted.size());
            ret.append(converted);
        }
#else
        static_assert(false, "Unknown Platform");
#endif
        return ret;
    }

    static WString StringToWideString(const String& str)
    {
        if (str.empty())
        {
            return WString();
        }

        size_t pos;
        size_t begin = 0;
        WString ret;
#ifdef WINDOWS_PLATFORM
        int size = 0;
        pos = str.find(static_cast<char>(0), begin);
        while (pos != std::string::npos) {
            std::string segment = std::string(&str[begin], pos - begin);
            std::wstring converted = std::wstring(segment.size() + 1, 0);
            size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, &segment[0], segment.size(), &converted[0], converted.length());
            converted.resize(size);
            ret.append(converted);
            ret.append({ 0 });
            begin = pos + 1;
            pos = str.find(static_cast<char>(0), begin);
        }
        if (begin < str.length()) {
            std::string segment = std::string(&str[begin], str.length() - begin);
            std::wstring converted = std::wstring(segment.size() + 1, 0);
            size = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, segment.c_str(), segment.size(), &converted[0], converted.length());
            converted.resize(size);
            ret.append(converted);
        }

#elif LINUX_PLATFORM || MACOS_PLATFORM || EMSCRIPTEN_PLATFORM
        size_t size;
        pos = str.find(static_cast<char>(0), begin);
        while (pos != String::npos)
        {
            String segment = String(&str[begin], pos - begin);
            WString converted = WString(segment.size(), 0);
            size = mbstowcs(&converted[0], &segment[0], converted.size());
            converted.resize(size);
            ret.append(converted);
            ret.append({ 0 });
            begin = pos + 1;
            pos = str.find(static_cast<char>(0), begin);
        }
        if (begin < str.length())
        {
            String segment = String(&str[begin], str.length() - begin);
            WString converted = WString(segment.size(), 0);
            size = mbstowcs(&converted[0], &segment[0], converted.size());
            converted.resize(size);
            ret.append(converted);
        }
#else
        static_assert(false, "Unknown Platform");
#endif
        return ret;
    }


    static WString ToUpper(const WString& data)
    {
        WString result = data;
        auto& f = std::use_facet<std::ctype<wchar_t>>(std::locale());

        f.toupper(&result[0], &result[0] + result.size());
        return result;
    }

    static String  ToUpper(const String& data)
    {
        return WideStringToString(ToUpper(StringToWideString(data)));
    }

    static WString ToLower(const WString& data)
    {
        WString result = data;
        auto& f = std::use_facet<std::ctype<wchar_t>>(std::locale());
        f.tolower(&result[0], &result[0] + result.size());
        return result;
    }

    static String ToLower(const String& data)
    {
        return WideStringToString(ToLower(StringToWideString(data)));
    }

};

enum class ConsoleTextStyle
{
    DEFAULT = 0,
    BOLD = 1,
    FAINT = 2,
    ITALIC = 3,
    UNDERLINE = 4,
    SLOW_BLINK = 5,
    RAPID_BLINK = 6,
    REVERSE = 7,
};

enum class ConsoleForeground
{
    DEFAULT = 39,
    BLACK = 30,
    DARK_RED = 31,
    DARK_GREEN = 32,
    DARK_YELLOW = 33,
    DARK_BLUE = 34,
    DARK_MAGENTA = 35,
    DARK_CYAN = 36,
    GRAY = 37,
    DARK_GRAY = 90,
    RED = 91,
    GREEN = 92,
    YELLOW = 93,
    BLUE = 94,
    MAGENTA = 95,
    CYAN = 96,
    WHITE = 97
};

enum class ConsoleBackground
{
    DEFAULT = 49,
    BLACK = 40,
    DARK_RED = 41,
    DARK_GREEN = 42,
    DARK_YELLOW = 43,
    DARK_BLUE = 44,
    DARK_MAGENTA = 45,
    DARK_CYAN = 46,
    GRAY = 47,
    DARK_GRAY = 100,
    RED = 101,
    GREEN = 102,
    YELLOW = 103,
    BLUE = 104,
    MAGENTA = 105,
    CYAN = 106,
    WHITE = 107
};

class Console
{
private:
    static void EnableVirtualTermimalProcessing()
    {
#if defined WINDOWS_PLATFORM
        HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
        DWORD dwMode = 0;
        GetConsoleMode(hOut, &dwMode);
        if (!(dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING))
        {
            dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
            SetConsoleMode(hOut, dwMode);
        }
#endif
    }

    static void ResetTerminalFormat()
    {
        std::cout << u8"\033[0m";
    }

    static void SetVirtualTerminalFormat(ConsoleForeground foreground, ConsoleBackground background, std::set<ConsoleTextStyle> styles)
    {
        String format = u8"\033[";
        format.append(std::to_string(static_cast<int>(foreground)));
        format.append(u8";");
        format.append(std::to_string(static_cast<int>(background)));
        if (styles.size() > 0)
        {
            for (auto it = styles.begin(); it != styles.end(); ++it)
            {
                format.append(u8";");
                format.append(std::to_string(static_cast<int>(*it)));
            }
        }
        format.append(u8"m");
        std::cout << format;
    }
public:
    static void Clear()
    {

#ifdef WINDOWS_PLATFORM
        std::system(u8"cls");
#elif LINUX_PLATFORM || defined MACOS_PLATFORM
        std::system(u8"clear");
#elif EMSCRIPTEN_PLATFORM
        emscripten::val::global()["console"].call<void>(u8"clear");
#else
        static_assert(false, "Unknown Platform");
#endif
    }

    static void Write(const String& s, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})
    {
#ifndef EMSCRIPTEN_PLATFORM
        EnableVirtualTermimalProcessing();
        SetVirtualTerminalFormat(foreground, background, styles);
#endif
        String str = s;
#ifdef WINDOWS_PLATFORM
        WString unicode = Strings::StringToWideString(str);
        WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), unicode.c_str(), static_cast<DWORD>(unicode.length()), nullptr, nullptr);
#elif defined LINUX_PLATFORM || defined MACOS_PLATFORM || EMSCRIPTEN_PLATFORM
        std::cout << str;
#else
        static_assert(false, "Unknown Platform");
#endif

#ifndef EMSCRIPTEN_PLATFORM
        ResetTerminalFormat();
#endif
    }

    static void WriteLine(const String& s, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})
    {
        Write(s, foreground, background, styles);
        std::cout << std::endl;
    }

    static void Write(const WString& s, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})
    {
#ifndef EMSCRIPTEN_PLATFORM
        EnableVirtualTermimalProcessing();
        SetVirtualTerminalFormat(foreground, background, styles);
#endif
        WString str = s;

#ifdef WINDOWS_PLATFORM
        WriteConsole(GetStdHandle(STD_OUTPUT_HANDLE), str.c_str(), static_cast<DWORD>(str.length()), nullptr, nullptr);
#elif LINUX_PLATFORM || MACOS_PLATFORM || EMSCRIPTEN_PLATFORM
        std::cout << Strings::WideStringToString(str);
#else
        static_assert(false, "Unknown Platform");
#endif

#ifndef EMSCRIPTEN_PLATFORM
        ResetTerminalFormat();
#endif
    }

    static void WriteLine(const WString& s, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})
    {
        Write(s, foreground, background, styles);
        std::cout << std::endl;
    }

    static void WriteLine()
    {
        std::cout << std::endl;
    }

    static void Pause()
    {
        char c;
        do
        {
            c = getchar();
            std::cout << "Press Key " << std::endl;
        } while (c != 64);
        std::cout << "KeyPressed" << std::endl;
    }

    static int PauseAny(bool printWhenPressed = false, ConsoleForeground foreground = ConsoleForeground::DEFAULT, ConsoleBackground background = ConsoleBackground::DEFAULT, std::set<ConsoleTextStyle> styles = {})
    {
        int ch;
#ifdef WINDOWS_PLATFORM
        ch = _getch();
#elif LINUX_PLATFORM || MACOS_PLATFORM || EMSCRIPTEN_PLATFORM
        struct termios oldt, newt;
        tcgetattr(STDIN_FILENO, &oldt);
        newt = oldt;
        newt.c_lflag &= ~(ICANON | ECHO);
        tcsetattr(STDIN_FILENO, TCSANOW, &newt);
        ch = getchar();
        tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
#else
        static_assert(false, "Unknown Platform");
#endif
        if (printWhenPressed)
        {
            Console::Write(String(1, ch), foreground, background, styles);
        }
        return ch;
    }
};



int main()
{
    std::locale::global(std::locale(u8"en_US.UTF-8"));
    String dataStr = u8"Zoë Saldaña played in La maldición del padre Cardona. ëèñ a? óóChloë";
    WString dataWStr = L"Zoë Saldaña played in La maldición del padre Cardona. ëèñ a? óóChloë";
    std::string locale = u8"";
    //std::string locale = u8"de_DE.UTF-8";
    //std::string locale = u8"en_US.UTF-8";
    Console::WriteLine(dataStr);
    Console::WriteLine(dataWStr);
    dataStr = Strings::ToUpper(dataStr);
    dataWStr = Strings::ToUpper(dataWStr);
    Console::WriteLine(dataStr);
    Console::WriteLine(dataWStr);
    dataStr = Strings::ToLower(dataStr);
    dataWStr = Strings::ToLower(dataWStr);
    Console::WriteLine(dataStr);
    Console::WriteLine(dataWStr);
    
    
    Console::WriteLine(u8"Press any key to exit"s, ConsoleForeground::DARK_GRAY);
    Console::PauseAny();

    return 0;
}

Setting different color for each series in scatter plot on matplotlib

A MUCH faster solution for large dataset and limited number of colors is the use of Pandas and the groupby function:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import time


# a generic set of data with associated colors
nsamples=1000
x=np.random.uniform(0,10,nsamples)
y=np.random.uniform(0,10,nsamples)
colors={0:'r',1:'g',2:'b',3:'k'}
c=[colors[i] for i in np.round(np.random.uniform(0,3,nsamples),0)]

plt.close('all')

# "Fast" Scatter plotting
starttime=time.time()
# 1) make a dataframe
df=pd.DataFrame()
df['x']=x
df['y']=y
df['c']=c
plt.figure()
# 2) group the dataframe by color and loop
for g,b in df.groupby(by='c'):
    plt.scatter(b['x'],b['y'],color=g)
print('Fast execution time:', time.time()-starttime)

# "Slow" Scatter plotting
starttime=time.time()
plt.figure()
# 2) group the dataframe by color and loop
for i in range(len(x)):
    plt.scatter(x[i],y[i],color=c[i])
print('Slow execution time:', time.time()-starttime)

plt.show()

How to install a specific version of Node on Ubuntu?

It is possible to install specific version of nodejs from nodejs official distribution with using dpkg.

For example, currently recent 4.x version is 4.2.4, but you can install previous 4.2.3 version.

curl -s -O https://deb.nodesource.com/node_4.x/pool/main/n/nodejs/nodejs_4.2.3-1nodesource1~trusty1_amd64.deb
sudo apt-get install rlwrap
sudo dpkg -i nodejs_4.2.3-1nodesource1~trusty1_amd64.deb

ASP.Net MVC: How to display a byte array image from model

Something like this may work...

@{
    var base64 = Convert.ToBase64String(Model.ByteArray);
    var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
}

<img src="@imgSrc" />

As mentioned in the comments below, please use the above armed with the knowledge that although this may answer your question it may not solve your problem. Depending on your problem this may be the solution but I wouldn't completely rule out accessing the database twice.

Eclipse Java error: This selection cannot be launched and there are no recent launches

Have you checked if:

  1. You created a class file under src folder in your JAVA project?(not file)
  2. Did you name your class as the same name of your class file?

I am a newbie who try to run a helloworld example and just got the same error as yours, and these work for me.

How can I count text lines inside an DOM element? Can I?

Clone the container object and write 2 letters and calculate the height. This return the real height with all style applied, line height, etc. Now, calculate the height object / the size of a letter. In Jquery, the height excelude the padding, margin and border, it is great to calculate the real height of each line:

other = obj.clone();
other.html('a<br>b').hide().appendTo('body');
size = other.height() / 2;
other.remove();
lines = obj.height() /  size;

If you use a rare font with different height of each letter, this does not works. But works with all normal fonts, like Arial, mono, comics, Verdana, etc. Test with your font.

Example:

<div id="content" style="width: 100px">hello how are you? hello how are you? hello how are you?</div>
<script type="text/javascript">
$(document).ready(function(){

  calculate = function(obj){
    other = obj.clone();
    other.html('a<br>b').hide().appendTo('body');
    size = other.height() / 2;
    other.remove();
    return obj.height() /  size;
  }

  n = calculate($('#content'));
  alert(n + ' lines');
});
</script>

Result: 6 Lines

Works in all browser without rare functions out of standards.

Check: https://jsfiddle.net/gzceamtr/

Perform an action in every sub-directory using Bash

Handy one-liners

for D in *; do echo "$D"; done
for D in *; do find "$D" -type d; done ### Option A

find * -type d ### Option B

Option A is correct for folders with spaces in between. Also, generally faster since it doesn't print each word in a folder name as a separate entity.

# Option A
$ time for D in ./big_dir/*; do find "$D" -type d > /dev/null; done
real    0m0.327s
user    0m0.084s
sys     0m0.236s

# Option B
$ time for D in `find ./big_dir/* -type d`; do echo "$D" > /dev/null; done
real    0m0.787s
user    0m0.484s
sys     0m0.308s

Differences between SP initiated SSO and IDP initiated SSO

IDP Initiated SSO

From PingFederate documentation :- https://docs.pingidentity.com/bundle/pf_sm_supportedStandards_pf82/page/task/idpInitiatedSsoPOST.html

In this scenario, a user is logged on to the IdP and attempts to access a resource on a remote SP server. The SAML assertion is transported to the SP via HTTP POST.

Processing Steps:

  1. A user has logged on to the IdP.
  2. The user requests access to a protected SP resource. The user is not logged on to the SP site.
  3. Optionally, the IdP retrieves attributes from the user data store.
  4. The IdP’s SSO service returns an HTML form to the browser with a SAML response containing the authentication assertion and any additional attributes. The browser automatically posts the HTML form back to the SP.

SP Initiated SSO

From PingFederate documentation:- http://documentation.pingidentity.com/display/PF610/SP-Initiated+SSO--POST-POST

In this scenario a user attempts to access a protected resource directly on an SP Web site without being logged on. The user does not have an account on the SP site, but does have a federated account managed by a third-party IdP. The SP sends an authentication request to the IdP. Both the request and the returned SAML assertion are sent through the user’s browser via HTTP POST.

Processing Steps:

  1. The user requests access to a protected SP resource. The request is redirected to the federation server to handle authentication.
  2. The federation server sends an HTML form back to the browser with a SAML request for authentication from the IdP. The HTML form is automatically posted to the IdP’s SSO service.
  3. If the user is not already logged on to the IdP site or if re-authentication is required, the IdP asks for credentials (e.g., ID and password) and the user logs on.
  4. Additional information about the user may be retrieved from the user data store for inclusion in the SAML response. (These attributes are predetermined as part of the federation agreement between the IdP and the SP)

  5. The IdP’s SSO service returns an HTML form to the browser with a SAML response containing the authentication assertion and any additional attributes. The browser automatically posts the HTML form back to the SP. NOTE: SAML specifications require that POST responses be digitally signed.

  6. (Not shown) If the signature and assertion are valid, the SP establishes a session for the user and redirects the browser to the target resource.

D3 transform scale and translate

I realize this question is fairly old, but wanted to share a quick demo of group transforms, paths/shapes, and relative positioning, for anyone else who found their way here looking for more info:

http://bl.ocks.org/dustinlarimer/6050773

Converting Go struct to JSON

Related issue:

I was having trouble converting struct to JSON, sending it as response from Golang, then, later catch the same in JavaScript via Ajax.

Wasted a lot of time, so posting solution here.

In Go:

// web server

type Foo struct {
    Number int    `json:"number"`
    Title  string `json:"title"`
}

foo_marshalled, err := json.Marshal(Foo{Number: 1, Title: "test"})
fmt.Fprint(w, string(foo_marshalled)) // write response to ResponseWriter (w)

In JavaScript:

// web call & receive in "data", thru Ajax/ other

var Foo = JSON.parse(data);
console.log("number: " + Foo.number);
console.log("title: " + Foo.title);

how to convert object into string in php

In your case, you should simply use

$firstapiOutput->document_number

as the input for the second api.

How to change DatePicker dialog color for Android 5.0

You don't have create theme just write it in your dialog creation object

DatePickerDialog datePicker = new DatePickerDialog(getActivity(), AlertDialog.THEME_HOLO_LIGHT,this, mYear, mMonth, mDay);

follow this it will give you all type date picker style it's really work

http://www.android-examples.com/change-datepickerdialog-theme-in-android-using-dialogfragment/

How do I use Bash on Windows from the Visual Studio Code integrated terminal?

It depends on whether you have installed Git Bash in the current user only or all users:

If it is installed on all users then put "terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe" in your User Settings (Ctrl + Comma).

If it is installed on only the current user then put "terminal.integrated.shell.windows": "C:\\Users\\<name of your user>\\AppData\\Local\\Programs\\Git\\bin\\bash.exe" in your User Settings (Ctrl + Comma).

If the methods listed above do not work then you should try Christer's solution which says -

If you want the integrated environment you need to point to the sh.exe file inside the bin folder of your Git installation.

So the configuration should say C:\\<my-git-install>\\bin\\sh.exe.

Note: The sh.exe and bash.exe appear completely same to me. There should be no difference between them.

Setting DIV width and height in JavaScript

The onclick attribute of a button takes a string of JavaScript, not an href like you provided. Just remove the "javascript:" part.

Can two or more people edit an Excel document at the same time?

Unfortunately, the file must be locked for updates unless you're using Office 2010 and SharePoint 2010 together. This means that only one user per time can edit a file. The locking and version tracking capabilities of SharePoint are excellent, and this makes it a great tool for the type of collaboration you're talking about, but you would have to split documents into multiple files in order to extend the amount that could be edited at a time. For instance, we sometimes unmerge documents into technical, requirements, and financials sections so that the 3 experts required for the review can work concurrently. We then merge when everyone is finished.

How to fix SSL certificate error when running Npm on Windows?

TL;DR - Just run this and don't disable your security:

Replace existing certs

# Windows/MacOS/Linux 
npm config set cafile "<path to your certificate file>"

# Check the 'cafile'
npm config get cafile

or extend existing certs

Set this environment variable to extend pre-defined certs: NODE_EXTRA_CA_CERTS to "<path to certificate file>"

Full story

I've had to work with npm, pip, maven etc. behind a corporate firewall under Windows - it's not fun. I'll try and keep this platform agnostic/aware where possible.

HTTP_PROXY & HTTPS_PROXY

HTTP_PROXY & HTTPS_PROXY are environment variables used by lots of software to know where your proxy is. Under Windows, lots of software also uses your OS specified proxy which is a totally different thing. That means you can have Chrome (which uses the proxy specified in your Internet Options) connecting to the URL just fine, but npm, pip, maven etc. not working because they use HTTPS_PROXY (except when they use HTTP_PROXY - see later). Normally the environment variable would look something like:

http://proxy.example.com:3128

But you're getting a 403 which suggests you're not being authenticated against your proxy. If it is basic authentication on the proxy, you'll want to set the environment variable to something of the form:

http://user:[email protected]:3128

The dreaded NTLM

There is an HTTP status code 407 (proxy authentication required), which is the more correct way of saying it's the proxy rather than the destination server that's rejecting your request. That code plagued me for the longest time until after a lot of time on Google, I learned my proxy used NTLM authentication. HTTP basic authentication wasn't enough to satisfy whatever proxy my corporate overlords had installed. I resorted to using Cntlm on my local machine (unauthenticated), then had it handle the NTLM authentication with the upstream proxy. Then I had to tell all the programs that couldn't do NTLM to use my local machine as the proxy - which is generally as simple as setting HTTP_PROXY and HTTPS_PROXY. Otherwise, for npm use (as @Agus suggests):

npm config set proxy http://proxy.example.com:3128
npm config set https-proxy http://proxy.example.com:3128

"We need to decrypt all HTTPS traffic because viruses"

After this set-up had been humming along (clunkily) for about a year, the corporate overlords decided to change the proxy. Not only that, but it would no longer use NTLM! A brave new world to be sure. But because those writers of malicious software were now delivering malware via HTTPS, the only way they could protect we poor innocent users was to man-in-the-middle every connection to scan for threats before they even reached us. As you can imagine, I was overcome with the feeling of safety.

To cut a long story short, the self-signed certificate needs to be installed into npm to avoid SELF_SIGNED_CERT_IN_CHAIN:

npm config set cafile "<path to certificate file>"

Alternatively, the NODE_EXTRA_CA_CERTS environment variable can be set to the certificate file.

I think that's everything I know about getting npm to work behind a proxy/firewall. May someone find it useful.

Edit: It's a really common suggestion to turn off HTTPS for this problem either by using an HTTP registry or setting NODE_TLS_REJECT_UNAUTHORIZED. These are not good ideas because you're opening yourself up to further man-in-the-middle or redirection attacks. A quick spoof of your DNS records on the machine doing the package installation and you'll find yourself trusting packages from anywhere. It may seem like a lot of work to make HTTPS work, but it is highly recommended. When you're the one responsible for allowing untrusted code into the company, you'll understand why.

Edit 2: Keep in mind that setting npm config set cafile <path> causes npm to only use the certs provided in that file, instead of extending the existing ones with it.

If you want to extend the existing certs (e.g. with a company cert) using the environment variable NODE_EXTRA_CA_CERTS to link to the file is the way to go and can save you a lot of hassle. See how-to-add-custom-certificate-authority-ca-to-nodejs

How to change PHP version used by composer

Another possibility to make composer think you're using the correct version of PHP is to add to the config section of a composer.json file a platform option, like this:

"config": {
    "platform": {
        "php": "<ver>"
    }
},

Where <ver> is the PHP version of your choice.

Snippet from the docs:

Lets you fake platform packages (PHP and extensions) so that you can emulate a production env or define your target platform in the config. Example: {"php": "7.0.3", "ext-something": "4.0.3"}.

How to get current working directory in Java?

If you want to get your current working directory then use the following line

System.out.println(new File("").getAbsolutePath());

Multiline input form field using Bootstrap

I think the problem is that you are using type="text" instead of textarea. What you want is:

<textarea class="span6" rows="3" placeholder="What's up?" required></textarea>

To clarify, a type="text" will always be one row, where-as a textarea can be multiple.

Use CSS to make a span not clickable

In response to piemesons rant against jQuery, a Vanilla JavaScript(TM) solution (tested on FF and IE):

Put this in a script tag after your markup is loaded (right before the close of the body tag) and you'll get a similar effect to the jQuery example.

a = document.getElementsByTagName('a');
for (var i = 0; i < a.length;i++) {
  a[i].getElementsByTagName('span')[1].onclick = function() { return false;};
}

This will disable the click on every 2nd span inside of an a tag. You could also check the innerHTML of each span for "description", or set an attribute or class and check that.

How can you detect the version of a browser?

var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = '' + parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion, 10);
var nameOffset, verOffset, ix;

// In Opera 15+, the true version is after "OPR/" 
if ((verOffset = nAgt.indexOf("OPR/")) != -1) {
    browserName = "Opera";
    fullVersion = nAgt.substring(verOffset + 4);
}
// In older Opera, the true version is after "Opera" or after "Version"
else if ((verOffset = nAgt.indexOf("Opera")) != -1) {
    browserName = "Opera";
    fullVersion = nAgt.substring(verOffset + 6);
    if ((verOffset = nAgt.indexOf("Version")) != -1)
        fullVersion = nAgt.substring(verOffset + 8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset = nAgt.indexOf("MSIE")) != -1) {
    browserName = "Microsoft Internet Explorer";
    fullVersion = nAgt.substring(verOffset + 5);
}
// In Chrome, the true version is after "Chrome" 
else if ((verOffset = nAgt.indexOf("Chrome")) != -1) {
    browserName = "Google Chrome";
    fullVersion = nAgt.substring(verOffset + 7);
}
// In Safari, the true version is after "Safari" or after "Version" 
else if ((verOffset = nAgt.indexOf("Safari")) != -1) {
    browserName = "Safari";
    fullVersion = nAgt.substring(verOffset + 7);
    if ((verOffset = nAgt.indexOf("Version")) != -1)
        fullVersion = nAgt.substring(verOffset + 8);
}
// In Firefox, the true version is after "Firefox" 
else if ((verOffset = nAgt.indexOf("Firefox")) != -1) {
    browserName = "Mozilla Firefox";
    fullVersion = nAgt.substring(verOffset + 8);
}
// In most other browsers, "name/version" is at the end of userAgent 
else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt.lastIndexOf('/'))) {
    browserName = nAgt.substring(nameOffset, verOffset);
    fullVersion = nAgt.substring(verOffset + 1);
    if (browserName.toLowerCase() == browserName.toUpperCase()) {
        browserName = navigator.appName;
    }
}
// trim the fullVersion string at semicolon/space if present
if ((ix = fullVersion.indexOf(';')) != -1) fullVersion = fullVersion.substring(0, ix);
if ((ix = fullVersion.indexOf(' ')) != -1) fullVersion = fullVersion.substring(0, ix);

majorVersion = parseInt('' + fullVersion, 10);
if (isNaN(majorVersion)) {
    fullVersion = '' + parseFloat(navigator.appVersion);
    majorVersion = parseInt(navigator.appVersion, 10);
}

Publish to IIS, setting Environment Variable

To extend on @tredder's answer you can alter the environmentVariables using appcmd

Staging

%windir%\system32\inetsrv\appcmd set config "staging.example.com" /section:system.webServer/aspNetCore /+environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='Staging'] /commit:APPHOST

Production

%windir%\system32\inetsrv\appcmd set config "example.com" /section:system.webServer/aspNetCore /+environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='Production'] /commit:APPHOST

How to install python3 version of package via pip on Ubuntu?

Firstly, you need to install pip for the Python 3 installation that you want. Then you run that pip to install packages for that Python version.

Since you have both pip and python 3 in /usr/bin, I assume they are both installed with a package manager of some sort. That package manager should also have a Python 3 pip. That's the one you should install.

Felix' recommendation of virtualenv is a good one. If you are only testing, or you are doing development, then you shouldn't install the package in the system python. Using virtualenv, or even building your own Pythons for development, is better in those cases.

But if you actually do want to install this package in the system python, installing pip for Python 3 is the way to go.

JQuery Calculate Day Difference in 2 date textboxes

This is how I did it using the Math.floor() function:

var start = new Date($('#start').val());
var end = new Date($('#end').val());
var diff = Math.floor((end-start) / (365.25 * 24 * 60 * 60 * 1000));
console.log(diff);

You could also do it this way using the Math.round() function:

var start = new Date($('#start').val());
var end = new Date($('#end').val());
var diff = new Date(end - start) / (1000 * 60 * 60 * 24 * 365.25);
var age = Math.round(diff);
console.log(age);

How do I remove the old history from a git repository?

This method is easy to understand and works fine. The argument to the script ($1) is a reference (tag, hash, ...) to the commit starting from which you want to keep your history.

#!/bin/bash
git checkout --orphan temp $1 # create a new branch without parent history
git commit -m "Truncated history" # create a first commit on this branch
git rebase --onto temp $1 master # now rebase the part of master branch that we want to keep onto this branch
git branch -D temp # delete the temp branch

# The following 2 commands are optional - they keep your git repo in good shape.
git prune --progress # delete all the objects w/o references
git gc --aggressive # aggressively collect garbage; may take a lot of time on large repos

NOTE that old tags will still remain present; so you might need to remove them manually

remark: I know this is almost the same aswer as @yoyodin, but there are some important extra commands and informations here. I tried to edit the answer, but since it is a substantial change to @yoyodin's answer, my edit was rejected, so here's the information!

How can I get the class name from a C++ object?

You could try using "typeid".

This doesn't work for "object" name but YOU know the object name so you'll just have to store it somewhere. The Compiler doesn't care what you namned an object.

Its worth bearing in mind, though, that the output of typeid is a compiler specific thing so even if it produces what you are after on the current platform it may not on another. This may or may not be a problem for you.

The other solution is to create some kind of template wrapper that you store the class name in. Then you need to use partial specialisation to get it to return the correct class name for you. This has the advantage of working compile time but is significantly more complex.

Edit: Being more explicit

template< typename Type > class ClassName
{
public:
    static std::string name()
    {
        return "Unknown";
    }
};

Then for each class somethign liek the following:

template<> class ClassName<MyClass>
{
public:
    static std::string name()
    {
        return "MyClass";
    }
};

Which could even be macro'd as follows:

#define DefineClassName( className ) \
\
template<> class ClassName<className> \
{ \
public: \
    static std::string name() \
    { \
        return #className; \
    } \
}; \

Allowing you to, simply, do

DefineClassName( MyClass );

Finally to Get the class name you'd do the following:

ClassName< MyClass >::name();

Edit2: Elaborating further you'd then need to put this "DefineClassName" macro in each class you make and define a "classname" function that would call the static template function.

Edit3: And thinking about it ... Its obviously bad posting first thing in the morning as you may as well just define a member function "classname()" as follows:

std::string classname()
{
     return "MyClass";
}

which can be macro'd as follows:

DefineClassName( className ) \
std::string classname()  \
{ \
     return #className; \
}

Then you can simply just drop

DefineClassName( MyClass );

into the class as you define it ...

How do I see all foreign keys to a table or column?

Posting on an old answer to add some useful information.

I had a similar problem, but I also wanted to see the CONSTRAINT_TYPE along with the REFERENCED table and column names. So,

  1. To see all FKs in your table:

    USE '<yourschema>';
    
    SELECT i.TABLE_NAME, i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME 
    FROM information_schema.TABLE_CONSTRAINTS i 
    LEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME 
    WHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY' 
    AND i.TABLE_SCHEMA = DATABASE()
    AND i.TABLE_NAME = '<yourtable>';
    
  2. To see all the tables and FKs in your schema:

    USE '<yourschema>';
    
    SELECT i.TABLE_NAME, i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME 
    FROM information_schema.TABLE_CONSTRAINTS i 
    LEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME 
    WHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY' 
    AND i.TABLE_SCHEMA = DATABASE();
    
  3. To see all the FKs in your database:

    SELECT i.TABLE_SCHEMA, i.TABLE_NAME, i.CONSTRAINT_TYPE, i.CONSTRAINT_NAME, k.REFERENCED_TABLE_NAME, k.REFERENCED_COLUMN_NAME 
    FROM information_schema.TABLE_CONSTRAINTS i 
    LEFT JOIN information_schema.KEY_COLUMN_USAGE k ON i.CONSTRAINT_NAME = k.CONSTRAINT_NAME 
    WHERE i.CONSTRAINT_TYPE = 'FOREIGN KEY';
    

Remember!

This is using the InnoDB storage engine. If you can't seem to get any foreign keys to show up after adding them it's probably because your tables are using MyISAM.

To check:

SELECT * TABLE_NAME, ENGINE FROM information_schema.TABLES WHERE TABLE_SCHEMA = '<yourschema>';

To fix, use this:

ALTER TABLE `<yourtable>` ENGINE=InnoDB;

The remote end hung up unexpectedly while git cloning

I had a similar problem, but with a bamboo job. Bamboo was failing doing a local clone (local but over an SSH proxy) of a cached repository, I deleted the cache and after that it worked, but any time it tries to clone from the local cache there is a failure. Seems like a problem with bamboo's version of the SSH proxy not git per se.

convert php date to mysql format

You are looking for the the MySQL functions FROM_UNIXTIME() and UNIX_TIMESTAMP().

Use them in your SQL, e.g.:

mysql> SELECT UNIX_TIMESTAMP(NOW());
+-----------------------+
| UNIX_TIMESTAMP(NOW()) |
+-----------------------+
|            1311343579 |
+-----------------------+
1 row in set (0.00 sec)

mysql> SELECT FROM_UNIXTIME(1311343579);
+---------------------------+
| FROM_UNIXTIME(1311343579) |
+---------------------------+
| 2011-07-22 15:06:19       |
+---------------------------+
1 row in set (0.00 sec)

How to run Visual Studio post-build events for debug build only

Visual Studio 2015: The correct syntax is (keep it on one line):

if "$(ConfigurationName)"=="My Debug CFG" ( xcopy "$(TargetDir)test1.tmp" "$(TargetDir)test.xml" /y) else ( xcopy "$(TargetDir)test2.tmp" "$(TargetDir)test.xml" /y)

No error 255 here.

How to convert a plain object into an ES6 Map?

Do I really have to first convert it into an array of arrays of key-value pairs?

No, an iterator of key-value pair arrays is enough. You can use the following to avoid creating the intermediate array:

function* entries(obj) {
    for (let key in obj)
        yield [key, obj[key]];
}

const map = new Map(entries({foo: 'bar'}));
map.get('foo'); // 'bar'

Wait until all jQuery Ajax requests are done?

jQuery now defines a when function for this purpose.

It accepts any number of Deferred objects as arguments, and executes a function when all of them resolve.

That means, if you want to initiate (for example) four ajax requests, then perform an action when they are done, you could do something like this:

$.when(ajax1(), ajax2(), ajax3(), ajax4()).done(function(a1, a2, a3, a4){
    // the code here will be executed when all four ajax requests resolve.
    // a1, a2, a3 and a4 are lists of length 3 containing the response text,
    // status, and jqXHR object for each of the four ajax calls respectively.
});

function ajax1() {
    // NOTE:  This function must return the value 
    //        from calling the $.ajax() method.
    return $.ajax({
        url: "someUrl",
        dataType: "json",
        data:  yourJsonData,            
        ...
    });
}

In my opinion, it makes for a clean and clear syntax, and avoids involving any global variables such as ajaxStart and ajaxStop, which could have unwanted side effects as your page develops.

If you don't know in advance how many ajax arguments you need to wait for (i.e. you want to use a variable number of arguments), it can still be done but is just a little bit trickier. See Pass in an array of Deferreds to $.when() (and maybe jQuery .when troubleshooting with variable number of arguments).

If you need deeper control over the failure modes of the ajax scripts etc., you can save the object returned by .when() - it's a jQuery Promise object encompassing all of the original ajax queries. You can call .then() or .fail() on it to add detailed success/failure handlers.

Get filename in batch for loop

When Command Extensions are enabled (Windows XP and newer, roughly), you can use the syntax %~nF (where F is the variable and ~n is the request for its name) to only get the filename.

FOR /R C:\Directory %F in (*.*) do echo %~nF

should echo only the filenames.

How do I find out what type each object is in a ArrayList<Object>?

for (Object object : list) {
    System.out.println(object.getClass().getName());
}

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

Buttons with the btn class do not have underlines unless you are doing something wrong: In this case nesting <button> inside of <a>.

Something that I think you might be trying to do, is to create a bootstrap button without any decorations (underline, outline, button borders, etc). In other words, if your anchor is not a hyperlink, it is semantically a button.

Bootstrap's existing btn class appears to be the correct way to remove underline decorations from anchor buttons:

Use the button classes on an <a>, <button>, or <input> element

EDIT: Hitesh points out that btn will give you a shadow on :active. Thanks! I have modified my first example to use btn-link and incorporated the accepted answer's text-decoration: none to avoid this problem. Note that nesting a button inside of an anchor remains malformed html, a point which isn't addressed by any of the other answers.

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div>_x000D_
    <!-- use anchors for borderless buttons -->_x000D_
    <a href="#" class="btn btn-link" style="text-decoration: none">Text</a> _x000D_
    <a href="#" class="btn btn-link" style="text-decoration: none">Text</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Alternatively, for a regular button group using anchors:

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="btn-group">_x000D_
    <!-- use anchors for borderless buttons -->_x000D_
    <a href="#" class="btn btn-default">Text</a> _x000D_
    <a href="#" class="btn btn-default">Text</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

In other words, it should not be necessary to introduce your own nounderline class and/or custom styling as the other answers suggest. However, be aware of certain subtleties.


According to the HTML5 spec, <a><button>..</button></a> is illegal:

Content model: Transparent, but there must be no interactive content descendant.

...

Interactive content is content that is specifically intended for user interaction. a, audio (if the controls attribute is present), button, embed, iframe, img (if the usemap attribute is present), input (if the type attribute is not in the hidden state), keygen, label, object (if the usemap attribute is present), select, textarea, video (if the controls attribute is present)


P.S. If, conversely, you wanted a button that has underline decorations, you might have used btn-link. However, that should be rare - this is almost always just an anchor instead of a button!

How to convert current date into string in java?

public static Date getDateByString(String dateTime) {
        if(dateTime==null || dateTime.isEmpty()) {
            return null;
        }
        else{
            String modified = dateTime + ".000+0000";
            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
            Date dateObj = new Date();
            Date dateObj1 = new Date();
            try {
                if (dateTime != null) {
                    dateObj = formatter.parse(modified);
                }

            } catch (ParseException e) {
                e.printStackTrace();
            }

            return dateObj;
        }

    }

Simple Pivot Table to Count Unique Values

I found an easier way of doing this. Referring to Siddarth Rout's example, if I want to count unique values in column A:

  • add a new column C and fill C2 with formula "=1/COUNTIF($A:$A,A2)"
  • drag formula down to the rest of the column
  • pivot with column A as row label, and Sum{column C) in values to get the number of unique values in column A

json_encode is returning NULL?

The PHP.net recommended way of setting the charset is now this:

mysqli_set_charset('utf8')

Find and Replace Inside a Text File from a Bash Command

Be careful if you replace URLs with "/" character.

An example of how to do it:

sed -i "s%http://domain.com%http://www.domain.com/folder/%g" "test.txt"

Extracted from: http://www.sysadmit.com/2015/07/linux-reemplazar-texto-en-archivos-con-sed.html

How do I get the different parts of a Flask request's url?

You can examine the url through several Request fields:

Imagine your application is listening on the following application root:

http://www.example.com/myapplication

And a user requests the following URI:

http://www.example.com/myapplication/foo/page.html?x=y

In this case the values of the above mentioned attributes would be the following:

    path             /foo/page.html
    full_path        /foo/page.html?x=y
    script_root      /myapplication
    base_url         http://www.example.com/myapplication/foo/page.html
    url              http://www.example.com/myapplication/foo/page.html?x=y
    url_root         http://www.example.com/myapplication/

You can easily extract the host part with the appropriate splits.

How do I return a string from a regex match in python?

You should use re.MatchObject.group(0). Like

imtag = re.match(r'<img.*?>', line).group(0)

Edit:

You also might be better off doing something like

imgtag  = re.match(r'<img.*?>',line)
if imtag:
    print("yo it's a {}".format(imgtag.group(0)))

to eliminate all the Nones.

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

WIth the Help of @excray's comment, I manage to figure it out the answer, What we need to do is actually write a simple for loop to iterate over the two arrays that represent the train data and test data.

First implement a simple lambda function to hold formula for the cosine calculation:

cosine_function = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)

And then just write a simple for loop to iterate over the to vector, logic is for every "For each vector in trainVectorizerArray, you have to find the cosine similarity with the vector in testVectorizerArray."

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from nltk.corpus import stopwords
import numpy as np
import numpy.linalg as LA

train_set = ["The sky is blue.", "The sun is bright."] #Documents
test_set = ["The sun in the sky is bright."] #Query
stopWords = stopwords.words('english')

vectorizer = CountVectorizer(stop_words = stopWords)
#print vectorizer
transformer = TfidfTransformer()
#print transformer

trainVectorizerArray = vectorizer.fit_transform(train_set).toarray()
testVectorizerArray = vectorizer.transform(test_set).toarray()
print 'Fit Vectorizer to train set', trainVectorizerArray
print 'Transform Vectorizer to test set', testVectorizerArray
cx = lambda a, b : round(np.inner(a, b)/(LA.norm(a)*LA.norm(b)), 3)

for vector in trainVectorizerArray:
    print vector
    for testV in testVectorizerArray:
        print testV
        cosine = cx(vector, testV)
        print cosine

transformer.fit(trainVectorizerArray)
print
print transformer.transform(trainVectorizerArray).toarray()

transformer.fit(testVectorizerArray)
print 
tfidf = transformer.transform(testVectorizerArray)
print tfidf.todense()

Here is the output:

Fit Vectorizer to train set [[1 0 1 0]
 [0 1 0 1]]
Transform Vectorizer to test set [[0 1 1 1]]
[1 0 1 0]
[0 1 1 1]
0.408
[0 1 0 1]
[0 1 1 1]
0.816

[[ 0.70710678  0.          0.70710678  0.        ]
 [ 0.          0.70710678  0.          0.70710678]]

[[ 0.          0.57735027  0.57735027  0.57735027]]

How to select first parent DIV using jQuery?

Use .closest() to traverse up the DOM tree up to the specified selector.

var classes = $(this).parent().closest('div').attr('class').split(' '); // this gets the parent classes.

python max function using 'key' and lambda expression

How does the max function work?

It looks for the "largest" item in an iterable. I'll assume that you can look up what that is, but if not, it's something you can loop over, i.e. a list or string.

What is use of the keyword key in max function? I know it is also used in context of sort function

Key is a lambda function that will tell max which objects in the iterable are larger than others. Say if you were sorting some object that you created yourself, and not something obvious, like integers.

Meaning of the lambda expression? How to read them? How do they work?

That's sort of a larger question. In simple terms, a lambda is a function you can pass around, and have other pieces of code use it. Take this for example:

def sum(a, b, f):
    return (f(a) + f(b))

This takes two objects, a and b, and a function f. It calls f() on each object, then adds them together. So look at this call:

>>> sum(2, 2, lambda a:  a * 2)
8

sum() takes 2, and calls the lambda expression on it. So f(a) becomes 2 * 2, which becomes 4. It then does this for b, and adds the two together.

In not so simple terms, lambdas come from lambda calculus, which is the idea of a function that returns a function; a very cool math concept for expressing computation. You can read about that here, and then actually understand it here.

It's probably better to read about this a little more, as lambdas can be confusing, and it's not immediately obvious how useful they are. Check here.

The following untracked working tree files would be overwritten by merge, but I don't care

If this is a one-time operation, you could just remove all untracked files from the working directory before doing the pull. Read How to remove local (untracked) files from the current Git working tree? for information on how to remove all untracked files.

Be sure to not accidentally remove untracked file that you still need ;)

submit the form using ajax

I would like to add a new pure javascript way to do this, which in my opinion is much cleaner, by using the fetch() API. This a modern way to implements network requests. In your case, since you already have a form element we can simply use it to build our request.

const formInputs = oForm.getElementsByTagName("input");
let formData = new FormData();
for (let input of formInputs) {
    formData.append(input.name, input.value);
}

fetch(oForm.action,
    {
        method: oForm.method,
        body: formData
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.log(error.message))
    .finally(() => console.log("Done"));

As you can see it is very clean and much less verbose to use than XMLHttpRequest.

How can I get terminal output in python?

The recommended way in Python 3.5 and above is to use subprocess.run():

from subprocess import run
output = run("pwd", capture_output=True).stdout

Tell Ruby Program to Wait some amount of time

This is an example of using sleep with sidekiq

require 'sidekiq'

class PlainOldRuby
  include Sidekiq::Worker

  def perform(how_hard="super hard", how_long=10)
    sleep how_long
    puts "Workin' #{how_hard}"
  end
end

sleep for 10 seconds and print out "Working super hard" .

Selecting an element in iFrame jQuery

Take a look at this post: http://praveenbattula.blogspot.com/2009/09/access-iframe-content-using-jquery.html

$("#iframeID").contents().find("[tokenid=" + token + "]").html();

Place your selector in the find method.

This may not be possible however if the iframe is not coming from your server. Other posts talk about permission denied errors.

jQuery/JavaScript: accessing contents of an iframe

Select 50 items from list at random to write to file

I think random.choice() is a better option.

import numpy as np

mylist = [13,23,14,52,6,23]

np.random.choice(mylist, 3, replace=False)

the function returns an array of 3 randomly chosen values from the list

Finding all possible combinations of numbers to reach a given sum

Here is a better version with better output formatting and C++ 11 features:

void subset_sum_rec(std::vector<int> & nums, const int & target, std::vector<int> & partialNums) 
{
    int currentSum = std::accumulate(partialNums.begin(), partialNums.end(), 0);
    if (currentSum > target)
        return;
    if (currentSum == target) 
    {
        std::cout << "sum([";
        for (auto it = partialNums.begin(); it != std::prev(partialNums.end()); ++it)
            cout << *it << ",";
        cout << *std::prev(partialNums.end());
        std::cout << "])=" << target << std::endl;
    }
    for (auto it = nums.begin(); it != nums.end(); ++it) 
    {
        std::vector<int> remaining;
        for (auto it2 = std::next(it); it2 != nums.end(); ++it2)
            remaining.push_back(*it2);

        std::vector<int> partial = partialNums;
        partial.push_back(*it);
        subset_sum_rec(remaining, target, partial);
    }
}

How do you add PostgreSQL Driver as a dependency in Maven?

Depending on your PostgreSQL version you would need to add the postgresql driver to your pom.xml file.

For PostgreSQL 9.1 this would be:

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <name>Your project name.</name>
    <dependencies>
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>
    </dependencies>
</project>

You can get the code for the dependency (as well as any other dependency) from maven's central repository

If you are using postgresql 9.2+:

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <name>Your project name.</name>
    <dependencies>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.1</version>
        </dependency>
    </dependencies>
</project>

You can check the latest versions and dependency snippets from:

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I would like to add an example of prototypical inheritance with javascript to @Scott Driscoll answer. We'll be using classical inheritance pattern with Object.create() which is a part of EcmaScript 5 specification.

First we create "Parent" object function

function Parent(){

}

Then add a prototype to "Parent" object function

 Parent.prototype = {
 primitive : 1,
 object : {
    one : 1
   }
}

Create "Child" object function

function Child(){

}

Assign child prototype (Make child prototype inherit from parent prototype)

Child.prototype = Object.create(Parent.prototype);

Assign proper "Child" prototype constructor

Child.prototype.constructor = Child;

Add method "changeProps" to a child prototype, which will rewrite "primitive" property value in Child object and change "object.one" value both in Child and Parent objects

Child.prototype.changeProps = function(){
    this.primitive = 2;
    this.object.one = 2;
};

Initiate Parent (dad) and Child (son) objects.

var dad = new Parent();
var son = new Child();

Call Child (son) changeProps method

son.changeProps();

Check the results.

Parent primitive property did not change

console.log(dad.primitive); /* 1 */

Child primitive property changed (rewritten)

console.log(son.primitive); /* 2 */

Parent and Child object.one properties changed

console.log(dad.object.one); /* 2 */
console.log(son.object.one); /* 2 */

Working example here http://jsbin.com/xexurukiso/1/edit/

More info on Object.create here https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/create

How to add a linked source folder in Android Studio?

While sourceSets allows you to include entire directory structures, there's no way to exclude parts of it in Android Studio (as of version 1.2), as described here: Android Studio Exclude Class from build?

Until Android Studio gets updated to support include/exclude directives for Android sources, Symlinks work quite well. If you're using Windows, native tools such as junction or mklink can accomplish the equivalent of Un*x symlinks. CygWin can also create these with a little coersion. See: Git Symlinks in Windows and How to make symbolic link with cygwin in Windows 7

How to call two methods on button's onclick method in HTML or JavaScript?

The modern event handling method:

element.addEventListener('click', startDragDrop, false);
element.addEventListener('click', spyOnUser, false);

The first argument is the event, the second is the function and the third specifies whether to allow event bubbling.

From QuirksMode:

W3C’s DOM Level 2 Event specification pays careful attention to the problems of the traditional model. It offers a simple way to register as many event handlers as you like for the same event on one element.

The key to the W3C event registration model is the method addEventListener(). You give it three arguments: the event type, the function to be executed and a boolean (true or false) that I’ll explain later on. To register our well known doSomething() function to the onclick of an element you do:

Full details here: http://www.quirksmode.org/js/events_advanced.html

Using jQuery

if you're using jQuery, there is a nice API for event handling:

$('#myElement').bind('click', function() { doStuff(); });
$('#myElement').bind('click', function() { doMoreStuff(); });
$('#myElement').bind('click', doEvenMoreStuff);

Full details here: http://api.jquery.com/category/events/

How to reset db in Django? I get a command 'reset' not found error

if you are using Django 2.0 Then

python manage.py flush 

will work

How do I determine the current operating system with Node.js

when you are using 32bits node on 64bits windows(like node-webkit or atom-shell developers), process.platform will echo win32

use

    function isOSWin64() {
      return process.arch === 'x64' || process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432');
    }

(check here for details)

How to deal with SettingWithCopyWarning in Pandas

For me this issue occured in a following >simplified< example. And I was also able to solve it (hopefully with a correct solution):

old code with warning:

def update_old_dataframe(old_dataframe, new_dataframe):
    for new_index, new_row in new_dataframe.iterrorws():
        old_dataframe.loc[new_index] = update_row(old_dataframe.loc[new_index], new_row)

def update_row(old_row, new_row):
    for field in [list_of_columns]:
        # line with warning because of chain indexing old_dataframe[new_index][field]
        old_row[field] = new_row[field]  
    return old_row

This printed the warning for the line old_row[field] = new_row[field]

Since the rows in update_row method are actually type Series, I replaced the line with:

old_row.at[field] = new_row.at[field]

i.e. method for accessing/lookups for a Series. Eventhough both works just fine and the result is same, this way I don't have to disable the warnings (=keep them for other chain indexing issues somewhere else).

I hope this may help someone.

How can getContentResolver() be called in Android?

Access contentResolver in Kotlin , inside activities, Object classes &... :

Application().contentResolver

What is the difference between an int and an Integer in Java and C#?

In java as per my knowledge if you learner then, when you write int a; then in java generic it will compile code like Integer a = new Integer(). So,as per generics Integer is not used but int is used. so there is so such difference there.

multiple prints on the same line in Python

Found this Quora post, with this example which worked for me (python 3), which was closer to what I needed it for (i.e. erasing the whole previous line).

The example they provide:

def clock():
   while True:
       print(datetime.now().strftime("%H:%M:%S"), end="\r")

For printing the on the same line, as others have suggested, just use end=""

How to close existing connections to a DB

in restore wizard click "close existing connections to destination database"

in Detach Database wizard click "Drop connection" item.

Java SecurityException: signer information does not match

In my case it was a package name conflict. Current project and signed referenced library had one package in common package.foo.utils. Just changed the current project error-prone package name to something else.

What is the difference between $routeProvider and $stateProvider?

Both do the same work as they are used for routing purposes in SPA(Single Page Application).

1. Angular Routing - per $routeProvider docs

URLs to controllers and views (HTML partials). It watches $location.url() and tries to map the path to an existing route definition.

HTML

<div ng-view></div>

Above tag will render the template from the $routeProvider.when() condition which you had mentioned in .config (configuration phase) of angular

Limitations:-

  • The page can only contain single ng-view on page
  • If your SPA has multiple small components on the page that you wanted to render based on some conditions, $routeProvider fails. (to achieve that, we need to use directives like ng-include, ng-switch, ng-if, ng-show, which looks bad to have them in SPA)
  • You can not relate between two routes like parent and child relationship.
  • You cannot show and hide a part of the view based on url pattern.

2. ui-router - per $stateProvider docs

AngularUI Router is a routing framework for AngularJS, which allows you to organize the parts of your interface into a state machine. UI-Router is organized around states, which may optionally have routes, as well as other behavior, attached.

Multiple & Named Views

Another great feature is the ability to have multiple ui-views in a template.

While multiple parallel views are a powerful feature, you'll often be able to manage your interfaces more effectively by nesting your views, and pairing those views with nested states.

HTML

<div ui-view>
    <div ui-view='header'></div>
    <div ui-view='content'></div>
    <div ui-view='footer'></div>
</div>

The majority of ui-router's power is it can manage nested state & views.

Pros

  • You can have multiple ui-view on single page
  • Various views can be nested in each other and maintained by defining state in routing phase.
  • We can have child & parent relationship here, simply like inheritance in state, also you could define sibling states.
  • You could change the ui-view="some" of state just by using absolute routing using @ with state name.
  • Another way you could do relative routing is by using only @ to change ui-view="some". This will replace the ui-view rather than checking if it is nested or not.
  • Here you could use ui-sref to create a href URL dynamically on the basis of URL mentioned in a state, also you could give a state params in the json format.

For more Information Angular ui-router

For better flexibility with various nested view with states, I'd prefer you to go for ui-router

Difference between const reference and normal parameter

The difference is more prominent when you are passing a big struct/class.

struct MyData {
    int a,b,c,d,e,f,g,h;
    long array[1234];
};
void DoWork(MyData md);
void DoWork(const MyData& md);

when you use use 'normal' parameter, you pass the parameter by value and hence creating a copy of the parameter you pass. if you are using const reference, you pass it by reference and the original data is not copied.

in both cases, the original data cannot be modified from inside the function.

EDIT:
In certain cases, the original data might be able to get modified as pointed out by Charles Bailey in his answer.

How to switch from POST to GET in PHP CURL

Add this before calling curl_exec($curl_handle)

curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, 'GET');

java collections - keyset() vs entrySet() in map

Every time you call itr2.next() you are getting a distinct value. Not the same value. You should only call this once in the loop.

Iterator<String> itr2 = keys.iterator();
    while(itr2.hasNext()){
        String v = itr2.next();
        System.out.println("Key: "+v+" ,value: "+m.get(v));
    }

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

ClassNotFoundException com.mysql.jdbc.Driver

You should download MariaDB connector.
Then:

  1. Expand your project.
  2. Right-click on Libraries.
  3. Select Add Jar/Folder.
  4. Add mariadb-java-client-2.0.2.jar which you just downloaded.

Handle ModelState Validation in ASP.NET Web API

You can also throw exceptions as documented here: http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx

Note, to do what that article suggests, remember to include System.Net.Http

Rails: Can't verify CSRF token authenticity when making a POST request

Cross site request forgery (CSRF/XSRF) is when a malicious web page tricks users into performing a request that is not intended for example by using bookmarklets, iframes or just by creating a page which is visually similar enough to fool users.

The Rails CSRF protection is made for "classical" web apps - it simply gives a degree of assurance that the request originated from your own web app. A CSRF token works like a secret that only your server knows - Rails generates a random token and stores it in the session. Your forms send the token via a hidden input and Rails verifies that any non GET request includes a token that matches what is stored in the session.

However an API is usually by definition cross site and meant to be used in more than your web app, which means that the whole concept of CSRF does not quite apply.

Instead you should use a token based strategy of authenticating API requests with an API key and secret since you are verifying that the request comes from an approved API client - not from your own app.

You can deactivate CSRF as pointed out by @dcestari:

class ApiController < ActionController::Base
  protect_from_forgery with: :null_session
end

Updated. In Rails 5 you can generate API only applications by using the --api option:

rails new appname --api

They do not include the CSRF middleware and many other components that are superflouus.

How to delete multiple files at once in Bash on Linux?

If you want to delete all files whose names match a particular form, a wildcard (glob pattern) is the most straightforward solution. Some examples:

$ rm -f abc.log.*             # Remove them all
$ rm -f abc.log.2012*         # Remove all logs from 2012
$ rm -f abc.log.2012-0[123]*  # Remove all files from the first quarter of 2012

Regular expressions are more powerful than wildcards; you can feed the output of grep to rm -f. For example, if some of the file names start with "abc.log" and some with "ABC.log", grep lets you do a case-insensitive match:

$ rm -f $(ls | grep -i '^abc\.log\.')

This will cause problems if any of the file names contain funny characters, including spaces. Be careful.

When I do this, I run the ls | grep ... command first and check that it produces the output I want -- especially if I'm using rm -f:

$ ls | grep -i '^abc\.log\.'
(check that the list is correct)
$ rm -f $(!!)

where !! expands to the previous command. Or I can type up-arrow or Ctrl-P and edit the previous line to add the rm -f command.

This assumes you're using the bash shell. Some other shells, particularly csh and tcsh and some older sh-derived shells, may not support the $(...) syntax. You can use the equivalent backtick syntax:

$ rm -f `ls | grep -i '^abc\.log\.'`

The $(...) syntax is easier to read, and if you're really ambitious it can be nested.

Finally, if the subset of files you want to delete can't be easily expressed with a regular expression, a trick I often use is to list the files to a temporary text file, then edit it:

$ ls > list
$ vi list   # Use your favorite text editor

I can then edit the list file manually, leaving only the files I want to remove, and then:

$ rm -f $(<list)

or

$ rm -f `cat list`

(Again, this assumes none of the file names contain funny characters, particularly spaces.)

Or, when editing the list file, I can add rm -f to the beginning of each line and then:

$ . ./list

or

$ source ./list

Editing the file is also an opportunity to add quotes where necessary, for example changing rm -f foo bar to rm -f 'foo bar' .

How to get last inserted id?

I had the same need and found this answer ..

This creates a record in the company table (comp), it the grabs the auto ID created on the company table and drops that into a Staff table (staff) so the 2 tables can be linked, MANY staff to ONE company. It works on my SQL 2008 DB, should work on SQL 2005 and above.

===========================

CREATE PROCEDURE [dbo].[InsertNewCompanyAndStaffDetails]

 @comp_name varchar(55) = 'Big Company',

 @comp_regno nchar(8) = '12345678',

 @comp_email nvarchar(50) = '[email protected]',

 @recID INT OUTPUT

-- The '@recID' is used to hold the Company auto generated ID number that we are about to grab

AS
 Begin

  SET NOCOUNT ON

  DECLARE @tableVar TABLE (tempID INT)

-- The line above is used to create a tempory table to hold the auto generated ID number for later use. It has only one field 'tempID' and its type INT is the same as the '@recID'.

  INSERT INTO comp(comp_name, comp_regno, comp_email) 

  OUTPUT inserted.comp_id INTO @tableVar

-- The 'OUTPUT inserted.' line above is used to grab data out of any field in the record it is creating right now. This data we want is the ID autonumber. So make sure it says the correct field name for your table, mine is 'comp_id'. This is then dropped into the tempory table we created earlier.

  VALUES (@comp_name, @comp_regno, @comp_email)

  SET @recID = (SELECT tempID FROM @tableVar)

-- The line above is used to search the tempory table we created earlier where the ID we need is saved. Since there is only one record in this tempory table, and only one field, it will only select the ID number you need and drop it into '@recID'. '@recID' now has the ID number you want and you can use it how you want like i have used it below.

  INSERT INTO staff(Staff_comp_id) 
  VALUES (@recID)

 End

-- So there you go. You can actually grab what ever you want in the 'OUTPUT inserted.WhatEverFieldNameYouWant' line and create what fields you want in your tempory table and access it to use how ever you want.

I was looking for something like this for ages, with this detailed break down, I hope this helps.

How to fix an UnsatisfiedLinkError (Can't find dependent libraries) in a JNI project

When calling System.loadLibrary(), the JVM will look on the java.library.path for your native library. However, if that native library declares any dependencies on other native libraries, then the operating system will be tasked with finding those native library dependencies.

Since the operating system has no concept of the java.library.path, it will not see any directories you place on the java.library.path. Instead, it will only search the directories on PATH environment variable of the operating system. This is totally fine if the native library dependency is an operating system native library because it will be found on the PATH. However, if the native library dependency is a native library that you or someone else created, then it will not be found on the PATH unless you place it there. This behavior is strange, unexpected, and not well documented, but it is documented in the OpenJDK issue tracker here. You can also find another StackOverflow answer reinforcing this explanation, here.

So, you have a couple of options. You could either load each native library in the correct dependency order using System.loadLibrary(), or you could modify the PATH to include the directories where your native libraries are stored.

How to convert object array to string array in Java

Another alternative to System.arraycopy:

String[] stringArray = Arrays.copyOf(objectArray, objectArray.length, String[].class);

Creating a new empty branch for a new project

On base this answer from Hiery Nomus.

You can create a branch as an orphan:

git checkout --orphan <branchname>

This will create a new branch with no parents. Then, you can clear the working directory with:

git rm --cached -r .

And then you just commit branch with empty commit and then push

git commit -m <commit message> --allow-empty
git push origin <newbranch>

Label axes on Seaborn Barplot

Seaborn's barplot returns an axis-object (not a figure). This means you can do the following:

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fake = pd.DataFrame({'cat': ['red', 'green', 'blue'], 'val': [1, 2, 3]})
ax = sns.barplot(x = 'val', y = 'cat', 
              data = fake, 
              color = 'black')
ax.set(xlabel='common xlabel', ylabel='common ylabel')
plt.show()

How to create batch file in Windows using "start" with a path and command with spaces

Escaping the path with apostrophes is correct, but the start command takes a parameter containing the title of the new window. This parameter is detected by the surrounding apostrophes, so your application is not executed.

Try something like this:

start "Dummy Title" "c:\path with spaces\app.exe" param1 "param with spaces"

not None test in Python

The best bet with these types of questions is to see exactly what python does. The dis module is incredibly informative:

>>> import dis
>>> dis.dis("val != None")
  1           0 LOAD_NAME                0 (val)
              2 LOAD_CONST               0 (None)
              4 COMPARE_OP               3 (!=)
              6 RETURN_VALUE
>>> dis.dis("not (val is None)")
  1           0 LOAD_NAME                0 (val)
              2 LOAD_CONST               0 (None)
              4 COMPARE_OP               9 (is not)
              6 RETURN_VALUE
>>> dis.dis("val is not None")
  1           0 LOAD_NAME                0 (val)
              2 LOAD_CONST               0 (None)
              4 COMPARE_OP               9 (is not)
              6 RETURN_VALUE

Notice that the last two cases reduce to the same sequence of operations, Python reads not (val is None) and uses the is not operator. The first uses the != operator when comparing with None.

As pointed out by other answers, using != when comparing with None is a bad idea.

Powershell: count members of a AD group

easy way to do it: To get the actual user count:

$ADInfo = Get-ADGroup -Identity '<groupname>' -Properties Members
$AdInfo.Members.Count

and you get the count easily, it is pretty fast as well for 20k+ users too

In Android, how do I set margins in dp programmatically?

Best way ever:

private void setMargins (View view, int left, int top, int right, int bottom) {
    if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
        p.setMargins(left, top, right, bottom);
        view.requestLayout();
    }
}

How to call method:

setMargins(mImageView, 50, 50, 50, 50);

Hope this will help you.

Accessing SQL Database in Excel-VBA

I've added the Initial Catalog to your connection string. I've also abandonded the ADODB.Command syntax in favor of simply creating my own SQL statement and open the recordset on that variable.

Hope this helps.

Sub GetDataFromADO()
    'Declare variables'
        Set objMyConn = New ADODB.Connection
        Set objMyRecordset = New ADODB.Recordset
        Dim strSQL As String

    'Open Connection'
        objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=MyDatabase;User ID=abc;Password=abc;"
        objMyConn.Open

    'Set and Excecute SQL Command'
        strSQL = "select * from myTable"

    'Open Recordset'
        Set objMyRecordset.ActiveConnection = objMyConn
        objMyRecordset.Open strSQL            

    'Copy Data to Excel'
        ActiveSheet.Range("A1").CopyFromRecordset (objMyRecordset)

End Sub

XML Schema minOccurs / maxOccurs default values

Short answer:

As written in xsd:

<xs:attribute name="minOccurs" type="xs:nonNegativeInteger" use="optional" default="1"/>
<xs:attribute name="maxOccurs" type="xs:allNNI" use="optional" default="1"/>

If you provide an attribute with number, then the number is boundary. Otherwise attribute should appear exactly once.

Parse DateTime string in JavaScript

refs: http://momentjs.com/docs/#/parsing/string/

If you use moment.js, you can use "string" + "format" mode

moment(String, String);
moment(String, String, String);
moment(String, String, Boolean);
moment(String, String, String, Boolean);

ex:

moment("12-25-1995", "MM-DD-YYYY");

How do I tell Maven to use the latest version of a dependency?

The dependencies syntax is located at the Dependency Version Requirement Specification documentation. Here it is is for completeness:

Dependencies' version element define version requirements, used to compute effective dependency version. Version requirements have the following syntax:

  • 1.0: "Soft" requirement on 1.0 (just a recommendation, if it matches all other ranges for the dependency)
  • [1.0]: "Hard" requirement on 1.0
  • (,1.0]: x <= 1.0
  • [1.2,1.3]: 1.2 <= x <= 1.3
  • [1.0,2.0): 1.0 <= x < 2.0
  • [1.5,): x >= 1.5
  • (,1.0],[1.2,): x <= 1.0 or x >= 1.2; multiple sets are comma-separated
  • (,1.1),(1.1,): this excludes 1.1 (for example if it is known not to work in combination with this library)

In your case, you could do something like <version>[1.2.3,)</version>

IOCTL Linux device driver

An ioctl, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.

An alternative is the sysfs interface, where you set up a file under /sys/ and read/write that to get information from and to the driver. An example of how to set this up:

static ssize_t mydrvr_version_show(struct device *dev,
        struct device_attribute *attr, char *buf)
{
    return sprintf(buf, "%s\n", DRIVER_RELEASE);
}

static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);

And during driver setup:

device_create_file(dev, &dev_attr_version);

You would then have a file for your device in /sys/, for example, /sys/block/myblk/version for a block driver.

Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl or libnl3 libraries.

Execute jar file with multiple classpath libraries from command prompt

Regardless of the OS the below command should work:

java -cp "MyJar.jar;lib/*" com.mainClass

Always use quotes and please take attention that lib/*.jar will not work.

How do I read and parse an XML file in C#?

  public void ReadXmlFile()
    {
        string path = HttpContext.Current.Server.MapPath("~/App_Data"); // Finds the location of App_Data on server.
        XmlTextReader reader = new XmlTextReader(System.IO.Path.Combine(path, "XMLFile7.xml")); //Combines the location of App_Data and the file name
        while (reader.Read())
        {
            switch (reader.NodeType)
            {
                case XmlNodeType.Element:
                    break;
                case XmlNodeType.Text:
                    columnNames.Add(reader.Value);
                    break;
                case XmlNodeType.EndElement:
                    break;
            }
        }
    }

You can avoid the first statement and just specify the path name in constructor of XmlTextReader.

Python: Continuing to next iteration in outer loop

I think you could do something like this:

for ii in range(200):
    restart = False
    for jj in range(200, 400):
        ...block0...
        if something:
            restart = True
            break
    if restart:
        continue
    ...block1...

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

I had the same problem and I did it this way

//note that I added jquery separately above this

<!--ENJOY HINT PACKAGES --START -->
<link href="path/enjoyhint/jquery.enjoyhint.css" rel="stylesheet">
<script src="path/enjoyhint/jquery.enjoyhint.js"></script>
<script src="path/enjoyhint/kinetic.min.js"></script>
<script src="path/enjoyhint/enjoyhint.js"></script>  
<!--ENJOY HINT PACKAGES --END -->

and it works

Running MSBuild fails to read SDKToolsPath

Besides the registry mods, you may need to change version of the .net sdk your settings set to in Visual Studio.

I was having this problem and decided to check the project debug settings.

Project => Toolbar Properties => Debug Advance Compile Options button

The Target Framework (all configurations) was set to 3.0 which is not on my system.

I changed that to 4.0, then had to restart the project and Visual Studio 2010.

The project then built without errors and ran.

How do I convert a string to a double in Python?

Be aware that if your string number contains more than 15 significant digits float(s) will round it.In those cases it is better to use Decimal

Here is an explanation and some code samples: https://docs.python.org/3/library/sys.html#sys.float_info

How to read json file into java with simple JSON library

Hope this example helps too

I have done java coding in a similar way for the below json array example as follows :

following is the json data format : stored as "EMPJSONDATA.json"

[{"EMPNO":275172,"EMP_NAME":"Rehan","DOB":"29-02-1992","DOJ":"10-06-2013","ROLE":"JAVA DEVELOPER"},

{"EMPNO":275173,"EMP_NAME":"G.K","DOB":"10-02-1992","DOJ":"11-07-2013","ROLE":"WINDOWS ADMINISTRATOR"},

{"EMPNO":275174,"EMP_NAME":"Abiram","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}

{"EMPNO":275174,"EMP_NAME":"Mohamed Mushi","DOB":"10-04-1992","DOJ":"12-08-2013","ROLE":"PROJECT ANALYST"}]

public class Jsonminiproject {

public static void main(String[] args) {

      JSONParser parser = new JSONParser();

    try {
        JSONArray a = (JSONArray) parser.parse(new FileReader("F:/JSON DATA/EMPJSONDATA.json"));
        for (Object o : a)
        {
            JSONObject employee = (JSONObject) o;

            Long no = (Long) employee.get("EMPNO");
            System.out.println("Employee Number : " + no);

            String st = (String) employee.get("EMP_NAME");
            System.out.println("Employee Name : " + st);

            String dob = (String) employee.get("DOB");
            System.out.println("Employee DOB : " + dob);

            String doj = (String) employee.get("DOJ");
            System.out.println("Employee DOJ : " + doj);

            String role = (String) employee.get("ROLE");
            System.out.println("Employee Role : " + role);

            System.out.println("\n");

        }


    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }




}

}

Change input value onclick button - pure javascript or jQuery

Another simple solution for this case using jQuery. Keep in mind it's not a good practice to use inline javascript.

JsFiddle

I've added IDs to html on the total price and on the buttons. Here is the jQuery.

$('#two').click(function(){
    $('#count').val('2');
    $('#total').text('Product price: $1000');
});

$('#four').click(function(){
    $('#count').val('4');
    $('#total').text('Product price: $2000');
});

Why does the 260 character path length limit exist in Windows?

It does, and it is a default for some reason, but you could easily override it with this registry key:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\FileSystem]
"LongPathsEnabled"=dword:00000001

See: https://blogs.msdn.microsoft.com/jeremykuhne/2016/07/30/net-4-6-2-and-long-paths-on-windows-10/

Finding the position of bottom of a div with jquery

The bottom is the top + the outerHeight, not the height, as it wouldn't include the margin or padding.

var $bot,
    top,
    bottom;
$bot = $('#bottom');
top = $bot.position().top;
bottom = top + $bot.outerHeight(true); //true is necessary to include the margins

error: expected primary-expression before ')' token (C)

A function call needs to be performed with objects. You are doing the equivalent of this:

// function declaration/definition
void foo(int) {}

// function call
foo(int); // wat!??

i.e. passing a type where an object is required. This makes no sense in C or C++. You need to be doing

int i = 42;
foo(i);

or

foo(42);

jQuery set radio button

In my case, radio button value is fetched from database and then set into the form. Following code works for me.

$("input[name=name_of_radio_button_fields][value=" + saved_value_comes_from_database + "]").prop('checked', true);

Can anyone explain me StandardScaler?

The answers above are great, but I needed a simple example to alleviate some concerns that I have had in the past. I wanted to make sure it was indeed treating each column separately. I am now reassured and can't find what example had caused me concern. All columns ARE scaled separately as described by those above.

CODE

import pandas as pd
import scipy.stats as ss
from sklearn.preprocessing import StandardScaler


data= [[1, 1, 1, 1, 1],[2, 5, 10, 50, 100],[3, 10, 20, 150, 200],[4, 15, 40, 200, 300]]

df = pd.DataFrame(data, columns=['N0', 'N1', 'N2', 'N3', 'N4']).astype('float64')

sc_X = StandardScaler()
df = sc_X.fit_transform(df)

num_cols = len(df[0,:])
for i in range(num_cols):
    col = df[:,i]
    col_stats = ss.describe(col)
    print(col_stats)

OUTPUT

DescribeResult(nobs=4, minmax=(-1.3416407864998738, 1.3416407864998738), mean=0.0, variance=1.3333333333333333, skewness=0.0, kurtosis=-1.3599999999999999)
DescribeResult(nobs=4, minmax=(-1.2828087129930659, 1.3778315806221817), mean=-5.551115123125783e-17, variance=1.3333333333333337, skewness=0.11003776770595125, kurtosis=-1.394993095506219)
DescribeResult(nobs=4, minmax=(-1.155344148338584, 1.53471088361394), mean=0.0, variance=1.3333333333333333, skewness=0.48089217736510326, kurtosis=-1.1471008824318165)
DescribeResult(nobs=4, minmax=(-1.2604572012883055, 1.2668071116222517), mean=-5.551115123125783e-17, variance=1.3333333333333333, skewness=0.0056842140599118185, kurtosis=-1.6438177182479734)
DescribeResult(nobs=4, minmax=(-1.338945389819976, 1.3434309690153527), mean=5.551115123125783e-17, variance=1.3333333333333333, skewness=0.005374558840039456, kurtosis=-1.3619131970819205)

NOTE:

The scipy.stats module is correctly reporting the "sample" variance, which uses (n - 1) in the denominator. The "population" variance would use n in the denominator for the calculation of variance. To understand better, please see the code below that uses scaled data from the first column of the data set above:

Code

import scipy.stats as ss

sc_Data = [[-1.34164079], [-0.4472136], [0.4472136], [1.34164079]]
col_stats = ss.describe([-1.34164079, -0.4472136, 0.4472136, 1.34164079])
print(col_stats)
print()

mean_by_hand = 0
for row in sc_Data:
    for element in row:
        mean_by_hand += element
mean_by_hand /= 4

variance_by_hand = 0
for row in sc_Data:
    for element in row:
        variance_by_hand += (mean_by_hand - element)**2
sample_variance_by_hand = variance_by_hand / 3
sample_std_dev_by_hand = sample_variance_by_hand ** 0.5

pop_variance_by_hand = variance_by_hand / 4
pop_std_dev_by_hand = pop_variance_by_hand ** 0.5

print("Sample of Population Calcs:")
print(mean_by_hand, sample_variance_by_hand, sample_std_dev_by_hand, '\n')
print("Population Calcs:")
print(mean_by_hand, pop_variance_by_hand, pop_std_dev_by_hand)

Output

DescribeResult(nobs=4, minmax=(-1.34164079, 1.34164079), mean=0.0, variance=1.3333333422778562, skewness=0.0, kurtosis=-1.36000000429325)

Sample of Population Calcs:
0.0 1.3333333422778562 1.1547005422523435

Population Calcs:
0.0 1.000000006708392 1.000000003354196

What does the star operator mean, in a function call?

The single star * unpacks the sequence/collection into positional arguments, so you can do this:

def sum(a, b):
    return a + b

values = (1, 2)

s = sum(*values)

This will unpack the tuple so that it actually executes as:

s = sum(1, 2)

The double star ** does the same, only using a dictionary and thus named arguments:

values = { 'a': 1, 'b': 2 }
s = sum(**values)

You can also combine:

def sum(a, b, c, d):
    return a + b + c + d

values1 = (1, 2)
values2 = { 'c': 10, 'd': 15 }
s = sum(*values1, **values2)

will execute as:

s = sum(1, 2, c=10, d=15)

Also see section 4.7.4 - Unpacking Argument Lists of the Python documentation.


Additionally you can define functions to take *x and **y arguments, this allows a function to accept any number of positional and/or named arguments that aren't specifically named in the declaration.

Example:

def sum(*values):
    s = 0
    for v in values:
        s = s + v
    return s

s = sum(1, 2, 3, 4, 5)

or with **:

def get_a(**values):
    return values['a']

s = get_a(a=1, b=2)      # returns 1

this can allow you to specify a large number of optional parameters without having to declare them.

And again, you can combine:

def sum(*values, **options):
    s = 0
    for i in values:
        s = s + i
    if "neg" in options:
        if options["neg"]:
            s = -s
    return s

s = sum(1, 2, 3, 4, 5)            # returns 15
s = sum(1, 2, 3, 4, 5, neg=True)  # returns -15
s = sum(1, 2, 3, 4, 5, neg=False) # returns 15

DLL Load Library - Error Code 126

This error can happen because some MFC library (eg. mfc120.dll) from which the DLL is dependent is missing in windows/system32 folder.

Multiple select in Visual Studio?

I couldn't find anything built in, which is sad. There is this functionality in CodeRush though.

With Notepad++, this feature comes in built in. Just turn on multi-editing from

Setting > Preferences > Editing > Multi-Editing Settings

But its not as intuitive as MS Word which lets you select two words by double clicking on them (after Ctrl of course).

Vue.js data-bind style backgroundImage not working

Binding background image style using a dynamic value from v-for loop could be done like this.

<div v-for="i in items" :key="n" 
  :style="{backgroundImage: 'url('+require('./assets/cars/'+i.src+'.jpg')+')'}">
</div>

How to convert image to byte array

To be convert the image to byte array.The code is give below.

public byte[] ImageToByteArray(System.Drawing.Image images)
{
   using (var _memorystream = new MemoryStream())
   {
      images.Save(_memorystream ,images.RawFormat);
      return  _memorystream .ToArray();
   }
}

To be convert the Byte array to Image.The code is given below.The code is handle A Generic error occurred in GDI+ in Image Save.

public void SaveImage(string base64String, string filepath)
{
    // image convert to base64string is base64String 
    //File path is which path to save the image.
    var bytess = Convert.FromBase64String(base64String);
    using (var imageFile = new FileStream(filepath, FileMode.Create))
    {
        imageFile.Write(bytess, 0, bytess.Length);
        imageFile.Flush();
    }
}

PHP preg replace only allow numbers

Try this:

return preg_replace("/[^0-9]/", "",$c);

How do I align views at the bottom of the screen?

Use android:layout_alignParentBottom="true" in your <RelativeLayout>.

This will definitely help.

Auto-click button element on page load using jQuery

You would simply use jQuery like so...

<script>
jQuery(function(){
   jQuery('#modal').click();
});
</script>

Use the click function to auto-click the #modal button

What is deserialize and serialize in JSON?

Explanation of Serialize and Deserialize using Python

In python, pickle module is used for serialization. So, the serialization process is called pickling in Python. This module is available in Python standard library.

Serialization using pickle

import pickle

#the object to serialize
example_dic={1:"6",2:"2",3:"f"}

#where the bytes after serializing end up at, wb stands for write byte
pickle_out=open("dict.pickle","wb")
#Time to dump
pickle.dump(example_dic,pickle_out)
#whatever you open, you must close
pickle_out.close()

The PICKLE file (can be opened by a text editor like notepad) contains this (serialized data):

€}q (KX 6qKX 2qKX fqu.

Deserialization using pickle

import pickle

pickle_in=open("dict.pickle","rb")
get_deserialized_data_back=pickle.load(pickle_in)

print(get_deserialized_data_back)

Output:

{1: '6', 2: '2', 3: 'f'}

MINGW64 "make build" error: "bash: make: command not found"

Try using cmake itself. In the build directory, run:

cmake --build .

Regular expression for excluding special characters

I guess it depends what language you are targeting. In general, something like this should work:

[^<>%$]

The "[]" construct defines a character class, which will match any of the listed characters. Putting "^" as the first character negates the match, ie: any character OTHER than one of those listed.

You may need to escape some of the characters within the "[]", depending on what language/regex engine you are using.

Why does ENOENT mean "No such file or directory"?

It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.

It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.

Is there an addHeaderView equivalent for RecyclerView?

you can create addHeaderView and use

adapter.addHeaderView(View).

This code build the addHeaderView for more then one header. the headers should have:

android:layout_height="wrap_content"

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private static final int TYPE_ITEM = -1;
    public class MyViewSHolder extends RecyclerView.ViewHolder {
        public MyViewSHolder (View view) {
            super(view);
        }
        // put you code. for example:
        View mView;
        ...
    }

    public class ViewHeader extends RecyclerView.ViewHolder {
        public ViewHeader(View view) {
            super(view);
        }
    }

    private List<View> mHeaderViews = new ArrayList<>();
    public void addHeaderView(View headerView) {
        mHeaderViews.add(headerView);
    }

    @Override
    public int getItemCount() {
       return ... + mHeaderViews.size();
    }

    @Override
    public int getItemViewType(int position) {
        if (mHeaderViews.size() > position) {
            return position;
        }

        return TYPE_ITEM;
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (viewType != TYPE_ITEM) {
            //inflate your layout and pass it to view holder
            return new ViewHeader(mHeaderViews.get(viewType));
        }
        ...
    }
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int basePosition1) {
        if (holder instanceof ViewHeader) {
            return;
        }
        int basePosition = basePosition1 -  mHeaderViews.size();
        ...
    }
}

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

use -n parameter to install like for cocoapods:

sudo gem install cocoapods -n /usr/local/bin

C#: How to add subitems in ListView

Create a listview item

ListViewItem item1 = new ListViewItem("sdasdasdasd", 0)
item1.SubItems.Add("asdasdasd")

Is it possible to get the current spark context settings in PySpark?

Spark 2.1+

spark.sparkContext.getConf().getAll() where spark is your sparksession (gives you a dict with all configured settings)

How to select the first row for each group in MySQL?

Yet another way to do it

Select max from group that works in views

SELECT * FROM action a 
WHERE NOT EXISTS (
   SELECT 1 FROM action a2 
   WHERE a2.user_id = a.user_id 
   AND a2.action_date > a.action_date 
   AND a2.action_type = a.action_type
)
AND a.action_type = "CF"

How to stash my previous commit?

I solving doing this:

Remove the target commit

git revert --strategy resolve 222

Save commit 222 to patch file

git diff HEAD~2 HEAD~1 > 222.patch

Apply this patch to unstage

patch -p1 < 222.patch

Push to stash

git stash

Remove temp file

rm -f 222.patch

Very simple strategy in my opinion

How to check the extension of a filename in a bash script?

I wrote a bash script that looks at the type of a file then copies it to a location, I use it to look through the videos I've watched online from my firefox cache:

#!/bin/bash
# flvcache script

CACHE=~/.mozilla/firefox/xxxxxxxx.default/Cache
OUTPUTDIR=~/Videos/flvs
MINFILESIZE=2M

for f in `find $CACHE -size +$MINFILESIZE`
do
    a=$(file $f | cut -f2 -d ' ')
    o=$(basename $f)
    if [ "$a" = "Macromedia" ]
        then
            cp "$f" "$OUTPUTDIR/$o"
    fi
done

nautilus  "$OUTPUTDIR"&

It uses similar ideas to those presented here, hope this is helpful to someone.

SQL-Server: Is there a SQL script that I can use to determine the progress of a SQL Server backup or restore process?

Here's a simple script that generally does the trick for me:

SELECT command, percent_complete,total_elapsed_time, estimated_completion_time, start_time
  FROM sys.dm_exec_requests
  WHERE command IN ('RESTORE DATABASE','BACKUP DATABASE') 

General error: 1364 Field 'user_id' doesn't have a default value

In my case, the error was because I had not declared the field in my $fillable array in the model. Well, it seems to be something basic, but for us who started with laravel it could work.

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

  1. The reason this is failing is because (Python 3) input returns a string. To convert it to an integer, use int(some_string).

  2. You do not typically keep track of indices manually in Python. A better way to implement such a function would be

    def cat_n_times(s, n):
        for i in range(n):
            print(s) 
    
    text = input("What would you like the computer to repeat back to you: ")
    num = int(input("How many times: ")) # Convert to an int immediately.
    
    cat_n_times(text, num)
    
  3. I changed your API above a bit. It seems to me that n should be the number of times and s should be the string.

What's the better (cleaner) way to ignore output in PowerShell?

I just did some tests of the four options that I know about.

Measure-Command {$(1..1000) | Out-Null}

TotalMilliseconds : 76.211

Measure-Command {[Void]$(1..1000)}

TotalMilliseconds : 0.217

Measure-Command {$(1..1000) > $null}

TotalMilliseconds : 0.2478

Measure-Command {$null = $(1..1000)}

TotalMilliseconds : 0.2122

## Control, times vary from 0.21 to 0.24
Measure-Command {$(1..1000)}

TotalMilliseconds : 0.2141

So I would suggest that you use anything but Out-Null due to overhead. The next important thing, to me, would be readability. I kind of like redirecting to $null and setting equal to $null myself. I use to prefer casting to [Void], but that may not be as understandable when glancing at code or for new users.

I guess I slightly prefer redirecting output to $null.

Do-Something > $null

Edit

After stej's comment again, I decided to do some more tests with pipelines to better isolate the overhead of trashing the output.

Here are some tests with a simple 1000 object pipeline.

## Control Pipeline
Measure-Command {$(1..1000) | ?{$_ -is [int]}}

TotalMilliseconds : 119.3823

## Out-Null
Measure-Command {$(1..1000) | ?{$_ -is [int]} | Out-Null}

TotalMilliseconds : 190.2193

## Redirect to $null
Measure-Command {$(1..1000) | ?{$_ -is [int]} > $null}

TotalMilliseconds : 119.7923

In this case, Out-Null has about a 60% overhead and > $null has about a 0.3% overhead.

Addendum 2017-10-16: I originally overlooked another option with Out-Null, the use of the -inputObject parameter. Using this the overhead seems to disappear, however the syntax is different:

Out-Null -inputObject ($(1..1000) | ?{$_ -is [int]})

And now for some tests with a simple 100 object pipeline.

## Control Pipeline
Measure-Command {$(1..100) | ?{$_ -is [int]}}

TotalMilliseconds : 12.3566

## Out-Null
Measure-Command {$(1..100) | ?{$_ -is [int]} | Out-Null}

TotalMilliseconds : 19.7357

## Redirect to $null
Measure-Command {$(1..1000) | ?{$_ -is [int]} > $null}

TotalMilliseconds : 12.8527

Here again Out-Null has about a 60% overhead. While > $null has an overhead of about 4%. The numbers here varied a bit from test to test (I ran each about 5 times and picked the middle ground). But I think it shows a clear reason to not use Out-Null.

How to easily initialize a list of Tuples?

    var colors = new[]
    {
        new { value = Color.White, name = "White" },
        new { value = Color.Silver, name = "Silver" },
        new { value = Color.Gray, name = "Gray" },
        new { value = Color.Black, name = "Black" },
        new { value = Color.Red, name = "Red" },
        new { value = Color.Maroon, name = "Maroon" },
        new { value = Color.Yellow, name = "Yellow" },
        new { value = Color.Olive, name = "Olive" },
        new { value = Color.Lime, name = "Lime" },
        new { value = Color.Green, name = "Green" },
        new { value = Color.Aqua, name = "Aqua" },
        new { value = Color.Teal, name = "Teal" },
        new { value = Color.Blue, name = "Blue" },
        new { value = Color.Navy, name = "Navy" },
        new { value = Color.Pink, name = "Pink" },
        new { value = Color.Fuchsia, name = "Fuchsia" },
        new { value = Color.Purple, name = "Purple" }
    };
    foreach (var color in colors)
    {
        stackLayout.Children.Add(
            new Label
            {
                Text = color.name,
                TextColor = color.value,
            });
        FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label))
    }

this is a Tuple<Color, string>

JPA OneToMany not deleting child

@Entity 
class Employee {
     @OneToOne(orphanRemoval=true)
     private Address address;
}

See here.

What is __pycache__?

Execution of a python script would cause the byte code to be generated in memory and kept until the program is shutdown. In case a module is imported, for faster reusability, Python would create a cache .pyc (PYC is 'Python' 'Compiled') file where the byte code of the module being imported is cached. Idea is to speed up loading of python modules by avoiding re-compilation ( compile once, run multiple times policy ) when they are re-imported.

The name of the file is the same as the module name. The part after the initial dot indicates Python implementation that created the cache (could be CPython) followed by its version number.

Looping through list items with jquery

You can use each for this:

$('#productList li').each(function(i, li) {
  var $product = $(li);  
  // your code goes here
});

That being said - are you sure you want to be updating the values to be +1 each time? Couldn't you just find the count and then set the values based on that?

Sorting an array of objects by property values

While it is a bit of an overkill for just sorting a single array, this prototype function allows to sort Javascript arrays by any key, in ascending or descending order, including nested keys, using dot syntax.

(function(){
    var keyPaths = [];

    var saveKeyPath = function(path) {
        keyPaths.push({
            sign: (path[0] === '+' || path[0] === '-')? parseInt(path.shift()+1) : 1,
            path: path
        });
    };

    var valueOf = function(object, path) {
        var ptr = object;
        for (var i=0,l=path.length; i<l; i++) ptr = ptr[path[i]];
        return ptr;
    };

    var comparer = function(a, b) {
        for (var i = 0, l = keyPaths.length; i < l; i++) {
            aVal = valueOf(a, keyPaths[i].path);
            bVal = valueOf(b, keyPaths[i].path);
            if (aVal > bVal) return keyPaths[i].sign;
            if (aVal < bVal) return -keyPaths[i].sign;
        }
        return 0;
    };

    Array.prototype.sortBy = function() {
        keyPaths = [];
        for (var i=0,l=arguments.length; i<l; i++) {
            switch (typeof(arguments[i])) {
                case "object": saveKeyPath(arguments[i]); break;
                case "string": saveKeyPath(arguments[i].match(/[+-]|[^.]+/g)); break;
            }
        }
        return this.sort(comparer);
    };    
})();

Usage:

var data = [
    { name: { first: 'Josh', last: 'Jones' }, age: 30 },
    { name: { first: 'Carlos', last: 'Jacques' }, age: 19 },
    { name: { first: 'Carlos', last: 'Dante' }, age: 23 },
    { name: { first: 'Tim', last: 'Marley' }, age: 9 },
    { name: { first: 'Courtney', last: 'Smith' }, age: 27 },
    { name: { first: 'Bob', last: 'Smith' }, age: 30 }
]

data.sortBy('age'); // "Tim Marley(9)", "Carlos Jacques(19)", "Carlos Dante(23)", "Courtney Smith(27)", "Josh Jones(30)", "Bob Smith(30)"

Sorting by nested properties with dot-syntax or array-syntax:

data.sortBy('name.first'); // "Bob Smith(30)", "Carlos Dante(23)", "Carlos Jacques(19)", "Courtney Smith(27)", "Josh Jones(30)", "Tim Marley(9)"
data.sortBy(['name', 'first']); // "Bob Smith(30)", "Carlos Dante(23)", "Carlos Jacques(19)", "Courtney Smith(27)", "Josh Jones(30)", "Tim Marley(9)"

Sorting by multiple keys:

data.sortBy('name.first', 'age'); // "Bob Smith(30)", "Carlos Jacques(19)", "Carlos Dante(23)", "Courtney Smith(27)", "Josh Jones(30)", "Tim Marley(9)"
data.sortBy('name.first', '-age'); // "Bob Smith(30)", "Carlos Dante(23)", "Carlos Jacques(19)", "Courtney Smith(27)", "Josh Jones(30)", "Tim Marley(9)"

You can fork the repo: https://github.com/eneko/Array.sortBy

AWS - Disconnected : No supported authentication methods available (server sent :publickey)

I am using OpsWorks and wanted to register a new existing Linux instance from my Windows machine on AWS Cli.

Frist problem was, that I had to use my Putty generated .pkk file.

Second problem was that I needed to quote the absolute path to that .pkk file like that:

aws opsworks register --infrastructure-class ec2 --ssh-username ec2-user --ssh-private-key "C:\key.ppk"

How to find out line-endings in a text file?

You may use the command todos filename to convert to DOS endings, and fromdos filename to convert to UNIX line endings. To install the package on Ubuntu, type sudo apt-get install tofrodos.

MAC addresses in JavaScript

No you cannot get the MAC address in JavaScript, mainly because the MAC address uniquely identifies the running computer so it would be a security vulnerability.

Now if all you need is a unique identifier, I suggest you create one yourself using some cryptographic algorithm and store it in a cookie.

If you really need to know the MAC address of the computer AND you are developing for internal applications, then I suggest you use an external component to do that: ActiveX for IE, XPCOM for Firefox (installed as an extension).

What's the best way to cancel event propagation between nested ng-click calls?

Sometimes, it may make most sense just to do this:

<widget ng-click="myClickHandler(); $event.stopPropagation()"/>

I chose to do it this way because I didn't want myClickHandler() to stop the event propagation in the many other places it was used.

Sure, I could've added a boolean parameter to the handler function, but stopPropagation() is much more meaningful than just true.

Dynamically load a JavaScript file

There are scripts that are designed specifically for this purpose.

yepnope.js is built into Modernizr, and lab.js is a more optimized (but less user friendly version.

I wouldn't reccomend doing this through a big library like jquery or prototype - because one of the major benefits of a script loader is the ability to load scripts early - you shouldn't have to wait until jquery & all your dom elements load before running a check to see if you want to dynamically load a script.

Read input from console in Ruby?

Are you talking about gets?

puts "Enter A"
a = gets.chomp
puts "Enter B"
b = gets.chomp
c = a.to_i + b.to_i
puts c

Something like that?

Update

Kernel.gets tries to read the params found in ARGV and only asks to console if not ARGV found. To force to read from console even if ARGV is not empty use STDIN.gets

Difference between JSON.stringify and JSON.parse

JSON.stringify turns a JavaScript object into JSON text and stores that JSON text in a string, eg:

var my_object = { key_1: "some text", key_2: true, key_3: 5 };

var object_as_string = JSON.stringify(my_object);  
// "{"key_1":"some text","key_2":true,"key_3":5}"  

typeof(object_as_string);  
// "string"  

JSON.parse turns a string of JSON text into a JavaScript object, eg:

var object_as_string_as_object = JSON.parse(object_as_string);  
// {key_1: "some text", key_2: true, key_3: 5} 

typeof(object_as_string_as_object);  
// "object" 

Redirect stdout to a file in Python?

There is contextlib.redirect_stdout() function in Python 3.4+:

from contextlib import redirect_stdout

with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        print('it now prints to `help.text`')

It is similar to:

import sys
from contextlib import contextmanager

@contextmanager
def redirect_stdout(new_target):
    old_target, sys.stdout = sys.stdout, new_target # replace sys.stdout
    try:
        yield new_target # run some code with the replaced stdout
    finally:
        sys.stdout = old_target # restore to the previous value

that can be used on earlier Python versions. The latter version is not reusable. It can be made one if desired.

It doesn't redirect the stdout at the file descriptors level e.g.:

import os
from contextlib import redirect_stdout

stdout_fd = sys.stdout.fileno()
with open('output.txt', 'w') as f, redirect_stdout(f):
    print('redirected to a file')
    os.write(stdout_fd, b'not redirected')
    os.system('echo this also is not redirected')

b'not redirected' and 'echo this also is not redirected' are not redirected to the output.txt file.

To redirect at the file descriptor level, os.dup2() could be used:

import os
import sys
from contextlib import contextmanager

def fileno(file_or_fd):
    fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)()
    if not isinstance(fd, int):
        raise ValueError("Expected a file (`.fileno()`) or a file descriptor")
    return fd

@contextmanager
def stdout_redirected(to=os.devnull, stdout=None):
    if stdout is None:
       stdout = sys.stdout

    stdout_fd = fileno(stdout)
    # copy stdout_fd before it is overwritten
    #NOTE: `copied` is inheritable on Windows when duplicating a standard stream
    with os.fdopen(os.dup(stdout_fd), 'wb') as copied: 
        stdout.flush()  # flush library buffers that dup2 knows nothing about
        try:
            os.dup2(fileno(to), stdout_fd)  # $ exec >&to
        except ValueError:  # filename
            with open(to, 'wb') as to_file:
                os.dup2(to_file.fileno(), stdout_fd)  # $ exec > to
        try:
            yield stdout # allow code to be run with the redirected stdout
        finally:
            # restore stdout to its previous value
            #NOTE: dup2 makes stdout_fd inheritable unconditionally
            stdout.flush()
            os.dup2(copied.fileno(), stdout_fd)  # $ exec >&copied

The same example works now if stdout_redirected() is used instead of redirect_stdout():

import os
import sys

stdout_fd = sys.stdout.fileno()
with open('output.txt', 'w') as f, stdout_redirected(f):
    print('redirected to a file')
    os.write(stdout_fd, b'it is redirected now\n')
    os.system('echo this is also redirected')
print('this is goes back to stdout')

The output that previously was printed on stdout now goes to output.txt as long as stdout_redirected() context manager is active.

Note: stdout.flush() does not flush C stdio buffers on Python 3 where I/O is implemented directly on read()/write() system calls. To flush all open C stdio output streams, you could call libc.fflush(None) explicitly if some C extension uses stdio-based I/O:

try:
    import ctypes
    from ctypes.util import find_library
except ImportError:
    libc = None
else:
    try:
        libc = ctypes.cdll.msvcrt # Windows
    except OSError:
        libc = ctypes.cdll.LoadLibrary(find_library('c'))

def flush(stream):
    try:
        libc.fflush(None)
        stream.flush()
    except (AttributeError, ValueError, IOError):
        pass # unsupported

You could use stdout parameter to redirect other streams, not only sys.stdout e.g., to merge sys.stderr and sys.stdout:

def merged_stderr_stdout():  # $ exec 2>&1
    return stdout_redirected(to=sys.stdout, stdout=sys.stderr)

Example:

from __future__ import print_function
import sys

with merged_stderr_stdout():
     print('this is printed on stdout')
     print('this is also printed on stdout', file=sys.stderr)

Note: stdout_redirected() mixes buffered I/O (sys.stdout usually) and unbuffered I/O (operations on file descriptors directly). Beware, there could be buffering issues.

To answer, your edit: you could use python-daemon to daemonize your script and use logging module (as @erikb85 suggested) instead of print statements and merely redirecting stdout for your long-running Python script that you run using nohup now.

Generic Interface

Here's another suggestion:

public interface Service<T> {
   T execute();
}

using this simple interface you can pass arguments via constructor in the concrete service classes:

public class FooService implements Service<String> {

    private final String input1;
    private final int input2;

    public FooService(String input1, int input2) {
       this.input1 = input1;
       this.input2 = input2;
    }

    @Override
    public String execute() {
        return String.format("'%s%d'", input1, input2);
    }
}

How can I tell jackson to ignore a property for which I don't have control over the source code?

Using Java Class

new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

Using Annotation

@JsonIgnoreProperties(ignoreUnknown=true)

How to check if text fields are empty on form submit using jQuery?

function isEmpty(val) {
if(val.length ==0 || val.length ==null){
    return 'emptyForm';
}else{
    return 'not emptyForm';
}

}

$(document).ready(function(){enter code here
    $( "form" ).submit(function( event ) {
        $('input').each(function(){
           var getInputVal = $(this).val();
            if(isEmpty(getInputVal) =='emptyForm'){
                alert(isEmpty(getInputVal));
            }else{
                alert(isEmpty(getInputVal));
            }
        });
        event.preventDefault();
    });
});

Unable to compile class for JSP

<pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>       
                <version>2.2</version>
            </plugin>
        </plugins>

Removing html5 required attribute with jQuery

Even though the ID selector is the simplest, you can also use the name selector as below:

$('[name='submitted[first_name]']').removeAttr('required');

For more see: https://api.jquery.com/attribute-equals-selector/

Split string using a newline delimiter with Python

data = """a,b,c
d,e,f
g,h,i
j,k,l"""

print(data.split())       # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

str.split, by default, splits by all the whitespace characters. If the actual string has any other whitespace characters, you might want to use

print(data.split("\n"))   # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

Or as @Ashwini Chaudhary suggested in the comments, you can use

print(data.splitlines())

Conditionally change img src based on model data

For angular 4 I have used

<img [src]="data.pic ? data.pic : 'assets/images/no-image.png' " alt="Image" title="Image">

It works for me , I hope it may use to other's also for Angular 4-5. :)

how to make a html iframe 100% width and height?

Answering this just in case if someone else like me stumbles upon this post among many that advise use of JavaScripts for changing iframe height to 100%.

I strongly recommend that you see and try this option specified at How do you give iframe 100% height before resorting to a JavaScript based option. The referenced solution works perfectly for me in all of the testing I have done so far. Hope this helps someone.

SQL WHERE condition is not equal to?

I was just solving this problem. If you use <> or is not in on a variable, that is null, it will result in false. So instead of <> 1, you must check it like this:

 AND (isdelete is NULL or isdelete = 0)

Shortcut to open file in Vim

FuzzyFinder has been mentioned, however I love the textmate like behaviour of the FuzzyFinderTextmate plugin which extends the behaviour to include all subdirs.

Make sure you are using version 2.16 of fuzzyfinder.vim - The higher versions break the plugin.

phpMyAdmin says no privilege to create database, despite logged in as root user

This worked for me

open config.inc.php file in phpmyadmin root, set auth type from cookie to config

$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = ''; // leave blank if no password

How to get an isoformat datetime string including the default timezone?

You need to make your datetime objects timezone aware. from the datetime docs:

There are two kinds of date and time objects: “naive” and “aware”. This distinction refers to whether the object has any notion of time zone, daylight saving time, or other kind of algorithmic or political time adjustment. Whether a naive datetime object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it’s up to the program whether a particular number represents metres, miles, or mass. Naive datetime objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.

When you have an aware datetime object, you can use isoformat() and get the output you need.

To make your datetime objects aware, you'll need to subclass tzinfo, like the second example in here, or simpler - use a package that does it for you, like pytz or python-dateutil

Using pytz, this would look like:

import datetime, pytz
datetime.datetime.now(pytz.timezone('US/Central')).isoformat()

You can also control the output format, if you use strftime with the '%z' format directive like

datetime.datetime.now(pytz.timezone('US/Central')).strftime('%Y-%m-%dT%H:%M:%S.%f%z')

SELECT using 'CASE' in SQL

which platform ?

SELECT 
  CASE 
    WHEN FRUIT = 'A' THEN 'APPLE' 
    ELSE FRUIT ='B' THEN 'BANANA' 
   END AS FRUIT     
FROM FRUIT_TABLE;

How to push to History in React Router v4?

Nasty question, took me quite a lot of time, but eventually, I solved it this way:

Wrap your container with withRouter and pass history to your action in mapDispatchToProps function. In action use history.push('/url') to navigate.

Action:

export function saveData(history, data) {
  fetch.post('/save', data)
     .then((response) => {
       ...
       history.push('/url');
     })
};

Container:

import { withRouter } from 'react-router-dom';
...
const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    save: (data) => dispatch(saveData(ownProps.history, data))}
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Container));

This is valid for React Router v4.x.

jQuery change URL of form submit

Try using this:

$(".move_to").on("click", function(e){
    e.preventDefault();
    $('#contactsForm').attr('action', "/test1").submit();
});

Moving the order in which you use .preventDefault() might fix your issue. You also didn't use function(e) so e.preventDefault(); wasn't working.

Here it is working: http://jsfiddle.net/TfTwe/1/ - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1.

When to use IMG vs. CSS background-image?

Another background-image PRO: Background-images for <ul>/<ol> lists.

Use background images if they are part of the overall-design and are repeated on multiple pages. Preferably in background sprite form for optimization.

Use tags for all images that are not part of the overall design, and are most likely placed once, like specific images for articles, people, and important images that deserve to be added to google images.

** The only repeated image that I enclose in a <img> tag is the site/company logo. Because people tend to click it to go to the homepage, thus you wrap it with an <a> tag.

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

I was able to solve "ORA-00604: error" by Droping with purge.

DROP TABLE tablename PURGE

Linux command to translate DomainName to IP

You can use:

nslookup www.example.com

Why should I prefer to use member initialization lists?

Just to add some additional info to demonstrate how much difference the member initialization list can mak. In the leetcode 303 Range Sum Query - Immutable, https://leetcode.com/problems/range-sum-query-immutable/, where you need to construct and initialize to zero a vector with certain size. Here is two different implementation and speed comparison.

Without member initialization list, to get AC it cost me about 212 ms.

class NumArray {
public:
vector<int> preSum;
NumArray(vector<int> nums) {
    preSum = vector<int>(nums.size()+1, 0);
    int ps = 0;
    for (int i = 0; i < nums.size(); i++)
    {
        ps += nums[i];
        preSum[i+1] = ps;
    }
}

int sumRange(int i, int j) {
    return preSum[j+1] - preSum[i];
}
};

Now using member initialization list, the time to get AC is about 108 ms. With this simple example, it is quite obvious that, member initialization list is way more efficient. All the measurement is from the running time from LC.

class NumArray {
public:
vector<int> preSum;
NumArray(vector<int> nums) : preSum(nums.size()+1, 0) { 
    int ps = 0;
    for (int i = 0; i < nums.size(); i++)
    {
        ps += nums[i];
        preSum[i+1] = ps;
    }
}

int sumRange(int i, int j) {
    return preSum[j+1] - preSum[i];
}
};

Detect if HTML5 Video element is playing

a bit example when playing video

  let v = document.getElementById('video-plan');
  v.onplay = function() {
      console.log('Start video')
  };

How to create custom view programmatically in swift having controls text field, button etc

let viewDemo = UIView()
viewDemo.frame = CGRect(x: 50, y: 50, width: 50, height: 50)
self.view.addSubview(viewDemo)

How to draw border around a UILabel?

You can set label's border via its underlying CALayer property:

#import <QuartzCore/QuartzCore.h>

myLabel.layer.borderColor = [UIColor greenColor].CGColor
myLabel.layer.borderWidth = 3.0

Swift 5:

myLabel.layer.borderColor = UIColor.darkGray.cgColor
myLabel.layer.borderWidth = 3.0

Reading a binary input stream into a single byte array in Java

Please keep in mind that the answers here assume that the length of the file is less than or equal to Integer.MAX_VALUE(2147483647).

If you are reading in from a file, you can do something like this:

    File file = new File("myFile");
    byte[] fileData = new byte[(int) file.length()];
    DataInputStream dis = new DataInputStream(new FileInputStream(file));
    dis.readFully(fileData);
    dis.close();

UPDATE (May 31, 2014):

Java 7 adds some new features in the java.nio.file package that can be used to make this example a few lines shorter. See the readAllBytes() method in the java.nio.file.Files class. Here is a short example:

import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

// ...
        Path p = FileSystems.getDefault().getPath("", "myFile");
        byte [] fileData = Files.readAllBytes(p);

Android has support for this starting in Api level 26 (8.0.0, Oreo).

How to Specify Eclipse Proxy Authentication Credentials?

For eclipse Mar1 : - Window > Preferences > General > Network connections. Choose "Manual" from drop down. Double click "HTTP" option and enter the Host, Port, Username and Password. Apply and Finish,,it will work as expected...

Checking if date is weekend PHP

If you have PHP >= 5.1:

function isWeekend($date) {
    return (date('N', strtotime($date)) >= 6);
}

otherwise:

function isWeekend($date) {
    $weekDay = date('w', strtotime($date));
    return ($weekDay == 0 || $weekDay == 6);
}

How can I set focus on an element in an HTML form using JavaScript?

For what it's worth, you can use the autofocus attribute on HTML5 compatible browsers. Works even on IE as of version 10.

<input name="myinput" value="whatever" autofocus />

How to convert an Instant to a date format?

try Parsing and Formatting

Take an example Parsing

String input = ...;
try {
    DateTimeFormatter formatter =
                      DateTimeFormatter.ofPattern("MMM d yyyy");
    LocalDate date = LocalDate.parse(input, formatter);
    System.out.printf("%s%n", date);
}
catch (DateTimeParseException exc) {
    System.out.printf("%s is not parsable!%n", input);
    throw exc;      // Rethrow the exception.
}

Formatting

ZoneId leavingZone = ...;
ZonedDateTime departure = ...;

try {
    DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy  hh:mm a");
    String out = departure.format(format);
    System.out.printf("LEAVING:  %s (%s)%n", out, leavingZone);
}
catch (DateTimeException exc) {
    System.out.printf("%s can't be formatted!%n", departure);
    throw exc;
}

The output for this example, which prints both the arrival and departure time, is as follows:

LEAVING:  Jul 20 2013  07:30 PM (America/Los_Angeles)
ARRIVING: Jul 21 2013  10:20 PM (Asia/Tokyo)

For more details check this page- https://docs.oracle.com/javase/tutorial/datetime/iso/format.html

A function to convert null to string

You can just use the null coalesce operator.

string result = value ?? "";

Determine what user created objects in SQL Server

If the object was recently created, you can check the Schema Changes History report, within the SQL Server Management Studio, which "provides a history of all committed DDL statement executions within the Database recorded by the default trace":

enter image description here

You then can search for the create statements of the objects. Among all the information displayed, there is the login name of whom executed the DDL statement.

Regex to match words of a certain length

Method 1

Word boundaries would work perfectly here, such as with:

\b\w{3,8}\b
\b\w{2,}
\b\w{,10}\b
\b\w{5}\b

RegEx Demo 1

Java

Some languages such as Java and C++ are double-escape required:

\\b\\w{3,8}\\b
\\b\\w{2,}
\\b\\w{,10}\\b
\\b\\w{5}\\b

PS: \\b\\w{,10}\\b may not work for all languages or flavors.

Test 1

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegularExpression{

    public static void main(String[] args){


        final String regex = "\\b\\w{3,8}\\b";
        final String string = "words with length three to eight";

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
        }

    }
}

Output 1

Full match: words
Full match: with
Full match: length
Full match: three
Full match: eight

Method 2

Another good-to-know method is to use negative lookarounds:

(?<!\w)\w{3,8}(?!\w)
(?<!\w)\w{2,}
(?<!\w)\w{,10}(?!\w)
(?<!\w)\w{5}(?!\w)

Java

(?<!\\w)\\w{3,8}(?!\\w)
(?<!\\w)\\w{2,}
(?<!\\w)\\w{,10}(?!\\w)
(?<!\\w)\\w{5}(?!\\w)

RegEx Demo 2

Test 2

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegularExpression{

    public static void main(String[] args){


        final String regex = "(?<!\\w)\\w{1,10}(?!\\w)";
        final String string = "words with length three to eight";

        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);

        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
        }

    }
}

Output 2

Full match: words
Full match: with
Full match: length
Full match: three
Full match: to
Full match: eight

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Drop all duplicate rows across multiple columns in Python Pandas

This is much easier in pandas now with drop_duplicates and the keep parameter.

import pandas as pd
df = pd.DataFrame({"A":["foo", "foo", "foo", "bar"], "B":[0,1,1,1], "C":["A","A","B","A"]})
df.drop_duplicates(subset=['A', 'C'], keep=False)

Start and stop a timer PHP

Since PHP 7.3 the hrtime function should be used for any timing.

$start = hrtime(true);
// execute...
$end = hrtime(true);   

echo ($end - $start);                // Nanoseconds
echo ($end - $start) / 1000000000;   // Seconds

The mentioned microtime function relies on the system clock. Which can be modified e.g. by the ntpd program on ubuntu or just the sysadmin.

What is $@ in Bash?

Just from reading that i would have never understood that "$@" expands into a list of separate parameters. Whereas, "$*" is one parameter consisting of all the parameters added together.

If it still makes no sense do this.

http://www.thegeekstuff.com/2010/05/bash-shell-special-parameters/

Sending email from Azure

For people wanting to use the built-in .NET SmtpClient rather than the SendGrid client library (not sure if that was the OP's intent), I couldn't get it to work unless I used apikey as my username and the api key itself as the password as outlined here.

<mailSettings>
    <smtp>
        <network host="smtp.sendgrid.net" port="587" userName="apikey" password="<your key goes here>" />
    </smtp>
</mailSettings>

Soft hyphen in HTML (<wbr> vs. &shy;)

This is a crossbrowser solution that I was looking at a little while ago that runs on the client and using jQuery:

(function($) { 
  $.fn.breakWords = function() { 
    this.each(function() { 
      if(this.nodeType !== 1) { return; } 

      if(this.currentStyle && typeof this.currentStyle.wordBreak === 'string') { 
        //Lazy Function Definition Pattern, Peter's Blog 
        //From http://peter.michaux.ca/article/3556 
        this.runtimeStyle.wordBreak = 'break-all'; 
      } 
      else if(document.createTreeWalker) { 

        //Faster Trim in Javascript, Flagrant Badassery 
        //http://blog.stevenlevithan.com/archives/faster-trim-javascript 

        var trim = function(str) { 
          str = str.replace(/^\s\s*/, ''); 
          var ws = /\s/, 
          i = str.length; 
          while (ws.test(str.charAt(--i))); 
          return str.slice(0, i + 1); 
        }; 

        //Lazy Function Definition Pattern, Peter's Blog 
        //From http://peter.michaux.ca/article/3556 

        //For Opera, Safari, and Firefox 
        var dWalker = document.createTreeWalker(this, NodeFilter.SHOW_TEXT, null, false); 
        var node,s,c = String.fromCharCode('8203'); 
        while (dWalker.nextNode()) { 
          node = dWalker.currentNode; 
          //we need to trim String otherwise Firefox will display 
          //incorect text-indent with space characters 
          s = trim( node.nodeValue ).split('').join(c); 
          node.nodeValue = s; 
        } 
      } 
    }); 

    return this; 
  }; 
})(jQuery); 

How to set min-height for bootstrap container

Two things are happening here.

  1. You are not using the container class properly.
  2. You are trying to override Bootstrap's CSS for the container class

Bootstrap uses a grid system and the .container class is defined in its own CSS. The grid has to exist within a container class DIV. The container DIV is just an indication to Bootstrap that the grid within has that parent. Therefore, you cannot set the height of a container.

What you want to do is the following:

<div class="container-fluid"> <!-- this is to make it responsive to your screen width -->
    <div class="row">
        <div class="col-md-4 myClassName">  <!-- myClassName is defined in my CSS as you defined your container -->
            <img src="#.jpg" height="200px" width="300px">
        </div>
    </div>
</div>

Here you can find more info on the Bootstrap grid system.

That being said, if you absolutely MUST override the Bootstrap CSS then I would try using the "!important" clause to my CSS definition as such...

.container {
   padding-right: 15px;
   padding-left: 15px;
   margin-right: auto;
   margin-left: auto;
   max-width: 900px;
   overflow:hidden;
   min-height:0px !important;
}

But I have always found that the "!important" clause just makes for messy CSS.

jQuery onclick event for <li> tags

this is a HTML element.
$(this) is a jQuery object that encapsulates the HTML element.

Use $(this).text() to retrieve the element's inner text.

I suggest you refer to the jQuery API documentation for further information.

When is a language considered a scripting language?

just to breif

Scripting languages run inside another program. Scripting languages are not compiled. Scripting languages are easy to use and easy to write. but …

Very popular programming languages (Java, C#) run inside a ‘parent’ program – like scripting languages. Scripting languages today are used to build complex software. Computers are so fast these days, and scripting languages are so efficient, that for most business operations, there is no practical speed advantage (that there once was,) with a compiled programming language.

Using DataContractSerializer to serialize, but can't deserialize back

This best for XML Deserialize

 public static object Deserialize(string xml, Type toType)
    {

        using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
        {
            System.IO.StreamReader str = new System.IO.StreamReader(memoryStream);
            System.Xml.Serialization.XmlSerializer xSerializer = new System.Xml.Serialization.XmlSerializer(toType);
            return xSerializer.Deserialize(str);
        }

    }

builder for HashMap

Since Java 9 Map interface contains:

  • Map.of(k1,v1, k2,v2, ..)
  • Map.ofEntries(Map.entry(k1,v1), Map.entry(k2,v2), ..).

Limitations of those factory methods are that they:

  • can't hold nulls as keys and/or values (if you need to store nulls take a look at other answers)
  • produce immutable maps

If we need mutable map (like HashMap) we can use its copy-constructor and let it copy content of map created via Map.of(..)

Map<Integer, String> map = new HashMap<>( Map.of(1,"a", 2,"b", 3,"c") );

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

JOptionPane Input to int

Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.

What is the difference between instanceof and Class.isAssignableFrom(...)?

When using instanceof, you need to know the class of B at compile time. When using isAssignableFrom() it can be dynamic and change during runtime.

Android ListView with Checkbox and all clickable

holder.checkbox.setTag(row_id);

and

holder.checkbox.setOnClickListener( new OnClickListener() {

                @Override
                public void onClick(View v) {
                    CheckBox c = (CheckBox) v;

                    int row_id = (Integer) v.getTag();

                    checkboxes.put(row_id, c.isChecked());


                }
        });

How to automatically close cmd window after batch file execution?

You normally end a batch file with a line that just says exit. If you want to make sure the file has run and the DOS window closes after 2 seconds, you can add the lines:

timeout 2 >nul
exit

But the exit command will not work if your batch file opens another window, because while ever the second window is open the old DOS window will also be displayed.

SOLUTION: For example there's a great little free program called BgInfo which will display all the info about your computer. Assuming it's in a directory called C:\BgInfo, to run it from a batch file with the /popup switch and to close the DOS window while it still runs, use:

start "" "C:\BgInfo\BgInfo.exe" /popup
exit

Java Runtime.getRuntime(): getting output from executing a command line program

Here is the way to go:

Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-get t"};
Process proc = rt.exec(commands);

BufferedReader stdInput = new BufferedReader(new 
     InputStreamReader(proc.getInputStream()));

BufferedReader stdError = new BufferedReader(new 
     InputStreamReader(proc.getErrorStream()));

// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}

Read the Javadoc for more details here. ProcessBuilder would be a good choice to use.

docker build with --build-arg with multiple arguments

It's a shame that we need multiple ARG too, it results in multiple layers and slows down the build because of that, and for anyone also wondering that, currently there is no way to set multiple ARGs.

How to hide reference counts in VS2013?

I guess you probably are running the preview of VS2013 Ultimate, because it is not present in my professional preview. But looking online I found that the feature is called Code Information Indicators or CodeLens, and can be located under

Tools ? Options ? Text Editor ? All Languages ? CodeLens

(for RC/final version)

or

Tools ? Options ? Text Editor ? All Languages ? Code Information Indicators

(for preview version)

That was according to this link. It seems to be pretty well hidden.

In Visual Studio 2013 RTM, you can also get to the CodeLens options by right clicking the indicators themselves in the editor:

editor options

documented in the Q&A section of the msdn CodeLens documentation

How to move certain commits to be based on another branch in git?

I believe it's:

git checkout master
git checkout -b good_quickfix2
git cherry-pick quickfix2^
git cherry-pick quickfix2

How to connect TFS in Visual Studio code

Just as Daniel said "Git and TFVC are the two source control options in TFS". Fortunately both are supported for now in VS Code.

You need to install the Azure Repos Extension for Visual Studio Code. The process of installing is pretty straight forward.

  1. Search for Azure Repos in VS Code and select to install the one by Microsoft
  2. Open File -> Preferences -> Settings
  3. Add the following lines to your user settings

    If you have VS 2015 installed on your machine, your path to Team Foundation tool (tf.exe) may look like this:

    {
        "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\tf.exe",
        "tfvc.restrictWorkspace": true
    }

    Or for VS 2017:

    {
        "tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Enterprise\\Common7\\IDE\\CommonExtensions\\Microsoft\\TeamFoundation\\Team Explorer\\tf.exe",
        "tfvc.restrictWorkspace": true
    }
  4. Open a local folder (repository), From View -> Command Pallette ..., type team signin

  5. Provide user name --> Enter --> Provide password to connect to TFS.

Please refer to below links for more details:

Note that Server Workspaces are not supported:

"TFVC support is limited to Local workspaces":

on installing Azure extension, visual studio code warns you "It appears you are using a Server workspace. Currently, TFVC support is limited to Local workspaces"

No tests found with test runner 'JUnit 4'

When we get these errors it seems like Eclipse is just confused. Restart Eclipse, refresh the project, clean it, let Eclipse rebuild it, and try again. Most times that works like a charm.

Environment variables in Mac OS X

There's no need for duplication. You can set environment variables used by launchd (and child processes, i.e. anything you start from Spotlight) using launchctl setenv.

For example, if you want to mirror your current path in launchd after setting it up in .bashrc or wherever:

PATH=whatever:you:want
launchctl setenv PATH $PATH

Environment variables are not automatically updated in running applications. You will need to relaunch applications to get the updated environment variables (although you can just set variables in your shell, e.g. PATH=whatever:you:want; there's no need to relaunch the terminal).

Calculating percentile of dataset column

If you order a vector x, and find the values that is half way through the vector, you just found a median, or 50th percentile. Same logic applies for any percentage. Here are two examples.

x <- rnorm(100)
quantile(x, probs = c(0, 0.25, 0.5, 0.75, 1)) # quartile
quantile(x, probs = seq(0, 1, by= 0.1)) # decile

How to call a REST web service API from JavaScript?

Your Javascript:

function UserAction() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
             alert(this.responseText);
         }
    };
    xhttp.open("POST", "Your Rest URL Here", true);
    xhttp.setRequestHeader("Content-type", "application/json");
    xhttp.send("Your JSON Data Here");
}

Your Button action::

<button type="submit" onclick="UserAction()">Search</button>

For more info go through the following link (Updated 2017/01/11)

I am getting Failed to load resource: net::ERR_BLOCKED_BY_CLIENT with Google chrome

My advice is to avoid any image names; class names or ID's with the words:

  • Advert
  • Advertise

in their name!

I ran some tests and Ad blockers regularly block any direct content with these names either within the CSS file, Div or Span Layers.

So an image name loaded via CSS such as advertise-with-us.png gets blocked on any machine running such software for example.

EDIT: I've Traced a list of web page elements in Chrome which AdBlock Plus sets the CSS value to "display:none". They probably apply to other browsers too:

::content #ads > .dose > .dosesingle, 
::content #content > #center > .dose > .dosesingle,
::content #content > #right > .dose > .dosesingle, 
::content #header + #content > #left > #rlblock_left, 
::content .trc_rbox_border_elm .syndicatedItem, 
::content .trc_rbox_div .syndicatedItem, 
::content div[id^="mainads"], ::content #ad-banner-980, 
::content #adbox300600, ::content #chartAdWrap, 
::content #in-content-ad, ::content #main-right-ad-tray, 
::content #second-right-ad-tray, ::content #sponsored-message, 
::content #tr-adv-banner, ::content #votvAds_inner, 
::content #welcome_ad, ::content #wp_ad_marker, 
::content .PremiumObitAdBar, ::content .ad-active