Programs & Examples On #Decoding

Decoding is the reverse of encoding.

How can I send and receive WebSocket messages on the server side?

Thank you for the answer, i would like to add onto hfern's(above) Python version to include the Sending function if any one is interested.

def DecodedWebsockRecieve(stringStreamIn):
    byteArray =  stringStreamIn 
    datalength = byteArray[1] & 127
    indexFirstMask = 2 
    if datalength == 126:
        indexFirstMask = 4
    elif datalength == 127:
        indexFirstMask = 10
    masks = [m for m in byteArray[indexFirstMask : indexFirstMask+4]]
    indexFirstDataByte = indexFirstMask + 4
    decodedChars = []
    i = indexFirstDataByte
    j = 0
    while i < len(byteArray):
        decodedChars.append( chr(byteArray[i] ^ masks[j % 4]) )
        i += 1
        j += 1
    return ''.join(decodedChars)

def EncodeWebSockSend(socket,data):
    bytesFormatted = []
    bytesFormatted.append(129)

    bytesRaw = data.encode()
    bytesLength = len(bytesRaw)
    if bytesLength <= 125 :
        bytesFormatted.append(bytesLength)
    elif bytesLength >= 126 and bytesLength <= 65535 :
        bytesFormatted.append(126)
        bytesFormatted.append( ( bytesLength >> 8 ) & 255 )
        bytesFormatted.append( bytesLength & 255 )
    else :
        bytesFormatted.append( 127 )
        bytesFormatted.append( ( bytesLength >> 56 ) & 255 )
        bytesFormatted.append( ( bytesLength >> 48 ) & 255 )
        bytesFormatted.append( ( bytesLength >> 40 ) & 255 )
        bytesFormatted.append( ( bytesLength >> 32 ) & 255 )
        bytesFormatted.append( ( bytesLength >> 24 ) & 255 )
        bytesFormatted.append( ( bytesLength >> 16 ) & 255 )
        bytesFormatted.append( ( bytesLength >>  8 ) & 255 )
        bytesFormatted.append( bytesLength & 255 )

    bytesFormatted = bytes(bytesFormatted)
    bytesFormatted = bytesFormatted + bytesRaw
    socket.send(bytesFormatted) 

Usage for reading:

bufSize = 1024     
read = DecodedWebsockRecieve(socket.recv(bufSize))

Usage for writing:

EncodeWebSockSend(sock,"hellooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo")

How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

print_r(json_decode('{"t":"\u00ed"}')); // -> stdClass Object ( [t] => í )

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

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

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

For Node.js v5.11.1 and below

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

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

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

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

How do I draw a set of vertical lines in gnuplot?

alternatively you can also do this:

p '< echo "x y"' w impulse

x and y are the coordinates of the point to which you draw a vertical bar

Make: how to continue after a command fails?

Change your clean so rm will not complain:

clean:
    rm -f .lambda .lambda_t .activity .activity_t_lambda

Classpath including JAR within a JAR

Not without writing your own class loader. You can add jars to the jar's classpath, but they must be co-located, not contained in the main jar.

Using LINQ to concatenate strings

I always use the extension method:

public static string JoinAsString<T>(this IEnumerable<T> input, string seperator)
{
    var ar = input.Select(i => i.ToString());
    return string.Join(seperator, ar);
}

Which .NET Dependency Injection frameworks are worth looking into?

It depends on what you are looking for, as they each have their pros and cons.

  1. Spring.NET is the most mature as it comes out of Spring from the Java world. Spring has a very rich set of framework libraries that extend it to support Web, Windows, etc.
  2. Castle Windsor is one of the most widely used in the .NET platform and has the largest ecosystem, is highly configurable / extensible, has custom lifetime management, AOP support, has inherent NHibernate support and is an all around awesome container. Windsor is part of an entire stack which includes Monorail, Active Record, etc. NHibernate itself builds on top of Windsor.
  3. Structure Map has very rich and fine grained configuration through an internal DSL.
  4. Autofac is an IoC container of the new age with all of it's inherent functional programming support. It also takes a different approach on managing lifetime than the others. Autofac is still very new, but it pushes the bar on what is possible with IoC.
  5. Ninject I have heard is more bare bones with a less is more approach (heard not experienced).
  6. The biggest discriminator of Unity is: it's from and supported by Microsoft (p&p). Unity has very good performance, and great documentation. It is also highly configurable. It doesn't have all the bells and whistles of say Castle / Structure Map.

So in summary, it really depends on what is important to you. I would agree with others on going and evaluating and seeing which one fits. The nice thing is you have a nice selection of donuts rather than just having to have a jelly one.

LINQ to SQL Left Outer Join

Public Sub LinqToSqlJoin07()
Dim q = From e In db.Employees _
        Group Join o In db.Orders On e Equals o.Employee Into ords = Group _
        From o In ords.DefaultIfEmpty _
        Select New With {e.FirstName, e.LastName, .Order = o}

ObjectDumper.Write(q) End Sub

Check http://msdn.microsoft.com/en-us/vbasic/bb737929.aspx

how to declare global variable in SQL Server..?

You could try a global table:

create table ##global_var
            (var1 int
            ,var2 int)

USE "DB_1"
GO
SELECT * FROM "TABLE" WHERE "COL_!" = (select var1 from ##global_var) 

AND "COL_2" = @GLOBAL_VAR_2

USE "DB_2"
GO

SELECT * FROM "TABLE" WHERE "COL_!" = (select var2 from ##global_var) 

Is it possible to decrypt MD5 hashes?

MD5 has its weaknesses (see Wikipedia), so there are some projects, which try to precompute Hashes. Wikipedia does also hint at some of these projects. One I know of (and respect) is ophrack. You can not tell the user their own password, but you might be able to tell them a password that works. But i think: Just mail thrm a new password in case they forgot.

Place a button right aligned

Another possibility is to use an absolute positioning oriented to the right. You can do it this way:

style="position: absolute; right: 0;"

Efficiently sorting a numpy array in descending order?

You could sort the array first (Ascending by default) and then apply np.flip() (https://docs.scipy.org/doc/numpy/reference/generated/numpy.flip.html)

FYI It works with datetime objects as well.

Example:

    x = np.array([2,3,1,0]) 
    x_sort_asc=np.sort(x) 
    print(x_sort_asc)

    >>> array([0, 1, 2, 3])

    x_sort_desc=np.flip(x_sort_asc) 
    print(x_sort_desc)

    >>> array([3,2,1,0])

Unsupported major.minor version 52.0

If you're using the NetBeans IDE, right click on the project and choose Properties and go to sources, and you can change the Source/Binary Format to a lower JDK version.

Enter image description here

Laravel 5 How to switch from Production mode

What you could also have a look at is the exposed method Application->loadEnvironmentFrom($file)

I needed one application to run on multiple subdomains. So in bootstrap/app.php I added something like:

$envFile = '.env';
// change $envFile conditionally here
$app->loadEnvironmentFrom($envFile);

How to disable the back button in the browser using JavaScript

history.pushState(null, null, document.title);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.title);
});

This script will overwrite attempts to navigate back and forth with the state of the current page.


Update:

Some users have reported better success with using document.URL instead of document.title:

history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.URL);
});

Hard reset of a single file

You can use the following command:

git reset -- my-file.txt

which will update both the working copy of my-file.txt when added.

private constructor

For example, you can invoke a private constructor inside a friend class or a friend function.

Singleton pattern usually uses it to make sure that nobody creates more instances of the intended type.

how to get 2 digits after decimal point in tsql?

Try cast result to numeric

CAST(sum(cast(datediff(second, IEC.CREATE_DATE, IEC.STATUS_DATE) as float) / 60)
    AS numeric(10,2)) TotalSentMinutes

Input

1
2
3

Output

1.00
2.00
3.00

How do I exclude Weekend days in a SQL Server query?

Try the DATENAME() function:

select [date_created]
from table
where DATENAME(WEEKDAY, [date_created]) <> 'Saturday'
  and DATENAME(WEEKDAY, [date_created]) <> 'Sunday'

'"SDL.h" no such file or directory found' when compiling

If the header file is /usr/include/sdl/SDL.h and your code has:

#include "SDL.h"

You need to either fix your code:

#include "sdl/SDL.h"

Or tell the preprocessor where to find include files:

CFLAGS = ... -I/usr/include/sdl ...

Count number of occurences for each unique value

table() function is a good way to go, as Chase suggested. If you are analyzing a large dataset, an alternative way is to use .N function in datatable package.

Make sure you installed the data table package by

install.packages("data.table")

Code:

# Import the data.table package
library(data.table)

# Generate a data table object, which draws a number 10^7 times  
# from 1 to 10 with replacement
DT<-data.table(x=sample(1:10,1E7,TRUE))

# Count Frequency of each factor level
DT[,.N,by=x]

How can I exclude all "permission denied" messages from "find"?

Those errors are printed out to the standard error output (fd 2). To filter them out, simply redirect all errors to /dev/null:

find . 2>/dev/null > some_file

or first join stderr and stdout and then grep out those specific errors:

find . 2>&1 | grep -v 'Permission denied' > some_file

How to get history on react-router v4?

This works! https://reacttraining.com/react-router/web/api/withRouter

import { withRouter } from 'react-router-dom';

class MyComponent extends React.Component {
  render () {
    this.props.history;
  }
}

withRouter(MyComponent);

ng serve not detecting file changes automatically

I had the same issue and figured out, that some files in my Angular Project were only permitted to the user root and to the corresponding group root. You can check that with ls -hal. I fixed it by setting both to the user I used the system with.

You can do that with: chown -R username:groupname *

If you want to know what exactly this command does, checkout:

https://superuser.com/questions/462141/how-to-chown-chmod-all-files-in-current-directory

How to extract multiple JSON objects from one file?

Added streaming support based on the answer of @dunes:

import re
from json import JSONDecoder, JSONDecodeError

NOT_WHITESPACE = re.compile(r"[^\s]")


def stream_json(file_obj, buf_size=1024, decoder=JSONDecoder()):
    buf = ""
    ex = None
    while True:
        block = file_obj.read(buf_size)
        if not block:
            break
        buf += block
        pos = 0
        while True:
            match = NOT_WHITESPACE.search(buf, pos)
            if not match:
                break
            pos = match.start()
            try:
                obj, pos = decoder.raw_decode(buf, pos)
            except JSONDecodeError as e:
                ex = e
                break
            else:
                ex = None
                yield obj
        buf = buf[pos:]
    if ex is not None:
        raise ex

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

Paste this on your command line:

export LC_CTYPE="en_US.UTF-8" 

uint8_t vs unsigned char

Just to be pedantic, some systems may not have an 8 bit type. According to Wikipedia:

An implementation is required to define exact-width integer types for N = 8, 16, 32, or 64 if and only if it has any type that meets the requirements. It is not required to define them for any other N, even if it supports the appropriate types.

So uint8_t isn't guaranteed to exist, though it will for all platforms where 8 bits = 1 byte. Some embedded platforms may be different, but that's getting very rare. Some systems may define char types to be 16 bits, in which case there probably won't be an 8-bit type of any kind.

Other than that (minor) issue, @Mark Ransom's answer is the best in my opinion. Use the one that most clearly shows what you're using the data for.

Also, I'm assuming you meant uint8_t (the standard typedef from C99 provided in the stdint.h header) rather than uint_8 (not part of any standard).

Combining border-top,border-right,border-left,border-bottom in CSS

No, you cannot set them all in a single statement.
At the general case, you need at least three properties:

border-color: red green white blue;
border-style: solid dashed dotted solid;
border-width: 1px 2px 3px 4px;

However, that would be quite messy. It would be more readable and maintainable with four:

border-top:    1px solid  #ff0;
border-right:  2px dashed #f0F;
border-bottom: 3px dotted #f00;
border-left:   5px solid  #09f;

Determine if a String is an Integer in Java

Using regular expression is better.

str.matches("-?\\d+");


-?     --> negative sign, could have none or one
\\d+   --> one or more digits

It is not good to use NumberFormatException here if you can use if-statement instead.


If you don't want leading zero's, you can just use the regular expression as follow:

str.matches("-?(0|[1-9]\\d*)");

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

If you can use a C++ compiler to build the object file that you want to contain your version string, then we can do exactly what you want! The only magic here is that C++ allows you to use expressions to statically initialize an array, while C doesn't. The expressions need to be fully computable at compile time, but these expressions are, so it's no problem.

We build up the version string one byte at a time, and get exactly what we want.

// source file version_num.h

#ifndef VERSION_NUM_H

#define VERSION_NUM_H


#define VERSION_MAJOR 1
#define VERSION_MINOR 4


#endif // VERSION_NUM_H

// source file build_defs.h

#ifndef BUILD_DEFS_H

#define BUILD_DEFS_H


// Example of __DATE__ string: "Jul 27 2012"
//                              01234567890

#define BUILD_YEAR_CH0 (__DATE__[ 7])
#define BUILD_YEAR_CH1 (__DATE__[ 8])
#define BUILD_YEAR_CH2 (__DATE__[ 9])
#define BUILD_YEAR_CH3 (__DATE__[10])


#define BUILD_MONTH_IS_JAN (__DATE__[0] == 'J' && __DATE__[1] == 'a' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_FEB (__DATE__[0] == 'F')
#define BUILD_MONTH_IS_MAR (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'r')
#define BUILD_MONTH_IS_APR (__DATE__[0] == 'A' && __DATE__[1] == 'p')
#define BUILD_MONTH_IS_MAY (__DATE__[0] == 'M' && __DATE__[1] == 'a' && __DATE__[2] == 'y')
#define BUILD_MONTH_IS_JUN (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'n')
#define BUILD_MONTH_IS_JUL (__DATE__[0] == 'J' && __DATE__[1] == 'u' && __DATE__[2] == 'l')
#define BUILD_MONTH_IS_AUG (__DATE__[0] == 'A' && __DATE__[1] == 'u')
#define BUILD_MONTH_IS_SEP (__DATE__[0] == 'S')
#define BUILD_MONTH_IS_OCT (__DATE__[0] == 'O')
#define BUILD_MONTH_IS_NOV (__DATE__[0] == 'N')
#define BUILD_MONTH_IS_DEC (__DATE__[0] == 'D')


#define BUILD_MONTH_CH0 \
    ((BUILD_MONTH_IS_OCT || BUILD_MONTH_IS_NOV || BUILD_MONTH_IS_DEC) ? '1' : '0')

#define BUILD_MONTH_CH1 \
    ( \
        (BUILD_MONTH_IS_JAN) ? '1' : \
        (BUILD_MONTH_IS_FEB) ? '2' : \
        (BUILD_MONTH_IS_MAR) ? '3' : \
        (BUILD_MONTH_IS_APR) ? '4' : \
        (BUILD_MONTH_IS_MAY) ? '5' : \
        (BUILD_MONTH_IS_JUN) ? '6' : \
        (BUILD_MONTH_IS_JUL) ? '7' : \
        (BUILD_MONTH_IS_AUG) ? '8' : \
        (BUILD_MONTH_IS_SEP) ? '9' : \
        (BUILD_MONTH_IS_OCT) ? '0' : \
        (BUILD_MONTH_IS_NOV) ? '1' : \
        (BUILD_MONTH_IS_DEC) ? '2' : \
        /* error default */    '?' \
    )

