Programs & Examples On #Transitivity

Read from database and fill DataTable

Connection object is for illustration only. The DataAdapter is the key bit:

Dim strSql As String = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
  cnn.Open()
  Using dad As New SqlDataAdapter(strSql, cnn)
    dad.Fill(dtb)
  End Using
  cnn.Close()
End Using

Assert that a WebElement is not present using Selenium WebDriver with java

Try this -

private boolean verifyElementAbsent(String locator) throws Exception {
    try {
        driver.findElement(By.xpath(locator));
        System.out.println("Element Present");
        return false;

    } catch (NoSuchElementException e) {
        System.out.println("Element absent");
        return true;
    }
}

C# 30 Days From Todays Date

One I can answer confidently!

DateTime expiryDate = DateTime.Now.AddDays(30);

Or possibly - if you just want the date without a time attached which might be more appropriate:

DateTime expiryDate = DateTime.Today.AddDays(30);

invalid use of non-static member function

The simplest fix is to make the comparator function be static:

static int comparator (const Bar & first, const Bar & second);
^^^^^^

When invoking it in Count, its name will be Foo::comparator.

The way you have it now, it does not make sense to be a non-static member function because it does not use any member variables of Foo.

Another option is to make it a non-member function, especially if it makes sense that this comparator might be used by other code besides just Foo.

How to check if command line tools is installed

In macOS Catalina, and possibly some earlier versions, you can find out where the command line tools are installed using:

xcode-select -p a.k.a. xcode-select --print-path

Which will, if it is installed, respond with something like:

/Library/Developer/CommandLineTools

To find out which version you have installed there, you can use:

xcode-select -v a.k.a. xcode-select --version

Which will return something like:

xcode-select version 2370.

However, if you attempt to upgrade it to the latest version, assuming it is installed, using this:

xcode-select --install

You will receive in response:

xcode-select: error: command line tools are already installed, use "Software Update" to install updates

Which rather erroneously gives the impression you need to use Spotlight find something called 'Software Update'. In actual fact, you need to continue in the Terminal, and use this:

softwareupdate -i -a a.k.a. softwareupdate --install --all

Which tries to update everything it can and may well respond with:

Software Update Tool

Finding available software
No new software available.

To find out which versions of the different Apple SDKs are installed on your machine, use this:

xcodebuild -showsdks

pip install returning invalid syntax

The problem is the OS can’t find Pip. Pip helps you install packages MODIFIED SOME GREAT ANSWERS TO BE BETTER

Method 1 Go to path of python, then search for pip

  1. open cmd.exe
  2. write the following command:

E.g

cd C:\Users\Username\AppData\Local\Programs\Python\Python37-32

In this directory, search pip with python -m pip then install package

E.g

python -m pip install ipywidgets

-m module-name Searches sys.path for the named module and runs the corresponding .py file as a script.

OR

GO TO scripts from CMD. This is where Pip stays :)

cd C:\Users\User name\AppData\Local\Programs\Python\Python37-32\Scripts>

Then

pip install anypackage

How to change the port of Tomcat from 8080 to 80?

Here are the steps:

--> Follow the path: {tomcat directory>/conf -->Find this line:

<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />

change portnumber from "8080" to "80".

--> Save the file.

--> Restart the server :)

Different ways of clearing lists

If you're clearing the list, you, obviously, don't need the list anymore. If so, you can just delete the entire list by simple del method.

a = [1, 3, 5, 6]
del a # This will entirely delete a(the list).

But in case, you need it again, you can reinitialize it. Or just simply clear its elements by

del a[:]

Regex: Use start of line/end of line signs (^ or $) in different context

you just need to use word boundary (\b) instead of ^ and $:

\bgarp\b

How can I list all commits that changed a specific file?

As jackrabb1t pointed out, --follow is more robust since it continues listing the history beyond renames/moves. So, if you are looking for a file that is not currently in the same path or a file that has been renamed throughout various commits, --follow will track it.

This can be a better option if you want to visualize the name/path changes:

git log --follow --name-status -- <path>

But if you want a more compact list with only what matters:

git log --follow --name-status --format='%H' -- <path>

or even

git log --follow --name-only --format='%H' -- <path>

The downside is that --follow only works for a single file.

How to do a background for a label will be without color?

You are right. but here is the simplest way for making the back color of the label transparent In the properties window of that label select Web.. In Web select Transparent :)

Convert a matrix to a 1 dimensional array

If we're talking about data.frame, then you should ask yourself are the variables of the same type? If that's the case, you can use rapply, or unlist, since data.frames are lists, deep down in their souls...

 data(mtcars)
 unlist(mtcars)
 rapply(mtcars, c) # completely stupid and pointless, and slower

XML Parser for C

Two examples with expat and libxml2. The second one is, IMHO, much easier to use since it creates a tree in memory, a data structure which is easy to work with. expat, on the other hand, does not build anything (you have to do it yourself), it just allows you to call handlers at specific events during the parsing. But expat may be faster (I didn't measure).

With expat, reading a XML file and displaying the elements indented:

/* 
   A simple test program to parse XML documents with expat
   <http://expat.sourceforge.net/>. It just displays the element
   names.

   On Debian, compile with:

   gcc -Wall -o expat-test -lexpat expat-test.c  

   Inspired from <http://www.xml.com/pub/a/1999/09/expat/index.html> 
*/

#include <expat.h>
#include <stdio.h>
#include <string.h>

/* Keep track of the current level in the XML tree */
int             Depth;

#define MAXCHARS 1000000

void
start(void *data, const char *el, const char **attr)
{
    int             i;

    for (i = 0; i < Depth; i++)
        printf("  ");

    printf("%s", el);

    for (i = 0; attr[i]; i += 2) {
        printf(" %s='%s'", attr[i], attr[i + 1]);
    }

    printf("\n");
    Depth++;
}               /* End of start handler */

void
end(void *data, const char *el)
{
    Depth--;
}               /* End of end handler */

int
main(int argc, char **argv)
{

    char           *filename;
    FILE           *f;
    size_t          size;
    char           *xmltext;
    XML_Parser      parser;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s filename\n", argv[0]);
        return (1);
    }
    filename = argv[1];
    parser = XML_ParserCreate(NULL);
    if (parser == NULL) {
        fprintf(stderr, "Parser not created\n");
        return (1);
    }
    /* Tell expat to use functions start() and end() each times it encounters
     * the start or end of an element. */
    XML_SetElementHandler(parser, start, end);
    f = fopen(filename, "r");
    xmltext = malloc(MAXCHARS);
    /* Slurp the XML file in the buffer xmltext */
    size = fread(xmltext, sizeof(char), MAXCHARS, f);
    if (XML_Parse(parser, xmltext, strlen(xmltext), XML_TRUE) ==
        XML_STATUS_ERROR) {
        fprintf(stderr,
            "Cannot parse %s, file may be too large or not well-formed XML\n",
            filename);
        return (1);
    }
    fclose(f);
    XML_ParserFree(parser);
    fprintf(stdout, "Successfully parsed %i characters in file %s\n", size,
        filename);
    return (0);
}

With libxml2, a program which displays the name of the root element and the names of its children:

/*
   Simple test with libxml2 <http://xmlsoft.org>. It displays the name
   of the root element and the names of all its children (not
   descendents, just children).

   On Debian, compiles with:
   gcc -Wall -o read-xml2 $(xml2-config --cflags) $(xml2-config --libs) \
                    read-xml2.c    

*/

#include <stdio.h>
#include <string.h>
#include <libxml/parser.h>

int
main(int argc, char **argv)
{
    xmlDoc         *document;
    xmlNode        *root, *first_child, *node;
    char           *filename;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s filename.xml\n", argv[0]);
        return 1;
    }
    filename = argv[1];

    document = xmlReadFile(filename, NULL, 0);
    root = xmlDocGetRootElement(document);
    fprintf(stdout, "Root is <%s> (%i)\n", root->name, root->type);
    first_child = root->children;
    for (node = first_child; node; node = node->next) {
        fprintf(stdout, "\t Child is <%s> (%i)\n", node->name, node->type);
    }
    fprintf(stdout, "...\n");
    return 0;
}

How to really read text file from classpath in Java

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile

{
    /**
     * * feel free to make any modification I have have been here so I feel you
     * * * @param args * @throws InterruptedException
     */

    public static void main(String[] args) throws InterruptedException {
        // thread pool of 10
        File dir = new File(".");
        // read file from same directory as source //
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                // if you wanna read file name with txt files
                if (file.getName().contains("txt")) {
                    System.out.println(file.getName());
                }

                // if you want to open text file and read each line then
                if (file.getName().contains("txt")) {
                    try {
                        // FileReader reads text files in the default encoding.
                        FileReader fileReader = new FileReader(
                                file.getAbsolutePath());
                        // Always wrap FileReader in BufferedReader.
                        BufferedReader bufferedReader = new BufferedReader(
                                fileReader);
                        String line;
                        // get file details and get info you need.
                        while ((line = bufferedReader.readLine()) != null) {
                            System.out.println(line);
                            // here you can say...
                            // System.out.println(line.substring(0, 10)); this
                            // prints from 0 to 10 indext
                        }
                    } catch (FileNotFoundException ex) {
                        System.out.println("Unable to open file '"
                                + file.getName() + "'");
                    } catch (IOException ex) {
                        System.out.println("Error reading file '"
                                + file.getName() + "'");
                        // Or we could just do this:
                        ex.printStackTrace();
                    }
                }
            }
        }

    }

}

Using Java 8 to convert a list of objects into a string obtained from the toString() method

There is a method in the String API for those "joining list of string" usecases, you don't even need Stream.

List<String> myStringIterable = Arrays.asList("baguette", "bonjour");

String myReducedString = String.join(",", myStringIterable);

// And here you obtain "baguette,bonjour" in your myReducedString variable

Extracting jar to specified directory

This worked for me.

I created a folder then changed into the folder using CD option from command prompt.

Then executed the jar from there.

d:\LS\afterchange>jar xvf ..\mywar.war

How to make a background 20% transparent on Android

I know, that's a very old question.

If you want use a color value, you can also use the short version of that with #ARGB. Where A is the value for the alpha channel.

In case of a white color there are the following transparency values:

#FFFF  -     0%
#EFFF  -   6,7%
#DFFF  -  13,3%
#CFFF  -  20,0%
#BFFF  -  26,7%
#AFFF  -  33,3%
#9FFF  -  40,0%
#FFF8  -  46,7%
#7FFF  -  53,3%
#6FFF  -  60,0%
#5FFF  -  66,7%
#4FFF  -  73,3%
#3FFF  -  80,0%
#2FFF  -  86,7%
#1FFF  -  93,3%
#0FFF  - 100,0%

So you can for TextView add the following line for 20% transparency:

<TextView
    android:background="#CFFF"
    ... />

How to convert file to base64 in JavaScript?

If you're after a promise-based solution, this is @Dmitri's code adapted for that:

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file).then(
  data => console.log(data)
);

How to do a SUM() inside a case statement in SQL server

The error you posted can happen when you're using a clause in the GROUP BY statement without including it in the select.

Example

This one works!

     SELECT t.device,
            SUM(case when transits.direction = 1 then 1 else 0 end) ,
            SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t 
            where t.device in ('A','B') group by t.device

This one not (omitted t.device from the select)

     SELECT 
            SUM(case when transits.direction = 1 then 1 else 0 end) ,
            SUM(case when transits.direction = 0 then 1 else 0 end) from t1 t 
            where t.device in ('A','B') group by t.device

This will produce your error complaining that I'm grouping for something that is not included in the select

Please, provide all the query to get more support.

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

__PRETTY_FUNCTION__ handles C++ features: classes, namespaces, templates and overload

main.cpp

#include <iostream>

namespace N {
    class C {
        public:
            template <class T>
            static void f(int i) {
                (void)i;
                std::cout << "__func__            " << __func__ << std::endl
                          << "__FUNCTION__        " << __FUNCTION__ << std::endl
                          << "__PRETTY_FUNCTION__ " << __PRETTY_FUNCTION__ << std::endl;
            }
            template <class T>
            static void f(double f) {
                (void)f;
                std::cout << "__PRETTY_FUNCTION__ " << __PRETTY_FUNCTION__ << std::endl;
            }
    };
}

int main() {
    N::C::f<char>(1);
    N::C::f<void>(1.0);
}

Compile and run:

g++ -ggdb3 -O0 -std=c++11 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out

Output:

__func__            f
__FUNCTION__        f
__PRETTY_FUNCTION__ static void N::C::f(int) [with T = char]
__PRETTY_FUNCTION__ static void N::C::f(double) [with T = void]

You may also be interested in stack traces with function names: print call stack in C or C++

Tested in Ubuntu 19.04, GCC 8.3.0.

C++20 std::source_location::function_name

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p1208r5.pdf went into C++20, so we have yet another way to do it.

The documentation says:

constexpr const char* function_name() const noexcept;

6 Returns: If this object represents a position in the body of a function, returns an implementation-defined NTBS that should correspond to the function name. Otherwise, returns an empty string.

where NTBS means "Null Terminated Byte String".

I'll give it a try when support arrives to GCC, GCC 9.1.0 with g++-9 -std=c++2a still doesn't support it.

https://en.cppreference.com/w/cpp/utility/source_location claims usage will be like:

#include <iostream>
#include <string_view>
#include <source_location>
 
void log(std::string_view message,
         const std::source_location& location std::source_location::current()
) {
    std::cout << "info:"
              << location.file_name() << ":"
              << location.line() << ":"
              << location.function_name() << " "
              << message << '\n';
}
 
int main() {
    log("Hello world!");
}

Possible output:

info:main.cpp:16:main Hello world!

so note how this returns the caller information, and is therefore perfect for usage in logging, see also: Is there a way to get function name inside a C++ function?

BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

You're comparing apples to oranges here:

  • webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service

  • basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.

So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).

Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:

  • basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security

  • wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network

For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding

How to center a checkbox in a table cell?

Make sure that your <td> is not display: block;

Floating will do this, but much easier to just: display: inline;

How do I indent multiple lines at once in Notepad++?

Just install the NppAutoIndent plug-in, select Plugins > NppAutoIndent > Ignore Language and then Plugins > NppAutoIndent > Smart Indent.

MySQL - ERROR 1045 - Access denied

use this command to check the possible output

mysql> select user,host,password from mysql.user;

output

