Programs & Examples On #Advanceddatagrid

An extended version of the Flex DataGrid control that provides features like column groups and renderers for non-text data.

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?

for Xcode 8:

What I do is run sudo du -khd 1 in the Terminal to see my file system's storage amounts for each folder in simple text, then drill up/down into where the huge GB are hiding using the cd command.

Ultimately you'll find the Users//Library/Developer/CoreSimulator/Devices folder where you can have little concern about deleting all those "devices" using iOS versions you no longer need. It's also safe to just delete them all, but keep in mind you'll lose data that's written to the device like sqlite files you may want to use as a backup version.

I once saved over 50GB doing this since I did so much testing on older iOS versions.

Build a simple HTTP server in C

I suggest you take a look at tiny httpd. If you want to write it from scratch, then you'll want to thoroughly read RFC 2616. Use BSD sockets to access the network at a really low level.

How to convert a structure to a byte array in C#?

This can be done very straightforwardly.

Define your struct explicitly with [StructLayout(LayoutKind.Explicit)]

int size = list.GetLength(0);
IntPtr addr = Marshal.AllocHGlobal(size * sizeof(DataStruct));
DataStruct *ptrBuffer = (DataStruct*)addr;
foreach (DataStruct ds in list)
{
    *ptrBuffer = ds;
    ptrBuffer += 1;
}

This code can only be written in an unsafe context. You have to free addr when you're done with it.

Marshal.FreeHGlobal(addr);

Convert Char to String in C

Here is a working exemple :

printf("-%s-", (char[2]){'A', 0});

This will display -A-

Reference list item by index within Django template?

A better way: custom template filter: https://docs.djangoproject.com/en/dev/howto/custom-template-tags/

such as get my_list[x] in templates:

in template

{% load index %}
{{ my_list|index:x }}

templatetags/index.py

from django import template
register = template.Library()

@register.filter
def index(indexable, i):
    return indexable[i]

if my_list = [['a','b','c'], ['d','e','f']], you can use {{ my_list|index:x|index:y }} in template to get my_list[x][y]

It works fine with "for"

{{ my_list|index:forloop.counter0 }}

Tested and works well ^_^

Is there any boolean type in Oracle databases?

A common space-saving trick is storing boolean values as an Oracle CHAR, rather than NUMBER:

C++ float array initialization

You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,

float arr1[10] = { };       // all elements are 0
float arr2[10] = { 0 };     // all elements are 0
float arr3[10] = { 1 };     // first element is 1, all others are 0
float arr4[10] = { 1, 2 };  // first element is 1, second is 2, all others are 0

What character represents a new line in a text area


- Line Feed and 
 Carriage Return

These HTML entities will insert a new line or carriage return inside a text area.

How to extract a single value from JSON response?

Only suggestion is to access your resp_dict via .get() for a more graceful approach that will degrade well if the data isn't as expected.

resp_dict = json.loads(resp_str)
resp_dict.get('name') # will return None if 'name' doesn't exist

You could also add some logic to test for the key if you want as well.

if 'name' in resp_dict:
    resp_dict['name']
else:
    # do something else here.

How do I write data to csv file in columns and rows from a list in python?

Well, if you are writing to a CSV file, then why do you use space as a delimiter? CSV files use commas or semicolons (in Excel) as cell delimiters, so if you use delimiter=' ', you are not really producing a CSV file. You should simply construct csv.writer with the default delimiter and dialect. If you want to read the CSV file later into Excel, you could specify the Excel dialect explicitly just to make your intention clear (although this dialect is the default anyway):

example = csv.writer(open("test.csv", "wb"), dialect="excel")

How to retrieve a module's path?

If you would like to know absolute path from your script you can use Path object:

from pathlib import Path

print(Path().absolute())
print(Path().resolve('.'))
print(Path().cwd())

cwd() method

Return a new path object representing the current directory (as returned by os.getcwd())

resolve() method

Make the path absolute, resolving any symlinks. A new path object is returned:

whitespaces in the path of windows filepath

Try putting double quotes in your filepath variable

"\"E:/ABC/SEM 2/testfiles/all.txt\""

Check the permissions of the file or in any case consider renaming the folder to remove the space

What is difference between MVC, MVP & MVVM design pattern in terms of coding c#

Great Explanation from the link : http://geekswithblogs.net/dlussier/archive/2009/11/21/136454.aspx

Let's First look at MVC

The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality.

There is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed.

There is one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller.

The Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.

MVP – Model View Presenter

Now let’s look at the MVP pattern. It looks very similar to MVC, except for some key distinctions:

The input begins with the View, not the Presenter.

There is a one-to-one mapping between the View and the associated Presenter.

The View holds a reference to the Presenter. The Presenter is also reacting to events being triggered from the View, so its aware of the View its associated with.

The Presenter updates the View based on the requested actions it performs on the Model, but the View is not Model aware.

MVVM – Model View View Model

So with the MVC and MVP patterns in front of us, let’s look at the MVVM pattern and see what differences it holds:

The input begins with the View, not the View Model.

While the View holds a reference to the View Model, the View Model has no information about the View. This is why its possible to have a one-to-many mapping between various Views and one View Model…even across technologies. For example, a WPF View and a Silverlight View could share the same View Model.

How to use && in EL boolean expressions in Facelets?

Facelets is a XML based view technology. The & is a special character in XML representing the start of an entity like & which ends with the ; character. You'd need to either escape it, which is ugly:

rendered="#{beanA.prompt == true && beanB.currentBase != null}"

or to use the and keyword instead, which is preferred as to readability and maintainability:

rendered="#{beanA.prompt == true and beanB.currentBase != null}"

See also:


Unrelated to the concrete problem, comparing booleans with booleans makes little sense when the expression expects a boolean outcome already. I'd get rid of == true:

rendered="#{beanA.prompt and beanB.currentBase != null}"

Checkout Jenkins Pipeline Git SCM with credentials?

It solved for me using

checkout scm: ([
                    $class: 'GitSCM',
                    userRemoteConfigs: [[credentialsId: '******',url: ${project_url}]],
                    branches: [[name: 'refs/tags/${project_tag}']]
            ])

Count the number of Occurrences of a Word in a String

We can count from many ways for the occurrence of substring:-

public class Test1 {
public static void main(String args[]) {
    String st = "abcdsfgh yfhf hghj gjgjhbn hgkhmn abc hadslfahsd abcioh abc  a ";
    count(st, 0, "a".length());

}

public static void count(String trim, int i, int length) {
    if (trim.contains("a")) {
        trim = trim.substring(trim.indexOf("a") + length);
        count(trim, i + 1, length);
    } else {
        System.out.println(i);
    }
}

public static void countMethod2() {
    int index = 0, count = 0;
    String inputString = "mynameiskhanMYlaptopnameishclMYsirnameisjasaiwalmyfrontnameisvishal".toLowerCase();
    String subString = "my".toLowerCase();

    while (index != -1) {
        index = inputString.indexOf(subString, index);
        if (index != -1) {
            count++;
            index += subString.length();
        }
    }
    System.out.print(count);
}}

How do I improve ASP.NET MVC application performance?

Using Bundling and Minification also helps you improve the performance. It basically reduces the page loading time.

How do I find the stack trace in Visual Studio?

Do you mean finding a stack trace of the thrown exception location? That's either Debug/Exceptions, or better - Ctrl-Alt-E. Set filters for the exceptions you want to break on.

There's even a way to reconstruct the thrower stack after the exception was caught, but it's really unpleasant. Much, much easier to set a break on the throw.

Function vs. Stored Procedure in SQL Server

  • It is mandatory for Function to return a value while it is not for stored procedure.
  • Select statements only accepted in UDF while DML statements not required.
  • Stored procedure accepts any statements as well as DML statements.
  • UDF only allows inputs and not outputs.
  • Stored procedure allows for both inputs and outputs.
  • Catch blocks cannot be used in UDF but can be used in stored procedure.
  • No transactions allowed in functions in UDF but in stored procedure they are allowed.
  • Only table variables can be used in UDF and not temporary tables.
  • Stored procedure allows for both table variables and temporary tables.
  • UDF does not allow stored procedures to be called from functions while stored procedures allow calling of functions.
  • UDF is used in join clause while stored procedures cannot be used in join clause.
  • Stored procedure will always allow for return to zero. UDF, on the contrary, has values that must come - back to a predetermined point.

Controlling number of decimal digits in print output in R

If you are producing the entire output yourself, you can use sprintf(), e.g.

> sprintf("%.10f",0.25)
[1] "0.2500000000"

specifies that you want to format a floating point number with ten decimal points (in %.10f the f is for float and the .10 specifies ten decimal points).

I don't know of any way of forcing R's higher level functions to print an exact number of digits.

Displaying 100 digits does not make sense if you are printing R's usual numbers, since the best accuracy you can get using 64-bit doubles is around 16 decimal digits (look at .Machine$double.eps on your system). The remaining digits will just be junk.

Display a float with two decimal places in Python

You could use the string formatting operator for that:

>>> '%.2f' % 1.234
'1.23'
>>> '%.2f' % 5.0
'5.00'

The result of the operator is a string, so you can store it in a variable, print etc.

How to plot a function curve in R

As sjdh also mentioned, ggplot2 comes to the rescue. A more intuitive way without making a dummy data set is to use xlim:

library(ggplot2)
eq <- function(x){sin(x)}
base <- ggplot() + xlim(0, 30)
base + geom_function(fun=eq)

Additionally, for a smoother graph we can set the number of points over which the graph is interpolated using n:

base + geom_function(fun=eq, n=10000)

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

Try adding all these headers in this code below Before every route, you define in your app, not after the routes

app.use((req, res, next) =>{
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers','Origin, X-Requested-With, Content-Type,Accept, Authortization');  
res.setHeader('Acces-Control-Allow-Methods','GET, POST, PATCH, DELETE');

How to overwrite existing files in batch?

Add /y to the command line of xcopy:

Example:

xcopy /y c:\mmyinbox\test.doc C:\myoutbox

Why does my sorting loop seem to append an element where it shouldn't?

Starting from Java 8, you can also use parallelSort which is useful if you have arrays containing a lot of elements.

Example:

public static void main(String[] args) {
    String[] strings = { "x", "a", "c", "b", "y" };
    Arrays.parallelSort(strings);
    System.out.println(Arrays.toString(strings));   // [a, b, c, x, y]
}

If you want to ignore the case, you can use:

public static void main(String[] args) {
    String[] strings = { "x", "a", "c", "B", "y" };
    Arrays.parallelSort(strings, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {              
            return o1.compareToIgnoreCase(o2);
        }
    });
    System.out.println(Arrays.toString(strings));   // [a, B, c, x, y]
}

otherwise B will be before a.

If you want to ignore the trailing spaces during the comparison, you can use trim():

public static void main(String[] args) {
    String[] strings = { "x", "  a", "c ", " b", "y" };
    Arrays.parallelSort(strings, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {              
            return o1.trim().compareTo(o2.trim());
        }
    });
    System.out.println(Arrays.toString(strings)); // [  a,  b, c , x, y]
}

See:

How to use ArrayList.addAll()?

You can use Google guava as such:

ImmutableList<char> dirs = ImmutableList.of('+', '-', '*', '^');

Select records from NOW() -1 Day

Sure you can:

SELECT * FROM table
WHERE DateStamp > DATE_ADD(NOW(), INTERVAL -1 DAY)

