Programs & Examples On #Power series

What is DOM element?

DOM stands for Document Object Model. It is the W3C(World Wide Web Consortium) Standard. It define standard for accessing and manipulating HTML and XML document and The elements of DOM is head,title,body tag etc. So the answer of your first statement is

Statement #1 You can add multiple classes to a single DOM element.

Explanation : "div class="cssclass1 cssclass2 cssclass3"

Here tag is element of DOM and i have applied multiple classes to DOM element.

How to Navigate from one View Controller to another using Swift

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let home = storyBoard.instantiateViewController(withIdentifier: "HOMEVC") as! HOMEVC
navigationController?.pushViewController(home, animated: true);

Handling the null value from a resultset in JAVA

output = rs.getString("column");// if data is null `output` would be null, so there is no chance of NPE unless `rs` is `null`

if(output == null){// if you fetched null value then initialize output with blank string
  output= "";
}

How do I embed a mp4 movie into my html?

Most likely the TinyMce editor is adding its own formatting to the post. You'll need to see how you can escape TinyMce's editing abilities. The code works fine for me. Is it a wordpress blog?

Validation of radio button group using jQuery validation plugin

use the following rule for validating radio button group selection

myRadioGroupName : {required :true}

myRadioGroupName is the value you have given to name attribute

How to draw border around a UILabel?

UILabel properties borderColor,borderWidth,cornerRadius in Swift 4

@IBOutlet weak var anyLabel: UILabel!
   override func viewDidLoad() {
        super.viewDidLoad()
        anyLabel.layer.borderColor = UIColor.black.cgColor
        anyLabel.layer.borderWidth = 2
        anyLabel.layer.cornerRadius = 5
        anyLabel.layer.masksToBounds = true
}

Vue equivalent of setTimeout?

It is likely a scope issue. Try the following instead:

addToBasket: function(){
    item = this.photo;
    this.$http.post('/api/buy/addToBasket', item);
    this.basketAddSuccess = true;
    var self = this;
    setTimeout(function(){
        self.basketAddSuccess = false;
    }, 2000);
}

Is it possible to embed animated GIFs in PDFs?

I do it for beamer presentations,

provide tmp-0.png through tmp-34.png

\usepackage{animate}

\begin{frame}{Torque Generating Mechanism}
  \animategraphics[loop,controls,width=\linewidth]{12}{output/tmp-}{0}{34}
\end{frame}

What are App Domains in Facebook Apps?

If you don't specify the platform for the app you won't able to add app domain correctly.

Here is an example -- validate that its a type a website platform. enter image description here

jQuery - find table row containing table cell containing specific text

This will search text in all the td's inside each tr and show/hide tr's based on search text

 $.each($(".table tbody").find("tr"), function () {                              

                if ($(this).text().toLowerCase().replace(/\s+/g, '').indexOf(searchText.replace(/\s+/g, '').toLowerCase()) == -1)
                    $(this).hide();
                else
                    $(this).show();
 });

.htaccess not working apache

use RewriteBase /{your folder}/ on your .htaccess

What is the JSF resource library for and how should it be used?

Actually, all of those examples on the web wherein the common content/file type like "js", "css", "img", etc is been used as library name are misleading.

Real world examples

To start, let's look at how existing JSF implementations like Mojarra and MyFaces and JSF component libraries like PrimeFaces and OmniFaces use it. No one of them use resource libraries this way. They use it (under the covers, by @ResourceDependency or UIViewRoot#addComponentResource()) the following way:

<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputScript library="omnifaces" name="fixviewstate.js" />
<h:outputScript library="omnifaces.combined" name="[dynamicname].js" />
<h:outputStylesheet library="primefaces" name="primefaces.css" />
<h:outputStylesheet library="primefaces-aristo" name="theme.css" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />

It should become clear that it basically represents the common library/module/theme name where all of those resources commonly belong to.

Easier identifying

This way it's so much easier to specify and distinguish where those resources belong to and/or are coming from. Imagine that you happen to have a primefaces.css resource in your own webapp wherein you're overriding/finetuning some default CSS of PrimeFaces; if PrimeFaces didn't use a library name for its own primefaces.css, then the PrimeFaces own one wouldn't be loaded, but instead the webapp-supplied one, which would break the look'n'feel.

Also, when you're using a custom ResourceHandler, you can also apply more finer grained control over resources coming from a specific library when library is used the right way. If all component libraries would have used "js" for all their JS files, how would the ResourceHandler ever distinguish if it's coming from a specific component library? Examples are OmniFaces CombinedResourceHandler and GraphicResourceHandler; check the createResource() method wherein the library is checked before delegating to next resource handler in chain. This way they know when to create CombinedResource or GraphicResource for the purpose.

Noted should be that RichFaces did it wrong. It didn't use any library at all and homebrewed another resource handling layer over it and it's therefore impossible to programmatically identify RichFaces resources. That's exactly the reason why OmniFaces CombinedResourceHander had to introduce a reflection-based hack in order to get it to work anyway with RichFaces resources.

Your own webapp

Your own webapp does not necessarily need a resource library. You'd best just omit it.

<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/logo.png" />

Or, if you really need to have one, you can just give it a more sensible common name, like "default" or some company name.

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

Or, when the resources are specific to some master Facelets template, you could also give it the name of the template, so that it's easier to relate each other. In other words, it's more for self-documentary purposes. E.g. in a /WEB-INF/templates/layout.xhtml template file:

<h:outputStylesheet library="layout" name="css/style.css" />
<h:outputScript library="layout" name="js/script.js" />

And a /WEB-INF/templates/admin.xhtml template file:

<h:outputStylesheet library="admin" name="css/style.css" />
<h:outputScript library="admin" name="js/script.js" />

For a real world example, check the OmniFaces showcase source code.

Or, when you'd like to share the same resources over multiple webapps and have created a "common" project for that based on the same example as in this answer which is in turn embedded as JAR in webapp's /WEB-INF/lib, then also reference it as library (name is free to your choice; component libraries like OmniFaces and PrimeFaces also work that way):

<h:outputStylesheet library="common" name="css/style.css" />
<h:outputScript library="common" name="js/script.js" />
<h:graphicImage library="common" name="img/logo.png" />

Library versioning

Another main advantage is that you can apply resource library versioning the right way on resources provided by your own webapp (this doesn't work for resources embedded in a JAR). You can create a direct child subfolder in the library folder with a name in the \d+(_\d+)* pattern to denote the resource library version.

WebContent
 |-- resources
 |    `-- default
 |         `-- 1_0
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js
 :

When using this markup:

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

This will generate the following HTML with the library version as v parameter:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_0" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_0"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_0" alt="" />

So, if you have edited/updated some resource, then all you need to do is to copy or rename the version folder into a new value. If you have multiple version folders, then the JSF ResourceHandler will automatically serve the resource from the highest version number, according to numerical ordering rules.

So, when copying/renaming resources/default/1_0/* folder into resources/default/1_1/* like follows:

WebContent
 |-- resources
 |    `-- default
 |         |-- 1_0
 |         |    :
 |         |
 |         `-- 1_1
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js
 :

Then the last markup example would generate the following HTML:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_1" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_1"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_1" alt="" />

This will force the webbrowser to request the resource straight from the server instead of showing the one with the same name from the cache, when the URL with the changed parameter is been requested for the first time. This way the endusers aren't required to do a hard refresh (Ctrl+F5 and so on) when they need to retrieve the updated CSS/JS resource.

Please note that library versioning is not possible for resources enclosed in a JAR file. You'd need a custom ResourceHandler. See also How to use JSF versioning for resources in jar.

See also:

How to make lists contain only distinct element in Python?

To preserve the order:

l = [1, 1, 2, 2, 3]
result = list()
map(lambda x: not x in result and result.append(x), l)
result
# [1, 2, 3]

Create PostgreSQL ROLE (user) if it doesn't exist

The same solution as for Simulate CREATE DATABASE IF NOT EXISTS for PostgreSQL? should work - send a CREATE USER … to \gexec.

Workaround from within psql

SELECT 'CREATE USER my_user'
WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec

Workaround from the shell

echo "SELECT 'CREATE USER my_user' WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = 'my_user')\gexec" | psql

See accepted answer there for more details.

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;
}

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

For me nothing of the above worked, so I just downloaded all the files by hand from the web site http://www.nltk.org/nltk_data/ and I put them also by hand in a file "tokenizers" inside of "nltk_data" folder. Not a pretty solution but still a solution.

.keyCode vs. .which

jQuery normalises event.which depending on whether event.which, event.keyCode or event.charCode is supported by the browser:

// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
   event.which = event.charCode != null ? event.charCode : event.keyCode;
}

An added benefit of .which is that jQuery does it for mouse clicks too:

// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
    event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}

Decoding UTF-8 strings in Python

It's an encoding error - so if it's a unicode string, this ought to fix it:

text.encode("windows-1252").decode("utf-8")

If it's a plain string, you'll need an extra step:

text.decode("utf-8").encode("windows-1252").decode("utf-8")

Both of these will give you a unicode string.

By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:

>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

how to convert an RGB image to numpy array?

You can get numpy array of rgb image easily by using numpy and Image from PIL

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

im = Image.open('*image_name*') #These two lines
im_arr = np.array(im) #are all you need
plt.imshow(im_arr) #Just to verify that image array has been constructed properly

How should I store GUID in MySQL tables?

For those just stumbling across this, there is now a much better alternative as per research by Percona.

It consists of reorganising the UUID chunks for optimal indexing, then converting into binary for reduced storage.

Read the full article here

SQL Server, division returns zero

Either declare set1 and set2 as floats instead of integers or cast them to floats as part of the calculation:

SET @weight= CAST(@set1 AS float) / CAST(@set2 AS float);

How to squash all git commits into one?

I read something about using grafts but never investigated it much.

Anyway, you can squash those last 2 commits manually with something like this:

git reset HEAD~1
git add -A
git commit --amend

How to handle the `onKeyPress` event in ReactJS?

var Test = React.createClass({
     add: function(event){
         if(event.key === 'Enter'){
            alert('Adding....');
         }
     },
     render: function(){
        return(
           <div>
            <input type="text" id="one" onKeyPress={(event) => this.add(event)}/>    
          </div>
        );
     }
});

Convert 4 bytes to int

Converting a 4-byte array into integer:

//Explictly declaring anInt=-4, byte-by-byte
byte[] anInt = {(byte)0xff,(byte)0xff,(byte)0xff,(byte)0xfc}; // Equals -4
//And now you have a 4-byte array with an integer equaling -4...
//Converting back to integer from 4-bytes...
result = (int) ( anInt[0]<<24 | ( (anInt[1]<<24)>>>8 ) | ( (anInt[2]<<24)>>>16) | ( (anInt[3]<<24)>>>24) );

What is the syntax to insert one list into another list in python?

foo = [1, 2, 3]
bar = [4, 5, 6]

foo.append(bar) --> [1, 2, 3, [4, 5, 6]]
foo.extend(bar) --> [1, 2, 3, 4, 5, 6]

http://docs.python.org/tutorial/datastructures.html

How to make a JFrame button open another JFrame class in Netbeans?

JFrame.setVisible(true);

You can either use setVisible(false) or dispose() method to disappear current form.

%i or %d to print integer in C using printf()?

As others said, they produce identical output on printf, but behave differently on scanf. I would prefer %d over %i for this reason. A number that is printed with %d can be read in with %d and you will get the same number. That is not always true with %i, if you ever choose to use zero padding. Because it is common to copy printf format strings into scanf format strings, I would avoid %i, since it could give you a surprising bug introduction:

I write fprintf("%i ...", ...);

You copy and write fscanf(%i ...", ...);

I decide I want to align columns more nicely and make alphabetization behave the same as sorting: fprintf("%03i ...", ...); (or %04d)

Now when you read my numbers, anything between 10 and 99 is interpreted in octal. Oops.

If you want decimal formatting, just say so.

missing private key in the distribution certificate on keychain

Check whether you are using Login or not to add the certificates, if you are checking in System at top left hand side then we wont be able to see it.

So drag and drop the .cer into login then check you are able to get the private key or not.

Difference between Inheritance and Composition

In Simple Word Aggregation means Has A Relationship ..

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

Why Use Aggregation

Code Reusability

When Use Aggregation

Code reuse is also best achieved by aggregation when there is no is a Relation ship

Inheritance

Inheritance is a Parent Child Relationship Inheritance Means Is A RelationShip

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

Using inheritance in Java 1 Code Reusability. 2 Add Extra Feature in Child Class as well as Method Overriding (so runtime polymorphism can be achieved).

List<T> or IList<T>

The most important case for using interfaces over implementations is in the parameters to your API. If your API takes a List parameter, then anyone who uses it has to use List. If the parameter type is IList, then the caller has much more freedom, and can use classes you never heard about, which may not even have existed when your code was written.

WPF: ItemsControl with scrollbar (ScrollViewer)

To get a scrollbar for an ItemsControl, you can host it in a ScrollViewer like this:

<ScrollViewer VerticalScrollBarVisibility="Auto">
  <ItemsControl>
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
    <uc:UcSpeler />
  </ItemsControl>
</ScrollViewer>

Print the contents of a DIV

I think the solutions proposed so far have the following drawbacks:

  1. The CSS media query solutions assume there is only one div to print.
  2. The javascript solutions work only on certain browsers.
  3. Destroying the parent window content and recreating that creates a mess.

I have improved on the solutions above. Here is something that I have tested that works really well with the following benefits.

  1. Works on all the browsers including IE, Chrome, Safari and firefox.
  2. Doesn't destroy and reload the parent window.
  3. Can print any number of DIV's in a page.
  4. Uses html templates to avoid error prone string concatenation.

Key Points to note :

  1. Have to have a onload="window.print()" on the newly created window.
  2. Don't call targetwindow.close() or targetwindow.print() from the parent.
  3. Make sure you do targetwindow.document.close() and target.focus()
  4. I'm using jquery but you can do the same technique using plain javascript as well.
  5. You can see this in action here http://math.tools/table/multiplication. You can print each table separately, by clicking on the print button on the box header.

_x000D_
_x000D_
<script id="print-header" type="text/x-jquery-tmpl">_x000D_
   <html>_x000D_
   <header>_x000D_
       <title>Printing Para {num}</title>_x000D_
       <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
       <style>_x000D_
          body {_x000D_
            max-width: 300px;_x000D_
          }_x000D_
       </style>_x000D_
   </header>_x000D_
   <body onload="window.print()">_x000D_
   <h2>Printing Para {num} </h2>_x000D_
   <h4>http://math.tools</h4>_x000D_
</script>_x000D_
<script id="print-footer" type="text/x-jquery-tmpl">_x000D_
    </body>_x000D_
    </html>_x000D_
</script>_x000D_
<script>_x000D_
$('.printthis').click(function() {_x000D_
   num = $(this).attr("data-id");_x000D_
   w = window.open();_x000D_
   w.document.write(_x000D_
                   $("#print-header").html().replace("{num}",num)  +_x000D_
                   $("#para-" + num).html() +_x000D_
                   $("#print-footer").html() _x000D_
                   );_x000D_
   w.document.close();_x000D_
   w.focus();_x000D_
   //w.print(); Don't do this otherwise chrome won't work. Look at the onload on the body of the newly created window._x000D_
   ///w.close(); Don't do this otherwise chrome won't work_x000D_
});_x000D_
</script>
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<a class="btn printthis" data-id="1" href="#" title="Print Para 1"><i class="fa fa-print"></i> Print Para 1</a>_x000D_
<a class="btn printthis" data-id="2" href="#" title="Print Para 2"><i class="fa fa-print"></i> Print Para 2</a>_x000D_
  _x000D_
<p class="para" id="para-1">_x000D_
  Para 1 : Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
  _x000D_
_x000D_
<p class="para" id="para-2">_x000D_
  Para 2 : Lorem 2 ipsum 2 dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>_x000D_
  
_x000D_
_x000D_
_x000D_

Logging framework incompatibility

Just to help those in a similar situation to myself...

This can be caused when a dependent library has accidentally bundled an old version of slf4j. In my case, it was tika-0.8. See https://issues.apache.org/jira/browse/TIKA-556

The workaround is exclude the component and then manually depends on the correct, or patched version.

EG.

<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-parsers</artifactId>
    <version>0.8</version>
    <exclusions>
        <exclusion>
            <!-- NOTE: Version 4.2 has bundled slf4j -->
            <groupId>edu.ucar</groupId>
            <artifactId>netcdf</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <!-- Patched version 4.2-min does not bundle slf4j -->
    <groupId>edu.ucar</groupId>
    <artifactId>netcdf</artifactId>
    <version>4.2-min</version>
</dependency>

Can I start the iPhone simulator without "Build and Run"?

For Xcode 7.2

open /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/MacOS/Simulator.app

sudo ./Simulator

And adding this path in your profile is the best way.

Git copy changes from one branch to another

git checkout BranchB
git merge BranchA
git push origin BranchB

This is all if you intend to not merge your changes back to master. Generally it is a good practice to merge all your changes back to master, and create new branches off of that.

Also, after the merge command, you will have some conflicts, which you will have to edit manually and fix.

Make sure you are in the branch where you want to copy all the changes to. git merge will take the branch you specify and merge it with the branch you are currently in.

jQuery AJAX Call to PHP Script with JSON Return

I recommend you use:

var returnedData = JSON.parse(data);

to convert the JSON string (if it is just text) to a JavaScript object.

Convert string to buffer Node

You can use Buffer.from() to convert a string to buffer. More information on this can be found here

var buf = Buffer.from('some string', 'encoding');

for example

var buf = Buffer.from(bStr, 'utf-8');

What is the best way to search the Long datatype within an Oracle database?

You can't search LONGs directly. LONGs can't appear in the WHERE clause. They can appear in the SELECT list though so you can use that to narrow down the number of rows you'd have to examine.

Oracle has recommended converting LONGs to CLOBs for at least the past 2 releases. There are fewer restrictions on CLOBs.

I'm trying to use python in powershell

  1. download Nodejs for windows
  2. install node-vxxx.msi
  3. find "Install Additional Tools for Node.js" script
  4. open and install it
  5. reopen a new shell prompt, type "python" >> press "enter" >> it works!!

What data is stored in Ephemeral Storage of Amazon EC2 instance?

Basically, root volume (your entire virtual system disk) is ephemeral, but only if you choose to create AMI backed by Amazon EC2 instance store.

If you choose to create AMI backed by EBS then your root volume is backed by EBS and everything you have on your root volume will be saved between reboots.

If you are not sure what type of volume you have, look under EC2->Elastic Block Store->Volumes in your AWS console and if your AMI root volume is listed there then you are safe. Also, if you go to EC2->Instances and then look under column "Root device type" of your instance and if it says "ebs", then you don't have to worry about data on your root device.

More details here: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/RootDeviceStorage.html

How to change ProgressBar's progress indicator color in Android

A simpler solution:

progess_drawable_blue

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
    <shape>
        <solid
                android:color="@color/disabled" />
    </shape>
</item>

<item
    android:id="@android:id/progress">
    <clip>
        <shape>
            <solid
                android:color="@color/blue" />
        </shape>
    </clip>
</item>

</layer-list>

Vue.js toggle class on click

Try :

<template>
   <th :class="'initial '+ active" v-on="click: myFilter">
       <span class="wkday">M</span>
   </th>  
</template>

<script lang="ts">

    active:string=''
    myFilter(){
       this.active='active'
    }
</script>

<style>
  .active{
     /***your action***/
   }

