Programs & Examples On #Radwindow

RadWindow is Telerik component for creating Child and Dialog Windows and customize their appearance and content.

How can I style the border and title bar of a window in WPF?

I suggest you to start from an existing solution and customize it to fit your needs, that's better than starting from scratch!

I was looking for the same thing and I fall on this open source solution, I hope it will help.

Differences between MySQL and SQL Server

Frankly, I can't find a single reason to use MySQL rather than MSSQL. The issue before used to be cost but SQL Server 2005 Express is free and there are lots of web hosting companies which offer full hosting with sql server for less than $5.00 a month.

MSSQL is easier to use and has many features which do not exist in MySQL.

How do I find the install time and date of Windows?

Determine the Windows Installation Date with WMIC

wmic os get installdate

OS specific instructions in CMAKE: How to?

Generator expressions are also possible:

target_link_libraries(
    target_name
    PUBLIC
        libA
        $<$<PLATFORM_ID:Windows>:wsock32>
    PRIVATE
        $<$<PLATFORM_ID:Linux>:libB>
        libC
)

This will link libA, wsock32 & libC on Windows and link libA, libB & libC on Linux

CMake Generator Expressions

How to clear browsing history using JavaScript?

As MDN Window.history() describes :

For top-level pages you can see the list of pages in the session history, accessible via the History object, in the browser's dropdowns next to the back and forward buttons.

For security reasons the History object doesn't allow the non-privileged code to access the URLs of other pages in the session history, but it does allow it to navigate the session history.

There is no way to clear the session history or to disable the back/forward navigation from unprivileged code. The closest available solution is the location.replace() method, which replaces the current item of the session history with the provided URL.

So there is no Javascript method to clear the session history, instead, if you want to block navigating back to a certain page, you can use the location.replace() method, and pass the page link as parameter, which will not push the page to the browser's session history list. For example, there are three pages:

a.html:

<!doctype html>
<html>
    <head>
        <title>a.html page</title>
    <meta charset="utf-8">
    </head>
    <body>
         <p>This is <code style="color:red">a.html</code> page ! Go to <a href="b.html">b.html</a> page !</p>        
    </body>
 </html>

b.html:

<!doctype html>
<html>
    <head>
    <title>b.html page</title>
    <meta charset="utf-8">
</head>
<body>
    <p>This is <code style="color:red">b.html</code> page ! Go to <a id="jumper" href="c.html">c.html</a> page !</p>

    <script type="text/javascript">
        var jumper = document.getElementById("jumper");
        jumper.onclick = function(event) {
            var e = event || window.event ;
            if(e.preventDefault) {
                e.preventDefault();
            } else {
                e.returnValue = true ;
            }
            location.replace(this.href);
            jumper = null;
        }
    </script>
</body>

c.html:

<!doctype html>
<html>
<head>
    <title>c.html page</title>
    <meta charset="utf-8">
</head>
<body>
    <p>This is <code style="color:red">c.html</code> page</p>
</body>
</html>

With href link, we can navigate from a.html to b.html to c.html. In b.html, we use the location.replace(c.html) method to navigate from b.html to c.html. Finally, we go to c.html*, and if we click the back button in the browser, we will jump to **a.html.

So this is it! Hope it helps.

Package php5 have no installation candidate (Ubuntu 16.04)

sudo apt-get install php7.0-mysql

for php7.0 works well for me

Volatile Vs Atomic

Volatile and Atomic are two different concepts. Volatile ensures, that a certain, expected (memory) state is true across different threads, while Atomics ensure that operation on variables are performed atomically.

Take the following example of two threads in Java:

Thread A:

value = 1;
done = true;

Thread B:

if (done)
  System.out.println(value);

Starting with value = 0 and done = false the rule of threading tells us, that it is undefined whether or not Thread B will print value. Furthermore value is undefined at that point as well! To explain this you need to know a bit about Java memory management (which can be complex), in short: Threads may create local copies of variables, and the JVM can reorder code to optimize it, therefore there is no guarantee that the above code is run in exactly that order. Setting done to true and then setting value to 1 could be a possible outcome of the JIT optimizations.

volatile only ensures, that at the moment of access of such a variable, the new value will be immediately visible to all other threads and the order of execution ensures, that the code is at the state you would expect it to be. So in case of the code above, defining done as volatile will ensure that whenever Thread B checks the variable, it is either false, or true, and if it is true, then value has been set to 1 as well.

As a side-effect of volatile, the value of such a variable is set thread-wide atomically (at a very minor cost of execution speed). This is however only important on 32-bit systems that i.E. use long (64-bit) variables (or similar), in most other cases setting/reading a variable is atomic anyways. But there is an important difference between an atomic access and an atomic operation. Volatile only ensures that the access is atomically, while Atomics ensure that the operation is atomically.

Take the following example:

i = i + 1;

No matter how you define i, a different Thread reading the value just when the above line is executed might get i, or i + 1, because the operation is not atomically. If the other thread sets i to a different value, in worst case i could be set back to whatever it was before by thread A, because it was just in the middle of calculating i + 1 based on the old value, and then set i again to that old value + 1. Explanation:

Assume i = 0
Thread A reads i, calculates i+1, which is 1
Thread B sets i to 1000 and returns
Thread A now sets i to the result of the operation, which is i = 1

Atomics like AtomicInteger ensure, that such operations happen atomically. So the above issue cannot happen, i would either be 1000 or 1001 once both threads are finished.

How to get Map data using JDBCTemplate.queryForMap

To add to @BrianBeech's answer, this is even more trimmed down in java 8:

jdbcTemplate.query("select string1,string2 from table where x=1", (ResultSet rs) -> {
    HashMap<String,String> results = new HashMap<>();
    while (rs.next()) {
        results.put(rs.getString("string1"), rs.getString("string2"));
    }
    return results;
});

VarBinary vs Image SQL Server Data Type to Store Binary Data?

There is also the rather spiffy FileStream, introduced in SQL Server 2008.

Touch move getting stuck Ignored attempt to cancel a touchmove

The event must be cancelable. Adding an if statement solves this issue.

if (e.cancelable) {
   e.preventDefault();
}

In your code you should put it here:

if (this.isSwipe(swipeThreshold) && e.cancelable) {
   e.preventDefault();
   e.stopPropagation();
   swiping = true;
}

String comparison in Python: is vs. ==

The logic is not flawed. The statement

if x is y then x==y is also True

should never be read to mean

if x==y then x is y

It is a logical error on the part of the reader to assume that the converse of a logic statement is true. See http://en.wikipedia.org/wiki/Converse_(logic)

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

With the GnuWin32 tools I found the openssl.cnf under C:\gnuwin32\share

set OPENSSL_CONF=C:\gnuwin32\share\openssl.cnf

How to add \newpage in Rmarkdown in a smart way?

Simply \newpage or \pagebreak will work, e.g.

hello world
\newpage
```{r, echo=FALSE}
1+1
```
\pagebreak
```{r, echo=FALSE}
plot(1:10)
```

This solution assumes you are knitting PDF. For HTML, you can achieve a similar effect by adding a tag <P style="page-break-before: always">. Note that you likely won't see a page break in your browser (HTMLs don't have pages per se), but the printing layout will have it.

error: member access into incomplete type : forward declaration of

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

class B;

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

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

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

Vim for Windows - What do I type to save and exit from a file?

A faster way to

  • Save
  • and quit

would be

:x

If you have opened multiple files you may need to do a

:xa

C++ vector of char array

Use std::string instead of char-arrays

std::string k ="abcde";
std::vector<std::string> v;
v.push_back(k);

Color text in terminal applications in UNIX

Different solution that I find more elegant

Here's another way to do it. Some people will prefer this as the code is a bit cleaner. There are no %s and a RESET color to end the coloration.

#include <stdio.h>

#define RED   "\x1B[31m"
#define GRN   "\x1B[32m"
#define YEL   "\x1B[33m"
#define BLU   "\x1B[34m"
#define MAG   "\x1B[35m"
#define CYN   "\x1B[36m"
#define WHT   "\x1B[37m"
#define RESET "\x1B[0m"

int main() {
  printf(RED "red\n"     RESET);
  printf(GRN "green\n"   RESET);
  printf(YEL "yellow\n"  RESET);
  printf(BLU "blue\n"    RESET);
  printf(MAG "magenta\n" RESET);
  printf(CYN "cyan\n"    RESET);
  printf(WHT "white\n"   RESET);

  return 0;
}

This program gives the following output:

enter image description here


Simple example with multiple colors

This way, it's easy to do something like:

printf("This is " RED "red" RESET " and this is " BLU "blue" RESET "\n");

This line produces the following output:

execution's output

What are the differences between the BLOB and TEXT datatypes in MySQL?

According to High-performance Mysql book:

The only difference between the BLOB and TEXT families is that BLOB types store binary data with no collation or character set, but TEXT types have a character set and collation.

Accessing items in an collections.OrderedDict by index

It's a new era and with Python 3.6.1 dictionaries now retain their order. These semantics aren't explicit because that would require BDFL approval. But Raymond Hettinger is the next best thing (and funnier) and he makes a pretty strong case that dictionaries will be ordered for a very long time.

So now it's easy to create slices of a dictionary:

test_dict = {
                'first':  1,
                'second': 2,
                'third':  3,
                'fourth': 4
            }

list(test_dict.items())[:2]

Note: Dictonary insertion-order preservation is now official in Python 3.7.

Split by comma and strip whitespace in Python

import re
result=[x for x in re.split(',| ',your_string) if x!='']

this works fine for me.

How to undo a SQL Server UPDATE query?

If you can catch this in time and you don't have the ability to ROLLBACK or use the transaction log, you can take a backup immediately and use a tool like Redgate's SQL Data Compare to generate a script to "restore" the affected data. This worked like a charm for me. :)

How do I do a multi-line string in node.js?

What exactly are you looking for when you mean multiline strings.

Are you looking for something like:

var str = "Some \
    String \
    Here";

Which would print as "Some String Here"?

If so, keep in mind that the above is valid Javascript, but this isn't:

var str = "Some \ 
    String \
    Here";

What's the difference? A space after the \. Have fun debugging that.

Has anyone ever got a remote JMX JConsole to work?

PROTIP:

The RMI port are opened at arbitrary portnr's. If you have a firewall and don't want to open ports 1024-65535 (or use vpn) then you need to do the following.

You need to fix (as in having a known number) the RMI Registry and JMX/RMI Server ports. You do this by putting a jar-file (catalina-jmx-remote.jar it's in the extra's) in the lib-dir and configuring a special listener under server:

<Listener className="org.apache.catalina.mbeans.JmxRemoteLifecycleListener"
      rmiRegistryPortPlatform="10001" rmiServerPortPlatform="10002" />