mysql> select user,host,password from mysql.user;
+-------+-----------------------+-------------------------------------------+
| user  | host                  | password                                  |
+-------+-----------------------+-------------------------------------------+
| root  | localhost             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | 127.0.0.1             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| admin | localhost             | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| admin | %                     |                                           |
+-------+-----------------------+-------------------------------------------+
5 rows in set (0.00 sec)
  1. In this user admin will not be allowed to login from another host though you have granted permission. the reason is that user admin is not identified by any password.
  2. Grant the user admin with password using GRANT command once again

    mysql> GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED by 'password'
    

then check the GRANT LIST the out put will be like his

mysql> select user,host,password from mysql.user;

+-------+-----------------------+-------------------------------------------+
| user  | host                  | password                                  |
+-------+-----------------------+-------------------------------------------+
| root  | localhost             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | 127.0.0.1             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| admin | localhost             | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| admin | %                     | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
+-------+-----------------------+-------------------------------------------+
5 rows in set (0.00 sec)

if the desired user for example user 'admin' is need to be allowed login then use once GRANT command and execute the command.

Now the user should be allowed to login.

How to get current CPU and RAM usage in Python?

The psutil library gives you information about CPU, RAM, etc., on a variety of platforms:

psutil is a module providing an interface for retrieving information on running processes and system utilization (CPU, memory) in a portable way by using Python, implementing many functionalities offered by tools like ps, top and Windows task manager.

It currently supports Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures, with Python versions from 2.6 to 3.5 (users of Python 2.4 and 2.5 may use 2.1.3 version).


Some examples:

#!/usr/bin/env python
import psutil
# gives a single float value
psutil.cpu_percent()
# gives an object with many fields
psutil.virtual_memory()
# you can convert that object to a dictionary 
dict(psutil.virtual_memory()._asdict())
# you can have the percentage of used RAM
psutil.virtual_memory().percent
79.2
# you can calculate percentage of available memory
psutil.virtual_memory().available * 100 / psutil.virtual_memory().total
20.8

Here's other documentation that provides more concepts and interest concepts:

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

I'm running Chrome version 60 and none of the previous CSS answers worked.

I found that Chrome was adding the blue highlight via the outline style. Adding the following CSS fixed it for me:

:focus {
    outline: none !important;
}

How to use target in location.href

You can use this on any element where onclick works:

onclick="window.open('some.htm','_blank');"

YouTube Autoplay not working

mute=1 or muted=1 as suggested by @Fab will work. However, if you wish to enable autoplay with sound you should add allow="autoplay" to your embedded <iframe>.

<iframe type="text/html" src="https://www.youtube.com/embed/-ePDPGXkvlw?autoplay=1" frameborder="0" allow="autoplay"></iframe>

This is officially supported and documented in Google's Autoplay Policy Changes 2017 post

Iframe delegation A feature policy allows developers to selectively enable and disable use of various browser features and APIs. Once an origin has received autoplay permission, it can delegate that permission to cross-origin iframes with a new feature policy for autoplay. Note that autoplay is allowed by default on same-origin iframes.

<!-- Autoplay is allowed. -->
<iframe src="https://cross-origin.com/myvideo.html" allow="autoplay">

<!-- Autoplay and Fullscreen are allowed. -->
<iframe src="https://cross-origin.com/myvideo.html" allow="autoplay; fullscreen">

When the feature policy for autoplay is disabled, calls to play() without a user gesture will reject the promise with a NotAllowedError DOMException. And the autoplay attribute will also be ignored.

Send raw ZPL to Zebra printer via USB

I've found yet an easier way to write to a Zebra printer over a COM port. I went to the Windows control panel and added a new printer. For the port, I chose COM1 (the port the printer was plugged in to). I used a "Generic / Text Only" printer driver. I disabled the print spooler (a standard option in the printer preferences) as well as all advanced printing options. Now, I can just print any string to that printer and if the string contains ZPL, the printer renders the ZPL just fine! No need for special "start sequences" or funky stuff like that. Yay for simplicity!

How to change Apache Tomcat web server port number

You need to edit the Tomcat/conf/server.xml and change the connector port. The connector setting should look something like this:

<Connector port="8080" maxHttpHeaderSize="8192"
           maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
           enableLookups="false" redirectPort="8443" acceptCount="100"
           connectionTimeout="20000" disableUploadTimeout="true" />

Just change the connector port from default 8080 to another valid port number.

Is there an equivalent of 'which' on the Windows command line?

For you Windows XP users (who have no where command built-in), I have written a "where like" command as a rubygem called whichr.

To install it, install Ruby.

Then

gem install whichr

Run it like:

C:> whichr cmd_here

getFilesDir() vs Environment.getDataDirectory()

Environment returns user data directory. And getFilesDir returns application data directory.

How can I generate random alphanumeric strings?

A slightly cleaner version of DTB's solution.

    var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var random = new Random();
    var list = Enumerable.Repeat(0, 8).Select(x=>chars[random.Next(chars.Length)]);
    return string.Join("", list);

Your style preferences may vary.

javascript create empty array of a given size

If you want to create anonymous array with some values so you can use this syntax.

_x000D_
_x000D_
var arr = new Array(50).fill().map((d,i)=>++i)
console.log(arr)
_x000D_
_x000D_
_x000D_

toBe(true) vs toBeTruthy() vs toBeTrue()

In javascript there are trues and truthys. When something is true it is obviously true or false. When something is truthy it may or may not be a boolean, but the "cast" value of is a boolean.

Examples.

true == true; // (true) true
1 == true; // (true) truthy
"hello" == true;  // (true) truthy
[1, 2, 3] == true; // (true) truthy
[] == false; // (true) truthy
false == false; // (true) true
0 == false; // (true) truthy
"" == false; // (true) truthy
undefined == false; // (true) truthy
null == false; // (true) truthy

This can make things simpler if you want to check if a string is set or an array has any values.

var users = [];

if(users) {
  // this array is populated. do something with the array
}

var name = "";

if(!name) {
  // you forgot to enter your name!
}

And as stated. expect(something).toBe(true) and expect(something).toBeTrue() is the same. But expect(something).toBeTruthy() is not the same as either of those.

Best approach to converting Boolean object to string in java

If you see implementation of both the method, they look same.

String.valueOf(b)

public static String valueOf(boolean b) {
        return b ? "true" : "false";
    }

Boolean.toString(b)

public static String toString(boolean b) {
        return b ? "true" : "false";
    }

So both the methods are equally efficient.

How to set an image's width and height without stretching it?