#define BUILD_DAY_CH0 ((__DATE__[4] >= '0') ? (__DATE__[4]) : '0')
#define BUILD_DAY_CH1 (__DATE__[ 5])



// Example of __TIME__ string: "21:06:19"
//                              01234567

#define BUILD_HOUR_CH0 (__TIME__[0])
#define BUILD_HOUR_CH1 (__TIME__[1])

#define BUILD_MIN_CH0 (__TIME__[3])
#define BUILD_MIN_CH1 (__TIME__[4])

#define BUILD_SEC_CH0 (__TIME__[6])
#define BUILD_SEC_CH1 (__TIME__[7])


#if VERSION_MAJOR > 100

#define VERSION_MAJOR_INIT \
    ((VERSION_MAJOR / 100) + '0'), \
    (((VERSION_MAJOR % 100) / 10) + '0'), \
    ((VERSION_MAJOR % 10) + '0')

#elif VERSION_MAJOR > 10

#define VERSION_MAJOR_INIT \
    ((VERSION_MAJOR / 10) + '0'), \
    ((VERSION_MAJOR % 10) + '0')

#else

#define VERSION_MAJOR_INIT \
    (VERSION_MAJOR + '0')

#endif

#if VERSION_MINOR > 100

#define VERSION_MINOR_INIT \
    ((VERSION_MINOR / 100) + '0'), \
    (((VERSION_MINOR % 100) / 10) + '0'), \
    ((VERSION_MINOR % 10) + '0')

#elif VERSION_MINOR > 10

#define VERSION_MINOR_INIT \
    ((VERSION_MINOR / 10) + '0'), \
    ((VERSION_MINOR % 10) + '0')

#else

#define VERSION_MINOR_INIT \
    (VERSION_MINOR + '0')

#endif



#endif // BUILD_DEFS_H

// source file main.c

#include "version_num.h"
#include "build_defs.h"

// want something like: 1.4.1432.2234

const unsigned char completeVersion[] =
{
    VERSION_MAJOR_INIT,
    '.',
    VERSION_MINOR_INIT,
    '-', 'V', '-',
    BUILD_YEAR_CH0, BUILD_YEAR_CH1, BUILD_YEAR_CH2, BUILD_YEAR_CH3,
    '-',
    BUILD_MONTH_CH0, BUILD_MONTH_CH1,
    '-',
    BUILD_DAY_CH0, BUILD_DAY_CH1,
    'T',
    BUILD_HOUR_CH0, BUILD_HOUR_CH1,
    ':',
    BUILD_MIN_CH0, BUILD_MIN_CH1,
    ':',
    BUILD_SEC_CH0, BUILD_SEC_CH1,
    '\0'
};


#include <stdio.h>

int main(int argc, char **argv)
{
    printf("%s\n", completeVersion);
    // prints something similar to: 1.4-V-2013-05-09T15:34:49
}

This isn't exactly the format you asked for, but I still don't fully understand how you want days and hours mapped to an integer. I think it's pretty clear how to make this produce any desired string.

How can I add reflection to a C++ application?

I think you might find interesting the article "Using Templates for Reflection in C++" by Dominic Filion. It is in section 1.4 of Game Programming Gems 5. Unfortunately I dont have my copy with me, but look for it because I think it explains what you are asking for.

Hibernate Annotations - Which is better, field or property access?

Both :

The EJB3 spec requires that you declare annotations on the element type that will be accessed, i.e. the getter method if you use property access, the field if you use field access.

https://docs.jboss.org/hibernate/annotations/3.5/reference/en/html_single/#entity-mapping

RuntimeWarning: invalid value encountered in divide

Python indexing starts at 0 (rather than 1), so your assignment "r[1,:] = r0" defines the second (i.e. index 1) element of r and leaves the first (index 0) element as a pair of zeros. The first value of i in your for loop is 0, so rr gets the square root of the dot product of the first entry in r with itself (which is 0), and the division by rr in the subsequent line throws the error.

Rails: How can I set default values in ActiveRecord?

Although doing that for setting default values is confusing and awkward in most cases, you can use :default_scope as well. Check out squil's comment here.

NoClassDefFoundError - Eclipse and Android

Try this:-

Step 1

Add all the libraries to build pat in Eclipse( means make all libraries referenced libraries)

Step 2

Delete R.java file and again build the project. Don't worry, R.java will automatically get recreated.

Chill :)

Why I'm getting 'Non-static method should not be called statically' when invoking a method in a Eloquent model?

Solution to the original question

You called a non-static method statically. To make a public function static in the model, would look like this:

public static function {
  
}

In General:

Post::get()

In this particular instance:

Post::take(2)->get()

One thing to be careful of, when defining relationships and scope, that I had an issue with that caused a 'non-static method should not be called statically' error is when they are named the same, for example:

public function category(){
    return $this->belongsTo('App\Category');
}

public function scopeCategory(){
    return $query->where('category', 1);
}

When I do the following, I get the non-static error:

Event::category()->get();

The issue, is that Laravel is using my relationship method called category, rather than my category scope (scopeCategory). This can be resolved by renaming the scope or the relationship. I chose to rename the relationship:

public function cat(){
    return $this->belongsTo('App\Category', 'category_id');
}

Please observe that I defined the foreign key (category_id) because otherwise Laravel would have looked for cat_id instead, and it wouldn't have found it, as I had defined it as category_id in the database.

Inner join with 3 tables in mysql

Almost correctly.. Look at the joins, you are referring the wrong fields

SELECT student.firstname,
       student.lastname,
       exam.name,
       exam.date,
       grade.grade
  FROM grade
 INNER JOIN student ON student.studentId = grade.fk_studentId
 INNER JOIN exam ON exam.examId = grade.fk_examId
 ORDER BY exam.date

Turn off display errors using file "php.ini"

Let me quickly summarize this for reference:

  • error_reporting() adapts the currently active setting for the default error handler.

  • Editing the error reporting ini options also changes the defaults.

    • Here it's imperative to edit the correct php.ini version - it's typically /etc/php5/fpm/php.ini on modern servers, /etc/php5/mod_php/php.ini alternatively; while the CLI version has a distinct one.

    • Alternatively you can use depending on SAPI:

      • mod_php: .htaccess with php_flag options
      • FastCGI: commonly a local php.ini
      • And with PHP above 5.3 also a .user.ini

    • Restarting the webserver as usual.

If your code is unwieldy and somehow resets these options elsewhere at runtime, then an alternative and quick way is to define a custom error handler that just slurps all notices/warnings/errors up:

set_error_handler(function(){});

Again, this is not advisable, just an alternative.

How to delete selected text in the vi editor

If you want to delete using line numbers you can use:

:startingline, last line d

Example:

:7,20 d

This example will delete line 7 to 20.

IE7 Z-Index Layering Issues

It looks like not a ie bug, just for diffrent understanding to the css standard. If outside container is not specified the z-index, but the inner element specified a higher z-index. So the container's sibling maybe overlay the high z-index element. Even if like that, it only occurs in IE7, but IE6, IE8 and Firefox is ok.

Excel is not updating cells, options > formula > workbook calculation set to automatic

I had this happen in a worksheet today. Neither F9 nor turning on Iterative Calculation made the cells in question update, but double-clicking the cell and pressing Enter did. I searched the Excel Help and found this in the help article titled Change formula recalculation, iteration, or precision:

CtrlAltF9:
Recalculate all formulas in all open workbooks, regardless of whether they have changed since the last recalculation.

CtrlShiftAltF9:
Check dependent formulas, and then recalculate all formulas in all open workbooks, regardless of whether they have changed since the last recalculation.

So I tried CtrlShiftAltF9, and sure enough, all of my non-recalculating formulas finally recalculated!

What is meaning of negative dbm in signal strength?

At ms end Rx lev ranges 0 to -120 dbm Mean antenna power which received at ms end alway less than 1mW.

Thats why it always -ve.

Is there a way to only install the mysql client (Linux)?

When I now just use the command: mysql

I get: Command 'mysql' not found, but can be installed with:

sudo apt install mysql-client-core-8.0 # version 8.0.22-0ubuntu0.20.04.2, or sudo apt install mariadb-client-core-10.3 # version 1:10.3.25-0ubuntu0.20.04.1

Very helpfull.

Java Reflection: How to get the name of a variable?

It is not possible at all. Variable names aren't communicated within Java (and might also be removed due to compiler optimizations).

EDIT (related to comments):

If you step back from the idea of having to use it as function parameters, here's an alternative (which I wouldn't use - see below):

public void printFieldNames(Object obj, Foo... foos) {
    List<Foo> fooList = Arrays.asList(foos);
    for(Field field : obj.getClass().getFields()) {
         if(fooList.contains(field.get()) {
              System.out.println(field.getName());
         }
    }
}

There will be issues if a == b, a == r, or b == r or there are other fields which have the same references.

EDIT now unnecessary since question got clarified

Is it possible to see more than 65536 rows in Excel 2007?

Excel 2003, doesn't included 1M row features, Introduced in 2007 onwards.

In Excel2007, save as "normal" Excel file, not a backwards compatible one.

You may have to close and re-open Excel to get the full 1M rows

Thilip

How to increase size of DOSBox window?

Looking again at your question, I think I see what's wrong with your conf file. You set:

fullresolution=1366x768 windowresolution=1366x768

That's why you're getting the letterboxing (black on either side). You've essentially told Dosbox that your screen is the same size as your window, but your screen is actually bigger, 1600x900 (or higher) per the Googled specs for that computer. So the 'difference' shows up in black. So you either should change fullresolution to your actual screen resolution, or revert to fullresolution=original default, and only specify the window resolution.

So now I wonder if you really want fullscreen, though your question asks about only a window. For you are getting a window, but you sized it short of your screen, hence the two black stripes (letterboxing). If you really want fullscreen, then you need to specify the actual resolution of your screen. 1366x768 is not big enough.

The next issue is, what's the resolution of the program itself? It won't go past its own resolution. So if the program/game is (natively) say 1280x720 (HD), then your window resolution setting shouldn't be bigger than that (remember, it's fixed not dynamic when you use AxB as windowresolution).

Example: DOS Lotus 123 will only extend eight columns and 20 rows. The bigger the Dosbox, the bigger the text, but not more columns and rows. So setting a higher windowresolution for that, only results in bigger text, not more columns and rows. After that you'll have letterboxing.

Hope this helps you better.

Docker: Multiple Dockerfiles in project

When working on a project that requires the use of multiple dockerfiles, simply create each dockerfile in a separate directory. For instance,

app/ db/

Each of the above directories will contain their dockerfile. When an application is being built, docker will search all directories and build all dockerfiles.

How do you see the entire command history in interactive Python?

If you want to write the history to a file:

import readline
readline.write_history_file('python_history.txt')

The help function gives:

Help on built-in function write_history_file in module readline:

write_history_file(...)
    write_history_file([filename]) -> None
    Save a readline history file.
    The default filename is ~/.history.

illegal use of break statement; javascript

You need to make sure requestAnimFrame stops being called once game == 1. A break statement only exits a traditional loop (e.g. while()).

function loop() {
    if (isPlaying) {
        jet1.draw();
        drawAllEnemies();
        if (game != 1) {
            requestAnimFrame(loop);
        }
    }
}

Or alternatively you could simply skip the second if condition and change the first condition to if (isPlaying && game !== 1). You would have to make a variable called game and give it a value of 0. Add 1 to it every game.

Are there inline functions in java?

Well, there are methods could be called "inline" methods in java, but depending on the jvm. After compiling, if the method's machine code is less than 35 byte, it will be transferred to a inline method right away, if the method's machine code is less than 325 byte, it could be transferred into a inline method, depending on the jvm.

How do you get the selected value of a Spinner?

mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()) works based on Rich's description.

return string with first match Regex

Maybe this would perform a bit better in case greater amount of input data does not contain your wanted piece because except has greater cost.

def return_first_match(text):
    result = re.findall('\d+',text)
    result = result[0] if result else ""
    return result

Get class list for element with jQuery

Here you go, just tweaked readsquare's answer to return an array of all classes:

function classList(elem){
   var classList = elem.attr('class').split(/\s+/);
    var classes = new Array(classList.length);
    $.each( classList, function(index, item){
        classes[index] = item;
    });

    return classes;
}

Pass a jQuery element to the function, so that a sample call will be:

var myClasses = classList($('#myElement'));

mysql data directory location

As suggested, I edited this message to place a proper answer.

The 'physical' location of the mysql databases are under /usr/local/mysql

the mysql is a symlink to the current active mysql installation, in my case the exact folder is mysql-5.6.10-osx10.7-x86_64.

Inside that folder you'll see another data folder, inside it are RESTRICTED folders with your databases.

You can't actually see the size of your databases (that was my issue) from the Finder because the folder are protected, you can though see from the terminal with sudo du -sh /usr/local/mysql/data/{your-database-name} and like this you'll get a nice formatted output with the size.

In those folder you have different files with all the folders present in your database, so it's safer to check the db's folder to get a size.

That's it. Enjoy!

Including a css file in a blade template?

Work with this code :

{!! include ('css/app.css') !!}

How to get a jqGrid cell value when editing

You can use getCol to get the column values as an array then index into it by the row you are interested in.

var col = $('#grid').jqGrid('getCol', 'Sales', false);

var val = col[row];

Changing the cursor in WPF sometimes works, sometimes doesn't

The following worked for me:

ForceCursor = true;
Cursor = Cursors.Wait;

How to get the caret column (not pixels) position in a textarea, in characters, from the start?

I modified the above function to account for carriage returns in IE. It's untested but I did something similar with it in my code so it should be workable.

function getCaret(el) {
  if (el.selectionStart) { 
    return el.selectionStart; 
  } else if (document.selection) { 
    el.focus(); 

    var r = document.selection.createRange(); 
    if (r == null) { 
      return 0; 
    } 

    var re = el.createTextRange(), 
    rc = re.duplicate(); 
    re.moveToBookmark(r.getBookmark()); 
    rc.setEndPoint('EndToStart', re); 

    var add_newlines = 0;
    for (var i=0; i<rc.text.length; i++) {
      if (rc.text.substr(i, 2) == '\r\n') {
        add_newlines += 2;
        i++;
      }
    }

    //return rc.text.length + add_newlines;

    //We need to substract the no. of lines
    return rc.text.length - add_newlines; 
  }  
  return 0; 
}

Removing nan values from an array

Try this:

import math
print [value for value in x if not math.isnan(value)]

For more, read on List Comprehensions.

Download File to server from URL

  1. Create a folder called "downloads" in destination server
  2. Save [this code] into .php file and run in destination server

Downloader :