(And ofcourse the usual flags for activating JMX

    -Dcom.sun.management.jmxremote  \
    -Dcom.sun.management.jmxremote.ssl=false \
    -Dcom.sun.management.jmxremote.authenticate=false \
    -Djava.rmi.server.hostname=<HOSTNAME> \

See: JMX Remote Lifecycle Listener at http://tomcat.apache.org/tomcat-6.0-doc/config/listeners.html

Then you can connect using this horrific URL:

service:jmx:rmi://<hostname>:10002/jndi/rmi://<hostname>:10001/jmxrmi

Named parameters in JDBC

To avoid including a large framework, I think a simple homemade class can do the trick.

Example of class to handle named parameters:

public class NamedParamStatement {
    public NamedParamStatement(Connection conn, String sql) throws SQLException {
        int pos;
        while((pos = sql.indexOf(":")) != -1) {
            int end = sql.substring(pos).indexOf(" ");
            if (end == -1)
                end = sql.length();
            else
                end += pos;
            fields.add(sql.substring(pos+1,end));
            sql = sql.substring(0, pos) + "?" + sql.substring(end);
        }       
        prepStmt = conn.prepareStatement(sql);
    }

    public PreparedStatement getPreparedStatement() {
        return prepStmt;
    }
    public ResultSet executeQuery() throws SQLException {
        return prepStmt.executeQuery();
    }
    public void close() throws SQLException {
        prepStmt.close();
    }

    public void setInt(String name, int value) throws SQLException {        
        prepStmt.setInt(getIndex(name), value);
    }

    private int getIndex(String name) {
        return fields.indexOf(name)+1;
    }
    private PreparedStatement prepStmt;
    private List<String> fields = new ArrayList<String>();
}

Example of calling the class:

String sql;
sql = "SELECT id, Name, Age, TS FROM TestTable WHERE Age < :age OR id = :id";
NamedParamStatement stmt = new NamedParamStatement(conn, sql);
stmt.setInt("age", 35);
stmt.setInt("id", 2);
ResultSet rs = stmt.executeQuery();

Please note that the above simple example does not handle using named parameter twice. Nor does it handle using the : sign inside quotes.

Create an ArrayList with multiple object types?

You could create a List<Object>, but you really don't want to do this. Mixed lists that abstract to Object are not very useful and are a potential source of bugs. In fact the fact that your code requires such a construct gives your code a bad code smell and suggests that its design may be off. Consider redesigning your program so you aren't forced to collect oranges with orangutans.

Instead -- do what G V recommends and I was about to recommend, create a custom class that holds both int and String and create an ArrayList of it. 1+ to his answer!

How to include file in a bash shell script

Simply put inside your script :

source FILE

Or

. FILE # POSIX compliant

$ LANG=C help source
source: source filename [arguments]
Execute commands from a file in the current shell.

Read and execute commands from FILENAME in the current shell.  The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.

Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.

Regular expression to limit number of characters to 10

grep '^[0-9]\{1,16\}' | wc -l

Gives the counts with exact match count with limit

Javascript - check array for value

This should do it:

for (var i = 0; i < bank_holidays.length; i++) {
    if (bank_holidays[i] === '06/04/2012') {
        alert('LOL');
    }
}

jsFiddle

How to view the Folder and Files in GAC?

You install as assemblies by using:

  • A setup program, that you author for your application.
  • Using the gacutil.exe tool with the -i option from the command line.
  • Dropping the assembly in %windir%\Assembly (only up to .NET 3.5, CLR 2.0)

You view the content of the GAC using:

  • The gacutil.exe tool with the -l option.
  • For .NET 2.0, 3.0 and 3.5 (CLR 2.0) browsing to %windir%\assembly using the Windows Explorer.

Note that the (physical) GAC location has changed for .NET 4.0. It is no longer in %windir%\Assembly, but now in %windir%\Microsoft.NET\assembly. However, you should never write any code that depends on the physical location anyway, because given the tools available that is hardly necessary (some "cool" homegrown system diagnostics tools aside).

How to 'insert if not exists' in MySQL?

on duplicate key update, or insert ignore can be viable solutions with MySQL.


Example of on duplicate key update update based on mysql.com

INSERT INTO table (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

UPDATE table SET c=c+1 WHERE a=1;

Example of insert ignore based on mysql.com

INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name [(col_name,...)]
    {VALUES | VALUE} ({expr | DEFAULT},...),(...),...
    [ ON DUPLICATE KEY UPDATE
      col_name=expr
        [, col_name=expr] ... ]

Or:

INSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name
    SET col_name={expr | DEFAULT}, ...
    [ ON DUPLICATE KEY UPDATE
      col_name=expr
        [, col_name=expr] ... ]

Or:

INSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]
    [INTO] tbl_name [(col_name,...)]
    SELECT ...
    [ ON DUPLICATE KEY UPDATE
      col_name=expr
        [, col_name=expr] ... ]

How can I verify if a Windows Service is running

Here you get all available services and their status in your local machine.

ServiceController[] services = ServiceController.GetServices();
foreach(ServiceController service in services)
{
    Console.WriteLine(service.ServiceName+"=="+ service.Status);
}

You can Compare your service with service.name property inside loop and you get status of your service. For details go with the http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx also http://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx

Checking Value of Radio Button Group via JavaScript?

If you wrap your form elements in a form tag with a name attribute you can easily get the value using document.formName.radioGroupName.value.

<form name="myForm">
    <input type="radio" id="genderm" name="gender" value="male" />
    <label for="genderm">Male</label>
    <input type="radio" id="genderf" name="gender" value="female" />
    <label for="genderf">Female</label>
</form>

<script>
    var selected = document.forms.myForm.gender.value;
</script>

How do I change tab size in Vim?

As a one-liner into vim:

:set tabstop=4 shiftwidth=4

For permanent setup, add these lines to ~/.vimrc:

set tabstop=4
set shiftwidth=4

NOTE: Add set expandtab if you prefer 4-spaces indentation, instead of a tab indentation.

Convert a hexadecimal string to an integer efficiently in C?

Edit: Now compatible with MSVC, C++ and non-GNU compilers (see end).

The question was "most efficient way." The OP doesn't specify platform, he could be compiling for a RISC based ATMEL chip with 256 bytes of flash storage for his code.

For the record, and for those (like me), who appreciate the difference between "the easiest way" and the "most efficient way", and who enjoy learning...

static const long hextable[] = {
   [0 ... 255] = -1, // bit aligned access into this table is considerably
   ['0'] = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, // faster for most modern processors,
   ['A'] = 10, 11, 12, 13, 14, 15,       // for the space conscious, reduce to
   ['a'] = 10, 11, 12, 13, 14, 15        // signed char.
};

/** 
 * @brief convert a hexidecimal string to a signed long
 * will not produce or process negative numbers except 
 * to signal error.
 * 
 * @param hex without decoration, case insensitive. 
 * 
 * @return -1 on error, or result (max (sizeof(long)*8)-1 bits)
 */
long hexdec(unsigned const char *hex) {
   long ret = 0; 
   while (*hex && ret >= 0) {
      ret = (ret << 4) | hextable[*hex++];
   }
   return ret; 
}

It requires no external libraries, and it should be blindingly fast. It handles uppercase, lowercase, invalid characters, odd-sized hex input (eg: 0xfff), and the maximum size is limited only by the compiler.

For non-GCC or C++ compilers or compilers that will not accept the fancy hextable declaration.

Replace the first statement with this (longer, but more conforming) version:

static const long hextable[] = { 
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1, 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,-1,10,11,12,13,14,15,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
    -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
};

Show Current Location and Update Location in MKMapView in Swift

For Swift 2, you should change it to the following:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations.last

    let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
    let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))

    self.map.setRegion(region, animated: true)
}

How do I create a batch file timer to execute / call another batch throughout the day

For the timer part of your script i highly reccomend using:

echo.
echo Waiting For One Hour... 
TIMEOUT /T 3600 /NOBREAK
echo.
echo (Put some Other Processes Here)
echo.
pause >nul

This script waits for 1 hour (3600 seconds) and then continues on with the script and the user cannot press any buttons to bypass the timer (besides CTRL+C).

You can use

Timeout /t 3600 /nobreak >nul

If you don't want to see a countdown on the screen.

Multi-dimensional arrays in Bash

Bash does not supports multidimensional array, but we can implement using Associate array. Here the indexes are the key to retrieve the value. Associate array is available in bash version 4.

#!/bin/bash

declare -A arr2d
rows=3
columns=2

for ((i=0;i<rows;i++)) do
    for ((j=0;j<columns;j++)) do
        arr2d[$i,$j]=$i
    done
done


for ((i=0;i<rows;i++)) do
    for ((j=0;j<columns;j++)) do
        echo ${arr2d[$i,$j]}
    done
done

Import Excel Data into PostgreSQL 9.3

You can handle loading the excel file content by writing Java code using Apache POI library (https://poi.apache.org/). The library is developed for working with MS office application data including Excel.

I have recently created the application based on the technology that will help you to load Excel files to the Postgres database. The application is available under http://www.abespalov.com/. The application is tested only for Windows, but should work for Linux as well.

The application automatically creates necessary tables with the same columns as in the Excel files and populate the tables with content. You can export several files in parallel. You can skip the step to convert the files into the CSV format. The application handles the xls and xlsx formats.

Overall application stages are :

  1. Load the excel file content. Here is the code depending on file extension:

{

fileExtension = FilenameUtils.getExtension(inputSheetFile.getName());
    if (fileExtension.equalsIgnoreCase("xlsx")) {
        workbook = createWorkbook(openOPCPackage(inputSheetFile));
    } else {
        workbook =     
        createWorkbook(openNPOIFSFileSystemPackage(inputSheetFile));
    }

sheet = workbook.getSheetAt(0);

}

  1. Establish Postgres JDBC connection
  2. Create a Postgres table
  3. Iterate over the sheet and inset rows into the table. Here is a piece of Java code :

{

Iterator<Row> rowIterator = InitInputFilesImpl.sheet.rowIterator();

//skip a header
if (rowIterator.hasNext()) {
    rowIterator.next();
}
while (rowIterator.hasNext()) {
    Row row = (Row) rowIterator.next();
    // inserting rows
}  

}

Here you can find all Java code for the application created for exporting excel to Postgres (https://github.com/palych-piter/Excel2DB).

Pandas - Get first row value of a given column

To access a single value you can use the method iat that is much faster than iloc:

df['Btime'].iat[0]

Output:

1.2

How to repair COMException error 80040154?

WORKAROUND:

The possible workaround is modify your project's platform from 'Any CPU' to 'X86' (in Project's Properties, Build/Platform's Target)

ROOTCAUSE

The VSS Interop is a managed assembly using 32-bit Framework and the dll contains a 32-bit COM object. If you run this COM dll in 64 bit environment, you will get the error message.

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use the below code on your string and you will get the complete string without html part.

string title = "<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)".Replace("&nbsp;",string.Empty);            
        string s = Regex.Replace(title, "<.*?>", String.Empty);

How can you use optional parameters in C#?

An easy way which allows you to omit any parameters in any position, is taking advantage of nullable types as follows:

public void PrintValues(int? a = null, int? b = null, float? c = null, string s = "")
{
    if(a.HasValue)
        Console.Write(a);
    else
        Console.Write("-");

    if(b.HasValue)
        Console.Write(b);
    else
        Console.Write("-");

    if(c.HasValue)
        Console.Write(c);
    else
        Console.Write("-");

    if(string.IsNullOrEmpty(s)) // Different check for strings
        Console.Write(s);
    else
        Console.Write("-");
}

Strings are already nullable types so they don't need the ?.

Once you have this method, the following calls are all valid:

PrintValues (1, 2, 2.2f);
PrintValues (1, c: 1.2f);
PrintValues(b:100);
PrintValues (c: 1.2f, s: "hello");
PrintValues();

When you define a method that way you have the freedom to set just the parameters you want by naming them. See the following link for more information on named and optional parameters:

Named and Optional Arguments (C# Programming Guide) @ MSDN

what is this value means 1.845E-07 in excel?

Highlight the cells, format cells, select Custom then select zero.

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

You need to start by understanding that the target of a symlink is a pathname. And it can be absolute or relative to the directory which contains the symlink

Assuming you have foo.conf in sites-available

Try

cd sites-enabled
sudo ln -s ../sites-available/foo.conf .
ls -l

Now you will have a symlink in sites-enabled called foo.conf which has a target ../sites-available/foo.conf

Just to be clear, the normal configuration for Apache is that the config files for potential sites live in sites-available and the symlinks for the enabled sites live in sites-enabled, pointing at targets in sites-available. That doesn't quite seem to be the case the way you describe your setup, but that is not your primary problem.

If you want a symlink to ALWAYS point at the same file, regardless of the where the symlink is located, then the target should be the full path.

ln -s /etc/apache2/sites-available/foo.conf mysimlink-whatever.conf

Here is (line 1 of) the output of my ls -l /etc/apache2/sites-enabled:

lrwxrwxrwx 1 root root  26 Jun 24 21:06 000-default -> ../sites-available/default

See how the target of the symlink is relative to the directory that contains the symlink (it starts with ".." meaning go up one directory).

Hardlinks are totally different because the target of a hardlink is not a directory entry but a filing system Inode.

How to read a text file into a list or an array with Python

You can also use numpy loadtxt like

from numpy import loadtxt
lines = loadtxt("filename.dat", comments="#", delimiter=",", unpack=False)

PHP - cannot use a scalar as an array warning

Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.

Android Percentage Layout Height

android:layout_weight=".YOURVALUE" is best way to implement in percentage

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

    <TextView
        android:id="@+id/logTextBox"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight=".20"
        android:maxLines="500"
        android:scrollbars="vertical"
        android:singleLine="false"
        android:text="@string/logText" >
    </TextView>

</LinearLayout>

Can't type in React input text field

i'm also facing that problem now solved.Give the onChange to the searchTool. then that problem will solve for you.

How to convert a date string to different format

If you can live with 01 for January instead of 1, then try...

d = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print datetime.date.strftime(d, "%m/%d/%y")

You can check the docs for other formatting directives.

Disable Chrome strict MIME type checking

In case you are using node.js (with express)

If you want to serve static files in node.js, you need to use a function. Add the following code to your js file:

app.use(express.static("public"));

Where app is:

const express = require("express");
const app = express();

Then create a folder called public in you project folder. (You could call it something else, this is just good practice but remember to change it from the function as well.)

Then in this file create another folder named css (and/or images file under css if you want to serve static images as well.) then add your css files to this folder.

After you add them change the stylesheet accordingly. For example if it was:

href="cssFileName.css"

and

src="imgName.png"

Make them:

href="css/cssFileName.css"
src="css/images/imgName.png"

That should work

One time page refresh after first page load

use window.localStorage... like this

var refresh = $window.localStorage.getItem('refresh');
console.log(refresh);
if (refresh===null){
    window.location.reload();
    $window.localStorage.setItem('refresh', "1");
}

It's work for me

insert data into database using servlet and jsp in eclipse

Check that doPost() method of servlet is called from the jsp form and remove conn.commit.

Swift addsubview and remove it

Thanks for help. This is the solution: I created the subview and i add a gesture to remove it

@IBAction func infoView(sender: UIButton) {
    var testView: UIView = UIView(frame: CGRectMake(0, 0, 320, 568))
    testView.backgroundColor = UIColor.blueColor()
    testView.alpha = 0.5
    testView.tag = 100
    testView.userInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = "removeSubview"
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){
    println("Start remove sibview")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        println("No!")
    }
}

Update:

Swift 3+

@IBAction func infoView(sender: UIButton) {
    let testView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
    testView.backgroundColor = .blue
    testView.alpha = 0.5
    testView.tag = 100
    testView.isUserInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = #selector(GasMapViewController.removeSubview)
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){
    print("Start remove sibview")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        print("No!")
    }
}

How to find the socket connection state in C?

I had a similar problem. I wanted to know whether the server is connected to client or the client is connected to server. In such circumstances the return value of the recv function can come in handy. If the socket is not connected it will return 0 bytes. Thus using this I broke the loop and did not have to use any extra threads of functions. You might also use this same if experts feel this is the correct method.

Illegal mix of collations MySQL Error

In general the best way is to Change the table collation. However I have an old application and are not really able to estimate the outcome whether this has side effects. Therefore I tried somehow to convert the string into some other format that solved the collation problem. What I found working is to do the string compare by converting the strings into a hexadecimal representation of it's characters. On the database this is done with HEX(column). For PHP you may use this function:

public static function strToHex($string)
{
    $hex = '';
    for ($i=0; $i<strlen($string); $i++){
        $ord = ord($string[$i]);
        $hexCode = dechex($ord);
        $hex .= substr('0'.$hexCode, -2);
    }
    return strToUpper($hex);
}

When doing the database query, your original UTF8 string must be converted first into an iso string (e.g. using utf8_decode() in PHP) before using it in the DB. Because of the collation type the database cannot have UTF8 characters inside so the comparism should work event though this changes the original string (converting UTF8 characters that are not existend in the ISO charset result in a ? or these are removed entirely). Just make sure that when you write data into the database, that you use the same UTF8 to ISO conversion.

How to open local files in Swagger-UI

Use the spec parameter.

Instructions below.

Create spec.js file containing Swagger JSON

Create a new javascript file in the same directory as index.html (/dist/)

Then insert spec variable declaration:

var spec = 

Then paste in the swagger.json file contents after. It does not have to be on the same line as the = sign.

Example:

var spec =

{
    "swagger": "2.0",
    "info": {
        "title": "I love Tex-Mex API",
        "description": "You can barbecue it, boil it, broil it, bake it, sauté it. Dey's uh, Tex-Mex-kabobs, Tex-Mex creole, Tex-Mex gumbo. Pan fried, deep fried, stir-fried. There's pineapple Tex-Mex, lemon Tex-Mex, coconut Tex-Mex, pepper Tex-Mex, Tex-Mex soup, Tex-Mex stew, Tex-Mex salad, Tex-Mex and potatoes, Tex-Mex burger, Tex-Mex sandwich..",
        "version": "1.0.0"
    },
    ...
    }
}