Difference between onStart() and onResume()

onResume() is called:

  1. after onStart()
  2. when the Activity comes to the foreground.

From http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle: alt text

Convert ndarray from float64 to integer

While astype is probably the "best" option there are several other ways to convert it to an integer array. I'm using this arr in the following examples:

>>> import numpy as np
>>> arr = np.array([1,2,3,4], dtype=float)
>>> arr
array([ 1.,  2.,  3.,  4.])

The int* functions from NumPy

>>> np.int64(arr)
array([1, 2, 3, 4])

>>> np.int_(arr)
array([1, 2, 3, 4])

The NumPy *array functions themselves:

>>> np.array(arr, dtype=int)
array([1, 2, 3, 4])

>>> np.asarray(arr, dtype=int)
array([1, 2, 3, 4])

>>> np.asanyarray(arr, dtype=int)
array([1, 2, 3, 4])

The astype method (that was already mentioned but for completeness sake):

>>> arr.astype(int)
array([1, 2, 3, 4])

Note that passing int as dtype to astype or array will default to a default integer type that depends on your platform. For example on Windows it will be int32, on 64bit Linux with 64bit Python it's int64. If you need a specific integer type and want to avoid the platform "ambiguity" you should use the corresponding NumPy types like np.int32 or np.int64.

What is a good Hash Function?

I'd say that the main rule of thumb is not to roll your own. Try to use something that has been thoroughly tested, e.g., SHA-1 or something along those lines.

Where to download visual studio express 2005?

For somebody like me who lands onto this page from Google ages after this question had been posted, you can find VS2005 here: http://apdubey.blogspot.com/2009/04/microsoft-visual-studio-2005-express.html

EDIT: In case that blog dies, here are the links from the blog.

All the bellow files are more them 400MB.

Visual Web Developer 2005 Express Edition
449,848 KB
.IMG File | .ISO File

Visual Basic 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C# 2005 Express Edition
445,282 KB
.IMG File | .ISO File

Visual C++ 2005 Express Edition
474,686 KB
.IMG File | .ISO File

Visual J# 2005 Express Edition
448,702 KB
.IMG File | .ISO File

Reading Space separated input in python

For python 3 it would be like this n,m,p=map(int,input().split())

Using Notepad++ to validate XML against an XSD

  1. In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager then find Xml Tools plugin. Tick the box and click Install

    enter image description here

  2. Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now).
    Following dialog will open: enter image description here

  3. Click on .... Point to XSD file and I am pretty sure you'll be able to handle things from here.

Hope this saves you some time.

EDIT: Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1 plugin manager is back under a different guise... Plugin Admin so now you can simply update notepad++ and have it back.

enter image description here

Does Hibernate create tables in the database automatically

Hibernate can create a table, hibernate sequence and tables used for many-to-many mapping on your behalf but you have to explicitly configure it by calling setProperty("hibernate.hbm2ddl.auto", "create") of the Configuration object. By Default, it just validates the schema with DB and fails if anything not already exists by giving error "ORA-00942: table or view does not exist".

If you do above configuration then order of performed actions will be:- a) Drop all tables and sequence and do not give an error if they are not already present. b) create all table and sequence c) alter tables with constraints d) insert data into it.

CSS: auto height on containing div, 100% height on background div inside containing div

You shouldn't have to set height: 100% at any point if you want your container to fill the page. Chances are, your problem is rooted in the fact that you haven't cleared the floats in the container's children. There are quite a few ways to solve this problem, mainly adding overflow: hidden to the container.

#container { overflow: hidden; }

Should be enough to solve whatever height problem you're having.

Why is HttpContext.Current null?

try to implement Application_AuthenticateRequest instead of Application_Start.

this method has an instance for HttpContext.Current, unlike Application_Start (which fires very soon in app lifecycle, soon enough to not hold a HttpContext.Current object yet).

hope that helps.

Getting a directory name from a filename

Standard C++ won't do much for you in this regard, since path names are platform-specific. You can manually parse the string (as in glowcoder's answer), use operating system facilities (e.g. http://msdn.microsoft.com/en-us/library/aa364232(v=VS.85).aspx ), or probably the best approach, you can use a third-party filesystem library like boost::filesystem.

How to print the full NumPy array, without truncation?

Since NumPy version 1.16, for more details see GitHub ticket 12251.

from sys import maxsize
from numpy import set_printoptions

set_printoptions(threshold=maxsize)

Call a Javascript function every 5 seconds continuously

Good working example here: http://jsfiddle.net/MrTest/t4NXD/62/

Plus:

  • has nice fade in / fade out animation
  • will pause on :hover
  • will prevent running multiple actions (finish run animation before starting second)
  • will prevent going broken when in the tab ( browser stops scripts in the tabs)

Tested and working!

Use Mockito to mock some methods but not others

What you want is org.mockito.Mockito.CALLS_REAL_METHODS according to the docs:

/**
 * Optional <code>Answer</code> to be used with {@link Mockito#mock(Class, Answer)}
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations.
 * <p>
 * This implementation can be helpful when working with legacy code.
 * When this implementation is used, unstubbed methods will delegate to the real implementation.
 * This is a way to create a partial mock object that calls real methods by default.
 * <p>
 * As usual you are going to read <b>the partial mock warning</b>:
 * Object oriented programming is more less tackling complexity by dividing the complexity into separate, specific, SRPy objects.
 * How does partial mock fit into this paradigm? Well, it just doesn't... 
 * Partial mock usually means that the complexity has been moved to a different method on the same object.
 * In most cases, this is not the way you want to design your application.
 * <p>
 * However, there are rare cases when partial mocks come handy: 
 * dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.)
 * However, I wouldn't use partial mocks for new, test-driven & well-designed code.
 * <p>
 * Example:
 * <pre class="code"><code class="java">
 * Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
 *
 * // this calls the real implementation of Foo.getSomething()
 * value = mock.getSomething();
 *
 * when(mock.getSomething()).thenReturn(fakeValue);
 *
 * // now fakeValue is returned
 * value = mock.getSomething();
 * </code></pre>
 */

Thus your code should look like:

import org.junit.Test;
import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

public class StockTest {

    public class Stock {
        private final double price;
        private final int quantity;

        Stock(double price, int quantity) {
            this.price = price;
            this.quantity = quantity;
        }

        public double getPrice() {
            return price;
        }

        public int getQuantity() {
            return quantity;
        }

        public double getValue() {
            return getPrice() * getQuantity();
        }
    }

    @Test
    public void getValueTest() {
        Stock stock = mock(Stock.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
        when(stock.getPrice()).thenReturn(100.00);
        when(stock.getQuantity()).thenReturn(200);
        double value = stock.getValue();

        assertEquals("Stock value not correct", 100.00 * 200, value, .00001);
    }
}

The call to Stock stock = mock(Stock.class); calls org.mockito.Mockito.mock(Class<T>) which looks like this:

 public static <T> T mock(Class<T> classToMock) {
    return mock(classToMock, withSettings().defaultAnswer(RETURNS_DEFAULTS));
}

The docs of the value RETURNS_DEFAULTS tell:

/**
 * The default <code>Answer</code> of every mock <b>if</b> the mock was not stubbed.
 * Typically it just returns some empty value. 
 * <p>
 * {@link Answer} can be used to define the return values of unstubbed invocations. 
 * <p>
 * This implementation first tries the global configuration. 
 * If there is no global configuration then it uses {@link ReturnsEmptyValues} (returns zeros, empty collections, nulls, etc.)
 */

Move a view up only when the keyboard covers an input field

for swift 4.2.

This will apply to any form. No need of scrollview. do not forget to set delegate.

Make a var of uitextfield

var clickedTextField = UITextField()

In your viewdid load

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:NSNotification.Name.UIKeyboardWillShow, object: nil);
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:NSNotification.Name.UIKeyboardWillHide, object: nil);

Know the clicked text field. probably you are having textfields on the entire screen.

func textFieldDidBeginEditing(_ textField: UITextField) {
    clickedTextField = textField
}

Check if the keyboard is covering textfield or not.

@objc func keyboardWillShow(sender: NSNotification,_ textField : UITextField) {
    if let keyboardSize = (sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {

        if clickedTextField.frame.origin.y > keyboardSize.origin.y {
            self.view.frame.origin.y = keyboardSize.origin.y - clickedTextField.center.y - 20
        }
    }
}

@objc func keyboardWillHide(sender: NSNotification) {
    self.view.frame.origin.y = 0
}

Return to close keyboard

func textFieldShouldReturn(_ textField: UITextField) -> Bool {   //delegate method
    textField.resignFirstResponder()
    return true
}

UPDATE : NSNotification.Name.UIKeyboardWillShow & NSNotification.Name.UIKeyboardWillHide are renamed to UIResponder.keyboardWillShowNotification & UIResponder.keyboardWillHideNotification respectively.

Use a.empty, a.bool(), a.item(), a.any() or a.all()

solution is easy:

replace

 mask = (50  < df['heart rate'] < 101 &
            140 < df['systolic blood pressure'] < 160 &
            90  < df['dyastolic blood pressure'] < 100 &
            35  < df['temperature'] < 39 &
            11  < df['respiratory rate'] < 19 &
            95  < df['pulse oximetry'] < 100
            , "excellent", "critical")

by

mask = ((50  < df['heart rate'] < 101) &
        (140 < df['systolic blood pressure'] < 160) &
        (90  < df['dyastolic blood pressure'] < 100) &
        (35  < df['temperature'] < 39) &
        (11  < df['respiratory rate'] < 19) &
        (95  < df['pulse oximetry'] < 100)
        , "excellent", "critical")

Check if an array contains any element of another array in JavaScript

Update @Paul Grimshaw answer, use includes insteed of indexOf for more readable

let found = arr1.some(r=> arr2.indexOf(r) >= 0)
let found = arr1.some(r=> arr2.includes(r))

How does Facebook Sharer select Images and other metadata when sharing my URL?

This is what worked for me: I placed the desired thumbnail image on the page right after the tag and making it too small to see..

<img src="imagename.jpg" width="1" height="1" />

I have not tested it with height 0 and width 0 but it probably will still work.. This does not guarantee the user will select this image..

ALSO it seems like Facebook caches the thumbnails on your page and doesnt always check it for new ones.. try adding this to another page on your site and you'll see that it works.

python JSON object must be str, bytes or bytearray, not 'dict

json.loads take a string as input and returns a dictionary as output.

json.dumps take a dictionary as input and returns a string as output.


With json.loads({"('Hello',)": 6, "('Hi',)": 5}),

You are calling json.loads with a dictionary as input.

You can fix it as follows (though I'm not quite sure what's the point of that):

d1 = {"('Hello',)": 6, "('Hi',)": 5}
s1 = json.dumps(d1)
d2 = json.loads(s1)

ExecutorService that interrupts tasks after a timeout

Using John W answer I created an implementation that correctly begin the timeout when the task starts its execution. I even write a unit test for it :)

However, it does not suit my needs since some IO operations do not interrupt when Future.cancel() is called (ie when Thread.interrupt() is called). Some examples of IO operation that may not be interrupted when Thread.interrupt() is called are Socket.connect and Socket.read (and I suspect most of IO operation implemented in java.io). All IO operations in java.nio should be interruptible when Thread.interrupt() is called. For example, that is the case for SocketChannel.open and SocketChannel.read.