<html>
<form method="post">
<input name="url" size="50" />
<input name="submit" type="submit" />
</form>
<?php
    // maximum execution time in seconds
    set_time_limit (24 * 60 * 60);

    if (!isset($_POST['submit'])) die();

    // folder to save downloaded files to. must end with slash
    $destination_folder = 'downloads/';

    $url = $_POST['url'];
    $newfname = $destination_folder . basename($url);

    $file = fopen ($url, "rb");
    if ($file) {
      $newf = fopen ($newfname, "wb");

      if ($newf)
      while(!feof($file)) {
        fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
      }
    }

    if ($file) {
      fclose($file);
    }

    if ($newf) {
      fclose($newf);
    }
?>
</html> 

How to apply CSS page-break to print a table with lots of rows?

Here is an example:

Via css:

<style>
  .my-table {
    page-break-before: always;
    page-break-after: always;
  }
  .my-table tr {
    page-break-inside: avoid;
  }
</style>

or directly on the element:

<table style="page-break-before: always; page-break-after: always;">
  <tr style="page-break-inside: avoid;">
    ..
  </tr>
</table>

While loop in batch

@echo off

set countfiles=10

:loop

set /a countfiles -= 1

echo hi

if %countfiles% GTR 0 goto loop

pause

on the first "set countfiles" the 10 you see is the amount it will loop the echo hi is the thing you want to loop

...i'm 5 years late

Using media breakpoints in Bootstrap 4-alpha

Use breakpoint mixins like this:

.something {
    padding: 5px;
    @include media-breakpoint-up(sm) { 
        padding: 20px;
    }
    @include media-breakpoint-up(md) { 
        padding: 40px;
    }
}

v4 breakpoints reference

v4 alpha6 breakpoints reference


Below full options and values.

Breakpoint & up (toggle on value and above):

@include media-breakpoint-up(xs) { ... }
@include media-breakpoint-up(sm) { ... }
@include media-breakpoint-up(md) { ... }
@include media-breakpoint-up(lg) { ... }
@include media-breakpoint-up(xl) { ... }

breakpoint & up values:

// Extra small devices (portrait phones, less than 576px)
// No media query since this is the default in Bootstrap

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }

breakpoint & down (toggle on value and down):

@include media-breakpoint-down(xs) { ... }
@include media-breakpoint-down(sm) { ... }
@include media-breakpoint-down(md) { ... }
@include media-breakpoint-down(lg) { ... }

breakpoint & down values:

// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }

// Small devices (landscape phones, less than 768px)
@media (max-width: 767px) { ... }

// Medium devices (tablets, less than 992px)
@media (max-width: 991px) { ... }

// Large devices (desktops, less than 1200px)
@media (max-width: 1199px) { ... }

// Extra large devices (large desktops)
// No media query since the extra-large breakpoint has no upper bound on its width

breakpoint only:

@include media-breakpoint-only(xs) { ... }
@include media-breakpoint-only(sm) { ... }
@include media-breakpoint-only(md) { ... }
@include media-breakpoint-only(lg) { ... }
@include media-breakpoint-only(xl) { ... }

breakpoint only values (toggle in between values only):

// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) and (max-width: 767px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) and (max-width: 991px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) and (max-width: 1199px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }

Print in Landscape format

you cannot set this in javascript, you have to do this with html/css:

<style type="text/css" media="print">
  @page { size: landscape; }
</style>

EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?

Android- create JSON Array and JSON Object

Have been struggling with this till I found out the answer:

  1. Use GSON library:

    Gson gson = Gson();
    String str_json = gson.tojson(jsonArray);`
    
  2. Pass the json array. This will be auto stringfied. This option worked perfectly for me.

What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

Try

$query = mysql_query("SELECT * FROM users WHERE name = 'Admin' ")or die(mysql_error());

and check if this throw any error.

Then use while($rows = mysql_fetch_assoc($query)):

And finally display it as

echo $name . "<br/>" . $address . "<br/>" . $email . "<br/>" . $subject . "<br/>" . $comment . "<br/><br/>" . ;

Do not user mysql_* as its deprecated.

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

First you need to use this command

npm config set registry https://registry.your-registry.npme.io/

This we are doing to set our companies Enterprise registry as our default registry.

You can try other given solutions also.

Save file Javascript with file name

Replace your "Save" button with an anchor link and set the new download attribute dynamically. Works in Chrome and Firefox:

var d = "ha";
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");

Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/

Here a compatibility table for downloadattribute: http://caniuse.com/download

How to get cookie expiration date / creation date from javascript?

If you are using Chrome you can goto the "Resources" tab and find the item "Cookies" in the left sidebar. From there select the domain you are checking the set cookie for and it will give you a list of cookies associated with that domain, along with their expiration date.

How to programmatically set drawableLeft on Android button?

myEdtiText.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);

fork: retry: Resource temporarily unavailable

Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used

watch -n 5 -d "ps -eL <java_pid> | wc -l"

to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.

Find file in directory from command line

I use this script to quickly find files across directories in a project. I have found it works great and takes advantage of Vim's autocomplete by opening up and closing an new buffer for the search. It also smartly completes as much as possible for you so you can usually just type a character or two and open the file across any directory in your project. I started using it specifically because of a Java project and it has saved me a lot of time. You just build the cache once when you start your editing session by typing :FC (directory names). You can also just use . to get the current directory and all subdirectories. After that you just type :FF (or FS to open up a new split) and it will open up a new buffer to select the file you want. After you select the file the temp buffer closes and you are inside the requested file and can start editing. In addition, here is another link on Stack Overflow that may help.

Add Expires headers

try this solution and it is working fine for me

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>

<IfModule mod_headers.c>
  <FilesMatch "\.(js|css|xml|gz)$">
    Header append Vary: Accept-Encoding
  </FilesMatch>
</IfModule>

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml text/x-js text/js 
</IfModule>

## EXPIRES CACHING ##

XSLT counting elements with a given value

This XPath:

count(//Property[long = '11007'])

returns the same value as:

count(//Property/long[text() = '11007'])

...except that the first counts Property nodes that match the criterion and the second counts long child nodes that match the criterion.

As per your comment and reading your question a couple of times, I believe that you want to find uniqueness based on a combination of criteria. Therefore, in actuality, I think you are actually checking multiple conditions. The following would work as well:

count(//Property[@Name = 'Alive'][long = '11007'])

because it means the same thing as:

count(//Property[@Name = 'Alive' and long = '11007'])

Of course, you would substitute the values for parameters in your template. The above code only illustrates the point.

EDIT (after question edit)


You were quite right about the XML being horrible. In fact, this is a downright CodingHorror candidate! I had to keep recounting to keep track of the "Property" node I was on presently. I feel your pain!

Here you go:

count(/root/ac/Properties/Property[Properties/Property/Properties/Property/long = $parPropId])

Note that I have removed all the other checks (for ID and Value). They appear not to be required since you are able to arrive at the relevant node using the hierarchy in the XML. Also, you already mentioned that the check for uniqueness is based only on the contents of the long element.

Python error: "IndexError: string index out of range"

There were several problems in your code. Here you have a functional version you can analyze (Lets set 'hello' as the target word):

word = 'hello'
so_far = "-" * len(word)       # Create variable so_far to contain the current guess

while word != so_far:          # if still not complete
    print(so_far)
    guess = input('>> ')       # get a char guess

    if guess in word:
        print("\nYes!", guess, "is in the word!")

        new = ""
        for i in range(len(word)):  
            if guess == word[i]:
                new += guess        # fill the position with new value
            else:
                new += so_far[i]    # same value as before
        so_far = new
    else:
        print("try_again")

print('finish')

I tried to write it for py3k with a py2k ide, be careful with errors.

Angular ui-grid dynamically calculate height of the grid

I like Tony approach. It works, but I decided to implement in different way. Here my comments:

1) I did some tests and when using ng-style, Angular evaluates ng-style content, I mean getTableHeight() function more than once. I put a breakpoint into getTableHeight() function to analyze this.

By the way, ui-if was removed. Now you have ng-if build-in.

2) I prefer to write a service like this:

angular.module('angularStart.services').factory('uiGridService', function ($http, $rootScope) {

var factory = {};

factory.getGridHeight = function(gridOptions) {

    var length = gridOptions.data.length;
    var rowHeight = 30; // your row height
    var headerHeight = 40; // your header height
    var filterHeight = 40; // your filter height

    return length * rowHeight + headerHeight + filterHeight + "px";
}
factory.removeUnit = function(value, unit) {

    return value.replace(unit, '');
}
return factory;

});

And then in the controller write the following:

  angular.module('app',['ui.grid']).controller('AppController', ['uiGridConstants', function(uiGridConstants) {

  ...

  // Execute this when you have $scope.gridData loaded...
  $scope.gridHeight = uiGridService.getGridHeight($scope.gridData);

And at the HTML file:

  <div id="grid1" ui-grid="gridData" class="grid" ui-grid-auto-resize style="height: {{gridHeight}}"></div>

When angular applies the style, it only has to look in the $scope.gridHeight variable and not to evaluate a complete function.

3) If you want to calculate dynamically the height of an expandable grid, it is more complicated. In this case, you can set expandableRowHeight property. This fixes the reserved height for each subgrid.

    $scope.gridData = {
        enableSorting: true,
        multiSelect: false,  
        enableRowSelection: true,
        showFooter: false,
        enableFiltering: true,    
        enableSelectAll: false,
        enableRowHeaderSelection: false, 
        enableGridMenu: true,
        noUnselect: true,
        expandableRowTemplate: 'subGrid.html',
        expandableRowHeight: 380,   // 10 rows * 30px + 40px (header) + 40px (filters)
        onRegisterApi: function(gridApi) {

            gridApi.expandable.on.rowExpandedStateChanged($scope, function(row){
                var height = parseInt(uiGridService.removeUnit($scope.jdeNewUserConflictsGridHeight,'px'));
                var changedRowHeight = parseInt(uiGridService.getGridHeight(row.entity.subGridNewUserConflictsGrid, true));

                if (row.isExpanded)
                {
                    height += changedRowHeight;                    
                }
                else
                {
                    height -= changedRowHeight;                    
                }

                $scope.jdeNewUserConflictsGridHeight = height + 'px';
            });
        },
        columnDefs :  [
                { field: 'GridField1', name: 'GridField1', enableFiltering: true }
        ]
    }

how to read all files inside particular folder

using System.IO;

//...

  string[] files;

  if (Directory.Exists(Path)) {
    files = Directory.GetFiles(Path, @"*.xml", SearchOption.TopDirectoryOnly);
    //...

Parameter "stratify" from method "train_test_split" (scikit Learn)

This stratify parameter makes a split so that the proportion of values in the sample produced will be the same as the proportion of values provided to parameter stratify.

For example, if variable y is a binary categorical variable with values 0 and 1 and there are 25% of zeros and 75% of ones, stratify=y will make sure that your random split has 25% of 0's and 75% of 1's.

How to remove folders with a certain name

This command works for me. It does its work recursively

find . -name "node_modules" -type d -prune -exec rm -rf '{}' +

. - current folder

"node_modules" - folder name

How do I connect to a MySQL Database in Python?

MySQLdb is the straightforward way. You get to execute SQL queries over a connection. Period.

My preferred way, which is also pythonic, is to use the mighty SQLAlchemy instead. Here is a query related tutorial, and here is a tutorial on ORM capabilities of SQLALchemy.

How do I create documentation with Pydoc?

Another thing that people may find useful...make sure to leave off ".py" from your module name. For example, if you are trying to generate documentation for 'original' in 'original.py':

yourcode_dir$ pydoc -w original.py
no Python documentation found for 'original.py'

yourcode_dir$ pydoc -w original
wrote original.html

Getting the size of an array in an object

Javascript arrays have a length property. Use it like this:

st.itemb.length

Stop setInterval call in JavaScript

The clearInterval() method can be used to clear a timer set with the setInterval() method.

setInterval always returns a ID value. This value can be passed in clearInterval() to stop the timer. Here is an example of timer starting from 30 and stops when it becomes 0.

  let time = 30;
  const timeValue = setInterval((interval) => {
  time = this.time - 1;
  if (time <= 0) {
    clearInterval(timeValue);
  }
}, 1000);

Calculate average in java

I'm going to show you 2 ways. If you don't need a lot of stats in your project simply implement following.

public double average(ArrayList<Double> x) {
    double sum = 0;
    for (double aX : x) sum += aX;
    return (sum / x.size());
}

If you plan on doing a lot of stats might as well not reinvent the wheel. So why not check out http://commons.apache.org/proper/commons-math/userguide/stat.html

You'll fall into true luv!

Looking to understand the iOS UIViewController lifecycle

Let's concentrate on methods, which are responsible for the UIViewController's lifecycle:

  • Creation:

    - (void)init

    - (void)initWithNibName:

  • View creation:

    - (BOOL)isViewLoaded

    - (void)loadView

    - (void)viewDidLoad

    - (UIView *)initWithFrame:(CGRect)frame

    - (UIView *)initWithCoder:(NSCoder *)coder

  • Handling of view state changing:

    - (void)viewDidLoad

    - (void)viewWillAppear:(BOOL)animated

    - (void)viewDidAppear:(BOOL)animated

    - (void)viewWillDisappear:(BOOL)animated

    - (void)viewDidDisappear:(BOOL)animated

    - (void)viewDidUnload

  • Memory warning handling:

    - (void)didReceiveMemoryWarning

  • Deallocation

    - (void)viewDidUnload

    - (void)dealloc

UIViewController's lifecycle diagram

For more information please take a look on UIViewController Class Reference.

What precisely does 'Run as administrator' do?

Things like "elevates the privileges", "restricted access token", "Administrator privilege" ... what the heck is administrator privilege anyway? are nonsense.

Here is an ACCESS_TOKEN for a process normally run from a user belonging to Administrators group.

0: kd> !process 0 1 test.exe
PROCESS 87065030  SessionId: 1  Cid: 0d60    Peb: 7ffdf000  ParentCid: 0618
    DirBase: 2f22e1e0  ObjectTable: a0c8a088  HandleCount:   6.
    Image: test.exe
    VadRoot 8720ef50 Vads 18 Clone 0 Private 83. Modified 0. Locked 0.
    DeviceMap 8936e560
    Token                             935c98e0
0: kd> !token -n 935c98e0
_TOKEN 935c98e0
TS Session ID: 0x1
User: S-1-5-21-2452432034-249115698-1235866470-1000 (no name mapped)
User Groups: 
 00 S-1-5-21-2452432034-249115698-1235866470-513 (no name mapped)
    Attributes - Mandatory Default Enabled 
 01 S-1-1-0 (Well Known Group: localhost\Everyone)
    Attributes - Mandatory Default Enabled 
 02 S-1-5-32-544 (Alias: BUILTIN\Administrators)
    Attributes - Mandatory Default Enabled Owner 
 03 S-1-5-32-545 (Alias: BUILTIN\Users)
    Attributes - Mandatory Default Enabled 
 04 S-1-5-4 (Well Known Group: NT AUTHORITY\INTERACTIVE)
    Attributes - Mandatory Default Enabled 
 05 S-1-2-1 (Well Known Group: localhost\CONSOLE LOGON)
    Attributes - Mandatory Default Enabled 
 06 S-1-5-11 (Well Known Group: NT AUTHORITY\Authenticated Users)
    Attributes - Mandatory Default Enabled 
 07 S-1-5-15 (Well Known Group: NT AUTHORITY\This Organization)
    Attributes - Mandatory Default Enabled 
 08 S-1-5-5-0-85516 (no name mapped)
    Attributes - Mandatory Default Enabled LogonId 
 09 S-1-2-0 (Well Known Group: localhost\LOCAL)
    Attributes - Mandatory Default Enabled 
 10 S-1-5-64-10 (Well Known Group: NT AUTHORITY\NTLM Authentication)
    Attributes - Mandatory Default Enabled 
 11 S-1-16-12288 (Label: Mandatory Label\High Mandatory Level)
    Attributes - GroupIntegrity GroupIntegrityEnabled 
Primary Group: S-1-5-21-2452432034-249115698-1235866470-513 (no name mapped)
Privs: 
 05 0x000000005 SeIncreaseQuotaPrivilege          Attributes - 
 08 0x000000008 SeSecurityPrivilege               Attributes - 
 09 0x000000009 SeTakeOwnershipPrivilege          Attributes - 
 10 0x00000000a SeLoadDriverPrivilege             Attributes - 
 11 0x00000000b SeSystemProfilePrivilege          Attributes - 
 12 0x00000000c SeSystemtimePrivilege             Attributes - 
 13 0x00000000d SeProfileSingleProcessPrivilege   Attributes - 
 14 0x00000000e SeIncreaseBasePriorityPrivilege   Attributes - 
 15 0x00000000f SeCreatePagefilePrivilege         Attributes - 
 17 0x000000011 SeBackupPrivilege                 Attributes - 
 18 0x000000012 SeRestorePrivilege                Attributes - 
 19 0x000000013 SeShutdownPrivilege               Attributes - 
 20 0x000000014 SeDebugPrivilege                  Attributes - 
 22 0x000000016 SeSystemEnvironmentPrivilege      Attributes - 
 23 0x000000017 SeChangeNotifyPrivilege           Attributes - Enabled Default 
 24 0x000000018 SeRemoteShutdownPrivilege         Attributes - 
 25 0x000000019 SeUndockPrivilege                 Attributes - 
 28 0x00000001c SeManageVolumePrivilege           Attributes - 
 29 0x00000001d SeImpersonatePrivilege            Attributes - Enabled Default 
 30 0x00000001e SeCreateGlobalPrivilege           Attributes - Enabled Default 
 33 0x000000021 SeIncreaseWorkingSetPrivilege     Attributes - 
 34 0x000000022 SeTimeZonePrivilege               Attributes - 
 35 0x000000023 SeCreateSymbolicLinkPrivilege     Attributes - 
Authentication ID:         (0,14e4c)
Impersonation Level:       Anonymous
TokenType:                 Primary
Source: User32             TokenFlags: 0x2000 ( Token in use )
Token ID: d166b            ParentToken ID: 0
Modified ID:               (0, d052f)
RestrictedSidCount: 0      RestrictedSids: 00000000
OriginatingLogonSession: 3e7

... and here is an ACCESS_TOKEN for a process normally run by the same user with "Run as administrator".

TS Session ID: 0x1
User: S-1-5-21-2452432034-249115698-1235866470-1000 (no name mapped)
User Groups: 
 00 S-1-5-21-2452432034-249115698-1235866470-513 (no name mapped)
    Attributes - Mandatory Default Enabled 
 01 S-1-1-0 (Well Known Group: localhost\Everyone)
    Attributes - Mandatory Default Enabled 
 02 S-1-5-32-544 (Alias: BUILTIN\Administrators)
    Attributes - Mandatory Default Enabled Owner 
 03 S-1-5-32-545 (Alias: BUILTIN\Users)
    Attributes - Mandatory Default Enabled 
 04 S-1-5-4 (Well Known Group: NT AUTHORITY\INTERACTIVE)
    Attributes - Mandatory Default Enabled 
 05 S-1-2-1 (Well Known Group: localhost\CONSOLE LOGON)
    Attributes - Mandatory Default Enabled 
 06 S-1-5-11 (Well Known Group: NT AUTHORITY\Authenticated Users)
    Attributes - Mandatory Default Enabled 
 07 S-1-5-15 (Well Known Group: NT AUTHORITY\This Organization)
    Attributes - Mandatory Default Enabled 
 08 S-1-5-5-0-85516 (no name mapped)
    Attributes - Mandatory Default Enabled LogonId 
 09 S-1-2-0 (Well Known Group: localhost\LOCAL)
    Attributes - Mandatory Default Enabled 
 10 S-1-5-64-10 (Well Known Group: NT AUTHORITY\NTLM Authentication)
    Attributes - Mandatory Default Enabled 
 11 S-1-16-12288 (Label: Mandatory Label\High Mandatory Level)
    Attributes - GroupIntegrity GroupIntegrityEnabled 
Primary Group: S-1-5-21-2452432034-249115698-1235866470-513 (no name mapped)
Privs: 
 05 0x000000005 SeIncreaseQuotaPrivilege          Attributes - 
 08 0x000000008 SeSecurityPrivilege               Attributes - 
 09 0x000000009 SeTakeOwnershipPrivilege          Attributes - 
 10 0x00000000a SeLoadDriverPrivilege             Attributes - 
 11 0x00000000b SeSystemProfilePrivilege          Attributes - 
 12 0x00000000c SeSystemtimePrivilege             Attributes - 
 13 0x00000000d SeProfileSingleProcessPrivilege   Attributes - 
 14 0x00000000e SeIncreaseBasePriorityPrivilege   Attributes - 
 15 0x00000000f SeCreatePagefilePrivilege         Attributes - 
 17 0x000000011 SeBackupPrivilege                 Attributes - 
 18 0x000000012 SeRestorePrivilege                Attributes - 
 19 0x000000013 SeShutdownPrivilege               Attributes - 
 20 0x000000014 SeDebugPrivilege                  Attributes - 
 22 0x000000016 SeSystemEnvironmentPrivilege      Attributes - 
 23 0x000000017 SeChangeNotifyPrivilege           Attributes - Enabled Default 
 24 0x000000018 SeRemoteShutdownPrivilege         Attributes - 
 25 0x000000019 SeUndockPrivilege                 Attributes - 
 28 0x00000001c SeManageVolumePrivilege           Attributes - 
 29 0x00000001d SeImpersonatePrivilege            Attributes - Enabled Default 
 30 0x00000001e SeCreateGlobalPrivilege           Attributes - Enabled Default 
 33 0x000000021 SeIncreaseWorkingSetPrivilege     Attributes - 
 34 0x000000022 SeTimeZonePrivilege               Attributes - 
 35 0x000000023 SeCreateSymbolicLinkPrivilege     Attributes - 
Authentication ID:         (0,14e4c)
Impersonation Level:       Anonymous
TokenType:                 Primary
Source: User32             TokenFlags: 0x2000 ( Token in use )
Token ID: ce282            ParentToken ID: 0
Modified ID:               (0, cddbd)
RestrictedSidCount: 0      RestrictedSids: 00000000
OriginatingLogonSession: 3e7

As you see, the only difference is the token ID:

Token ID: d166b            ParentToken ID: 0
Modified ID:               (0, d052f)

vs

Token ID: ce282            ParentToken ID: 0
Modified ID:               (0, cddbd)

Sorry, I can't add much light into this yet, but I am still digging.

Does Notepad++ show all hidden characters?

Yes, it does. The way to enable this depends on your version of Notepad++. On newer versions you can use:

Menu View ? Show Symbol ? *Show All Characters`