Modify Swagger UI index.html

This is a two-step like Ciara.

Include spec.js

Modify the /dist/index.html file to include the external spec.js file.

 <script src='spec.js' type="text/javascript"></script>

Example:

  <!-- Some basic translations -->
  <!-- <script src='lang/translator.js' type='text/javascript'></script> -->
  <!-- <script src='lang/ru.js' type='text/javascript'></script> -->
  <!-- <script src='lang/en.js' type='text/javascript'></script> -->

  <!-- Original file pauses -->
  <!-- Insert external modified swagger.json -->
  <script src='spec.js' type="text/javascript"></script>
  <!-- Original file resumes -->

  <script type="text/javascript">

    $(function () {
      var url = window.location.search.match(/url=([^&]+)/);
      if (url && url.length > 1) {
        url = decodeURIComponent(url[1]);
      } else {
        url = "http://petstore.swagger.io/v2/swagger.json";
      }

Add spec parameter

Modify the SwaggerUi instance to include the spec parameter:

  window.swaggerUi = new SwaggerUi({
    url: url,
    spec: spec,
    dom_id: "swagger-ui-container",

Creating a copy of an object in C#

You could do:

class myClass : ICloneable
{
    public String test;
    public object Clone()
    {
        return this.MemberwiseClone();
    }
}

then you can do

myClass a = new myClass();
myClass b = (myClass)a.Clone();

N.B. MemberwiseClone() Creates a shallow copy of the current System.Object.

Windows batch: sleep

I don't know why those commands are not working for you, but you can also try timeout

timeout <delay in seconds>

React.createElement: type is invalid -- expected a string

What missing for me was I was using

import { Router, Route, browserHistory, IndexRoute } from 'react-router';

instead or correct answer should be :

import { BrowserRouter as Router, Route } from 'react-router-dom';

Ofcourse you need to add npm package react-router-dom:

npm install react-router-dom@next --save

How to get temporary folder for current user

System.IO.Path.GetTempPath() is just a wrapper for a native call to GetTempPath(..) in Kernel32.

Have a look at http://msdn.microsoft.com/en-us/library/aa364992(VS.85).aspx

Copied from that page:

The GetTempPath function checks for the existence of environment variables in the following order and uses the first path found:

  • The path specified by the TMP environment variable.
  • The path specified by the TEMP environment variable.
  • The path specified by the USERPROFILE environment variable.
  • The Windows directory.

It's not entirely clear to me whether "The Windows directory" means the temp directory under windows or the windows directory itself. Dumping temp files in the windows directory itself sounds like an undesirable case, but who knows.

So combining that page with your post I would guess that either one of the TMP, TEMP or USERPROFILE variables for your Administrator user points to the windows path, or else they're not set and it's taking a fallback to the windows temp path.

"undefined" function declared in another file?

you should use go modules now, if you are not following How to write go code

With go module you don't have to put the code in the $GOPATH/src. it can live in any other location as well.

You can move the code to different directory like /employee, To make it work Just under employee directory initialise the go module

go mod init example.com/employee

get the value of "onclick" with jQuery?

$('#google').attr('onclick') + ""

However, Firebug shows that this returns a function 'onclick'. You can call the function later on using the following approach:

(new Function ($('#google').attr('onclick') + ';onclick();'))()

... or use a RegEx to strip the function and get only the statements within it.

$.ajax - dataType

jQuery Ajax loader is not working well when you call two APIs simultaneously. To resolve this problem you have to call the APIs one by one using the isAsync property in Ajax setting. You also need to make sure that there should not be any error in the setting. Otherwise, the loader will not work. E.g undefined content-type, data-type for POST/PUT/DELETE/GET call.

Using git to get just the latest revision

Use git clone with the --depth option set to 1 to create a shallow clone with a history truncated to the latest commit.

For example:

git clone --depth 1 https://github.com/user/repo.git

To also initialize and update any nested submodules, also pass --recurse-submodules and to clone them shallowly, also pass --shallow-submodules.

For example:

git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git

Format datetime to YYYY-MM-DD HH:mm:ss in moment.js

Use different format or pattern to get the information from the date

_x000D_
_x000D_
var myDate = new Date("2015-06-17 14:24:36");_x000D_
console.log(moment(myDate).format("YYYY-MM-DD HH:mm:ss"));_x000D_
console.log("Date: "+moment(myDate).format("YYYY-MM-DD"));_x000D_
console.log("Year: "+moment(myDate).format("YYYY"));_x000D_
console.log("Month: "+moment(myDate).format("MM"));_x000D_
console.log("Month: "+moment(myDate).format("MMMM"));_x000D_
console.log("Day: "+moment(myDate).format("DD"));_x000D_
console.log("Day: "+moment(myDate).format("dddd"));_x000D_
console.log("Time: "+moment(myDate).format("HH:mm")); // Time in24 hour format_x000D_
console.log("Time: "+moment(myDate).format("hh:mm A"));
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

For more info: https://momentjs.com/docs/#/parsing/string-format/

file_get_contents() how to fix error "Failed to open stream", "No such file"

The actual problem of this error has nothing to do with file_get_content, the problem is the requested url if the url is not throwing content of the page and redirecting the request to some where else file_get_content says "Failed to open stream", just before file_get_contents check whether the url is working and not redirecting, here is the code:

function checkRedirect404($url) {

$ch = curl_init();

curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    curl_setopt($ch, CURLOPT_URL, $url);
    $out = curl_exec($ch);

    // line endings is the wonkiest piece of this whole thing
    $out = str_replace("\r", "", $out);

    // only look at the headers
    $headers_end = strpos($out, "\n\n");
    if( $headers_end !== false ) { 
        $out = substr($out, 0, $headers_end);
    }   

    $headers = explode("\n", $out);
    foreach($headers as $header) {
        if( substr($header, 0, 10) == "Location: " ) { 
            $target = substr($header, 10);

            //echo "Redirects: $target<br>";

            return true;
        }   
    }   

    return false;

}

How to change border color of textarea on :focus

you need just in scss varible

$input-btn-focus-width:       .05rem !default;

How to validate a form with multiple checkboxes to have atleast one checked

This script below should put you on the right track perhaps?

You can keep this html the same (though I changed the method to POST):

<form method="POST" id="subscribeForm">
    <fieldset id="cbgroup">
        <div><input name="list" id="list0" type="checkbox"  value="newsletter0" >zero</div>
        <div><input name="list" id="list1" type="checkbox"  value="newsletter1" >one</div>
        <div><input name="list" id="list2" type="checkbox"  value="newsletter2" >two</div>
    </fieldset>
    <input name="submit" type="submit"  value="submit">
</form>

and this javascript validates

function onSubmit() 
{ 
    var fields = $("input[name='list']").serializeArray(); 
    if (fields.length === 0) 
    { 
        alert('nothing selected'); 
        // cancel submit
        return false;
    } 
    else 
    { 
        alert(fields.length + " items selected"); 
    }
}

// register event on form, not submit button
$('#subscribeForm').submit(onSubmit)

and you can find a working example of it here

UPDATE (Oct 2012)
Additionally it should be noted that the checkboxes must have a "name" property, or else they will not be added to the array. Only having "id" will not work.

UPDATE (May 2013)
Moved the submit registration to javascript and registered the submit onto the form (as it should have been originally)

UPDATE (June 2016)
Changes == to ===

How to determine one year from now in Javascript

You should use getFullYear() instead of getYear(). getYear() returns the actual year minus 1900 (and so is fairly useless).

Thus a date marking exactly one year from the present moment would be:

var oneYearFromNow = new Date();
oneYearFromNow.setFullYear(oneYearFromNow.getFullYear() + 1);

Note that the date will be adjusted if you do that on February 29.

Similarly, you can get a date that's a month from now via getMonth() and setMonth(). You don't have to worry about "rolling over" from the current year into the next year if you do it in December; the date will be adjusted automatically. Same goes for day-of-month via getDate() and setDate().

TypeError: got multiple values for argument

I had the same problem that is really easy to make, but took me a while to see through.

I had copied the declaration to where I was using it and had left the 'self' argument there, but it took me ages to realise that.

I had

self.myFunction(self, a, b, c='123')

but it should have been

self.myFunction(a, b, c='123')

Is JavaScript's "new" keyword considered harmful?

Crockford has done a lot to popularize good JavaScript techniques. His opinionated stance on key elements of the language have sparked many useful discussions. That said, there are far too many people that take each proclamation of "bad" or "harmful" as gospel, refusing to look beyond one man's opinion. It can be a bit frustrating at times.

Use of the functionality provided by the new keyword has several advantages over building each object from scratch:

  1. Prototype inheritance. While often looked at with a mix of suspicion and derision by those accustomed to class-based OO languages, JavaScript's native inheritance technique is a simple and surprisingly effective means of code re-use. And the new keyword is the canonical (and only available cross-platform) means of using it.
  2. Performance. This is a side-effect of #1: if I want to add 10 methods to every object I create, I could just write a creation function that manually assigns each method to each new object... Or, I could assign them to the creation function's prototype and use new to stamp out new objects. Not only is this faster (no code needed for each and every method on the prototype), it avoids ballooning each object with separate properties for each method. On slower machines (or especially, slower JS interpreters) when many objects are being created this can mean a significant savings in time and memory.

And yes, new has one crucial disadvantage, ably described by other answers: if you forget to use it, your code will break without warning. Fortunately, that disadvantage is easily mitigated - simply add a bit of code to the function itself:

function foo()
{
   // if user accidentally omits the new keyword, this will 
   // silently correct the problem...
   if ( !(this instanceof foo) )
      return new foo();

   // constructor logic follows...
}

Now you can have the advantages of new without having to worry about problems caused by accidentally misuse. You could even add an assertion to the check if the thought of broken code silently working bothers you. Or, as some commented, use the check to introduce a runtime exception:

if ( !(this instanceof arguments.callee) ) 
   throw new Error("Constructor called as a function");

(Note that this snippet is able to avoid hard-coding the constructor function name, as unlike the previous example it has no need to actually instantiate the object - therefore, it can be copied into each target function without modification.)

John Resig goes into detail on this technique in his Simple "Class" Instantiation post, as well as including a means of building this behavior into your "classes" by default. Definitely worth a read... as is his upcoming book, Secrets of the JavaScript Ninja, which finds hidden gold in this and many other "harmful" features of the JavaScript language (the chapter on with is especially enlightening for those of us who initially dismissed this much-maligned feature as a gimmick).

How to use a link to call JavaScript?

based on @mister_lucky answer use with jquery:

$('#unobtrusive').on('click',function (e) {
    e.preventDefault(); //optional
    //some code
});

Html Code:

<a id="unobtrusive" href="http://jquery.com">jquery</a>

XML Parser for C

Could you give some indication of what platforms you are writing for? This should weigh heavily on what is 'best'. You might find a super 'xml-foo' library that does not ship commonly on most systems by default .. while its great, the lack of the library might prevent (or at least) annoy users.

Mostly, I use libxml2 .. because its standard or easy to install on the platforms that I target.

As you see, 'best' is also determined by the library being available on your target platforms.

Android EditText view Floating Hint in Material Design

Import the Support Libraries, In your project's build.gradle file, add the following lines in the project's dependencies:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    compile 'com.android.support:design:22.2.0'
    compile 'com.android.support:appcompat-v7:22.2.0'
}

Use following TextInputLayout in your UI Layout:

<android.support.design.widget.TextInputLayout
    android:id="@+id/usernameWrapper"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <EditText
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textEmailAddress"
        android:hint="Username"/>

</android.support.design.widget.TextInputLayout>

Than, call setHint on TextInputLayout just after setContentView call because, to animate the floating label, you just need to set a hint, using the setHint method.

final TextInputLayout usernameWrapper = (TextInputLayout) findViewById(R.id.usernameWrapper);
usernameWrapper.setHint("Username");

XML Schema (XSD) validation tool?

You can connect your XML schema to Microsoft Visual Studio's Intellisense. This option gives you both real-time validation AND autocomplete, which is just awesome.

I have this exact scenario running on my free copy of Microsoft Visual C++ 2010 Express.

c# open file with default application and parameters

If you want the file to be opened with the default application, I mean without specifying Acrobat or Reader, you can't open the file in the specified page.

On the other hand, if you are Ok with specifying Acrobat or Reader, keep reading:


You can do it without telling the full Acrobat path, like this:

Process myProcess = new Process();    
myProcess.StartInfo.FileName = "acroRd32.exe"; //not the full application path
myProcess.StartInfo.Arguments = "/A \"page=2=OpenActions\" C:\\example.pdf";
myProcess.Start();

If you don't want the pdf to open with Reader but with Acrobat, chage the second line like this:

myProcess.StartInfo.FileName = "Acrobat.exe";

You can query the registry to identify the default application to open pdf files and then define FileName on your process's StartInfo accordingly.

Follow this question for details on doing that: Finding the default application for opening a particular file type on Windows

How to get a list of column names

Try this sqlite table schema parser, I implemented the sqlite table parser for parsing the table definitions in PHP.

It returns the full definitions (unique, primary key, type, precision, not null, references, table constraints... etc)

https://github.com/maghead/sqlite-parser

Input mask for numeric and decimal

Try imaskjs. It has Number, RegExp and other masks. Very simple to extend.

Command-line svn for Windows?

The subversion client itself is available on Windows. See here for certified binaries from CollabNet.

CollabNet Subversion Command-Line Client v1.6.9 (for Windows)

This installer only includes the command-line client and an auto-update component.

Even though I can't understand it's possible not to love Tortoise! :)

Note:
The above link is for newer products - you can find version 1.11.1 through 1.7.19 at Older Subversion Releases

jQuery - Getting the text value of a table cell in the same row as a clicked element

Nick has the right answer, but I wanted to add you could also get the cell data without needing the class name

var Something = $(this).closest('tr').find('td:eq(1)').text();

:eq(#) has a zero based index (link).

printing all contents of array in C#

this is the easiest way that you could print the String by using array!!!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace arraypracticeforstring
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] arr = new string[3] { "Snehal", "Janki", "Thakkar" };

            foreach (string item in arr)
            {
                Console.WriteLine(item.ToString());
            }
            Console.ReadLine();
        }
    }
}