</style>    

How to clone object in C++ ? Or Is there another solution?

If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.

If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.

Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.

Find all packages installed with easy_install/pip?

pip freeze will output a list of installed packages and their versions. It also allows you to write those packages to a file that can later be used to set up a new environment.

https://pip.pypa.io/en/stable/reference/pip_freeze/#pip-freeze

How to set default values for Angular 2 component properties?

Here is the best solution for this. (ANGULAR All Version)

Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.

I have provided solution for this kind of similar question. You can find the full solution from here

export class CarComponent implements OnInit {
  private _defaultCar: car = {
    // default isCar is true
    isCar: true,
    // default wheels  will be 4
    wheels: 4
  };

  @Input() newCar: car = {};

  constructor() {}

  ngOnInit(): void {

   // this will concate both the objects and the object declared later (ie.. ...this.newCar )
   // will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT

    this.newCar = { ...this._defaultCar, ...this.newCar };
   //  console.log(this.newCar);
  }
}

Import JavaScript file and call functions using webpack, ES6, ReactJS

import * as utils from './utils.js'; 

If you do the above, you will be able to use functions in utils.js as

utils.someFunction()

Dynamically adding elements to ArrayList in Groovy

What you actually created with:

MyType[] list = []

Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:

MyType[] array = new MyType[4]

But there's no add method of course.

If you create list with def it's something like creating this instance with Object (You can read more about def here). And [] creates empty ArrayList in this case.

So using def list = [] you can then append new items with add() method of ArrayList

list.add(new MyType())

Or more groovy way with overloaded left shift operator:

list << new MyType() 

Android Paint: .measureText() vs .getTextBounds()

My experience with this is that getTextBounds will return that absolute minimal bounding rect that encapsulates the text, not necessarily the measured width used when rendering. I also want to say that measureText assumes one line.

In order to get accurate measuring results, you should use the StaticLayout to render the text and pull out the measurements.

For example:

String text = "text";
TextPaint textPaint = textView.getPaint();
int boundedWidth = 1000;

StaticLayout layout = new StaticLayout(text, textPaint, boundedWidth , Alignment.ALIGN_NORMAL, 1.0f, 0.0f, false);
int height = layout.getHeight();

Force Java timezone as GMT/UTC

Also if you can set JVM timezone this way

System.setProperty("user.timezone", "EST");

or -Duser.timezone=GMT in the JVM args.

What is the standard Python docstring format?

Docstring conventions are in PEP-257 with much more detail than PEP-8.

However, docstrings seem to be far more personal than other areas of code. Different projects will have their own standard.

I tend to always include docstrings, because they tend to demonstrate how to use the function and what it does very quickly.

I prefer to keep things consistent, regardless of the length of the string. I like how to code looks when indentation and spacing are consistent. That means, I use:

def sq(n):
    """
    Return the square of n. 
    """
    return n * n

Over:

def sq(n):
    """Returns the square of n."""
    return n * n

And tend to leave off commenting on the first line in longer docstrings:

def sq(n):
    """
    Return the square of n, accepting all numeric types:

    >>> sq(10)
    100

    >>> sq(10.434)
    108.86835599999999

    Raises a TypeError when input is invalid:

    >>> sq(4*'435')
    Traceback (most recent call last):
      ...
    TypeError: can't multiply sequence by non-int of type 'str'

    """
    return n*n

Meaning I find docstrings that start like this to be messy.