or

Menu View ? Show Symbol ? Show White Space and TAB

(Thanks to bers' comment and bkaid's answers below for these updated locations.)


On older versions you can look for:

Menu View ? Show all characters

or

Menu View ? Show White Space and TAB

Try-catch speeding up my code?

Well, the way you're timing things looks pretty nasty to me. It would be much more sensible to just time the whole loop:

var stopwatch = Stopwatch.StartNew();
for (int i = 1; i < 100000000; i++)
{
    Fibo(100);
}
stopwatch.Stop();
Console.WriteLine("Elapsed time: {0}", stopwatch.Elapsed);

That way you're not at the mercy of tiny timings, floating point arithmetic and accumulated error.

Having made that change, see whether the "non-catch" version is still slower than the "catch" version.

EDIT: Okay, I've tried it myself - and I'm seeing the same result. Very odd. I wondered whether the try/catch was disabling some bad inlining, but using [MethodImpl(MethodImplOptions.NoInlining)] instead didn't help...

Basically you'll need to look at the optimized JITted code under cordbg, I suspect...

EDIT: A few more bits of information:

  • Putting the try/catch around just the n++; line still improves performance, but not by as much as putting it around the whole block
  • If you catch a specific exception (ArgumentException in my tests) it's still fast
  • If you print the exception in the catch block it's still fast
  • If you rethrow the exception in the catch block it's slow again
  • If you use a finally block instead of a catch block it's slow again
  • If you use a finally block as well as a catch block, it's fast

Weird...

EDIT: Okay, we have disassembly...

This is using the C# 2 compiler and .NET 2 (32-bit) CLR, disassembling with mdbg (as I don't have cordbg on my machine). I still see the same performance effects, even under the debugger. The fast version uses a try block around everything between the variable declarations and the return statement, with just a catch{} handler. Obviously the slow version is the same except without the try/catch. The calling code (i.e. Main) is the same in both cases, and has the same assembly representation (so it's not an inlining issue).

Disassembled code for fast version:

 [0000] push        ebp
 [0001] mov         ebp,esp
 [0003] push        edi
 [0004] push        esi
 [0005] push        ebx
 [0006] sub         esp,1Ch
 [0009] xor         eax,eax
 [000b] mov         dword ptr [ebp-20h],eax
 [000e] mov         dword ptr [ebp-1Ch],eax
 [0011] mov         dword ptr [ebp-18h],eax
 [0014] mov         dword ptr [ebp-14h],eax
 [0017] xor         eax,eax
 [0019] mov         dword ptr [ebp-18h],eax
*[001c] mov         esi,1
 [0021] xor         edi,edi
 [0023] mov         dword ptr [ebp-28h],1
 [002a] mov         dword ptr [ebp-24h],0
 [0031] inc         ecx
 [0032] mov         ebx,2
 [0037] cmp         ecx,2
 [003a] jle         00000024
 [003c] mov         eax,esi
 [003e] mov         edx,edi
 [0040] mov         esi,dword ptr [ebp-28h]
 [0043] mov         edi,dword ptr [ebp-24h]
 [0046] add         eax,dword ptr [ebp-28h]
 [0049] adc         edx,dword ptr [ebp-24h]
 [004c] mov         dword ptr [ebp-28h],eax
 [004f] mov         dword ptr [ebp-24h],edx
 [0052] inc         ebx
 [0053] cmp         ebx,ecx
 [0055] jl          FFFFFFE7
 [0057] jmp         00000007
 [0059] call        64571ACB
 [005e] mov         eax,dword ptr [ebp-28h]
 [0061] mov         edx,dword ptr [ebp-24h]
 [0064] lea         esp,[ebp-0Ch]
 [0067] pop         ebx
 [0068] pop         esi
 [0069] pop         edi
 [006a] pop         ebp
 [006b] ret

Disassembled code for slow version:

 [0000] push        ebp
 [0001] mov         ebp,esp
 [0003] push        esi
 [0004] sub         esp,18h
*[0007] mov         dword ptr [ebp-14h],1
 [000e] mov         dword ptr [ebp-10h],0
 [0015] mov         dword ptr [ebp-1Ch],1
 [001c] mov         dword ptr [ebp-18h],0
 [0023] inc         ecx
 [0024] mov         esi,2
 [0029] cmp         ecx,2
 [002c] jle         00000031
 [002e] mov         eax,dword ptr [ebp-14h]
 [0031] mov         edx,dword ptr [ebp-10h]
 [0034] mov         dword ptr [ebp-0Ch],eax
 [0037] mov         dword ptr [ebp-8],edx
 [003a] mov         eax,dword ptr [ebp-1Ch]
 [003d] mov         edx,dword ptr [ebp-18h]
 [0040] mov         dword ptr [ebp-14h],eax
 [0043] mov         dword ptr [ebp-10h],edx
 [0046] mov         eax,dword ptr [ebp-0Ch]
 [0049] mov         edx,dword ptr [ebp-8]
 [004c] add         eax,dword ptr [ebp-1Ch]
 [004f] adc         edx,dword ptr [ebp-18h]
 [0052] mov         dword ptr [ebp-1Ch],eax
 [0055] mov         dword ptr [ebp-18h],edx
 [0058] inc         esi
 [0059] cmp         esi,ecx
 [005b] jl          FFFFFFD3
 [005d] mov         eax,dword ptr [ebp-1Ch]
 [0060] mov         edx,dword ptr [ebp-18h]
 [0063] lea         esp,[ebp-4]
 [0066] pop         esi
 [0067] pop         ebp
 [0068] ret

In each case the * shows where the debugger entered in a simple "step-into".

EDIT: Okay, I've now looked through the code and I think I can see how each version works... and I believe the slower version is slower because it uses fewer registers and more stack space. For small values of n that's possibly faster - but when the loop takes up the bulk of the time, it's slower.

Possibly the try/catch block forces more registers to be saved and restored, so the JIT uses those for the loop as well... which happens to improve the performance overall. It's not clear whether it's a reasonable decision for the JIT to not use as many registers in the "normal" code.

EDIT: Just tried this on my x64 machine. The x64 CLR is much faster (about 3-4 times faster) than the x86 CLR on this code, and under x64 the try/catch block doesn't make a noticeable difference.

Javascript: How to remove the last character from a div or a string?

Are u sure u want to remove only last character. What if the user press backspace from the middle of the word.. Its better to get the value from the field and replace the divs html. On keyup

$("#div").html($("#input").val());

Exception: There is already an open DataReader associated with this Connection which must be closed first

Add MultipleActiveResultSets=true to the provider part of your connection string example in the file appsettings.json

"ConnectionStrings": {
"EmployeeDBConnection": "server=(localdb)\\MSSQLLocalDB;database=YourDatabasename;Trusted_Connection=true;MultipleActiveResultSets=true"}

How to list all the files in android phone by using adb shell?

just to add the full command:

adb shell ls -R | grep filename

this is actually a pretty fast lookup on Android

Setting "checked" for a checkbox with jQuery

Here is the code and demo for how to check multiple check boxes...

http://jsfiddle.net/tamilmani/z8TTt/

$("#check").on("click", function () {

    var chk = document.getElementById('check').checked;
    var arr = document.getElementsByTagName("input");

    if (chk) {
        for (var i in arr) {
            if (arr[i].name == 'check') arr[i].checked = true;
        }
    } else {
        for (var i in arr) {
            if (arr[i].name == 'check') arr[i].checked = false;
        }
    }
});

Using jQuery To Get Size of Viewport

Please note that CSS3 viewport units (vh,vw) wouldn't play well on iOS When you scroll the page, viewport size is somehow recalculated and your size of element which uses viewport units also increases. So, actually some javascript is required.

Shorthand for if-else statement

?: Operator

If you want to shorten If/Else you can use ?: operator as:

condition ? action-on-true : action-on-false(else)

For instance:

let gender = isMale ? 'Male' : 'Female';

In this case else part is mandatory.

&& Operator

In another case, if you have only if condition you can use && operator as:

condition && action;

For instance:

!this.settings && (this.settings = new TableSettings());

FYI: You have to try to avoid using if-else or at least decrease using it and try to replace it with Polymorphism or Inheritance. Go for being Anti-If guy.

Check if cookies are enabled

it is easy to detect whether the cookies is enabled:

  1. set a cookie.
  2. get the cookie

if you can get the cookie you set, the cookie is enabled, otherwise not.

BTW: it is a bad idea to Embedding the session id in the links and forms, it is bad for SEO. In my opinion, it is not very common that people dont want to enable cookies.

Add JavaScript object to JavaScript object

var jsonIssues = []; // new Array
jsonIssues.push( { ID:1, "Name":"whatever" } );
// "push" some more here

How can I pop-up a print dialog box using Javascript?

I know the answer has already been provided. But I just wanted to elaborate with regards to doing this in a Blazor app (razor)...

You will need to inject IJSRuntime, in order to perform JSInterop (running javascript functions from C#)

IN YOUR RAZOR PAGE:

@inject IJSRuntime JSRuntime

Once you have that injected, create a button with a click event that calls a C# method:

<MatFAB Icon="@MatIconNames.Print" OnClick="@(async () => await print())"></MatFAB>

(or something more simple if you don't use MatBlazor)

<button @onclick="@(async () => await print())">PRINT</button>

For the C# method:

public async Task print()
{
    await JSRuntime.InvokeVoidAsync("printDocument");
}

NOW IN YOUR index.html:

<script>
    function printDocument() {
        window.print();
    }
</script>

Something to note, the reason the onclick events are asynchronous is because IJSRuntime awaits it's calls such as InvokeVoidAsync

PS: If you wanted to message box in asp net core for instance:

await JSRuntime.InvokeAsync<string>("alert", "Hello user, this is the message box");

To have a confirm message box:

bool question = await JSRuntime.InvokeAsync<bool>("confirm", "Are you sure you want to do this?");
    if(question == true)
    {
        //user clicked yes
    }
    else
    {
        //user clicked no
    }

Hope this helps :)

How to set combobox default value?

Suppose you bound your combobox to a List<Person>

List<Person> pp = new List<Person>();
pp.Add(new Person() {id = 1, name="Steve"});
pp.Add(new Person() {id = 2, name="Mark"});
pp.Add(new Person() {id = 3, name="Charles"});

cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;

At this point you cannot set the Text property as you like, but instead you need to add an item to your list before setting the datasource

pp.Insert(0, new Person() {id=-1, name="--SELECT--"});
cbo1.DisplayMember = "name";
cbo1.ValueMember = "id";
cbo1.DataSource = pp;
cbo1.SelectedIndex = 0;

Of course this means that you need to add a checking code when you try to use the info from the combobox

if(cbo1.SelectedValue != null && Convert.ToInt32(cbo1.SelectedValue) == -1)
    MessageBox.Show("Please select a person name");
else
    ...... 

The code is the same if you use a DataTable instead of a list. You need to add a fake row at the first position of the Rows collection of the datatable and set the initial index of the combobox to make things clear. The only thing you need to look at are the name of the datatable columns and which columns should contain a non null value before adding the row to the collection

In a table with three columns like ID, FirstName, LastName with ID,FirstName and LastName required you need to

DataRow row = datatable.NewRow();
row["ID"] = -1;
row["FirstName"] = "--Select--";    
row["LastName"] = "FakeAddress";
dataTable.Rows.InsertAt(row, 0);

How to make div fixed after you scroll to that div?

Adding on to @Alexandre Aimbiré's answer - sometimes you may need to specify z-index:1 to have the element always on top while scrolling. Like this:

position: -webkit-sticky; /* Safari & IE */
position: sticky;
top: 0;
z-index: 1;

Windows Scheduled task succeeds but returns result 0x1

I've had the same problem. It is just a batch-file, working when manually started, but not working as a scheduled task.

there were drive-letters in the batch-file like this:

put z:\folder\file.ext

seems like you should not use drive-letters, they are bound to the user, who created them - for me this little change made it work again:

put \\server\folder\file.ext

Is it possible to open a Windows Explorer window from PowerShell?

Use:

ii .

which is short for

Invoke-Item .

It is one of the most common things I type at the PowerShell command line.

How do I free memory in C?

You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc(), the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap(). Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc(), it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free() the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.

If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc(). Thus, if you make a lot of calls to malloc() and free() with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc() fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.

How to run Spring Boot web application in Eclipse itself?

You can also use the "Spring Boot App" run configuration. For that you'll need to install the Spring Tool Suite plug-in for Eclipse (STS).

Converting XDocument to XmlDocument and vice versa

There is a discussion on http://blogs.msdn.com/marcelolr/archive/2009/03/13/fast-way-to-convert-xmldocument-into-xdocument.aspx

It seems that reading an XDocument via an XmlNodeReader is the fastest method. See the blog for more details.

is there a 'block until condition becomes true' function in java?

You could use a semaphore.

While the condition is not met, another thread acquires the semaphore.
Your thread would try to acquire it with acquireUninterruptibly()
or tryAcquire(int permits, long timeout, TimeUnit unit) and would be blocked.

When the condition is met, the semaphore is also released and your thread would acquire it.

You could also try using a SynchronousQueue or a CountDownLatch.

How to get the home directory in Python?

You want to use os.path.expanduser.
This will ensure it works on all platforms:

from os.path import expanduser
home = expanduser("~")

If you're on Python 3.5+ you can use pathlib.Path.home():

from pathlib import Path
home = str(Path.home())

Django ManyToMany filter()

Note that if the user may be in multiple zones used in the query, you may probably want to add .distinct(). Otherwise you get one user multiple times:

users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3]).distinct()

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

What about this for a catch all...

if (string.IsNullOrEmpty(x.Trim())
{
}

This will trim all the spaces if they are there avoiding the performance penalty of IsWhiteSpace, which will enable the string to meet the "empty" condition if its not null.

I also think this is clearer and its generally good practise to trim strings anyway especially if you are putting them into a database or something.

What is the difference between PUT, POST and PATCH?

PUT = replace the ENTIRE RESOURCE with the new representation provided

PATCH = replace parts of the source resource with the values provided AND|OR other parts of the resource are updated that you havent provided (timestamps) AND|OR updating the resource effects other resources (relationships)

https://laracasts.com/discuss/channels/general-discussion/whats-the-differences-between-put-and-patch?page=1

How to find third or n?? maximum salary from salary table?

Subqueries always take more time:

use below query to get the any highest and lowest data:

Highest Data: select *from business order by id desc limit 3,1;

Lowest data: select *from business order by id asc limit 3,1;

Can use N in the place of 3 to get nth data.

PDF Blob - Pop up window not showing content

If you set { responseType: 'blob' }, no need to create Blob on your own. You can simply create url based with response content:

$http({
    url: "...",
    method: "POST",
    responseType: "blob"
}).then(function(response) {
    var fileURL = URL.createObjectURL(response.data);
    window.open(fileURL);
});

What is causing the error `string.split is not a function`?

Change this...

var string = document.location;

to this...

var string = document.location + '';

This is because document.location is a Location object. The default .toString() returns the location in string form, so the concatenation will trigger that.


You could also use document.URL to get a string.

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

Instead of

$("form").submit()

try this

 $("<input type='submit' id='btn_tmpSubmit'/>").css('display','none').appendTo('form');
 $("#btn_tmpSubmit").click();

Nested lists python

You can do this. Adapt it to your situation:

  for l in Nlist:
      for item in l:
        print item

Equivalent to 'app.config' for a library (DLL)

Why not to use:

  • [ProjectNamespace].Properties.Settings.Default.[KeyProperty] for C#
  • My.Settings.[KeyProperty] for VB.NET

You just have to update visually those properties at design-time through:

[Solution Project]->Properties->Settings

Is there any way I can define a variable in LaTeX?

This works for me: \newcommand{\variablename}{the text}

For eg: \newcommand\m{100}

So when you type " \m\ is my mark " in the source code,

the pdf output displays as :

100 is my mark

Display back button on action bar

I think onSupportNavigateUp() is the best and Easiest way to do so, check the below steps. Step 1 is necessary, step two have alternative.

Step 1 showing back button: Add this line in onCreate() method to show back button.

assert getSupportActionBar() != null;   //null check
getSupportActionBar().setDisplayHomeAsUpEnabled(true);   //show back button

Step 2 implementation of back click: Override this method

@Override
public boolean onSupportNavigateUp() {  
    finish();  
    return true;  
}

thats it you are done
OR Step 2 Alternative: You can add meta to the activity in manifest file as

<meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="MainActivity" />

Edit: If you are not using AppCompat Activity then do not use support word, you can use

getActionBar().setDisplayHomeAsUpEnabled(true); // In `OnCreate();`

// And override this method
@Override 
public boolean onNavigateUp() { 
     finish(); 
     return true; 
}

Thanks to @atariguy for comment.

Return empty cell from formula in Excel

Use COUNTBLANK(B1)>0 instead of ISBLANK(B1) inside your IF statement.

Unlike ISBLANK(), COUNTBLANK() considers "" as empty and returns 1.

dotnet ef not found in .NET Core 3

Global tools can be installed in the default directory or in a specific location. The default directories are:

  • Linux/macOS ---> $HOME/.dotnet/tools

  • Windows ---> %USERPROFILE%\.dotnet\tools

If you're trying to run a global tool, check that the PATH environment variable on your machine contains the path where you installed the global tool and that the executable is in that path.

Troubleshoot .NET Core tool usage issues

How to find controls in a repeater header or footer

The best and clean way to do this is within the Item_Created Event :

 protected void rptSummary_ItemCreated(Object sender, RepeaterItemEventArgs e)
        {
            switch (e.Item.ItemType)
            {
                case ListItemType.AlternatingItem:
                    break;
                case ListItemType.EditItem:
                    break;
                case ListItemType.Footer:
                    e.Item.FindControl(ctrl);
                    break;
                case ListItemType.Header:
                    break;
                case ListItemType.Item:
                    break;
                case ListItemType.Pager:
                    break;
                case ListItemType.SelectedItem:
                    break;
                case ListItemType.Separator:
                    break;
                default:
                    break;
            }
    }

Getting the client IP address: REMOTE_ADDR, HTTP_X_FORWARDED_FOR, what else could be useful?

No real answer to your question but:
Generally relying on the clients IP address is in my opinion not a good practice as it is not usable to identify clients in a unique fashion.

Problems on the road are that there are quite a lot scenarios where the IP does not really align to a client:

  • Proxy/Webfilter (mangle almost everything)
  • Anonymizer network (no chance here either)
  • NAT (an internal IP is not very useful for you)
  • ...

I cannot offer any statistics on how many IP addresses are on average reliable but what I can tell you that it is almost impossible to tell if a given IP address is the real clients address.

Illegal pattern character 'T' when parsing a date string to java.util.Date

tl;dr

Use java.time.Instant class to parse text in standard ISO 8601 format, representing a moment in UTC.

Instant.parse( "2010-10-02T12:23:23Z" )

ISO 8601

That format is defined by the ISO 8601 standard for date-time string formats.

Both:

…use ISO 8601 formats by default for parsing and generating strings.

You should generally avoid using the old java.util.Date/.Calendar & java.text.SimpleDateFormat classes as they are notoriously troublesome, confusing, and flawed. If required for interoperating, you can convert to and fro.

java.time

Built into Java 8 and later is the new java.time framework. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.

Instant instant = Instant.parse( "2010-10-02T12:23:23Z" );  // `Instant` is always in UTC.

Convert to the old class.

java.util.Date date = java.util.Date.from( instant );  // Pass an `Instant` to the `from` method.

Time Zone

If needed, you can assign a time zone.

ZoneId zoneId = ZoneId.of( "America/Montreal" ); // Define a time zone rather than rely implicitly on JVM’s current default time zone.
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );  // Assign a time zone adjustment from UTC.

Convert.

java.util.Date date = java.util.Date.from( zdt.toInstant() );  // Extract an `Instant` from the `ZonedDateTime` to pass to the `from` method.

Joda-Time

UPDATE: The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes.

Here is some example code in Joda-Time 2.8.

org.joda.time.DateTime dateTime_Utc = new DateTime( "2010-10-02T12:23:23Z" , DateTimeZone.UTC );  // Specifying a time zone to apply, rather than implicitly assigning the JVM’s current default.

Convert to old class. Note that the assigned time zone is lost in conversion, as j.u.Date cannot be assigned a time zone.

java.util.Date date = dateTime_Utc.toDate(); // The `toDate` method converts to old class.

Time Zone

If needed, you can assign a time zone.

DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );
DateTime dateTime_Montreal = dateTime_Utc.withZone ( zone );

Table of date-time types in Java, both modern and legacy.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android.

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to add a new row to datagridview programmatically

Like this:

 dataGridView1.Columns[0].Name = "column2";
 dataGridView1.Columns[1].Name = "column6";

 string[] row1 = new string[] { "column2 value", "column6 value" };
 dataGridView1.Rows.Add(row1);

Or you need to set there values individually use the propery .Rows(), like this:

 dataGridView1.Rows[1].Cells[0].Value = "cell value";

Twitter Bootstrap date picker

I was having the same problem but when I created a test project, to my surprise, datepicker worked perfectly using Bootstrap v2.0.2 and Jquery UI 1.8.11. Here are the scripts i'm including:

        <link href="@Url.Content("~/Content/bootstrap.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/bootstrap-responsive.css")" rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Content/themes/base/jquery.ui.all.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.min.js")" type="text/javascript"></script>

Is there a way to get a textarea to stretch to fit its content without using PHP or JavaScript?

Not really. This is normally done using javascript.

there is a good discussion of ways of doing this here...

Autosizing textarea using Prototype

Difference between window.location.href=window.location.href and window.location.reload()

A difference in Firefox (12.0) is that on a page rendered from a POST, reload() will pop up a warning and do a re-post, while a URL assignment will do a GET.

Google Chrome does a GET for both.

CSS Auto hide elements after 5 seconds

Of course you can, just use setTimeout to change a class or something to trigger the transition.

HTML:

<p id="aap">OHAI!</p>

CSS:

p {
    opacity:1;
    transition:opacity 500ms;
}
p.waa {
    opacity:0;
}

JS to run on load or DOMContentReady:

setTimeout(function(){
    document.getElementById('aap').className = 'waa';
}, 5000);

Example fiddle here.

MySQL user DB does not have password columns - Installing MySQL on OSX

For this problem, I used a simple and rude method, rename the field name to password, the reason for this is that I use the mac navicat premium software in the visual operation error: Unknown column 'password' in 'field List ', the software itself uses password so that I can not easily operate. Therefore, I root into the database command line, run

Use mysql;

And then modify the field name:

ALTER TABLE user CHANGE authentication_string password text;

After all normal.

How can I temporarily disable a foreign key constraint in MySQL?

If the key field is nullable, then you can also set the value to null before attempting to delete it:

cursor.execute("UPDATE myapp_item SET myapp_style_id = NULL WHERE n = %s", n)
transaction.commit_unless_managed() 

cursor.execute("UPDATE myapp_style SET myapp_item_id = NULL WHERE n = %s", n)
transaction.commit_unless_managed()

cursor.execute("DELETE FROM myapp_item WHERE n = %s", n)
transaction.commit_unless_managed()

cursor.execute("DELETE FROM myapp_style WHERE n = %s", n)
transaction.commit_unless_managed()

Center Align on a Absolutely Positioned Div

If it is necessary for you to have a relative width (in percentage), you could wrap your div in a absolute positioned one:

div#wrapper {
    position: absolute;
    width: 100%;
    text-align: center;
}

Remember that in order to position an element absolutely, the parent element must be positioned relatively.

extract digits in a simple way from a python string

This regular expression handles floats as well

import re
re_float = re.compile(r'\d*\.?\d+')

You could also add a group to the expression that catches your weight units.

re_banana = re.compile(r'(?P<number>\d*\.?\d+)\s?(?P<uni>[a-zA-Z]+)')

You can access the named groups like this re_banana.match("200 kgm").group('number').

I think this should help you getting started.

Pull all images from a specified directory and then display them

You need to change the loop from for ($i=1; $i<count($files); $i++) to for ($i=0; $i<count($files); $i++):

So the correct code is

<?php
$files = glob("images/*.*");

for ($i=0; $i<count($files); $i++) {
    $image = $files[$i];
    print $image ."<br />";
    echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
}

?>

Can an Android Toast be longer than Toast.LENGTH_LONG?

The user cannot custome defined the Toast's duration. because NotificationManagerService's scheduleTimeoutLocked() function not use the field duration. the source code is the following.

private void scheduleTimeoutLocked(ToastRecord r, boolean immediate)
    {
        Message m = Message.obtain(mHandler, MESSAGE_TIMEOUT, r);
        long delay = immediate ? 0 : (r.duration == Toast.LENGTH_LONG ? LONG_DELAY : SHORT_DELAY);
        mHandler.removeCallbacksAndMessages(r);
        mHandler.sendMessageDelayed(m, delay);
    }

trigger click event from angularjs directive

This is an extension to Langdon's answer with a directive approach to the problem. If you're going to have multiple galleries on the page this may be one way to go about it without much fuss.

Usage:

<gallery images="items"></gallery>
<gallery images="cats"></gallery>

See it working here

How to print values separated by spaces instead of new lines in Python 2.7

First of all print isn't a function in Python 2, it is a statement.

To suppress the automatic newline add a trailing ,(comma). Now a space will be used instead of a newline.

Demo:

print 1,
print 2

output:

1 2

Or use Python 3's print() function:

from __future__ import print_function
print(1, end=' ') # default value of `end` is '\n'
print(2)

As you can clearly see print() function is much more powerful as we can specify any string to be used as end rather a fixed space.

Pass react component as props

Using this.props.children is the idiomatic way to pass instantiated components to a react component

const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>

When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div or span):

const Label = props => <span>{props.children}</span>
const Button = props => {
    const Inner = props.inner; // Note: variable name _must_ start with a capital letter 
    return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>

If what you want to do is to pass a children-like parameter as a prop, you can do that:

const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />

After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.

How do I search an SQL Server database for a string?

Here is how you can search the database in Swift using the FMDB library.

First, go to this link and add this to your project: FMDB. When you have done that, then here is how you do it. For example, you have a table called Person, and you have firstName and secondName and you want to find data by first name, here is a code for that:

    func loadDataByfirstName(firstName : String, completion: @escaping CompletionHandler){
    if isDatabaseOpened {
        let query = "select * from Person where firstName like '\(firstName)'"
        do {
            let results = try database.executeQuery(query, values: [firstName])
            while results.next() {
                let firstName = results.string(forColumn: "firstName") ?? ""
                let lastName = results.string(forColumn: "lastName") ?? ""
                let newPerson = Person(firstName: firstName, lastName: lastName)
                self.persons.append(newPerson)
            }
            completion(true)
        }catch let err {
            completion(false)
            print(err.localizedDescription)
        }
        database.close()
    }
}

Then in your ViewController you will write this to find the person detail you are looking for:

  override func viewWillAppear(_ animated: Bool) {
     super.viewWillAppear(animated)
      SQLManager.instance.openDatabase { (success) in
        if success {
            SQLManager.instance.loadDataByfirstName(firstName: "Hardi") { (success) in
                if success {
                    // You have your data Here
                }
            }
        }
    }
}

How to store the hostname in a variable in a .bat file?

hmm - something like this?

set host=%COMPUTERNAME%
echo %host%

EDIT: expanding on jitter's answer and using a technique in an answer to this question to set an environment variable with the result of running a command line app:

@echo off
hostname.exe > __t.tmp
set /p host=<__t.tmp
del __t.tmp
echo %host%

In either case, 'host' is created as an environment variable.

The provider is not compatible with the version of Oracle client

Recently I had to work on an older project where the solution and all contained projects were targeted to x32 platform. I kept on trying to copy Oracle.DataAccess.dll and all other suggested Oracle files on all the places, but hit the wall every time. Finally the bulb in the head lit up (after 8 hours :)), and asked to check for the installed ODAC assemblies and their platform. I had all the 64-bit (x64) ODAC clients installed already but not the 32 bit ones (x32). Installed the 32-bit ODAC and the problem disappeared.

How to check the version of installed ODAC: Look in folder C:\Windows\assembly. The "Processor Architecture" property will inform the platform of installed ODAC.

Eight hours is a long time for the bulb to light up. No wonder I always have to slog at work :).

Most efficient way to create a zero filled JavaScript array?

It might be worth pointing out, that Array.prototype.fill had been added as part of the ECMAScript 6 (Harmony) proposal. I would rather go with the polyfill written below, before considering other options mentioned on the thread.

if (!Array.prototype.fill) {
  Array.prototype.fill = function(value) {

    // Steps 1-2.
    if (this == null) {
      throw new TypeError('this is null or not defined');
    }

    var O = Object(this);

    // Steps 3-5.
    var len = O.length >>> 0;

    // Steps 6-7.
    var start = arguments[1];
    var relativeStart = start >> 0;

    // Step 8.
    var k = relativeStart < 0 ?
      Math.max(len + relativeStart, 0) :
      Math.min(relativeStart, len);

    // Steps 9-10.
    var end = arguments[2];
    var relativeEnd = end === undefined ?
      len : end >> 0;

    // Step 11.
    var final = relativeEnd < 0 ?
      Math.max(len + relativeEnd, 0) :
      Math.min(relativeEnd, len);

    // Step 12.
    while (k < final) {
      O[k] = value;
      k++;
    }

    // Step 13.
    return O;
  };
}

Can't bind to 'routerLink' since it isn't a known property

I totally chose another way for this method.

app.component.ts

import { Router } from '@angular/router';
export class AppComponent {

   constructor(
        private router: Router,
    ) {}

    routerComment() {
        this.router.navigateByUrl('/marketing/social/comment');
    }
}

app.component.html

<button (click)="routerComment()">Router Link </button>

Calculating distance between two points (Latitude, Longitude)

Create Function [dbo].[DistanceKM] 
( 
      @Lat1 Float(18),  
      @Lat2 Float(18), 
      @Long1 Float(18), 
      @Long2 Float(18)
)
Returns Float(18)
AS
Begin
      Declare @R Float(8); 
      Declare @dLat Float(18); 
      Declare @dLon Float(18); 
      Declare @a Float(18); 
      Declare @c Float(18); 
      Declare @d Float(18);
      Set @R =  6367.45
            --Miles 3956.55  
            --Kilometers 6367.45 
            --Feet 20890584 
            --Meters 6367450 


      Set @dLat = Radians(@lat2 - @lat1);
      Set @dLon = Radians(@long2 - @long1);
      Set @a = Sin(@dLat / 2)  
                 * Sin(@dLat / 2)  
                 + Cos(Radians(@lat1)) 
                 * Cos(Radians(@lat2))  
                 * Sin(@dLon / 2)  
                 * Sin(@dLon / 2); 
      Set @c = 2 * Asin(Min(Sqrt(@a))); 

      Set @d = @R * @c; 
      Return @d; 

End
GO

Usage:

select dbo.DistanceKM(37.848832506474, 37.848732506474, 27.83935546875, 27.83905546875)

Outputs:

0,02849639

You can change @R parameter with commented floats.

Import error: No module name urllib2

Some tab completions to show the contents of the packages in Python 2 vs Python 3.

In Python 2:

In [1]: import urllib

In [2]: urllib.
urllib.ContentTooShortError      urllib.ftpwrapper                urllib.socket                    urllib.test1
urllib.FancyURLopener            urllib.getproxies                urllib.splitattr                 urllib.thishost
urllib.MAXFTPCACHE               urllib.getproxies_environment    urllib.splithost                 urllib.time
urllib.URLopener                 urllib.i                         urllib.splitnport                urllib.toBytes
urllib.addbase                   urllib.localhost                 urllib.splitpasswd               urllib.unquote
urllib.addclosehook              urllib.noheaders                 urllib.splitport                 urllib.unquote_plus
urllib.addinfo                   urllib.os                        urllib.splitquery                urllib.unwrap
urllib.addinfourl                urllib.pathname2url              urllib.splittag                  urllib.url2pathname
urllib.always_safe               urllib.proxy_bypass              urllib.splittype                 urllib.urlcleanup
urllib.base64                    urllib.proxy_bypass_environment  urllib.splituser                 urllib.urlencode
urllib.basejoin                  urllib.quote                     urllib.splitvalue                urllib.urlopen
urllib.c                         urllib.quote_plus                urllib.ssl                       urllib.urlretrieve
urllib.ftpcache                  urllib.re                        urllib.string                    
urllib.ftperrors                 urllib.reporthook                urllib.sys  

In Python 3:

In [2]: import urllib.
urllib.error        urllib.parse        urllib.request      urllib.response     urllib.robotparser

In [2]: import urllib.error.
urllib.error.ContentTooShortError  urllib.error.HTTPError             urllib.error.URLError

In [2]: import urllib.parse.
urllib.parse.parse_qs          urllib.parse.quote_plus        urllib.parse.urldefrag         urllib.parse.urlsplit
urllib.parse.parse_qsl         urllib.parse.unquote           urllib.parse.urlencode         urllib.parse.urlunparse
urllib.parse.quote             urllib.parse.unquote_plus      urllib.parse.urljoin           urllib.parse.urlunsplit
urllib.parse.quote_from_bytes  urllib.parse.unquote_to_bytes  urllib.parse.urlparse

In [2]: import urllib.request.
urllib.request.AbstractBasicAuthHandler         urllib.request.HTTPSHandler
urllib.request.AbstractDigestAuthHandler        urllib.request.OpenerDirector
urllib.request.BaseHandler                      urllib.request.ProxyBasicAuthHandler
urllib.request.CacheFTPHandler                  urllib.request.ProxyDigestAuthHandler
urllib.request.DataHandler                      urllib.request.ProxyHandler
urllib.request.FTPHandler                       urllib.request.Request
urllib.request.FancyURLopener                   urllib.request.URLopener
urllib.request.FileHandler                      urllib.request.UnknownHandler
urllib.request.HTTPBasicAuthHandler             urllib.request.build_opener
urllib.request.HTTPCookieProcessor              urllib.request.getproxies
urllib.request.HTTPDefaultErrorHandler          urllib.request.install_opener
urllib.request.HTTPDigestAuthHandler            urllib.request.pathname2url
urllib.request.HTTPErrorProcessor               urllib.request.url2pathname
urllib.request.HTTPHandler                      urllib.request.urlcleanup
urllib.request.HTTPPasswordMgr                  urllib.request.urlopen
urllib.request.HTTPPasswordMgrWithDefaultRealm  urllib.request.urlretrieve
urllib.request.HTTPRedirectHandler     


In [2]: import urllib.response.
urllib.response.addbase       urllib.response.addclosehook  urllib.response.addinfo       urllib.response.addinfourl

Get height and width of a layout programmatically

try with this metods:

int width = mView.getMeasuredWidth();

int height = mView.getMeasuredHeight();

Or

int width = mTextView.getMeasuredWidth();

int height = mTextView.getMeasuredHeight();

Fatal error: Call to undefined function pg_connect()

I also had this problem on OSX. The solution was uncommenting the extension = pgsql.so in php.ini.default and deleting the .default suffix, since the file php.ini was not there.

If you are using XAMPP, the php.ini file resides in /XAMPP/xampfiles/etc

Python group by

The following function will quickly (no sorting required) group tuples of any length by a key having any index:

# given a sequence of tuples like [(3,'c',6),(7,'a',2),(88,'c',4),(45,'a',0)],
# returns a dict grouping tuples by idx-th element - with idx=1 we have:
# if merge is True {'c':(3,6,88,4),     'a':(7,2,45,0)}
# if merge is False {'c':((3,6),(88,4)), 'a':((7,2),(45,0))}
def group_by(seqs,idx=0,merge=True):
    d = dict()
    for seq in seqs:
        k = seq[idx]
        v = d.get(k,tuple()) + (seq[:idx]+seq[idx+1:] if merge else (seq[:idx]+seq[idx+1:],))
        d.update({k:v})
    return d

In the case of your question, the index of key you want to group by is 1, therefore:

group_by(input,1)

gives

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

which is not exactly the output you asked for, but might as well suit your needs.

What is the difference between loose coupling and tight coupling in the object oriented paradigm?

In object oriented design, the amount of coupling refers to how much the design of one class depends on the design of another class. In other words, how often do changes in class A force related changes in class B? Tight coupling means the two classes often change together, loose coupling means they are mostly independent. In general, loose coupling is recommended because it's easier to test and maintain.

You may find this paper by Martin Fowler (PDF) helpful.

Find and kill a process in one line using bash and regex

I use this to kill Firefox when it's being script slammed and cpu bashing :) Replace 'Firefox' with the app you want to die. I'm on the Bash shell - OS X 10.9.3 Darwin.

kill -Hup $(ps ux | grep Firefox | awk 'NR == 1 {next} {print $2}' | uniq | sort)

JSON Invalid UTF-8 middle byte

JSON data must be encoded as UTF-8, UTF-16 or UTF-32. The JSON decoder can determine the encoding by examining the first four octets of the byte stream:

       00 00 00 xx  UTF-32BE
       00 xx 00 xx  UTF-16BE
       xx 00 00 00  UTF-32LE
       xx 00 xx 00  UTF-16LE
       xx xx xx xx  UTF-8

It sounds like the server is encoding data in some illegal encoding (ISO-8859-1, windows-1252, etc.)

How can I record a Video in my Android App.?

Check out this Sample Camera Preview code, CameraPreview. This would help you in devloping video recording code for video preview, create MediaRecorder object, and set video recording parameters.

Linux command to print directory structure in the form of a tree

Adding the below function in bashrc lets you run the command without any arguments which displays the current directory structure and when run with any path as argument, will display the directory structure of that path. This avoids the need to switch to a particular directory before running the command.