Difference between RUN and CMD in a Dockerfile

Note: Don’t confuse RUN with CMD. RUN actually runs a command and commits the result; CMD does not execute anything at build time, but specifies the intended command for the image.

from docker file reference

https://docs.docker.com/engine/reference/builder/#cmd

What is the basic difference between the Factory and Abstract Factory Design Patterns?

Many people will feel surprised maybe, but this question is incorrect. If you hear this question during an interview, you need to help the interviewer understand where the confusion is.

Let's start from the fact that there is no concrete pattern that is called just "Factory". There is pattern that is called "Abstract Factory", and there is pattern that is called "Factory Method".

So, what does "Factory" mean then? one of the following (all can be considered correct, depending on the scope of the reference):

  • Some people use it as an alias (shortcut) for "Abstract Factory".
  • Some people use it as an alias (shortcut) for "Factory Method".
  • Some people use it as a more general name for all factory/creational patterns. E.g. both "Abstract Factory" and "Factory Method" are Factories.

And, unfortunately, many people use "Factory" to denote another kind of factory, that creates factory or factories (or their interfaces). Based on their theory:

Product implements IProduct, which is created by Factory, which implements IFactory, which is created by AbstractFactory.

To understand how silly this is, let's continue our equation:

AbstractFactory implements IAbstractFactory, which is created by... AbstractAbstractFactory???

I hope you see the point. Don't get confused, and please don't invent things that don't exist for reason.

-

P.S.: Factory for Products is AbstractFactory, and Factory for Abstract Factories would be just another example of AbstractFactory as well.

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

How to fix HTTP 404 on Github Pages?

I also faced this issue, my pages getting 404. And then I added README.md on my repository, and the 404 was gone.

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

int(b, 2)  # Convert a binary string to a decimal int.

How to split (chunk) a Ruby array into parts of X elements?

If you're using rails you can also use in_groups_of:

foo.in_groups_of(3)

Android Studio Gradle Configuration with name 'default' not found

For me it turned out to be an relative symbolic link (to the referenced project) that couldn't be used by grade. (I was referencing a library). Thats a pretty edgy edge-case but maybe it helps someone in the future.

I solved it by putting a absolute symbolic link.

Before ln -s ../library after ln -s /the/full/path/to/the/library

Ignore <br> with CSS?

As per your question, to solve this problem for Firefox and Opera using Aneesh Karthik C approach you need to add "float" right" attribute.

Check the example here. This CSS works in Firefox (26.0) , Opera (12.15), Chrome (32.0.1700) and Safari (7.0)

br {
   content: " ";  
   float:right; 
}

I hope this will answer your question!!

CSS selectors ul li a {...} vs ul > li > a {...}

Here > a to specifiy the color for root of li.active.menu-item

#primary-menu > li.active.menu-item > a

_x000D_
_x000D_
#primary-menu>li.active.menu-item>a {_x000D_
  color: #c19b66;_x000D_
}
_x000D_
<ul id="primary-menu">_x000D_
  <li class="active menu-item"><a>Coffee</a>_x000D_
    <ul id="sub-menu">_x000D_
      <li class="active menu-item"><a>aaa</a></li>_x000D_
      <li class="menu-item"><a>bbb</a></li>_x000D_
      <li class="menu-item"><a>ccc</a></li>_x000D_
    </ul>_x000D_
  </li>_x000D_
_x000D_
  <li class="menu-item"><a>Tea</a></li>_x000D_
  <li class="menu-item"><a>Coca Cola</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

creating array without declaring the size - java

I think what you really want is an ArrayList or Vector. Arrays in Java are not like those in Javascript.

How to ignore parent css style

You should use this

height:auto !important;

selectOneMenu ajax events

You could check whether the value of your selectOneMenu component belongs to the list of subjects.

Namely:

public void subjectSelectionChanged() {
    // Cancel if subject is manually written
    if (!subjectList.contains(aktNachricht.subject)) { return; }
    // Write your code here in case the user selected (or wrote) an item of the list
    // ....
}

Supposedly subjectList is a collection type, like ArrayList. Of course here your code will run in case the user writes an item of your selectOneMenu list.

git undo all uncommitted or unsaved changes

Adding this answer because the previous answers permanently delete your changes

The Safe way

git stash -u

Explanation: Stash local changes including untracked changes (-u flag). The command saves your local modifications away and reverts the working directory to match the HEAD commit.

Want to recover the changes later?

git stash pop

Explanation: The command will reapply the changes to the top of the current working tree state.

Want to permanently remove the changes?

git stash drop

Explanation: The command will permanently remove the stashed entry

Link to git stash documentation

How can I increment a date by one day in Java?