def sq(n):
    """Return the squared result. 
    ...

How to check that an element is in a std::set?

I was able to write a general contains function for std::list and std::vector,

template<typename T>
bool contains( const list<T>& container, const T& elt )
{
  return find( container.begin(), container.end(), elt ) != container.end() ;
}

template<typename T>
bool contains( const vector<T>& container, const T& elt )
{
  return find( container.begin(), container.end(), elt ) != container.end() ;
}

// use:
if( contains( yourList, itemInList ) ) // then do something

This cleans up the syntax a bit.

But I could not use template template parameter magic to make this work arbitrary stl containers.

// NOT WORKING:
template<template<class> class STLContainer, class T>
bool contains( STLContainer<T> container, T elt )
{
  return find( container.begin(), container.end(), elt ) != container.end() ;
}

Any comments about improving the last answer would be nice.

PHPMyAdmin Default login password

Default is:

Username: root

Password: [null]

The Password is set to 'password' in some versions.

String representation of an Enum

You can reference the name rather than the value by using ToString()

Console.WriteLine("Auth method: {0}", AuthenticationMethod.Forms.ToString());

The documentation is here:

http://msdn.microsoft.com/en-us/library/16c1xs4z.aspx

...and if you name your enums in Pascal Case (as I do - such as ThisIsMyEnumValue = 1 etc.) then you could use a very simple regex to print the friendly form:

static string ToFriendlyCase(this string EnumString)
{
    return Regex.Replace(EnumString, "(?!^)([A-Z])", " $1");
}

which can easily be called from any string:

Console.WriteLine("ConvertMyCrazyPascalCaseSentenceToFriendlyCase".ToFriendlyCase());

Outputs:

Convert My Crazy Pascal Case Sentence To Friendly Case

That saves running all the way around the houses creating custom attributes and attaching them to your enums or using lookup tables to marry an enum value with a friendly string and best of all it's self managing and can be used on any Pascal Case string which is infinitely more reusable. Of course, it doesn't allow you to have a different friendly name than your enum which your solution does provide.

I do like your original solution though for more complex scenarios though. You could take your solution one step further and make your GetStringValue an extension method of your enum and then you wouldn't need to reference it like StringEnum.GetStringValue...

public static string GetStringValue(this AuthenticationMethod value)
{
  string output = null;
  Type type = value.GetType();
  FieldInfo fi = type.GetField(value.ToString());
  StringValue[] attrs = fi.GetCustomAttributes(typeof(StringValue), false) as StringValue[];
  if (attrs.Length > 0)
    output = attrs[0].Value;
  return output;
}

You could then access it easily straight from your enum instance:

Console.WriteLine(AuthenticationMethod.SSO.GetStringValue());

Is there a way to get the source code from an APK file?

Use this tool http://www.javadecompilers.com/

But recently, a new wave of decompilers has forayed onto the market: Procyon, CFR, JD, Fernflower, Krakatau, Candle.

Here's a list of decompilers presented on this site:

CFR - Free, no source-code available, http://www.benf.org/other/cfr/ Author: Lee Benfield

Very well-updated decompiler! CFR is able to decompile modern Java features - Java 9 modules, Java 8 lambdas, Java 7 String switches etc. It'll even make a decent go of turning class files from other JVM langauges back into java!

JD - free for non-commercial use only, http://jd.benow.ca/ Author: Emmanuel Dupuy

Updated in 2015. Has its own visual interface and plugins to Eclipse and IntelliJ . Written in C++, so very fast. Supports Java 5.

Procyon - open-source, https://bitbucket.org/mstrobel/procyon/wiki/Java%20Decompiler Author: Mike Strobel

Fernflower - open-source, https://github.com/fesh0r/fernflower Author: Egor Ushakov

Updated in 2015. Very promising analytical Java decompiler, now becomes an integral part of IntelliJ 14. (https://github.com/JetBrains/intellij-community/tree/master/plugins/java-decompiler) Supports Java up to version 6 (Annotations, generics, enums)

JAD - given here only for historical reason. Free, no source-code available, jad download mirror Author: Pavel Kouznetsov

What's the difference between 'r+' and 'a+' when open file in python?

One difference is for r+ if the files does not exist, it'll not be created and open fails. But in case of a+ the file will be created if it does not exist.

Remove first Item of the array (like popping from stack)

The easiest way is using shift(). If you have an array, the shift function shifts everything to the left.

var arr = [1, 2, 3, 4]; 
var theRemovedElement = arr.shift(); // theRemovedElement == 1
console.log(arr); // [2, 3, 4]

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

8388608 bytes is 8M, the default limit in PHP. Update your post_max_size in php.ini to a larger value.

upload_max_filesize sets the max file size that a user can upload while post_max_size sets the maximum amount of data that can be sent via a POST in a form.

So you can set upload_max_filesize to 1 meg, which will mean that the biggest single file a user can upload is 1 megabyte, but they could upload 5 of them at once if the post_max_size was set to 5.

Python: Tuples/dictionaries as keys, select, sort

Database, dict of dicts, dictionary of list of dictionaries, named tuple (it's a subclass), sqlite, redundancy... I didn't believe my eyes. What else ?

"It might well be that dictionaries with tuples as keys are not the proper way to handle this situation."

"my gut feeling is that a database is overkill for the OP's needs; "

Yeah! I thought

So, in my opinion, a list of tuples is plenty enough :

from operator import itemgetter

li = [  ('banana',     'blue'   , 24) ,
        ('apple',      'green'  , 12) ,
        ('strawberry', 'blue'   , 16 ) ,
        ('banana',     'yellow' , 13) ,
        ('apple',      'gold'   , 3 ) ,
        ('pear',       'yellow' , 10) ,
        ('strawberry', 'orange' , 27) ,
        ('apple',      'blue'   , 21) ,
        ('apple',      'silver' , 0 ) ,
        ('strawberry', 'green'  , 4 ) ,
        ('banana',     'brown'  , 14) ,
        ('strawberry', 'yellow' , 31) ,
        ('apple',      'pink'   , 9 ) ,
        ('strawberry', 'gold'   , 0 ) ,
        ('pear',       'gold'   , 66) ,
        ('apple',      'yellow' , 9 ) ,
        ('pear',       'brown'  , 5 ) ,
        ('strawberry', 'pink'   , 8 ) ,
        ('apple',      'purple' , 7 ) ,
        ('pear',       'blue'   , 51) ,
        ('chesnut',    'yellow',  0 )   ]


print set( u[1] for u in li ),': all potential colors'
print set( c for f,c,n in li if n!=0),': all effective colors'
print [ c for f,c,n in li if f=='banana' ],': all potential colors of bananas'
print [ c for f,c,n in li if f=='banana' and n!=0],': all effective colors of bananas'
print

print set( u[0] for u in li ),': all potential fruits'
print set( f for f,c,n in li if n!=0),': all effective fruits'
print [ f for f,c,n in li if c=='yellow' ],': all potential fruits being yellow'
print [ f for f,c,n in li if c=='yellow' and n!=0],': all effective fruits being yellow'
print

print len(set( u[1] for u in li )),': number of all potential colors'
print len(set(c for f,c,n in li if n!=0)),': number of all effective colors'
print len( [c for f,c,n in li if f=='strawberry']),': number of potential colors of strawberry'
print len( [c for f,c,n in li if f=='strawberry' and n!=0]),': number of effective colors of strawberry'
print

# sorting li by name of fruit
print sorted(li),'  sorted li by name of fruit'
print

# sorting li by number 
print sorted(li, key = itemgetter(2)),'  sorted li by number'
print

# sorting li first by name of color and secondly by name of fruit
print sorted(li, key = itemgetter(1,0)),'  sorted li first by name of color and secondly by name of fruit'
print

result

set(['blue', 'brown', 'gold', 'purple', 'yellow', 'pink', 'green', 'orange', 'silver']) : all potential colors
set(['blue', 'brown', 'gold', 'purple', 'yellow', 'pink', 'green', 'orange']) : all effective colors
['blue', 'yellow', 'brown'] : all potential colors of bananas
['blue', 'yellow', 'brown'] : all effective colors of bananas

set(['strawberry', 'chesnut', 'pear', 'banana', 'apple']) : all potential fruits
set(['strawberry', 'pear', 'banana', 'apple']) : all effective fruits
['banana', 'pear', 'strawberry', 'apple', 'chesnut'] : all potential fruits being yellow
['banana', 'pear', 'strawberry', 'apple'] : all effective fruits being yellow

9 : number of all potential colors
8 : number of all effective colors
6 : number of potential colors of strawberry
5 : number of effective colors of strawberry

[('apple', 'blue', 21), ('apple', 'gold', 3), ('apple', 'green', 12), ('apple', 'pink', 9), ('apple', 'purple', 7), ('apple', 'silver', 0), ('apple', 'yellow', 9), ('banana', 'blue', 24), ('banana', 'brown', 14), ('banana', 'yellow', 13), ('chesnut', 'yellow', 0), ('pear', 'blue', 51), ('pear', 'brown', 5), ('pear', 'gold', 66), ('pear', 'yellow', 10), ('strawberry', 'blue', 16), ('strawberry', 'gold', 0), ('strawberry', 'green', 4), ('strawberry', 'orange', 27), ('strawberry', 'pink', 8), ('strawberry', 'yellow', 31)]   sorted li by name of fruit

[('apple', 'silver', 0), ('strawberry', 'gold', 0), ('chesnut', 'yellow', 0), ('apple', 'gold', 3), ('strawberry', 'green', 4), ('pear', 'brown', 5), ('apple', 'purple', 7), ('strawberry', 'pink', 8), ('apple', 'pink', 9), ('apple', 'yellow', 9), ('pear', 'yellow', 10), ('apple', 'green', 12), ('banana', 'yellow', 13), ('banana', 'brown', 14), ('strawberry', 'blue', 16), ('apple', 'blue', 21), ('banana', 'blue', 24), ('strawberry', 'orange', 27), ('strawberry', 'yellow', 31), ('pear', 'blue', 51), ('pear', 'gold', 66)]   sorted li by number

[('apple', 'blue', 21), ('banana', 'blue', 24), ('pear', 'blue', 51), ('strawberry', 'blue', 16), ('banana', 'brown', 14), ('pear', 'brown', 5), ('apple', 'gold', 3), ('pear', 'gold', 66), ('strawberry', 'gold', 0), ('apple', 'green', 12), ('strawberry', 'green', 4), ('strawberry', 'orange', 27), ('apple', 'pink', 9), ('strawberry', 'pink', 8), ('apple', 'purple', 7), ('apple', 'silver', 0), ('apple', 'yellow', 9), ('banana', 'yellow', 13), ('chesnut', 'yellow', 0), ('pear', 'yellow', 10), ('strawberry', 'yellow', 31)]   sorted li first by name of color and secondly by name of fruit

Select a random sample of results from a query result

I know this has already been answered, but seeing so many visits here I'd like to add one version that uses the SAMPLE clause but still allows to filter the rows first:

with cte1 as (
    select *
    from t_your_table
    where your_column = 'ABC'
)
select * from cte1 sample (5)

Note however that the base select needs a ROWID column, which means it may not work for some views for example.

Pass a datetime from javascript to c# (Controller)

The following format should work:

$.ajax({
    type: "POST",
    url: "@Url.Action("refresh", "group")",
    contentType: "application/json; charset=utf-8",
    data: JSON.stringify({ 
        myDate: '2011-04-02 17:15:45'
    }),
    success: function (result) {
        //do something
    },
    error: function (req, status, error) {
        //error                        
    }
});

What is a mutex?

Mutual Exclusion. Here's the Wikipedia entry on it.

The point of a mutex is to synchronize two threads. When you have two threads attempting to access a single resource, the general pattern is to have the first block of code attempting access to set the mutex before entering the code. When the second code block attempts access, it sees that the mutex is set and waits until the first block of code is complete (and unsets the mutex), then continues.

Specific details of how this is accomplished obviously varies greatly by programming language.

How can I add new item to the String array?

You can't do it the way you wanted.

Use ArrayList instead:

List<String> a = new ArrayList<String>();
a.add("kk");
a.add("pp");

And then you can have an array again by using toArray:

String[] myArray = new String[a.size()];
a.toArray(myArray);

How to retrieve raw post data from HttpServletRequest in java

This worked for me: (notice that java 8 is required)

String requestData = request.getReader().lines().collect(Collectors.joining());
UserJsonParser u = gson.fromJson(requestData, UserJsonParser.class);

UserJsonParse is a class that shows gson how to parse the json formant.

class is like that:

public class UserJsonParser {

    private String username;
    private String name;
    private String lastname;
    private String mail;
    private String pass1;
//then put setters and getters
}

the json string that is parsed is like that:

$jsonData: {    "username": "testuser",    "pass1": "clave1234" }

The rest of values (mail, lastname, name) are set to null

Correct way to convert size in bytes to KB, MB, GB in JavaScript

This is how a byte should be shown to a human:

function bytesToHuman(bytes, decimals = 2) {
  // https://en.wikipedia.org/wiki/Orders_of_magnitude_(data)
  const units = ["bytes", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"]; // etc

  let i = 0;
  let h = 0;

  let c = 1 / 1023; // change it to 1024 and see the diff

  for (; h < c && i < units.length; i++) {
    if ((h = Math.pow(1024, i) / bytes) >= c) {
      break;
    }
  }

  // remove toFixed and let `locale` controls formatting
  return (1 / h).toFixed(decimals).toLocaleString() + " " + units[i];
}

// test
for (let i = 0; i < 9; i++) {
  let val = i * Math.pow(10, i);
  console.log(val.toLocaleString() + " bytes is the same as " + bytesToHuman(val));

}

// let's fool around
console.log(bytesToHuman(1023));
console.log(bytesToHuman(1024));
console.log(bytesToHuman(1025));

How to dynamically change the color of the selected menu item of a web page?

There is a pure CSS solution I'm currently using.

Add a body ID (or class) identifying your pages and your menu items, then use something like:

HTML:

<html>
    <body id="body_questions">
        <ul class="menu">
            <li id="questions">Question</li>
            <li id="tags">Tags</li>
            <li id="users">Users</li>
        </ul>
        ...
    </body>
</html>

CSS:

.menu li:hover,
#body_questions #questions,
#body_tags      #tags,
#body_users     #users {
    background-color: #f90;
}

No value accessor for form control

If you get this issue, then either

  • the formControlName is not located on the value accessor element.
  • or you're not importing the module for that element.

Difference between natural join and inner join

mysql> SELECT  * FROM tb1 ;
+----+------+
| id | num  |
+----+------+
|  6 |   60 |
|  7 |   70 |
|  8 |   80 |
|  1 |    1 |
|  2 |    2 |
|  3 |    3 |
+----+------+
6 rows in set (0.00 sec)

mysql> SELECT  * FROM tb2 ;
+----+------+
| id | num  |
+----+------+
|  4 |   40 |
|  5 |   50 |
|  9 |   90 |
|  1 |    1 |
|  2 |    2 |
|  3 |    3 |
+----+------+
6 rows in set (0.00 sec)

INNER JOIN :

mysql> SELECT  * FROM tb1 JOIN tb2 ; 
+----+------+----+------+
| id | num  | id | num  |
+----+------+----+------+
|  6 |   60 |  4 |   40 |
|  7 |   70 |  4 |   40 |
|  8 |   80 |  4 |   40 |
|  1 |    1 |  4 |   40 |
|  2 |    2 |  4 |   40 |
|  3 |    3 |  4 |   40 |
|  6 |   60 |  5 |   50 |
|  7 |   70 |  5 |   50 |
|  8 |   80 |  5 |   50 |
.......more......
return 36 rows in set (0.01 sec) 
AND NATURAL JOIN :

    mysql> SELECT  * FROM tb1 NATURAL JOIN tb2 ;
    +----+------+
    | id | num  |
    +----+------+
    |  1 |    1 |
    |  2 |    2 |
    |  3 |    3 |
    +----+------+
    3 rows in set (0.01 sec)

How to get the text of the selected value of a dropdown list?

Hi if you are having dropdownlist like this

<select id="testID">
<option value="1">Value1</option>
<option value="2">Value2</option>
<option value="3">Value3</option>
<option value="4">Value4</option>
<option value="5">Value5</option>
<option value="6">Value6</option>
</select>
<input type="button" value="Get dropdown selected Value" onclick="getHTML();">

after giving id to dropdownlist you just need to add jquery code like this

function getHTML()
{
      var display=$('#testID option:selected').html();
      alert(display);
}

Difference between numpy dot() and Python 3.5+ matrix multiplication @

In mathematics, I think the dot in numpy makes more sense

dot(a,b)_{i,j,k,a,b,c} = formula

since it gives the dot product when a and b are vectors, or the matrix multiplication when a and b are matrices


As for matmul operation in numpy, it consists of parts of dot result, and it can be defined as

>matmul(a,b)_{i,j,k,c} = formula

So, you can see that matmul(a,b) returns an array with a small shape, which has smaller memory consumption and make more sense in applications. In particular, combining with broadcasting, you can get

matmul(a,b)_{i,j,k,l} = formula

for example.


From the above two definitions, you can see the requirements to use those two operations. Assume a.shape=(s1,s2,s3,s4) and b.shape=(t1,t2,t3,t4)

  • To use dot(a,b) you need

    1. t3=s4;
  • To use matmul(a,b) you need

    1. t3=s4
    2. t2=s2, or one of t2 and s2 is 1
    3. t1=s1, or one of t1 and s1 is 1

Use the following piece of code to convince yourself.

Code sample

import numpy as np
for it in xrange(10000):
    a = np.random.rand(5,6,2,4)
    b = np.random.rand(6,4,3)
    c = np.matmul(a,b)
    d = np.dot(a,b)
    #print 'c shape: ', c.shape,'d shape:', d.shape

    for i in range(5):
        for j in range(6):
            for k in range(2):
                for l in range(3):
                    if not c[i,j,k,l] == d[i,j,k,j,l]:
                        print it,i,j,k,l,c[i,j,k,l]==d[i,j,k,j,l] #you will not see them

How do you underline a text in Android XML?

I used below method, it worked for me. Below is example for Button but we can use in TextView as well.

Button btnClickMe = (Button) findViewById(R.id.btn_click_me);
btnClickMe.setPaintFlags(btnClickMe.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);

java.util.NoSuchElementException: No line found

with Scanner you need to check if there is a next line with hasNextLine()

so the loop becomes

while(sc.hasNextLine()){
    str=sc.nextLine();
    //...
}

it's readers that return null on EOF

ofcourse in this piece of code this is dependent on whether the input is properly formatted

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

In the java programs I have written for release I used the motherboard serial number (which is what I beleive windows use); however, this only works on windows as my function creates a temporary VB script which uses the WMI to retrieve the value.

public static String getMotherboardSerial() {
      String result = "";
        try {
          File file = File.createTempFile("GetMBSerial",".vbs");
          file.deleteOnExit();
          FileWriter fw = new FileWriter(file);

          String vbs =
             "Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
            + "Set colItems = objWMIService.ExecQuery _ \n"
            + "   (\"Select * from Win32_ComputerSystemProduct\") \n"
            + "For Each objItem in colItems \n"
            + "    Wscript.Echo objItem.IdentifyingNumber \n"
            + "Next \n";

          fw.write(vbs);
          fw.close();
          Process gWMI = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
          BufferedReader input = new BufferedReader(new InputStreamReader(gWMI.getInputStream()));
          String line;
          while ((line = input.readLine()) != null) {
             result += line;
             System.out.println(line);
          }
          input.close();
        }
        catch(Exception e){
            e.printStackTrace();
        }
        result = result.trim();
        return result;
      }

Using a dictionary to select function to execute

Not proud of it, but:

def myMain(key):
    def ExecP1():
        pass
    def ExecP2():
        pass
    def ExecP3():
        pass
    def ExecPn():
        pass 
    locals()['Exec' + key]()

I do however recommend that you put those in a module/class whatever, this is truly horrible.

How to create an XML document using XmlDocument?

Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here

and edited my code: (xmlDoc.DocumentElement.AppendChild(body))

//a dictionary:
Dictionary<string, string> Level2Data 
{
    {"level2", "text"},
    {"level2", "other text"},
    {"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR



foreach (KeyValuePair<string, string> entry in Level2Data)
{
    //write to xml: - it works version 1.
    XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
    keyNode.InnerText = entry.Value;
    body.AppendChild(keyNode); //close TAB

    //Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
    //XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
    //XmlText value = xmlDoc.CreateTextNode(entry.Value);
    //key.AppendChild(value);
    //body.AppendChild(key);
}

Both versions (1 and 2 inside foreach loop) give the output:

<?xml version="1.0" encoding="UTF-8"?>
<body>
    <level1>
        <level2>text</level2>
        <level2>ther text</level2>
         <same_level2>more text</same_level2>
    </level1>
</body>

(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.

How do I erase an element from std::vector<> by index?

If you have an unordered vector you can take advantage of the fact that it's unordered and use something I saw from Dan Higgins at CPPCON

template< typename TContainer >
static bool EraseFromUnorderedByIndex( TContainer& inContainer, size_t inIndex )
{
    if ( inIndex < inContainer.size() )
    {
        if ( inIndex != inContainer.size() - 1 )
            inContainer[inIndex] = inContainer.back();
        inContainer.pop_back();
        return true;
    }
    return false;
}

Since the list order doesn't matter, just take the last element in the list and copy it over the top of the item you want to remove, then pop and delete the last item.

SyntaxError: expected expression, got '<'

The main idea is that somehow HTML has been returned instead of Javascript.

The reason may be:

  • wrong paths
  • assets itself

It may be caused by wrong assets precompilation. In my case, I caught this error because of wrong encoding.

When I opened my application.js I saw application error Encoding::UndefinedConversionError at /assets/application.js

There was full backtrace of error formatted as HTML instead of Javasript.

Make sure that assets had been successfully precompiled.

How do I make a JAR from a .java file?

Open a command prompt.

Go to the directory where you have your .java files

Create a directory build

Run java compilation from the command line

javac -d ./build *.java

if there are no errors, in the build directory you should have your class tree

move to the build directory and do a

jar cvf YourJar.jar *

For adding manifest check jar command line switches

How do I set headers using python's urllib?

For multiple headers do as follow:

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('param1', '212212')
req.add_header('param2', '12345678')
req.add_header('other_param1', 'sample')
req.add_header('other_param2', 'sample1111')
req.add_header('and_any_other_parame', 'testttt')
resp = urllib2.urlopen(req)
content = resp.read()

Java JSON serialization - best practice

As others have hinted, you should consider dumping org.json's library. It's pretty much obsolete these days, and trying to work around its problems is waste of time.

But to specific question; type variable T just does not have any information to help you, as it is little more than compile-time information. Instead you need to pass actual class (as 'Class cls' argument), and you can then create an instance with 'cls.newInstance()'.

TypeError: $(...).on is not a function

In my case this code solved my error :

(function (window, document, $) {
            'use strict';
             var $html = $('html');
             $('input[name="myiCheck"]').on('ifClicked', function (event) {
             alert("You clicked " + this.value);
             });
})(window, document, jQuery);

You don't should put your function inside $(document).ready

How to get current value of RxJS Subject or Observable?

You could store the last emitted value separately from the Observable. Then read it when needed.

let lastValue: number;

const subscription = new Service().start();
subscription
    .subscribe((data) => {
        lastValue = data;
    }
);

How can I make Visual Studio wrap lines at 80 characters?

If the problem is simply that you want to know when you pass 80 characters for a single line, which is a common coding guideline limit, you can use a different approach: Editor Guidelines. This will add vertical column guides behind your code.

Cmake doesn't find Boost

I struggled with this problem for a while myself. It turned out that cmake was looking for Boost library files using Boost's naming convention, in which the library name is a function of the compiler version used to build it. Our Boost libraries were built using GCC 4.9.1, and that compiler version was in fact present on our system; however, GCC 4.4.7 also happened to be installed. As it happens, cmake's FindBoost.cmake script was auto-detecting the GCC 4.4.7 installation instead of the GCC 4.9.1 one, and thus was looking for Boost library files with "gcc44" in the file names, rather than "gcc49".

The simple fix was to force cmake to assume that GCC 4.9 was present, by setting Boost_COMPILER to "-gcc49" in CMakeLists.txt. With this change, FindBoost.cmake looked for, and found, my Boost library files.

How do I drop a function if it already exists?

This works for any object, not just functions:

IF OBJECT_ID('YourObjectName') IS NOT NULL 

then just add your flavor of object, as in:

IF OBJECT_ID('YourFunction') IS NOT NULL
   DROP FUNCTION YourFunction

How to overcome root domain CNAME restrictions?

I see readytocloud.com is hosted on Apache 2.2.

There is a much simpler and more efficient way to redirect the non-www site to the www site in Apache.

Add the following rewrite rules to the Apache configs (either inside the virtual host or outside. It doesn't matter):

RewriteCond %{HTTP_HOST} ^readytocloud.com [NC]
RewriteRule ^/$ http://www.readytocloud.com/ [R=301,L]

Or, the following rewrite rules if you want a 1-to-1 mapping of URLs from the non-www site to the www site:

RewriteCond %{HTTP_HOST} ^readytocloud.com [NC]
RewriteRule (.*) http://www.readytocloud.com$1 [R=301,L]

Note, the mod_rewrite module needs to be loaded for this to work. Luckily readytocloud.com is runing on a CentOS box, which by default loads mod_rewrite.

We have a client server running Apache 2.2 with just under 3,000 domains and nearly 4,000 redirects, however, the load on the server hover around 0.10 - 0.20.

How to set HttpResponse timeout for Android in Java

you can creat HttpClient instance by the way with Httpclient-android-4.3.5,it can work well.

 SSLContext sslContext = SSLContexts.createSystemDefault();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                sslContext,
                SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
                RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCircularRedirectsAllowed(false).setConnectionRequestTimeout(30*1000).setConnectTimeout(30 * 1000).setMaxRedirects(10).setSocketTimeout(60 * 1000);
        CloseableHttpClient hc = HttpClients.custom().setSSLSocketFactory(sslsf).setDefaultRequestConfig(requestConfigBuilder.build()).build();

Does Python have a package/module management system?

And just to provide a contrast, there's also pip.

jquery onclick change css background image

I think this should be:

$('.home').click(function() {
     $(this).css('background', 'url(images/tabs3.png)');
 });

and remove this:

<div class="home" onclick="function()">
     //-----------^^^^^^^^^^^^^^^^^^^^---------no need for this

You have to make sure you have a correct path to your image.

How to read .pem file to get private and public key

Java supports using DER for public and private keys out of the box (which is basically the same as PEM, as the OP asks, except PEM files contain base 64 data plus header and footer lines).

You can rely on this code (modulo exception handling) without any external library if you are on Java 8+ (this assumes your key files are available in the classpath):

class Signer {
    private KeyFactory keyFactory;

    public Signer() {
        this.keyFactory = KeyFactory.getInstance("RSA");
    }

    public PublicKey getPublicKey() {
        byte[] publicKey = readFileAsBytes("public-key.der");

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);

        return keyFactory.generatePublic(keySpec);
    }

    public PrivateKey getPrivateKey() {
        byte[] privateKey = readFileAsBytes("private-key.der");

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKey);
    
        return keyFactory.generatePrivate(keySpec);
    }

    private URI readFileAsBytes(String name) {
        URI fileUri = getClass().getClassLoader().getResource(name).toURI();

        return Files.readAllBytes(Paths.get(fileUri));
    }
}

For the record, you can convert a PEM key to a DER key with the following command:

$ openssl pkcs8 -topk8 -inform PEM -outform DER -in private-key.pem -out private-key.der -nocrypt

And get the public key in DER with:

$ openssl rsa -in private-key.pem -pubout -outform DER -out public-key.der

Keras, how do I predict after I trained a model?

I trained a neural network in Keras to perform non linear regression on some data. This is some part of my code for testing on new data using previously saved model configuration and weights.

fname = r"C:\Users\tauseef\Desktop\keras\tutorials\BestWeights.hdf5"
modelConfig = joblib.load('modelConfig.pkl')
recreatedModel = Sequential.from_config(modelConfig)
recreatedModel.load_weights(fname)
unseenTestData = np.genfromtxt(r"C:\Users\tauseef\Desktop\keras\arrayOf100Rows257Columns.txt",delimiter=" ")
X_test = unseenTestData
standard_scalerX = StandardScaler()
standard_scalerX.fit(X_test)
X_test_std = standard_scalerX.transform(X_test)
X_test_std = X_test_std.astype('float32')
unseenData_predictions = recreatedModel.predict(X_test_std)

How can I get the concatenation of two lists in Python without modifying either one?

And if you have more than two lists to concatenate:

import operator
from functools import reduce  # For Python 3
list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
reduce(operator.add, [list1, list2, list3])

# or with an existing list
all_lists = [list1, list2, list3]
reduce(operator.add, all_lists)

It doesn't actually save you any time (intermediate lists are still created) but nice if you have a variable number of lists to flatten, e.g., *args.

Python 101: Can't open file: No such file or directory

Try uninstalling Python and then install it again, but this time make sure that the option Add Python to Path is marked as checked during the installation process.

Escaping backslash in string - javascript

Escape the backslash character.

foo.split('\\')

How to debug when Kubernetes nodes are in 'Not Ready' state

I recently started using VMWare Octant https://github.com/vmware-tanzu/octant. This is a better UI than the Kubernetes Dashboard. You can view the Kubernetes cluster and look at the details of the cluster and the PODS. This will allow you to check the logs and open a terminal into the POD(s).

Image overlay on responsive sized images bootstrap

I had a bit of trouble getting this to work as well. Using brouxhaha's answer got me 90% of the way to what I was looking for. But the padding adjust wouldn't allow me to put the text anywhere I wanted. Using top and left seemed to work better for my purposes.

.project-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    color: #fff;
    top: 80%;
    left: 20%;
}

http://jsfiddle.net/1rz0b7d8/1/

Permanently adding a file path to sys.path in Python

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run 'export' cmd and check the output or you can check it using this cmd:

python -c "import sys; print(sys.path)"

Why can't radio buttons be "readonly"?

Radio buttons would only need to be read-only if there are other options. If you don't have any other options, a checked radio button cannot be unchecked. If you have other options, you can prevent the user from changing the value merely by disabling the other options:

<input type="radio" name="foo" value="Y" checked>
<input type="radio" name="foo" value="N" disabled>

Fiddle: http://jsfiddle.net/qqVGu/

phpmailer - The following SMTP Error: Data not accepted

For AWS users who work with Amazon SES in conjunction with PHPMailer, this error also appears when your "from" mail sender isn't a verified sender.

To add a verified sender:

  1. Log in to your Amazon AWS console: https://console.aws.amazon.com

  2. Select "Amazon SES" from your list of available AWS applications

  3. Select, under "Verified Senders", the "Email Addresses" --> "Verify a new email address"

  4. Navigate to that new sender's email, click the confirmation e-mail's link.

And you're all set.

How do I access my SSH public key?

If you're on Windows use the following, select all, and copy from a Notepad window:

notepad ~/.ssh/id_rsa.pub  

If you're on OS X, use:

pbcopy < ~/.ssh/id_rsa.pub

Add new column with foreign key constraint in one command

In MS SQL SERVER:

With user defined foreign key name

ALTER TABLE tableName
ADD columnName dataType,
CONSTRAINT fkName FOREIGN KEY(fkColumnName) 
   REFERENCES pkTableName(pkTableColumnName);

Without user defined foreign key name

ALTER TABLE tableName
ADD columnName dataType,
FOREIGN KEY(fkColumnName) REFERENCES pkTableName(pkTableColumnName);

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

Eclipse error: indirectly referenced from required .class files?

It happens to me sometimes, I always fixed that with "mvn eclipse:clean" command to clean old properties and then run mvn eclipse:eclipse -Dwtpversion=2.0 (for web project of course). There are some old properties saved so eclipse is confused sometimes.

Spring Boot Remove Whitelabel Error Page

I was trying to call a REST endpoint from a microservice and I was using the resttemplate's put method.

In my design if any error occurred inside the REST endpoint it should return a JSON error response, it was working for some calls but not for this put one, it returned the white label error page instead.

So I did some investigation and I found out that;

Spring try to understand the caller if it is a machine then it returns JSON response or if it is a browser than it returns the white label error page HTML.

As a result: my client app needed to say to REST endpoint that the caller is a machine, not a browser so for this the client app needed to add 'application/json' into the ACCEPT header explicitly for the resttemplate's 'put' method. I added this to the header and solved the problem.

my call to the endpoint:

restTemplate.put(url, request, param1, param2);

for above call I had to add below header param.

headers.set("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);

or I tried to change put to exchange as well, in this case, exchange call added the same header for me and solved the problem too but I don't know why :)

restTemplate.exchange(....)

Can I rollback a transaction I've already committed? (data loss)

No, you can't undo, rollback or reverse a commit.

STOP THE DATABASE!

(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

Urgent mitigation

Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

Ways some data could've survived

If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.

Recovery

You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

See: pg_dirtyread on GitHub.

I've removed what I'd written in this section as it's obsoleted by that tool.

See also PostgreSQL row storage fundamentals

Prevention

See my blog entry Preventing PostgreSQL database corruption.


On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.

Difference between OpenJDK and Adoptium/AdoptOpenJDK

In short:

  • OpenJDK has multiple meanings and can refer to:
    • free and open source implementation of the Java Platform, Standard Edition (Java SE)
    • open source repository — the Java source code aka OpenJDK project
    • prebuilt OpenJDK binaries maintained by Oracle
    • prebuilt OpenJDK binaries maintained by the OpenJDK community
  • AdoptOpenJDK — prebuilt OpenJDK binaries maintained by community (open source licensed)

Explanation:

Prebuilt OpenJDK (or distribution) — binaries, built from http://hg.openjdk.java.net/, provided as an archive or installer, offered for various platforms, with a possible support contract.

OpenJDK, the source repository (also called OpenJDK project) - is a Mercurial-based open source repository, hosted at http://hg.openjdk.java.net. The Java source code. The vast majority of Java features (from the VM and the core libraries to the compiler) are based solely on this source repository. Oracle have an alternate fork of this.

OpenJDK, the distribution (see the list of providers below) - is free as in beer and kind of free as in speech, but, you do not get to call Oracle if you have problems with it. There is no support contract. Furthermore, Oracle will only release updates to any OpenJDK (the distribution) version if that release is the most recent Java release, including LTS (long-term support) releases. The day Oracle releases OpenJDK (the distribution) version 12.0, even if there's a security issue with OpenJDK (the distribution) version 11.0, Oracle will not release an update for 11.0. Maintained solely by Oracle.

Some OpenJDK projects - such as OpenJDK 8 and OpenJDK 11 - are maintained by the OpenJDK community and provide releases for some OpenJDK versions for some platforms. The community members have taken responsibility for releasing fixes for security vulnerabilities in these OpenJDK versions.

AdoptOpenJDK, the distribution is very similar to Oracle's OpenJDK distribution (in that it is free, and it is a build produced by compiling the sources from the OpenJDK source repository). AdoptOpenJDK as an entity will not be backporting patches, i.e. there won't be an AdoptOpenJDK 'fork/version' that is materially different from upstream (except for some build script patches for things like Win32 support). Meaning, if members of the community (Oracle or others, but not AdoptOpenJDK as an entity) backport security fixes to updates of OpenJDK LTS versions, then AdoptOpenJDK will provide builds for those. Maintained by OpenJDK community.

OracleJDK - is yet another distribution. Starting with JDK12 there will be no free version of OracleJDK. Oracle's JDK distribution offering is intended for commercial support. You pay for this, but then you get to rely on Oracle for support. Unlike Oracle's OpenJDK offering, OracleJDK comes with longer support for LTS versions. As a developer you can get a free license for personal/development use only of this particular JDK, but that's mostly a red herring, as 'just the binary' is basically the same as the OpenJDK binary. I guess it means you can download security-patched versions of LTS JDKs from Oracle's websites as long as you promise not to use them commercially.

Note. It may be best to call the OpenJDK builds by Oracle the "Oracle OpenJDK builds".

Donald Smith, Java product manager at Oracle writes:

Ideally, we would simply refer to all Oracle JDK builds as the "Oracle JDK", either under the GPL or the commercial license, depending on your situation. However, for historical reasons, while the small remaining differences exist, we will refer to them separately as Oracle’s OpenJDK builds and the Oracle JDK.


OpenJDK Providers and Comparison

----------------------------------------------------------------------------------------
|     Provider      | Free Builds | Free Binary   | Extended | Commercial | Permissive |
|                   | from Source | Distributions | Updates  | Support    | License    |
|--------------------------------------------------------------------------------------|
| AdoptOpenJDK      |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Amazon – Corretto |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Azul Zulu         |    No       |    Yes        |   Yes    |   Yes      |   Yes      |
| BellSoft Liberica |    No       |    Yes        |   Yes    |   Yes      |   Yes      |
| IBM               |    No       |    No         |   Yes    |   Yes      |   Yes      |
| jClarity          |    No       |    No         |   Yes    |   Yes      |   Yes      |
| OpenJDK           |    Yes      |    Yes        |   Yes    |   No       |   Yes      |
| Oracle JDK        |    No       |    Yes        |   No**   |   Yes      |   No       |
| Oracle OpenJDK    |    Yes      |    Yes        |   No     |   No       |   Yes      |
| ojdkbuild         |    Yes      |    Yes        |   No     |   No       |   Yes      |
| RedHat            |    Yes      |    Yes        |   Yes    |   Yes      |   Yes      |
| SapMachine        |    Yes      |    Yes        |   Yes    |   Yes      |   Yes      |
----------------------------------------------------------------------------------------

Free Builds from Source - the distribution source code is publicly available and one can assemble its own build

Free Binary Distributions - the distribution binaries are publicly available for download and usage

Extended Updates - aka LTS (long-term support) - Public Updates beyond the 6-month release lifecycle

Commercial Support - some providers offer extended updates and customer support to paying customers, e.g. Oracle JDK (support details)

Permissive License - the distribution license is non-protective, e.g. Apache 2.0


Which Java Distribution Should I Use?

In the Sun/Oracle days, it was usually Sun/Oracle producing the proprietary downstream JDK distributions based on OpenJDK sources. Recently, Oracle had decided to do their own proprietary builds only with the commercial support attached. They graciously publish the OpenJDK builds as well on their https://jdk.java.net/ site.

What is happening starting JDK 11 is the shift from single-vendor (Oracle) mindset to the mindset where you select a provider that gives you a distribution for the product, under the conditions you like: platforms they build for, frequency and promptness of releases, how support is structured, etc. If you don't trust any of existing vendors, you can even build OpenJDK yourself.

Each build of OpenJDK is usually made from the same original upstream source repository (OpenJDK “the project”). However each build is quite unique - $free or commercial, branded or unbranded, pure or bundled (e.g., BellSoft Liberica JDK offers bundled JavaFX, which was removed from Oracle builds starting JDK 11).

If no environment (e.g., Linux) and/or license requirement defines specific distribution and if you want the most standard JDK build, then probably the best option is to use OpenJDK by Oracle or AdoptOpenJDK.


Additional information

Time to look beyond Oracle's JDK by Stephen Colebourne

Java Is Still Free by Java Champions community (published on September 17, 2018)

Java is Still Free 2.0.0 by Java Champions community (published on March 3, 2019)

Aleksey Shipilev about JDK updates interview by Opsian (published on June 27, 2019)

array.select() in javascript

There's also Array.find() in ES6 which returns the first matching element it finds.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

const myArray = [1, 2, 3]

const myElement = myArray.find((element) => element === 2)

console.log(myElement)
// => 2

Python object deleting itself

class A:
  def __init__(self, function):
    self.function = function
  def kill(self):
    self.function(self)

def delete(object):                        #We are no longer in A object
  del object

a = A(delete)
print(a)
a.kill()
print(a)

May this code work ?

Difference between document.addEventListener and window.addEventListener?

The document and window are different objects and they have some different events. Using addEventListener() on them listens to events destined for a different object. You should use the one that actually has the event you are interested in.

For example, there is a "resize" event on the window object that is not on the document object.

For example, the "DOMContentLoaded" event is only on the document object.

So basically, you need to know which object receives the event you are interested in and use .addEventListener() on that particular object.

Here's an interesting chart that shows which types of objects create which types of events: https://developer.mozilla.org/en-US/docs/DOM/DOM_event_reference


If you are listening to a propagated event (such as the click event), then you can listen for that event on either the document object or the window object. The only main difference for propagated events is in timing. The event will hit the document object before the window object since it occurs first in the hierarchy, but that difference is usually immaterial so you can pick either. I find it generally better to pick the closest object to the source of the event that meets your needs when handling propagated events. That would suggest that you pick document over window when either will work. But, I'd often move even closer to the source and use document.body or even some closer common parent in the document (if possible).

How do I prevent site scraping?

Note: Since the complete version of this answer exceeds Stack Overflow's length limit, you'll need to head to GitHub to read the extended version, with more tips and details.


In order to hinder scraping (also known as Webscraping, Screenscraping, Web data mining, Web harvesting, or Web data extraction), it helps to know how these scrapers work, and , by extension, what prevents them from working well.

There's various types of scraper, and each works differently:

  • Spiders, such as Google's bot or website copiers like HTtrack, which recursively follow links to other pages in order to get data. These are sometimes used for targeted scraping to get specific data, often in combination with a HTML parser to extract the desired data from each page.

  • Shell scripts: Sometimes, common Unix tools are used for scraping: Wget or Curl to download pages, and Grep (Regex) to extract the data.

  • HTML parsers, such as ones based on Jsoup, Scrapy, and others. Similar to shell-script regex based ones, these work by extracting data from pages based on patterns in HTML, usually ignoring everything else.

    For example: If your website has a search feature, such a scraper might submit a request for a search, and then get all the result links and their titles from the results page HTML, in order to specifically get only search result links and their titles. These are the most common.

  • Screenscrapers, based on eg. Selenium or PhantomJS, which open your website in a real browser, run JavaScript, AJAX, and so on, and then get the desired text from the webpage, usually by:

    • Getting the HTML from the browser after your page has been loaded and JavaScript has run, and then using a HTML parser to extract the desired data. These are the most common, and so many of the methods for breaking HTML parsers / scrapers also work here.

    • Taking a screenshot of the rendered pages, and then using OCR to extract the desired text from the screenshot. These are rare, and only dedicated scrapers who really want your data will set this up.

  • Webscraping services such as ScrapingHub or Kimono. In fact, there's people whose job is to figure out how to scrape your site and pull out the content for others to use.

    Unsurprisingly, professional scraping services are the hardest to deter, but if you make it hard and time-consuming to figure out how to scrape your site, these (and people who pay them to do so) may not be bothered to scrape your website.

  • Embedding your website in other site's pages with frames, and embedding your site in mobile apps.

    While not technically scraping, mobile apps (Android and iOS) can embed websites, and inject custom CSS and JavaScript, thus completely changing the appearance of your pages.

  • Human copy - paste: People will copy and paste your content in order to use it elsewhere.

There is a lot overlap between these different kinds of scraper, and many scrapers will behave similarly, even if they use different technologies and methods.

These tips mostly my own ideas, various difficulties that I've encountered while writing scrapers, as well as bits of information and ideas from around the interwebs.

How to stop scraping

You can't completely prevent it, since whatever you do, determined scrapers can still figure out how to scrape. However, you can stop a lot of scraping by doing a few things:

Monitor your logs & traffic patterns; limit access if you see unusual activity:

Check your logs regularly, and in case of unusual activity indicative of automated access (scrapers), such as many similar actions from the same IP address, you can block or limit access.

Specifically, some ideas:

  • Rate limiting:

    Only allow users (and scrapers) to perform a limited number of actions in a certain time - for example, only allow a few searches per second from any specific IP address or user. This will slow down scrapers, and make them ineffective. You could also show a captcha if actions are completed too fast or faster than a real user would.

  • Detect unusual activity:

    If you see unusual activity, such as many similar requests from a specific IP address, someone looking at an excessive number of pages or performing an unusual number of searches, you can prevent access, or show a captcha for subsequent requests.

  • Don't just monitor & rate limit by IP address - use other indicators too:

    If you do block or rate limit, don't just do it on a per-IP address basis; you can use other indicators and methods to identify specific users or scrapers. Some indicators which can help you identify specific users / scrapers include:

    • How fast users fill out forms, and where on a button they click;

    • You can gather a lot of information with JavaScript, such as screen size / resolution, timezone, installed fonts, etc; you can use this to identify users.

    • HTTP headers and their order, especially User-Agent.

    As an example, if you get many request from a single IP address, all using the same User Agent, screen size (determined with JavaScript), and the user (scraper in this case) always clicks on the button in the same way and at regular intervals, it's probably a screen scraper; and you can temporarily block similar requests (eg. block all requests with that user agent and screen size coming from that particular IP address), and this way you won't inconvenience real users on that IP address, eg. in case of a shared internet connection.

    You can also take this further, as you can identify similar requests, even if they come from different IP addresses, indicative of distributed scraping (a scraper using a botnet or a network of proxies). If you get a lot of otherwise identical requests, but they come from different IP addresses, you can block. Again, be aware of not inadvertently blocking real users.

    This can be effective against screenscrapers which run JavaScript, as you can get a lot of information from them.

    Related questions on Security Stack Exchange:

  • Instead of temporarily blocking access, use a Captcha:

    The simple way to implement rate-limiting would be to temporarily block access for a certain amount of time, however using a Captcha may be better, see the section on Captchas further down.

Require registration & login

Require account creation in order to view your content, if this is feasible for your site. This is a good deterrent for scrapers, but is also a good deterrent for real users.

  • If you require account creation and login, you can accurately track user and scraper actions. This way, you can easily detect when a specific account is being used for scraping, and ban it. Things like rate limiting or detecting abuse (such as a huge number of searches in a short time) become easier, as you can identify specific scrapers instead of just IP addresses.

In order to avoid scripts creating many accounts, you should:

  • Require an email address for registration, and verify that email address by sending a link that must be opened in order to activate the account. Allow only one account per email address.

  • Require a captcha to be solved during registration / account creation.

Requiring account creation to view content will drive users and search engines away; if you require account creation in order to view an article, users will go elsewhere.

Block access from cloud hosting and scraping service IP addresses

Sometimes, scrapers will be run from web hosting services, such as Amazon Web Services or GAE, or VPSes. Limit access to your website (or show a captcha) for requests originating from the IP addresses used by such cloud hosting services.

Similarly, you can also limit access from IP addresses used by proxy or VPN providers, as scrapers may use such proxy servers to avoid many requests being detected.

Beware that by blocking access from proxy servers and VPNs, you will negatively affect real users.

Make your error message nondescript if you do block

If you do block / limit access, you should ensure that you don't tell the scraper what caused the block, thereby giving them clues as to how to fix their scraper. So a bad idea would be to show error pages with text like:

  • Too many requests from your IP address, please try again later.

  • Error, User Agent header not present !

Instead, show a friendly error message that doesn't tell the scraper what caused it. Something like this is much better:

  • Sorry, something went wrong. You can contact support via [email protected], should the problem persist.

This is also a lot more user friendly for real users, should they ever see such an error page. You should also consider showing a captcha for subsequent requests instead of a hard block, in case a real user sees the error message, so that you don't block and thus cause legitimate users to contact you.

Use Captchas if you suspect that your website is being accessed by a scraper.

Captchas ("Completely Automated Test to Tell Computers and Humans apart") are very effective against stopping scrapers. Unfortunately, they are also very effective at irritating users.

As such, they are useful when you suspect a possible scraper, and want to stop the scraping, without also blocking access in case it isn't a scraper but a real user. You might want to consider showing a captcha before allowing access to the content if you suspect a scraper.

Things to be aware of when using Captchas:

  • Don't roll your own, use something like Google's reCaptcha : It's a lot easier than implementing a captcha yourself, it's more user-friendly than some blurry and warped text solution you might come up with yourself (users often only need to tick a box), and it's also a lot harder for a scripter to solve than a simple image served from your site

  • Don't include the solution to the captcha in the HTML markup: I've actually seen one website which had the solution for the captcha in the page itself, (although quite well hidden) thus making it pretty useless. Don't do something like this. Again, use a service like reCaptcha, and you won't have this kind of problem (if you use it properly).

  • Captchas can be solved in bulk: There are captcha-solving services where actual, low-paid, humans solve captchas in bulk. Again, using reCaptcha is a good idea here, as they have protections (such as the relatively short time the user has in order to solve the captcha). This kind of service is unlikely to be used unless your data is really valuable.

Serve your text content as an image

You can render text into an image server-side, and serve that to be displayed, which will hinder simple scrapers extracting text.

However, this is bad for screen readers, search engines, performance, and pretty much everything else. It's also illegal in some places (due to accessibility, eg. the Americans with Disabilities Act), and it's also easy to circumvent with some OCR, so don't do it.

You can do something similar with CSS sprites, but that suffers from the same problems.

Don't expose your complete dataset:

If feasible, don't provide a way for a script / bot to get all of your dataset. As an example: You have a news site, with lots of individual articles. You could make those articles be only accessible by searching for them via the on site search, and, if you don't have a list of all the articles on the site and their URLs anywhere, those articles will be only accessible by using the search feature. This means that a script wanting to get all the articles off your site will have to do searches for all possible phrases which may appear in your articles in order to find them all, which will be time-consuming, horribly inefficient, and will hopefully make the scraper give up.

This will be ineffective if:

  • The bot / script does not want / need the full dataset anyway.
  • Your articles are served from a URL which looks something like example.com/article.php?articleId=12345. This (and similar things) which will allow scrapers to simply iterate over all the articleIds and request all the articles that way.
  • There are other ways to eventually find all the articles, such as by writing a script to follow links within articles which lead to other articles.
  • Searching for something like "and" or "the" can reveal almost everything, so that is something to be aware of. (You can avoid this by only returning the top 10 or 20 results).
  • You need search engines to find your content.

Don't expose your APIs, endpoints, and similar things:

Make sure you don't expose any APIs, even unintentionally. For example, if you are using AJAX or network requests from within Adobe Flash or Java Applets (God forbid!) to load your data it is trivial to look at the network requests from the page and figure out where those requests are going to, and then reverse engineer and use those endpoints in a scraper program. Make sure you obfuscate your endpoints and make them hard for others to use, as described.

To deter HTML parsers and scrapers:

Since HTML parsers work by extracting content from pages based on identifiable patterns in the HTML, we can intentionally change those patterns in oder to break these scrapers, or even screw with them. Most of these tips also apply to other scrapers like spiders and screenscrapers too.

Frequently change your HTML

Scrapers which process HTML directly do so by extracting contents from specific, identifiable parts of your HTML page. For example: If all pages on your website have a div with an id of article-content, which contains the text of the article, then it is trivial to write a script to visit all the article pages on your site, and extract the content text of the article-content div on each article page, and voilà, the scraper has all the articles from your site in a format that can be reused elsewhere.

If you change the HTML and the structure of your pages frequently, such scrapers will no longer work.

  • You can frequently change the id's and classes of elements in your HTML, perhaps even automatically. So, if your div.article-content becomes something like div.a4c36dda13eaf0, and changes every week, the scraper will work fine initially, but will break after a week. Make sure to change the length of your ids / classes too, otherwise the scraper will use div.[any-14-characters] to find the desired div instead. Beware of other similar holes too..

  • If there is no way to find the desired content from the markup, the scraper will do so from the way the HTML is structured. So, if all your article pages are similar in that every div inside a div which comes after a h1 is the article content, scrapers will get the article content based on that. Again, to break this, you can add / remove extra markup to your HTML, periodically and randomly, eg. adding extra divs or spans. With modern server side HTML processing, this should not be too hard.

Things to be aware of:

  • It will be tedious and difficult to implement, maintain, and debug.

  • You will hinder caching. Especially if you change ids or classes of your HTML elements, this will require corresponding changes in your CSS and JavaScript files, which means that every time you change them, they will have to be re-downloaded by the browser. This will result in longer page load times for repeat visitors, and increased server load. If you only change it once a week, it will not be a big problem.

  • Clever scrapers will still be able to get your content by inferring where the actual content is, eg. by knowing that a large single block of text on the page is likely to be the actual article. This makes it possible to still find & extract the desired data from the page. Boilerpipe does exactly this.

Essentially, make sure that it is not easy for a script to find the actual, desired content for every similar page.

See also How to prevent crawlers depending on XPath from getting page contents for details on how this can be implemented in PHP.

Change your HTML based on the user's location

This is sort of similar to the previous tip. If you serve different HTML based on your user's location / country (determined by IP address), this may break scrapers which are delivered to users. For example, if someone is writing a mobile app which scrapes data from your site, it will work fine initially, but break when it's actually distributed to users, as those users may be in a different country, and thus get different HTML, which the embedded scraper was not designed to consume.

Frequently change your HTML, actively screw with the scrapers by doing so !

An example: You have a search feature on your website, located at example.com/search?query=somesearchquery, which returns the following HTML:

<div class="search-result">
  <h3 class="search-result-title">Stack Overflow has become the world's most popular programming Q & A website</h3>
  <p class="search-result-excerpt">The website Stack Overflow has now become the most popular programming Q & A website, with 10 million questions and many users, which...</p>
  <a class"search-result-link" href="/stories/story-link">Read more</a>
</div>
(And so on, lots more identically structured divs with search results)

As you may have guessed this is easy to scrape: all a scraper needs to do is hit the search URL with a query, and extract the desired data from the returned HTML. In addition to periodically changing the HTML as described above, you could also leave the old markup with the old ids and classes in, hide it with CSS, and fill it with fake data, thereby poisoning the scraper. Here's how the search results page could be changed:

<div class="the-real-search-result">
  <h3 class="the-real-search-result-title">Stack Overflow has become the world's most popular programming Q & A website</h3>
  <p class="the-real-search-result-excerpt">The website Stack Overflow has now become the most popular programming Q & A website, with 10 million questions and many users, which...</p>
  <a class"the-real-search-result-link" href="/stories/story-link">Read more</a>
</div>

<div class="search-result" style="display:none">
  <h3 class="search-result-title">Visit Example.com now, for all the latest Stack Overflow related news !</h3>
  <p class="search-result-excerpt">Example.com is so awesome, visit now !</p>
  <a class"search-result-link" href="http://example.com/">Visit Now !</a>
</div>
(More real search results follow)

This will mean that scrapers written to extract data from the HTML based on classes or IDs will continue to seemingly work, but they will get fake data or even ads, data which real users will never see, as they're hidden with CSS.

Screw with the scraper: Insert fake, invisible honeypot data into your page

Adding on to the previous example, you can add invisible honeypot items to your HTML to catch scrapers. An example which could be added to the previously described search results page:

<div class="search-result" style="display:none">
  <h3 class="search-result-title">This search result is here to prevent scraping</h3>
  <p class="search-result-excerpt">If you're a human and see this, please ignore it. If you're a scraper, please click the link below :-)
  Note that clicking the link below will block access to this site for 24 hours.</p>
  <a class"search-result-link" href="/scrapertrap/scrapertrap.php">I'm a scraper !</a>
</div>
(The actual, real, search results follow.)

A scraper written to get all the search results will pick this up, just like any of the other, real search results on the page, and visit the link, looking for the desired content. A real human will never even see it in the first place (due to it being hidden with CSS), and won't visit the link. A genuine and desirable spider such as Google's will not visit the link either because you disallowed /scrapertrap/ in your robots.txt.

You can make your scrapertrap.php do something like block access for the IP address that visited it or force a captcha for all subsequent requests from that IP.

  • Don't forget to disallow your honeypot (/scrapertrap/) in your robots.txt file so that search engine bots don't fall into it.

  • You can / should combine this with the previous tip of changing your HTML frequently.

  • Change this frequently too, as scrapers will eventually learn to avoid it. Change the honeypot URL and text. Also want to consider changing the inline CSS used for hiding, and use an ID attribute and external CSS instead, as scrapers will learn to avoid anything which has a style attribute with CSS used to hide the content. Also try only enabling it sometimes, so the scraper works initially, but breaks after a while. This also applies to the previous tip.

  • Malicious people can prevent access for real users by sharing a link to your honeypot, or even embedding that link somewhere as an image (eg. on a forum). Change the URL frequently, and make any ban times relatively short.

Serve fake and useless data if you detect a scraper

If you detect what is obviously a scraper, you can serve up fake and useless data; this will corrupt the data the scraper gets from your website. You should also make it impossible to distinguish such fake data from real data, so that scrapers don't know that they're being screwed with.

As an example: you have a news website; if you detect a scraper, instead of blocking access, serve up fake, randomly generated articles, and this will poison the data the scraper gets. If you make your fake data indistinguishable from the real thing, you'll make it hard for scrapers to get what they want, namely the actual, real data.

Don't accept requests if the User Agent is empty / missing

Often, lazily written scrapers will not send a User Agent header with their request, whereas all browsers as well as search engine spiders will.

If you get a request where the User Agent header is not present, you can show a captcha, or simply block or limit access. (Or serve fake data as described above, or something else..)

It's trivial to spoof, but as a measure against poorly written scrapers it is worth implementing.

Don't accept requests if the User Agent is a common scraper one; blacklist ones used by scrapers

In some cases, scrapers will use a User Agent which no real browser or search engine spider uses, such as:

  • "Mozilla" (Just that, nothing else. I've seen a few questions about scraping here, using that. A real browser will never use only that)
  • "Java 1.7.43_u43" (By default, Java's HttpUrlConnection uses something like this.)
  • "BIZCO EasyScraping Studio 2.0"
  • "wget", "curl", "libcurl",.. (Wget and cURL are sometimes used for basic scraping)

If you find that a specific User Agent string is used by scrapers on your site, and it is not used by real browsers or legitimate spiders, you can also add it to your blacklist.

If it doesn't request assets (CSS, images), it's not a real browser.

A real browser will (almost always) request and download assets such as images and CSS. HTML parsers and scrapers won't as they are only interested in the actual pages and their content.

You could log requests to your assets, and if you see lots of requests for only the HTML, it may be a scraper.

Beware that search engine bots, ancient mobile devices, screen readers and misconfigured devices may not request assets either.

Use and require cookies; use them to track user and scraper actions.

You can require cookies to be enabled in order to view your website. This will deter inexperienced and newbie scraper writers, however it is easy to for a scraper to send cookies. If you do use and require them, you can track user and scraper actions with them, and thus implement rate-limiting, blocking, or showing captchas on a per-user instead of a per-IP basis.

For example: when the user performs search, set a unique identifying cookie. When the results pages are viewed, verify that cookie. If the user opens all the search results (you can tell from the cookie), then it's probably a scraper.

Using cookies may be ineffective, as scrapers can send the cookies with their requests too, and discard them as needed. You will also prevent access for real users who have cookies disabled, if your site only works with cookies.

Note that if you use JavaScript to set and retrieve the cookie, you'll block scrapers which don't run JavaScript, since they can't retrieve and send the cookie with their request.

Use JavaScript + Ajax to load your content

You could use JavaScript + AJAX to load your content after the page itself loads. This will make the content inaccessible to HTML parsers which do not run JavaScript. This is often an effective deterrent to newbie and inexperienced programmers writing scrapers.

Be aware of:

  • Using JavaScript to load the actual content will degrade user experience and performance

  • Search engines may not run JavaScript either, thus preventing them from indexing your content. This may not be a problem for search results pages, but may be for other things, such as article pages.

Obfuscate your markup, network requests from scripts, and everything else.

If you use Ajax and JavaScript to load your data, obfuscate the data which is transferred. As an example, you could encode your data on the server (with something as simple as base64 or more complex), and then decode and display it on the client, after fetching via Ajax. This will mean that someone inspecting network traffic will not immediately see how your page works and loads data, and it will be tougher for someone to directly request request data from your endpoints, as they will have to reverse-engineer your descrambling algorithm.

  • If you do use Ajax for loading the data, you should make it hard to use the endpoints without loading the page first, eg by requiring some session key as a parameter, which you can embed in your JavaScript or your HTML.

  • You can also embed your obfuscated data directly in the initial HTML page and use JavaScript to deobfuscate and display it, which would avoid the extra network requests. Doing this will make it significantly harder to extract the data using a HTML-only parser which does not run JavaScript, as the one writing the scraper will have to reverse engineer your JavaScript (which you should obfuscate too).

  • You might want to change your obfuscation methods regularly, to break scrapers who have figured it out.

There are several disadvantages to doing something like this, though:

  • It will be tedious and difficult to implement, maintain, and debug.

  • It will be ineffective against scrapers and screenscrapers which actually run JavaScript and then extract the data. (Most simple HTML parsers don't run JavaScript though)

  • It will make your site nonfunctional for real users if they have JavaScript disabled.

  • Performance and page-load times will suffer.

Non-Technical:

  • Tell people not to scrape, and some will respect it

  • Find a lawyer

  • Make your data available, provide an API:

    You could make your data easily available and require attribution and a link back to your site. Perhaps charge $$$ for it.

Miscellaneous:

  • There are also commercial scraping protection services, such as the anti-scraping by Cloudflare or Distill Networks (Details on how it works here), which do these things, and more for you.

  • Find a balance between usability for real users and scraper-proofness: Everything you do will impact user experience negatively in one way or another, find compromises.

  • Don't forget your mobile site and apps. If you have a mobile app, that can be screenscraped too, and network traffic can be inspected to determine the REST endpoints it uses.

  • Scrapers can scrape other scrapers: If there's one website which has content scraped from yours, other scrapers can scrape from that scraper's website.

Further reading:

How to get URL of current page in PHP

 $uri = $_SERVER['REQUEST_URI'];

This will give you the requested directory and file name. If you use mod_rewrite, this is extremely useful because it tells you what page the user was looking at.

If you need the actual file name, you might want to try either $_SERVER['PHP_SELF'], the magic constant __FILE__, or $_SERVER['SCRIPT_FILENAME']. The latter 2 give you the complete path (from the root of the server), rather than just the root of your website. They are useful for includes and such.

$_SERVER['PHP_SELF'] gives you the file name relative to the root of the website.

 $relative_path = $_SERVER['PHP_SELF'];
 $complete_path = __FILE__;
 $complete_path = $_SERVER['SCRIPT_FILENAME'];

How to open html file?

you can make use of the following code:

from __future__ import division, unicode_literals 
import codecs
from bs4 import BeautifulSoup

f=codecs.open("test.html", 'r', 'utf-8')
document= BeautifulSoup(f.read()).get_text()
print document

If you want to delete all the blank lines in between and get all the words as a string (also avoid special characters, numbers) then also include:

import nltk
from nltk.tokenize import word_tokenize
docwords=word_tokenize(document)
for line in docwords:
    line = (line.rstrip())
    if line:
        if re.match("^[A-Za-z]*$",line):
            if (line not in stop and len(line)>1):
                st=st+" "+line
print st

*define st as a string initially, like st=""

How to overwrite styling in Twitter Bootstrap

Add your own class, ex: <div class="sidebar right"></div>, with the CSS as

.sidebar.right { 
    float:right
} 

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

Try this

 <allow  users="?" />

Now you are using <deny users="?" /> that means you are not allowing authenticated user to use your site.

authorization Element

What is the purpose of the "final" keyword in C++11 for functions?

A use-case for the 'final' keyword that I am fond of is as follows:

// This pure abstract interface creates a way
// for unit test suites to stub-out Foo objects
class FooInterface
{
public:
   virtual void DoSomething() = 0;
private:
   virtual void DoSomethingImpl() = 0;
};

// Implement Non-Virtual Interface Pattern in FooBase using final
// (Alternatively implement the Template Pattern in FooBase using final)
class FooBase : public FooInterface
{
public:
    virtual void DoSomething() final { DoFirst(); DoSomethingImpl(); DoLast(); }
private:
    virtual void DoSomethingImpl() { /* left for derived classes to customize */ }
    void DoFirst(); // no derived customization allowed here
    void DoLast(); // no derived customization allowed here either
};

// Feel secure knowing that unit test suites can stub you out at the FooInterface level
// if necessary
// Feel doubly secure knowing that your children cannot violate your Template Pattern
// When DoSomething is called from a FooBase * you know without a doubt that
// DoFirst will execute before DoSomethingImpl, and DoLast will execute after.
class FooDerived : public FooBase
{
private:
    virtual void DoSomethingImpl() {/* customize DoSomething at this location */}
};

Regular expression for decimal number

In general, i.e. unlimited decimal places:

^-?(([1-9]\d*)|0)(.0*[1-9](0*[1-9])*)?$

passing object by reference in C++

One thing that I have to add is that there is no reference in C.

Secondly, this is the language syntax convention. & - is an address operator but it also mean a reference - all depends on usa case

If there was some "reference" keyword instead of & you could write

int CDummy::isitme (reference CDummy param)

but this is C++ and we should accept it advantages and disadvantages...

CodeIgniter -> Get current URL relative to base url

If url helper is loaded, use

current_url();

will be better

Find PHP version on windows command line

For Beginners to anything php, it is usually stored in the C:/ path folder of your PC (My Computer).

==On Windows==
1.Click Start Menu button
2.Type cmd and press enter to select the first program/application that responds to your search result.
A black window terminal will appear, this is known as a Command Line Interpreter
3.In the Terminal Window (Application) Type cd c: and press enter
4.Now type php -v and press enter

and viola there you'll have the current php version that is installed in your machine

How to import the class within the same directory or sub directory?

Python3

use

from .user import User inside dir.py file

and

use from class.dir import Dir inside main.py
or from class.usr import User inside main.py

like so

Use jQuery to navigate away from page

window.location.href = "/somewhere/else";

SQL (MySQL) vs NoSQL (CouchDB)

One of the best options is to go for MongoDB(NOSql dB) that supports scalability.Stores large amounts of data nothing but bigdata in the form of documents unlike rows and tables in sql.This is fasters that follows sharding of the data.Uses replicasets to ensure data guarantee that maintains multiple servers having primary db server as the base. Language independent. Flexible to use

What is &amp used for

My Source: http://htmlhelp.com/tools/validator/problems.html#amp

Another common error occurs when including a URL which contains an ampersand ("&"):

This is invalid:

a href="foo.cgi?chapter=1&section=2&copy=3&lang=en"

Explanation:

This example generates an error for "unknown entity section" because the "&" is assumed to begin an entity reference. Browsers often recover safely from this kind of error, but real problems do occur in some cases. In this example, many browsers correctly convert &copy=3 to ©=3, which may cause the link to fail. Since ⟨ is the HTML entity for the left-pointing angle bracket, some browsers also convert &lang=en to <=en. And one old browser even finds the entity §, converting &section=2 to §ion=2.

So the goal here is to avoid problems when you are trying to validate your website. So you should be replacing your ampersands with &amp; when writing a URL in your markup.

Note that replacing & with &amp; is only done when writing the URL in HTML, where "&" is a special character (along with "<" and ">"). When writing the same URL in a plain text email message or in the location bar of your browser, you would use "&" and not "&amp;". With HTML, the browser translates "&amp;" to "&" so the Web server would only see "&" and not "&amp;" in the query string of the request.

Hope this helps : )

error: member access into incomplete type : forward declaration of

Move doSomething definition outside of its class declaration and after B and also make add accessible to A by public-ing it or friend-ing it.

class B;

class A
{
    void doSomething(B * b);
};

class B
{
public:
    void add() {}
};

void A::doSomething(B * b)
{
    b->add();
}

Laravel 4: how to "order by" using Eloquent ORM

If you are using post as a model (without dependency injection), you can also do:

$posts = Post::orderBy('id', 'DESC')->get();

Java Minimum and Maximum values in Array

Yes you need to use a System.out.println. But you are getting the minimum and maximum everytime they input a value and don't keep track of the number of elements if they break early.

Try:

for (int i = 0 ; i < array.length; i++ ) {
       int next = input.nextInt();
       // sentineil that will stop loop when 999 is entered
       if (next == 999)
           break;

       array[i] = next;
 }
 int length = i;
 // get biggest number
 int large = getMaxValue(array, length);
 // get smallest number
 int small = getMinValue(array, length);

 // actually print
 System.out.println( "Max: " + large + " Min: " + small );

Then you will have to pass length into the methods to determine min and max and to print. If you don't do this, the rest of the fields will be 0 and can mess up the proper min and max values.

How to query a MS-Access Table from MS-Excel (2010) using VBA

Sub Button1_Click()
Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=C:\Documents and Settings\XXXXXX\My Documents\my_access_table.accdb"
    strSql = "SELECT Count(*) FROM mytable;"
    cn.Open strConnection
    Set rs = cn.Execute(strSql)
    MsgBox rs.Fields(0) & " rows in MyTable"

    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing

End Sub

How to make Firefox headless programmatically in Selenium with Python?

from selenium.webdriver.firefox.options import Options

if __name__ == "__main__":
    options = Options()
    options.add_argument('-headless')
    driver = Firefox(executable_path='geckodriver', firefox_options=options) 
    wait = WebDriverWait(driver, timeout=10)
    driver.get('http://www.google.com')

Tested, works as expected and this is from Official - Headless Mode | Mozilla

Difference between Select Unique and Select Distinct

select unique is not valid syntax for what you are trying to do

you want to use either select distinct or select distinctrow

And actually, you don't even need distinct/distinctrow in what you are trying to do. You can eliminate duplicates by choosing the appropriate union statement parameters.

the below query by itself will only provide distinct values

select col from table1 
union 
select col from table2

if you did want duplicates you would have to do

select col from table1 
union all
select col from table2

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

DataTable's Select method only supports simple filtering expressions like {field} = {value}. It does not support complex expressions, let alone SQL/Linq statements.

You can, however, use Linq extension methods to extract a collection of DataRows then create a new DataTable.

dt = dt.AsEnumerable()
       .GroupBy(r => new {Col1 = r["Col1"], Col2 = r["Col2"]})
       .Select(g => g.OrderBy(r => r["PK"]).First())
       .CopyToDataTable();

How do you grep a file and get the next 5 lines

Here is a sed solution:

sed '/19:55/{
N
N
N
N
N
s/\n/ /g
}' file.txt

Interfaces — What's the point?

I'm surprised that not many posts contain the one most important reason for an interface: Design Patterns. It's the bigger picture into using contracts, and although it's a syntax decoration to machine code (to be honest, the compiler probably just ignores them), abstraction and interfaces are pivotal for OOP, human understanding, and complex system architectures.

Let's expand the pizza analogy to say a full fledge 3 course meal. We'll still have the core Prepare() interface for all our food categories, but we'd also have abstract declarations for course selections (starter, main, dessert), and differing properties for food types (savoury/sweet, vegetarian/non-vegetarian, gluten free etc).

Based on these specifications, we could implement the Abstract Factory pattern to conceptualise the whole process, but use interfaces to ensure that only the foundations were concrete. Everything else could become flexible or encourage polymorphism, yet maintain encapsulation between the different classes of Course that implement the ICourse interface.

If I had more time, I'd like to draw up a full example of this, or someone can extend this for me, but in summary, a C# interface would be the best tool in designing this type of system.

How can I run PowerShell with the .NET 4 runtime?

The other answers are from before 2012, and they focus on "hacking" PowerShell 1.0 or PowerShell 2.0 into targeting newer versions of the .NET Framework and Common Language Runtime (CLR).

However, as has been written in many comments, since 2012 (when PowerShell 3.0 came) a much better solution is to install the newest version of PowerShell. It will automatically target CLR v4.0.30319. This means .NET 4.0, 4.5, 4.5.1, 4.5.2, or 4.6 (expected in 2015) since all of these versions are in-place replacements of each other. Use $PSVersionTable or see the Determine installed PowerShell version thread if you are unsure of your PowerShell version.

At the time of writing, the newest version of PowerShell is 4.0, and it can be downloaded with the Windows Management Framework (Google search link).

Swift - Split string over multiple lines

Adding to @Connor answer, there needs to be \n also. Here is revised code:

var text:String = "This is some text \n" +
                  "over multiple lines"

Pass a simple string from controller to a view MVC3

@Steve Hobbs' answer is probably the best, but some of your other solutions could have worked. For example, @Html.Label(ViewBag.CurrentPath); will probably work with an explicit cast, like @Html.Label((string)ViewBag.CurrentPath);. Also, your reference to currentPath in @Html.Label(ViewData["CurrentPath"].ToString()); is capitalized, wherein your other code it is not, which is probably why you were getting null reference exceptions.

What is the SQL command to return the field names of a table?

You can use the provided system views to do this:

eg

select * from INFORMATION_SCHEMA.COLUMNS
where table_name = '[table name]'

alternatively, you can use the system proc sp_help

eg

sp_help '[table name]'

center MessageBox in parent form

Surely using your own panel or form would be by far the simplest approach if a little more heavy on the background (designer) code. It gives all the control in terms of centring and manipulation without writing all that custom code.

Python list subtraction operation

The other solutions have one of a few problems:

  1. They don't preserve order, or
  2. They don't remove a precise count of elements, e.g. for x = [1, 2, 2, 2] and y = [2, 2] they convert y to a set, and either remove all matching elements (leaving [1] only) or remove one of each unique element (leaving [1, 2, 2]), when the proper behavior would be to remove 2 twice, leaving [1, 2], or
  3. They do O(m * n) work, where an optimal solution can do O(m + n) work

Alain was on the right track with Counter to solve #2 and #3, but that solution will lose ordering. The solution that preserves order (removing the first n copies of each value for n repetitions in the list of values to remove) is:

from collections import Counter

x = [1,2,3,4,3,2,1]  
y = [1,2,2]  
remaining = Counter(y)

out = []
for val in x:
    if remaining[val]:
        remaining[val] -= 1
    else:
        out.append(val)
# out is now [3, 4, 3, 1], having removed the first 1 and both 2s.

Try it online!

To make it remove the last copies of each element, just change the for loop to for val in reversed(x): and add out.reverse() immediately after exiting the for loop.

Constructing the Counter is O(n) in terms of y's length, iterating x is O(n) in terms of x's length, and Counter membership testing and mutation are O(1), while list.append is amortized O(1) (a given append can be O(n), but for many appends, the overall big-O averages O(1) since fewer and fewer of them require a reallocation), so the overall work done is O(m + n).

You can also test for to determine if there were any elements in y that were not removed from x by testing:

remaining = +remaining  # Removes all keys with zero counts from Counter
if remaining:
    # remaining contained elements with non-zero counts

Specifying maxlength for multiline textbox

$("textarea[maxlength]").on("keydown paste", function (evt) {
            if ($(this).val().length > $(this).prop("maxlength")) {
                if (evt.type == "paste") {
                    $(this).val($(this).val().substr(0, $(this).prop("maxlength")));
                } else {
                    if ([8, 37, 38, 39, 40, 46].indexOf(evt.keyCode) == -1) {
                        evt.returnValue = false;
                        evt.preventDefault();
                    }
                }
            }
        });

Oracle Date TO_CHAR('Month DD, YYYY') has extra spaces in it

SQL> -- original . . .
SQL> select
  2  to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ) dt
  3  from dual;

DT
----------------------------------------
Friday    the 13th of May      , 2016

SQL>
SQL> -- collapse repeated spaces . . .
SQL> select
  2  regexp_replace(
  3      to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
  4      '  * *', ' ') datesp
  5  from dual;

DATESP
----------------------------------------
Friday the 13th of May , 2016

SQL>
SQL> -- and space before commma . . .
SQL> select
  2  regexp_replace(
  3      to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
  4      '  *(,*) *', '\1 ') datesp
  5  from dual;

DATESP
----------------------------------------
Friday the 13th of May, 2016

SQL>
SQL> -- space before punctuation . . .
SQL> select
  2  regexp_replace(
  3      to_char( sysdate, 'Day "the" Ddth "of" Month, yyyy' ),
  4      '  *([.,/:;]*) *', '\1 ') datesp
  5  from dual;

DATESP
----------------------------------------
Friday the 13th of May, 2016

How to access child's state in React?

Just before I go into detail about how you can access the state of a child component, please make sure to read Markus-ipse's answer regarding a better solution to handle this particular scenario.

If you do indeed wish to access the state of a component's children, you can assign a property called ref to each child. There are now two ways to implement references: Using React.createRef() and callback refs.

Using React.createRef()

This is currently the recommended way to use references as of React 16.3 (See the docs for more info). If you're using an earlier version then see below regarding callback references.

You'll need to create a new reference in the constructor of your parent component and then assign it to a child via the ref attribute.

class FormEditor extends React.Component {
  constructor(props) {
    super(props);
    this.FieldEditor1 = React.createRef();
  }
  render() {
    return <FieldEditor ref={this.FieldEditor1} />;
  }
}

In order to access this kind of ref, you'll need to use:

const currentFieldEditor1 = this.FieldEditor1.current;

This will return an instance of the mounted component so you can then use currentFieldEditor1.state to access the state.

Just a quick note to say that if you use these references on a DOM node instead of a component (e.g. <div ref={this.divRef} />) then this.divRef.current will return the underlying DOM element instead of a component instance.

Callback Refs

This property takes a callback function that is passed a reference to the attached component. This callback is executed immediately after the component is mounted or unmounted.

For example:

<FieldEditor
    ref={(fieldEditor1) => {this.fieldEditor1 = fieldEditor1;}
    {...props}
/>

In these examples the reference is stored on the parent component. To call this component in your code, you can use:

this.fieldEditor1

and then use this.fieldEditor1.state to get the state.

One thing to note, make sure your child component has rendered before you try to access it ^_^

As above, if you use these references on a DOM node instead of a component (e.g. <div ref={(divRef) => {this.myDiv = divRef;}} />) then this.divRef will return the underlying DOM element instead of a component instance.

Further Information

If you want to read more about React's ref property, check out this page from Facebook.

Make sure you read the "Don't Overuse Refs" section that says that you shouldn't use the child's state to "make things happen".

Hope this helps ^_^

Edit: Added React.createRef() method for creating refs. Removed ES5 code.

Aren't promises just callbacks?

No, Not at all.

Callbacks are simply Functions In JavaScript which are to be called and then executed after the execution of another function has finished. So how it happens?

Actually, In JavaScript, functions are itself considered as objects and hence as all other objects, even functions can be sent as arguments to other functions. The most common and generic use case one can think of is setTimeout() function in JavaScript.

Promises are nothing but a much more improvised approach of handling and structuring asynchronous code in comparison to doing the same with callbacks.

The Promise receives two Callbacks in constructor function: resolve and reject. These callbacks inside promises provide us with fine-grained control over error handling and success cases. The resolve callback is used when the execution of promise performed successfully and the reject callback is used to handle the error cases.

A tool to convert MATLAB code to Python

There's also oct2py which can call .m files within python

https://pypi.python.org/pypi/oct2py

It requires GNU Octave, which is highly compatible with MATLAB.

https://www.gnu.org/software/octave/

ISO time (ISO 8601) in Python

The ISO 8601 time format does not store a time zone name, only the corresponding UTC offset is preserved.

To convert a file ctime to an ISO 8601 time string while preserving the UTC offset in Python 3:

>>> import os
>>> from datetime import datetime, timezone
>>> ts = os.path.getctime(some_file)
>>> dt = datetime.fromtimestamp(ts, timezone.utc)
>>> dt.astimezone().isoformat()
'2015-11-27T00:29:06.839600-05:00'

The code assumes that your local timezone is Eastern Time Zone (ET) and that your system provides a correct UTC offset for the given POSIX timestamp (ts), i.e., Python has access to a historical timezone database on your system or the time zone had the same rules at a given date.

If you need a portable solution; use the pytz module that provides access to the tz database:

>>> import os
>>> from datetime import datetime
>>> import pytz  # pip install pytz
>>> ts = os.path.getctime(some_file)
>>> dt = datetime.fromtimestamp(ts, pytz.timezone('America/New_York'))
>>> dt.isoformat()
'2015-11-27T00:29:06.839600-05:00'

The result is the same in this case.

If you need the time zone name/abbreviation/zone id, store it separately.

>>> dt.astimezone().strftime('%Y-%m-%d %H:%M:%S%z (%Z)')
'2015-11-27 00:29:06-0500 (EST)'

Note: no, : in the UTC offset and EST timezone abbreviation is not part of the ISO 8601 time format. It is not unique.

Different libraries/different versions of the same library may use different time zone rules for the same date/timezone. If it is a future date then the rules might be unknown yet. In other words, the same UTC time may correspond to a different local time depending on what rules you use -- saving a time in ISO 8601 format preserves UTC time and the local time that corresponds to the current time zone rules in use on your platform. You might need to recalculate the local time on a different platform if it has different rules.

Why does LayoutInflater ignore the layout_width and layout_height layout parameters I've specified?

andig is correct that a common reason for LayoutInflater ignoring your layout_params would be because a root was not specified. Many people think you can pass in null for root. This is acceptable for a few scenarios such as a dialog, where you don't have access to root at the time of creation. A good rule to follow, however, is that if you have root, give it to LayoutInflater.

I wrote an in-depth blog post about this that you can check out here:

https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/

Elasticsearch: Failed to connect to localhost port 9200 - Connection refused

If you encounter the Connection refused error, simply run the command below to check the status of ElasticSearch service

sudo service elasticsearch status

This will help you decipher the state of ElasticSearch service and what to do about it.

What does "#pragma comment" mean?

#pragma comment is a compiler directive which indicates Visual C++ to leave a comment in the generated object file. The comment can then be read by the linker when it processes object files.

#pragma comment(lib, libname) tells the linker to add the 'libname' library to the list of library dependencies, as if you had added it in the project properties at Linker->Input->Additional dependencies

See #pragma comment on MSDN

Batch file to copy files from one folder to another folder

You may want to take a look at XCopy or RoboCopy which are pretty comprehensive solutions for nearly all file copy operations on Windows.

Running ASP.Net on a Linux based server

Now a days .Net is run in multiple platforms,like linux ,Mac os etc. but mono is not fully platform independent ,Because to deploy .NET in another OS required third party software.so it is not like java platform independent.

Mono is running in different platform ,because of JIT is there in different os.

Mono is not fully success in moonlight(silver light in .NET) .Not only Research is going on.

Mono uses XSP2 server or apache . some of the big companies are using this project,Some of the robotic project are also running on mono.

For more details http://www.mono-project.com/Main_Page.

Angular2 router (@angular/router), how to set default route?

I faced same issue apply all possible solution but finally this solve my problem

export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['404']); // or redirect to default route
    }
  }
}

Hope this will help you.

Invalid column count in CSV input on line 1 Error

You will need to skip first row (where column names are defined) and you will need to check which "character" is separating cells (usually is ,, but in my case was ;)

Bellow is the picture of my import:

enter image description here

jquery get all form elements: input, textarea & select

all inputs:

var inputs = $("#formId :input");

all buttons

var button = $("#formId :button")

Iterate through a HashMap

Iterate through the entrySet() like so:

public static void printMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
        it.remove(); // avoids a ConcurrentModificationException
    }
}

Read more about Map.

How to search text using php if ($text contains "World")

What you need is strstr()(or stristr(), like LucaB pointed out). Use it like this:

if(strstr($text, "world")) {/* do stuff */}

What do pty and tty mean?

A tty is a physical terminal-teletype port on a computer (usually a serial port).

The word teletype is a shorting of the telegraph typewriter, or teletypewriter device from the 1930s - itself an electromagnetic device which replaced the telegraph encoding machines of the 1830s and 1840s.

Teletypewriter
TTY - Teletypewriter 1930s

A pty is a pseudo-teletype port provided by a computer Operating System Kernel to connect software programs emulating terminals, such as ssh, xterm, or screen.

enter image description here
PTY - PseudoTeletype

A terminal is simply a computer's user interface that uses text for input and output.


OS Implementations

These use pseudo-teletype ports however, their naming and implementations have diverged a little.

Linux mounts a special file system devpts on /dev (the 's' presumably standing for serial) that creates a corresponding entry in /dev/pts for every new terminal window you open, e.g. /dev/pts/0


macOS/FreeBSD also use the /dev file structure however, they use a numbered TTY naming convention ttys for every new terminal window you open e.g. /dev/ttys002


Microsoft Windows still has the concept of an LPT port for Line Printer Terminals within it's Command Shell for output to a printer.

How to add a jar in External Libraries in android studio

If you dont see option "Add as Library", make sure you extract (unzip) your file so that you have mail.jar and not mail.zip.

Then right click your file, and you can see the option "Add as library".

How to get commit history for just one branch?

You can use only git log --oneline

Regular expression to limit number of characters to 10

It very much depend on the program you're using. Different programs (Emacs, vi, sed, and Perl) use slightly different regular expressions. In this case, I'd say that in the first pattern, the last "+" should be removed.

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

Solved this in Angular 2 Final version simply by using the dynamicComponent directive from ng-dynamic.

Usage:

<div *dynamicComponent="template; context: {text: text};"></div>

Where template is your dynamic template and context can be set to any dynamic datamodel that you want your template to bind to.

Change Schema Name Of Table In SQL

CREATE SCHEMA exe AUTHORIZATION [dbo]
GO

ALTER SCHEMA exe
TRANSFER dbo.Employees
GO

How do I remove blue "selected" outline on buttons?

That is a default behaviour of each browser; your browser seems to be Safari, in Google Chrome it is orange in color!

Use this to remove this effect:

button {
  outline: none; // this one
}

I have Python on my Ubuntu system, but gcc can't find Python.h

On ubuntu you can just type sudo apt-get install python-dev -y in terminal to install the python-dev package.

Cannot set property 'innerHTML' of null

Is this running in the <head> of the html? If so, you need to make sure the <body> tag has actually loaded first.

You need to use an onload handler, for example: http://javascript.about.com/library/blonload.htm

Format cell color based on value in another sheet and cell

Here's how I did it in Excel 2003 using conditional formatting.

To apply conditional formatting to Sheet1 using values from Sheet2, you need to mirror the values into Sheet1.

Creating a mirror of Sheet2, column B in Sheet 1

  1. Go to Sheet1.
  2. Insert a new column by right-clicking column A's header and selecting "Insert".
  3. Enter the following formula into A1:

    =IF(ISBLANK(Sheet2!B1),"",Sheet2!B1)

  4. Copy A1 by right-clicking it and selecting "Copy".
  5. Paste the formula into column A by right-clicking its header and selecting "Paste".

Sheet1, column A should now exactly mirror the values in Sheet2, column B.

(Note: if you don't like it in column A, it works just as well to have it in column Z or anywhere else.)

Applying the conditional formatting

  1. Stay on Sheet1.
  2. Select column B by left-clicking its header.
  3. Select the menu item Format > Conditional Formatting...
  4. Change Condition 1 to "Formula is" and enter this formula:

    =MATCH(B1,$A:$A,0)

  5. Click the Format... button and select a green background.

You should now see the green background applied to the matching cells in Sheet1.

Hiding the mirror column

  1. Stay on Sheet1.
  2. Right-click the header on column A and select "Hide".

This should automatically update Sheet1 whenever anything in Sheet2 is changed.

How to search in array of object in mongodb

The right way is:

db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})

$elemMatch allows you to match more than one component within the same array element.

Without $elemMatch mongo will look for users with National Medal in some year and some award in 1975s, but not for users with National Medal in 1975.

See MongoDB $elemMatch Documentation for more info. See Read Operations Documentation for more information about querying documents with arrays.

Could not load the Tomcat server configuration

I've just solved this exact problem on my Ubuntu 14.04 with Eclipse Mars 2.

This could happen when Eclipse is not finding Tomcat's configuration files where they are expected to be. This place is in

$eclipse_workspace_folder/$version_of_your_tomcat_server_at_localhost/

(by default if you didn't changed server's name). So you have to copy all the files under your $tomcat_installation_folder/conf/* to the workspace server's folder.

But it was easier to just remove the server from your server list and add it again. Eclipse will automatically recreate all these files again into the proper folders. Like in the picture below:

enter image description here

In my case I've downloaded tomcat-8.0.35 from the website, so the configuration files needed are in /opt/apache-tomcat-8.0.35/conf/ filesystem.

Just delete the desired server from the Servers view (Window -> Show View -> Servers) and then go to Window -> Preferences -> Server -> Runtime Environment -> Add and add the server again.

Select SQL results grouped by weeks

Base on @increddibelly answer, I applied to my query as below.

I share for whom concerned.

My table structure FamilyData(Id, nodeTime, totalEnergy)

select
   sum(totalEnergy) as TotalEnergy,
   DATEPART ( week, nodeTime ) as weeknr
from FamilyData
group by DATEPART (week, nodeTime)

How to get height of Keyboard?

// Step 1 :- Register NotificationCenter

ViewDidLoad() {

   self.yourtextfield.becomefirstresponder()

   // Register your Notification, To know When Key Board Appears.
    NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillShow(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

   // Register your Notification, To know When Key Board Hides.
    NotificationCenter.default.addObserver(self, selector: #selector(SelectVendorViewController.keyboardWillHide(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

// Step 2 :- These Methods will be called Automatically when Keyboard appears Or Hides

    func keyboardWillShow(notification:NSNotification) {
        let userInfo:NSDictionary = notification.userInfo! as NSDictionary
        let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
        let keyboardRectangle = keyboardFrame.cgRectValue
        let keyboardHeight = keyboardRectangle.height
        tblViewListData.frame.size.height = fltTblHeight-keyboardHeight
    }

    func keyboardWillHide(notification:NSNotification) {
        tblViewListData.frame.size.height = fltTblHeight
    }

How to match "anything up until this sequence of characters" in a regular expression?

On python:

.+?(?=abc) works for the single line case.

[^]+?(?=abc) does not work, since python doesn't recognize [^] as valid regex. To make multiline matching work, you'll need to use the re.DOTALL option, for example:

re.findall('.+?(?=abc)', data, re.DOTALL)

Binding to static property

These answers are all good if you want to follow good conventions but the OP wanted something simple, which is what I wanted too instead of dealing with GUI design patterns. If all you want to do is have a string in a basic GUI app you can update ad-hoc without anything fancy, you can just access it directly in your C# source.

Let's say you've got a really basic WPF app MainWindow XAML like this,

<Window x:Class="MyWPFApp.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:MyWPFApp"
            mc:Ignorable="d"
            Title="MainWindow"
            Height="200"
            Width="400"
            Background="White" >
    <Grid>
        <TextBlock x:Name="textBlock"                   
                       Text=".."
                       HorizontalAlignment="Center"
                       VerticalAlignment="Top"
                       FontWeight="Bold"
                       FontFamily="Helvetica"
                       FontSize="16"
                       Foreground="Blue" Margin="0,10,0,0"
             />
        <Button x:Name="Find_Kilroy"
                    Content="Poke Kilroy"
                    Click="Button_Click_Poke_Kilroy"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Center"
                    FontFamily="Helvetica"
                    FontWeight="Bold"
                    FontSize="14"
                    Width="280"
            />
    </Grid>
</Window>

That will look something like this:

enter image description here

In your MainWindow XAML's source, you could have something like this where all we're doing in changing the value directly via textBlock.Text's get/set functionality:

using System.Windows;

namespace MyWPFApp
{
    public partial class MainWindow : Window
    {
        public MainWindow() { InitializeComponent(); }

        private void Button_Click_Poke_Kilroy(object sender, RoutedEventArgs e)
        {
            textBlock.Text = "              \\|||/\r\n" +
                             "              (o o) \r\n" +
                             "----ooO- (_) -Ooo----";
        }
    }
}

Then when you trigger that click event by clicking the button, voila! Kilroy appears :)

enter image description here

Failed to locate the winutils binary in the hadoop binary path

Set up HADOOP_HOME variable in windows to resolve the problem.

You can find answer in org/apache/hadoop/hadoop-common/2.2.0/hadoop-common-2.2.0-sources.jar!/org/apache/hadoop/util/Shell.java :

IOException from

  public static final String getQualifiedBinPath(String executable) 
  throws IOException {
    // construct hadoop bin path to the specified executable
    String fullExeName = HADOOP_HOME_DIR + File.separator + "bin" 
      + File.separator + executable;
    File exeFile = new File(fullExeName);
    if (!exeFile.exists()) {
      throw new IOException("Could not locate executable " + fullExeName
        + " in the Hadoop binaries.");
    }
    return exeFile.getCanonicalPath();
  }

HADOOP_HOME_DIR from

// first check the Dflag hadoop.home.dir with JVM scope
String home = System.getProperty("hadoop.home.dir");
// fall back to the system/user-global env variable
if (home == null) {
  home = System.getenv("HADOOP_HOME");
}

How to reset AUTO_INCREMENT in MySQL?

Best way is remove the field with AI and add it again with AI, works for all tables

How to display table data more clearly in oracle sqlplus

I usually start with something like:

set lines 256
set trimout on
set tab off

Have a look at help set if you have the help information installed. And then select name,address rather than select * if you really only want those two columns.

How do I instantiate a Queue object in java?

Queue is an interface in java, you can not do that.

Instead you have two options:

option1:

Queue<Integer> Q = new LinkedList<>();

option2:

Queue<Integer> Q = new ArrayDeque<>();

I recommend using option2 as it is bit faster than the other

sql insert into table with select case values

You have the alias inside of the case, it needs to be outside of the END:

Insert into TblStuff (FullName,Address,City,Zip)
Select
  Case
    When Middle is Null 
    Then Fname + LName
    Else Fname +' ' + Middle + ' '+ Lname
  End as FullName,
  Case
    When Address2 is Null Then Address1
    else Address1 +', ' + Address2 
  End as  Address,
  City as City,
  Zip as Zip
from tblImport

How to import component into another root component in Angular 2

You should declare it with declarations array(meta property) of @NgModule as shown below (RC5 and later),

import {CoursesComponent} from './courses.component';

@NgModule({
  imports:      [ BrowserModule],
  declarations: [ AppComponent,CoursesComponent],  //<----here
  providers:    [],      
  bootstrap:    [ AppComponent ]
})

Why does C++ compilation take so long?

The biggest issues are:

1) The infinite header reparsing. Already mentioned. Mitigations (like #pragma once) usually only work per compilation unit, not per build.

2) The fact that the toolchain is often separated into multiple binaries (make, preprocessor, compiler, assembler, archiver, impdef, linker, and dlltool in extreme cases) that all have to reinitialize and reload all state all the time for each invocation (compiler, assembler) or every couple of files (archiver, linker, and dlltool).

See also this discussion on comp.compilers: http://compilers.iecc.com/comparch/article/03-11-078 specially this one:

http://compilers.iecc.com/comparch/article/02-07-128

Note that John, the moderator of comp.compilers seems to agree, and that this means it should be possible to achieve similar speeds for C too, if one integrates the toolchain fully and implements precompiled headers. Many commercial C compilers do this to some degree.

Note that the Unix model of factoring everything out to a separate binary is a kind of the worst case model for Windows (with its slow process creation). It is very noticable when comparing GCC build times between Windows and *nix, especially if the make/configure system also calls some programs just to obtain information.

Go test string contains substring

To compare, there are more options:

import (
    "fmt"
    "regexp"
    "strings"
)

const (
    str    = "something"
    substr = "some"
)

// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true

// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0

// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2

// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1

// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true

// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true

Benchmarks: Contains internally calls Index, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).

BenchmarkStringsContains-4              100000000               10.5 ns/op             0 B/op          0 allocs/op
BenchmarkStringsIndex-4                 117090943               10.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsSplit-4                  6958126               152 ns/op              32 B/op          1 allocs/op
BenchmarkStringsCount-4                 42397729                29.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsRegExp-4                  461696              2467 ns/op            1326 B/op         16 allocs/op
BenchmarkStringsRegExpCompiled-4         7109509               168 ns/op               0 B/op          0 allocs/op

Internet Explorer 11 detection

And how I implemented this

<script type="text/javascript">
  !(window.ActiveXObject) && "ActiveXObject"
  function isIE11(){
    return !!navigator.userAgent.match(/Trident.*rv[ :]*11\./);
  }
</script>

static constructors in C++? I need to initialize private static objects

Test::StaticTest() is called exactly once during global static initialization.

Caller only has to add one line to the function that is to be their static constructor.

static_constructor<&Test::StaticTest>::c; forces initialization of c during global static initialization.

template<void(*ctor)()>
struct static_constructor
{
    struct constructor { constructor() { ctor(); } };
    static constructor c;
};

template<void(*ctor)()>
typename static_constructor<ctor>::constructor static_constructor<ctor>::c;

/////////////////////////////

struct Test
{
    static int number;

    static void StaticTest()
    {
        static_constructor<&Test::StaticTest>::c;

        number = 123;
        cout << "static ctor" << endl;
    }
};

int Test::number;

int main(int argc, char *argv[])
{
    cout << Test::number << endl;
    return 0;
}

adding text to an existing text element in javascript via DOM

_x000D_
_x000D_
var t = document.getElementById("p").textContent;
var y = document.createTextNode("This just got added");

t.appendChild(y);
_x000D_
<p id="p">This is some text</p>
_x000D_
_x000D_
_x000D_

git: can't push (unpacker error) related to permission issues

For what it worth, I had the same problem over my own VPS and it was caused by my low hard disk space on VPS. Confirmed by df -h command and after i cleaned up my VPS' hard disk; the problem was gone.

Cheers.

How to export data to an excel file using PHPExcel

Work 100%. maybe not relation to creator answer but i share it for users have a problem with export mysql query to excel with phpexcel. Good Luck.

require('../phpexcel/PHPExcel.php');

require('../phpexcel/PHPExcel/Writer/Excel5.php');

$filename = 'userReport'; //your file name

    $objPHPExcel = new PHPExcel();
    /*********************Add column headings START**********************/
    $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', 'username')
                ->setCellValue('B1', 'city_name');

    /*********************Add data entries START**********************/
//get_result_array_from_class**You can replace your sql code with this line.
$result = $get_report_clas->get_user_report();
//set variable for count table fields.
$num_row = 1;
foreach ($result as $value) {
  $user_name = $value['username'];
  $c_code = $value['city_name'];
  $num_row++;
        $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A'.$num_row, $user_name )
                ->setCellValue('B'.$num_row, $c_code );
}

    /*********************Autoresize column width depending upon contents START**********************/
    foreach(range('A','B') as $columnID) {
        $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setAutoSize(true);
    }
    $objPHPExcel->getActiveSheet()->getStyle('A1:B1')->getFont()->setBold(true);



//Make heading font bold

        /*********************Add color to heading START**********************/
        $objPHPExcel->getActiveSheet()
                    ->getStyle('A1:B1')
                    ->getFill()
                    ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
                    ->getStartColor()
                    ->setARGB('99ff99');

        $objPHPExcel->getActiveSheet()->setTitle('userReport'); //give title to sheet
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;Filename=$filename.xls");
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');

MVC 4 @Scripts "does not exist"

Create a new MVC 4 RC internet application and run it. Navigate to Login which uses the same code

 @section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

What allows Login.cshtml to work is the the Views\Web.config file (not the app root version) contains

<namespaces>

    <add namespace="System.Web.Optimization"/>

  </namespaces>

Why is your Create view not working and Login is?

How to access your website through LAN in ASP.NET

I'm not sure how stuck you are:

You must have a web server (Windows comes with one called IIS, but it may not be installed)

  1. Make sure you actually have IIS installed! Try typing http://localhost/ in your browser and see what happens. If nothing happens it means that you may not have IIS installed. See Installing IIS
  2. Set up IIS How to set up your first IIS Web site
  3. You may even need to Install the .NET Framework (or your server will only serve static html pages, and not asp.net pages)

Installing your application

Once you have done that, you can more or less just copy your application to c:\wwwroot\inetpub\. Read Installing ASP.NET Applications (IIS 6.0) for more information

Accessing the web site from another machine

In theory, once you have a web server running, and the application installed, you only need the IP address of your web server to access the application.

To find your IP address try: Start -> Run -> type cmd (hit ENTER) -> type ipconfig (hit ENTER)

Once

  • you have the IP address AND
  • IIS running AND
  • the application is installed

you can access your website from another machine in your LAN by just typing in the IP Address of you web server and the correct path to your application.

If you put your application in a directory called NewApp, you will need to type something like http://your_ip_address/NewApp/default.aspx

Turn off your firewall

If you do have a firewall turn it off while you try connecting for the first time, you can sort that out later.

How do you add a Dictionary of items into another Dictionary

It's not built into the Swift library but you can add what you want with operator overloading, e.g:

func + <K,V>(left: Dictionary<K,V>, right: Dictionary<K,V>) 
    -> Dictionary<K,V> 
{
    var map = Dictionary<K,V>()
    for (k, v) in left {
        map[k] = v
    }
    for (k, v) in right {
        map[k] = v
    }
    return map
}

This overloads the + operator for Dictionaries which you can now use to add dictionaries with the + operator, e.g:

var dict1 = ["a" : "foo"]
var dict2 = ["b" : "bar"]

var dict3 = dict1 + dict2 // ["a": "foo", "b": "bar"]

New lines inside paragraph in README.md

You can use a backslash at the end of a line.
So this:

a\
b\
c

will then look like:

a
b
c

Notice that there is no backslash at the end of the last line (after the 'c' character).

Writing data into CSV file in C#

I would highly recommend you to go the more tedious route. Especially if your file size is large.

using(var w = new StreamWriter(path))
{
    for( /* your loop */)
    {
        var first = yourFnToGetFirst();
        var second = yourFnToGetSecond();
        var line = string.Format("{0},{1}", first, second);
        w.WriteLine(line);
        w.Flush();
    }
}

File.AppendAllText() opens a new file, writes the content and then closes the file. Opening files is a much resource-heavy operation, than writing data into open stream. Opening\closing a file inside a loop will cause performance drop.

The approach suggested by Johan solves that problem by storing all the output in memory and then writing it once. However (in case of big files) you program will consume a large amount of RAM and even crash with OutOfMemoryException

Another advantage of my solution is that you can implement pausing\resuming by saving current position in input data.

upd. Placed using in the right place

Stop Visual Studio from launching a new browser window when starting debug?

Joao Costa answer also holds true for .Net core 2 projects.

launchsettings.json --> "launchBrowser": false

"profiles": {
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": false,
      "environmentVariables": {
        "Hosting:Environment": "Development"
      }
    }
}

HTML <select> selected option background-color CSS style

I realise this is an old post, but in case it helps, you can apply this CSS to have IE11 draw a dotted outline for the focus indication of a <select> element so that it resembles Firefox's focus indication: select:focus::-ms-value { background: transparent; color: inherit; outline-style: dotted; outline-width: thin; }

Work on a remote project with Eclipse via SSH

I had the same problem 2 years ago and I solved it in the following way:

1) I build my projects with makefiles, not managed by eclipse 2) I use a SAMBA connection to edit the files inside Eclipse 3) Building the project: Eclipse calles a "local" make with a makefile which opens a SSH connection to the Linux Host. On the SSH command line you can give parameters which are executed on the Linux host. I use for that parameter a makeit.sh shell script which call the "real" make on the linux host. The different targets for building you can give also by parameters from the local makefile --> makeit.sh --> makefile on linux host.

How To Set Text In An EditText

String text = "Example";
EditText edtText = (EditText) findViewById(R.id.edtText);
edtText.setText(text);

Check it out EditText accept only String values if necessary convert it to string.

If int, double, long value, do:

String.value(value);

Update elements in a JSONObject

Remove key and then add again the modified key, value pair as shown below :

    JSONObject js = new JSONObject();
    js.put("name", "rai");

    js.remove("name");
    js.put("name", "abc");

I haven't used your example; but conceptually its same.

Post values from a multiple select

try this : here select is your select element

let select = document.getElementsByClassName('lstSelected')[0],
    options = select.options,
    len = options.length,
    data='',
    i=0;
while (i<len){
    if (options[i].selected)
        data+= "&" + select.name + '=' + options[i].value;
    i++;
}
return data;

Data is in the form of query string i.e.name=value&name=anotherValue

ValueError: unconverted data remains: 02:05

  timeobj = datetime.datetime.strptime(my_time, '%Y-%m-%d %I:%M:%S')
  File "/usr/lib/python2.7/_strptime.py", line 335, in _strptime
    data_string[found.end():])
ValueError: unconverted data remains:

In my case, the problem was an extra space in the input date string. So I used strip() and it started to work.