Anyway if anyone is interested, I created a gist for a thread pool executor that allows tasks to timeout (if they are using interruptible operations...): https://gist.github.com/amanteaux/64c54a913c1ae34ad7b86db109cbc0bf

How to use EOF to run through a text file in C?

You should check the EOF after reading from file.

fscanf_s                   // read from file
while(condition)           // check EOF
{
   fscanf_s               // read from file
}

Is there a way to create interfaces in ES6 / Node 4?

Given that ECMA is a 'class-free' language, implementing classical composition doesn't - in my eyes - make a lot of sense. The danger is that, in so doing, you are effectively attempting to re-engineer the language (and, if one feels strongly about that, there are excellent holistic solutions such as the aforementioned TypeScript that mitigate reinventing the wheel)

Now that isn't to say that composition is out of the question however in Plain Old JS. I researched this at length some time ago. The strongest candidate I have seen for handling composition within the object prototypal paradigm is stampit, which I now use across a wide range of projects. And, importantly, it adheres to a well articulated specification.

more information on stamps here

Difference between parameter and argument

They are often used interchangeably in text, but in most standards the distinction is that an argument is an expression passed to a function, where a parameter is a reference declared in a function declaration.

How to parse string into date?

Assuming that the database is MS SQL Server 2012 or greater, here's a solution that works. The basic statement contains the in-line try-parse:

SELECT TRY_PARSE('02/04/2016 10:52:00' AS datetime USING 'en-US') AS Result;

Here's what we implemented in the production version:

UPDATE dbo.StagingInputReview
 SET ReviewedOn = 
     ISNULL(TRY_PARSE(RTrim(LTrim(ReviewedOnText)) AS datetime USING 'en-US'), getdate()),
 ModifiedOn = (getdate()), ModifiedBy = (suser_sname())
 -- Check for empty/null/'NULL' text
 WHERE not ReviewedOnText is null 
   AND RTrim(LTrim(ReviewedOnText))<>''
   AND Replace(RTrim(LTrim(ReviewedOnText)),'''','') <> 'NULL';

The ModifiedOn and ModifiedBy columns are just for internal database tracking purposes.

See also these Microsoft MSDN references:

Creating a BLOB from a Base64 string in JavaScript

For all copy-paste lovers out there like me, here is a cooked download function which works on Chrome, Firefox and Edge:

window.saveFile = function (bytesBase64, mimeType, fileName) {
var fileUrl = "data:" + mimeType + ";base64," + bytesBase64;
fetch(fileUrl)
    .then(response => response.blob())
    .then(blob => {
        var link = window.document.createElement("a");
        link.href = window.URL.createObjectURL(blob, { type: mimeType });
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    });
}

Change URL parameters

I just wrote a simple module to deal with reading and updating the current url query params.

Example usage:

import UrlParams from './UrlParams'

UrlParams.remove('foo') //removes all occurences of foo=?
UrlParams.set('foo', 'bar') //set all occurences of foo equal to bar
UrlParams.add('foo', 'bar2') //add bar2 to foo result: foo=bar&foo=bar2
UrlParams.get('foo') //returns bar
UrlParams.get('foo', true) //returns [bar, bar2]

Here is my code named UrlParams.(js/ts):

class UrlParams {

    /**
     * Get params from current url
     * 
     * @returns URLSearchParams
     */
    static getParams(){
        let url = new URL(window.location.href)
        return new URLSearchParams(url.search.slice(1))
    }

    /**
     * Update current url with params
     * 
     * @param params URLSearchParams
     */
    static update(params){
        if(`${params}`){
            window.history.replaceState({}, '', `${location.pathname}?${params}`)
        } else {
            window.history.replaceState({}, '', `${location.pathname}`)
        }
    }

    /**
     * Remove key from url query
     * 
     * @param param string
     */
    static remove(param){
        let params = this.getParams()
        if(params.has(param)){
            params.delete(param)
            this.update(params)
        }
    }

    /**
     * Add key value pair to current url
     * 
     * @param key string
     * @param value string
     */
    static add(key, value){
        let params = this.getParams()
        params.append(key, value)
        this.update(params)
    }

    /**
     * Get value or values of key
     * 
     * @param param string
     * @param all string | string[]
     */
    static get(param, all=false){
        let params = this.getParams()
        if(all){
            return params.getAll(param)
        }
        return params.get(param)
    }

    /**
     * Set value of query param
     * 
     * @param key string
     * @param value string
     */
    static set(key, value){
        let params = this.getParams()
        params.set(key, value)
        this.update(params)
    }

}
export default UrlParams
export { UrlParams }

Excel VBA If cell.Value =... then

You can determine if as certain word is found in a cell by using

If InStr(cell.Value, "Word1") > 0 Then

If Word1 is found in the string the InStr() function will return the location of the first character of Word1 in the string.

Construct a manual legend for a complicated plot

In case you were struggling to change linetypes, the following answer should be helpful. (This is an addition to the solution by Andy W.)

We will try to extend the learned pattern:

cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
line_types <- c("LINE1"=1,"LINE2"=3)
ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1", linetype="LINE1"),size=0.5) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=2) +           #red
  geom_line(aes(y=c,group=1,colour="LINE2", linetype="LINE2"),size=0.5) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=2) +           #blue
  scale_colour_manual(name="Error Bars",values=cols, 
                  guide = guide_legend(override.aes=aes(fill=NA))) + 
  scale_linetype_manual(values=line_types)+
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

However, what we get is the following result: manual without name

The problem is that the linetype is not merged in the main legend. Note that we did not give any name to the method scale_linetype_manual. The trick which works here is to give it the same name as what you used for naming scale_colour_manual. More specifically, if we change the corresponding line to the following we get the desired result:

scale_linetype_manual(name="Error Bars",values=line_types)

manual with the same name

Now, it is easy to change the size of the line with the same idea.

Note that the geom_bar has not colour property anymore. (I did not try to fix this issue.) Also, adding geom_errorbar with colour attribute spoils the result. It would be great if somebody can come up with a better solution which resolves these two issues as well.

Django Multiple Choice Field / Checkbox Select Multiple

You can easily achieve this using ArrayField:

# in my models...
tags = ArrayField(models.CharField(null=True, blank=True, max_length=100, choices=SECTORS_TAGS_CHOICES), blank=True, default=list)

# in my forms...
class MyForm(forms.ModelForm):

    class Meta:
        model = ModelClass
        fields = [..., 'tags', ...]

I use tagsinput JS library to render my tags but you can use whatever you like: This my template for this widget:

{% if not hidelabel and field.label %}<label for="{{ field.id_for_label }}">{{ field.label }}</label>{% endif %}
<input id="{{ field.id_for_label }}" type="text" name="{{ field.name }}" data-provide="tagsinput"{% if field.value %} value="{{ field.value }}"{% endif %}{% if field.field.disabled %} disabled{% endif %}>
{% if field.help_text %}<small id="{{ field.name }}-help-text" class="form-text text-muted">{{ field.help_text | safe }}</small>{% endif %}

Accessing a property in a parent Component

You could:

  • Define a userStatus parameter for the child component and provide the value when using this component from the parent:

    @Component({
      (...)
    })
    export class Profile implements OnInit {
      @Input()
      userStatus:UserStatus;
    
      (...)
    }
    

    and in the parent:

    <profile [userStatus]="userStatus"></profile>
    
  • Inject the parent into the child component:

    @Component({
      (...)
    })
    export class Profile implements OnInit {
      constructor(app:App) {
        this.userStatus = app.userStatus;
      }
    
      (...)
    }
    

    Be careful about cyclic dependencies between them.

Save image from url with curl PHP

Improved version of Komang answer (add referer and user agent, check if you can write the file), return true if it's ok, false if there is an error :

public function downloadImage($url,$filename){
    if(file_exists($filename)){
        @unlink($filename);
    }
    $fp = fopen($filename,'w');
    if($fp){
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
        $result = parse_url($url);
        curl_setopt($ch, CURLOPT_REFERER, $result['scheme'].'://'.$result['host']);
        curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0');
        $raw=curl_exec($ch);
        curl_close ($ch);
        if($raw){
            fwrite($fp, $raw);
        }
        fclose($fp);
        if(!$raw){
            @unlink($filename);
            return false;
        }
        return true;
    }
    return false;
}

Getting the last n elements of a vector. Is there a better way than using the length() function?

You can do exactly the same thing in R with two more characters:

x <- 0:9
x[-5:-1]
[1] 5 6 7 8 9

or

x[-(1:5)]

Managing jQuery plugin dependency in webpack

In your webpack.config.js file add below:

 var webpack = require("webpack");
 plugins: [
    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery"
    })
 ],

Install jQuery using npm:

$ npm i jquery --save

In app.js file add below lines:

import $ from 'jquery';
window.jQuery = $;
window.$ = $;

This worked for me. :)

List of foreign keys and the tables they reference in Oracle DB

select d.table_name,

       d.constraint_name "Primary Constraint Name",

       b.constraint_name "Referenced Constraint Name"

from user_constraints d,

     (select c.constraint_name,

             c.r_constraint_name,

             c.table_name

      from user_constraints c 

      where table_name='EMPLOYEES' --your table name instead of EMPLOYEES

      and constraint_type='R') b

where d.constraint_name=b.r_constraint_name

How to achieve pagination/table layout with Angular.js?

The best simple plug and play solution for pagination.

https://ciphertrick.com/2015/06/01/search-sort-and-pagination-ngrepeat-angularjs/#comment-1002

you would jus need to replace ng-repeat with custom directive.

<tr dir-paginate="user in userList|filter:search |itemsPerPage:7">
<td>{{user.name}}</td></tr>

Within the page u just need to add

<div align="center">
       <dir-pagination-controls
            max-size="100"
            direction-links="true"
            boundary-links="true" >
       </dir-pagination-controls>
</div>

In your index.html load

<script src="./js/dirPagination.js"></script>

In your module just add dependencies

angular.module('userApp',['angularUtils.directives.dirPagination']);

and thats all needed for pagination.

Might be helpful for someone.

Command /Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

My problem was that under Build Phases -> Compile Sources, I added a compiler flag for a file, but I had misspelled it. It was supposed to be:

-fno-obj-arc

to show that this file does not use ARC.

Error on line 2 at column 1: Extra content at the end of the document

The problem is database connection string, one of your MySQL database connection function parameter is not correct ,so there is an error message in the browser output, Just right click output webpage and view html source code you will see error line followed by correct XML output data(file). I had same problem and the above solution worked perfectly.

CSS3 transform: rotate; in IE9

I also had problems with transformations in IE9, I used -ms-transform: rotate(10deg) and it didn't work. Tried everything I could, but the problem was in browser mode, to make transformations work, you need to set compatibility mode to "Standard IE9".

Oracle comparing timestamp with date

You can truncate the date part:

select * from table1 where trunc(field1) = to_date('2012-01-01', 'YYYY-MM-DD')

The trouble with this approach is that any index on field1 wouldn't be used due to the function call.

Alternatively (and more index friendly)

select * from table1 
 where field1 >= to_timestamp('2012-01-01', 'YYYY-MM-DD') 
   and field1 < to_timestamp('2012-01-02', 'YYYY-MM-DD')

Printing 2D array in matrix format

You can do it like this (with a slightly modified array to show it works for non-square arrays):

        long[,] arr = new long[5, 4] { { 1, 2, 3, 4 }, { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 }, { 4, 4, 4, 4 } };

        int rowLength = arr.GetLength(0);
        int colLength = arr.GetLength(1);

        for (int i = 0; i < rowLength; i++)
        {
            for (int j = 0; j < colLength; j++)
            {
                Console.Write(string.Format("{0} ", arr[i, j]));
            }
            Console.Write(Environment.NewLine + Environment.NewLine);
        }
        Console.ReadLine();

How do you sign a Certificate Signing Request with your Certification Authority?

In addition to answer of @jww, I would like to say that the configuration in openssl-ca.cnf,

default_days     = 1000         # How long to certify for

defines the default number of days the certificate signed by this root-ca will be valid. To set the validity of root-ca itself you should use '-days n' option in:

openssl req -x509 -days 3000 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM

Failing to do so, your root-ca will be valid for only the default one month and any certificate signed by this root CA will also have validity of one month.

Android Layout Weight

<LinearLayout
    android:id="@+id/linear1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:weightSum="9"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/ring_oss"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/ring_oss" />

    <ImageView
        android:id="@+id/maila_oss"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/maila_oss" />
<EditText
        android:id="@+id/edittxt"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="3"
        android:src="@drawable/maila_oss" />
</LinearLayout>

Update TensorFlow

Before trying to update tensorflow try updating pip

pip install --upgrade pip

If you are upgrading from a previous installation of TensorFlow < 0.7.1, you should uninstall the previous TensorFlow and protobuf using,

pip uninstall tensorflow

to make sure you get a clean installation of the updated protobuf dependency.

Uninstall the TensorFlow on your system, and check out Download and Setup to reinstall again.

If you are using pip install, go check the available version over https://storage.googleapis.com/tensorflow, search keywords with linux/cpu/tensorflow to see the availabilities.

Then, set the path for download and execute in sudo.

$ export TF_BINARY_URL=https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-1.0.0-py2-none-any.whl

$ sudo pip install --upgrade $TF_BINARY_URL

For more detail, follow this link in here

automatically execute an Excel macro on a cell change

Your code looks pretty good.

Be careful, however, for your call to Range("H5") is a shortcut command to Application.Range("H5"), which is equivalent to Application.ActiveSheet.Range("H5"). This could be fine, if the only changes are user-changes -- which is the most typical -- but it is possible for the worksheet's cell values to change when it is not the active sheet via programmatic changes, e.g. VBA.

With this in mind, I would utilize Target.Worksheet.Range("H5"):

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Target.Worksheet.Range("H5")) Is Nothing Then Macro
End Sub

Or you can use Me.Range("H5"), if the event handler is on the code page for the worksheet in question (it usually is):

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Me.Range("H5")) Is Nothing Then Macro
End Sub

Hope this helps...

How do you list all triggers in a MySQL database?

For showing a particular trigger in a particular schema you can try the following:

select * from information_schema.triggers where 
information_schema.triggers.trigger_name like '%trigger_name%' and 
information_schema.triggers.trigger_schema like '%data_base_name%'

Laravel back button

You can use {{ URL::previous() }} But it not perfect UX.

For example, when you press F5 button and click again to Back Button with {{ URL::previous() }} you will stay in.

A good way is using {{ route('page.edit', $item->id) }} it always true page you wanna to redirect.

Where can I find WcfTestClient.exe (part of Visual Studio)

The prerequisite to have WcfTestClient is to have Windows Communication Foundation component installed. If WcfTestClient is missing, install it by modifying Visual Studio:

Control Panel > Apps & Features > Visual Studio (your version)

In Visual Studio Installer, click on Modify, choose Individual components tab and then select (see below screenshot):

? Windows Communication Foundation

Click on Modify and voilà, application will be on your disk.

Visual Studio Installer

If you want to use WcfTestClient with no Visual Studio, see answer(s) on: How can the Wcf Test Client be used without Visual Studio?

PHP - find entry by object property from an array of objects

I've found more elegant solution here. Adapted to the question it may look like:

$neededObject = array_filter(
    $arrayOfObjects,
    function ($e) use ($searchedValue) {
        return $e->id == $searchedValue;
    }
);

Finding out current index in EACH loop (Ruby)

x.each_with_index { |v, i| puts "current index...#{i}" }

Intellisense and code suggestion not working in Visual Studio 2012 Ultimate RC

A. Save or export out your Import/Export settings:

Tools->Import and Export settings

B. Do the Import/ Export reset:

Tools->Import and Export settings->Reset all settings.

C. Go back and reload your original settings again! Intellisense works and you have your original settings back!

How can I make SQL case sensitive string comparison on MySQL?

The answer posted by Craig White has a big performance penalty

SELECT *  FROM `table` WHERE BINARY `column` = 'value'

because it doesn't use indexes. So, either you need to change the table collation like mention here https://dev.mysql.com/doc/refman/5.7/en/case-sensitivity.html.

OR

Easiest fix, you should use a BINARY of value.

SELECT *  FROM `table` WHERE `column` = BINARY 'value'

E.g.

mysql> EXPLAIN SELECT * FROM temp1 WHERE BINARY col1 = "ABC" AND col2 = "DEF" ;
+----+-------------+--------+------+---------------+------+---------+------+--------+-------------+
| id | select_type | table  | type | possible_keys | key  | key_len | ref  | rows   | Extra       |
+----+-------------+--------+------+---------------+------+---------+------+--------+-------------+
|  1 | SIMPLE      | temp1  | ALL  | NULL          | NULL | NULL    | NULL | 190543 | Using where |
+----+-------------+--------+------+---------------+------+---------+------+--------+-------------+

VS

mysql> EXPLAIN SELECT * FROM temp1 WHERE col1 = BINARY "ABC" AND col2 = "DEF" ;
+----+-------------+-------+-------+---------------+---------------+---------+------+------+------------------------------------+
| id | select_type | table | type  | possible_keys | key           | key_len | ref  | rows | Extra                              |
+----+-------------+-------+-------+---------------+---------------+---------+------+------+------------------------------------+
|  1 | SIMPLE      | temp1 | range | col1_2e9e898e | col1_2e9e898e | 93      | NULL |    2 | Using index condition; Using where |
+----+-------------+-------+-------+---------------+---------------+---------+------+------+------------------------------------+
enter code here

1 row in set (0.00 sec)

Tracking Google Analytics Page Views with AngularJS

The best way to do this is using Google Tag Manager to fire your Google Analytics tags based on history listeners. These are built in to the GTM interface and easily allow tracking on client side HTML5 interactions .

Enable the built in History variables and create a trigger to fire an event based on history changes.

PHPmailer sending HTML CODE

all you need to do is just add $mail->IsHTML(true); to the code it works fine..

JavaScript - Get Browser Height

With JQuery you can try this $(window).innerHeight() (Works for me on Chrome, FF and IE). With bootstrap modal I used something like the following;

$('#YourModal').on('show.bs.modal', function () {
    $('.modal-body').css('height', $(window).innerHeight() * 0.7);
});

Oracle SQL - DATE greater than statement

You need to convert the string to date using the to_date() function

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31-Dec-2014','DD-MON-YYYY');

OR

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('31 Dec 2014','DD MON YYYY');

OR

SELECT * FROM OrderArchive
WHERE OrderDate <= to_date('2014-12-31','yyyy-MM-dd');

This will work only if OrderDate is stored in Date format. If it is Varchar you should apply to_date() func on that column also like

 SELECT * FROM OrderArchive
    WHERE to_date(OrderDate,'yyyy-Mm-dd') <= to_date('2014-12-31','yyyy-MM-dd');

Select multiple columns by labels in pandas

Just pick the columns you want directly....

df[['A','E','I','C']]

What is the most compatible way to install python modules on a Mac?

I use easy_install with Apple's Python, and it works like a charm.

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

It is said that objects state is referred with respect to the fields in it and it would become ambiguous if too many classes were inherited. Here is the link

http://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html

Get a json via Http Request in NodeJS

http sends/receives data as strings... this is just the way things are. You are looking to parse the string as json.

var jsonObject = JSON.parse(data);

How to parse JSON using Node.js?

UIWebView open links in Safari

The other answers have one problem: they rely on the action you do and not on the link itself to decide whether to load it in Safari or in webview.

Now sometimes this is exactly what you want, which is fine; but some other times, especially if you have anchor links in your page, you want really to open only external links in Safari, and not internal ones. In that case you should check the URL.host property of your request.

I use that piece of code to check whether I have a hostname in the URL that is being parsed, or if it is embedded html:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    static NSString *regexp = @"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9-]*[a-zA-Z0-9])[.])+([A-Za-z]|[A-Za-z][A-Za-z0-9-]*[A-Za-z0-9])$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regexp];

    if ([predicate evaluateWithObject:request.URL.host]) {
        [[UIApplication sharedApplication] openURL:request.URL];
        return NO; 
    } else {
        return YES; 
    }
}

You can of course adapt the regular expression to fit your needs.

Create list of object from another using Java 8 Streams

If you want to iterate over a list and create a new list with "transformed" objects, you should use the map() function of stream + collect(). In the following example I find all people with the last name "l1" and each person I'm "mapping" to a new Employee instance.

public class Test {

    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
                new Person("e1", "l1"),
                new Person("e2", "l1"),
                new Person("e3", "l2"),
                new Person("e4", "l2")
        );

        List<Employee> employees = persons.stream()
                .filter(p -> p.getLastName().equals("l1"))
                .map(p -> new Employee(p.getName(), p.getLastName(), 1000))
                .collect(Collectors.toList());

        System.out.println(employees);
    }

}

class Person {

    private String name;
    private String lastName;

    public Person(String name, String lastName) {
        this.name = name;
        this.lastName = lastName;
    }

    // Getter & Setter
}

class Employee extends Person {

    private double salary;

    public Employee(String name, String lastName, double salary) {
        super(name, lastName);
        this.salary = salary;
    }

    // Getter & Setter
}

Calling Java from Python

Through my own experience trying to run some java code from within python i a manner similar to how python code runs within java code in python, I was unable to a find a straight forward methodology.

My solution to my problem was by running this java code as beanshell scripts by calling the beanshell interpreter as a shell commnad from within my python code after editing the java code in a temporary file with the appropriate packages and variables.

If what I am talking about is helpful in any manner, I am glad to help you sharing more details of my solutions.

How to loop through a plain JavaScript object with the objects as members?

I think it's worth pointing out that jQuery sorts this out nicely with $.each().

See: .each()

Example:

$('.foo').each(function() {
    console.log($(this));
});

$(this) being the single item inside the object. Swap $('.foo') to a variable if you don't want to use jQuery's selector engine.

How can I extract substrings from a string in Perl?

(\S*)\s*\((.*?)\)\s*(\*?)


(\S*)    picks up anything which is NOT whitespace
\s*      0 or more whitespace characters
\(       a literal open parenthesis
(.*?)    anything, non-greedy so stops on first occurrence of...
\)       a literal close parenthesis
\s*      0 or more whitespace characters
(\*?)    0 or 1 occurances of literal *

Detect HTTP or HTTPS then force HTTPS in JavaScript

How about this?

if (window.location.protocol !== 'https:') {
    window.location = 'https://' + window.location.hostname + window.location.pathname + window.location.hash;
}

Ideally you'd do it on the server side, though.

How to call MVC Action using Jquery AJAX and then submit form in MVC?

Use preventDefault() to stop the event of submit button and in ajax call success submit the form using submit():

$('#btnSave').click(function (e) {
    e.preventDefault(); // <------------------ stop default behaviour of button
    var element = this;    
    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.status == "Success") {
                alert("Done");
                $(element).closest("form").submit(); //<------------ submit form
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

Get json value from response

If response is in json and not a string then

alert(response.id);
or
alert(response['id']);

otherwise

var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301

How to use JavaScript to change div backgroundColor

This one might be a bit weird because I am really not a serious programmer and I am discovering things in programming the way penicillin was invented - sheer accident. So how to change an element on mouseover? Use the :hover attribute just like with a elements.

Example:

div.classname:hover
{
    background-color: black;
}

This changes any div with the class classname to have a black background on mousover. You can basically change any attribute. Tested in IE and Firefox

Happy programming!

jQuery add required to input fields

Should not enclose true with double quote " " it should be like

$(document).ready(function() {            
   $('input').attr('required', true);   
});

Also you can use prop

jQuery(document).ready(function() {            
   $('input').prop('required', true);   
}); 

Instead of true you can try required. Such as

$('input').prop('required', 'required');

rails simple_form - hidden field - create?

= f.input_field :title, as: :hidden, value: "some value"

Is also an option. Note, however, that it skips any wrapper defined for your form builder.

How to suppress scientific notation when printing float values?

Most of the answers above require you to specify precision. But what if you want to display floats like this, with no unnecessary zeros:

1
0.1
0.01
0.001
0.0001
0.00001
0.000001
0.000000000001

numpy has an answer: np.format_float_positional

import numpy as np

def format_float(num):
    return np.format_float_positional(num, trim='-')

pandas GroupBy columns with NaN (missing) values

This is mentioned in the Missing Data section of the docs:

NA groups in GroupBy are automatically excluded. This behavior is consistent with R

One workaround is to use a placeholder before doing the groupby (e.g. -1):

In [11]: df.fillna(-1)
Out[11]: 
   a   b
0  1   4
1  2  -1
2  3   6

In [12]: df.fillna(-1).groupby('b').sum()
Out[12]: 
    a
b    
-1  2
4   1
6   3

That said, this feels pretty awful hack... perhaps there should be an option to include NaN in groupby (see this github issue - which uses the same placeholder hack).

However, as described in another answer, "from pandas 1.1 you have better control over this behavior, NA values are now allowed in the grouper using dropna=False"

Console.WriteLine does not show up in Output window

Try to uncheck the CheckBox “Use Managed Compatibility Mode” in

Tools => Options => Debugging => General

It worked for me.

Calculate distance between 2 GPS coordinates

I guess you want it along the curvature of the earth. Your two points and the center of the earth are on a plane. The center of the earth is the center of a circle on that plane and the two points are (roughly) on the perimeter of that circle. From that you can calculate the distance by finding out what the angle from one point to the other is.

If the points are not the same heights, or if you need to take into account that the earth is not a perfect sphere it gets a little more difficult.

if (boolean condition) in Java

Booleans default value is false only for classes' fields. If within a method, you have to initialize your variable by true or false. Thus for example in your case, you'll have a compilation error.

Moreover, I don't really get the point, but the only way to enter within a if is to evaluate the condition to true.

How do I find out where login scripts live?

The default location for logon scripts is the netlogon share of a domain controller. On the server this is located:

%SystemRoot%'SYSVOL'sysvol''scripts

It can presumably be changes from this default but I've never met anyone that had a reason to.

To get list of domain controllers programatically see this article: http://www.microsoft.com/technet/scriptcenter/resources/qanda/dec04/hey1216.mspx

Run command on the Ansible host

ansible your_server_name -i custom_inventory_file_name -m -a "uptime"

The default module is command module, hence command keyword is not required.

If you need to issue any command with elevated privileges use -b at the end of the same command.

ansible your_server_name -i custom_inventory_file_name -m -a "uptime" -b

Importing packages in Java

You don't import methods in Java, only types:

import Dan.Vik;
class Kab
{
    public static void main(String args[])
    {
        Vik Sam = new Vik();
        Sam.disp();
    }
}

The exception is so-called "static imports", which let you import class (static) methods from other types.

Connecting to remote MySQL server using PHP

This maybe not the answer to poster's question.But this may helpful to people whose face same situation with me:

The client have two network cards,a wireless one and a normal one. The ping to server can be succeed.However telnet serverAddress 3306 would fail. And would complain

Can't connect to MySQL server on 'xxx.xxx.xxx.xxx' (10060)

when try to connect to server.So I forbidden the normal network adapters. And tried telnet serverAddress 3306 it works.And then it work when connect to MySQL server.

What is the fastest way to create a checksum for large files in C#

The problem here is that SHA256Managed reads 4096 bytes at a time (inherit from FileStream and override Read(byte[], int, int) to see how much it reads from the filestream), which is too small a buffer for disk IO.

To speed things up (2 minutes for hashing 2 Gb file on my machine with SHA256, 1 minute for MD5) wrap FileStream in BufferedStream and set reasonably-sized buffer size (I tried with ~1 Mb buffer):

// Not sure if BufferedStream should be wrapped in using block
using(var stream = new BufferedStream(File.OpenRead(filePath), 1200000))
{
    // The rest remains the same
}

Android saving file to external storage

Make sure your app has the proper permissions to be allowed to write to external storage: http://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE

It should look something like this in your manifest file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

dyld: Library not loaded: /usr/local/lib/libpng16.16.dylib with anything php related

I solved this by copying it over to the missing directory:

cp /opt/X11/lib/libpng15.15.dylib /usr/local/lib/libpng15.15.dylib

brew reinstall libpng kept installing libpng16, not libpng15 so I was forced to do the above.

How to beautify JSON in Python?

With jsonlint (like xmllint):

aptitude install python-demjson
jsonlint -f foo.json

Explaining Apache ZooKeeper

I would suggest the following resources:

  1. The paper: https://pdos.csail.mit.edu/6.824/papers/zookeeper.pdf
  2. The lecture offered by MIT 6.824 from 36:00: https://youtu.be/pbmyrNjzdDk?t=2198

I would suggest watching the video, read the paper, and then watch the video again. It would be easier to understand if you know Raft beforehand.

Groovy / grails how to determine a data type?

Simple groovy way to check object type:

somObject in Date

Can be applied also to interfaces.

Is there a command to list all Unix group names?

If you want all groups known to the system, I would recommend using getent group instead of parsing /etc/group:

getent group

The reason is that on networked systems, groups may not only read from /etc/group file, but also obtained through LDAP or Yellow Pages (the list of known groups comes from the local group file plus groups received via LDAP or YP in these cases).

If you want just the group names you can use:

getent group | cut -d: -f1

How can I do division with variables in a Linux shell?

Referencing Bash Variables Requires Parameter Expansion

The default shell on most Linux distributions is Bash. In Bash, variables must use a dollar sign prefix for parameter expansion. For example:

x=20
y=5
expr $x / $y

Of course, Bash also has arithmetic operators and a special arithmetic expansion syntax, so there's no need to invoke the expr binary as a separate process. You can let the shell do all the work like this:

x=20; y=5
echo $((x / y))

Avoid dropdown menu close on click inside

I did it with this:

$(element).on({
    'mouseenter': function(event) {
        $(event.currentTarget).data('mouseover', true);
    },
    'mouseleave': function(event) {
        $(event.currentTarget).data('mouseover', false);
    },
    'hide.bs.dropdown': function (event) {
        return !$(event.currentTarget).data('mouseover');
    }
});

How to search a string in String array

I'm surprised that no one suggested using Array.IndexOf Method.

Indeed, Array.IndexOf has two advantages :

  • It allows searching if an element is included into an array,
  • It gets at the same time the index into the array.
int stringIndex = Array.IndexOf(arr, theString);
if (stringIndex >= 0)
{
    // theString has been found
}

Inline version :

if (Array.IndexOf(arr, theString) >= 0)
{
    // theString has been found
}

How to show disable HTML select option in by default?

You can set which option is selected by default like this:

<option value="" selected>Choose Tagging</option>

I would suggest using javascript and JQuery to observe for click event and disable the first option after another has been selected: First, give the element an ID like so:

<select id="option_select" name="tagging">

and the option an id :

<option value="" id="initial">Choose Tagging</option>

then:

<script type="text/javascript">

$('option_select').observe(click, handleClickFunction);

Then you just create the function:

function handleClickFunction () {

if ($('option_select').value !== "option_select") 
{
   $('initial').disabled=true; }
}

What Vim command(s) can be used to quote/unquote words?

Here's some mapping that could help:

:nnoremap <Leader>q" ciw""<Esc>P
:nnoremap <Leader>q' ciw''<Esc>P
:nnoremap <Leader>qd daW"=substitute(@@,"'\\\|\"","","g")<CR>P

If you haven't changed the mapleader variable, then activate the mapping with \q" \q' or \qd. They add double quote around the word under the cursor, single quote around the word under the cursor, delete any quotes around the word under the cursor respectively.

How to play only the audio of a Youtube video using HTML 5?

You can parse Youtube meta file for all streams available for this particular video id using this link: https://www.youtube.com/get_video_info?video_id={VID} and extract audio only streams.

Here is an example with public Google Image proxy (but you can use any free or your own CORS proxy):

_x000D_
_x000D_
var vid = "3r_Z5AYJJd4",_x000D_
    audio_streams = {},_x000D_
    audio_tag = document.getElementById('youtube');_x000D_
_x000D_
fetch("https://"+vid+"-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=https%3A%2F%2Fwww.youtube.com%2Fget_video_info%3Fvideo_id%3D" + vid).then(response => {_x000D_
    if (response.ok) {_x000D_
        response.text().then(data => {_x000D_
_x000D_
            var data = parse_str(data),_x000D_
                streams = (data.url_encoded_fmt_stream_map + ',' + data.adaptive_fmts).split(',');_x000D_
_x000D_
            streams.forEach(function(s, n) {_x000D_
                var stream = parse_str(s),_x000D_
                    itag = stream.itag * 1,_x000D_
                    quality = false;_x000D_
                console.log(stream);_x000D_
                switch (itag) {_x000D_
                    case 139:_x000D_
                        quality = "48kbps";_x000D_
                        break;_x000D_
                    case 140:_x000D_
                        quality = "128kbps";_x000D_
                        break;_x000D_
                    case 141:_x000D_
                        quality = "256kbps";_x000D_
                        break;_x000D_
                }_x000D_
                if (quality) audio_streams[quality] = stream.url;_x000D_
            });_x000D_
_x000D_
            console.log(audio_streams);_x000D_
_x000D_
            audio_tag.src = audio_streams['128kbps'];_x000D_
            audio_tag.play();_x000D_
        })_x000D_
    }_x000D_
});_x000D_
_x000D_
function parse_str(str) {_x000D_
    return str.split('&').reduce(function(params, param) {_x000D_
        var paramSplit = param.split('=').map(function(value) {_x000D_
            return decodeURIComponent(value.replace('+', ' '));_x000D_
        });_x000D_
        params[paramSplit[0]] = paramSplit[1];_x000D_
        return params;_x000D_
    }, {});_x000D_
}
_x000D_
<audio id="youtube" autoplay controls loop></audio>
_x000D_
_x000D_
_x000D_

Doesn't work for all videos, very depends on monetization settings or something like that.

Get Locale Short Date Format using javascript

new Date(YOUR_DATE_STRING).toLocaleDateString(navigator.language)

~ combination of answers of above

Width equal to content

The solution with inline-block forces you to insert <br> after each element.
The solution with float forces you to wrap all elements with "clearfix" div.

Another elegant solution is to use display: table for elements.

With this solution you don't need to insert line breaks manually (like with inline-block), you don't need a wrapper around your elements (like with floats) and you can center your element if you need.

http://jsfiddle.net/8md3jy4r/3/

How can I clear event subscriptions in C#?

Add a method to c1 that will set 'someEvent' to null.

public class c1
{
    event EventHandler someEvent;
    public ResetSubscriptions() => someEvent = null;    
}

Visual Studio 2017 - Git failed with a fatal error

In Control Panel\All Control Panel Items\Credential Manager ==> Windows Credentials Remove Git:http://........

and Retry..

Enjoy !

SQL query to get most recent row for each instance of a given key

Nice elegant solution with ROW_NUMBER window function (supported by PostgreSQL - see in SQL Fiddle):

SELECT username, ip, time_stamp FROM (
 SELECT username, ip, time_stamp, 
  ROW_NUMBER() OVER (PARTITION BY username ORDER BY time_stamp DESC) rn
 FROM Users
) tmp WHERE rn = 1;

How can I decrypt a password hash in PHP?

The passwords cannot be decrypted as will makes a vulnerability for users. So, you can simply use password_verify() method to compare the passwords.

if(password_verify($upass, $userRow['user_pass'])){
     //code for redirecting to login screen }

where, $upass is password entered by user and $userRow['user_pass'] is user_pass field in database which is encrypted by password_hash() function.

Capturing URL parameters in request.GET

For situations where you only have the request object you can use request.parser_context['kwargs']['your_param']

Using jQuery to test if an input has focus

There is a plugin to check if an element is focused: http://plugins.jquery.com/project/focused

$('input').each(function(){
   if ($(this) == $.focused()) {
      $(this).addClass('focused');
   }
})

How to set full calendar to a specific start date when it's initialized for the 1st time?

In version 2.1.1 this works :

$('#calendar').fullCalendar({
// your calendar settings...
});

$('#calendar').fullCalendar('gotoDate', '2014-05-01');

Documentation about moment time/date format : http://fullcalendar.io/docs/utilities/Moment/ Documentation about the upgrades in version 2 : https://github.com/arshaw/fullcalendar/wiki/Upgrading-to-v2

Can't push to the heroku

If you are using django app to deploy on heroku

make sure to put request library in the requirements.txt file.

Find all table names with column name?

You could do this:

SELECT t.name AS table_name,
SCHEMA_NAME(schema_id) AS schema_name,
c.name AS column_name
FROM sys.tables AS t
INNER JOIN sys.columns c ON t.OBJECT_ID = c.OBJECT_ID
WHERE c.name LIKE '%MyColumn%'
ORDER BY schema_name, table_name;

Reference:

How to top, left justify text in a <td> cell that spans multiple rows

td[rowspan] {
  vertical-align: top;
  text-align: left;
}

See: CSS attribute selectors.

C++ - Assigning null to a std::string

I can't assign a null to a String?

No. std::string is not a pointer type; it cannot be made "null." It cannot represent the absence of a value, which is what a null pointer is used to represent.

It can be made empty, by assigning an empty string to it (s = "" or s = std::string()) or by clearing it (s.clear()).

What is the http-header "X-XSS-Protection"?

You can see in this List of useful HTTP headers.

X-XSS-Protection: This header enables the Cross-site scripting (XSS) filter built into most recent web browsers. It's usually enabled by default anyway, so the role of this header is to re-enable the filter for this particular website if it was disabled by the user. This header is supported in IE 8+, and in Chrome (not sure which versions). The anti-XSS filter was added in Chrome 4. Its unknown if that version honored this header.

Print an ArrayList with a for-each loop

import java.util.ArrayList;
import java.util.List;

class ArrLst{

    public static void main(String args[]){

        List l=new ArrayList();
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.forEach((a)->System.out.println(a));
    }
}

How can I inspect element in chrome when right click is disabled?

Sure, you can open the devtools with Ctrl+Shift+I, and then click the inspect element button (square with the arrow)

How to set ObjectId as a data type in mongoose

Unlike traditional RBDMs, mongoDB doesn't allow you to define any random field as the primary key, the _id field MUST exist for all standard documents.

For this reason, it doesn't make sense to create a separate uuid field.

In mongoose, the ObjectId type is used not to create a new uuid, rather it is mostly used to reference other documents.

Here is an example:

var mongoose = require('mongoose');

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;
var Schema_Product = new Schema({
    categoryId  : ObjectId, // a product references a category _id with type ObjectId
    title       : String,
    price       : Number
});

As you can see, it wouldn't make much sense to populate categoryId with a ObjectId.

However, if you do want a nicely named uuid field, mongoose provides virtual properties that allow you to proxy (reference) a field.

Check it out:

var mongoose = require('mongoose');

var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;
var Schema_Category = new Schema({
    title       : String,
    sortIndex   : String
});

Schema_Category.virtual('categoryId').get(function() {
    return this._id;
});

So now, whenever you call category.categoryId, mongoose just returns the _id instead.

You can also create a "set" method so that you can set virtual properties, check out this link for more info

Can you append strings to variables in PHP?

In PHP use .= to append strings, and not +=.

Why does this output 0? [...] Does PHP not like += with strings?

+= is an arithmetic operator to add a number to another number. Using that operator with strings leads to an automatic type conversion. In the OP's case the strings have been converted to integers of the value 0.


More about operators in PHP:

How to change users in TortoiseSVN

After struggling with this and trying all the answers on this page, I finally realized I had the incorrect credentials stored by windows for the server that hosts our subversion. I cleared this stored value from windows credentials and all is well.

https://web.archive.org/web/20160614002053/http://windows.microsoft.com/en-us/windows7/remove-stored-passwords-certificates-and-other-credentials

Loop through a Map with JSTL

You can loop through a hash map like this

<%
ArrayList list = new ArrayList();
TreeMap itemList=new TreeMap();
itemList.put("test", "test");
list.add(itemList);
pageContext.setAttribute("itemList", list);                            
%>

  <c:forEach items="${itemList}" var="itemrow">
   <input  type="text"  value="<c:out value='${itemrow.test}'/>"/>
  </c:forEach>               

For more JSTL functionality look here

Resize iframe height according to content height in it

You can do this with JavaScript.

document.getElementById('foo').height = document.getElementById('foo').contentWindow.document.body.scrollHeight + "px";

How to insert a value that contains an apostrophe (single quote)?

eduffy had a good idea. He just got it backwards in his code example. Either in JavaScript or in SQLite you can replace the apostrophe with the accent symbol.

He (accidentally I am sure) placed the accent symbol as the delimiter for the string instead of replacing the apostrophe in O'Brian. This is in fact a terrifically simple solution for most cases.

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

Python iterating through object attributes

UPDATED

For python 3, you should use items() instead of iteritems()

PYTHON 2

for attr, value in k.__dict__.iteritems():
        print attr, value

PYTHON 3

for attr, value in k.__dict__.items():
        print(attr, value)

This will print

'names', [a list with names]
'tweet', [a list with tweet]

How to populate/instantiate a C# array with a single value?

Make a private class inside where you make the array and the have a getter and setter for it. Unless you need each position in the array to be something unique, like random, then use int? as an array and then on get if the position is equal null fill that position and return the new random value.

IsVisibleHandler
{

  private bool[] b = new bool[10000];

  public bool GetIsVisible(int x)
  {
  return !b[x]
  }

  public void SetIsVisibleTrueAt(int x)
  {
  b[x] = false //!true
  }
}

Or use

public void SetIsVisibleAt(int x, bool isTrue)
{
b[x] = !isTrue;
}

As setter.

How to remove unused imports from Eclipse

Better way is just to add "save action" so when you save the project it will clear the unused import's and format the code as well if you like .

Go to Window > Preferences > Java > Editor > Save Actions

and pick what ever you want .

How to Exit a Method without Exiting the Program?

There are two ways to exit a method early (without quitting the program):

  • Use the return keyword.
  • Throw an exception.

Exceptions should only be used for exceptional circumstances - when the method cannot continue and it cannot return a reasonable value that would make sense to the caller. Usually though you should just return when you are done.

If your method returns void then you can write return without a value:

return;

Specifically about your code:

  • There is no need to write the same test three times. All those conditions are equivalent.
  • You should also use curly braces when you write an if statement so that it is clear which statements are inside the body of the if statement:

    if (textBox1.Text == String.Empty)
    {
        textBox3.Text += "[-] Listbox is Empty!!!!\r\n";
    }
    return; // Are you sure you want the return to be here??
    
  • If you are using .NET 4 there is a useful method that depending on your requirements you might want to consider using here: String.IsNullOrWhitespace.

  • You might want to use Environment.Newline instead of "\r\n".
  • You might want to consider another way to display invalid input other than writing messages to a text box.

How to fix height of TR?

I had to do this to get the result that I wanted:

<td style="font-size:3px; float:left; height:5px; vertical-align:middle;" colspan="7"><div style="font-size:3px; height:5px; vertical-align:middle;"><b><hr></b></div></td>

It refused to work with only the cell or the div and needed both.

Warning: Null value is eliminated by an aggregate or other SET operation in Aqua Data Studio

One way to solve this problem is by turning the warnings off.

SET ANSI_WARNINGS OFF;
GO

Understanding repr( ) function in Python

When you say

foo = 'bar'
baz(foo)

you are not passing foo to the baz function. foo is just a name used to represent a value, in this case 'bar', and that value is passed to the baz function.

Python - Join with newline

You forgot to print the result. What you get is the P in RE(P)L and not the actual printed result.

In Py2.x you should so something like

>>> print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines

and in Py3.X, print is a function, so you should do

print("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))

Now that was the short answer. Your Python Interpreter, which is actually a REPL, always displays the representation of the string rather than the actual displayed output. Representation is what you would get with the repr statement

>>> print repr("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))
'I\nwould\nexpect\nmultiple\nlines'

How to listen state changes in react.js?

Since React 16.8 in 2019 with useState and useEffect Hooks, following are now equivalent (in simple cases):

AngularJS:

$scope.name = 'misko'
$scope.$watch('name', getSearchResults)

<input ng-model="name" />

React:

const [name, setName] = useState('misko')
useEffect(getSearchResults, [name])

<input value={name} onChange={e => setName(e.target.value)} />

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

May be it helps some one, On Android i had same issue but i figured it out by using setTimeout inside document.ready so it worked for me secondly you have to increase the timeout just incase if user allow his location after few seconds, so i kept it to 60000 mili seconds (1 minute) allowing my success function to call if user click on allow button within 1 minute.

How do I bind a List<CustomObject> to a WPF DataGrid?

You dont need to give column names manually in xaml. Just set AutoGenerateColumns property to true and your list will be automatically binded to DataGrid. refer code. XAML Code:

<Grid>
    <DataGrid x:Name="MyDatagrid" AutoGenerateColumns="True" Height="447" HorizontalAlignment="Left" Margin="20,85,0,0" VerticalAlignment="Top" Width="799"  ItemsSource="{Binding Path=ListTest, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"  CanUserAddRows="False"> </Grid>

C#

Public Class Test 
{
    public string m_field1_Test{get;set;}
    public string m_field2_Test { get; set; }
    public Test()
    {
        m_field1_Test = "field1";
        m_field2_Test = "field2";
    }
    public MainWindow()
    {

        listTest = new List<Test>();

        for (int i = 0; i < 10; i++)
        {
            obj = new Test();
            listTest.Add(obj);

        }

        this.MyDatagrid.ItemsSource = ListTest;

        InitializeComponent();

    }

Behaviour of increment and decrement operators in Python

Python does not have these operators, but if you really need them you can write a function having the same functionality.

def PreIncrement(name, local={}):
    #Equivalent to ++name
    if name in local:
        local[name]+=1
        return local[name]
    globals()[name]+=1
    return globals()[name]

def PostIncrement(name, local={}):
    #Equivalent to name++
    if name in local:
        local[name]+=1
        return local[name]-1
    globals()[name]+=1
    return globals()[name]-1

Usage:

x = 1
y = PreIncrement('x') #y and x are both 2
a = 1
b = PostIncrement('a') #b is 1 and a is 2

Inside a function you have to add locals() as a second argument if you want to change local variable, otherwise it will try to change global.

x = 1
def test():
    x = 10
    y = PreIncrement('x') #y will be 2, local x will be still 10 and global x will be changed to 2
    z = PreIncrement('x', locals()) #z will be 11, local x will be 11 and global x will be unaltered
test()

Also with these functions you can do:

x = 1
print(PreIncrement('x'))   #print(x+=1) is illegal!

But in my opinion following approach is much clearer:

x = 1
x+=1
print(x)

Decrement operators:

def PreDecrement(name, local={}):
    #Equivalent to --name
    if name in local:
        local[name]-=1
        return local[name]
    globals()[name]-=1
    return globals()[name]

def PostDecrement(name, local={}):
    #Equivalent to name--
    if name in local:
        local[name]-=1
        return local[name]+1
    globals()[name]-=1
    return globals()[name]+1

I used these functions in my module translating javascript to python.

Scroll to bottom of div with Vue.js

For those that haven't found a working solution above, I believe I have a working one. My specific use case was that I wanted to scroll to the bottom of a specific div - in my case a chatbox - whenever a new message was added to the array.

const container = this.$el.querySelector('#messagesCardContent');
        this.$nextTick(() => {
          // DOM updated
          container.scrollTop = container.scrollHeight;
        });

I have to use nextTick as we need to wait for the dom to update from the data change before doing the scroll!

I just put the above code in a watcher for the messages array, like so:

messages: {
      handler() {
        // this scrolls the messages to the bottom on loading data
        const container = this.$el.querySelector('#messagesCard');
        this.$nextTick(() => {
          // DOM updated
          container.scrollTop = container.scrollHeight;
        });
      },
      deep: true,
    }, 

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

from jquery $.ajax to angular $http

You may use this :

Download "angular-post-fix": "^0.1.0"

Then add 'httpPostFix' to your dependencies while declaring the angular module.

Ref : https://github.com/PabloDeGrote/angular-httppostfix

Negative regex for Perl string pattern match

Your regex does not work because [] defines a character class, but what you want is a lookahead:

(?=) - Positive look ahead assertion foo(?=bar) matches foo when followed by bar
(?!) - Negative look ahead assertion foo(?!bar) matches foo when not followed by bar
(?<=) - Positive look behind assertion (?<=foo)bar matches bar when preceded by foo
(?<!) - Negative look behind assertion (?<!foo)bar matches bar when NOT preceded by foo
(?>) - Once-only subpatterns (?>\d+)bar Performance enhancing when bar not present
(?(x)) - Conditional subpatterns
(?(3)foo|fu)bar - Matches foo if 3rd subpattern has matched, fu if not
(?#) - Comment (?# Pattern does x y or z)

So try: (?!bush)

Recommended SQL database design for tags or tagging

I've always kept the tags in a separate table and then had a mapping table. Of course I've never done anything on a really large scale either.

Having a "tags" table and a map table makes it pretty trivial to generate tag clouds & such since you can easily put together SQL to get a list of tags with counts of how often each tag is used.

Setting up an MS-Access DB for multi-user access

Table or record locking is available in Access during data writes. You can control the Default record locking through Tools | Options | Advanced tab:

  1. No Locks
  2. All Records
  3. Edited Record

You can set this on a form's Record Locks or in your DAO/ADO code for specific needs.

Transactions shouldn't be a problem if you use them correctly.

Best practice: Separate your tables from All your other code. Give each user their own copy of the code file and then share the data file on a network server. Work on a 'test' copy of the code (and a link to a test data file) and then update user's individual code files separately. If you need to make data file changes (add tables, columns, etc), you will have to have all users get out of the application to make the changes.

See other answers for Oracle comparison.

AngularJS: how to enable $locationProvider.html5Mode with deeplinking

This problem was due to the use of AngularJS 1.1.5 (which was unstable, and obviously had some bug or different implementation of the routing than it was in 1.0.7)

turning it back to 1.0.7 solved the problem instantly.

have tried the 1.2.0rc1 version, but have not finished testing as I had to rewrite some of the router functionality since they took it out of the core.

anyway, this problem is fixed when using AngularJS vs 1.0.7.

Is there a Python caching library?

You can use my simple solution to the problem. It is really straightforward, nothing fancy:

class MemCache(dict):
    def __init__(self, fn):
        dict.__init__(self)
        self.__fn = fn

    def __getitem__(self, item):
        if item not in self:
            dict.__setitem__(self, item, self.__fn(item))
        return dict.__getitem__(self, item)

mc = MemCache(lambda x: x*x)

for x in xrange(10):
    print mc[x]

for x in xrange(10):
    print mc[x]

It indeed lacks expiration funcionality, but you can easily extend it with specifying a particular rule in MemCache c-tor.

Hope code is enough self-explanatory, but if not, just to mention, that cache is being passed a translation function as one of its c-tor params. It's used in turn to generate cached output regarding the input.

Hope it helps

Compare two Timestamp in java

From : http://download.oracle.com/javase/6/docs/api/java/sql/Timestamp.html#compareTo(java.sql.Timestamp)

public int compareTo(Timestamp ts)

Compares this Timestamp object to the given Timestamp object. Parameters: ts - the Timestamp object to be compared to this Timestamp object Returns: the value 0 if the two Timestamp objects are equal; a value less than 0 if this Timestamp object is before the given argument; and a value greater than 0 if this Timestamp object is after the given argument. Since: 1.4

Trying to get PyCharm to work, keep getting "No Python interpreter selected"

for mac I can tell you that first you have to check your path

by executing this command

which python or which python3

check where python is installed

then you have to configure it in your pycharm.

pycharm-->preferences-->gear button-->add..

enter image description here

click on system interpreter--> then on ...

then you search where your python version is installed

enter image description here

once it is done then you have to configure for your project

click on edit configuration

enter image description here

then choose the python interpreter

enter image description here

Git Push ERROR: Repository not found

you have to generate ssh key and add it in your github account in settings go to your project where you clone inside that run these command.-

1-ssh-keygen -t rsa -b 4096 -C "[email protected]"

after the command you will get some options path and name can be leave empty and you can put password.

2-eval $(ssh-agent -s) .

3-ssh-add ~/.ssh/id_rsa

after this command you have to put same password that you created in 1st command

and after that you can check your default home directory or whatever directory it is showing on the terminal .pub file open and copy the key and past in github settings new ssh

HTML span align center not working?

span.login-text {
    font-size: 22px;
    display:table;
    margin-left: auto;
    margin-right: auto;
}

<span class="login-text">Welcome To .....CMP</span>

For me it worked very well. try this also

CSS getting text in one line rather than two

Add white-space: nowrap;:

.garage-title {
    clear: both;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
}

jsFiddle

What's the difference between commit() and apply() in SharedPreferences

From javadoc:

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a > apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself

How to change the font on the TextView?

First download the .ttf file of the font you need (arial.ttf). Place it in the assets folder. (Inside assets folder create new folder named fonts and place it inside it.) Use the following code to apply the font to your TextView:

Typeface type = Typeface.createFromAsset(getAssets(),"fonts/arial.ttf"); 
textView.setTypeface(type);

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.

How do I register a DLL file on Windows 7 64-bit?

On a x64 system, system32 is for 64 bit and syswow64 is for 32 bit (not the other way around as stated in another answer). WOW (Windows on Windows) is the 32 bit subsystem that runs under the 64 bit subsystem).

It's a mess in naming terms, and serves only to confuse, but that's the way it is.

Again ...

syswow64 is 32 bit, NOT 64 bit.

system32 is 64 bit, NOT 32 bit.

There is a regsrv32 in each of these directories. One is 64 bit, and the other is 32 bit. It is the same deal with odbcad32 and et al. (If you want to see 32-bit ODBC drivers which won't show up with the default odbcad32 in system32 which is 64-bit.)

What's an appropriate HTTP status code to return by a REST API service for a validation failure?

I would say technically it might not be an HTTP failure, since the resource was (presumably) validly specified, the user was authenticated, and there was no operational failure (however even the spec does include some reserved codes like 402 Payment Required which aren't strictly speaking HTTP-related either, though it might be advisable to have that at the protocol level so that any device can recognize the condition).

If that's actually the case, I would add a status field to the response with application errors, like

<status><code>4</code><message>Date range is invalid</message></status>

Is there a combination of "LIKE" and "IN" in SQL?

If you are using MySQL the closest you can get is full-text search:

Full-Text Search, MySQL Documentation

How to sum digits of an integer in java?

Mine is more simple than the others hopefully you can understand this if you are a some what new programmer like myself.

import java.util.Scanner;
import java.lang.Math;

public class DigitsSum {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);
        int digit = 0;
        System.out.print("Please enter a positive integer: ");
        digit = in.nextInt();
        int D1 = 0;
        int D2 = 0;
        int D3 = 0;
        int G2 = 0;
        D1 = digit / 100;
        D2 = digit % 100;
        G2 = D2 / 10;
        D3 = digit % 10;


        System.out.println(D3 + G2 + D1);

    }
}

How do I do logging in C# without using 3rd party libraries?

If you want to stay close to .NET check out Enterprise Library Logging Application Block. Look here. Or for a quickstart tutorial check this. I have used the Validation application Block from the Enterprise Library and it really suits my needs and is very easy to "inherit" (install it and refrence it!) in your project.

Can I remove the URL from my print css, so the web address doesn't print?

This solution will do the trick in Chrome and Opera by setting margin to 0 in a css @page directive. It will not (currently) work for other browsers though...

How to make method call another one in classes?

Because the Method2 is static, all you have to do is call like this:

public class AllMethods
{
    public static void Method2()
    {
        // code here
    }
}

class Caller
{
    public static void Main(string[] args)
    {
        AllMethods.Method2();
    }
}

If they are in different namespaces you will also need to add the namespace of AllMethods to caller.cs in a using statement.

If you wanted to call an instance method (non-static), you'd need an instance of the class to call the method on. For example:

public class MyClass
{
    public void InstanceMethod() 
    { 
        // ...
    }
}

public static void Main(string[] args)
{
    var instance = new MyClass();
    instance.InstanceMethod();
}

Update

As of C# 6, you can now also achieve this with using static directive to call static methods somewhat more gracefully, for example:

// AllMethods.cs
namespace Some.Namespace
{
    public class AllMethods
    {
        public static void Method2()
        {
            // code here
        }
    }
}

// Caller.cs
using static Some.Namespace.AllMethods;

namespace Other.Namespace
{
    class Caller
    {
        public static void Main(string[] args)
        {
            Method2(); // No need to mention AllMethods here
        }
    }
}

Further Reading

JavaScript: Create and destroy class instance through class method

1- There is no way to actually destroy an object in javascript, but using delete, we could remove a reference from an object:

var obj = {};
obj.mypointer = null;
delete obj.mypointer;

2- The important point about the delete keyword is that it does not actually destroy the object BUT if only after deleting that reference to the object, there is no other reference left in the memory pointed to the same object, that object would be marked as collectible. The delete keyword deletes the reference but doesn't GC the actual object. it means if you have several references of the same object, the object will be collected just after you delete all the pointed references.

3- there are also some tricks and workarounds that could help us out, when we want to make sure we do not leave any memory leaks behind. for instance if you have an array consisting several objects, without any other pointed reference to those objects, if you recreate the array all those objects would be killed. For instance if you have var array = [{}, {}] overriding the value of the array like array = [] would remove the references to the two objects inside the array and those two objects would be marked as collectible.

4- for your solution the easiest way is just this:

var storage = {};
storage.instance = new Class();
//since 'storage.instance' is your only reference to the object, whenever you wanted to destroy do this:
storage.instance = null;
// OR
delete storage.instance;

As mentioned above, either setting storage.instance = null or delete storage.instance would suffice to remove the reference to the object and allow it to be cleaned up by the GC. The difference is that if you set it to null then the storage object still has a property called instance (with the value null). If you delete storage.instance then the storage object no longer has a property named instance.

and WHAT ABOUT destroy method ??

the paradoxical point here is if you use instance.destroy in the destroy function you have no access to the actual instance pointer, and it won't let you delete it.

The only way is to pass the reference to the destroy function and then delete it:

// Class constructor
var Class = function () {
     this.destroy = function (baseObject, refName) {
         delete baseObject[refName];
     };
};

// instanciate
var storage = {};
storage.instance = new Class();
storage.instance.destroy(object, "instance");
console.log(storage.instance); // now it is undefined

BUT if I were you I would simply stick to the first solution and delete the object like this:

storage.instance = null;
// OR
delete storage.instance;

WOW it was too much :)

docker mounting volumes on host

Basically VOLUME and -v option are almost equal. These mean 'mount specific directory on your container'. For example, VOLUME /data and -v /data is exactly same meaning. If you run the image that have VOLUME /data or with -v /data option, /data directory is mounted your container. This directory doesn't belong to your container.

Imagine that You add some files to /data on the container, then commit the container into new image. There isn't any files on data directory because mounted /data directory is belong to original container.

$ docker run -it -v /data --name volume ubuntu:14.04 bash
root@2b5e0f2d37cd:/# cd /data
root@2b5e0f2d37cd:/data# touch 1 2 3 4 5 6 7 8 9
root@2b5e0f2d37cd:/data# cd /tmp
root@2b5e0f2d37cd:/tmp# touch 1 2 3 4 5 6 7 8 9
root@2b5e0f2d37cd:/tmp# exit
exit

$ docker commit volume nacyot/volume  
835cfe3d8d159622507ba3256bb1c0b0d6e7c1419ae32751ad0f925c40378945
nacyot $ docker run -it nacyot/volume
root@dbe335c7e64d:/# cd /data
root@dbe335c7e64d:/data# ls
root@dbe335c7e64d:/data# cd /tmp
root@dbe335c7e64d:/tmp# ls
1  2  3  4  5  6  7  8  9
root@dbe335c7e64d:/tmp# 
root@dbe335c7e64d:/tmp# 

This mounted directory like /data is used to store data that is not belong to your application. And you can predefine the data directory that is not belong to the container by using VOLUME.

A difference between Volume and -v option is that you can use -v option dynamically on starting container. It mean you can mount some directory dynamically. And another difference is that you can mount your host directory on your container by using -v

Multiple separate IF conditions in SQL Server

Maybe this is a bit redundant, but no one appeared to have mentioned this as a solution.

As a beginner in SQL I find that when using a BEGIN and END SSMS usually adds a squiggly line with incorrect syntax near 'END' to END, simply because there's no content in between yet. If you're just setting up BEGIN and END to get started and add the actual query later, then simply add a bogus PRINT statement so SSMS stops bothering you.

For example:

IF (1=1)
BEGIN
  PRINT 'BOGUS'
END

The following will indeed set you on the wrong track, thinking you made a syntax error which in this case just means you still need to add content in between BEGIN and END:

IF (1=1)
BEGIN
END

Save the console.log in Chrome to a file

On Linux (at least) you can set CHROME_LOG_FILE in the environment to have chrome write a log of the Console activity to the named file each time it runs. The log is overwritten every time chrome starts. This way, if you have an automated session that runs chrome, you don't have a to change the way chrome is started, and the log is there after the session ends.

export CHROME_LOG_FILE=chrome.log

Converting unix time into date-time via excel

If you have ########, it can help you:

=((A1/1000+1*3600)/86400+25569)

+1*3600 is GTM+1

Reverse a comparator in Java 8

Why not to extend the existing comperator and overwrite super and nor the result. The implementation the Comperator Interface is not nessesery but it makes it more clear what happens.

In result you get a easy reusable Class File, testable unit step and clear javadoc.

public class NorCoperator extends ExistingComperator implements Comparator<MyClass> {
    @Override
    public int compare(MyClass a, MyClass b) throws Exception {
        return super.compare(a, b)*-1;
    }
}

SQL - How to find the highest number in a column?

If you've just inserted a record into the Customers table and you need the value of the recently populated ID field, you can use the SCOPE_IDENTITY function. This is only useful when the INSERT has occurred within the same scope as the call to SCOPE_IDENTITY.

INSERT INTO Customers(ID, FirstName, LastName)
Values
(23, 'Bob', 'Smith')

SET @mostRecentId = SCOPE_IDENTITY()

This may or may not be useful for you, but it's a good technique to be aware of. It will also work with auto-generated columns.

Passing capturing lambda as function pointer

Lambda expressions, even captured ones, can be handled as a function pointer (pointer to member function).

It is tricky because an lambda expression is not a simple function. It is actually an object with an operator().

When you are creative, you can use this! Think of an "function" class in style of std::function. If you save the object you also can use the function pointer.

To use the function pointer, you can use the following:

int first = 5;
auto lambda = [=](int x, int z) {
    return x + z + first;
};
int(decltype(lambda)::*ptr)(int, int)const = &decltype(lambda)::operator();
std::cout << "test = " << (lambda.*ptr)(2, 3) << std::endl;

To build a class that can start working like a "std::function", first you need a class/struct than can store object and function pointer. Also you need an operator() to execute it:

// OT => Object Type
// RT => Return Type
// A ... => Arguments
template<typename OT, typename RT, typename ... A>
struct lambda_expression {
    OT _object;
    RT(OT::*_function)(A...)const;

    lambda_expression(const OT & object)
        : _object(object), _function(&decltype(_object)::operator()) {}

    RT operator() (A ... args) const {
        return (_object.*_function)(args...);
    }
};

With this you can now run captured, non-captured lambdas, just like you are using the original:

auto capture_lambda() {
    int first = 5;
    auto lambda = [=](int x, int z) {
        return x + z + first;
    };
    return lambda_expression<decltype(lambda), int, int, int>(lambda);
}

auto noncapture_lambda() {
    auto lambda = [](int x, int z) {
        return x + z;
    };
    return lambda_expression<decltype(lambda), int, int, int>(lambda);
}

void refcapture_lambda() {
    int test;
    auto lambda = [&](int x, int z) {
        test = x + z;
    };
    lambda_expression<decltype(lambda), void, int, int>f(lambda);
    f(2, 3);

    std::cout << "test value = " << test << std::endl;
}

int main(int argc, char **argv) {
    auto f_capture = capture_lambda();
    auto f_noncapture = noncapture_lambda();

    std::cout << "main test = " << f_capture(2, 3) << std::endl;
    std::cout << "main test = " << f_noncapture(2, 3) << std::endl;

    refcapture_lambda();

    system("PAUSE");
    return 0;
}

This code works with VS2015

Update 04.07.17:

template <typename CT, typename ... A> struct function
: public function<decltype(&CT::operator())(A...)> {};

template <typename C> struct function<C> {
private:
    C mObject;

public:
    function(const C & obj)
        : mObject(obj) {}

    template<typename... Args> typename 
    std::result_of<C(Args...)>::type operator()(Args... a) {
        return this->mObject.operator()(a...);
    }

    template<typename... Args> typename 
    std::result_of<const C(Args...)>::type operator()(Args... a) const {
        return this->mObject.operator()(a...);
    }
};

namespace make {
    template<typename C> auto function(const C & obj) {
        return ::function<C>(obj);
    }
}

int main(int argc, char ** argv) {
   auto func = make::function([](int y, int x) { return x*y; });
   std::cout << func(2, 4) << std::endl;
   system("PAUSE");
   return 0;
}

How to disable scrolling the document body?

with css

body,html{
  overflow:hidden
}

How to use std::sort to sort an array in C++

you can use,

 std::sort(v.begin(),v.end());

Entity Framework - Linq query with order by and group by

You can try to cast the result of GroupBy and Take into an Enumerable first then process the rest (building on the solution provided by NinjaNye

var groupByReference = (from m in context.Measurements
                              .GroupBy(m => m.Reference)
                              .Take(numOfEntries).AsEnumerable()
                               .Select(g => new {Creation = g.FirstOrDefault().CreationTime, 
                                             Avg = g.Average(m => m.CreationTime.Ticks),
                                                Items = g })
                              .OrderBy(x => x.Creation)
                              .ThenBy(x => x.Avg)
                              .ToList() select m);

Your sql query would look similar (depending on your input) this

SELECT TOP (3) [t1].[Reference] AS [Key]
FROM (
    SELECT [t0].[Reference]
    FROM [Measurements] AS [t0]
    GROUP BY [t0].[Reference]
    ) AS [t1]
GO

-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref1'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]
GO

-- Region Parameters
DECLARE @x1 NVarChar(1000) = 'Ref2'
-- EndRegion
SELECT [t0].[CreationTime], [t0].[Id], [t0].[Reference]
FROM [Measurements] AS [t0]
WHERE @x1 = [t0].[Reference]

What do we mean by Byte array?

A byte is 8 bits (binary data).

A byte array is an array of bytes (tautology FTW!).

You could use a byte array to store a collection of binary data, for example, the contents of a file. The downside to this is that the entire file contents must be loaded into memory.

For large amounts of binary data, it would be better to use a streaming data type if your language supports it.

CSS3 transition events

All modern browsers now support the unprefixed event:

element.addEventListener('transitionend', callback, false);

Works in the latest versions of Chrome, Firefox and Safari. Even IE10+.

Unable to execute dex: Multiple dex files define

ULTRA simple solution and finest:

Remove everything in Right Click Main Project's Folder -> Properties -> Java Build Path except Android X.Y (where X.Y is the version in android). Clean, and Build. Done!

Make sure before of that to have a single android-support-v4.jar.

Convert NSNumber to int in Objective-C

A tested one-liner:

int number = ((NSNumber*)[dict objectForKey:@"integer"]).intValue;