Take a look at Joda-Time (https://www.joda.org/joda-time/).

DateTimeFormatter parser = ISODateTimeFormat.date();

DateTime date = parser.parseDateTime(dateString);

String nextDay = parser.print(date.plusDays(1));

How to make a SIMPLE C++ Makefile

You had two options.

Option 1: simplest makefile = NO MAKEFILE.

Rename "a3driver.cpp" to "a3a.cpp", and then on the command line write:

nmake a3a.exe

And that's it. If you're using GNU Make, use "make" or "gmake" or whatever.

Option 2: a 2-line makefile.

a3a.exe: a3driver.obj
    link /out:a3a.exe a3driver.obj

When should I use h:outputLink instead of h:commandLink?

The <h:outputLink> renders a fullworthy HTML <a> element with the proper URL in the href attribute which fires a bookmarkable GET request. It cannot directly invoke a managed bean action method.

<h:outputLink value="destination.xhtml">link text</h:outputLink>

The <h:commandLink> renders a HTML <a> element with an onclick script which submits a (hidden) POST form and can invoke a managed bean action method. It's also required to be placed inside a <h:form>.

<h:form>
    <h:commandLink value="link text" action="destination" />
</h:form>

The ?faces-redirect=true parameter on the <h:commandLink>, which triggers a redirect after the POST (as per the Post-Redirect-Get pattern), only improves bookmarkability of the target page when the link is actually clicked (the URL won't be "one behind" anymore), but it doesn't change the href of the <a> element to be a fullworthy URL. It still remains #.

<h:form>
    <h:commandLink value="link text" action="destination?faces-redirect=true" />
</h:form>

Since JSF 2.0, there's also the <h:link> which can take a view ID (a navigation case outcome) instead of an URL. It will generate a HTML <a> element as well with the proper URL in href.

<h:link value="link text" outcome="destination" />

So, if it's for pure and bookmarkable page-to-page navigation like the SO username link, then use <h:outputLink> or <h:link>. That's also better for SEO since bots usually doesn't cipher POST forms nor JS code. Also, UX will be improved as the pages are now bookmarkable and the URL is not "one behind" anymore.

When necessary, you can do the preprocessing job in the constructor or @PostConstruct of a @RequestScoped or @ViewScoped @ManagedBean which is attached to the destination page in question. You can make use of @ManagedProperty or <f:viewParam> to set GET parameters as bean properties.

See also:

How to make a owl carousel with arrows instead of next previous

If you using latest Owl Carousel 2 version. You can replace the Navigation text by fontawesome icon. Code is below.

$('.your-class').owlCarousel({
        loop: true,
        items: 1, // Select Item Number
        autoplay:true,
        dots: false,
        nav: true,
        navText: ["<i class='fa fa-long-arrow-left'></i>","<i class='fa fa-long-arrow-right'></i>"],

    });

find all subsets that sum to a particular value

I used Dynamic Programming & Memoization to find count of subsets from a set having a particular total. The code below code is in java. Have included the comments to explain the code intentions -

package com.company.dynamicProgramming;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class FindSumInSubSet {

    public static void main(String...args){

        int[] arr = {3, 2, 4, 6, 10};
        int total = 16;
        // Challenge is to find the subsets of numbers total 6 in above super set (represented as array)
        // In general - Write a code to count subset of elements totalling m(6 above) in given set of n(9 as array size above) elements

        Map<Entry, Integer> memoMap = new HashMap<>();

        Entry entry = new Entry(total, arr.length-1);

        int count = countSubSetForSum(arr, entry, memoMap);
        System.out.format("In set of %d elements, the number of subsets having total=%d is %d %n", arr.length,total, count);
    }


    static int countSubSetForSum(int[] arr, Entry entry, Map<Entry, Integer> memoMap){

        int total = entry.getTotal();
        int i = entry.getI();

        if (total == 0){             // means element was equal in previous recursion
            return 1;
        }else if(total < 0){         // means element was less in previous recursion i.e. not equal
            return 0;
        }else if (i < 0){            // means arr was finished previous recursion
            return 0;
        }else if (arr[i] > total){   // means element is greater than total
                                     // i.e. leave that element and look further sets excluding this element
            return getCountForIthAndTotal(arr, new Entry( total, i-1), memoMap);

        }else{                       // means element is less than total i.e. 2 possibilities :
                                     // 1st - look further sets including this element
                                     // 2nd - look further sets excluding this element
            return getCountForIthAndTotal(arr, new Entry( total-arr[i], i-1), memoMap) +
                    getCountForIthAndTotal(arr, new Entry( total, i-1), memoMap);
        }
    }


    static int getCountForIthAndTotal(int[] arr, Entry entry, Map<Entry, Integer> memoMap){
        if (memoMap.containsKey(entry)){     //look up in has table if we already calculated particular total for ith subset..
            return memoMap.get(entry);       //This is nothing but using memoization that reduce the entire below code i.e. further recursion -
        }else {
            int count = countSubSetForSum(arr, entry, memoMap);  //Recursion
            memoMap.put(entry, count); //Build memoization
            return count;
        }
    }


    //Just Data Structure for Key in HashMap (memoMaP)... intent to include particular total for ith element's subset.
    static class Entry {
        int total;
        int i;

        public Entry(int total, int i) {
            this.total = total;
            this.i = i;
        }

        public int getTotal() {
            return total;
        }

        public int getI() {
            return i;
        }


        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Entry entry = (Entry) o;
            return total == entry.total &&
                    i == entry.i;
        }

        @Override
        public int hashCode() {
            return Objects.hash(total, i);
        }
    }

}

When i ran this the out put is :

In set of 5 elements, the number of subsets having total=16 is 2 
Process finished with exit code 0

How to download Javadoc to read offline?

For any javadoc (not just the ones available for download) you can use the DownThemAll addon for Firefox with a suitable renaming mask, for example:

*subdirs*/*name*.*ext*

https://addons.mozilla.org/en-us/firefox/addon/downthemall/

https://www.downthemall.org/main/install-it/downthemall-3-0-7/

Edit: It's possible to use some older versions of the DownThemAll add-on with Pale Moon browser.

Generate UML Class Diagram from Java Project

I use eUML2 plugin from Soyatec, under Eclipse and it works fine for the generation of UML giving the source code. This tool is useful up to Eclipse 4.4.x

If list index exists, do X

You can try something like this

list = ["a", "b", "C", "d", "e", "f", "r"]

for i in range(0, len(list), 2):
    print list[i]
    if len(list) % 2 == 1 and  i == len(list)-1:
        break
    print list[i+1];

Color Tint UIButton Image

None of above worked for me, because tint was cleared after click. I had to use

button.setImageTintColor(Palette.darkGray(), for: UIControlState())

Using GCC to produce readable assembly?

use -Wa,-adhln as option on gcc or g++ to produce a listing output to stdout.

-Wa,... is for command line options for the assembler part (execute in gcc/g++ after C/++ compilation). It invokes as internally (as.exe in Windows). See

>as --help

as command line to see more help for the assembler tool inside gcc

Calculating arithmetic mean (one type of average) in Python

I always supposed avg is omitted from the builtins/stdlib because it is as simple as

sum(L)/len(L) # L is some list

and any caveats would be addressed in caller code for local usage already.

Notable caveats:

  1. non-float result: in python2, 9/4 is 2. to resolve, use float(sum(L))/len(L) or from __future__ import division

  2. division by zero: the list may be empty. to resolve:

    if not L:
        raise WhateverYouWantError("foo")
    avg = float(sum(L))/len(L)
    

How do I make a redirect in PHP?

Use:

<?php header('Location: another-php-file.php'); exit(); ?>

Or if you've already opened PHP tags, use this:

header('Location: another-php-file.php'); exit();

You can also redirect to external pages, e.g.:

header('Location: https://www.google.com'); exit();

Make sure you include exit() or include die().

Difference between @click and v-on:click Vuejs

v-bind and v-on are two frequently used directives in vuejs html template. So they provided a shorthand notation for the both of them as follows:

You can replace v-on: with @

v-on:click='someFunction'

as:

@click='someFunction'

Another example:

v-on:keyup='someKeyUpFunction'

as:

@keyup='someKeyUpFunction'

Similarly, v-bind with :

v-bind:href='var1'

Can be written as:

:href='var1'

Hope it helps!

How do I force Internet Explorer to render in Standards Mode and NOT in Quirks?

  1. Using html5 doctype at the beginning of the page.

    <!DOCTYPE html>

  2. Force IE to use the latest render mode

    <meta http-equiv="X-UA-Compatible" content="IE=edge">

  3. If your target browser is ie8, then check your compatible settings in IE8

I blog this in details

How to merge 2 JSON objects from 2 files using jq?

First, {"value": .value} can be abbreviated to just {value}.

Second, the --argfile option (available in jq 1.4 and jq 1.5) may be of interest as it avoids having to use the --slurp option.

Putting these together, the two objects in the two files can be combined in the specified way as follows:

$ jq -n --argfile o1 file1 --argfile o2 file2 '$o1 * $o2 | {value}'

The '-n' flag tells jq not to read from stdin, since inputs are coming from the --argfile options here.

Note on --argfile

The jq manual deprecates --argfile because its semantics are non-trivial: if the specified input file contains exactly one JSON entity, then that entity is read as is; otherwise, the items in the stream are wrapped in an array.

If you are uncomfortable using --argfile, there are several alternatives you may wish to consider. In doing so, be assured that using --slurpfile does not incur the inefficiencies of the -s command-line option when the latter is used with multiple files.

AngularJS - difference between pristine/dirty and touched/untouched

This is a late answer but hope this might help.

Scenario 1: You visited the site for first time and did not touch any field. The state of form is

ng-untouched and ng-pristine

Scenario 2: You are currently entering the values in a particular field in the form. Then the state is

ng-untouched and ng-dirty

Scenario 3: You are done with entering the values in the field and moved to next field

ng-touched and ng-dirty

Scenario 4: Say a form has a phone number field . You have entered the number but you have actually entered 9 digits but there are 10 digits required for a phone number.Then the state is ng-invalid

In short:

ng-untouched:When the form field has not been visited yet

ng-touched: When the form field is visited AND the field has lost focus

ng-pristine: The form field value is not changed

ng-dirty: The form field value is changed

ng-valid : When all validations of form fields are successful

ng-invalid: When all validations of form fields are not successful

How can I disable HREF if onclick is executed?

You can use the first un-edited solution, if you put return first in the onclick attribute:

<a href="https://example.com/no-js-login" onclick="return yes_js_login();">Log in</a>

yes_js_login = function() {
     // Your code here
     return false;
}

Example: https://jsfiddle.net/FXkgV/289/

Renaming the current file in Vim

sav person.haml_spec.rb | call delete(expand('#'))

How do you perform address validation?

In the course of developing an in-house address verification service at a German company I used to work for I've come across a number of ways to tackle this issue. I'll do my best to sum up my findings below:

Free, Open Source Software

Clearly, the first approach anyone would take is an open-source one (like openstreetmap.org), which is never a bad idea. But whether or not you can really put this to good and reliable use depends very much on how much you need to rely on the results.

Addresses are an incredibly variable thing. Verifying U.S. addresses is not an easy task, but bearable, but once you're going for Europe, especially the U.K. with their extensive Postal Code system, the open-source approach will simply lack data.

Web Services / APIs

Enterprise-Class Software

Money gets it done, obviously. But not every business or developer can spend ~$0.15 per address lookup (that's $150 for 1,000 API requests) - a very expensive business model the vast majority of address validation APIs have implemented.

What I ended up integrating: streetlayer API

Since I was not willing to take on the programmatic approach of verifying address data manually I finally came to the conclusion that I was in need of an API with a price tag that would not make my boss want to fire me and still deliver solid and reliable international verification results.

Long story short, I ended up integrating an API built by apilayer, called "streetlayer API". I was easily convinced by a simple JSON integration, surprisingly accurate validation results and their developer-friendly pricing. Also, 100 requests/month are entirely free.

Hope this helps!

How do I show a console output/window in a forms application?

This worked for me, to pipe the output to a file. Call the console with

cmd /c "C:\path\to\your\application.exe" > myfile.txt

Add this code to your application.

    [DllImport("kernel32.dll")]
    static extern bool AttachConsole(UInt32 dwProcessId);
    [DllImport("kernel32.dll")]
    private static extern bool GetFileInformationByHandle(
        SafeFileHandle hFile,
        out BY_HANDLE_FILE_INFORMATION lpFileInformation
        );
    [DllImport("kernel32.dll")]
    private static extern SafeFileHandle GetStdHandle(UInt32 nStdHandle);
    [DllImport("kernel32.dll")]
    private static extern bool SetStdHandle(UInt32 nStdHandle, SafeFileHandle hHandle);
    [DllImport("kernel32.dll")]
    private static extern bool DuplicateHandle(
        IntPtr hSourceProcessHandle,
        SafeFileHandle hSourceHandle,
        IntPtr hTargetProcessHandle,
        out SafeFileHandle lpTargetHandle,
        UInt32 dwDesiredAccess,
        Boolean bInheritHandle,
        UInt32 dwOptions
        );
    private const UInt32 ATTACH_PARENT_PROCESS = 0xFFFFFFFF;
    private const UInt32 STD_OUTPUT_HANDLE = 0xFFFFFFF5;
    private const UInt32 STD_ERROR_HANDLE = 0xFFFFFFF4;
    private const UInt32 DUPLICATE_SAME_ACCESS = 2;
    struct BY_HANDLE_FILE_INFORMATION
    {
        public UInt32 FileAttributes;
        public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime;
        public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime;
        public System.Runtime.InteropServices.ComTypes.FILETIME LastWriteTime;
        public UInt32 VolumeSerialNumber;
        public UInt32 FileSizeHigh;
        public UInt32 FileSizeLow;
        public UInt32 NumberOfLinks;
        public UInt32 FileIndexHigh;
        public UInt32 FileIndexLow;
    }
    static void InitConsoleHandles()
    {
        SafeFileHandle hStdOut, hStdErr, hStdOutDup, hStdErrDup;
        BY_HANDLE_FILE_INFORMATION bhfi;
        hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
        hStdErr = GetStdHandle(STD_ERROR_HANDLE);
        // Get current process handle
        IntPtr hProcess = Process.GetCurrentProcess().Handle;
        // Duplicate Stdout handle to save initial value
        DuplicateHandle(hProcess, hStdOut, hProcess, out hStdOutDup,
        0, true, DUPLICATE_SAME_ACCESS);
        // Duplicate Stderr handle to save initial value
        DuplicateHandle(hProcess, hStdErr, hProcess, out hStdErrDup,
        0, true, DUPLICATE_SAME_ACCESS);
        // Attach to console window – this may modify the standard handles
        AttachConsole(ATTACH_PARENT_PROCESS);
        // Adjust the standard handles
        if (GetFileInformationByHandle(GetStdHandle(STD_OUTPUT_HANDLE), out bhfi))
        {
            SetStdHandle(STD_OUTPUT_HANDLE, hStdOutDup);
        }
        else
        {
            SetStdHandle(STD_OUTPUT_HANDLE, hStdOut);
        }
        if (GetFileInformationByHandle(GetStdHandle(STD_ERROR_HANDLE), out bhfi))
        {
            SetStdHandle(STD_ERROR_HANDLE, hStdErrDup);
        }
        else
        {
            SetStdHandle(STD_ERROR_HANDLE, hStdErr);
        }
    }

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        // initialize console handles
        InitConsoleHandles();

        if (args.Length != 0)
        {

            if (args[0].Equals("waitfordebugger"))
            {
                MessageBox.Show("Attach the debugger now");
            }
            if (args[0].Equals("version"))
            {
#if DEBUG
                String typeOfBuild = "d";
#else
                String typeOfBuild = "r";
#endif
                String output = typeOfBuild + Assembly.GetExecutingAssembly()
                    .GetName().Version.ToString();
                //Just for the fun of it
                Console.Write(output);
                Console.Beep(4000, 100);
                Console.Beep(2000, 100);
                Console.Beep(1000, 100);
                Console.Beep(8000, 100);
                return;
            }
        }
    }

I found this code here: http://www.csharp411.com/console-output-from-winforms-application/ I thought is was worthy to post it here as well.

Callback functions in Java

When I need this kind of functionality in Java, I usually use the Observer pattern. It does imply an extra object, but I think it's a clean way to go, and is a widely understood pattern, which helps with code readability.

How to link an image and target a new window

If you use script to navigate to the page, use the open method with the target _blank to open a new window / tab:

<img src="..." alt="..." onclick="window.open('anotherpage.html', '_blank');" />

However, if you want search engines to find the page, you should just wrap the image in a regular link instead.

Truncating a table in a stored procedure

All DDL statements in Oracle PL/SQL should use Execute Immediate before the statement. Hence you should use:

execute immediate 'truncate table schema.tablename';

How to append data to a json file?

Using a instead of w should let you update the file instead of creating a new one/overwriting everything in the existing file.

See this answer for a difference in the modes.

Centering the pagination in bootstrap

It works for me:

<div class="text-center">
<ul class="pagination pagination-lg">
   <li>
  <a href="#" aria-label="Previous">
    <span aria-hidden="true">&laquo;</span>
  </a>
</li>
<li><a href="#">1</a></li>
<li><a href="#">2</a></li>
<li><a href="#">3</a></li>
<li><a href="#">4</a></li>
<li><a href="#">5</a></li>
<li>
  <a href="#" aria-label="Next">
    <span aria-hidden="true">&raquo;</span>
  </a>
</li>
</ul>

Using RegEX To Prefix And Append In Notepad++

Assuming alphanumeric words, you can use:

Search  = ^([A-Za-z0-9]+)$
Replace = able:"\1"

Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):

Search = ^(.+)$

^ points to the start of the line.
$ points to the end of the line.

\1 will be the source match within the parentheses.

Making Python loggers output all messages to stdout in addition to log file

The simplest way to log to stdout:

import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)

adb is not recognized as internal or external command on windows

If you go to your android-sdk/tools folder I think you'll find a message :

The adb tool has moved to platform-tools/

If you don't see this directory in your SDK, launch the SDK and AVD Manager (execute the android tool) and install "Android SDK Platform-tools"

Please also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.

So you should also add C:/android-sdk/platform-tools to you environment path. Also after you modify the PATH variable make sure that you start a new CommandPrompt window.

How can you have SharePoint Link Lists default to opening in a new window?

It is not possible with the default Link List web part, but there are resources describing how to extend Sharepoint server-side to add this functionality.

Share Point Links Open in New Window
Changing Link Lists in Sharepoint 2007

How to read text files with ANSI encoding and non-English letters?

If I remember correctly the XmlDocument.Load(string) method always assumes UTF-8, regardless of the XML encoding. You would have to create a StreamReader with the correct encoding and use that as the parameter.

xmlDoc.Load(new StreamReader(
                     File.Open("file.xml"), 
                     Encoding.GetEncoding("iso-8859-15"))); 

I just stumbled across KB308061 from Microsoft. There's an interesting passage: Specify the encoding declaration in the XML declaration section of the XML document. For example, the following declaration indicates that the document is in UTF-16 Unicode encoding format:

<?xml version="1.0" encoding="UTF-16"?>

Note that this declaration only specifies the encoding format of an XML document and does not modify or control the actual encoding format of the data.

Link Source:

XmlDocument.Load() method fails to decode € (euro)

Creating folders inside a GitHub repository without using Git

After searching a lot I find out that it is possible to create a new folder from the web interface, but it would require you to have at least one file within the folder when creating it.

When using the normal way of creating new files through the web interface, you can type in the folder into the file name to create the file within that new directory.

For example, if I would like to create the file filename.md in a series of sub-folders, I can do this (taken from the GitHub blog):

Enter image description here

How can you get the active users connected to a postgreSQL database via SQL?

OP asked for users connected to a particular database:

-- Who's currently connected to my_great_database?
SELECT * FROM pg_stat_activity 
  WHERE datname = 'my_great_database';

This gets you all sorts of juicy info (as others have mentioned) such as

  • userid (column usesysid)
  • username (usename)
  • client application name (appname), if it bothers to set that variable -- psql does :-)
  • IP address (client_addr)
  • what state it's in (a couple columns related to state and wait status)
  • and everybody's favorite, the current SQL command being run (query)

How to get javax.comm API?

Use RXTX.

On Debian install librxtx-java by typing:

sudo apt-get install librxtx-java

On Fedora or Enterprise Linux install rxtx by typing:

sudo yum install rxtx

How to export non-exportable private key from store

There is code and binaries available here for a console app that can export private keys marked as non-exportable, and it won't trigger antivirus apps like mimikatz will.

The code is based on a paper by the NCC Group. will need to run the tool with the local system account, as it works by writing directly to memory used by Windows' lsass process, in order to temporarily mark keys as exportable. This can be done using PsExec from SysInternals' PsTools:

  1. Spawn a new command prompt running as the local system user:

PsExec64.exe -s -i cmd

  1. In the new command prompt, run the tool:

exportrsa.exe

  1. It will loop over every Local Computer store, searching for certificates with a private key. For each one, it will prompt you for a password - this is the password you want to secure the exported PFX file with, so can be whatever you want

How to check postgres user and password?

You will not be able to find out the password he chose. However, you may create a new user or set a new password to the existing user.

Usually, you can login as the postgres user:

Open a Terminal and do sudo su postgres. Now, after entering your admin password, you are able to launch psql and do

CREATE USER yourname WITH SUPERUSER PASSWORD 'yourpassword';

This creates a new admin user. If you want to list the existing users, you could also do

\du

to list all users and then

ALTER USER yourusername WITH PASSWORD 'yournewpass';

Skip download if files exist in wget?

Try the following parameter:

-nc, --no-clobber: skip downloads that would download to existing files.

Sample usage:

wget -nc http://example.com/pic.png

Can I change the name of `nohup.out`?

For some reason, the above answer did not work for me; I did not return to the command prompt after running it as I expected with the trailing &. Instead, I simply tried with

nohup some_command > nohup2.out&

and it works just as I want it to. Leaving this here in case someone else is in the same situation. Running Bash 4.3.8 for reference.

How to use <DllImport> in VB.NET?

I saw in getwindowtext (user32) on pinvoke.net that you can place a MarshalAs statement to state that the StringBuffer is equivalent to LPSTR.

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
Public Function GetWindowText(hwnd As IntPtr, <MarshalAs(UnManagedType.LPStr)>lpString As System.Text.StringBuilder, cch As Integer) As Integer
End Function

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

I found a solution to solve this problem in Python.

go to c:\python27\ directory and rigtlcick python.exe and tab to compaitbility and select the admin privilege option and apply the changes. Now you issue the command it allows to create the socket connection.

Difference between SurfaceView and View?

One of the main differences between surfaceview and view is that to refresh the screen for a normal view we have to call invalidate method from the same thread where the view is defined. But even if we call invalidate, the refreshing does not happen immediately. It occurs only after the next arrival of the VSYNC signal. VSYNC signal is a kernel generated signal which happens every 16.6 ms or this is also known as 60 frame per second. So if we want more control over the refreshing of the screen (for example for very fast moving animation), we should not use normal view class.

On the other hand in case of surfaceview, we can refresh the screen as fast as we want and we can do it from a background thread. So refreshing of the surfaceview really does not depend upon VSYNC, and this is very useful if we want to do high speed animation. I have few training videos and example application which explain all these things nicely. Please have a look at the following training videos.

https://youtu.be/kRqsoApOr9U

https://youtu.be/Ji84HJ85FIQ

https://youtu.be/U8igPoyrUf8

"Uncaught TypeError: Illegal invocation" in Chrome

When you execute a method (i.e. function assigned to an object), inside it you can use this variable to refer to this object, for example:

_x000D_
_x000D_
var obj = {_x000D_
  someProperty: true,_x000D_
  someMethod: function() {_x000D_
    console.log(this.someProperty);_x000D_
  }_x000D_
};_x000D_
obj.someMethod(); // logs true
_x000D_
_x000D_
_x000D_

If you assign a method from one object to another, its this variable refers to the new object, for example:

_x000D_
_x000D_
var obj = {_x000D_
  someProperty: true,_x000D_
  someMethod: function() {_x000D_
    console.log(this.someProperty);_x000D_
  }_x000D_
};_x000D_
_x000D_
var anotherObj = {_x000D_
  someProperty: false,_x000D_
  someMethod: obj.someMethod_x000D_
};_x000D_
_x000D_
anotherObj.someMethod(); // logs false
_x000D_
_x000D_
_x000D_

The same thing happens when you assign requestAnimationFrame method of window to another object. Native functions, such as this, has build-in protection from executing it in other context.

There is a Function.prototype.call() function, which allows you to call a function in another context. You just have to pass it (the object which will be used as context) as a first parameter to this method. For example alert.call({}) gives TypeError: Illegal invocation. However, alert.call(window) works fine, because now alert is executed in its original scope.

If you use .call() with your object like that:

support.animationFrame.call(window, function() {});

it works fine, because requestAnimationFrame is executed in scope of window instead of your object.

However, using .call() every time you want to call this method, isn't very elegant solution. Instead, you can use Function.prototype.bind(). It has similar effect to .call(), but instead of calling the function, it creates a new function which will always be called in specified context. For example:

_x000D_
_x000D_
window.someProperty = true;_x000D_
var obj = {_x000D_
  someProperty: false,_x000D_
  someMethod: function() {_x000D_
    console.log(this.someProperty);_x000D_
  }_x000D_
};_x000D_
_x000D_
var someMethodInWindowContext = obj.someMethod.bind(window);_x000D_
someMethodInWindowContext(); // logs true
_x000D_
_x000D_
_x000D_

The only downside of Function.prototype.bind() is that it's a part of ECMAScript 5, which is not supported in IE <= 8. Fortunately, there is a polyfill on MDN.

As you probably already figured out, you can use .bind() to always execute requestAnimationFrame in context of window. Your code could look like this:

var support = {
    animationFrame: (window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame).bind(window)
};

Then you can simply use support.animationFrame(function() {});.

Appending to 2D lists in Python

[[]]*3 is not the same as [[], [], []].

It's as if you'd said

a = []
listy = [a, a, a]

In other words, all three list references refer to the same list instance.

How to do a regular expression replace in MySQL?

we solve this problem without using regex this query replace only exact match string.

update employee set
employee_firstname = 
trim(REPLACE(concat(" ",employee_firstname," "),' jay ',' abc '))

Example:

emp_id employee_firstname

1 jay

2 jay ajay

3 jay

After executing query result:

emp_id employee_firstname

1 abc

2 abc ajay

3 abc

How to use PHP string in mySQL LIKE query?

You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");

You can confirm this by printing out the string to see that it turns out identical to the first case.

Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
               mysql_real_escape_string($prefix));
$query = mysql_query($sql);

Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.

How do I convert an existing callback API to promises?

Under node v7.6+ which has built in promises and async:

// promisify.js
let promisify = fn => (...args) =>
    new Promise((resolve, reject) =>
        fn(...args, (err, result) => {
            if (err) return reject(err);
            return resolve(result);
        })
    );

module.exports = promisify;

How to use:

let readdir = require('fs').readdir;
let promisify = require('./promisify');
let readdirP = promisify(readdir);

async function myAsyncFn(path) {
    let entries = await readdirP(path);
    return entries;
}

How to add an image to the emulator gallery in android studio?

Although you can have logat on a real device too, if you need to use an emulator try transferring the images through the Android Device Monitor, accessible from the toolbar in Android Studio (it's in eclipse too, of course).

Once you select the device from ADM, you can see the folders tree and copy things inside

How to check if input file is empty in jQuery

Just check the length of files property, which is a FileList object contained on the input element

if( document.getElementById("videoUploadFile").files.length == 0 ){
    console.log("no files selected");
}

How could I put a border on my grid control in WPF?

I think your problem is that the margin should be specified in the border tag and not in the grid.

Warning comparison between pointer and integer

In this line ...

if (*message == "\0") {

... as you can see in the warning ...

warning: comparison between pointer and integer
      ('int' and 'char *')

... you are actually comparing an int with a char *, or more specifically, an int with an address to a char.

To fix this, use one of the following:

if(*message == '\0') ...
if(message[0] == '\0') ...
if(!*message) ...

On a side note, if you'd like to compare strings you should use strcmp or strncmp, found in string.h.

read file in classpath

Try getting Spring to inject it, assuming you're using Spring as a dependency-injection framework.

In your class, do something like this:

public void setSqlResource(Resource sqlResource) {
    this.sqlResource = sqlResource;
}

And then in your application context file, in the bean definition, just set a property:

<bean id="someBean" class="...">
    <property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>

And Spring should be clever enough to load up the file from the classpath and give it to your bean as a resource.

You could also look into PropertyPlaceholderConfigurer, and store all your SQL in property files and just inject each one separately where needed. There are lots of options.

How to create EditText with rounded corners?

Just to add to the other answers, I found that the simplest solution to achieve the rounded corners was to set the following as a background to your Edittext.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="@android:color/white"/>
    <corners android:radius="8dp"/>

</shape>

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

Move the -h and specify that mydir is a directory

attrib /S /D /L -H mydir\*.*

Get and set position with jQuery .offset()

//Get
var p = $("#elementId");
var offset = p.offset();

//set
$("#secondElementId").offset({ top: offset.top, left: offset.left});

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

ImportError: Couldn't import Django

  1. Check that you have installed Django; by executing import django in python. you mustn't see ModuleNotFoundError if everything's ok.

  2. Check that you have installed virtualenv; by executing virtualenv --version. you must see the version number if everything's ok.

  3. Check that you have enabled virtualenv; there's got to be the name of your virtualenv in your command prompt starting line. enable it by source bin/activate. also, remember to deactivate it every time your job is finished with the virtualenv.

    my terminal changes after enabling virtualenv

  4. Check that your virtualenv includes django. a virtualenv by default has no modules installed. you either have to install django in your virtualenv (even if you have it in your machine already) or use virtualenv --system-site-packages when creating a virtualenv to include system site packages in the virtualenv.

  5. Add django to your path. open python, import django, then run django to see django's path. then add it to your ~/.bashrc (or ~/.zshrc if you're using zsh). more info in here

  6. Install django-admin by running pip install django-admin

Can I apply the required attribute to <select> fields in HTML5?

Make the value of first item of selection box to blank.

So when every you post the FORM you get blank value and using this way you would know that user hasn't selected anything from dropdown.

<select name="user_role" required>
    <option value="">-Select-</option>
    <option value="User">User</option>
    <option value="Admin">Admin</option>
</select>

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

trigger('submit') does not work.beacuse onSubmit method does not get fired. the following code works for me, call onSubmit method when using this code :

$("form").find(':submit').click();

Git push error: "origin does not appear to be a git repository"

my case was a little different - unintentionally I have changed owner of git repository (project.git directory in my case), changing owner back to the git user helped

What is the difference between AF_INET and PF_INET in socket programming?

AF_INET = Address Format, Internet = IP Addresses

PF_INET = Packet Format, Internet = IP, TCP/IP or UDP/IP

AF_INET is the address family that is used for the socket you're creating (in this case an Internet Protocol address). The Linux kernel, for example, supports 29 other address families such as UNIX sockets and IPX, and also communications with IRDA and Bluetooth (AF_IRDA and AF_BLUETOOTH, but it is doubtful you'll use these at such a low level).

For the most part sticking with AF_INET for socket programming over a network is the safest option.

Meaning, AF_INET refers to addresses from the internet, IP addresses specifically.

PF_INET refers to anything in the protocol, usually sockets/ports.

jQuery: Check if div with certain class name exists

Here is a solution without using Jquery

var hasClass = element.classList.contains('class name to search');
// hasClass is boolean
if(hasClass === true)
{
     // Class exists
}

reference link

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

In order to complete BlueM's accepted answer, you can desactivate it here:

Tools > Options > Debugging > General Output Settings > Thread Exit Messages : Off

Getting selected value of a combobox

You are getting NullReferenceExeption because of you are using the cmb.SelectedValue which is null. the comboBox doesn't know what is the value of your custom class ComboboxItem, so either do:

ComboboxItem selectedCar = (ComboboxItem)comboBox2.SelectedItem;
int selecteVal = Convert.ToInt32(selectedCar.Value);

Or better of is use data binding like:

ComboboxItem item1 = new ComboboxItem();
item1.Text = "test";
item1.Value = "123";

ComboboxItem item2 = new ComboboxItem();
item2.Text = "test2";
item2.Value = "456";

List<ComboboxItem> items = new List<ComboboxItem> { item1, item2 };

this.comboBox1.DisplayMember = "Text";
this.comboBox1.ValueMember = "Value";
this.comboBox1.DataSource = items;

Is it possible to log all HTTP request headers with Apache?

mod_log_forensic is what you want, but it may not be included/available with your Apache install by default.

Here is how to use it.

LoadModule log_forensic_module /usr/lib64/httpd/modules/mod_log_forensic.so 
<IfModule log_forensic_module> 
ForensicLog /var/log/httpd/forensic_log 
</IfModule> 

Can I call a base class's virtual function if I'm overriding it?

The C++ syntax is like this:

class Bar : public Foo {
  // ...

  void printStuff() {
    Foo::printStuff(); // calls base class' function
  }
};

How can one see content of stack with GDB?

info frame to show the stack frame info

To read the memory at given addresses you should take a look at x

x/x $esp for hex x/d $esp for signed x/u $esp for unsigned etc. x uses the format syntax, you could also take a look at the current instruction via x/i $eip etc.

spring data jpa @query and pageable

Considering that the UrnMapping class is mapped to the internal_uddi table, I would suggest this:

@Repository
public interface UrnMappingRepository extends JpaRepository<UrnMapping, Long> {

    @Query(value = "select iu from UrnMapping iu where iu.urn like %:text% or iu.contact like %:text%")
    Page<UrnMapping> fullTextSearch(@Param("text") String text, Pageable pageable);
}

Please note that you might have to turn off native queries with dynamic requests.

Using success/error/finally/catch with Promises in AngularJS

Promises are an abstraction over statements that allow us to express ourselves synchronously with asynchronous code. They represent a execution of a one time task.

They also provide exception handling, just like normal code, you can return from a promise or you can throw.

What you'd want in synchronous code is:

try{
  try{
      var res = $http.getSync("url");
      res = someProcessingOf(res);
  } catch (e) {
      console.log("Got an error!",e);
      throw e; // rethrow to not marked as handled
  }
  // do more stuff with res
} catch (e){
     // handle errors in processing or in error.
}

The promisified version is very similar:

$http.get("url").
then(someProcessingOf).
catch(function(e){
   console.log("got an error in initial processing",e);
   throw e; // rethrow to not marked as handled, 
            // in $q it's better to `return $q.reject(e)` here
}).then(function(res){
    // do more stuff
}).catch(function(e){
    // handle errors in processing or in error.
});

Combining "LIKE" and "IN" for SQL Server

No, you will have to use OR to combine your LIKE statements:

SELECT 
   * 
FROM 
   table
WHERE 
   column LIKE 'Text%' OR 
   column LIKE 'Link%' OR 
   column LIKE 'Hello%' OR
   column LIKE '%World%'

Have you looked at Full-Text Search?

How to disable Google asking permission to regularly check installed apps on my phone?

On Android 5.1 Lollipop for my device, click on the Google Settings icon > Security > Scan device for security threats .

Note that Google Settings is separated from the Settings app itself.

PHP - Get array value with a numeric index

Yes, for scalar values, a combination of implode and array_slice will do:

$bar = implode(array_slice($array, 0, 1));
$bin = implode(array_slice($array, 1, 1));
$ipsum = implode(array_slice($array, 2, 1));

Or mix it up with array_values and list (thanks @nikic) so that it works with all types of values:

list($bar) = array_values(array_slice($array, 0, 1));

Can I set text box to readonly when using Html.TextBoxFor?

In case if you have to apply your custom class you can use

  @Html.TextBoxFor(m => m.Birthday,   new Dictionary<string, object>() { {"readonly", "true"}, {"class", "commonField"} } )

Where are

commonField is CSS class

and Birthday could be string field that you probably can use to keep jQuery Datapicker date :)

<script>
             $(function () {
                 $("#Birthday").datepicker({

                 });
             });
  </script>

That's a real life example.

Concatenate a NumPy array to another NumPy array

Actually one can always create an ordinary list of numpy arrays and convert it later.

In [1]: import numpy as np

In [2]: a = np.array([[1,2],[3,4]])

In [3]: b = np.array([[1,2],[3,4]])

In [4]: l = [a]

In [5]: l.append(b)

In [6]: l = np.array(l)

In [7]: l.shape
Out[7]: (2, 2, 2)

In [8]: l
Out[8]: 
array([[[1, 2],
        [3, 4]],

       [[1, 2],
        [3, 4]]])

SQL: how to select a single id ("row") that meets multiple criteria from a single column

Users who have one of the 3 countries

SELECT DISTINCT user_id
FROM table
WHERE ancestry IN('England','France','Germany')

Users who have all 3 countries

SELECT DISTINCT A.userID
FROM table A
   INNER JOIN table B on A.user_id = B.user_id
   INNER JOIN table C on A.user_id = C.user_id
WHERE A.ancestry = 'England'
   AND B.ancestry = 'Germany'
   AND C.ancestry = 'France'

I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

range() can only work with integers, but dividing with the / operator always results in a float value:

>>> 450 / 10
45.0
>>> range(450 / 10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer

Make the value an integer again:

for i in range(int(c / 10)):

or use the // floor division operator:

for i in range(c // 10):

document .click function for touch device

touchstart or touchend are not good, because if you scroll the page, the device do stuff. So, if I want close a window with tap or click outside the element, and scroll the window, I've done:

$(document).on('touchstart', function() {
    documentClick = true;
});
$(document).on('touchmove', function() {
    documentClick = false;
});
$(document).on('click touchend', function(event) {
    if (event.type == "click") documentClick = true;
    if (documentClick){
        doStuff();
    }
 });

Convert a timedelta to days, hours and minutes

I used the following:

delta = timedelta()
totalMinute, second = divmod(delta.seconds, 60)
hour, minute = divmod(totalMinute, 60)
print(f"{hour}h{minute:02}m{second:02}s")

jQuery check if <input> exists and has a value

You can create your own custom selector :hasValue and then use that to find, filter, or test any other jQuery elements.

jQuery.expr[':'].hasValue = function(el,index,match) {
  return el.value != "";
};

Then you can find elements like this:

var data = $("form input:hasValue").serialize();

Or test the current element with .is()

var elHasValue = $("#name").is(":hasValue");

_x000D_
_x000D_
jQuery.expr[':'].hasValue = function(el) {_x000D_
  return el.value != "";_x000D_
};_x000D_
_x000D_
_x000D_
var data = $("form input:hasValue").serialize();_x000D_
console.log(data)_x000D_
_x000D_
_x000D_
var elHasValue = $("[name='LastName']").is(":hasValue");_x000D_
console.log(elHasValue)
_x000D_
label { display: block; margin-top:10px; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<form>_x000D_
  <label>_x000D_
    First Name:_x000D_
    <input type="text" name="FirstName" value="Frida" />_x000D_
  </label>_x000D_
_x000D_
  <label>_x000D_
    Last Name:_x000D_
    <input type="text" name="LastName" />_x000D_
  </label>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Further Reading:

Groovy executing shell commands

Ok, solved it myself;

def sout = new StringBuilder(), serr = new StringBuilder()
def proc = 'ls /badDir'.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout\nerr> $serr"

displays:

out> err> ls: cannot access /badDir: No such file or directory

AWS ssh access 'Permission denied (publickey)' issue

this worked for me:

ssh-keygen -R <server_IP>

to delete the old keys stored on the workstation also works with instead of

then doing the same ssh again it worked:

ssh -v -i <your_pem_file> ubuntu@<server_IP>

on ubuntu instances the username is: ubuntu on Amazon Linux AMI the username is: ec2-user

I didn't have to re-create the instance from an image.

Docker Error bind: address already in use

I upgraded my docker this afternoon and ran into the same problem. I tried restarting docker but no luck.

Finally, I had to restart my computer and it worked. Definitely a bug.

Access the css ":after" selector with jQuery

You can't manipulate :after, because it's not technically part of the DOM and therefore is inaccessible by any JavaScript. But you can add a new class with a new :after specified.

CSS:

.pageMenu .active.changed:after { 
/* this selector is more specific, so it takes precedence over the other :after */
    border-top-width: 22px;
    border-left-width: 22px;
    border-right-width: 22px;
}