If using flexbox is a valid option for you (don't need to suport old browsers), check my other answer here (which is possibly a duplicate of this one):

Basically you'd need to wrap your img tag in a div and your css would look like this:

.img__container {
    display: flex;
    padding: 15px 12px;
    box-sizing: border-box;
    width: 400px; height: 200px;

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

How to fix "Root element is missing." when doing a Visual Studio (VS) Build?

In my case.I was getting missing element error pointing to NuGet.Config file. At that time it was looking some thing like this

<?xml version="1.0" encoding="utf-8"?>
<settings>
  <repositoryPath>Packages</repositoryPath>
</settings>

then I just added configuration tag that actually wraps entire xml. Now working fine for me

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <settings>
     <repositoryPath>Packages</repositoryPath>
  </settings>
</configuration>

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

How do you delete all text above a certain line

:1,.d deletes lines 1 to current.
:1,.-1d deletes lines 1 to above current.

(Personally I'd use dgg or kdgg like the other answers, but TMTOWTDI.)

Encode html entities in javascript

Sometimes you just want to encode every character... This function replaces "everything but nothing" in regxp.

function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}

_x000D_
_x000D_
function encode(w) {_x000D_
  return w.replace(/[^]/g, function(w) {_x000D_
    return "&#" + w.charCodeAt(0) + ";";_x000D_
  });_x000D_
}_x000D_
_x000D_
test.value=encode(document.body.innerHTML.trim());
_x000D_
<textarea id=test rows=11 cols=55>www.WHAK.com</textarea>
_x000D_
_x000D_
_x000D_

How can I write data in YAML format in a file?

import yaml

data = dict(
    A = 'a',
    B = dict(
        C = 'c',
        D = 'd',
        E = 'e',
    )
)

with open('data.yml', 'w') as outfile:
    yaml.dump(data, outfile, default_flow_style=False)

The default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:

A: a
B: {C: c, D: d, E: e}

public static const in TypeScript

If you did want something that behaved more like a static constant value in modern browsers (in that it can't be changed by other code), you could add a get only accessor to the Library class (this will only work for ES5+ browsers and NodeJS):

export class Library {
    public static get BOOK_SHELF_NONE():string { return "None"; }
    public static get BOOK_SHELF_FULL():string { return "Full"; }   
}

var x = Library.BOOK_SHELF_NONE;
console.log(x);
Library.BOOK_SHELF_NONE = "Not Full";
x = Library.BOOK_SHELF_NONE;
console.log(x);

If you run it, you'll see how the attempt to set the BOOK_SHELF_NONE property to a new value doesn't work.

2.0

In TypeScript 2.0, you can use readonly to achieve very similar results:

export class Library {
    public static readonly BOOK_SHELF_NONE = "None";
    public static readonly BOOK_SHELF_FULL = "Full";
}

The syntax is a bit simpler and more obvious. However, the compiler prevents changes rather than the run time (unlike in the first example, where the change would not be allowed at all as demonstrated).

In Chrome 55, prevent showing Download button for HTML 5 video

I solved the problem by covering the download button of a audio controller with a transparent div that changes the symbol of the mouse-cursor to "not-allowed".

The div blocks the activation of the download button.

Height: 50px, Width: 35px, Left: (document-right -60), Top: (same as the audio controller).

You must set the z-index style of the div above the z-index of the audio-controller.

See sapplic.com/jive66 for an example that works for chrome on win7 and on win8.

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

To delete an element use the following way:

// declaring and assigning array1 
std:vector<int> array1 {0,2,3,4};

// erasing the value in the array
array1.erase(array1.begin()+n);

For a more broad overview you can visit: http://www.cplusplus.com/reference/vector/vector/erase/

Uncaught TypeError: Cannot read property 'top' of undefined

I ran through similar problem and found that I was trying to get the offset of footer but I was loading my script inside a div before the footer. It was something like this:

<div> I have some contents </div>
<script>
  $('footer').offset().top;
</script>
<footer>This is footer</footer>

So, the problem was, I was calling the footer element before the footer was loaded.

I pushed down my script below footer and it worked fine!

A simple algorithm for polygon intersection

I understand the original poster was looking for a simple solution, but unfortunately there really is no simple solution.

Nevertheless, I've recently created an open-source freeware clipping library (written in Delphi, C++ and C#) which clips all kinds of polygons (including self-intersecting ones). This library is pretty simple to use: http://sourceforge.net/projects/polyclipping/ .

What's the difference between "Solutions Architect" and "Applications Architect"?

Sounds like the same to me! Though I don't totally disagree with Oli. I'd give a selected few people the Software Architect title if they want it but experience tells me the people who would actually deserve the title of Software Architect usually aint that in to titles.

Index all *except* one item in python

Use np.delete ! It does not actually delete anything inplace

Example:

import numpy as np
a = np.array([[1,4],[5,7],[3,1]])                                       

# a: array([[1, 4],
#           [5, 7],
#           [3, 1]])

ind = np.array([0,1])                                                   

# ind: array([0, 1])

# a[ind]: array([[1, 4],
#                [5, 7]])

all_except_index = np.delete(a, ind, axis=0)                                              
# all_except_index: array([[3, 1]])

# a: (still the same): array([[1, 4],
#                             [5, 7],
#                             [3, 1]])

CMake output/build directory

You should not rely on a hard coded build dir name in your script, so the line with ../Compile must be changed.

It's because it should be up to user where to compile.

Instead of that use one of predefined variables: http://www.cmake.org/Wiki/CMake_Useful_Variables (look for CMAKE_BINARY_DIR and CMAKE_CURRENT_BINARY_DIR)

How can I check whether a numpy array is empty or not?

One caveat, though. Note that np.array(None).size returns 1! This is because a.size is equivalent to np.prod(a.shape), np.array(None).shape is (), and an empty product is 1.

>>> import numpy as np
>>> np.array(None).size
1
>>> np.array(None).shape
()
>>> np.prod(())
1.0

Therefore, I use the following to test if a numpy array has elements:

>>> def elements(array):
    ...     return array.ndim and array.size

>>> elements(np.array(None))
0
>>> elements(np.array([]))
0
>>> elements(np.zeros((2,3,4)))
24

More than one file was found with OS independent path 'META-INF/LICENSE'

Add the following in app level gradle file inside android{}

packagingOptions {
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/ASL2.0'
    exclude("META-INF/*.kotlin_module") 
} 

     

How To Inject AuthenticationManager using Java Configuration in a Custom Filter

Override method authenticationManagerBean in WebSecurityConfigurerAdapter to expose the AuthenticationManager built using configure(AuthenticationManagerBuilder) as a Spring bean:

For example:

   @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
   @Override
   public AuthenticationManager authenticationManagerBean() throws Exception {
       return super.authenticationManagerBean();
   }

Angular2: How to load data before rendering the component?

A nice solution that I've found is to do on UI something like:

<div *ngIf="isDataLoaded">
 ...Your page...
</div

Only when: isDataLoaded is true the page is rendered.

How to get datas from List<Object> (Java)?

Thanks All for your responses. Good solution was to use 'brain`s' method:

List<Object> list = getHouseInfo();
for (int i=0; i<list.size; i++){
Object[] row = (Object[]) list.get(i);
System.out.println("Element "+i+Arrays.toString(row));
}

Problem solved. Thanks again.

What is the best free memory leak detector for a C/C++ program and its plug-in DLLs?

Try Jochen Kalmbach's Memory Leak Detector on Code Project. The URL to the latest version was somewhere in the comments when I last checked.

How to get JSON from webpage into Python script

All that the call to urlopen() does (according to the docs) is return a file-like object. Once you have that, you need to call its read() method to actually pull the JSON data across the network.

Something like:

jsonurl = urlopen(url)

text = json.loads(jsonurl.read())
print text

How to update a menu item shown in the ActionBar?

I have used this code:

public boolean onPrepareOptionsMenu (Menu menu) {       
    MenuInflater inflater = getMenuInflater();
    TextView title  = (TextView) findViewById(R.id.title);
    menu.getItem(0).setTitle(
        getString(R.string.payFor) + " " + title.getText().toString());
    menu.getItem(1).setTitle(getString(R.string.payFor) + "...");
    return true;        
}

And worked like a charm to me you can find OnPrepareOptionsMenu here

How to delete a cookie using jQuery?

You can try this:

$.removeCookie('the_cookie', { path: '/' });

source: https://github.com/carhartl/jquery-cookie#readme

What is path of JDK on Mac ?

Which Mac version are you using? try these paths

 /System/Library/Frameworks/JavaVM.framework/ OR
 /usr/libexec/java_home

This link might help - How To Set $JAVA_HOME Environment Variable On Mac OS X

Generate random password string with requirements in javascript

Here's a way to create a flexible generator that allows you to add some rules:

function generatePassword(length, rules) {
    if (!length || length == undefined) {
        length = 8;
    }

    if (!rules || rules == undefined) {
        rules = [
            {chars: "abcdefghijklmnopqrstuvwxyz", min: 3},  // As least 3 lowercase letters
            {chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", min: 2},  // At least 2 uppercase letters
            {chars: "0123456789", min: 2},                  // At least 2 digits
            {chars: "!@#$&*?|%+-_./:;=()[]{}", min: 1}      // At least 1 special char
        ];
    }

    var allChars = "", allMin = 0;
    rules.forEach(function(rule) {
        allChars += rule.chars;
        allMin += rule.min;
    });
    if (length < allMin) {
        length = allMin;
    }
    rules.push({chars: allChars, min: length - allMin});
    
    var pswd = "";
    rules.forEach(function(rule) {
        if (rule.min > 0) {
            pswd += shuffleString(rule.chars, rule.min);
        }
    });
    
    return shuffleString(pswd);
}

function shuffleString(str, maxlength) {
    var shuffledString = str.split('').sort(function(){return 0.5-Math.random()}).join('');
    if (maxlength > 0) {
        shuffledString = shuffledString.substr(0, maxlength);
    }
    return shuffledString;
}

var pswd = generatePassword(15, [
  {chars: "abcdefghijklmnopqrstuvwxyz", min: 4},  // As least 4 lowercase letters
  {chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", min: 1},  // At least 1 uppercase letters
  {chars: "0123456789", min: 3},                  // At least 3 digits
  {chars: "!@#$&*?|%+-_./:;=()[]{}", min: 2}      // At least 2 special chars
]);

console.log(pswd, pswd.length);

Converting a date in MySQL from string field

SELECT STR_TO_DATE(dateString, '%d/%m/%y') FROM yourTable...

How to import classes defined in __init__.py

Edit, since i misunderstood the question:

Just put the Helper class in __init__.py. Thats perfectly pythonic. It just feels strange coming from languages like Java.

hasNext in Python iterators?

There's an alternative to the StopIteration by using next(iterator, default_value).

For exapmle:

>>> a = iter('hi')
>>> print next(a, None)
h
>>> print next(a, None)
i
>>> print next(a, None)
None

So you can detect for None or other pre-specified value for end of the iterator if you don't want the exception way.

Set focus on TextBox in WPF from view model

The problem is that once the IsUserNameFocused is set to true, it will never be false. This solves it by handling the GotFocus and LostFocus for the FrameworkElement.

I was having trouble with the source code formatting so here is a link

How to set underline text on textview?

In my sign_in.xml file I used this:

<Button
    android:id="@+id/signuptextlinkbtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:background="@android:color/transparent"
    android:onClick="performSingUpMethod"
    android:text="Sign up now!"
    android:textColor="#5B55FF"
    android:textSize="15dp"
    android:textStyle="bold" />

In my SignIn.java file, I used this:

import android.graphics.Paint;
Button signuptextlinkbutton = (Button) findViewById(R.id.signuptextlinkbtn);
signuptextlinkbutton.setPaintFlags(signuptextlinkbutton.getPaintFlags()| Paint.UNDERLINE_TEXT_FLAG);

Now I can see my link underlined. It was simply text even thought I declared it as a Button.

jQuery + client-side template = "Syntax error, unrecognized expression"

As the official document: As of 1.9, a string is only considered to be HTML if it starts with a less-than ("<") character. The Migrate plugin can be used to restore the pre-1.9 behavior.

If a string is known to be HTML but may start with arbitrary text that is not an HTML tag, pass it to jQuery.parseHTML() which will return an array of DOM nodes representing the markup. A jQuery collection can be created from this, for example: $($.parseHTML(htmlString)). This would be considered best practice when processing HTML templates for example. Simple uses of literal strings such as $("<p>Testing</p>").appendTo("body") are unaffected by this change.

Can I change the headers of the HTTP request sent by the browser?

Use some javascript!

xmlhttp=new XMLHttpRequest();
xmlhttp.open('PUT',http://www.mydomain.org/documents/standards/browsers/supportlist)
xmlhttp.send("page content goes here");

How to list all `env` properties within jenkins pipeline job?

The easiest and quickest way is to use following url to print all environment variables

http://localhost:8080/env-vars.html/

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

If you are using CMake, you can also get this error when you set SET(GUI_TYPE WIN32) on a console application.

The thread has exited with code 0 (0x0) with no unhandled exception

if your application uses threads directly or indirectly (i.e. behind the scene like in a 3rd-party library) it is absolutely common to have threads terminate after they are done... which is basically what you describe... the debugger shows this message... you can configure the debugger to not display this message if you don't want it...

If the above does not help then please provide more details since I am not sure what exactly the problem is you face...

How to logout and redirect to login page using Laravel 5.4?

here is another way to do it by calling Auth::logout() in route

Route::get('/logout', function(){
   Auth::logout();
   return Redirect::to('login');
});

How to hide UINavigationBar 1px bottom line

Simple solution in swift

   let navigationBar = self.navigationController?.navigationBar
    navigationBar?.setBackgroundImage(UIImage(), forBarPosition: UIBarPosition.Any, barMetrics: UIBarMetrics.Default)
    navigationBar?.shadowImage = UIImage()

Java: how do I get a class literal from a generic type?

There are no Class literals for parameterized types, however there are Type objects that correctly define these types.

See java.lang.reflect.ParameterizedType - http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/ParameterizedType.html

Google's Gson library defines a TypeToken class that allows to simply generate parameterized types and uses it to spec json objects with complex parameterized types in a generic friendly way. In your example you would use:

Type typeOfListOfFoo = new TypeToken<List<Foo>>(){}.getType()

I intended to post links to the TypeToken and Gson classes javadoc but Stack Overflow won't let me post more than one link since I'm a new user, you can easily find them using Google search

Windows task scheduler error 101 launch failure code 2147943785

The user that is configured to run this scheduled task must have "Log on as a batch job" rights on the computer that hosts the exe you are launching. This can be configured on the local security policy of the computer that hosts the exe. You can change the policy (on the server hosting the exe) under

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log On As Batch Job

Add your user to this list (you could also make the user account a local admin on the machine hosting the exe).

Finally, you could also simply copy your exe from the network location to your local computer and run it from there instead.

Note also that a domain policy could be restricting "Log on as a batch job" rights at your organization.

How to get selected value of a html select with asp.net

<%@ Page Language="C#" AutoEventWireup="True" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">    
<head>
    <title> HtmlSelect Example </title>
    <script runat="server">
      void Button_Click (Object sender, EventArgs e)
      {
         Label1.Text = "Selected index: " + Select1.SelectedIndex.ToString()
                       + ", value: " + Select1.Value;    
      }    
   </script>    
</head>    
<body>    
   <form id="form1" runat="server">

      Select an item: 

      <select id="Select1" runat="server">    
         <option value="Text for Item 1" selected="selected"> Item 1 </option>
         <option value="Text for Item 2"> Item 2 </option>
         <option value="Text for Item 3"> Item 3 </option>
         <option value="Text for Item 4"> Item 4 </option>
      </select>

      <button onserverclick="Button_Click" runat="server" Text="Submit"/>

      <asp:Label id="Label1" runat="server"/>    
   </form>
</body>
</html>

Source from Microsoft. Hope this is helpful!

How to update values using pymongo?

in python the operators should be in quotes: db.ProductData.update({'fromAddress':'http://localhost:7000/'}, {"$set": {'fromAddress': 'http://localhost:5000/'}},{"multi": True})

Remove element by id

This is the best function to remove an element without script error:

function Remove(EId)
{
    return(EObj=document.getElementById(EId))?EObj.parentNode.removeChild(EObj):false;
}

Note to EObj=document.getElementById(EId).

This is ONE equal sign not ==.

if element EId exists then the function removes it, otherwise it returns false, not error.

Replace Div Content onclick

EDIT: This answer was submitted before the OP's jsFiddle example was posted in question. See second answer for response to that jsFiddle.


Here is an example of how it could work:

Working jsFiddle Demo

HTML:

<div id="someDiv">
    Once upon a midnight dreary
    <br>While I pondered weak and weary
    <br>Over many a quaint and curious
    <br>Volume of forgotten lore.
</div>
Type new text here:<br>
<input type="text" id="replacementtext" />
<input type="button" id="mybutt" value="Swap" />

<input type="hidden" id="vault" />

javascript/jQuery:

//Declare persistent vars outside function
var savText, newText, myState = 0;

$('#mybutt').click(function(){
    if (myState==0){
        savText = $('#someDiv').html(); //save poem data from DIV
        newText = $('#replacementtext').val(); //save data from input field
        $('#replacementtext').val(''); //clear input field
        $('#someDiv').html( newText ); //replace poem with insert field data
        myState = 1; //remember swap has been done once
    } else {
        $('#someDiv').html(savText);
        $('#replacementtext').val(newText); //replace contents
        myState = 0;
    }
});

Convert character to ASCII code in JavaScript

String.prototype.charCodeAt() can convert string characters to ASCII numbers. For example:

"ABC".charCodeAt(0) // returns 65

For opposite use String.fromCharCode(10) that convert numbers to equal ASCII character. This function can accept multiple numbers and join all the characters then return the string. Example:

String.fromCharCode(65,66,67); // returns 'ABC'

Here is a quick ASCII characters reference:

{
"31": "",      "32": " ",     "33": "!",     "34": "\"",    "35": "#",    
"36": "$",     "37": "%",     "38": "&",     "39": "'",     "40": "(",    
"41": ")",     "42": "*",     "43": "+",     "44": ",",     "45": "-",    
"46": ".",     "47": "/",     "48": "0",     "49": "1",     "50": "2",    
"51": "3",     "52": "4",     "53": "5",     "54": "6",     "55": "7",    
"56": "8",     "57": "9",     "58": ":",     "59": ";",     "60": "<",    
"61": "=",     "62": ">",     "63": "?",     "64": "@",     "65": "A",    
"66": "B",     "67": "C",     "68": "D",     "69": "E",     "70": "F",    
"71": "G",     "72": "H",     "73": "I",     "74": "J",     "75": "K",    
"76": "L",     "77": "M",     "78": "N",     "79": "O",     "80": "P",    
"81": "Q",     "82": "R",     "83": "S",     "84": "T",     "85": "U",    
"86": "V",     "87": "W",     "88": "X",     "89": "Y",     "90": "Z",    
"91": "[",     "92": "\\",    "93": "]",     "94": "^",     "95": "_",    
"96": "`",     "97": "a",     "98": "b",     "99": "c",     "100": "d",    
"101": "e",    "102": "f",    "103": "g",    "104": "h",    "105": "i",    
"106": "j",    "107": "k",    "108": "l",    "109": "m",    "110": "n",    
"111": "o",    "112": "p",    "113": "q",    "114": "r",    "115": "s",    
"116": "t",    "117": "u",    "118": "v",    "119": "w",    "120": "x",    
"121": "y",    "122": "z",    "123": "{",    "124": "|",    "125": "}",    
"126": "~",    "127": ""
}

Using a PHP variable in a text input value = statement

I have been doing PHP for my project, and I can say that the following code works for me. You should try it.

echo '<input type = "text" value = '.$idtest.'>'; 

Select mysql query between date?

You can use now() like:

Select data from tablename where datetime >= "01-01-2009 00:00:00" and datetime <= now();

How can you profile a Python script?

pprofile

line_profiler (already presented here) also inspired pprofile, which is described as:

Line-granularity, thread-aware deterministic and statistic pure-python profiler

It provides line-granularity as line_profiler, is pure Python, can be used as a standalone command or a module, and can even generate callgrind-format files that can be easily analyzed with [k|q]cachegrind.

vprof

There is also vprof, a Python package described as:

[...] providing rich and interactive visualizations for various Python program characteristics such as running time and memory usage.

heatmap

How to check if a file exists from inside a batch file

C:\>help if

Performs conditional processing in batch programs.

IF [NOT] ERRORLEVEL number command

IF [NOT] string1==string2 command

IF [NOT] EXIST filename command

How do I read a large csv file with pandas?

In case someone is still looking for something like this, I found that this new library called modin can help. It uses distributed computing that can help with the read. Here's a nice article comparing its functionality with pandas. It essentially uses the same functions as pandas.

import modin.pandas as pd
pd.read_csv(CSV_FILE_NAME)

JSONResult to String

You're looking for the JavaScriptSerializer class, which is used internally by JsonResult:

string json = new JavaScriptSerializer().Serialize(jsonResult.Data);

Searching for UUIDs in text with regex

If you want to check or validate a specific UUID version, here are the corresponding regexes.

Note that the only difference is the version number, which is explained in 4.1.3. Version chapter of UUID 4122 RFC.

The version number is the first character of the third group : [VERSION_NUMBER][0-9A-F]{3} :

  • UUID v1 :

    /^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    
  • UUID v2 :

    /^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    
  • UUID v3 :

    /^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    
  • UUID v4 :

    /^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    
  • UUID v5 :

    /^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
    

Is it possible to make desktop GUI application in .NET Core?

Yes, it is possible.

.NET Core doesn't have any components for native GUI application out of the box. However, there is a NuGet package for it that is called Electron.NET, as per Gregor Biswanger's answer.

Electron is a framework that allows you to build native GUI applications on top of Node.js. Electron.NET is a NuGet package that allows you to utilise Electron and Node.js from within your .NET Core code.

The good news is that you don't have to learn JavaScript, Electron or Node.js in order to be able to use the NuGet package. JS files do run inside your application, but they get automatically generated by the build process.

All you do is build a pretty standard ASP.NET Core MVC app. The only difference is that, instead of running in the browser, it runs as a native windowed app. Besides just a few lines of code specific to the Electron.NET package, you won't need to learn anything above ASP.NET Core MVC.

This page provides a tutorial on how to use it. It also contains some links to sample code repositories.

find difference between two text files with one item per line

With GNU sed:

sed 's#[^^]#[&]#g;s#\^#\\^#g;s#^#/^#;s#$#$/d#' file1 | sed -f- file2

How it works:

The first sed produces an output like this:

/^[d][s][f]$/d
/^[s][d][f][s][d]$/d
/^[d][s][f][s][d][f]$/d

Then it is used as a sed script by the second sed.

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

I know there are bunch of very well crafted answers. I found a correct documentation from apple website where they have specified the specification for screenshot requirements. Here is the link below https://help.apple.com/app-store-connect/#/devd274dd925 App Previews Screenshot Specs

Parsing domain from a URL

$domain = str_ireplace('www.', '', parse_url($url, PHP_URL_HOST));

This would return the google.com for both http://google.com/... and http://www.google.com/...

Converting List<String> to String[] in Java

I've designed and implemented Dollar for this kind of tasks:

String[] strarray= $(strlist).toArray();

Intellij JAVA_HOME variable

So far, nobody has answered the actual question.

Someone can figure what is happening ?

The problem here is that while the value of your $JAVA_HOME is correct, you defined it in the wrong place.

  • When you open a terminal and launch a Bash session, it will read the ~/.bash_profile file. Thus, when you enter echo $JAVA_HOME, it will return the value that has been set there.
  • When you launch IntelliJ directly, it will not read ~/.bash_profile … why should it? So to IntelliJ, this variable is not set.

There are two possible solutions to this:

  • Launch IntelliJ from a Bash session: open a terminal and run "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea". The idea process will inherit any environment variables of Bash that have been exported. (Since you did export JAVA_HOME=…, it works!), or, the sophisticated way:
  • Set global environment variables that apply to all programs, not only Bash sessions. This is more complicated than you might think, and is explained here and here, for example. What you should do is run

    /bin/launchctl setenv JAVA_HOME $(/usr/libexec/java_home)
    

    However, this gets reset after a reboot. To make sure this gets run on every boot, execute

    cat << EOF > ~/Library/LaunchAgents/setenv.JAVA_HOME.plist
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
        "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
      <plist version="1.0">
      <dict>
        <key>Label</key>
        <string>setenv.JAVA_HOME</string>
        <key>ProgramArguments</key>
        <array>
          <string>/bin/launchctl</string>
          <string>setenv</string>
          <string>JAVA_HOME</string>
          <string>$(/usr/libexec/java_home)</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>ServiceIPC</key>
        <false/>
      </dict>
    </plist>
    EOF
    

    Note that this also affects the Terminal process, so there is no need to put anything in your ~/.bash_profile.

Errno 13 Permission denied Python

If you have this problem in Windows 10, and you know you have premisions on folder (You could write before but it just started to print exception PermissionError recently).. You will need to install Windows updates... I hope someone will help this info.

javascript compare strings without being case sensitive

You can make both arguments lower case, and that way you will always end up with a case insensitive search.

var string1 = "aBc";
var string2 = "AbC";

if (string1.toLowerCase() === string2.toLowerCase())
{
    #stuff
}

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

Generic Interface

If I understand correctly, you want to have one class implement multiple of those interfaces with different input/output parameters? This will not work in Java, because the generics are implemented via erasure.

The problem with the Java generics is that the generics are in fact nothing but compiler magic. At runtime, the classes do not keep any information about the types used for generic stuff (class type parameters, method type parameters, interface type parameters). Therefore, even though you could have overloads of specific methods, you cannot bind those to multiple interface implementations which differ in their generic type parameters only.

In general, I can see why you think that this code has a smell. However, in order to provide you with a better solution, it would be necessary to know a little more about your requirements. Why do you want to use a generic interface in the first place?

How to stretch in width a WPF user control to its window?

The Canvas in WPF doesn't provide much automatic layout support. I try to steer clear of them for this reason (HorizontalAlignment and VerticalAlignment don't work as expected), but I got your code to work with these minor modifications (binding the Width and Height of the control to the canvas's ActualWidth/ActualHeight).

<Window x:Class="TCI.Indexer.UI.Operacao"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tci="clr-namespace:TCI.Indexer.UI.Controles"
Title=" " MinHeight="550" MinWidth="675" Loaded="Load" 
ResizeMode="NoResize" WindowStyle="None" WindowStartupLocation="CenterScreen" 
WindowState="Maximized" Focusable="True" x:Name="windowOperacao">

<Canvas x:Name="canv">
    <Grid>
        <tci:Status x:Name="ucStatus" Width="{Binding ElementName=canv
                                                    , Path=ActualWidth}" 
                                      Height="{Binding ElementName=canv
                                                    , Path=ActualHeight}"/> 
        <!-- the control which I want to stretch in width -->
    </Grid>
</Canvas>

The Canvas is the problem here. If you're not actually utilizing the features the canvas offers in terms of layout or Z-Order "squashing" (think of the flatten command in PhotoShop), I would consider using a control like a Grid instead so you don't end up having to learn the quirks of a control that works differently than you have come to expect with WPF.

check if a number already exist in a list in python

You could probably use a set object instead. Just add numbers to the set. They inherently do not replicate.

Check if cookies are enabled

Answer on an old question, this new post is posted on April the 4th 2013

To complete the answer of @misza, here a advanced method to check if cookies are enabled without page reloading. The problem with @misza is that it not always work when the php ini setting session.use_cookies is not true. Also the solution does not check if a session is already started.

I made this function and test it many times with in different situations and does the job very well.

    function suGetClientCookiesEnabled() // Test if browser has cookies enabled
    {
      // Avoid overhead, if already tested, return it
      if( defined( 'SU_CLIENT_COOKIES_ENABLED' ))
       { return SU_CLIENT_COOKIES_ENABLED; }

      $bIni = ini_get( 'session.use_cookies' ); 
      ini_set( 'session.use_cookies', 1 ); 

      $a = session_id();
      $bWasStarted = ( is_string( $a ) && strlen( $a ));
      if( !$bWasStarted )
      {
        @session_start();
        $a = session_id();
      }

   // Make a copy of current session data
  $aSesDat = (isset( $_SESSION ))?$_SESSION:array();
   // Now we destroy the session and we lost the data but not the session id 
   // when cookies are enabled. We restore the data later. 
  @session_destroy(); 
   // Restart it
  @session_start();

   // Restore copy
  $_SESSION = $aSesDat;

   // If no cookies are enabled, the session differs from first session start
  $b = session_id();
  if( !$bWasStarted )
   { // If not was started, write data to the session container to avoid data loss
     @session_write_close(); 
   }

   // When no cookies are enabled, $a and $b are not the same
  $b = ($a === $b);
  define( 'SU_CLIENT_COOKIES_ENABLED', $b );

  if( !$bIni )
   { @ini_set( 'session.use_cookies', 0 ); }

  //echo $b?'1':'0';
  return $b;
    }

Usage:

if( suGetClientCookiesEnabled())
 { echo 'Cookies are enabled!'; }
else { echo 'Cookies are NOT enabled!'; }

Important note: The function temporarily modify the ini setting of PHP when it not has the correct setting and restore it when it was not enabled. This is only to test if cookies are enabled. It can get go wrong when you start a session and the php ini setting session.use_cookies has an incorrect value. To be sure that the session is working correctly, check and/or set it before start a session, for example:

   if( suGetClientCookiesEnabled())
     { 
       echo 'Cookies are enabled!'; 
       ini_set( 'session.use_cookies', 1 ); 
       echo 'Starting session';
       @start_session(); 

     }
    else { echo 'Cookies are NOT enabled!'; }

How to serve .html files with Spring

I faced the same issue and tried various solutions to load the html page from Spring MVC, following solution worked for me

Step-1 in server's web.xml comment these two lines

<!--     <mime-mapping>
        <extension>htm</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>--> 
<!--     <mime-mapping>
        <extension>html</extension>
        <mime-type>text/html</mime-type>
    </mime-mapping>
 -->

Step-2 enter following code in application's web xml

  <servlet-mapping>
    <servlet-name>jsp</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>

Step-3 create a static controller class

@Controller 
public class FrontController {
     @RequestMapping("/landingPage") 
    public String getIndexPage() { 
    return "CompanyInfo"; 

    }

}

Step-4 in the Spring configuration file change the suffix to .htm .htm

Step-5 Rename page as .htm file and store it in WEB-INF and build/start the server

localhost:8080/.../landingPage

EOFError: EOF when reading a line

**The best is to use try except block to get rid of EOF **

try:
    width = input()
    height = input()
    def rectanglePerimeter(width, height):
       return ((width + height)*2)
    print(rectanglePerimeter(width, height))
except EOFError as e:
    print(end="")

I need to get all the cookies from the browser

To retrieve all cookies for the current document open in the browser, you again use the document.cookie property.

Ruby: kind_of? vs. instance_of? vs. is_a?

It is more Ruby-like to ask objects whether they respond to a method you need or not, using respond_to?. This allows both minimal interface and implementation unaware programming.

It is not always applicable of course, thus there is still a possibility to ask about more conservative understanding of "type", which is class or a base class, using the methods you're asking about.

How to put a text beside the image?

make the image float: left; and the text float: right;

Take a look at this fiddle I used a picture online but you can just swap it out for your picture.

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

Short answer

Install the latest version of mongodb.

A little longer answer

Make sure your package.json is using the latest version of mongodb, then remove node_modules/mongodb and do npm install again. If you didn't use mongodb as a direct dependency, try to find which package is using mongdb. I used:

find . -type f -name package.json | xargs grep mongodb
...
./sails-mongo/package.json:    "mongodb": "1.4.26",
...

So I updated ./sails-mongo/package.json to:

"mongodb": "2.1.7",

Then remove node_modules/mongodb and do npm install again. Seems fine now.

Even longer answer

I don't like the current suggested way of using

require('../browser_build/bson')

Since looking at ../browser_build/bson.js, a 4k+ lines file, which seem also a "non-native" implementation. So although it won't spit out any complains, it is still "using pure JS version", which means slower performance.

Looking at https://github.com/mongodb/js-bson/issues/145 and https://github.com/mongodb/js-bson/issues/165, it seems like the issue was caused by:

antoniofruci commented on Sep 15, 2015

I just found out that c++ code has been moved out 6 months ago and it is now an optional dependency: bson-ext. Indeed, if you install latest version no error occurs.

So I tried to remove the whole node_modules and still got the same error. And looking at package.json of node_modules/mongodb, its version is still 1.4.26, not latest 2.1.7.

Apparently my mongodb comes as a dependency of another package I installed: sails-mongo. Modifying the package.json of sails-mongo and redoing npm install finally solve the issue.

Set inputType for an EditText Programmatically?

i've solve all with

.setInputType(InputType.TYPE_CLASS_NUMBER);

for see clear data and

.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);

for see the dots (if the data is a number, it isn't choice che other class)

How do you make Vim unhighlight what you searched for?

I think the best answer is to have a leader shortcut:

<leader>c :nohl<CR>

Now whenever you have your document all junked up with highlighted terms, you just hit , + C (I have my leader mapped to a comma). It works perfectly.

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

If you want to use two-way data binding for form inputs you need to import theFormsModule package in your Angular module. For more info see the Angular 2 official tutorial here and the official documentation for forms

in the app.module.ts add below lines :

import { FormsModule } from '@angular/forms';

[...]

@NgModule({
  imports: [
    [...]
    FormsModule
  ],
  [...]
})

C programming: Dereferencing pointer to incomplete type error

You are using the pointer newFile without allocating space for it.

struct stasher_file *newFile = malloc(sizeof(stasher_file));

Also you should put the struct name at the top. Where you specified stasher_file is to create an instance of that struct.

struct stasher_file {
    char name[32];
    int  size;
    int  start;
    int  popularity;
};

Convert an integer to a byte array

What's wrong with converting it to a string?

[]byte(fmt.Sprintf("%d", myint))

In Gradle, is there a better way to get Environment Variables?

I couldn't get the form suggested by @thoredge to work in Gradle 1.11, but this works for me:

home = System.getenv('HOME')

It helps to keep in mind that anything that works in pure Java will work in Gradle too.

Is it possible to move/rename files in Git and maintain their history?

No.

The short answer is NO. It is not possible to rename a file in Git and remember the history. And it is a pain.

Rumor has it that git log --follow --find-copies-harder will work, but it does not work for me, even if there are zero changes to the file contents, and the moves have been made with git mv.

(Initially I used Eclipse to rename and update packages in one operation, which may have confused Git. But that is a very common thing to do. --follow does seem to work if only a mv is performed and then a commit and the mv is not too far.)

Linus says that you are supposed to understand the entire contents of a software project holistically, not needing to track individual files. Well, sadly, my small brain cannot do that.

It is really annoying that so many people have mindlessly repeated the statement that Git automatically tracks moves. They have wasted my time. Git does no such thing. By design(!) Git does not track moves at all.

My solution is to rename the files back to their original locations. Change the software to fit the source control. With Git you just seem to need to "git" it right the first time.

Unfortunately, that breaks Eclipse, which seems to use --follow. git log --follow sometimes does not show the full history of files with complicated rename histories even though git log does. (I do not know why.)

(There are some too clever hacks that go back and recommit old work, but they are rather frightening. See GitHub-Gist: emiller/git-mv-with-history.)

What's a concise way to check that environment variables are set in a Unix shell script?

Your question is dependent on the shell that you are using.

Bourne shell leaves very little in the way of what you're after.

BUT...

It does work, just about everywhere.

Just try and stay away from csh. It was good for the bells and whistles it added, compared the Bourne shell, but it is really creaking now. If you don't believe me, just try and separate out STDERR in csh! (-:

There are two possibilities here. The example above, namely using:

${MyVariable:=SomeDefault}

for the first time you need to refer to $MyVariable. This takes the env. var MyVariable and, if it is currently not set, assigns the value of SomeDefault to the variable for later use.

You also have the possibility of:

${MyVariable:-SomeDefault}

which just substitutes SomeDefault for the variable where you are using this construct. It doesn't assign the value SomeDefault to the variable, and the value of MyVariable will still be null after this statement is encountered.

How do I run a VBScript in 32-bit mode on a 64-bit machine?

We can force vbscript always run with 32 bit mode by changing "system32" to "sysWOW64" in default value of key "Computer\HKLM\SOFTWARE]\Classes\VBSFile\Shell\Open\Command"

How to change already compiled .class file without decompile?

As far as I've been able to find out, there is no simple way to do it. The easiest way is to not actually convert the class file into an executable, but to wrap an executable launcher around the class file. That is, create an executable file (perhaps an OS-based, executable scripting file) which simply invokes the Java class through the command line.

If you want to actually have a program that does it, you should look into some of the automated installers out there.

Here is a way I've found:

[code]
import java.io.*;
import java.util.jar.*;

class OnlyExt implements FilenameFilter{
String ext;
public OnlyExt(String ext){
this.ext="." + ext;
}

@Override
public boolean accept(File dir,String name){
return name.endsWith(ext);
}
}

public class ExeCreator {
public static int buffer = 10240;
protected void create(File exefile, File[] listFiles) {
try {
byte b[] = new byte[buffer];
FileOutputStream fout = new FileOutputStream(exefile);
JarOutputStream out = new JarOutputStream(fout, new Manifest());
for (int i = 0; i < listFiles.length; i++) {
if (listFiles[i] == null || !listFiles[i].exists()|| listFiles[i].isDirectory())
System.out.println("Adding " + listFiles[i].getName());
JarEntry addFiles = new JarEntry(listFiles[i].getName());
addFiles.setTime(listFiles[i].lastModified());
out.putNextEntry(addFiles);

FileInputStream fin = new FileInputStream(listFiles[i]);
while (true) {
int len = fin.read(b, 0, b.length);
if (len <= 0)
break;
out.write(b, 0, len);
}
fin.close();
}
out.close();
fout.close();
System.out.println("Jar File is created successfully.");
} catch (Exception ex) {}
}

public static void main(String[]args){
ExeCreator exe=new ExeCreator();
FilenameFilter ff = new OnlyExt("class");
File folder = new File("./examples");
File[] files = folder.listFiles(ff);
File file=new File("examples.exe");
exe.create(file, files);
}

}


[/code]`

What does the question mark operator mean in Ruby?

Also note ? along with a character, will return the ASCII character code for A

For example:

?F # => will return 70

Alternately in ruby 1.8 you can do:

"F"[0]

or in ruby 1.9:

"F".ord

Also notice that ?F will return the string "F", so in order to make the code shorter, you can also use ?F.ord in Ruby 1.9 to get the same result as "F".ord.

How to extend an existing JavaScript array with another array, without creating a new array

First a few words about apply() in JavaScript to help understand why we use it:

The apply() method calls a function with a given this value, and arguments provided as an array.

Push expects a list of items to add to the array. The apply() method, however, takes the expected arguments for the function call as an array. This allows us to easily push the elements of one array into another array with the builtin push() method.

Imagine you have these arrays:

var a = [1, 2, 3, 4];
var b = [5, 6, 7];

and simply do this:

Array.prototype.push.apply(a, b);

The result will be:

a = [1, 2, 3, 4, 5, 6, 7];

The same thing can be done in ES6 using the spread operator ("...") like this:

a.push(...b); //a = [1, 2, 3, 4, 5, 6, 7]; 

Shorter and better but not fully supported in all browsers at the moment.

Also if you want to move everything from array b to a, emptying b in the process, you can do this:

while(b.length) {
  a.push(b.shift());
} 

and the result will be as follows:

a = [1, 2, 3, 4, 5, 6, 7];
b = [];

Convert String into a Class Object

You can use the statement :-

Class c = s.getClass();

To get the class instance.

Visualizing branch topology in Git

On Windows there is a very useful tool you can use : git extensions. It's a gui tool and makes git operations very easy.

Also it's open sourced.

http://gitextensions.github.io

Sorting a tab delimited file

Lars Haugseth answer only worked from the command line for me where it gives this error if executed from a shell script:

sort: multi-character tab ‘$\t’

The solution if it's coded in a shell script if anyone's looking is

sort -t'    '

the tab character is in between the quote.

SQL Statement with multiple SETs and WHEREs

Use a query terminator string and set this in the options of your SQL client application. I use ; as the query terminator.

Your SQL would look like this;

UPDATE table SET ID = 111111259 WHERE ID = 2555;
UPDATE table SET ID = 111111261 WHERE ID = 2724;
UPDATE table SET ID = 111111263 WHERE ID = 2021;
UPDATE table SET ID = 111111264 WHERE ID = 2017;

This will allow you to do a Ctrl + A and run all the lines at once.

The string terminator tells the SQL client that the update statement is finished and to go to the next line and process the next statement.

Hope that helps

LINQ to SQL Left Outer Join

Take care of performance:

I experienced that at least with EF Core the different answers given here might result in different performance. I'm aware that the OP asked about Linq to SQL, but it seems to me that the same questions occur also with EF Core.

In a specific case I had to handle, the (syntactically nicer) suggestion by Marc Gravell resulted in left joins inside a cross apply -- similarly to what Mike U described -- which had the result that the estimated costs for this specific query were two times as high compared to a query with no cross joins. The server execution times differed by a factor of 3. [1]

The solution by Marc Gravell resulted in a query without cross joins.

Context: I essentially needed to perform two left joins on two tables each of which again required a join to another table. Furthermore, there I had to specify other where-conditions on the tables on which I needed to apply the left join. In addition, I had two inner joins on the main table.

Estimated operator costs:

  • with cross apply: 0.2534
  • without cross apply: 0.0991.

Server execution times in ms (queries executed 10 times; measured using SET STATISTICS TIME ON):

  • with cross apply: 5, 6, 6, 6, 6, 6, 6, 6, 6, 6
  • without cross apply: 2, 2, 2, 2, 2, 2, 2, 2, 2, 2

(The very first run was slower for both queries; seems that something is cached.)

Table sizes:

  • main table: 87 rows,
  • first table for left join: 179 rows;
  • second table for left join: 7 rows.

EF Core version: 2.2.1.

SQL Server version: MS SQL Server 2017 - 14... (on Windows 10).

All relevant tables had indexes on the primary keys only.

My conclusion: it's always recommended to look at the generated SQL since it can really differ.


[1] Interestingly enough, when setting the 'Client statistics' in MS SQL Server Management Studio on, I could see an opposite trend; namely that last run of the solution without cross apply took more than 1s. I suppose that something was going wrong here - maybe with my setup.

Run an Ansible task only when the variable contains a specific string

use this

when: "{{ 'value' in variable1}}"

instead of

when: "'value' in {{variable1}}"

Also for string comparison you can use

when: "{{ variable1 == 'value' }}"

PHP Date Format to Month Name and Year

You could use:

echo date('F Y', strtotime('20130814'));

which should do the trick.

Edit: You have a date which is in a string format. To be able to format it nicelt, you first need to change it into a date itself - which is where strtotime comes in. It is a fantastic feature that converts almost any plausible expression of a date into a date itself. Then we can actually use the date() function to format the output into what you want.

Adding calculated column(s) to a dataframe in pandas

For the second part of your question, you can also use shift, for example:

df['t-1'] = df['t'].shift(1)

t-1 would then contain the values from t one row above.

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html

How to write some data to excel file(.xlsx)

Try this code

Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
Microsoft.Office.Interop.Excel.Range oRng;
object misvalue = System.Reflection.Missing.Value;
try
{
    //Start Excel and get Application object.
    oXL = new Microsoft.Office.Interop.Excel.Application();
    oXL.Visible = true;

    //Get a new workbook.
    oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Add(""));
    oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;

    //Add table headers going cell by cell.
    oSheet.Cells[1, 1] = "First Name";
    oSheet.Cells[1, 2] = "Last Name";
    oSheet.Cells[1, 3] = "Full Name";
    oSheet.Cells[1, 4] = "Salary";

    //Format A1:D1 as bold, vertical alignment = center.
    oSheet.get_Range("A1", "D1").Font.Bold = true;
    oSheet.get_Range("A1", "D1").VerticalAlignment =
        Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;

    // Create an array to multiple values at once.
    string[,] saNames = new string[5, 2];

    saNames[0, 0] = "John";
    saNames[0, 1] = "Smith";
    saNames[1, 0] = "Tom";

    saNames[4, 1] = "Johnson";

    //Fill A2:B6 with an array of values (First and Last Names).
    oSheet.get_Range("A2", "B6").Value2 = saNames;

    //Fill C2:C6 with a relative formula (=A2 & " " & B2).
    oRng = oSheet.get_Range("C2", "C6");
    oRng.Formula = "=A2 & \" \" & B2";

    //Fill D2:D6 with a formula(=RAND()*100000) and apply format.
    oRng = oSheet.get_Range("D2", "D6");
    oRng.Formula = "=RAND()*100000";
    oRng.NumberFormat = "$0.00";

    //AutoFit columns A:D.
    oRng = oSheet.get_Range("A1", "D1");
    oRng.EntireColumn.AutoFit();

    oXL.Visible = false;
    oXL.UserControl = false;
    oWB.SaveAs("c:\\test\\test505.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing,
        false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);

    oWB.Close();
    oXL.Quit();

    //...

Padding between ActionBar's home icon and title

I used \t before the title and worked for me.

Invariant Violation: _registerComponent(...): Target container is not a DOM element

just a wild guess, how about adding to index.html the following:

type="javascript"

like this:

<script type="javascript" src="public/bundle.js"> </script>

For me it worked! :-)

How to get root directory in yii2

Try out this,

My installation is at D:\xampp\htdocs\advanced

\Yii::$app->basePath will give like D:\xampp\htdocs\advanced\backend.

\Yii::$app->request->BaseUrl will give like localhost\advanced\backend\web\

You may store the image using \Yii::$app->basePath and show it using \Yii::$app->request->BaseUrl

selenium get current url after loading a page

Page 2 is in a new tab/window ? If it's this, use the code bellow :

try {

    String winHandleBefore = driver.getWindowHandle();

    for(String winHandle : driver.getWindowHandles()){
        driver.switchTo().window(winHandle);
        String act = driver.getCurrentUrl();
    }
    }catch(Exception e){
   System.out.println("fail");
    }

How can I use Html.Action?

first, create a class to hold your parameters:

public class PkRk {
    public int pk { get; set; }
    public int rk { get; set; }
}

then, use the Html.Action passing the parameters:

Html.Action("PkRkAction", new { pkrk = new PkRk { pk=400, rk=500} })

and use in Controller:

public ActionResult PkRkAction(PkRk pkrk) {
    return PartialView(pkrk);
}

What does /p mean in set /p?

For future reference, you can get help for any command by using the /? switch, which should explain what switches do what.

According to the set /? screen, the format for set /p is SET /P variable=[promptString] which would indicate that the p in /p is "prompt." It just prints in your example because <nul passes in a nul character which immediately ends the prompt so it just acts like it's printing. It's still technically prompting for input, it's just immediately receiving it.

/L in for /L generates a List of numbers.

From ping /?:

Usage: ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS]
            [-r count] [-s count] [[-j host-list] | [-k host-list]]
            [-w timeout] [-R] [-S srcaddr] [-4] [-6] target_name

Options:
    -t             Ping the specified host until stopped.
                   To see statistics and continue - type Control-Break;
                   To stop - type Control-C.
    -a             Resolve addresses to hostnames.
    -n count       Number of echo requests to send.
    -l size        Send buffer size.
    -f             Set Don't Fragment flag in packet (IPv4-only).
    -i TTL         Time To Live.
    -v TOS         Type Of Service (IPv4-only. This setting has been deprecated
                   and has no effect on the type of service field in the IP Header).
    -r count       Record route for count hops (IPv4-only).
    -s count       Timestamp for count hops (IPv4-only).
    -j host-list   Loose source route along host-list (IPv4-only).
    -k host-list   Strict source route along host-list (IPv4-only).
    -w timeout     Timeout in milliseconds to wait for each reply.
    -R             Use routing header to test reverse route also (IPv6-only).
    -S srcaddr     Source address to use.
    -4             Force using IPv4.
    -6             Force using IPv6.

CardView not showing Shadow in Android L

use app:cardUseCompatPadding="true" inside your cardview. For Example

<android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginRight="@dimen/cardviewMarginRight"
        app:cardBackgroundColor="@color/menudetailsbgcolor"
        app:cardCornerRadius="@dimen/cardCornerRadius"
        app:cardUseCompatPadding="true"
        app:elevation="0dp">
    </android.support.v7.widget.CardView>

Print a list of space-separated elements in Python 3

You can apply the list as separate arguments:

print(*L)

and let print() take care of converting each element to a string. You can, as always, control the separator by setting the sep keyword argument:

>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5

Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join():

joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string

Note that this requires manual conversion to strings for any non-string values in L!

Stashing only staged changes in git - is it possible?

TL;DR Just add -- $(git diff --staged --name-only) for your git <pathspec> parameter

Here is a simple one-liner:

git stash -- $(git diff --staged --name-only)

And to add a message simply:

git stash push -m "My work in progress" -- $(git diff --staged --name-only)

Tested on v2.17.1 and v2.21.0.windows.1

Limitations:

  • Please be aware that this will stash every single thing, if you have no files staged.
  • Also if you have a file that is only partially staged ( i.e. only some changed lines, are staged while some other changed lines are not), then the whole file will get stashed (including unstaged lines).

How do I register a .NET DLL file in the GAC?

From the Publish tab go to application Files.

Then, click unnecessary files.

After that, do the exclude press ok.

Finally, build the project files and run the projects.

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

The issue for me was trying to sign the application with the app store distribution certificate. Switching the cert to the Xcode generated Team provisioning profile fixed the issue.

Import and Export Excel - What is the best library?

There's a pretty good article and library on CodeProject by Yogesh Jagota:

Excel XML Import-Export Library

I've used it to export data from SQL queries and other data sources to Excel - works just fine for me.

Cheers

Python update a key in dict if it doesn't exist

Use dict.setdefault():

>>> d = {1: 'one'}
>>> d.setdefault(1, '1')
'one'
>>> d    # d has not changed because the key already existed
{1: 'one'}
>>> d.setdefault(2, 'two')
'two'
>>> d
{1: 'one', 2: 'two'}

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

I think the docs explain the difference and usage of these two functions pretty well:

newFixedThreadPool

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue. At any point, at most nThreads threads will be active processing tasks. If additional tasks are submitted when all threads are active, they will wait in the queue until a thread is available. If any thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks. The threads in the pool will exist until it is explicitly shutdown.

newCachedThreadPool

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will be created and added to the pool. Threads that have not been used for sixty seconds are terminated and removed from the cache. Thus, a pool that remains idle for long enough will not consume any resources. Note that pools with similar properties but different details (for example, timeout parameters) may be created using ThreadPoolExecutor constructors.

In terms of resources, the newFixedThreadPool will keep all the threads running until they are explicitly terminated. In the newCachedThreadPool Threads that have not been used for sixty seconds are terminated and removed from the cache.

Given this, the resource consumption will depend very much in the situation. For instance, If you have a huge number of long running tasks I would suggest the FixedThreadPool. As for the CachedThreadPool, the docs say that "These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks".

Excel VBA Automation Error: The object invoked has disconnected from its clients

I have just met this problem today: I migrated my Excel project from Office 2007 to 2010. At a certain point, when my macro tried to Insert a new line (e.g. Range("5:5").Insert ), the same error message came. It happens only when previously another sheet has been edited (my macro switches to another sheet).

Thanks to Google, and your discussion, I found the following solution (based on the answer given by "red" at answered Jul 30 '13 at 0:27): after switching to the sheet a Cell has to be edited before inserting a new row. I have added the following code:

'=== Excel bugfix workaround - 2014.08.17
Range("B1").Activate
vCellValue = Range("B1").Value
Range("B1").ClearContents
Range("B1").Value = vCellValue

"B1" can be replaced by any cell on the sheet.

case statement in where clause - SQL Server

A CASE statement is an expression, just like a boolean comparison. That means the 'AND' needs to go before the 'CASE' statement, not within it.:

Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date)

AND -- Added the "AND" here

CASE WHEN @day = 'Monday' THEN (Monday = 1)   -- Removed "AND" 
    WHEN @day = 'Tuesday' THEN (Tuesday = 1)  -- Removed "AND" 
    ELSE AND (Wednesday = 1) 
END

Using 'make' on OS X

You will have to install the "Developer Tools" that are provided as optional packages in OS X installation disks.

How to implement and do OCR in a C# project?

If anyone is looking into this, I've been trying different options and the following approach yields very good results. The following are the steps to get a working example:

  1. Add .NET Wrapper for tesseract to your project. It can be added via NuGet package Install-Package Tesseract(https://github.com/charlesw/tesseract).
  2. Go to the Downloads section of the official Tesseract project (https://code.google.com/p/tesseract-ocr/ EDIT: It's now located here: https://github.com/tesseract-ocr/langdata).
  3. Download the preferred language data, example: tesseract-ocr-3.02.eng.tar.gz English language data for Tesseract 3.02.
  4. Create tessdata directory in your project and place the language data files in it.
  5. Go to Properties of the newly added files and set them to copy on build.
  6. Add a reference to System.Drawing.
  7. From .NET Wrapper repository, in the Samples directory copy the sample phototest.tif file into your project directory and set it to copy on build.
  8. Create the following two files in your project (just to get started):

Program.cs

using System;
using Tesseract;
using System.Diagnostics;

namespace ConsoleApplication
{
    class Program
    {
        public static void Main(string[] args)
        {
            var testImagePath = "./phototest.tif";
            if (args.Length > 0)
            {
                testImagePath = args[0];
            }

            try
            {
                var logger = new FormattedConsoleLogger();
                var resultPrinter = new ResultPrinter(logger);
                using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
                {
                    using (var img = Pix.LoadFromFile(testImagePath))
                    {
                        using (logger.Begin("Process image"))
                        {
                            var i = 1;
                            using (var page = engine.Process(img))
                            {
                                var text = page.GetText();
                                logger.Log("Text: {0}", text);
                                logger.Log("Mean confidence: {0}", page.GetMeanConfidence());

                                using (var iter = page.GetIterator())
                                {
                                    iter.Begin();
                                    do
                                    {
                                        if (i % 2 == 0)
                                        {
                                            using (logger.Begin("Line {0}", i))
                                            {
                                                do
                                                {
                                                    using (logger.Begin("Word Iteration"))
                                                    {
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Block))
                                                        {
                                                            logger.Log("New block");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Para))
                                                        {
                                                            logger.Log("New paragraph");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.TextLine))
                                                        {
                                                            logger.Log("New line");
                                                        }
                                                        logger.Log("word: " + iter.GetText(PageIteratorLevel.Word));
                                                    }
                                                } while (iter.Next(PageIteratorLevel.TextLine, PageIteratorLevel.Word));
                                            }
                                        }
                                        i++;
                                    } while (iter.Next(PageIteratorLevel.Para, PageIteratorLevel.TextLine));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                Console.WriteLine("Unexpected Error: " + e.Message);
                Console.WriteLine("Details: ");
                Console.WriteLine(e.ToString());
            }
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }



        private class ResultPrinter
        {
            readonly FormattedConsoleLogger logger;

            public ResultPrinter(FormattedConsoleLogger logger)
            {
                this.logger = logger;
            }

            public void Print(ResultIterator iter)
            {
                logger.Log("Is beginning of block: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Block));
                logger.Log("Is beginning of para: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Para));
                logger.Log("Is beginning of text line: {0}", iter.IsAtBeginningOf(PageIteratorLevel.TextLine));
                logger.Log("Is beginning of word: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Word));
                logger.Log("Is beginning of symbol: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Symbol));

                logger.Log("Block text: \"{0}\"", iter.GetText(PageIteratorLevel.Block));
                logger.Log("Para text: \"{0}\"", iter.GetText(PageIteratorLevel.Para));
                logger.Log("TextLine text: \"{0}\"", iter.GetText(PageIteratorLevel.TextLine));
                logger.Log("Word text: \"{0}\"", iter.GetText(PageIteratorLevel.Word));
                logger.Log("Symbol text: \"{0}\"", iter.GetText(PageIteratorLevel.Symbol));
            }
        }
    }
}

FormattedConsoleLogger.cs

using System;
using System.Collections.Generic;
using System.Text;
using Tesseract;

namespace ConsoleApplication
{
    public class FormattedConsoleLogger
    {
        const string Tab = "    ";
        private class Scope : DisposableBase
        {
            private int indentLevel;
            private string indent;
            private FormattedConsoleLogger container;

            public Scope(FormattedConsoleLogger container, int indentLevel)
            {
                this.container = container;
                this.indentLevel = indentLevel;
                StringBuilder indent = new StringBuilder();
                for (int i = 0; i < indentLevel; i++)
                {
                    indent.Append(Tab);
                }
                this.indent = indent.ToString();
            }

            public void Log(string format, object[] args)
            {
                var message = String.Format(format, args);
                StringBuilder indentedMessage = new StringBuilder(message.Length + indent.Length * 10);
                int i = 0;
                bool isNewLine = true;
                while (i < message.Length)
                {
                    if (message.Length > i && message[i] == '\r' && message[i + 1] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i += 2;
                    }
                    else if (message[i] == '\r' || message[i] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i++;
                    }
                    else
                    {
                        if (isNewLine)
                        {
                            indentedMessage.Append(indent);
                            isNewLine = false;
                        }
                        indentedMessage.Append(message[i]);
                        i++;
                    }
                }

                Console.WriteLine(indentedMessage.ToString());

            }

            public Scope Begin()
            {
                return new Scope(container, indentLevel + 1);
            }

            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    var scope = container.scopes.Pop();
                    if (scope != this)
                    {
                        throw new InvalidOperationException("Format scope removed out of order.");
                    }
                }
            }
        }

        private Stack<Scope> scopes = new Stack<Scope>();

        public IDisposable Begin(string title = "", params object[] args)
        {
            Log(title, args);
            Scope scope;
            if (scopes.Count == 0)
            {
                scope = new Scope(this, 1);
            }
            else
            {
                scope = ActiveScope.Begin();
            }
            scopes.Push(scope);
            return scope;
        }

        public void Log(string format, params object[] args)
        {
            if (scopes.Count > 0)
            {
                ActiveScope.Log(format, args);
            }
            else
            {
                Console.WriteLine(String.Format(format, args));
            }
        }

        private Scope ActiveScope
        {
            get
            {
                var top = scopes.Peek();
                if (top == null) throw new InvalidOperationException("No current scope");
                return top;
            }
        }
    }
}

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

<project>

    <!-- ... -->

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

How can I sort a std::map first by value, then by key?

You can use std::set instead of std::map.

You can store both key and value in std::pair and the type of container will look like this:

std::set< std::pair<int, std::string> > items;

std::set will sort it's values both by original keys and values that were stored in std::map.

jquery fill dropdown with json data

Here is an example of code, that attempts to featch AJAX data from /Ajax/_AjaxGetItemListHelp/ URL. Upon success, it removes all items from dropdown list with id = OfferTransModel_ItemID and then it fills it with new items based on AJAX call's result:

if (productgrpid != 0) {    
    $.ajax({
        type: "POST",
        url: "/Ajax/_AjaxGetItemListHelp/",
        data:{text:"sam",OfferTransModel_ItemGrpid:productgrpid},
        contentType: "application/json",              
        dataType: "json",
        success: function (data) {
            $("#OfferTransModel_ItemID").empty();

            $.each(data, function () {
                $("#OfferTransModel_ItemID").append($("<option>                                                      
                </option>").val(this['ITEMID']).html(this['ITEMDESC']));
            });
        }
    });
}

Returned AJAX result is expected to return data encoded as AJAX array, where each item contains ITEMID and ITEMDESC elements. For example:

{
    {
        "ITEMID":"13",
        "ITEMDESC":"About"
    },
    {
        "ITEMID":"21",
        "ITEMDESC":"Contact"
    }
}

The OfferTransModel_ItemID listbox is populated with above data and its code should look like:

<select id="OfferTransModel_ItemID" name="OfferTransModel[ItemID]">
    <option value="13">About</option>
    <option value="21">Contact</option>
</select>

When user selects About, form submits 13 as value for this field and 21 when user selects Contact and so on.

Fell free to modify above code if your server returns URL in a different format.

Get UserDetails object from Security Context in Spring MVC controller

You can use below code to find out principal (user email who logged in)

  org.opensaml.saml2.core.impl.NameIDImpl principal =  
  (NameIDImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

  String email = principal.getValue();

This code is written on top of SAML.

How do I obtain crash-data from my Android application?

Ok, well I looked at the provided samples from rrainn and Soonil, and I found a solution that does not mess up error handling.

I modified the CustomExceptionHandler so it stores the original UncaughtExceptionHandler from the Thread we associate the new one. At the end of the new "uncaughtException"- Method I just call the old function using the stored UncaughtExceptionHandler.

In the DefaultExceptionHandler class you need sth. like this:

public class DefaultExceptionHandler implements UncaughtExceptionHandler{
  private UncaughtExceptionHandler mDefaultExceptionHandler;

  //constructor
  public DefaultExceptionHandler(UncaughtExceptionHandler pDefaultExceptionHandler)
  {
       mDefaultExceptionHandler= pDefaultExceptionHandler;
  }
  public void uncaughtException(Thread t, Throwable e) {       
        //do some action like writing to file or upload somewhere         

        //call original handler  
        mStandardEH.uncaughtException(t, e);        

        // cleanup, don't know if really required
        t.getThreadGroup().destroy();
  }
}

With that modification on the code at http://code.google.com/p/android-remote-stacktrace you have a good working base for logging in the field to your webserver or to sd-card.

Javascript + Regex = Nothing to repeat error?

For Google travelers: this stupidly unhelpful error message is also presented when you make a type and double up the + regex operator:

Okay:

\w+

Not okay:

\w++

How to convert Double to int directly?

All other answer are correct, but remember that if you cast double to int you will loss decimal value.. so 2.9 double become 2 int.

You can use Math.round(double) function or simply do :

(int)(yourDoubleValue + 0.5d)

Cordova app not displaying correctly on iPhone X (Simulator)

For a manual fix to an existing cordova project

The black bars

Add this to your info.plist file. Fixing the launch image is a separate issue i.e. How to Add iPhoneX Launch Image

<key>UILaunchStoryboardName</key>
<string>CDVLaunchScreen</string>

The white bars

Set viewport-fit=cover in the meta tag

<meta name="viewport" content="initial-scale=1, width=device-width, height=device-height, viewport-fit=cover">

What's the difference between Perl's backticks, system, and exec?

In general I use system, open, IPC::Open2, or IPC::Open3 depending on what I want to do. The qx// operator, while simple, is too constraining in its functionality to be very useful outside of quick hacks. I find open to much handier.

system: run a command and wait for it to return

Use system when you want to run a command, don't care about its output, and don't want the Perl script to do anything until the command finishes.

#doesn't spawn a shell, arguments are passed as they are
system("command", "arg1", "arg2", "arg3");

or

#spawns a shell, arguments are interpreted by the shell, use only if you
#want the shell to do globbing (e.g. *.txt) for you or you want to redirect
#output
system("command arg1 arg2 arg3");

qx// or ``: run a command and capture its STDOUT

Use qx// when you want to run a command, capture what it writes to STDOUT, and don't want the Perl script to do anything until the command finishes.

#arguments are always processed by the shell

#in list context it returns the output as a list of lines
my @lines = qx/command arg1 arg2 arg3/;

#in scalar context it returns the output as one string
my $output = qx/command arg1 arg2 arg3/;

exec: replace the current process with another process.

Use exec along with fork when you want to run a command, don't care about its output, and don't want to wait for it to return. system is really just

sub my_system {
    die "could not fork\n" unless defined(my $pid = fork);
    return waitpid $pid, 0 if $pid; #parent waits for child
    exec @_; #replace child with new process
}

You may also want to read the waitpid and perlipc manuals.

open: run a process and create a pipe to its STDIN or STDERR

Use open when you want to write data to a process's STDIN or read data from a process's STDOUT (but not both at the same time).

#read from a gzip file as if it were a normal file
open my $read_fh, "-|", "gzip", "-d", $filename
    or die "could not open $filename: $!";

#write to a gzip compressed file as if were a normal file
open my $write_fh, "|-", "gzip", $filename
    or die "could not open $filename: $!";

IPC::Open2: run a process and create a pipe to both STDIN and STDOUT

Use IPC::Open2 when you need to read from and write to a process's STDIN and STDOUT.

use IPC::Open2;

open2 my $out, my $in, "/usr/bin/bc"
    or die "could not run bc";

print $in "5+6\n";

my $answer = <$out>;

IPC::Open3: run a process and create a pipe to STDIN, STDOUT, and STDERR

use IPC::Open3 when you need to capture all three standard file handles of the process. I would write an example, but it works mostly the same way IPC::Open2 does, but with a slightly different order to the arguments and a third file handle.

How to stop VMware port error of 443 on XAMPP Control Panel v3.2.1

Run XAMPP Control Panel as Administrator if using Windows 7 or more. Windows may block access to ports if not accessed by adminstrator user.

How do I make an editable DIV look like a text field?

I would suggest this for matching Chrome's style, extended from Jarish's example. Notice the cursor property which previous answers have omitted.

cursor: text;
border: 1px solid #ccc;
font: medium -moz-fixed;
font: -webkit-small-control;
height: 200px;
overflow: auto;
padding: 2px;
resize: both;
-moz-box-shadow: inset 0px 1px 2px #ccc;
-webkit-box-shadow: inset 0px 1px 2px #ccc;
box-shadow: inset 0px 1px 2px #ccc;

Null & empty string comparison in Bash

First of all, note you are not using the variable correctly:

if [ "pass_tc11" != "" ]; then
#     ^
#     missing $

Anyway, to check if a variable is empty or not you can use -z --> the string is empty:

if [ ! -z "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

or -n --> the length is non-zero:

if [ -n "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

From man test:

-z STRING

the length of STRING is zero

-n STRING

the length of STRING is nonzero

Samples:

$ [ ! -z "$var" ] && echo "yes"
$

$ var=""
$ [ ! -z "$var" ] && echo "yes"
$

$ var="a"
$ [ ! -z "$var" ] && echo "yes"
yes

$ var="a"
$ [ -n "$var" ] && echo "yes"
yes

INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE

Remove

<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE"/>
<permission
    android:name="${applicationId}.permission.C2D_MESSAGE"
    android:protectionLevel="signature"/>

Run App... Then Add the permisson again and Run App.

Ready!.

Using CookieContainer with WebClient class

I think there's cleaner way where you don't have to create a new webclient (and it'll work with 3rd party libraries as well)

internal static class MyWebRequestCreator
{
    private static IWebRequestCreate myCreator;

    public static IWebRequestCreate MyHttp
    {
        get
        {
            if (myCreator == null)
            {
                myCreator = new MyHttpRequestCreator();
            }
            return myCreator;
        }
    }

    private class MyHttpRequestCreator : IWebRequestCreate
    {
        public WebRequest Create(Uri uri)
        {
            var req = System.Net.WebRequest.CreateHttp(uri);
            req.CookieContainer = new CookieContainer();
            return req;
        }
    }
}

Now all you have to do is opt in for which domains you want to use this:

    WebRequest.RegisterPrefix("http://example.com/", MyWebRequestCreator.MyHttp);

That means ANY webrequest that goes to example.com will now use your custom webrequest creator, including the standard webclient. This approach means you don't have to touch all you code. You just call the register prefix once and be done with it. You can also register for "http" prefix to opt in for everything everywhere.

How to add to the end of lines containing a pattern with sed or awk?

Solution with awk:

awk '{if ($1 ~ /^all/) print $0, "anotherthing"; else print $0}' file

Simply: if the row starts with all print the row plus "anotherthing", else print just the row.

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

How to set javascript variables using MVC4 with Razor

I found a very clean solution that allows separate logic and GUI:

in your razor .cshtml page try this:

<body id="myId" data-my-variable="myValue">

...your page code here

</body>

in your .js file or .ts (if you use typeScript) to read stored value from your view put some like this (jquery library is required):

$("#myId").data("my-variable")

MySQL compare DATE string with string from DATETIME field

You can cast the DATETIME field into DATE as:

SELECT * FROM `calendar` WHERE CAST(startTime AS DATE) = '2010-04-29'

This is very much efficient.

Find out free space on tablespace

Here is a query used by Oracle SQL Developer in its Tablespaces view

select a.tablespace_name as "Tablespace Name",
       round(a.bytes_alloc / 1024 / 1024) "Allocated (MB)",
       round(nvl(b.bytes_free, 0) / 1024 / 1024) "Free (MB)",
       round((a.bytes_alloc - nvl(b.bytes_free, 0)) / 1024 / 1024) "Used (MB)",
       round((nvl(b.bytes_free, 0) / a.bytes_alloc) * 100) "% Free",
       100 - round((nvl(b.bytes_free, 0) / a.bytes_alloc) * 100) "% Used",
       round(maxbytes/1024 / 1024) "Max. Bytes (MB)"
from  ( select  f.tablespace_name,
               sum(f.bytes) bytes_alloc,
               sum(decode(f.autoextensible, 'YES',f.maxbytes,'NO', f.bytes)) maxbytes
        from dba_data_files f
        group by tablespace_name) a,
      ( select  f.tablespace_name,
               sum(f.bytes)  bytes_free
        from dba_free_space f
        group by tablespace_name) b
where a.tablespace_name = b.tablespace_name (+)
union all
select 
       h.tablespace_name as tablespace_name,
       round(sum(h.bytes_free + h.bytes_used) / 1048576) megs_alloc,
       round(sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / 1048576) megs_free,
       round(sum(nvl(p.bytes_used, 0))/ 1048576) megs_used,
       round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free)) * 100) Pct_Free,
       100 - round((sum((h.bytes_free + h.bytes_used) - nvl(p.bytes_used, 0)) / sum(h.bytes_used + h.bytes_free)) * 100) pct_used,
       round(sum(f.maxbytes) / 1048576) max
from   sys.v_$TEMP_SPACE_HEADER h, sys.v_$Temp_extent_pool p, dba_temp_files f
where  p.file_id(+) = h.file_id
and    p.tablespace_name(+) = h.tablespace_name
and    f.file_id = h.file_id
and    f.tablespace_name = h.tablespace_name
group by h.tablespace_name
ORDER BY 2;

Create a new txt file using VB.NET

You also might want to check if the file already exists to avoid replacing the file by accident (unless that is the idea of course:

Dim filepath as String = "C:\my files\2010\SomeFileName.txt"
If Not System.IO.File.Exists(filepath) Then
   System.IO.File.Create(filepath).Dispose()
End If

How to use timer in C?

Yes, you need a loop. If you already have a main loop (most GUI event-driven stuff does) you can probably stick your timer into that. Use:

#include <time.h> 
time_t my_t, fire_t;

Then (for times over 1 second), initialize your timer by reading the current time:

my_t = time(NULL);

Add the number of seconds your timer should wait and store it in fire_t. A time_t is essentially a uint32_t, you may need to cast it.

Inside your loop do another

my_t = time(NULL);

if (my_t > fire_t) then consider the timer fired and do the stuff you want there. That will probably include resetting it by doing another fire_t = time(NULL) + seconds_to_wait for next time.

A time_t is a somewhat antiquated unix method of storing time as the number of seconds since midnight 1/1/1970 but it has many advantages. For times less than 1 second you need to use gettimeofday() (microseconds) or clock_gettime() (nanoseconds) and deal with a struct timeval or struct timespec which is a time_t and the microseconds or nanoseconds since that 1 second mark. Making a timer works the same way except when you add your time to wait you need to remember to manually do the carry (into the time_t) if the resulting microseconds or nanoseconds value goes over 1 second. Yes, it's messy. See man 2 time, man gettimeofday, man clock_gettime.

sleep(), usleep(), nanosleep() have a hidden benefit. You see it as pausing your program, but what they really do is release the CPU for that amount of time. Repeatedly polling by reading the time and comparing to the done time (are we there yet?) will burn a lot of CPU cycles which may slow down other programs running on the same machine (and use more electricity/battery). It's better to sleep() most of the time then start checking the time.

If you're trying to sleep and do work at the same time you need threads.

What is the difference between --save and --save-dev?

  • --save-dev is used to save the package for development purpose. Example: unit tests, minification..
  • --save is used to save the package required for the application to run.

Stripping non printable characters from a string in python

Iterating over strings is unfortunately rather slow in Python. Regular expressions are over an order of magnitude faster for this kind of thing. You just have to build the character class yourself. The unicodedata module is quite helpful for this, especially the unicodedata.category() function. See Unicode Character Database for descriptions of the categories.

import unicodedata, re, itertools, sys

all_chars = (chr(i) for i in range(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(chr, itertools.chain(range(0x00,0x20), range(0x7f,0xa0))))

control_char_re = re.compile('[%s]' % re.escape(control_chars))

def remove_control_chars(s):
    return control_char_re.sub('', s)

For Python2

import unicodedata, re, sys

all_chars = (unichr(i) for i in xrange(sys.maxunicode))
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)
# or equivalently and much more efficiently
control_chars = ''.join(map(unichr, range(0x00,0x20) + range(0x7f,0xa0)))

control_char_re = re.compile('[%s]' % re.escape(control_chars))

def remove_control_chars(s):
    return control_char_re.sub('', s)

For some use-cases, additional categories (e.g. all from the control group might be preferable, although this might slow down the processing time and increase memory usage significantly. Number of characters per category:

  • Cc (control): 65
  • Cf (format): 161
  • Cs (surrogate): 2048
  • Co (private-use): 137468
  • Cn (unassigned): 836601

Edit Adding suggestions from the comments.

Multiple input in JOptionPane.showInputDialog

this is my solution

JTextField username = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
    "Username:", username,
    "Password:", password
};

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
    if (username.getText().equals("h") && password.getText().equals("h")) {
        System.out.println("Login successful");
    } else {
        System.out.println("login failed");
    }
} else {
    System.out.println("Login canceled");
}

How can I get the name of an html page in Javascript?

Try this

location.pathname.substring(location.pathname.lastIndexOf("/") + 1);

location.pathname gives the part (domain not included) of the page URL. To get only the filename you have to extract it using the substring method.

AngularJS open modal on button click

Hope this will help you .

Here is Html code:-

    <body>
    <div ng-controller="MyController" class="container">
      <h1>Modal example</h1>
      <button ng-click="open()" class="btn btn-primary">Test Modal</button>

      <modal title="Login form" visible="showModal">
        <form role="form">

        </form>
      </modal>
    </div>
</body>

AngularJs code:-

var mymodal = angular.module('mymodal', []);

mymodal.controller('MyController', function ($scope) {
    $scope.showModal = false;
    $scope.open = function(){
    $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ title }}</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
        scope.title = attrs.title;

        scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

Check this--jsfiddle

How to ignore whitespace in a regular expression subject string?

While the accepted answer is technically correct, a more practical approach, if possible, is to just strip whitespace out of both the regular expression and the search string.

If you want to search for "my cats", instead of:

myString.match(/m\s*y\s*c\s*a\*st\s*s\s*/g)

Just do:

myString.replace(/\s*/g,"").match(/mycats/g)

Warning: You can't automate this on the regular expression by just replacing all spaces with empty strings because they may occur in a negation or otherwise make your regular expression invalid.

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

At each point in these instructions, check to see if the problem is fixed. If so, great! Otherwise, continue.

  1. Get to Services. (I was able to right click the Apache launch icon to get there.)
  2. Scroll down to MySQL. Click to start. This will get rid of the #2002 error. Now you'll have a new error:

#1045 - Access denied for user 'root'@'localhost' (using password: NO)

  1. Edit the C:\wamp\apps\phpmyadmin3.5.1\config.inc.php file, changing $cfg['Servers'][$i]['extension'] = 'mysqli'; to instead be= 'mysql'
  2. Open Services again and Stop MySQL
  3. While in Services, Start wampmysqld

This is convoluted, I know, but that's what worked for me. Some posts may say you need a password in the config file, but you don't. Mine is still ""

Hope this helps.

TortoiseSVN icons overlay not showing after updating to Windows 10

I deleted all my onedrive keys, installed latest preview etc and finally realized that the icons were working all along for some explorer directory views and not others.

In other words, medium, large, extra large, and tiles, but not list or detail. Since I don't want to learn all about how that works, I am just viewing my work directories as tiles for now.

how to check if the input is a number or not in C?

Using fairly simple code:

int i;
int value;
int n;
char ch;

/* Skip i==0 because that will be the program name */
for (i=1; i<argc; i++) {
    n = sscanf(argv[i], "%d%c", &value, &ch);

    if (n != 1) {
        /* sscanf didn't find a number to convert, so it wasn't a number */
    }
    else {
        /* It was */
    }
}

How do I break out of a loop in Scala?

import scala.util.control._

object demo_brk_963 
{
   def main(args: Array[String]) 
   {
      var a = 0;
      var b = 0;
      val numList1 = List(1,2,3,4,5,6,7,8,9,10);
      val numList2 = List(11,12,13);

      val outer = new Breaks; //object for break
      val inner = new Breaks; //object for break

      outer.breakable // Outer Block
      {
         for( a <- numList1)
         {
            println( "Value of a: " + a);

            inner.breakable // Inner Block
            {
               for( b <- numList2)
               {
                  println( "Value of b: " + b);

                  if( b == 12 )
                  {
                      println( "break-INNER;");
                       inner.break;
                  }
               }
            } // inner breakable
            if( a == 6 )
            {
                println( "break-OUTER;");
                outer.break;
            }
         }
      } // outer breakable.
   }
}

Basic method to break the loop, using Breaks class. By declaring the loop as breakable.

How to set a JVM TimeZone Properly

You can pass the JVM this param

-Duser.timezone

For example

-Duser.timezone=Europe/Sofia

and this should do the trick. Setting the environment variable TZ also does the trick on Linux.

How to remove responsive features in Twitter Bootstrap 3?

Look at www.goo.gl/2SIOJj it is a work in progress but it may help you.

I use cookie to define if i want desktop or responsive version. In the footer of the page you can find two spans and in general.js is the script to handle the clicks.

        <div class="col-xs-6" style="text-align:center;"><span class="make_desktop">Desktop</span></div>
        <div class="col-xs-6" style="text-align:center;"><span class="make_responsive">Mobile</span></div>

function setMobDeskCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value + "; path=/";
    window.location.reload();
}

$(function() {
    $(".make_desktop").click(function() {
        setMobDeskCookie('deskmob', 1, 3650);
    });
    $(".make_responsive").click(function() {
        setMobDeskCookie('deskmob', 0, 3650);
    });
});`enter code here`

i ended up splitting all my custom css into two files i don't use bootstrap navigation but my own so that is majority of my custom styles, so it will not resolve your entire problem but it works for me

and i also created non-responsive.css that forces the grid to maintain the large screen version

in case u select mobile i would load / echo

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">  
<!-- Bootstrap core CSS and JS -->
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
        <script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>

and load these stylesheets
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style-responsive.css?modified=1402758346" />

in case you select desktop i would load /echo

<meta name="viewport" content="width=1024">    


        <!-- Bootstrap core CSS and JS -->
        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
        <link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
        <script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>

        <!-- Main CSS -->
        <link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/non-responsive.css?modified=1402758635" />

the non-responsive.css is the one that has overrides for bootstrap my concern is layout so there is not much in there, given that i handle the navigation in my own way so css for it and the other bits is in my other css files

please note that my setup does behave as desktop even on desktop browsers unlike some other solutions i have seen that will only ignore the viewport that seems to have wotked only on mobile devices for me

WPF C# button style

To solve your question definitely need to use the Style and Template for the Button. But how exactly does he look like? Decisions may be several. For example, Button are two texts to better define the relevant TextBlocks? Can be directly in the template, but then use the buttons will be limited, because the template can be only one ContentPresenter. I decided to do things differently, to identify one ContentPresenter with an icon in the form of a Path, and the content is set using the buttons on the side.

The style:

<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="#373737" />
    <Setter Property="Foreground" Value="White" />
    <Setter Property="FontSize" Value="15" />
    <Setter Property="SnapsToDevicePixels" Value="True" />

    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border CornerRadius="4" Background="{TemplateBinding Background}">
                    <Grid>
                        <Path x:Name="PathIcon" Width="15" Height="25" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z "/>
                        <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />                                
                    </Grid>
                </Border>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="#E59400" />
                        <Setter Property="Foreground" Value="White" />
                        <Setter TargetName="PathIcon" Property="Fill" Value="Black" />
                    </Trigger>

                    <Trigger Property="IsPressed" Value="True">
                        <Setter Property="Background" Value="OrangeRed" />
                        <Setter Property="Foreground" Value="White" />
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Sample of using:

<Button Width="200" Height="50" VerticalAlignment="Top" Margin="0,20,0,0" />
    <Button.Content>
        <StackPanel>
            <TextBlock Text="Watch Now" FontSize="20" />
            <TextBlock Text="Duration: 50m" FontSize="12" Foreground="Gainsboro" />
        </StackPanel>
    </Button.Content>
</Button>

Output

enter image description here

It is best to StackPanel determine the Resources and set the Button so:

<Window.Resources>
    <StackPanel x:Key="MyStackPanel">
        <TextBlock Name="MainContent" Text="Watch Now" FontSize="20" />
        <TextBlock Name="DurationValue" Text="Duration: 50m" FontSize="12" Foreground="Gainsboro" />
    </StackPanel>
</Window.Resources>

<Button Width="200" Height="50" Content="{StaticResource MyStackPanel}" VerticalAlignment="Top" Margin="0,20,0,0" />

The question remains with setting the value for TextBlock Duration, because this value must be dynamic. I implemented it using attached DependencyProperty. Set it to the window, like that:

<Window Name="MyWindow" local:MyDependencyClass.CurrentDuration="Duration: 50m" ... />

Using in TextBlock:

<TextBlock Name="DurationValue" Text="{Binding ElementName=MyWindow, Path=(local:MyDependencyClass.CurrentDuration)}" FontSize="12" Foreground="Gainsboro" />

In fact, there is no difference for anyone to determine the attached DependencyProperty, because it is the predominant feature.

Example of set value:

private void Button_Click(object sender, RoutedEventArgs e)
{
    MyDependencyClass.SetCurrentDuration(MyWindow, "Duration: 101m");
}

A complete listing of examples:

XAML

<Window x:Class="ButtonHelp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:ButtonHelp"
    Name="MyWindow"
    Title="MainWindow" Height="350" Width="525"
    WindowStartupLocation="CenterScreen"
    local:MyDependencyClass.CurrentDuration="Duration: 50m">

<Window.Resources>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="#373737" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="FontSize" Value="15" />
        <Setter Property="FontFamily" Value="./#Segoe UI" />
        <Setter Property="SnapsToDevicePixels" Value="True" />

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border CornerRadius="4" Background="{TemplateBinding Background}">
                        <Grid>
                            <Path x:Name="PathIcon" Width="15" Height="25" Stretch="Fill" Fill="#4C87B3" HorizontalAlignment="Left" Margin="17,0,0,0" Data="F1 M 30.0833,22.1667L 50.6665,37.6043L 50.6665,38.7918L 30.0833,53.8333L 30.0833,22.1667 Z "/>
                            <ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" />                                
                        </Grid>
                    </Border>

                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="#E59400" />
                            <Setter Property="Foreground" Value="White" />
                            <Setter TargetName="PathIcon" Property="Fill" Value="Black" />
                        </Trigger>

                        <Trigger Property="IsPressed" Value="True">
                            <Setter Property="Background" Value="OrangeRed" />
                            <Setter Property="Foreground" Value="White" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <StackPanel x:Key="MyStackPanel">
        <TextBlock Name="MainContent" Text="Watch Now" FontSize="20" />
        <TextBlock Name="DurationValue" Text="{Binding ElementName=MyWindow, Path=(local:MyDependencyClass.CurrentDuration)}" FontSize="12" Foreground="Gainsboro" />
    </StackPanel>
</Window.Resources>

<Grid>        
    <Button Width="200" Height="50" Content="{StaticResource MyStackPanel}" VerticalAlignment="Top" Margin="0,20,0,0" />

    <Button Content="Set some duration" Style="{x:Null}" Width="140" Height="30" VerticalAlignment="Top" HorizontalAlignment="Left" Click="Button_Click" />
</Grid>

Code behind

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

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        MyDependencyClass.SetCurrentDuration(MyWindow, "Duration: 101m");
    }
}

public class MyDependencyClass : DependencyObject
{
    public static readonly DependencyProperty CurrentDurationProperty;        

    public static void SetCurrentDuration(DependencyObject DepObject, string value)
    {
        DepObject.SetValue(CurrentDurationProperty, value);
    }

    public static string GetCurrentDuration(DependencyObject DepObject)
    {
        return (string)DepObject.GetValue(CurrentDurationProperty);
    }

    static MyDependencyClass()
    {
        PropertyMetadata MyPropertyMetadata = new PropertyMetadata("Duration: 0m");

        CurrentDurationProperty = DependencyProperty.RegisterAttached("CurrentDuration",
                                                            typeof(string),
                                                            typeof(MyDependencyClass),
                                                            MyPropertyMetadata);
    }
}

Simulate Keypress With jQuery

Another option:

$(el).trigger({type: 'keypress', which: 13, keyCode: 13});

http://api.jquery.com/trigger/

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

Have you tried Visual Assist X ? Sort of lights up the VS editor.

Fail to create Android virtual Device, "No system image installed for this Target"

If you use Android Studio .Open the SDK-Manager, checked "Show Package Details" you will find out "Android Wear ARM EABI v7a System Image" download it , success !

How to get a list of MySQL views?

 select * FROM information_schema.views\G; 

Bootstrap4 adding scrollbar to div

      <div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
        <strong>Column 0 </strong><br>
        <strong>Column 1</strong><br>
        <strong>Column 2</strong><br>
        <strong>Column 3</strong><br>
        <strong>Column 4</strong><br>
        <strong>Column 5</strong><br>
        <strong>Column 6</strong><br>
        <strong>Column 7</strong><br>
        <strong>Column 8</strong><br>
        <strong>Column 9</strong><br>
        <strong>Column 10</strong><br>
        <strong>Column 11</strong><br>
        <strong>Column 12</strong><br>
        <strong>Column 13</strong><br>
      </div>
    </div>

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

The HTTP Content-Type for .ogg should be application/ogg (video/ogg for .ogv) and for .mp4 it should be video/mp4. You can check using the Web Sniffer.

Change column type in pandas

Starting pandas 1.0.0, we have pandas.DataFrame.convert_dtypes. You can even control what types to convert!

In [40]: df = pd.DataFrame(
    ...:     {
    ...:         "a": pd.Series([1, 2, 3], dtype=np.dtype("int32")),
    ...:         "b": pd.Series(["x", "y", "z"], dtype=np.dtype("O")),
    ...:         "c": pd.Series([True, False, np.nan], dtype=np.dtype("O")),
    ...:         "d": pd.Series(["h", "i", np.nan], dtype=np.dtype("O")),
    ...:         "e": pd.Series([10, np.nan, 20], dtype=np.dtype("float")),
    ...:         "f": pd.Series([np.nan, 100.5, 200], dtype=np.dtype("float")),
    ...:     }
    ...: )

In [41]: dff = df.copy()

In [42]: df 
Out[42]: 
   a  b      c    d     e      f
0  1  x   True    h  10.0    NaN
1  2  y  False    i   NaN  100.5
2  3  z    NaN  NaN  20.0  200.0

In [43]: df.dtypes
Out[43]: 
a      int32
b     object
c     object
d     object
e    float64
f    float64
dtype: object

In [44]: df = df.convert_dtypes()

In [45]: df.dtypes
Out[45]: 
a      Int32
b     string
c    boolean
d     string
e      Int64
f    float64
dtype: object

In [46]: dff = dff.convert_dtypes(convert_boolean = False)

In [47]: dff.dtypes
Out[47]: 
a      Int32
b     string
c     object
d     string
e      Int64
f    float64
dtype: object

SQL query for getting data for last 3 months

Latest Versions of mysql don't support DATEADD instead use the syntax

DATE_ADD(date,INTERVAL expr type)

To get the last 3 months data use,

DATE_ADD(NOW(),INTERVAL -90 DAY) 
DATE_ADD(NOW(), INTERVAL -3 MONTH)

css padding is not working in outlook

In some cases we set border instead of padding and it works in outlook.

border: solid #efeeee;border-width: 20px 40px;

Format numbers in JavaScript similar to C#

You can do it in the following way: So you will not only format the number but you can also pass as a parameter how many decimal digits to display, you set a custom decimal and mile separator.

function format(number, decimals = 2, decimalSeparator = '.', thousandsSeparator = ',') {
    const roundedNumber = number.toFixed(decimals);
    let integerPart = '', fractionalPart = '';
    if (decimals == 0) {
        integerPart = roundedNumber;
        decimalSeparator = '';
    } else {
        let numberParts = roundedNumber.split('.');
        integerPart = numberParts[0];
        fractionalPart = numberParts[1];
    }
    integerPart = integerPart.replace(/(\d)(?=(\d{3})+(?!\d))/g, `$1${thousandsSeparator}`);
    return `${integerPart}${decimalSeparator}${fractionalPart}`;
}

Use:

let min = 1556454.0001;
let max = 15556982.9999;
console.time('number format');
for (let i = 0; i < 15000; i++) {
    let randomNumber = Math.random() * (max - min) + min;

    let formated = format(randomNumber, 4, ',', '.'); // formated number

    console.debug('number: ', randomNumber, 'formated: ', formated);
}
console.timeEnd('number format');

Jquery get form field value

You can get any input field value by $('input[fieldAttribute=value]').val()

here is an example

_x000D_
_x000D_
displayValue = () => {_x000D_
_x000D_
  // you can get the value by name attribute like this_x000D_
  _x000D_
  console.log('value of firstname : ' + $('input[name=firstName]').val());_x000D_
  _x000D_
  // if there is the id as lastname_x000D_
  _x000D_
  console.log('value of lastname by id : ' + $('#lastName').val());_x000D_
  _x000D_
  // get value of carType from placeholder  _x000D_
  console.log('value of carType from placeholder ' + $('input[placeholder=carType]').val());_x000D_
_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="formdiv">_x000D_
    <form name="inpForm">_x000D_
        <input type="text" name="firstName" placeholder='first name'/>_x000D_
        <input type="text" name="lastName" id='lastName' placeholder='last name'/>_x000D_
        _x000D_
        <input type="text" placeholder="carType" />_x000D_
        <input type="button" value="display value" onclick='displayValue()'/>_x000D_
        _x000D_
    </form>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Redirect using AngularJS

Assuming you're not using html5 routing, try $location.path("route"). This will redirect your browser to #/route which might be what you want.

how can I enable scrollbars on the WPF Datagrid?

WPF4

<DataGrid AutoGenerateColumns="True" Grid.Column="0" Grid.Row="0"
      ScrollViewer.CanContentScroll="True" 
      ScrollViewer.VerticalScrollBarVisibility="Auto"
      ScrollViewer.HorizontalScrollBarVisibility="Auto">
</DataGrid>

with : <ColumnDefinition Width="350" /> & <RowDefinition Height="300" /> works fine.

Scrollbars don't show with <ColumnDefinition Width="Auto" /> & <RowDefinition Height="300" />.

Also works fine with: <ColumnDefinition Width="*" /> & <RowDefinition Height="300" /> in the case where this is nested within an outer <Grid>.

Converting to upper and lower case in Java

WordUtils.capitalizeFully(str) from apache commons-lang has the exact semantics as required.

Check synchronously if file/directory exists in Node.js

The path module does not provide a synchronous version of path.exists so you have to trick around with the fs module.

Fastest thing I can imagine is using fs.realpathSync which will throw an error that you have to catch, so you need to make your own wrapper function with a try/catch.

How to read a text-file resource into Java unit test?

First make sure that abc.xml is being copied to your output directory. Then you should use getResourceAsStream():

InputStream inputStream = 
    Thread.currentThread().getContextClassLoader().getResourceAsStream("test/resources/abc.xml");

Once you have the InputStream, you just need to convert it into a string. This resource spells it out: http://www.kodejava.org/examples/266.html. However, I'll excerpt the relevent code:

public String convertStreamToString(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(
                    new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {        
        return "";
    }
}

Cancel a UIView animation?

The way I do it is to create a new animation to your end point. Set a very short duration and make sure you use the +setAnimationBeginsFromCurrentState: method to start from the current state. When you set it to YES, the current animation is cut short. Looks something like this:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationBeginsFromCurrentState:YES];
[UIView setAnimationDuration:0.1];
[UIView setAnimationCurve: UIViewAnimationCurveLinear];
// other animation properties

// set view properties

[UIView commitAnimations];

Progress Bar with HTML and CSS

In modern browsers you could use a CSS3 & HTML5 progress Element!

_x000D_
_x000D_
progress {_x000D_
  width: 40%;_x000D_
  display: block; /* default: inline-block */_x000D_
  margin: 2em auto;_x000D_
  padding: 3px;_x000D_
  border: 0 none;_x000D_
  background: #444;_x000D_
  border-radius: 14px;_x000D_
}_x000D_
progress::-moz-progress-bar {_x000D_
  border-radius: 12px;_x000D_
  background: orange;_x000D_
_x000D_
}_x000D_
/* webkit */_x000D_
@media screen and (-webkit-min-device-pixel-ratio:0) {_x000D_
  progress {_x000D_
    height: 25px;_x000D_
  }_x000D_
}_x000D_
progress::-webkit-progress-bar {_x000D_
    background: transparent;_x000D_
}  _x000D_
progress::-webkit-progress-value {  _x000D_
  border-radius: 12px;_x000D_
  background: orange;_x000D_
} 
_x000D_
<progress max="100" value="40"></progress>
_x000D_
_x000D_
_x000D_

No server in Eclipse; trying to install Tomcat

For future poeple who have the same problem: Try to add server tab from eclipse menu, if it doesnt work, then go do @Tomasz Bartnik solution above, and retry the following again:

  1. Go to WIndow > Show view > Other

    enter image description here

  2. search for servers, select it and press OK

    enter image description here

It will then be added to your tabs