function tree() {
    find ${1:-.} | sed -e "s/[^-][^\/]*\//  |/g" -e "s/|\([^ ]\)/|-\1/"
}

This works in gitbash too.

Source: Comment from @javasheriff here

Make a bucket public in Amazon S3

Amazon provides a policy generator tool:

https://awspolicygen.s3.amazonaws.com/policygen.html

After that, you can enter the policy requirements for the bucket on the AWS console:

https://console.aws.amazon.com/s3/home

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

I got same problem. If I run brew link --overwrite python2. There was still zsh: /usr/local/bin//fab: bad interpreter: /usr/local/opt/python/bin/python2.7: no such file or directory.

cd /usr/local/opt/
mv python2 python

Solved it! Now we can use python2 version fabric.

=== 2018/07/25 updated

There is convinient way to use python2 version fab when your os python linked to python3. .sh for your command.

# fab python2
cd /usr/local/opt
rm python
ln -s python2 python

# use the fab cli
...

# link to python3
cd /usr/local/opt
rm python
ln -s python3 python

Hope this helps.

Can I use multiple "with"?

Yes - just do it this way:

WITH DependencedIncidents AS
(
  ....
),  
lalala AS
(
  ....
)

You don't need to repeat the WITH keyword

How do I get the title of the current active window using c#?

Loop over Application.Current.Windows[] and find the one with IsActive == true.

Fast way to get the min/max values among properties of object

You can also try with Object.values

_x000D_
_x000D_
const points = { Neel: 100, Veer: 89, Shubham: 78, Vikash: 67 };_x000D_
_x000D_
const vals = Object.values(points);_x000D_
const max = Math.max(...vals);_x000D_
const min = Math.min(...vals);_x000D_
console.log(max);_x000D_
console.log(min);
_x000D_
_x000D_
_x000D_

No content to map due to end-of-input jackson parser

For one, @JsonProperty("status") and @JsonProperty("msg") should only be there only when declaring the fields, not on the setters and geters.

In fact, the simplest way to parse this would be

@JsonAutoDetect  //if you don't want to have getters and setters for each JsonProperty
public class StatusResponses {

   @JsonProperty("status")
   private String status;

   @JsonProperty("msg")
   private String message;

}

How to get mouse position in jQuery without mouse-events?

var CurrentMouseXPostion;
var CurrentMouseYPostion;

$(document).mousemove(function(event) {
    CurrentMouseXPostion = event.pageX;
    CurrentMouseYPostion = event.pageY;
});

Make an eventListener on the main object , in my case the document object, to get the mouse coords every frame and store them in global variables, and like that you can read mouse Y & Z whenever youlike , wherever you like.

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

in my case just

const myReducers = combineReducers({
  user: UserReducer
});

const store: any = createStore(
  myReducers,
  applyMiddleware(thunk)
);

shallow(<Login />, { context: { store } });

Arraylist swap elements

In Java, you cannot set a value in ArrayList by assigning to it, there's a set() method to call:

String a = words.get(0);
words.set(0, words.get(words.size() - 1));
words.set(words.size() - 1, a)

Continue For loop

A lot of years after... I like this one:

For x = LBound(arr) To UBound(arr): Do

    sname = arr(x)  
    If instr(sname, "Configuration item") Then Exit Do 

    '// other code to copy past and do various stuff

Loop While False: Next x

how to format date in Component of angular 5

Another option can be using built in angular formatDate function. I am assuming that you are using reactive forms. Here todoDate is a date input field in template.

import {formatDate} from '@angular/common';

this.todoForm.controls.todoDate.setValue(formatDate(this.todo.targetDate, 'yyyy-MM-dd', 'en-US'));

:last-child not working as expected?

The last-child selector is used to select the last child element of a parent. It cannot be used to select the last child element with a specific class under a given parent element.

The other part of the compound selector (which is attached before the :last-child) specifies extra conditions which the last child element must satisfy in-order for it to be selected. In the below snippet, you would see how the selected elements differ depending on the rest of the compound selector.

_x000D_
_x000D_
.parent :last-child{ /* this will select all elements which are last child of .parent */_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.parent div:last-child{ /* this will select the last child of .parent only if it is a div*/_x000D_
  background: crimson;_x000D_
}_x000D_
_x000D_
.parent div.child-2:last-child{ /* this will select the last child of .parent only if it is a div and has the class child-2*/_x000D_
  color: beige;_x000D_
}
_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child-2'>Child w/o class</div>_x000D_
</div>_x000D_
<div class='parent'>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <div class='child'>Child</div>_x000D_
  <p>Child w/o class</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_


To answer your question, the below would style the last child li element with background color as red.

li:last-child{
    background-color: red;
}

But the following selector would not work for your markup because the last-child does not have the class='complete' even though it is an li.

li.complete:last-child{
    background-color: green;
}

It would have worked if (and only if) the last li in your markup also had class='complete'.


To address your query in the comments:

@Harry I find it rather odd that: .complete:last-of-type does not work, yet .complete:first-of-type does work, regardless of it's position it's parents element. Thanks for your help.

The selector .complete:first-of-type works in the fiddle because it (that is, the element with class='complete') is still the first element of type li within the parent. Try to add <li>0</li> as the first element under the ul and you will find that first-of-type also flops. This is because the first-of-type and last-of-type selectors select the first/last element of each type under the parent.

Refer to the answer posted by BoltClock, in this thread for more details about how the selector works. That is as comprehensive as it gets :)

Passing an array of data as an input parameter to an Oracle procedure

If the types of the parameters are all the same (varchar2 for example), you can have a package like this which will do the following:

CREATE OR REPLACE PACKAGE testuser.test_pkg IS

   TYPE assoc_array_varchar2_t IS TABLE OF VARCHAR2(4000) INDEX BY BINARY_INTEGER;

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t);

END test_pkg;

CREATE OR REPLACE PACKAGE BODY testuser.test_pkg IS

   PROCEDURE your_proc(p_parm IN assoc_array_varchar2_t) AS
   BEGIN
      FOR i IN p_parm.first .. p_parm.last
      LOOP
         dbms_output.put_line(p_parm(i));
      END LOOP;

   END;

END test_pkg;

Then, to call it you'd need to set up the array and pass it:

DECLARE
  l_array testuser.test_pkg.assoc_array_varchar2_t;
BEGIN
  l_array(0) := 'hello';
  l_array(1) := 'there';  

  testuser.test_pkg.your_proc(l_array);
END;
/

How to convert DateTime? to DateTime

MS already made a method for this, so you dont have to use the null coalescing operator. No difference in functionality, but it is easier for non-experts to get what is happening at a glance.

DateTime updatedTime = _objHotelPackageOrder.UpdatedDate.GetValueOrDefault(DateTime.Now);

What's wrong with overridable method calls in constructors?

On invoking overridable method from constructors

Simply put, this is wrong because it unnecessarily opens up possibilities to MANY bugs. When the @Override is invoked, the state of the object may be inconsistent and/or incomplete.

A quote from Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it:

There are a few more restrictions that a class must obey to allow inheritance. Constructors must not invoke overridable methods, directly or indirectly. If you violate this rule, program failure will result. The superclass constructor runs before the subclass constructor, so the overriding method in the subclass will be invoked before the subclass constructor has run. If the overriding method depends on any initialization performed by the subclass constructor, the method will not behave as expected.

Here's an example to illustrate:

public class ConstructorCallsOverride {
    public static void main(String[] args) {

        abstract class Base {
            Base() {
                overrideMe();
            }
            abstract void overrideMe(); 
        }

        class Child extends Base {

            final int x;

            Child(int x) {
                this.x = x;
            }

            @Override
            void overrideMe() {
                System.out.println(x);
            }
        }
        new Child(42); // prints "0"
    }
}

Here, when Base constructor calls overrideMe, Child has not finished initializing the final int x, and the method gets the wrong value. This will almost certainly lead to bugs and errors.

Related questions

See also


On object construction with many parameters

Constructors with many parameters can lead to poor readability, and better alternatives exist.

Here's a quote from Effective Java 2nd Edition, Item 2: Consider a builder pattern when faced with many constructor parameters:

Traditionally, programmers have used the telescoping constructor pattern, in which you provide a constructor with only the required parameters, another with a single optional parameters, a third with two optional parameters, and so on...

The telescoping constructor pattern is essentially something like this:

public class Telescope {
    final String name;
    final int levels;
    final boolean isAdjustable;

    public Telescope(String name) {
        this(name, 5);
    }
    public Telescope(String name, int levels) {
        this(name, levels, false);
    }
    public Telescope(String name, int levels, boolean isAdjustable) {       
        this.name = name;
        this.levels = levels;
        this.isAdjustable = isAdjustable;
    }
}

And now you can do any of the following:

new Telescope("X/1999");
new Telescope("X/1999", 13);
new Telescope("X/1999", 13, true);

You can't, however, currently set only the name and isAdjustable, and leaving levels at default. You can provide more constructor overloads, but obviously the number would explode as the number of parameters grow, and you may even have multiple boolean and int arguments, which would really make a mess out of things.

As you can see, this isn't a pleasant pattern to write, and even less pleasant to use (What does "true" mean here? What's 13?).

Bloch recommends using a builder pattern, which would allow you to write something like this instead:

Telescope telly = new Telescope.Builder("X/1999").setAdjustable(true).build();

Note that now the parameters are named, and you can set them in any order you want, and you can skip the ones that you want to keep at default values. This is certainly much better than telescoping constructors, especially when there's a huge number of parameters that belong to many of the same types.

See also

Related questions

Mask output of `The following objects are masked from....:` after calling attach() function

You actually don't need to use the attach at all. I had the same problem and it was resolved by removing the attach statement.

Write to custom log file from a Bash script

If you see the man page of logger:

$ man logger

LOGGER(1) BSD General Commands Manual LOGGER(1)

NAME logger — a shell command interface to the syslog(3) system log module

SYNOPSIS logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message ...]

DESCRIPTION Logger makes entries in the system log. It provides a shell command interface to the syslog(3) system log module.

It Clearly says that it will log to system log. If you want to log to file, you can use ">>" to redirect to log file.

IIS Express Windows Authentication

option-1:

edit \My Documents\IISExpress\config\applicationhost.config file and enable windowsAuthentication, i.e:

<system.webServer>
...
  <security>
...
    <authentication>
      <windowsAuthentication enabled="true" />
    </authentication>
...
  </security>
...
</system.webServer>

option-2:

Unlock windowsAuthentication section in \My Documents\IISExpress\config\applicationhost.config as follows

<add name="WindowsAuthenticationModule" lockItem="false" />

Alter override settings for the required authentication types to 'Allow'

<sectionGroup name="security">
    ...
    <sectionGroup name="system.webServer">
        ...
        <sectionGroup name="authentication">
            <section name="anonymousAuthentication" overrideModeDefault="Allow" />
            ...
            <section name="windowsAuthentication" overrideModeDefault="Allow" />
    </sectionGroup>
</sectionGroup>

Add following in the application's web.config

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
      <security>
        <authentication>
          <windowsAuthentication enabled="true" />
        </authentication>
      </security>
    </system.webServer>
</configuration>

Below link may help: http://learn.iis.net/page.aspx/376/delegating-configuration-to-webconfig-files/

After installing VS 2010 SP1 applying option 1 + 2 may be required to get windows authentication working. In addition, you may need to set anonymous authentication to false in IIS Express applicationhost.config:

<authentication>

            <anonymousAuthentication enabled="false" userName="" />

for VS2015, the IIS Express applicationhost config file may be located here:

$(solutionDir)\.vs\config\applicationhost.config

and the <UseGlobalApplicationHostFile> option in the project file selects the default or solution-specific config file.

ASP.NET MVC - Set custom IIdentity or IPrincipal

Based on LukeP's answer, and add some methods to setup timeout and requireSSL cooperated with Web.config.

The references links

Modified Codes of LukeP

1, Set timeout based on Web.Config. The FormsAuthentication.Timeout will get the timeout value, which is defined in web.config. I wrapped the followings to be a function, which return a ticket back.

int version = 1;
DateTime now = DateTime.Now;

// respect to the `timeout` in Web.config.
TimeSpan timeout = FormsAuthentication.Timeout;
DateTime expire = now.Add(timeout);
bool isPersist = false;

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
     version,          
     name,
     now,
     expire,
     isPersist,
     userData);

2, Configure the cookie to be secure or not, based on the RequireSSL configuration.

HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
// respect to `RequreSSL` in `Web.Config`
bool bSSL = FormsAuthentication.RequireSSL;
faCookie.Secure = bSSL;

Where are environment variables stored in the Windows Registry?

CMD:

reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
reg query HKEY_CURRENT_USER\Environment

PowerShell:

Get-Item "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
Get-Item HKCU:\Environment

Powershell/.NET: (see EnvironmentVariableTarget Enum)

[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::Machine)
[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::User)

Is there possibility of sum of ArrayList without looping

This can be done with reduce using method references reduce(Integer::sum):

Integer reduceSum = Arrays.asList(1, 3, 4, 6, 4)
        .stream()
        .reduce(Integer::sum)
        .get();

Or without Optional:

Integer reduceSum = Arrays.asList(1, 3, 4, 6, 4)
        .stream()
        .reduce(0, Integer::sum);

Generating a PNG with matplotlib when DISPLAY is undefined

I found this snippet to work well when switching between X and no-X environments.

import os
import matplotlib as mpl
if os.environ.get('DISPLAY','') == '':
    print('no display found. Using non-interactive Agg backend')
    mpl.use('Agg')
import matplotlib.pyplot as plt

$ is not a function - jQuery error

<script type="text/javascript">
    $("ol li:nth-child(1)").addClass('olli1');
    $("ol li:nth-child(2)").addClass("olli2");
    $("ol li:nth-child(3)").addClass("olli3");
    $("ol li:nth-child(4)").addClass("olli4");
    $("ol li:nth-child(5)").addClass("olli5");
    $("ol li:nth-child(6)").addClass("olli6");
    $("ol li:nth-child(7)").addClass("olli7");
    $("ol li:nth-child(8)").addClass("olli8");
    $("ol li:nth-child(9)").addClass("olli9");
    $("ol li:nth-child(10)").addClass("olli10");
    $("ol li:nth-child(11)").addClass("olli11");
    $("ol li:nth-child(12)").addClass("olli12");
    $("ol li:nth-child(13)").addClass("olli13");
    $("ol li:nth-child(14)").addClass("olli14");
    $("ol li:nth-child(15)").addClass("olli15");
    $("ol li:nth-child(16)").addClass("olli16");
    $("ol li:nth-child(17)").addClass("olli17");
    $("ol li:nth-child(18)").addClass("olli18");
    $("ol li:nth-child(19)").addClass("olli19");
    $("ol li:nth-child(20)").addClass("olli20"); 
</script>