JS:

$('.pageMenu .active').toggleClass('changed');

UPDATE: while it's impossible to directly modify the :after content, there are ways to read and/or override it using JavaScript. See "Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)" for a comprehensive list of techniques.

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone http://svn.example.com/project -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone http://svn.example.com/project --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url = http://svn.example.com/project/branches/mybranch
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!


Further information

You may also be interested in reading an answer to a related question.

SVN Repository Search

If you're really desperate, do a dump of the repo (look at "svnadmin dump") and then grep through it. It's not pretty, but you can look around the search results to find the metadata that indicates the file and revision, then check it out for a better look.

Not a good solution, to be sure, but it is free :) SVN provides no feature for searching past checkins (or even past log files, AFAIK).

Unable to begin a distributed transaction

Apart from the security settings, I had to open some ports on both servers for the transaction to run. I had to open port 59640 but according to the following suggestion, port 135 has to be open. http://support.microsoft.com/kb/839279

Create html documentation for C# code

Doxygen or Sandcastle help file builder are the primary tools that will extract XML documentation into HTML (and other forms) of external documentation.

Note that you can combine these documentation exporters with documentation generators - as you've discovered, Resharper has some rudimentary helpers, but there are also much more advanced tools to do this specific task, such as GhostDoc (for C#/VB code with XML documentation) or my addin Atomineer Pro Documentation (for C#, C++/CLI, C++, C, VB, Java, JavaScript, TypeScript, JScript, PHP, Unrealscript code containing XML, Doxygen, JavaDoc or Qt documentation).

Getting rid of \n when using .readlines()

I recently used this to read all the lines from a file:

alist = open('maze.txt').read().split()

or you can use this for that little bit of extra added safety:

with f as open('maze.txt'):
    alist = f.read().split()

It doesn't work with whitespace in-between text in a single line, but it looks like your example file might not have whitespace splitting the values. It is a simple solution and it returns an accurate list of values, and does not add an empty string: '' for every empty line, such as a newline at the end of the file.

Text overwrite in visual studio 2010

press your keyboard Insert Key

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

For some people, the accepted answer is not working, I found this other answer and it is working for me: How can I pass a parameter to a setTimeout() callback?

var hello = "Hello World";
setTimeout(alert, 1000, hello); 

'hello' is the parameter being passed, you can pass all the parameters after the timeout time. Thanks to @Fabio Phms for the answer.

Can a website detect when you are using Selenium with chromedriver?

It sounds like they are behind a web application firewall. Take a look at modsecurity and OWASP to see how those work.

In reality, what you are asking is how to do bot detection evasion. That is not what Selenium WebDriver is for. It is for testing your web application not hitting other web applications. It is possible, but basically, you'd have to look at what a WAF looks for in their rule set and specifically avoid it with selenium if you can. Even then, it might still not work because you don't know what WAF they are using.