change this to

    <script type="text/javascript">
        jQuery(document).ready(function ($) {
        $("ol li:nth-child(1)").addClass('olli1');
        $("ol li:nth-child(2)").addClass("olli2");
        $("ol li:nth-child(3)").addClass("olli3");
        $("ol li:nth-child(4)").addClass("olli4");
        $("ol li:nth-child(5)").addClass("olli5");
        $("ol li:nth-child(6)").addClass("olli6");
        $("ol li:nth-child(7)").addClass("olli7");
        $("ol li:nth-child(8)").addClass("olli8");
        $("ol li:nth-child(9)").addClass("olli9");
        $("ol li:nth-child(10)").addClass("olli10");
        $("ol li:nth-child(11)").addClass("olli11");
        $("ol li:nth-child(12)").addClass("olli12");
        $("ol li:nth-child(13)").addClass("olli13");
        $("ol li:nth-child(14)").addClass("olli14");
        $("ol li:nth-child(15)").addClass("olli15");
        $("ol li:nth-child(16)").addClass("olli16");
        $("ol li:nth-child(17)").addClass("olli17");
        $("ol li:nth-child(18)").addClass("olli18");
        $("ol li:nth-child(19)").addClass("olli19");
        $("ol li:nth-child(20)").addClass("olli20"); 
     });
    </script>

the easiest way to convert matrix to one row vector

You can use the function RESHAPE:

B = reshape(A.',1,[]);

Commenting in a Bash script inside a multiline command

In addition to the examples by DigitalRoss, here's another form that you can use if you prefer $() instead of backticks `

echo abc $(: comment) \
     def $(: comment) \
     xyz

Of course, you can use the colon syntax with backticks as well:

echo abc `: comment` \
     def `: comment` \
     xyz

Additional Notes

The reason $(#comment) doesn't work is because once it sees the #, it treats the rest of the line as comments, including the closing parentheses: comment). So the parentheses is never closed.

Backticks parse differently and will detect the closing backtick even after a #.

How to deselect a selected UITableView cell?

Swift 3

I've run into this as well - when you navigate or unwind back to the table view it usually doesn't deselect the previously selected row for you. I put this code in the table view controller & it works well:

override func viewDidAppear(_ animated: Bool) {
    if let lastSelectedRow = tableView.indexPathForSelectedRow {
        tableView.deselectRow(at: lastSelectedRow, animated: true)
    }
}

What are best practices for multi-language database design?

I'm using next approach:

Product

ProductID OrderID,...

ProductInfo

ProductID Title Name LanguageID

Language

LanguageID Name Culture,....

Prevent PDF file from downloading and printing

(disclaimer - I work for Atalasoft)

If you present your PDF documents with the Atalasoft web image viewer, you can prevent the PDF from being downloaded. You could also control printing from javascript on the client side.

Setting Remote Webdriver to run tests in a remote computer using Java

This is how I got rid of the error:

WebDriverException: Error forwarding the new session cannot find : {platform=WINDOWS, ensureCleanSession=true, browserName=internet explorer, version=11}

In your nodeconfig.json, the version must be a String, not an integer.

So instead of using "version": 11 use "version": "11" (note the double quotes).

A full example of a working nodecondig.json file for a RemoteWebDriver:

{
  "capabilities":
  [
    {
      "platform": "WIN8_1",
      "browserName": "internet explorer",
      "maxInstances": 1,
      "seleniumProtocol": "WebDriver"
      "version": "11"
    }
    ,{
      "platform": "WIN7",
      "browserName": "chrome",
      "maxInstances": 4,
      "seleniumProtocol": "WebDriver"
      "version": "40"
    }
    ,{
      "platform": "LINUX",
      "browserName": "firefox",
      "maxInstances": 4,
      "seleniumProtocol": "WebDriver"
      "version": "33"
    }
  ],
  "configuration":
  {
    "proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
    "maxSession": 3,
    "port": 5555,
    "host": ip,
    "register": true,
    "registerCycle": 5000,
    "hubPort": 4444,
    "hubHost": {your-ip-address}
  }
}

How to use \n new line in VB msgbox() ...?

  • for VB: vbCrLf or vbNewLine
  • for VB.NET: Environment.NewLine or vbCrLf or Constants.vbCrLf

Info on VB.NET new line: http://msdn.microsoft.com/en-us/library/system.environment.newline.aspx

The info for Environment.NewLine came from Cody Gray and J Vermeire

How can I replace a regex substring match in Javascript?

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;
str = str.replace(regex, "$11$2");
console.log(str);

Or if you're sure there won't be any other digits in the string:

var str   = 'asd-0.testing';
var regex = /\d/;
str = str.replace(regex, "1");
console.log(str);

Head and tail in one line

Python 2, using lambda

>>> head, tail = (lambda lst: (lst[0], lst[1:]))([1, 1, 2, 3, 5, 8, 13, 21, 34, 55])
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]

What is a monad?

following your brief, succinct, practical indications:

The easiest way to understand a monad is as a way to apply/compose functions within a context. Let's say you have two computations which both can be seen as two mathematical functions f and g.

  • f takes a String and produces another String (take the first two letters)
  • g takes a String and produces another String (upper case transformation)

So in any language the transformation "take the first two letter and convert them to upper case" would be written g(f("some string")). So, in the world of pure perfect functions, composition is just: do one thing and then do the other.

But let's say we live in the world of functions which can fail. For example: the input string might be one char long so f would fail. So in this case

  • f takes a String and produces a String or Nothing.
  • g produces a String only if f hasn't failed. Otherwise, produces Nothing

So now, g(f("some string")) needs some extra checking: "Compute f, if it fails then g should return Nothing, else compute g"

This idea can be applied to any parametrized type as follows:

Let Context[Sometype] be a computation of Sometype within a Context. Considering functions

  • f:: AnyType -> Context[Sometype]
  • g:: Sometype -> Context[AnyOtherType]

the composition g(f()) should be readed as "compute f. Within this context do some extra computations and then compute g if it has sense within the context"

How to list all properties of a PowerShell object

You can also use:

Get-WmiObject -Class "Win32_computersystem" | Select *

This will show the same result as Format-List * used in the other answers here.

case-insensitive matching in xpath?

XPath 2 has a lower-case (and upper-case) string function. That's not quite the same as case-insensitive, but hopefully it will be close enough:

//CD[lower-case(@title)='empire burlesque']

If you are using XPath 1, there is a hack using translate.

Convert LocalDateTime to LocalDateTime in UTC

Here's a simple little utility class that you can use to convert local date times from zone to zone, including a utility method directly to convert a local date time from the current zone to UTC (with main method so you can run it and see the results of a simple test):

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public final class DateTimeUtil {
    private DateTimeUtil() {
        super();
    }

    public static void main(final String... args) {
        final LocalDateTime now = LocalDateTime.now();
        final LocalDateTime utc = DateTimeUtil.toUtc(now);

        System.out.println("Now: " + now);
        System.out.println("UTC: " + utc);
    }

    public static LocalDateTime toZone(final LocalDateTime time, final ZoneId fromZone, final ZoneId toZone) {
        final ZonedDateTime zonedtime = time.atZone(fromZone);
        final ZonedDateTime converted = zonedtime.withZoneSameInstant(toZone);
        return converted.toLocalDateTime();
    }

    public static LocalDateTime toZone(final LocalDateTime time, final ZoneId toZone) {
        return DateTimeUtil.toZone(time, ZoneId.systemDefault(), toZone);
    }

    public static LocalDateTime toUtc(final LocalDateTime time, final ZoneId fromZone) {
        return DateTimeUtil.toZone(time, fromZone, ZoneOffset.UTC);
    }

    public static LocalDateTime toUtc(final LocalDateTime time) {
        return DateTimeUtil.toUtc(time, ZoneId.systemDefault());
    }
}

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

In redux-saga, the equivalent of the above example would be

export function* loginSaga() {
  while(true) {
    const { user, pass } = yield take(LOGIN_REQUEST)
    try {
      let { data } = yield call(request.post, '/login', { user, pass });
      yield fork(loadUserData, data.uid);
      yield put({ type: LOGIN_SUCCESS, data });
    } catch(error) {
      yield put({ type: LOGIN_ERROR, error });
    }  
  }
}

export function* loadUserData(uid) {
  try {
    yield put({ type: USERDATA_REQUEST });
    let { data } = yield call(request.get, `/users/${uid}`);
    yield put({ type: USERDATA_SUCCESS, data });
  } catch(error) {
    yield put({ type: USERDATA_ERROR, error });
  }
}

The first thing to notice is that we're calling the api functions using the form yield call(func, ...args). call doesn't execute the effect, it just creates a plain object like {type: 'CALL', func, args}. The execution is delegated to the redux-saga middleware which takes care of executing the function and resuming the generator with its result.

The main advantage is that you can test the generator outside of Redux using simple equality checks

const iterator = loginSaga()

assert.deepEqual(iterator.next().value, take(LOGIN_REQUEST))

// resume the generator with some dummy action
const mockAction = {user: '...', pass: '...'}
assert.deepEqual(
  iterator.next(mockAction).value, 
  call(request.post, '/login', mockAction)
)

// simulate an error result
const mockError = 'invalid user/password'
assert.deepEqual(
  iterator.throw(mockError).value, 
  put({ type: LOGIN_ERROR, error: mockError })
)

Note we're mocking the api call result by simply injecting the mocked data into the next method of the iterator. Mocking data is way simpler than mocking functions.

The second thing to notice is the call to yield take(ACTION). Thunks are called by the action creator on each new action (e.g. LOGIN_REQUEST). i.e. actions are continually pushed to thunks, and thunks have no control on when to stop handling those actions.

In redux-saga, generators pull the next action. i.e. they have control when to listen for some action, and when to not. In the above example the flow instructions are placed inside a while(true) loop, so it'll listen for each incoming action, which somewhat mimics the thunk pushing behavior.

The pull approach allows implementing complex control flows. Suppose for example we want to add the following requirements

  • Handle LOGOUT user action

  • upon the first successful login, the server returns a token which expires in some delay stored in a expires_in field. We'll have to refresh the authorization in the background on each expires_in milliseconds

  • Take into account that when waiting for the result of api calls (either initial login or refresh) the user may logout in-between.

How would you implement that with thunks; while also providing full test coverage for the entire flow? Here is how it may look with Sagas:

function* authorize(credentials) {
  const token = yield call(api.authorize, credentials)
  yield put( login.success(token) )
  return token
}

function* authAndRefreshTokenOnExpiry(name, password) {
  let token = yield call(authorize, {name, password})
  while(true) {
    yield call(delay, token.expires_in)
    token = yield call(authorize, {token})
  }
}

function* watchAuth() {
  while(true) {
    try {
      const {name, password} = yield take(LOGIN_REQUEST)

      yield race([
        take(LOGOUT),
        call(authAndRefreshTokenOnExpiry, name, password)
      ])

      // user logged out, next while iteration will wait for the
      // next LOGIN_REQUEST action

    } catch(error) {
      yield put( login.error(error) )
    }
  }
}

In the above example, we're expressing our concurrency requirement using race. If take(LOGOUT) wins the race (i.e. user clicked on a Logout Button). The race will automatically cancel the authAndRefreshTokenOnExpiry background task. And if the authAndRefreshTokenOnExpiry was blocked in middle of a call(authorize, {token}) call it'll also be cancelled. Cancellation propagates downward automatically.

You can find a runnable demo of the above flow

How can I stop "property does not exist on type JQuery" syntax errors when using Typescript?

You can cast it to

(<any>$('.selector') ).function();

Ex: date picker initialize using jquery

(<any>$('.datepicker') ).datepicker();

How can I call a WordPress shortcode within a template?

Try this:

<?php 
/*
Template Name: [contact us]

*/
get_header();
echo do_shortcode('[CONTACT-US-FORM]'); 
?>

What's the difference between a single precision and double precision floating point operation?

As to the question "Can the ps3 and xbxo 360 pull off double precision floating point operations or only single precision and in generel use is the double precision capabilities made use of (if they exist?)."

I believe that both platforms are incapable of double floating point. The original Cell processor only had 32 bit floats, same with the ATI hardware which the XBox 360 is based on (R600). The Cell got double floating point support later on, but I'm pretty sure the PS3 doesn't use that chippery.

Error "initializer element is not constant" when trying to initialize variable with const

This is a bit old, but I ran into a similar issue. You can do this if you use a pointer:

#include <stdio.h>
typedef struct foo_t  {
    int a; int b; int c;
} foo_t;
static const foo_t s_FooInit = { .a=1, .b=2, .c=3 };
// or a pointer
static const foo_t *const s_pFooInit = (&(const foo_t){ .a=2, .b=4, .c=6 });
int main (int argc, char **argv) {
    const foo_t *const f1 = &s_FooInit;
    const foo_t *const f2 = s_pFooInit;
    printf("Foo1 = %d, %d, %d\n", f1->a, f1->b, f1->c);
    printf("Foo2 = %d, %d, %d\n", f2->a, f2->b, f2->c);
    return 0;
}

jQuery Cross Domain Ajax

When using "jsonp", you would basically be returning data wrapped in a function call, something like

jsonpCallback([{"id":1,"value":"testing"},{"id":2,"value":"test again"}])
where the function/callback name is 'jsonpCallback'.

If you have access to the server, please first verify that the response is in the correct "jsonp" format

For such a response coming from the server, you would need to specify something in the ajax call as well, something like

jsonpCallback: "jsonpCallback",  in your ajax call

Please note that the name of the callback does not need to be "jsonpCallback" its just a name picked as an example but it needs to match the name(wrapping) done on the server side.

My first guess to your problem is that the response from the server is not what it should be.

Generics in C#, using type of a variable as parameter

The point about generics is to give compile-time type safety - which means that types need to be known at compile-time.

You can call generic methods with types only known at execution time, but you have to use reflection:

// For non-public methods, you'll need to specify binding flags too
MethodInfo method = GetType().GetMethod("DoesEntityExist")
                             .MakeGenericMethod(new Type[] { t });
method.Invoke(this, new object[] { entityGuid, transaction });

Ick.

Can you make your calling method generic instead, and pass in your type parameter as the type argument, pushing the decision one level higher up the stack?

If you could give us more information about what you're doing, that would help. Sometimes you may need to use reflection as above, but if you pick the right point to do it, you can make sure you only need to do it once, and let everything below that point use the type parameter in a normal way.

TOMCAT - HTTP Status 404

You don't have to use Tomcat installation as a server location. It is much easier just to copy the files in the ROOT folder.

Eclipse forgets to copy the default apps (ROOT, examples, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to C:\apache-tomcat-7.0.8\webapps, R-click on the ROOT folder and copy it. Then go to your Eclipse workspace, go to the .metadata folder, and search for "wtpwebapps". You should find something like your-eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps (or ../tmp1/wtpwebapps if you already had another server registered in Eclipse). Go to the wtpwebapps folder, R-click, and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reload http://localhost/ to see the Tomcat welcome page.

Source: HTTP Status 404 error in tomcat

Javascript split regex question

try this instead

date.split(/\W+/)

Anaconda version with Python 3.5

It is very simple, first, you need to be inside the virtualenv you created, then to install a specific version of python say 3.5, use Anaconda, conda install python=3.5

In general you can do this for any python package you want

conda install package_name=package_version

Psexec "run as (remote) admin"

Use psexec -s

The s switch will cause it to run under system account which is the same as running an elevated admin prompt. just used it to enable WinRM remotely.