You did the right first step, that is, faking the user agent. If that didn't work though, then a WAF is in place and you probably need to get more tricky.

Point taken from other answer. Make sure your user agent is actually being set correctly first. Maybe have it hit a local web server or sniff the traffic going out.

WCF service maxReceivedMessageSize basicHttpBinding issue

When using HTTPS instead of ON the binding, put it IN the binding with the httpsTransport tag:

    <binding name="MyServiceBinding">
      <security defaultAlgorithmSuite="Basic256Rsa15" 
                authenticationMode="MutualCertificate" requireDerivedKeys="true" 
                securityHeaderLayout="Lax" includeTimestamp="true" 
                messageProtectionOrder="SignBeforeEncrypt" 
                messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
                requireSignatureConfirmation="false">
        <localClientSettings detectReplays="true" />
        <localServiceSettings detectReplays="true" />
        <secureConversationBootstrap keyEntropyMode="CombinedEntropy" />
      </security>
      <textMessageEncoding messageVersion="Soap11WSAddressing10">
        <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" 
                      maxArrayLength="2147483647" maxBytesPerRead="4096" 
                      maxNameTableCharCount="16384"/>
      </textMessageEncoding>
      <httpsTransport maxReceivedMessageSize="2147483647" 
                      maxBufferSize="2147483647" maxBufferPoolSize="2147483647" 
                      requireClientCertificate="false" />
    </binding>

MySQL "WITH" clause

You've got the syntax right:

WITH AuthorRating(AuthorName, AuthorRating) AS
   SELECT aname         AS AuthorName,
          AVG(quantity) AS AuthorRating
   FROM Book
   GROUP By Book.aname

However, as others have mentioned, MySQL does not support this command. WITH was added in SQL:1999; the newest version of the SQL standard is SQL:2008. You can find some more information about databases that support SQL:1999's various features on Wikipedia.

MySQL has traditionally lagged a bit in support for the SQL standard, whereas commercial databases like Oracle, SQL Server (recently), and DB2 have followed them a bit more closely. PostgreSQL is typically pretty standards compliant as well.

You may want to look at MySQL's roadmap; I'm not completely sure when this feature might be supported, but it's great for creating readable roll-up queries.

How do I extract data from a DataTable?

The DataTable has a collection .Rows of DataRow elements.

Each DataRow corresponds to one row in your database, and contains a collection of columns.

In order to access a single value, do something like this:

 foreach(DataRow row in YourDataTable.Rows)
 { 
     string name = row["name"].ToString();
     string description = row["description"].ToString();
     string icoFileName = row["iconFile"].ToString();
     string installScript = row["installScript"].ToString();
 }

Redirect HTTP to HTTPS on default virtual host without ServerName

Try adding this in your vhost config:

RewriteEngine On
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [R=301,L]

How do you push a tag to a remote repository using Git?

I am using git push <remote-name> tag <tag-name> to ensure that I am pushing a tag. I use it like: git push origin tag v1.0.1. This pattern is based upon the documentation (man git-push):

OPTIONS
   ...
   <refspec>...
       ...
       tag <tag> means the same as refs/tags/<tag>:refs/tags/<tag>.

How to negate 'isblank' function

I suggest:

=not(isblank(A1))  

which returns TRUE if A1 is populated and FALSE otherwise. Which compares with:

=isblank(A1)  

which returns TRUE if A1 is empty and otherwise FALSE.

How to get child process from parent process

ps -axf | grep parent_pid 

Above command prints respective processes generated from parent_pid, hope it helps. +++++++++++++++++++++++++++++++++++++++++++

root@root:~/chk_prgrm/lp#

 parent...18685

 child... 18686


root@root:~/chk_prgrm/lp# ps axf | grep frk

 18685 pts/45   R      0:11  |       \_ ./frk

 18686 pts/45   R      0:11  |       |   \_ ./frk

 18688 pts/45   S+     0:00  |       \_ grep frk

Allow user to select camera or gallery for image

Resolved too big image issue and avoid to out of memory.

    private static final int SELECT_PICTURE = 0;
    private static final int REQUEST_CAMERA = 1;
    private ImageView mImageView;

    private void selectImage() {
        final CharSequence[] items = {"Take Photo", "Choose from Library",
                "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment
                            .getExternalStorageDirectory(), "temp.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    startActivityForResult(intent, REQUEST_CAMERA);
                } else if (items[item].equals("Choose from Library")) {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(
                            Intent.createChooser(intent, "Select File"),
                            SELECT_PICTURE);
                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CAMERA) {
                File f = new File(Environment.getExternalStorageDirectory()
                        .toString());
                for (File temp : f.listFiles()) {
                    if (temp.getName().equals("temp.jpg")) {
                        f = temp;
                        break;
                    }
                }
                try {
                    Bitmap bm;
                    BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
                    btmapOptions.inSampleSize = 2;
                    bm = BitmapFactory.decodeFile(f.getAbsolutePath(),
                            btmapOptions);

                    // bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
                    mImageView.setImageBitmap(bm);

                    String path = android.os.Environment
                            .getExternalStorageDirectory()
                            + File.separator
                            + "test";
                    f.delete();
                    OutputStream fOut = null;
                    File file = new File(path, String.valueOf(System
                            .currentTimeMillis()) + ".jpg");
                    fOut = new FileOutputStream(file);
                    bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
                    fOut.flush();
                    fOut.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                String tempPath = getPath(selectedImageUri, this.getActivity());
                Bitmap bm;
                btmapOptions.inSampleSize = 2;
                BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
                bm = BitmapFactory.decodeFile(tempPath, btmapOptions);
                mImageView.setImageBitmap(bm);
            }
        }
    }
    public String getPath(Uri uri, Activity activity) {
        String[] projection = {MediaStore.MediaColumns.DATA};
        Cursor cursor = activity
                .managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

NLTK and Stopwords Fail #lookuperror

You don't seem to have the stopwords corpus on your computer.

You need to start the NLTK Downloader and download all the data you need.

Open a Python console and do the following:

>>> import nltk
>>> nltk.download()
showing info http://nltk.github.com/nltk_data/

In the GUI window that opens simply press the 'Download' button to download all corpora or go to the 'Corpora' tab and only download the ones you need/want.

How to Import .bson file format on mongodb

Run the following from command line and you should be in the Mongo bin directory.

mongorestore -d db_name -c collection_name path/file.bson

Array initialization in Perl

To produce the output in your comment to your post, this will do it:

use strict;
use warnings;

my @other_array = (0,0,0,1,2,2,3,3,3,4);
my @array;
my %uniqs;

$uniqs{$_}++ for @other_array;

foreach (keys %uniqs) { $array[$_]=$uniqs{$_} }

print "array[$_] = $array[$_]\n" for (0..$#array);

Output:

   array[0] = 3
   array[1] = 1
   array[2] = 2
   array[3] = 3
   array[4] = 1

This is different than your stated algorithm of producing a parallel array with zero values, but it is a more Perly way of doing it...

If you must have a parallel array that is the same size as your first array with the elements initialized to 0, this statement will dynamically do it: @array=(0) x scalar(@other_array); but really, you don't need to do that.

how to configure apache server to talk to HTTPS backend server?

In my case, my server was configured to work only in https mode, and error occured when I try to access http mode. So changing http://my-service to https://my-service helped.

How to get the width of a react element

With hooks:

const MyComponent = () => {
  const ref = useRef(null);
  useEffect(() => {
    console.log('width', ref.current ? ref.current.offsetWidth : 0);
  }, [ref.current]);
  return <div ref={ref}>Hello</div>;
};

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

If you are not worried about an unbounded queue of Callable/Runnable tasks, you can use one of them. As suggested by bruno, I too prefer newFixedThreadPool to newCachedThreadPool over these two.

But ThreadPoolExecutor provides more flexible features compared to either newFixedThreadPool or newCachedThreadPool

ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, 
TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory,
RejectedExecutionHandler handler)

Advantages:

  1. You have full control of BlockingQueue size. It's not un-bounded, unlike the earlier two options. I won't get an out of memory error due to a huge pile-up of pending Callable/Runnable tasks when there is unexpected turbulence in the system.

  2. You can implement custom Rejection handling policy OR use one of the policies:

    1. In the default ThreadPoolExecutor.AbortPolicy, the handler throws a runtime RejectedExecutionException upon rejection.

    2. In ThreadPoolExecutor.CallerRunsPolicy, the thread that invokes execute itself runs the task. This provides a simple feedback control mechanism that will slow down the rate that new tasks are submitted.

    3. In ThreadPoolExecutor.DiscardPolicy, a task that cannot be executed is simply dropped.

    4. In ThreadPoolExecutor.DiscardOldestPolicy, if the executor is not shut down, the task at the head of the work queue is dropped, and then execution is retried (which can fail again, causing this to be repeated.)

  3. You can implement a custom Thread factory for the below use cases:

    1. To set a more descriptive thread name
    2. To set thread daemon status
    3. To set thread priority