Programs & Examples On #Nhibernate

NHibernate is a mature, open source object-relational mapper (ORM) for the .NET framework.

What are the First and Second Level caches in (N)Hibernate?

Here some basic explanation of hibernate cache...

First level cache is associated with “session” object. The scope of cache objects is of session. Once session is closed, cached objects are gone forever. First level cache is enabled by default and you can not disable it. When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session. If we query same object again with same session object, it will be loaded from cache and no sql query will be executed. The loaded entity can be removed from session using evict() method. The next loading of this entity will again make a database call if it has been removed using evict() method. The whole session cache can be removed using clear() method. It will remove all the entities stored in cache.

Second level cache is apart from first level cache which is available to be used globally in session factory scope. second level cache is created in session factory scope and is available to be used in all sessions which are created using that particular session factory. It also means that once session factory is closed, all cache associated with it die and cache manager also closed down. Whenever hibernate session try to load an entity, the very first place it look for cached copy of entity in first level cache (associated with particular hibernate session). If cached copy of entity is present in first level cache, it is returned as result of load method. If there is no cached entity in first level cache, then second level cache is looked up for cached entity. If second level cache has cached entity, it is returned as result of load method. But, before returning the entity, it is stored in first level cache also so that next invocation to load method for entity will return the entity from first level cache itself, and there will not be need to go to second level cache again. If entity is not found in first level cache and second level cache also, then database query is executed and entity is stored in both cache levels, before returning as response of load() method.

NHibernate.MappingException: No persister for: XYZ

I got this off of here:

In my case the mapping class was not public. In other words, instead of:

public class UserMap : ClassMap<user>  // note the public!

I just had:

class UserMap : ClassMap<user>

Best way to convert IList or IEnumerable to Array

I feel like reinventing the wheel...

public static T[] ConvertToArray<T>(this IEnumerable<T> enumerable)
{
    if (enumerable == null)
        throw new ArgumentNullException("enumerable");

    return enumerable as T[] ?? enumerable.ToArray();
}

Declaring variables in Excel Cells

I also just found out how to do this with the Excel Name Manager (Formulas > Defined Names Section > Name Manager).

You can define a variable that doesn't have to "live" within a cell and then you can use it in formulas.

Excel Name Manager

How to disable postback on an asp Button (System.Web.UI.WebControls.Button)

ASP.NET always generate asp:Button as an input type=submit.
If you want a button which doesn't do a post, but need some control for the element on the server side, create a simple HTML input with attributes type=button and runat=server.

If you disable click actions doing OnClientClick=return false, it won't do anything on click, unless you create a function like:

function btnClick() {
    // do stuff
    return false;
}

How do I force Robocopy to overwrite files?

From the documentation:

/is Includes the same files. /it Includes "tweaked" files.

"Same files" means files that are identical (name, size, times, attributes). "Tweaked files" means files that have the same name, size, and times, but different attributes.

robocopy src dst sample.txt /is      # copy if attributes are equal
robocopy src dst sample.txt /it      # copy if attributes differ
robocopy src dst sample.txt /is /it  # copy irrespective of attributes

This answer on Super User has a good explanation of what kind of files the selection parameters match.

With that said, I could reproduce the behavior you describe, but from my understanding of the documentation and the output robocopy generated in my tests I would consider this a bug.

PS C:\temp> New-Item src -Type Directory >$null
PS C:\temp> New-Item dst -Type Directory >$null
PS C:\temp> New-Item src\sample.txt -Type File -Value "test001" >$null
PS C:\temp> New-Item dst\sample.txt -Type File -Value "test002" >$null
PS C:\temp> Set-ItemProperty src\sample.txt -Name LastWriteTime -Value "2016/1/1 15:00:00"
PS C:\temp> Set-ItemProperty dst\sample.txt -Name LastWriteTime -Value "2016/1/1 15:00:00"
PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir
...
  Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30

------------------------------------------------------------------------------

                           1    C:\temp\src\
            Modified                   7        sample.txt

------------------------------------------------------------------------------

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :         1         0         0         0         0         0
   Files :         1         1         0         0         0         0
   Bytes :         7         7         0         0         0         0
...
PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir
...
  Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30

------------------------------------------------------------------------------

                           1    C:\temp\src\
            Same                       7        sample.txt

------------------------------------------------------------------------------

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :         1         0         0         0         0         0
   Files :         1         1         0         0         0         0
   Bytes :         7         7         0         0         0         0
...
PS C:\temp> Get-Content .\src\sample.txt
test001
PS C:\temp> Get-Content .\dst\sample.txt
test002

The file is listed as copied, and since it becomes a same file after the first robocopy run at least the times are synced. However, even though seven bytes have been copied according to the output no data was actually written to the destination file in both cases despite the data flag being set (via /copyall). The behavior also doesn't change if the data flag is set explicitly (/copy:d).

I had to modify the last write time to get robocopy to actually synchronize the data.

PS C:\temp> Set-ItemProperty src\sample.txt -Name LastWriteTime -Value (Get-Date)
PS C:\temp> robocopy src dst sample.txt /is /it /copyall /mir
...
  Options : /S /E /COPYALL /PURGE /MIR /IS /IT /R:1000000 /W:30

------------------------------------------------------------------------------

                           1    C:\temp\src\
100%        Newer                      7        sample.txt

------------------------------------------------------------------------------

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :         1         0         0         0         0         0
   Files :         1         1         0         0         0         0
   Bytes :         7         7         0         0         0         0
...
PS C:\temp> Get-Content .\dst\sample.txt
test001

An admittedly ugly workaround would be to change the last write time of same/tweaked files to force robocopy to copy the data:

& robocopy src dst /is /it /l /ndl /njh /njs /ns /nc |
  Where-Object { $_.Trim() } |
  ForEach-Object {
    $f = Get-Item $_
    $f.LastWriteTime = $f.LastWriteTime.AddSeconds(1)
  }
& robocopy src dst /copyall /mir

Switching to xcopy is probably your best option:

& xcopy src dst /k/r/e/i/s/c/h/f/o/x/y

What are type hints in Python 3.5?

I would suggest reading PEP 483 and PEP 484 and watching this presentation by Guido on type hinting.

In a nutshell: Type hinting is literally what the words mean. You hint the type of the object(s) you're using.

Due to the dynamic nature of Python, inferring or checking the type of an object being used is especially hard. This fact makes it hard for developers to understand what exactly is going on in code they haven't written and, most importantly, for type checking tools found in many IDEs (PyCharm and PyDev come to mind) that are limited due to the fact that they don't have any indicator of what type the objects are. As a result they resort to trying to infer the type with (as mentioned in the presentation) around 50% success rate.


To take two important slides from the type hinting presentation:

Why type hints?

  1. Helps type checkers: By hinting at what type you want the object to be the type checker can easily detect if, for instance, you're passing an object with a type that isn't expected.
  2. Helps with documentation: A third person viewing your code will know what is expected where, ergo, how to use it without getting them TypeErrors.
  3. Helps IDEs develop more accurate and robust tools: Development Environments will be better suited at suggesting appropriate methods when know what type your object is. You have probably experienced this with some IDE at some point, hitting the . and having methods/attributes pop up which aren't defined for an object.

Why use static type checkers?

  • Find bugs sooner: This is self-evident, I believe.
  • The larger your project the more you need it: Again, makes sense. Static languages offer a robustness and control that dynamic languages lack. The bigger and more complex your application becomes the more control and predictability (from a behavioral aspect) you require.
  • Large teams are already running static analysis: I'm guessing this verifies the first two points.

As a closing note for this small introduction: This is an optional feature and, from what I understand, it has been introduced in order to reap some of the benefits of static typing.

You generally do not need to worry about it and definitely don't need to use it (especially in cases where you use Python as an auxiliary scripting language). It should be helpful when developing large projects as it offers much needed robustness, control and additional debugging capabilities.


Type hinting with mypy:

In order to make this answer more complete, I think a little demonstration would be suitable. I'll be using mypy, the library which inspired Type Hints as they are presented in the PEP. This is mainly written for anybody bumping into this question and wondering where to begin.

Before I do that let me reiterate the following: PEP 484 doesn't enforce anything; it is simply setting a direction for function annotations and proposing guidelines for how type checking can/should be performed. You can annotate your functions and hint as many things as you want; your scripts will still run regardless of the presence of annotations because Python itself doesn't use them.

Anyways, as noted in the PEP, hinting types should generally take three forms:

  • Function annotations (PEP 3107).
  • Stub files for built-in/user modules.
  • Special # type: type comments that complement the first two forms. (See: What are variable annotations? for a Python 3.6 update for # type: type comments)

Additionally, you'll want to use type hints in conjunction with the new typing module introduced in Py3.5. In it, many (additional) ABCs (abstract base classes) are defined along with helper functions and decorators for use in static checking. Most ABCs in collections.abc are included, but in a generic form in order to allow subscription (by defining a __getitem__() method).

For anyone interested in a more in-depth explanation of these, the mypy documentation is written very nicely and has a lot of code samples demonstrating/describing the functionality of their checker; it is definitely worth a read.

Function annotations and special comments:

First, it's interesting to observe some of the behavior we can get when using special comments. Special # type: type comments can be added during variable assignments to indicate the type of an object if one cannot be directly inferred. Simple assignments are generally easily inferred but others, like lists (with regard to their contents), cannot.

Note: If we want to use any derivative of containers and need to specify the contents for that container we must use the generic types from the typing module. These support indexing.

# Generic List, supports indexing.
from typing import List

# In this case, the type is easily inferred as type: int.
i = 0

# Even though the type can be inferred as of type list
# there is no way to know the contents of this list.
# By using type: List[str] we indicate we want to use a list of strings.
a = []  # type: List[str]

# Appending an int to our list
# is statically not correct.
a.append(i)

# Appending a string is fine.
a.append("i")

print(a)  # [0, 'i']

If we add these commands to a file and execute them with our interpreter, everything works just fine and print(a) just prints the contents of list a. The # type comments have been discarded, treated as plain comments which have no additional semantic meaning.

By running this with mypy, on the other hand, we get the following response:

(Python3)jimmi@jim: mypy typeHintsCode.py
typesInline.py:14: error: Argument 1 to "append" of "list" has incompatible type "int"; expected "str"

Indicating that a list of str objects cannot contain an int, which, statically speaking, is sound. This can be fixed by either abiding to the type of a and only appending str objects or by changing the type of the contents of a to indicate that any value is acceptable (Intuitively performed with List[Any] after Any has been imported from typing).

Function annotations are added in the form param_name : type after each parameter in your function signature and a return type is specified using the -> type notation before the ending function colon; all annotations are stored in the __annotations__ attribute for that function in a handy dictionary form. Using a trivial example (which doesn't require extra types from the typing module):

def annotated(x: int, y: str) -> bool:
    return x < y

The annotated.__annotations__ attribute now has the following values:

{'y': <class 'str'>, 'return': <class 'bool'>, 'x': <class 'int'>}

If we're a complete newbie, or we are familiar with Python 2.7 concepts and are consequently unaware of the TypeError lurking in the comparison of annotated, we can perform another static check, catch the error and save us some trouble:

(Python3)jimmi@jim: mypy typeHintsCode.py
typeFunction.py: note: In function "annotated":
typeFunction.py:2: error: Unsupported operand types for > ("str" and "int")

Among other things, calling the function with invalid arguments will also get caught:

annotated(20, 20)

# mypy complains:
typeHintsCode.py:4: error: Argument 2 to "annotated" has incompatible type "int"; expected "str"

These can be extended to basically any use case and the errors caught extend further than basic calls and operations. The types you can check for are really flexible and I have merely given a small sneak peak of its potential. A look in the typing module, the PEPs or the mypy documentation will give you a more comprehensive idea of the capabilities offered.

Stub files:

Stub files can be used in two different non mutually exclusive cases:

  • You need to type check a module for which you do not want to directly alter the function signatures
  • You want to write modules and have type-checking but additionally want to separate annotations from content.

What stub files (with an extension of .pyi) are is an annotated interface of the module you are making/want to use. They contain the signatures of the functions you want to type-check with the body of the functions discarded. To get a feel of this, given a set of three random functions in a module named randfunc.py:

def message(s):
    print(s)

def alterContents(myIterable):
    return [i for i in myIterable if i % 2 == 0]

def combine(messageFunc, itFunc):
    messageFunc("Printing the Iterable")
    a = alterContents(range(1, 20))
    return set(a)

We can create a stub file randfunc.pyi, in which we can place some restrictions if we wish to do so. The downside is that somebody viewing the source without the stub won't really get that annotation assistance when trying to understand what is supposed to be passed where.

Anyway, the structure of a stub file is pretty simplistic: Add all function definitions with empty bodies (pass filled) and supply the annotations based on your requirements. Here, let's assume we only want to work with int types for our Containers.

# Stub for randfucn.py
from typing import Iterable, List, Set, Callable

def message(s: str) -> None: pass

def alterContents(myIterable: Iterable[int])-> List[int]: pass

def combine(
    messageFunc: Callable[[str], Any],
    itFunc: Callable[[Iterable[int]], List[int]]
)-> Set[int]: pass

The combine function gives an indication of why you might want to use annotations in a different file, they some times clutter up the code and reduce readability (big no-no for Python). You could of course use type aliases but that sometime confuses more than it helps (so use them wisely).


This should get you familiarized with the basic concepts of type hints in Python. Even though the type checker used has been mypy you should gradually start to see more of them pop-up, some internally in IDEs (PyCharm,) and others as standard Python modules.

I'll try and add additional checkers/related packages in the following list when and if I find them (or if suggested).

Checkers I know of:

  • Mypy: as described here.
  • PyType: By Google, uses different notation from what I gather, probably worth a look.

Related Packages/Projects:

  • typeshed: Official Python repository housing an assortment of stub files for the standard library.

The typeshed project is actually one of the best places you can look to see how type hinting might be used in a project of your own. Let's take as an example the __init__ dunders of the Counter class in the corresponding .pyi file:

class Counter(Dict[_T, int], Generic[_T]):
        @overload
        def __init__(self) -> None: ...
        @overload
        def __init__(self, Mapping: Mapping[_T, int]) -> None: ...
        @overload
        def __init__(self, iterable: Iterable[_T]) -> None: ...

Where _T = TypeVar('_T') is used to define generic classes. For the Counter class we can see that it can either take no arguments in its initializer, get a single Mapping from any type to an int or take an Iterable of any type.


Notice: One thing I forgot to mention was that the typing module has been introduced on a provisional basis. From PEP 411:

A provisional package may have its API modified prior to "graduating" into a "stable" state. On one hand, this state provides the package with the benefits of being formally part of the Python distribution. On the other hand, the core development team explicitly states that no promises are made with regards to the the stability of the package's API, which may change for the next release. While it is considered an unlikely outcome, such packages may even be removed from the standard library without a deprecation period if the concerns regarding their API or maintenance prove well-founded.

So take things here with a pinch of salt; I'm doubtful it will be removed or altered in significant ways, but one can never know.


** Another topic altogether, but valid in the scope of type-hints: PEP 526: Syntax for Variable Annotations is an effort to replace # type comments by introducing new syntax which allows users to annotate the type of variables in simple varname: type statements.

See What are variable annotations?, as previously mentioned, for a small introduction to these.

jQuery.active function

This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache (where all of jQuery.data() goes).

I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart() and $.ajaxStop() (which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.


When jQuery starts an AJAX request, this happens:

if ( s.global && ! jQuery.active++ ) {
  jQuery.event.trigger( "ajaxStart" );
}

This is what causes the $.ajaxStart() event to fire, the number of connections just went from 0 to 1 (jQuery.active++ isn't 0 after this one, and !0 == true), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend abort via return false or an ajax call complete function runs):

if ( s.global && ! --jQuery.active ) {
  jQuery.event.trigger( "ajaxStop" );
}

This is what causes the $.ajaxStop() event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.

Converting HTML string into DOM elements?

Check out John Resig's pure JavaScript HTML parser.

EDIT: if you want the browser to parse the HTML for you, innerHTML is exactly what you want. From this SO question:

var tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;

How to add DOM element script to head section?

var script = $('<script type="text/javascript">// function </script>')
document.getElementsByTagName("head")[0].appendChild(script[0])

But in that case script will not be executed and functions will be not accessible in global namespase. To use code in <script> you need do as in you question

$('head').append(script);

Developing C# on Linux

Now Microsoft is migrating to open-source - see CoreFX (GitHub).

HTML 5 Favicon - Support?

No, not all browsers support the sizes attribute:

Note that some platforms define specific sizes:

How to copy only a single worksheet to another workbook using vba

Sub ActiveSheet_toDESKTOP_As_Workbook()

Dim Oldname As String
Dim MyRange As Range
Dim MyWS As String

MyWS = ActiveCell.Parent.Name

    Application.DisplayAlerts = False 'hide confirmation from user
    Application.ScreenUpdating = False
    Oldname = ActiveSheet.Name
    'Sheets.Add(Before:=Sheets(1)).Name = "FirstSheet"
    
    'Get path for desktop of user PC
    Path = Environ("USERPROFILE") & "\Desktop"
    

    ActiveSheet.Cells.Copy
    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "TransferSheet"
    ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    ActiveSheet.Cells.Copy
    
    'Create new workbook and past copied data in new workbook & save to desktop
    Workbooks.Add (xlWBATWorksheet)
    ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    ActiveSheet.Cells(1, 1).Select
    ActiveWorkbook.ActiveSheet.Name = Oldname    '"report"
    ActiveWorkbook.SaveAs Filename:=Path & "\" & Oldname & " WS " & Format(CStr(Now()), "dd-mmm (hh.mm.ss AM/PM)") & ".xlsx"
    ActiveWorkbook.Close SaveChanges:=True

    
    Sheets("TransferSheet").Delete
    
    
   Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    Worksheets(MyWS).Activate
    'MsgBox "Exported to Desktop"

End Sub

When should I use mmap for file access?

One area where I found mmap() to not be an advantage was when reading small files (under 16K). The overhead of page faulting to read the whole file was very high compared with just doing a single read() system call. This is because the kernel can sometimes satisify a read entirely in your time slice, meaning your code doesn't switch away. With a page fault, it seemed more likely that another program would be scheduled, making the file operation have a higher latency.

Singleton in Android

As @Lazy stated in this answer, you can create a singleton from a template in Android Studio. It is worth noting that there is no need to check if the instance is null because the static ourInstance variable is initialized first. As a result, the singleton class implementation created by Android Studio is as simple as following code:

public class MySingleton {
    private static MySingleton ourInstance = new MySingleton();

    public static MySingleton getInstance() {
        return ourInstance;
    }

    private MySingleton() {
    }
}

MySQL/SQL: Group by date only on a Datetime column

Cast the datetime to a date, then GROUP BY using this syntax:

SELECT SUM(foo), DATE(mydate) FROM a_table GROUP BY DATE(a_table.mydate);

Or you can GROUP BY the alias as @orlandu63 suggested:

SELECT SUM(foo), DATE(mydate) DateOnly FROM a_table GROUP BY DateOnly;

Though I don't think it'll make any difference to performance, it is a little clearer.

Closing WebSocket correctly (HTML5, Javascript)

By using close method of web socket, where you can write any function according to requirement.

var connection = new WebSocket('ws://127.0.0.1:1337');
    connection.onclose = () => {
            console.log('Web Socket Connection Closed');
        };

What function is to replace a substring from a string in C?

/*?????? ??????? ? ??????*/
char* replace_char(char* str, char in, char out) {
    char * p = str;

    while(p != '\0') {
        if(*p == in)
            *p == out;
        ++p;
    }

    return str;
}

How to get the GL library/headers?

In Visual Studio :

//OpenGL
#pragma comment(lib, "opengl32")
#pragma comment(lib, "glu32")
#include <gl/gl.h>
#include <gl/glu.h>

Headers are in the SDK : C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\gl

How to create a number picker dialog?

Consider using a Spinner instead of a Number Picker in a Dialog. It's not exactly what was asked for, but it's much easier to implement, more contextual UI design, and should fulfill most use cases. The equivalent code for a Spinner is:

Spinner picker = new Spinner(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, yourStringList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
picker.setAdapter(adapter);

UILabel is not auto-shrinking text to fit label size

also my solution is the boolean label.adjustsFontSizeToFitWidth = YES; BUT. You must in the interface Builder the Word Wrapping switch to "CLIP". Then autoshrink the Labels. This is very important.

"error: assignment to expression with array type error" when I assign a struct field (C)

You are facing issue in

 s1.name="Paolo";

because, in the LHS, you're using an array type, which is not assignable.

To elaborate, from C11, chapter §6.5.16

assignment operator shall have a modifiable lvalue as its left operand.

and, regarding the modifiable lvalue, from chapter §6.3.2.1

A modifiable lvalue is an lvalue that does not have array type, [...]

You need to use strcpy() to copy into the array.

That said, data s1 = {"Paolo", "Rossi", 19}; works fine, because this is not a direct assignment involving assignment operator. There we're using a brace-enclosed initializer list to provide the initial values of the object. That follows the law of initialization, as mentioned in chapter §6.7.9

Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.[....]

An implementation of the fast Fourier transform (FFT) in C#

http://www.exocortex.org/dsp/ is an open-source C# mathematics library with FFT algorithms.

JSON and XML comparison

I found this article at digital bazaar really interesting. Quoting their quotations from Norm:

About JSON pros:

If all you want to pass around are atomic values or lists or hashes of atomic values, JSON has many of the advantages of XML: it’s straightforwardly usable over the Internet, supports a wide variety of applications, it’s easy to write programs to process JSON, it has few optional features, it’s human-legible and reasonably clear, its design is formal and concise, JSON documents are easy to create, and it uses Unicode. ...

About XML pros:

XML deals remarkably well with the full richness of unstructured data. I’m not worried about the future of XML at all even if its death is gleefully celebrated by a cadre of web API designers.

And I can’t resist tucking an "I told you so!" token away in my desk. I look forward to seeing what the JSON folks do when they are asked to develop richer APIs. When they want to exchange less well strucured data, will they shoehorn it into JSON? I see occasional mentions of a schema language for JSON, will other languages follow? ...

I personally agree with Norm. I think that most attacks to XML come from Web Developers for typical applications, and not really from integration developers. But that's my opinion! ;)

UITableView, Separator color where to set?

Swift 3, xcode version 8.3.2, storyboard->choose your table View->inspector->Separator.

Swift 3, xcode version 8.3.2

WCF on IIS8; *.svc handler mapping doesn't work

Order of installation matters a lot when configuring IIS 8 on Windows 8 or Windows Server 2012.

I faced lot of issues configuring IIS 8 but finally these links helped me

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

In Linux, folders are case sensitive. I was getting this error because folder name TestAPI and was putting TestApi.

how do I set height of container DIV to 100% of window height?

I've been thinking over this and experimenting with height of the elements: html, body and div. Finally I came up with the code:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Height question</title>_x000D_
<style>_x000D_
 html {height: 50%; border: solid red 3px; }_x000D_
 body {height: 70vh; border: solid green 3px; padding: 12pt; }_x000D_
 div {height: 90vh; border: solid blue 3px; padding: 24pt; }_x000D_
 _x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
 <div id="container">_x000D_
  <p>&lt;html&gt; is red</p>_x000D_
  <p>&lt;body&gt; is green</p>_x000D_
  <p>&lt;div&gt; is blue</p>_x000D_
 </div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

With my browser (Firefox 65@mint 64), all three elements are of 1) different height, 2) every one is longer, than the previous (html is 50%, body is 70vh, and div 90vh). I also checked the styles without the height with respect to the html and body tags. Worked fine, too.

About CSS units: w3schools: CSS units

A note about the viewport: " Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm."

Convert JSON format to CSV format for MS Excel

You can use that gist, pretty easy to use, stores your settings in local storage: https://gist.github.com/4533361

Maven in Eclipse: step by step installation

You have to follow the following steps in the Eclipse IDE

  1. Go to Help - > Install New Software
  2. Click add button at top right corner
  3. In the popup coming, type in name as "Maven" and location as "http://download.eclipse.org/technology/m2e/releases"
  4. Click on OK.

Maven integration for eclipse will be dowloaded and installed. Restart the workspace.

In the .m2 folder(usually under C:\user\ directory) add settings.xml. Give proper proxy and profiles. Now create a new Maven project in eclipse.

DataGridView checkbox column - value and functionality

To test if the column is checked or not:

for (int i = 0; i < dgvName.Rows.Count; i++)
{
    if ((bool)dgvName.Rows[i].Cells[8].Value)
    {
    // Column is checked
    }
}

How to vertically center <div> inside the parent element with CSS?

have you try this one?

.parentdiv {
 margin: auto;
 position: absolute;
 top: 0; left: 0; bottom: 0; right: 0;
 height: 300px; // at least you have to specify height
}

hope this helps

Where does mysql store data?

In version 5.6 at least, the Management tab in MySQL Workbench shows that it's in a hidden folder called ProgramData in the C:\ drive. My default data directory is

C:\ProgramData\MySQL\MySQL Server 5.6\data

. Each database has a folder and each table has a file here.

iOS8 Beta Ad-Hoc App Download (itms-services)

If you have already installed app on your device, try to change bundle identifer on the web .plist (not app plist) with something else like "com.vistair.docunet-test2", after that refresh webpage and try to reinstall... It works for me

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

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

McAfee was blocking it for me. I had to allow the program in the access protection rules

  1. Open VirusScan
  2. Right click on Access Protection and choose Properties
  3. Click on "Anti-virus Standard Protection"
  4. Select rule "Prevent mass mailing worms from sending mail" and click edit
  5. Add the application to the Processes to exclude list and click OK

See http://www.symantec.com/connect/articles/we-are-unable-send-your-email-caused-mcafee

I need to get all the cookies from the browser

  1. You can't see cookies for other sites.
  2. You can't see HttpOnly cookies.
  3. All the cookies you can see are in the document.cookie property, which contains a semicolon separated list of name=value pairs.

Get first date of current month in java

In Java 8 you can use:

LocalDate date = LocalDate.now(); //2020-01-12
date.withDayOfMonth(1); //2020-01-01

(change) vs (ngModelChange) in angular

1 - (change) is bound to the HTML onchange event. The documentation about HTML onchange says the following :

Execute a JavaScript when a user changes the selected option of a <select> element

Source : https://www.w3schools.com/jsref/event_onchange.asp

2 - As stated before, (ngModelChange) is bound to the model variable binded to your input.

So, my interpretation is :

  • (change) triggers when the user changes the input
  • (ngModelChange) triggers when the model changes, whether it's consecutive to a user action or not

Trigger validation of all fields in Angular Form submit

I done something following to make it work.

<form name="form" name="plantRegistrationForm">
  <div ng-class="{ 'has-error': (form.$submitted || form.headerName.$touched) && form.headerName.$invalid }">
    <div class="col-md-3">
      <div class="label-color">HEADER NAME 
        <span class="red"><strong>*</strong></span></div>
    </div>
    <div class="col-md-9">
      <input type="text" name="headerName" id="headerName" 
             ng-model="header.headerName" 
             maxlength="100" 
             class="form-control" required>
      <div ng-show="form.$submitted || form.headerName.$touched">
        <span ng-show="form.headerName.$invalid" 
              class="label-color validation-message">Header Name is required</span>
      </div>
    </div>
  </div>

  <button ng-click="addHeader(form, header)" 
          type="button" 
          class="btn btn-default pull-right">Add Header
  </button>

</form>

In your controller you can do;

addHeader(form, header){
        let self = this;
        form.$submitted = true;
        ... 
    }

You need some css as well;

.label-color {
            color: $gray-color;
        }
.has-error {
       .label-color {
            color: rgb(221, 25, 29);
        }
        .select2-choice.ui-select-match.select2-default {
            border-color: #e84e40;
        }
    }
.validation-message {
       font-size: 0.875em;
    }
    .max-width {
        width: 100%;
        min-width: 100%;
    }

Convert python long/int to fixed size byte array

Little-endian, reverse the result or the range if you want Big-endian:

def int_to_bytes(val, num_bytes):
    return [(val & (0xff << pos*8)) >> pos*8 for pos in range(num_bytes)]

Big-endian:

def int_to_bytes(val, num_bytes):
    return [(val & (0xff << pos*8)) >> pos*8 for pos in reversed(range(num_bytes))]

Installing jQuery?

As pointed out, you don't need to. Use the Google AJAX Libraries API, and you get CDN hosting of jQuery for free, as depending on your site assets, jQuery can be one of the larger downloads for users.

Does java have a int.tryparse that doesn't throw an exception for bad data?

Edit -- just saw your comment about the performance problems associated with a potentially bad piece of input data. I don't know offhand how try/catch on parseInt compares to a regex. I would guess, based on very little hard knowledge, that regexes are not hugely performant, compared to try/catch, in Java.

Anyway, I'd just do this:

public Integer tryParse(Object obj) {
  Integer retVal;
  try {
    retVal = Integer.parseInt((String) obj);
  } catch (NumberFormatException nfe) {
    retVal = 0; // or null if that is your preference
  }
  return retVal;
}

How can I generate a list or array of sequential integers in Java?

This is the shortest I could get using Core Java.

List<Integer> makeSequence(int begin, int end) {
  List<Integer> ret = new ArrayList(end - begin + 1);

  for(int i = begin; i <= end; i++, ret.add(i));

  return ret;  
}

WAMP won't turn green. And the VCRUNTIME140.dll error

You need to install some Visual C++ packages BEFORE installing WAMP (if you have installed then you must uninstall and reinstall).

You need: VC9, VC10, VC11, VC13 and VC14

In readme.txt of wampserver 3 (on SourceForge) you can find the links.

Be careful! If you use a 64-bit OS you need to install both versions of each package.

How to add a local repo and treat it as a remote repo

I am posting this answer to provide a script with explanations that covers three different scenarios of creating a local repo that has a local remote. You can run the entire script and it will create the test repos in your home folder (tested on windows git bash). The explanations are inside the script for easier saving to your personal notes, its very readable from, e.g. Visual Studio Code.

I would also like to thank Jack for linking to this answer where adelphus has good, detailed, hands on explanations on the topic.

This is my first post here so please advise what should be improved.

## SETUP LOCAL GIT REPO WITH A LOCAL REMOTE
# the main elements:
# - remote repo must be initialized with --bare parameter
# - local repo must be initialized
# - local repo must have at least one commit that properly initializes a branch(root of the commit tree)
# - local repo needs to have a remote
# - local repo branch must have an upstream branch on the remote

{ # the brackets are optional, they allow to copy paste into terminal and run entire thing without interruptions, run without them to see which cmd outputs what

cd ~
rm -rf ~/test_git_local_repo/

## Option A - clean slate - you have nothing yet

mkdir -p ~/test_git_local_repo/option_a ; cd ~/test_git_local_repo/option_a
git init --bare local_remote.git # first setup the local remote
git clone local_remote.git local_repo # creates a local repo in dir local_repo
cd ~/test_git_local_repo/option_a/local_repo
git remote -v show origin # see that git clone has configured the tracking
touch README.md ; git add . ; git commit -m "initial commit on master" # properly init master
git push origin master # now have a fully functional setup, -u not needed, git clone does this for you

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branches and their respective remote upstream branches with the initial commit
git remote -v show origin # see all branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote

## Option B - you already have a local git repo and you want to connect it to a local remote

mkdir -p ~/test_git_local_repo/option_b ; cd ~/test_git_local_repo/option_b
git init --bare local_remote.git # first setup the local remote

# simulate a pre-existing git local repo you want to connect with the local remote
mkdir local_repo ; cd local_repo
git init # if not yet a git repo
touch README.md ; git add . ; git commit -m "initial commit on master" # properly init master
git checkout -b develop ; touch fileB ; git add . ; git commit -m "add fileB on develop" # create develop and fake change

# connect with local remote
cd ~/test_git_local_repo/option_b/local_repo
git remote add origin ~/test_git_local_repo/option_b/local_remote.git
git remote -v show origin # at this point you can see that there is no the tracking configured (unlike with git clone), so you need to push with -u
git push -u origin master # -u to set upstream
git push -u origin develop # -u to set upstream; need to run this for every other branch you already have in the project

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branch(es) and its remote upstream with the initial commit
git remote -v show origin # see all remote branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote

## Option C - you already have a directory with some files and you want it to be a git repo with a local remote

mkdir -p ~/test_git_local_repo/option_c ; cd ~/test_git_local_repo/option_c
git init --bare local_remote.git # first setup the local remote

# simulate a pre-existing directory with some files
mkdir local_repo ; cd local_repo ; touch README.md fileB

# make a pre-existing directory a git repo and connect it with local remote
cd ~/test_git_local_repo/option_c/local_repo
git init
git add . ; git commit -m "inital commit on master" # properly init master
git remote add origin ~/test_git_local_repo/option_c/local_remote.git
git remote -v show origin # see there is no the tracking configured (unlike with git clone), so you need to push with -u
git push -u origin master # -u to set upstream

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branch and its remote upstream with the initial commit
git remote -v show origin # see all remote branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote
}

Error Code: 1005. Can't create table '...' (errno: 150)

Error Code: 1005 -- there is a wrong primary key reference in your code

Usually it's due to a referenced foreign key field that does not exist. It might be you have a typo mistake, or check case it should be same, or there's a field-type mismatch. Foreign key-linked fields must match definitions exactly.

Some known causes may be:

  1. The two key fields type and/or size doesn’t match exactly. For example, if one is INT(10) the key field needs to be INT(10) as well and not INT(11) or TINYINT. You may want to confirm the field size using SHOW CREATE TABLE because Query Browser will sometimes visually show just INTEGER for both INT(10) and INT(11). You should also check that one is not SIGNED and the other is UNSIGNED. They both need to be exactly the same.
  2. One of the key field that you are trying to reference does not have an index and/or is not a primary key. If one of the fields in the relationship is not a primary key, you must create an index for that field.
  3. The foreign key name is a duplicate of an already existing key. Check that the name of your foreign key is unique within your database. Just add a few random characters to the end of your key name to test for this.
  4. One or both of your tables is a MyISAM table. In order to use foreign keys, the tables must both be InnoDB. (Actually, if both tables are MyISAM then you won’t get an error message - it just won’t create the key.) In Query Browser, you can specify the table type.
  5. You have specified a cascade ON DELETE SET NULL, but the relevant key field is set to NOT NULL. You can fix this by either changing your cascade or setting the field to allow NULL values.
  6. Make sure that the Charset and Collate options are the same both at the table level as well as individual field level for the key columns.
  7. You have a default value (that is, default=0) on your foreign key column
  8. One of the fields in the relationship is part of a combination (composite) key and does not have its own individual index. Even though the field has an index as part of the composite key, you must create a separate index for only that key field in order to use it in a constraint.
  9. You have a syntax error in your ALTER statement or you have mistyped one of the field names in the relationship
  10. The name of your foreign key exceeds the maximum length of 64 characters.

For more details, refer to: MySQL Error Number 1005 Can’t create table

HTML5 Canvas 100% Width Height of Viewport?

(Expanding upon ????'s answer)

Style the canvas to fill the body. When rendering to the canvas take its size into account.

http://jsfiddle.net/mqFdk/356/

<!DOCTYPE html>
<html>
<head>
    <title>aj</title>
</head>
<body>

    <canvas id="c"></canvas>

</body>
</html>

CSS:

body { 
       margin: 0; 
       padding: 0
     }
#c { 
     position: absolute; 
     width: 100%; 
     height: 100%; 
     overflow: hidden
   }

Javascript:

function redraw() {
    var cc = c.getContext("2d");
    c.width = c.clientWidth;
    c.height = c.clientHeight;
    cc.scale(c.width, c.height);

    // Draw a circle filling the canvas.
    cc.beginPath();
    cc.arc(0.5, 0.5, .5, 0, 2*Math.PI);
    cc.fill();
}

// update on any window size change.
window.addEventListener("resize", redraw);

// first draw
redraw();

How to show an empty view with a RecyclerView?

For my projects I made this solution (RecyclerView with setEmptyView method):

public class RecyclerViewEmptySupport extends RecyclerView {
    private View emptyView;

    private AdapterDataObserver emptyObserver = new AdapterDataObserver() {


        @Override
        public void onChanged() {
            Adapter<?> adapter =  getAdapter();
            if(adapter != null && emptyView != null) {
                if(adapter.getItemCount() == 0) {
                    emptyView.setVisibility(View.VISIBLE);
                    RecyclerViewEmptySupport.this.setVisibility(View.GONE);
                }
                else {
                    emptyView.setVisibility(View.GONE);
                    RecyclerViewEmptySupport.this.setVisibility(View.VISIBLE);
                }
            }

        }
    };

    public RecyclerViewEmptySupport(Context context) {
        super(context);
    }

    public RecyclerViewEmptySupport(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RecyclerViewEmptySupport(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setAdapter(Adapter adapter) {
        super.setAdapter(adapter);

        if(adapter != null) {
            adapter.registerAdapterDataObserver(emptyObserver);
        }

        emptyObserver.onChanged();
    }

    public void setEmptyView(View emptyView) {
        this.emptyView = emptyView;
    }
}

And you should use it instead of RecyclerView class:

<com.maff.utils.RecyclerViewEmptySupport android:id="@+id/list1"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    />

<TextView android:id="@+id/list_empty"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Empty"
    />

and

RecyclerViewEmptySupport list = 
    (RecyclerViewEmptySupport)rootView.findViewById(R.id.list1);
list.setLayoutManager(new LinearLayoutManager(context));
list.setEmptyView(rootView.findViewById(R.id.list_empty));

Updating a dataframe column in spark

Commonly when updating a column, we want to map an old value to a new value. Here's a way to do that in pyspark without UDF's:

# update df[update_col], mapping old_value --> new_value
from pyspark.sql import functions as F
df = df.withColumn(update_col,
    F.when(df[update_col]==old_value,new_value).
    otherwise(df[update_col])).

sort dict by value python

You could created sorted list from Values and rebuild the dictionary:

myDictionary={"two":"2", "one":"1", "five":"5", "1four":"4"}

newDictionary={}

sortedList=sorted(myDictionary.values())

for sortedKey in sortedList:
    for key, value in myDictionary.items():
        if value==sortedKey:
            newDictionary[key]=value

Output: newDictionary={'one': '1', 'two': '2', '1four': '4', 'five': '5'}

ImportError: No module named xlsxwriter

I am not sure what caused this but it went all well once I changed the path name from Lib into lib and I was finally able to make it work.

how to use LIKE with column name

SQL SERVER

 WHERE ColumnName LIKE '%'+ColumnName+'%'

Cannot serve WCF services in IIS on Windows 8

Please do the following two steps on IIS 8.0

Add new MIME type & HttpHandler

  1. Extension: .svc, MIME type: application/octet-stream

  2. Request path: *.svc, Type: System.ServiceModel.Activation.HttpHandler, Name: svc-Integrated

Which is preferred: Nullable<T>.HasValue or Nullable<T> != null?

In VB.Net. Do NOT use "IsNot Nothing" when you can use ".HasValue". I just solved an "Operation could destabilize the runtime" Medium trust error by replacing "IsNot Nothing" with ".HasValue" In one spot. I don't really understand why, but something is happening differently in the compiler. I would assume that "!= null" in C# may have the same issue.

How can I capitalize the first letter of each word in a string?

I really like this answer:

Copy-paste-ready version of @jibberia anwser:

def capitalize(line):
    return ' '.join([s[0].upper() + s[1:] for s in line.split(' ')])

But some of the lines that I was sending split off some blank '' characters that caused errors when trying to do s[1:]. There is probably a better way to do this, but I had to add in a if len(s)>0, as in

return ' '.join([s[0].upper() + s[1:] for s in line.split(' ') if len(s)>0])

Append text to file from command line without using io redirection

You can use the --append feature of tee:

cat file01.txt | tee --append bothFiles.txt 
cat file02.txt | tee --append bothFiles.txt 

Or shorter,

cat file01.txt file02.txt | tee --append bothFiles.txt 

I assume the request for no redirection (>>) comes from the need to use this in xargs or similar. So if that doesn't count, you can mute the output with >/dev/null.

Immutable vs Mutable types

What? Floats are immutable? But can't I do

x = 5.0
x += 7.0
print x # 12.0

Doesn't that "mut" x?

Well you agree strings are immutable right? But you can do the same thing.

s = 'foo'
s += 'bar'
print s # foobar

The value of the variable changes, but it changes by changing what the variable refers to. A mutable type can change that way, and it can also change "in place".

Here is the difference.

x = something # immutable type
print x
func(x)
print x # prints the same thing

x = something # mutable type
print x
func(x)
print x # might print something different

x = something # immutable type
y = x
print x
# some statement that operates on y
print x # prints the same thing

x = something # mutable type
y = x
print x
# some statement that operates on y
print x # might print something different

Concrete examples

x = 'foo'
y = x
print x # foo
y += 'bar'
print x # foo

x = [1, 2, 3]
y = x
print x # [1, 2, 3]
y += [3, 2, 1]
print x # [1, 2, 3, 3, 2, 1]

def func(val):
    val += 'bar'

x = 'foo'
print x # foo
func(x)
print x # foo

def func(val):
    val += [3, 2, 1]

x = [1, 2, 3]
print x # [1, 2, 3]
func(x)
print x # [1, 2, 3, 3, 2, 1]

Allow all remote connections, MySQL

Mabey you only need:

Step one:

grant all privileges on *.* to 'user'@'IP' identified by 'password';

or

grant all privileges on *.* to 'user'@'%' identified by 'password';

Step two:

sudo ufw allow 3306

Step three:

sudo service mysql restart

Disable native datepicker in Google Chrome

I know this is an old question now, but I just landed here looking for information about this so somebody else might too.

You can use Modernizr to detect whether the browser supports HTML5 input types, like 'date'. If it does, those controls will use the native behaviour to display things like datepickers. If it doesn't, you can specify what script should be used to display your own datepicker. Works well for me!

I added jquery-ui and Modernizr to my page, then added this code:

<script type="text/javascript">
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(initDateControls);
    initDateControls();

    function initDateControls() {
        //Adds a datepicker to inputs with a type of 'date' when the browser doesn't support that HTML5 tag (type=date)'
        Modernizr.load({
            test: Modernizr.inputtypes.datetime,
            nope: "scripts/jquery-ui.min.js",
            callback: function () {
                $("input[type=date]").datepicker({ dateFormat: "dd-mm-yy" });
            }
        });
    }

</script>

This means that the native datepicker is displayed in Chrome, and the jquery-ui one is displayed in IE.

Why can't variables be declared in a switch statement?

The entire section of the switch is a single declaration context. You can't declare a variable in a case statement like that. Try this instead:

switch (val)  
{  
case VAL:
{
  // This will work
  int newVal = 42;
  break;
}
case ANOTHER_VAL:  
  ...
  break;
}

Android app unable to start activity componentinfo

The question is answered already, but I want add more information about the causes.

Android app unable to start activity componentinfo

This error often comes with appropriate logs. You can read logs and can solve this issue easily.

Here is a sample log. In which you can see clearly ClassCastException. So this issue came because TextView cannot be cast to EditText.

Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText

11-04 01:24:10.403: D/AndroidRuntime(1050): Shutting down VM
11-04 01:24:10.403: W/dalvikvm(1050): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:24:10.543: E/AndroidRuntime(1050): FATAL EXCEPTION: main
11-04 01:24:10.543: E/AndroidRuntime(1050): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.os.Looper.loop(Looper.java:137)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at dalvik.system.NativeStart.main(Native Method)
11-04 01:24:10.543: E/AndroidRuntime(1050): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:24:10.543: E/AndroidRuntime(1050):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:45)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:24:10.543: E/AndroidRuntime(1050):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:24:10.543: E/AndroidRuntime(1050):     ... 11 more
11-04 01:29:11.177: I/Process(1050): Sending signal. PID: 1050 SIG: 9
11-04 01:31:32.080: D/AndroidRuntime(1109): Shutting down VM
11-04 01:31:32.080: W/dalvikvm(1109): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 01:31:32.194: E/AndroidRuntime(1109): FATAL EXCEPTION: main
11-04 01:31:32.194: E/AndroidRuntime(1109): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.os.Looper.loop(Looper.java:137)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at dalvik.system.NativeStart.main(Native Method)
11-04 01:31:32.194: E/AndroidRuntime(1109): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 01:31:32.194: E/AndroidRuntime(1109):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 01:31:32.194: E/AndroidRuntime(1109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 01:31:32.194: E/AndroidRuntime(1109):     ... 11 more
11-04 01:36:33.195: I/Process(1109): Sending signal. PID: 1109 SIG: 9
11-04 02:11:09.684: D/AndroidRuntime(1167): Shutting down VM
11-04 02:11:09.684: W/dalvikvm(1167): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-04 02:11:09.855: E/AndroidRuntime(1167): FATAL EXCEPTION: main
11-04 02:11:09.855: E/AndroidRuntime(1167): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.troysantry.tipcalculator/com.troysantry.tipcalculator.TipCalc}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.os.Looper.loop(Looper.java:137)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.main(ActivityThread.java:5103)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invokeNative(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at java.lang.reflect.Method.invoke(Method.java:525)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at dalvik.system.NativeStart.main(Native Method)
11-04 02:11:09.855: E/AndroidRuntime(1167): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.EditText
11-04 02:11:09.855: E/AndroidRuntime(1167):     at com.troysantry.tipcalculator.TipCalc.onCreate(TipCalc.java:44)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.Activity.performCreate(Activity.java:5133)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-04 02:11:09.855: E/AndroidRuntime(1167):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-04 02:11:09.855: E/AndroidRuntime(1167):     ... 11 more

Some Common Mistakes.

1.findViewById() of non existing view

Like when you use findViewById(R.id.button) when button id does not exist in layout XML.

2. Wrong cast.

If you wrong cast some class, then you get this error. Like you cast RelativeLayout to LinearLayout or EditText to TextView.

3. Activity not registered in manifest.xml

If you did not register Activity in manifest.xml then this error comes.

4. findViewById() with declaration at top level

Below code is incorrect. This will create error. Because you should do findViewById() after calling setContentView(). Because an View can be there after it is created.

public class MainActivity extends Activity {

  ImageView mainImage = (ImageView) findViewById(R.id.imageViewMain); //incorrect way

  @Override
  protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mainImage = (ImageView) findViewById(R.id.imageViewMain); //correct way
    //...
  }
}

5. Starting abstract Activity class.

When you try to start an Activity which is abstract, you will will get this error. So just remove abstract keyword before activity class name.

6. Using kotlin but kotlin not configured.

If your activity is written in Kotlin and you have not setup kotlin in your app. then you will get error. You can follow simple steps as written in Android Link or Kotlin Link. You can check this answer too.

More information

Read about Downcast and Upcast

Read about findViewById() method of Activity class

Super keyword in Java

How to register activity in manifest

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

Use Message.get_payload

b = email.message_from_string(a)
if b.is_multipart():
    for payload in b.get_payload():
        # if payload.is_multipart(): ...
        print payload.get_payload()
else:
    print b.get_payload()

How can I change property names when serializing with Json.net?

You could decorate the property you wish controlling its name with the [JsonProperty] attribute which allows you to specify a different name:

using Newtonsoft.Json;
// ...

[JsonProperty(PropertyName = "FooBar")]
public string Foo { get; set; }

Documentation: Serialization Attributes

How to Multi-thread an Operation Within a Loop in Python

Edit 2018-02-06: revision based on this comment

Edit: forgot to mention that this works on Python 2.7.x

There's multiprocesing.pool, and the following sample illustrates how to use one of them:

from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool

pool_size = 5  # your "parallelness"

# define worker function before a Pool is instantiated
def worker(item):
    try:
        api.my_operation(item)
    except:
        print('error with item')

pool = Pool(pool_size)

for item in items:
    pool.apply_async(worker, (item,))

pool.close()
pool.join()

Now if you indeed identify that your process is CPU bound as @abarnert mentioned, change ThreadPool to the process pool implementation (commented under ThreadPool import). You can find more details here: http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers

Targeting only Firefox with CSS

A variation on your idea is to have a server-side USER-AGENT detector that will figure out what style sheet to attach to the page. This way you can have a firefox.css, ie.css, opera.css, etc.

You can accomplish a similar thing in Javascript itself, although you may not regard it as clean.

I have done a similar thing by having a default.css which includes all common styles and then specific style sheets are added to override, or enhance the defaults.

Change key pair for ec2 instance

  • Create new key e.g. using PuTTY Key Generator
  • Stop instance
  • Set instance user data to push public key to server
  • Start instance

Warning: Don't forget to clear the user data again. Otherwise this key will be pushed on every instance start. Step-by-step instructions.

#cloud-config
bootcmd:
 - echo 'ssh-rsa AAAAB3Nz...' > /root/.ssh/authorized_keys

enter image description here

Display back button on action bar

The magic happens in onOptionsItemSelected.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // app icon in action bar clicked; go home
            Intent intent = new Intent(this, HomeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

jQuery ui dialog change title after load-callback

I tried to implement the result of Nick which is:

$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');

But that didn't work for me because i had multiple dialogs on 1 page. In such a situation it will only set the title correct the first time. Trying to staple commands did not work:

    $("#modal_popup").html(data);
    $("#modal_popup").dialog('option', 'title', 'My New Title');
    $("#modal_popup").dialog({ width: 950, height: 550);

I fixed this by adding the title to the javascript function arguments of each dialog on the page:

function show_popup1() {
    $("#modal_popup").html(data);
    $("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my First Dialog'});
}

function show_popup2() {
    $("#modal_popup").html(data);
    $("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my Other Dialog'});
}

Find maximum value of a column and return the corresponding row values using Pandas

My solution for finding maximum values in columns:

df.ix[df.idxmax()]

, also minimum:

df.ix[df.idxmin()]

How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

You can use the iterator remove() function to remove the object from underlying collection object. But in this case you can remove the same object and not any other object from the list.

from here

Cleanest way to build an SQL string in Java

Google provides a library called the Room Persitence Library which provides a very clean way of writing SQL for Android Apps, basically an abstraction layer over underlying SQLite Database. Bellow is short code snippet from the official website:

@Dao
public interface UserDao {
    @Query("SELECT * FROM user")
    List<User> getAll();

    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    List<User> loadAllByIds(int[] userIds);

    @Query("SELECT * FROM user WHERE first_name LIKE :first AND "
           + "last_name LIKE :last LIMIT 1")
    User findByName(String first, String last);

    @Insert
    void insertAll(User... users);

    @Delete
    void delete(User user);
}

There are more examples and better documentation in the official docs for the library.

There is also one called MentaBean which is a Java ORM. It has nice features and seems to be pretty simple way of writing SQL.

c# - approach for saving user settings in a WPF application?

You can use Application Settings for this, using database is not the best option considering the time consumed to read and write the settings(specially if you use web services).

Here are few links which explains how to achieve this and use them in WPF -

User Settings in WPF

Quick WPF Tip: How to bind to WPF application resources and settings?

A Configurable Window for WPF

Detect whether there is an Internet connection available on Android

The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none if the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available.

private boolean isNetworkAvailable() {
     ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
     NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
     return activeNetworkInfo != null; 
}

You will also need:

in your android manifest.

Edit:

Note that having an active network interface doesn't guarantee that a particular networked service is available. Networks issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.

getActiveNetworkInfo() shouldn't never give null. I don't know what they were thinking when they came up with that. It should give you an object always.

Android Studio - mergeDebugResources exception

In my case I just removed the space from project folder name From: MyApp latest

To: MyApp_latest

and it worked.

How to check if a subclass is an instance of a class at runtime?

You have to read the API carefully for this methods. Sometimes you can get confused very easily.

It is either:

if (B.class.isInstance(view))

API says: Determines if the specified Object (the parameter) is assignment-compatible with the object represented by this Class (The class object you are calling the method at)

or:

if (B.class.isAssignableFrom(view.getClass()))

API says: Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter

or (without reflection and the recommended one):

if (view instanceof B)

You are trying to add a non-nullable field 'new_field' to userprofile without a default

In case anyone is setting a ForeignKey, you can just allow nullable fields without setting a default:

new_field = models.ForeignKey(model, null=True)

If you already have data stored within the database, you can also set a default value:

new_field = models.ForeignKey(model, default=<existing model id here>)

How to customize a Spinner in Android

The most elegant and flexible solution I have found so far is here: http://android-er.blogspot.sg/2010/12/custom-arrayadapter-for-spinner-with.html

Basically, follow these steps:

  1. Create custom layout xml file for your dropdown item, let's say I will call it spinner_item.xml
  2. Create custom view class, for your dropdown Adapter. In this custom class, you need to overwrite and set your custom dropdown item layout in getView() and getDropdownView() method. My code is as below:

    public class CustomArrayAdapter extends ArrayAdapter<String>{
    
    private List<String> objects;
    private Context context;
    
    public CustomArrayAdapter(Context context, int resourceId,
         List<String> objects) {
         super(context, resourceId, objects);
         this.objects = objects;
         this.context = context;
    }
    
    @Override
    public View getDropDownView(int position, View convertView,
        ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }
    
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      return getCustomView(position, convertView, parent);
    }
    
    public View getCustomView(int position, View convertView, ViewGroup parent) {
    
    LayoutInflater inflater=(LayoutInflater) context.getSystemService(  Context.LAYOUT_INFLATER_SERVICE );
    View row=inflater.inflate(R.layout.spinner_item, parent, false);
    TextView label=(TextView)row.findViewById(R.id.spItem);
     label.setText(objects.get(position));
    
    if (position == 0) {//Special style for dropdown header
          label.setTextColor(context.getResources().getColor(R.color.text_hint_color));
    }
    
    return row;
    }
    
    }
    
  3. In your activity or fragment, make use of the custom adapter for your spinner view. Something like this:

    Spinner sp = (Spinner)findViewById(R.id.spMySpinner);
    ArrayAdapter<String> myAdapter = new CustomArrayAdapter(this, R.layout.spinner_item, options);
    sp.setAdapter(myAdapter);
    

where options is the list of dropdown item string.

Can Twitter Bootstrap alerts fade in as well as out?

Of course, Yes. Use this simple file in your project: https://gist.github.com/3851727

First add you HTML like this:

<div id="messagebox" class="alert hide"></div>

and then use:

$("#messagebox").message({text: "Hello world!", type: "error"});

You can pass all bootstrap alert types such as error, success and warning to type property as options.

gcc makefile error: "No rule to make target ..."

This message can mean many things clearly.

In my case it was compiling using multiple threads. One thread needed a dependency that another thread hadn't finished making, causing an error.

Not all builds are threadsafe, so consider a slow build with one thread if your build passes other tests such as the ones listed above.

Center the content inside a column in Bootstrap 4

There are multiple horizontal centering methods in Bootstrap 4...

  • text-center for center display:inline elements
  • offset-* or mx-auto can be used to center column (col-*)
  • or, justify-content-center on the row to center columns (col-*)
  • mx-auto for centering display:block elements inside d-flex

mx-auto (auto x-axis margins) will center display:block or display:flex elements that have a defined width, (%, vw, px, etc..). Flexbox is used by default on grid columns, so there are also various flexbox centering methods.

Demo of the Bootstrap 4 Centering Methods

In your case, use mx-auto to center the col-3 and text-center to center it's content..

<div class="row">
    <div class="col-3 mx-auto">
        <div class="text-center">
            center
        </div>
    </div>
</div>

https://codeply.com/go/GRUfnxl3Ol

or, using justify-content-center on flexbox elements (.row):

<div class="container">
    <div class="row justify-content-center">
        <div class="col-3 text-center">
            center
        </div>
    </div>
</div>

Also see:
Vertical Align Center in Bootstrap 4

PHP: HTTP or HTTPS?

If the request was sent with HTTPS you will have a extra parameter in the $_SERVER superglobal - $_SERVER['HTTPS']. You can check if it is set or not

if( isset($_SERVER['HTTPS'] ) ) {

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

Base64 length calculation?

I think the given answers miss the point of the original question, which is how much space needs to be allocated to fit the base64 encoding for a given binary string of length n bytes.

The answer is (floor(n / 3) + 1) * 4 + 1

This includes padding and a terminating null character. You may not need the floor call if you are doing integer arithmetic.

Including padding, a base64 string requires four bytes for every three-byte chunk of the original string, including any partial chunks. One or two bytes extra at the end of the string will still get converted to four bytes in the base64 string when padding is added. Unless you have a very specific use, it is best to add the padding, usually an equals character. I added an extra byte for a null character in C, because ASCII strings without this are a little dangerous and you'd need to carry the string length separately.

replace all occurrences in a string

Use the global flag.

str.replace(/\n/g, '<br />');

How to find which columns contain any NaN value in Pandas dataframe

You can use df.isnull().sum(). It shows all columns and the total NaNs of each feature.

Center div on the middle of screen

This should work with any div or screen size:

_x000D_
_x000D_
.center-screen {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  text-align: center;_x000D_
  min-height: 100vh;_x000D_
}
_x000D_
 <html>_x000D_
 <head>_x000D_
 </head>_x000D_
 <body>_x000D_
 <div class="center-screen">_x000D_
 I'm in the center_x000D_
 </div>_x000D_
 </body>_x000D_
 </html>
_x000D_
_x000D_
_x000D_

See more details about flex here. This should work on most of the browsers, see compatibility matrix here.

Update: If you don't want the scroll bar, make min-height smaller, for example min-height: 95vh;

How can I make a list of lists in R?

If you are trying to keep a list of lists (similar to python's list.append()) then this might work:

a <- list(1,2,3)
b <- list(4,5,6)
c <- append(list(a), list(b))

> c
[[1]]
[[1]][[1]]
[1] 1

[[1]][[2]]
[1] 2

[[1]][[3]]
[1] 3


[[2]]
[[2]][[1]]
[1] 4

[[2]][[2]]
[1] 5

[[2]][[3]]
[1] 6

AngularJS - Create a directive that uses ng-model

I wouldn't set the ngmodel via an attribute, you can specify it right in the template:

template: '<div class="some"><label>{{label}}</label><input data-ng-model="ngModel"></div>',

plunker: http://plnkr.co/edit/9vtmnw?p=preview

How to see the CREATE VIEW code for a view in PostgreSQL?

GoodNews from v.9.6 and above, View editing are now native from psql. Just invoke \ev command. View definitions will show in your configured editor.

julian@assange=# \ev {your_view_names}

Bonus. Some useful command to interact with query buffer.

Query Buffer
  \e [FILE] [LINE]       edit the query buffer (or file) with external editor
  \ef [FUNCNAME [LINE]]  edit function definition with external editor
  \ev [VIEWNAME [LINE]]  edit view definition with external editor
  \p                     show the contents of the query buffer
  \r                     reset (clear) the query buffer
  \s [FILE]              display history or save it to file
  \w FILE                write query buffer to file

PHP Email sending BCC

You were setting BCC but then overwriting the variable with the FROM

$to = "[email protected]";
     $subject .= "".$emailSubject."";
 $headers .= "Bcc: ".$emailList."\r\n";
 $headers .= "From: [email protected]\r\n" .
     "X-Mailer: php";
     $headers .= "MIME-Version: 1.0\r\n";
     $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
 $message = '<html><body>';
 $message .= 'THE MESSAGE FROM THE FORM';

     if (mail($to, $subject, $message, $headers)) {
     $sent = "Your email was sent!";
     } else {
      $sent = ("Error sending email.");
     }

Import PEM into Java Key Store

Although this question is pretty old and it has already a-lot answers, I think it is worth to provide an alternative. Using native java classes makes it very verbose to just use pem files and almost forces you wanting to convert the pem files into p12 or jks files as using p12 or jks files are much easier. I want to give anyone who wants an alternative for the already provided answers.

GitHub - SSLContext Kickstart

var keyManager = PemUtils.loadIdentityMaterial("certificate-chain.pem", "private-key.pem");
var trustManager = PemUtils.loadTrustMaterial("some-trusted-certificate.pem");

var sslFactory = SSLFactory.builder()
          .withIdentityMaterial(keyManager)
          .withTrustMaterial(trustManager)
          .build();

var sslContext = sslFactory.getSslContext();

I need to provide some disclaimer here, I am the library maintainer

What is the worst programming language you ever worked with?

The worse language I've ever seen come from the tool praat, which is a good audio analysis tool. It does a pretty good job until you use the script language. sigh bad memories.

Tiny praat script tutorial for beginners

  • Function call

    We've listed at least 3 different function calling syntax :
    • The regular one

      string = selected("Strings")

      Nothing special here, you assign to the variable string the result of the selected function. Not really scary... yet.

    • The "I'm invoking some GUI command with parameters"

      Create Strings as file list... liste 'path$'/'type$'

      As you can see, the function name start at "Create" and finish with the "...". The command "Create Strings as file list" is the text displayed on a button or a menu (I'm to scared to check) on praat. This command take 2 parameters liste and an expression. I'm going to look deeper in the expression 'path$'/'type$'

      Hmm. Yep. No spaces. If spaces were introduced, it would be separate arguments. As you can imagine, parenthesis don't work. At this point of the description I would like to point out the suffix of the variable names. I won't develop it in this paragraph, I'm just teasing.

    • The "Oh, but I want to get the result of the GUI command in my variable"

      noliftt = Get number of strings
      Yes we can see a pattern here, long and weird function name, it must be a GUI calling. But there's no '...' so no parameters. I don't want to see what the parser looks like.
  • The incredible type system

    (AKA Haskell and OCaml, praat is coming to you)
    • Simple natives types

      windowname$ = left$(line$,length(line$)-4)

      So, what's going on there? It's now time to look at the convention and types of expression, so here we got :

      • left$ :: (String, Int) -> String
      • lenght :: (String) -> Int
      • windowname$ :: String
      • line$ :: String
      As you can see, variable name and function names are suffixed with their type or return type. If their suffix is a '$', then it return a string or is a string. If there is nothing it's a number. I can see the point of prefixing the type to a variable to ease implementation, but to suffix, no sorry, I can't

    • Array type

      To show the array type, let me introduce a 'tiny' loop :
      
          for i from 1 to 4
              Select... time time
              bandwidth'i'$ = Get bandwidth... i
              forhertz'i'$ = Get formant... i
          endfor
          

      We got i which is a number and... (no it's not a function)
      bandwidth'i'$
      What it does is create string variables : bandwidth1$, bandwidth2$, bandwidth3$, bandwidth4$ and give them values. As you can expect, you can't create two dimensional array this way, you must do something like that : band2D__'i'__'j'$

      http://img214.imageshack.us/img214/3008/scaredkittylolqa2.jpg
    • The special string invocation

      outline$ = "'time'@F'i':'forhertznum'Hz,'bandnum'Hz, 'spec''newline$'" outline$ >> 'outfile$'

      Strings are weirdly (at least) handled in the language. the '' is used to call the value of a variable inside the global "" string. This is weird. It goes against all the convention built into many languages from bash to PHP passing by the powershell. And look, it even got redirection. Don't be fooled, it doesn't work like in your beloved shell. No you have to get the variable value with the ''

    • Da Wonderderderfulful execution model

      I'm going to put the final touch to this wonderderderfulful presentation by talking to you about the execution model. So as in every procedural languages you got instruction executed from top to bottom, there is the variables and the praat GUI. That is you code everything on the praat gui, you invoke commands written on menu/buttons.

      The main window of praat contain a list of items which can be :

      • files
      • list of files (created by a function with a wonderderfulful long long name)
      • Spectrogramm
      • Strings (don't ask)
      So if you want to perform operation on a given file, you must select the file in the list programmatically and then push the different buttons to take some actions. If you wanted to pass parameters to a GUI action, you have to follow the GUI layout of the form for your arguments, for example "To Spectrogram... 0.005 5000 0.002 20 Gaussian " is like that because it follows this layout:

      http://img7.imageshack.us/img7/5534/tospectrogramm.png

    Needless to say, my nightmares are filled with praat scripts dancing around me and shouting "DEBUG MEEEE!!".

    More information at the praat site, under the well-named section "easy programmable scripting language"

  • Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'

    I found the solution. I misplaced the path to the keystore.jks file. Searched for the file on my computer used that path and everything worked great.

    VBA Excel Provide current Date in Text box

    Here's a more simple version. In the cell you want the date to show up just type

    =Today()      
    

    Format the cell to the date format you want and Bob's your uncle. :)

    How to assign the output of a Bash command to a variable?

    In this specific case, note that bash has a variable called PWD that contains the current directory: $PWD is equivalent to `pwd`. (So do other shells, this is a standard feature.) So you can write your script like this:

    #!/bin/bash
    until [ "$PWD" = "/" ]; do
      echo "$PWD"
      ls && cd .. && ls 
    done
    

    Note the use of double quotes around the variable references. They are necessary if the variable (here, the current directory) contains whitespace or wildcards (\[?*), because the shell splits the result of variable expansions into words and performs globbing on these words. Always double-quote variable expansions "$foo" and command substitutions "$(foo)" (unless you specifically know you have not to).

    In the general case, as other answers have mentioned already:

    • You can't use whitespace around the equal sign in an assignment: var=value, not var = value
    • The $ means “take the value of this variable”, so you don't use it when assigning: var=value, not $var=value.

    How to calculate Date difference in Hive

    datediff(to_date(String timestamp), to_date(String timestamp))
    

    For example:

    SELECT datediff(to_date('2019-08-03'), to_date('2019-08-01')) <= 2;
    

    Get first key in a (possibly) associative array?

    This is the easier way I had ever found. Fast and only two lines of code :-D

    $keys = array_keys($array);
    echo $array[$keys[0]];
    

    Python: Adding element to list while iterating

    Access your list elements directly by i. Then you can append to your list:

    for i in xrange(len(myarr)):
        if somecond(a[i]):
            myarr.append(newObj())
    

    How do I format a date in Jinja2?

    in flask, with babel, I like to do this :

    @app.template_filter('dt')
    def _jinja2_filter_datetime(date, fmt=None):
        if fmt:
            return date.strftime(fmt)
        else:
            return date.strftime(gettext('%%m/%%d/%%Y'))
    

    used in the template with {{mydatetimeobject|dt}}

    so no with babel you can specify your various format in messages.po like this for instance :

    #: app/views.py:36
    #, python-format
    msgid "%%m/%%d/%%Y"
    msgstr "%%d/%%m/%%Y"
    

    Angular 2 TypeScript how to find element in Array

    Transform the data structure to a map if you frequently use this search

    mapPersons: Map<number, Person>;
    
    // prepare the map - call once or when person array change
    populateMap() : void {
        this.mapPersons = new Map();
        for (let o of this.personService.getPersons()) this.mapPersons.set(o.id, o);
    }
    getPerson(id: number) : Person {
        return this.mapPersons.get(id);
    }
    

    run a python script in terminal without the python command

    You need to use a hashbang. Add it to the first line of your python script.

    #! <full path of python interpreter>
    

    Then change the file permissions, and add the executing permission.

    chmod +x <filename>
    

    And finally execute it using

    ./<filename>
    

    If its in the current directory,

    How to convert a string with Unicode encoding to a string of letters

    The Apache Commons Lang StringEscapeUtils.unescapeJava() can decode it properly.

    import org.apache.commons.lang.StringEscapeUtils;
    
    @Test
    public void testUnescapeJava() {
        String sJava="\\u0048\\u0065\\u006C\\u006C\\u006F";
        System.out.println("StringEscapeUtils.unescapeJava(sJava):\n" + StringEscapeUtils.unescapeJava(sJava));
    }
    
    
     output:
     StringEscapeUtils.unescapeJava(sJava):
     Hello
    

    Recursive directory listing in DOS

    You can use various options with FINDSTR to remove the lines do not want, like so:

    DIR /S | FINDSTR "\-" | FINDSTR /VI DIR
    

    Normal output contains entries like these:

    28-Aug-14  05:14 PM    <DIR>          .
    28-Aug-14  05:14 PM    <DIR>          ..
    

    You could remove these using the various filtering options offered by FINDSTR. You can also use the excellent unxutils, but it converts the output to UNIX by default, so you no longer get CR+LF; FINDSTR offers the best Windows option.

    Get an OutputStream into a String

    I would use a ByteArrayOutputStream. And on finish you can call:

    new String( baos.toByteArray(), codepage );
    

    or better:

    baos.toString( codepage );
    

    For the String constructor, the codepage can be a String or an instance of java.nio.charset.Charset. A possible value is java.nio.charset.StandardCharsets.UTF_8.

    The method toString() accepts only a String as a codepage parameter (stand Java 8).

    Formatting "yesterday's" date in python

    all answers are correct, but I want to mention that time delta accepts negative arguments.

    >>> from datetime import date, timedelta
    >>> yesterday = date.today() + timedelta(days=-1)
    >>> print(yesterday.strftime('%m%d%y')) #for python2 remove parentheses 
    

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

    If "validation failure" means that there is some client error in the request, then use HTTP 400 (Bad Request). For instance if the URI is supposed to have an ISO-8601 date and you find that it's in the wrong format or refers to February 31st, then you would return an HTTP 400. Ditto if you expect well-formed XML in an entity body and it fails to parse.

    (1/2016): Over the last five years WebDAV's more specific HTTP 422 (Unprocessable Entity) has become a very reasonable alternative to HTTP 400. See for instance its use in JSON API. But do note that HTTP 422 has not made it into HTTP 1.1, RFC-7231.

    Richardson and Ruby's RESTful Web Services contains a very helpful appendix on when to use the various HTTP response codes. They say:

    400 (“Bad Request”)
    Importance: High.
    This is the generic client-side error status, used when no other 4xx error code is appropriate. It’s commonly used when the client submits a representation along with a PUT or POST request, and the representation is in the right format, but it doesn’t make any sense. (p. 381)

    and:

    401 (“Unauthorized”)
    Importance: High.
    The client tried to operate on a protected resource without providing the proper authentication credentials. It may have provided the wrong credentials, or none at all. The credentials may be a username and password, an API key, or an authentication token—whatever the service in question is expecting. It’s common for a client to make a request for a URI and accept a 401 just so it knows what kind of credentials to send and in what format. [...]

    Break or return from Java 8 stream forEach?

    Update with Java 9+ with takeWhile:

    MutableBoolean ongoing = MutableBoolean.of(true);
    someobjects.stream()...takeWhile(t -> ongoing.value()).forEach(t -> {
        // doing something.
        if (...) { // want to break;
            ongoing.setFalse();
        }
    });
    

    I can’t find the Android keytool

    I never installed Java, but when you install Android Studio it has its own version within the Android directory. Here is where mine is located. Your path may be similar. After that you can either put the keytool into your path, or just run it from that directory.

    C:\Program Files\Android\Android Studio\jre\bin
    

    sass :first-child not working

    First of all, there are still browsers out there that don't support those pseudo-elements (ie. :first-child, :last-child), so you have to 'deal' with this issue.

    There is a good example how to make that work without using pseudo-elements:

    http://www.darowski.com/tracesofinspiration/2010/01/11/this-newbies-first-impressions-of-haml-and-sass/

           -- see the divider pipe example.

    I hope that was useful.

    App not setup: This app is still in development mode

    Issue Log: App Not Setup. This app is still in development mode. and you dont have access to it. register test user or ask an app admin for permission

    1. The app are not in Live Mode
    2. You are not listed as admin or a tester in
      https://developers.facebook.com/app/yourapp
    3. Your App Hashkey are not set. if Facebook app cant be on Live Mode you need a hashkey to test it. because the app are not yet Live. Facebook wont allow an access.

    HOW TO CHANGE TO LIVE MODE
    1. go to : https://developers.facebook.com
    2. select your app on "My Apps" List
    3. toggle the switch from OFF to ON

    enter image description hereenter image description here

    HOW TO ADD AS TEST OR ADMIN
    1. go to : https://developers.facebook.com
    2. select your app on "My Apps" List
    3. go to : Roles > Roles > Press Add for example administratorenter image description here 4. Search your new admin/tester Facebook account.
    enter image description here 5. admin must enter facebook password to confirm.then submit enter image description here
    the new admin must go to developer.facebook page and accept the request
    6. go to : https://developers.facebook.com

    7. Profile > Requests > Confirm
    enter image description here List item 8. Congratulation you have been assign as new Admin

    HOW TO GET AND SET HASHKEY FOR DEVELOPMENT
    as Refer to Facebook Login Documentation
    https://developers.facebook.com/docs/android/getting-started/#create_hash
    The most preferable solution by me is by code ( Troubleshooting Sample Apps )
    it will print out the hash key. you can update it on
    https://developers.facebook.com/apps/yourFacebookappID/settings/basic/
    on Android > Key Hashes section

    a step by step process on how to get the hashKey.

    1. Firstly Add the code to any oncreate method enter image description here

    2. Run The app and Search the KeyHash at Logcat enter image description here

    step by step process on how Update on Facebook Developer.

    1. Open Facebook Developer Page. You need access as to update the Facebook Developer page.
      https://developers.facebook.com

    2. Follow the step as follow.enter image description here

    How to use Python to login to a webpage and retrieve cookies for later usage?

    import urllib, urllib2, cookielib
    
    username = 'myuser'
    password = 'mypassword'
    
    cj = cookielib.CookieJar()
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    login_data = urllib.urlencode({'username' : username, 'j_password' : password})
    opener.open('http://www.example.com/login.php', login_data)
    resp = opener.open('http://www.example.com/hiddenpage.php')
    print resp.read()
    

    resp.read() is the straight html of the page you want to open, and you can use opener to view any page using your session cookie.

    What is "with (nolock)" in SQL Server?

    WITH (NOLOCK) is the equivalent of using READ UNCOMMITED as a transaction isolation level. So, you stand the risk of reading an uncommitted row that is subsequently rolled back, i.e. data that never made it into the database. So, while it can prevent reads being deadlocked by other operations, it comes with a risk. In a banking application with high transaction rates, it's probably not going to be the right solution to whatever problem you're trying to solve with it IMHO.

    How can I change the font size using seaborn FacetGrid?

    For the legend, you can use this

    plt.setp(g._legend.get_title(), fontsize=20)
    

    Where g is your facetgrid object returned after you call the function making it.

    Load a Bootstrap popover content with AJAX. Is this possible?

    Having read all these solutions, I think the solution becomes much simpler if you use a synchronous ajax call. You can then use something like:

      $('#signin').popover({
        html: true,
        trigger: 'manual',
        content: function() {
          return $.ajax({url: '/path/to/content',
                         dataType: 'html',
                         async: false}).responseText;
        }
      }).click(function(e) {
        $(this).popover('toggle');
      });
    

    Convert PDF to PNG using ImageMagick

    Reducing the image size before output results in something that looks sharper, in my case:

    convert -density 300 a.pdf -resize 25% a.png
    

    How can I create a table with borders in Android?

    Well that may inspire u Those steps show how to create bordered table dynamically

    here is the table view

    <android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/nested_scroll_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="none"
        android:scrollingCache="true">
        <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/simpleTableLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="45dp"
            android:layout_marginRight="45dp"
            android:stretchColumns="*"
            >
        </TableLayout>
    </android.support.v4.widget.NestedScrollView>
    

    and here the row to use "attrib_row.xml"

    <?xml version="1.0" encoding="utf-8"?>
    <TableRow xmlns:android="http://schemas.android.com/apk/res/android"
        android:background="@drawable/border"
        >
        <TextView
            android:id="@+id/attrib_name"
            android:textStyle="bold"
            android:height="30dp"
            android:background="@drawable/border"
            android:gravity="center"
            />
        <TextView
            android:id="@+id/attrib_value"
            android:gravity="center"
            android:height="30dp"
            android:textStyle="bold"
            android:background="@drawable/border"
            />
    </TableRow>
    

    and we can add this xml file to drawable to add border to our table "border.xml"

    <?xml version="1.0" encoding="utf-8"?>
    <shape
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape= "rectangle">
        <solid android:color="@color/colorAccent"/>
        <stroke android:width="1dp" android:color="#000000"/>
    </shape>
    

    and finally here is the compact code written in Kotlin but it's easy to convert it to java if you need

    well temps is an array list contain data: ArrayList<Double>()

    fun CreateTable()
    {
        val temps=controller?.getTemps()
        val rowHead = LayoutInflater.from(context).inflate(R.layout.attrib_row, null) as TableRow
        (rowHead.findViewById<View>(R.id.attrib_name) as TextView).text=("time")
        (rowHead.findViewById<View>(R.id.attrib_value) as TextView).text=("Value")
        table!!.addView(rowHead)
        for (i in 0 until temps!!.size) {
    
            val row = LayoutInflater.from(context).inflate(R.layout.attrib_row, null) as TableRow
            (row.findViewById<View>(R.id.attrib_name) as TextView).text=((i+1).toString())
            (row.findViewById<View>(R.id.attrib_value) as TextView).text=(temps[i].toString())
            table!!.addView(row)
        }
        table!!.requestLayout()
    }
    

    and you can use it in your fragment for example like this

       override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
            table = view?.findViewById<View>(R.id.simpleTableLayout) as TableLayout
            CreateTable()
        }
    

    the final result looks like this enter image description here

    How do I import a Swift file from another Swift file?

    According To Apple you don't need an import for swift files in the Same Target. I finally got it working by adding my swift file to both my regular target and test target. Then I used the bridging header for test to make sure my ObjC files that I referenced in my regular bridging header were available. Ran like a charm now.

    import XCTest
    //Optionally you can import the whole Objc Module by doing #import ModuleName
    
    class HHASettings_Tests: XCTestCase {
    
    override func setUp() {
        let x : SettingsTableViewController = SettingsTableViewController()
    
        super.setUp()
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }
    
    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
        super.tearDown()
    }
    
    func testExample() {
        // This is an example of a functional test case.
        XCTAssert(true, "Pass")
    }
    
    func testPerformanceExample() {
        // This is an example of a performance test case.
        self.measureBlock() {
            // Put the code you want to measure the time of here.
        }
    }
    
    }
    

    SO make sure PrimeNumberModel has a target of your test Target. Or High6 solution of importing your whole module will work

    Pod install is staying on "Setting up CocoaPods Master repo"

    Try this command to track its work.

    while true; do
      du -sh ~/.cocoapods/
      sleep 3
    done
    

    Convert int to a bit array in .NET

    I would achieve it in a one-liner as shown below:

    using System;
    using System.Collections;
    
    namespace stackoverflowQuestions
    {
        class Program
        {
            static void Main(string[] args)
            {    
                //get bit Array for number 20
                var myBitArray = new BitArray(BitConverter.GetBytes(20));
            }
        }
    }
    

    Please note that every element of a BitArray is stored as bool as shown in below snapshot:

    enter image description here

    So below code works:

    if (myBitArray[0] == false)
    {
        //this code block will execute
    }
    

    but below code doesn't compile at all:

    if (myBitArray[0] == 0)
    {
        //some code
    }
    

    How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

    Expanding on Dominic Tancredi's awesome answer, I've rolled this into a bash package and stand-alone script. If you are already using the "Back Package Manager" called bpkg you can install the script by running:

    bpkg install -g brock/node-reinstall
    

    Or you can have a look at the script on Github at brock/node-reinstall. The script allows you to re-install node using nvm or nave, and to specify a node version as your default.

    How to give a pandas/matplotlib bar graph custom colors

    You can specify the color option as a list directly to the plot function.

    from matplotlib import pyplot as plt
    from itertools import cycle, islice
    import pandas, numpy as np  # I find np.random.randint to be better
    
    # Make the data
    x = [{i:np.random.randint(1,5)} for i in range(10)]
    df = pandas.DataFrame(x)
    
    # Make a list by cycling through the colors you care about
    # to match the length of your data.
    my_colors = list(islice(cycle(['b', 'r', 'g', 'y', 'k']), None, len(df)))
    
    # Specify this list of colors as the `color` option to `plot`.
    df.plot(kind='bar', stacked=True, color=my_colors)
    

    To define your own custom list, you can do a few of the following, or just look up the Matplotlib techniques for defining a color item by its RGB values, etc. You can get as complicated as you want with this.

    my_colors = ['g', 'b']*5 # <-- this concatenates the list to itself 5 times.
    my_colors = [(0.5,0.4,0.5), (0.75, 0.75, 0.25)]*5 # <-- make two custom RGBs and repeat/alternate them over all the bar elements.
    my_colors = [(x/10.0, x/20.0, 0.75) for x in range(len(df))] # <-- Quick gradient example along the Red/Green dimensions.
    

    The last example yields the follow simple gradient of colors for me:

    enter image description here

    I didn't play with it long enough to figure out how to force the legend to pick up the defined colors, but I'm sure you can do it.

    In general, though, a big piece of advice is to just use the functions from Matplotlib directly. Calling them from Pandas is OK, but I find you get better options and performance calling them straight from Matplotlib.

    AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

    I had similar issue just that excel was the destination in my case instead of source as in the case of the original question/issue. I have spent hours to resolve this issue but looks like finally Soniya Parmar saved the day for me. I have set job and let it run for few iterations already and all is good now. As per her suggestion I set up the delay validation of the Excel connection manager to 'True. Thanks Soniya

    Read a text file using Node.js?

    The async way of life:

    #! /usr/bin/node
    
    const fs = require('fs');
    
    function readall (stream)
    {
      return new Promise ((resolve, reject) => {
        const chunks = [];
        stream.on ('error', (error) => reject (error));
        stream.on ('data',  (chunk) => chunk && chunks.push (chunk));
        stream.on ('end',   ()      => resolve (Buffer.concat (chunks)));
      });
    }
    
    function readfile (filename)
    {
      return readall (fs.createReadStream (filename));
    }
    
    (async () => {
      let content = await readfile ('/etc/ssh/moduli').catch ((e) => {})
      if (content)
        console.log ("size:", content.length,
                     "head:", content.slice (0, 46).toString ());
    })();
    

    Double quotes within php script echo

    if you need to access your variables for an echo statement within your quotes put your variable inside curly brackets

    echo "i need to open my lock with its: {$array['key']}";
    

    make iframe height dynamic based on content inside- JQUERY/Javascript

    jQuery('.home_vidio_img1 img').click(function(){
        video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
        jQuery(this).replaceWith(video);
    });
    
    jQuery('.home_vidio_img2 img').click(function(){
        video = <iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>;
        jQuery('.home_vidio_img1 img').replaceWith(video);
        jQuery('.home_vidio_img1 iframe').replaceWith(video);
    });
    
    jQuery('.home_vidio_img3 img').click(function(){
        video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
        jQuery('.home_vidio_img1 img').replaceWith(video);
        jQuery('.home_vidio_img1 iframe').replaceWith(video);
    });
    
    jQuery('.home_vidio_img4 img').click(function(){
        video = '<iframe src="'+ jQuery(this).attr('data-video') +'"></iframe>';
        jQuery('.home_vidio_img1 img').replaceWith(video);
        jQuery('.home_vidio_img1 iframe').replaceWith(video);
    });
    

    Vue.js - How to properly watch for nested data

    Personally I prefer this clean implementation:

    watch: {
      myVariable: {
         handler(newVal, oldVal){  // here having access to the new and old value
           // do stuff
         },
         deep: true,
         immediate: true //  Also very important the immediate in case you need it, the callback will be called immediately after the start of the observation
    
      }
    }
    

    How do I use 'git reset --hard HEAD' to revert to a previous commit?

    WARNING: git clean -f will remove untracked files, meaning they're gone for good since they aren't stored in the repository. Make sure you really want to remove all untracked files before doing this.


    Try this and see git clean -f.

    git reset --hard will not remove untracked files, where as git-clean will remove any files from the tracked root directory that are not under Git tracking.

    Alternatively, as @Paul Betts said, you can do this (beware though - that removes all ignored files too)

    • git clean -df
    • git clean -xdf CAUTION! This will also delete ignored files

    Simple example for Intent and Bundle

    Basically this is what you need to do:
    in the first activity:

    Intent intent = new Intent();
    intent.setAction(this, SecondActivity.class);
    intent.putExtra(tag, value);
    startActivity(intent);
    

    and in the second activtiy:

    Intent intent = getIntent();
    intent.getBooleanExtra(tag, defaultValue);
    intent.getStringExtra(tag, defaultValue);
    intent.getIntegerExtra(tag, defaultValue);
    

    one of the get-functions will give return you the value, depending on the datatype you are passing through.

    C++ pass an array by reference

    Here, Erik explains every way pass an array by reference: https://stackoverflow.com/a/5724184/5090928.

    Similarly, you can create an array reference variable like so:

    int arr1[] = {1, 2, 3, 4, 5};
    int(&arr2)[5] = arr1;
    

    How to change font-color for disabled input?

    It is the solution that I found for this problem:

    //If IE

    inputElement.writeAttribute("unselectable", "on");

    //Other browsers

    inputElement.writeAttribute("disabled", "disabled");

    By using this trick, you can add style sheet to your input element that works in IE and other browsers on your not-editable input box.

    Make DateTimePicker work as TimePicker only in WinForms

    ...or alternatively if you only want to show a portion of the time value use "Custom":

    timePicker = new DateTimePicker();
    timePicker.Format = DateTimePickerFormat.Custom;
    timePicker.CustomFormat = "HH:mm"; // Only use hours and minutes
    timePicker.ShowUpDown = true;
    

    Why is Java Vector (and Stack) class considered obsolete or deprecated?

    Vector synchronizes on each individual operation. That's almost never what you want to do.

    Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time, which would cause a ConcurrentModificationException in the iterating thread) but also slower (why take out a lock repeatedly when once will be enough)?

    Of course, it also has the overhead of locking even when you don't need to.

    Basically, it's a very flawed approach to synchronization in most situations. As Mr Brian Henk pointed out, you can decorate a collection using the calls such as Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns.

    As for a Stack equivalent - I'd look at Deque/ArrayDeque to start with.

    Object reference not set to an instance of an object.

    I want to extend MattMitchell's answer by saying you can create an extension method for this functionality:

    public static IsEmptyOrWhitespace(this string value) {
        return String.IsEmptyOrWhitespace(value);
    }
    

    This makes it possible to call:

    string strValue;
    if (strValue.IsEmptyOrWhitespace())
         // do stuff
    

    To me this is a lot cleaner than calling the static String function, while still being NullReference safe!

    Is there a CSS parent selector?

    There is currently no way to select the parent of an element in CSS.

    If there was a way to do it, it would be in either of the current CSS selectors specs:

    That said, the Selectors Level 4 Working Draft includes a :has() pseudo-class that will provide this capability. It will be similar to the jQuery implementation.

    li:has(> a.active) { /* styles to apply to the li tag */ }
    

    However, as of 2020, this is still not supported by any browser.

    In the meantime, you'll have to resort to JavaScript if you need to select a parent element.

    python: NameError:global name '...‘ is not defined

    You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

    You may want to read through the Python tutorial on classes some more to get the finer details down.

    How do I use the includes method in lodash to check if an object is in the collection?

    You could use find to solve your problem

    https://lodash.com/docs/#find

    const data = [{"a": 1}, {"b": 2}]
    const item = {"b": 2}
    
    
    find(data, item)
    // > true
    
    

    How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

    Most of the above answers makes perfect sense. Since you are seeing data being formatted in XML format ,that means XML formatter is applied,SO you can see JSON format just by removing the XMLFormatter from the HttpConfiguration parameter like

    public static void Register(HttpConfiguration config)
            {
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );                
                config.Formatters.Remove(config.Formatters.XmlFormatter);                
                config.EnableSystemDiagnosticsTracing();
            }
    

    since JSON is the default format

    Code to loop through all records in MS Access

    In "References", import DAO 3.6 object reference.

    private sub showTableData
    
    dim db as dao.database
    dim rs as dao.recordset
    
    set db = currentDb
    set rs = db.OpenRecordSet("myTable") 'myTable is a MS-Access table created previously
    
    'populate the table
    rs.movelast
    rs.movefirst
    
    do while not rs.EOF
       debug.print(rs!myField) 'myField is a field name in table myTable
       rs.movenext             'press Ctrl+G to see debuG window beneath
    loop
    
    msgbox("End of Table")
    
    end sub
    

    You can interate data objects like queries and filtered tables in different ways:

    Trhough query:

    private sub showQueryData
    
    dim db as dao.database
    dim rs as dao.recordset
    dim sqlStr as string
    
    sqlStr = "SELECT * FROM customers as c WHERE c.country='Brazil'"
    
    set db = currentDb
    set rs = db.openRecordset(sqlStr)
    
    rs.movefirst
    
    do while not rs.EOF
      debug.print("cust ID: " & rs!id & " cust name: " & rs!name)
      rs.movenext
    loop
    
    msgbox("End of customers from Brazil")
    
    end sub
    

    You should also look for "Filter" property of the recordset object to filter only the desired records and then interact with them in the same way (see VB6 Help in MS-Access code window), or create a "QueryDef" object to run a query and use it as a recordset too (a little bit more tricky). Tell me if you want another aproach.

    I hope I've helped.

    Algorithm to return all combinations of k elements from n

    I have written a class to handle common functions for working with the binomial coefficient, which is the type of problem that your problem falls under. It performs the following tasks:

    1. Outputs all the K-indexes in a nice format for any N choose K to a file. The K-indexes can be substituted with more descriptive strings or letters. This method makes solving this type of problem quite trivial.

    2. Converts the K-indexes to the proper index of an entry in the sorted binomial coefficient table. This technique is much faster than older published techniques that rely on iteration. It does this by using a mathematical property inherent in Pascal's Triangle. My paper talks about this. I believe I am the first to discover and publish this technique, but I could be wrong.

    3. Converts the index in a sorted binomial coefficient table to the corresponding K-indexes.

    4. Uses Mark Dominus method to calculate the binomial coefficient, which is much less likely to overflow and works with larger numbers.

    5. The class is written in .NET C# and provides a way to manage the objects related to the problem (if any) by using a generic list. The constructor of this class takes a bool value called InitTable that when true will create a generic list to hold the objects to be managed. If this value is false, then it will not create the table. The table does not need to be created in order to perform the 4 above methods. Accessor methods are provided to access the table.

    6. There is an associated test class which shows how to use the class and its methods. It has been extensively tested with 2 cases and there are no known bugs.

    To read about this class and download the code, see Tablizing The Binomial Coeffieicent.

    It should not be hard to convert this class to C++.

    Current user in Magento?

    Simply,

    $current_customer = $this->_getSession()->getCustomer();
    

    This returns the customer object, then you can get all the details from this customer object.

    Escaping a forward slash in a regular expression

    Here are a few options:

    • In Perl, you can choose alternate delimiters. You're not confined to m//. You could choose another, such as m{}. Then escaping isn't necessary. As a matter of fact, Damian Conway in "Perl Best Practices" asserts that m{} is the only alternate delimiter that ought to be used, and this is reinforced by Perl::Critic (on CPAN). While you can get away with using a variety of alternate delimiter characters, // and {} seem to be the clearest to decipher later on. However, if either of those choices result in too much escaping, choose whichever one lends itself best to legibility. Common examples are m(...), m[...], and m!...!.

    • In cases where you either cannot or prefer not to use alternate delimiters, you can escape the forward slashes with a backslash: m/\/[^/]+$/ for example (using an alternate delimiter that could become m{/[^/]+$}, which may read more clearly). Escaping the slash with a backslash is common enough to have earned a name and a wikipedia page: Leaning Toothpick Syndrome. In regular expressions where there's just a single instance, escaping a slash might not rise to the level of being considered a hindrance to legibility, but if it starts to get out of hand, and if your language permits alternate delimiters as Perl does, that would be the preferred solution.

    Removing unwanted table cell borders with CSS

    to remove the border , juste using css like this :

    td {
     border-style : hidden!important;
    }
    

    Create Test Class in IntelliJ

    I can see some people have asked, so on OSX you can still go to navigate->test or use cmd+shift+T

    Remember you have to be focused in the class for this to work

    Get page title with Selenium WebDriver using Java

    You can do it easily by using JUnit or TestNG framework. Do the assertion as below:

    String actualTitle = driver.getTitle();
    String expectedTitle = "Title of Page";
    assertEquals(expectedTitle,actualTitle);
    

    OR,

    assertTrue(driver.getTitle().contains("Title of Page"));
    

    Correct way to push into state array

    Here you can not push the object to a state array like this. You can push like your way in normal array. Here you have to set the state,

    this.setState({ 
         myArray: [...this.state.myArray, 'new value'] 
    })
    

    Precision String Format Specifier In Swift

    //It will more help, by specify how much decimal Point you want.
    let decimalPoint = 2
    let floatAmount = 1.10001
    let amountValue = String(format: "%0.*f", decimalPoint, floatAmount)
    

    Sort collection by multiple fields in Kotlin

    sortedWith + compareBy (taking a vararg of lambdas) do the trick:

    val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))
    

    You can also use the somewhat more succinct callable reference syntax:

    val sortedList = list.sortedWith(compareBy(Person::age, Person::name))
    

    How to merge two arrays of objects by ID using lodash?

    If both arrays are in the correct order; where each item corresponds to its associated member identifier then you can simply use.

    var merge = _.merge(arr1, arr2);
    

    Which is the short version of:

    var merge = _.chain(arr1).zip(arr2).map(function(item) {
        return _.merge.apply(null, item);
    }).value();
    

    Or, if the data in the arrays is not in any particular order, you can look up the associated item by the member value.

    var merge = _.map(arr1, function(item) {
        return _.merge(item, _.find(arr2, { 'member' : item.member }));
    });
    

    You can easily convert this to a mixin. See the example below:

    _x000D_
    _x000D_
    _.mixin({_x000D_
      'mergeByKey' : function(arr1, arr2, key) {_x000D_
        var criteria = {};_x000D_
        criteria[key] = null;_x000D_
        return _.map(arr1, function(item) {_x000D_
          criteria[key] = item[key];_x000D_
          return _.merge(item, _.find(arr2, criteria));_x000D_
        });_x000D_
      }_x000D_
    });_x000D_
    _x000D_
    var arr1 = [{_x000D_
      "member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
      "bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
      "country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
    }, {_x000D_
      "member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
      "bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
      "country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
    }];_x000D_
    _x000D_
    var arr2 = [{_x000D_
      "member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
      "name": 'yyyyyyyyyy',_x000D_
      "age": 26_x000D_
    }, {_x000D_
      "member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
      "name": 'xxxxxx',_x000D_
      "age": 25_x000D_
    }];_x000D_
    _x000D_
    var arr3 = _.mergeByKey(arr1, arr2, 'member');_x000D_
    _x000D_
    document.body.innerHTML = JSON.stringify(arr3, null, 4);
    _x000D_
    body { font-family: monospace; white-space: pre; }
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
    _x000D_
    _x000D_
    _x000D_

    Adding a new entry to the PATH variable in ZSH

    Actually, using ZSH allows you to use special mapping of environment variables. So you can simply do:

    # append
    path+=('/home/david/pear/bin')
    # or prepend
    path=('/home/david/pear/bin' $path)
    # export to sub-processes (make it inherited by child processes)
    export PATH
    

    For me that's a very neat feature which can be propagated to other variables. Example:

    typeset -T LD_LIBRARY_PATH ld_library_path :
    

    Capitalize or change case of an NSString in Objective-C

    Here ya go:

    viewNoteDateMonth.text  = [[displayDate objectAtIndex:2] uppercaseString];
    

    Btw:
    "april" is lowercase ? [NSString lowercaseString]
    "APRIL" is UPPERCASE ? [NSString uppercaseString]
    "April May" is Capitalized/Word Caps ? [NSString capitalizedString]
    "April may" is Sentence caps ? (method missing; see workaround below)

    Hence what you want is called "uppercase", not "capitalized". ;)

    As for "Sentence Caps" one has to keep in mind that usually "Sentence" means "entire string". If you wish for real sentences use the second method, below, otherwise the first:

    @interface NSString ()
    
    - (NSString *)sentenceCapitalizedString; // sentence == entire string
    - (NSString *)realSentenceCapitalizedString; // sentence == real sentences
    
    @end
    
    @implementation NSString
    
    - (NSString *)sentenceCapitalizedString {
        if (![self length]) {
            return [NSString string];
        }
        NSString *uppercase = [[self substringToIndex:1] uppercaseString];
        NSString *lowercase = [[self substringFromIndex:1] lowercaseString];
        return [uppercase stringByAppendingString:lowercase];
    }
    
    - (NSString *)realSentenceCapitalizedString {
        __block NSMutableString *mutableSelf = [NSMutableString stringWithString:self];
        [self enumerateSubstringsInRange:NSMakeRange(0, [self length])
                                 options:NSStringEnumerationBySentences
                              usingBlock:^(NSString *sentence, NSRange sentenceRange, NSRange enclosingRange, BOOL *stop) {
            [mutableSelf replaceCharactersInRange:sentenceRange withString:[sentence sentenceCapitalizedString]];
        }];
        return [NSString stringWithString:mutableSelf]; // or just return mutableSelf.
    }
    
    @end
    

    python pip - install from local dir

    You were looking for help on installations with pip. You can find it with the following command:

    pip install --help
    

    Running pip install -e /path/to/package installs the package in a way, that you can edit the package, and when a new import call looks for it, it will import the edited package code. This can be very useful for package development.

    How to use <md-icon> in Angular Material?

    md-icons aren't in the bower release of angular-material yet. I've been using Polymer's icons, they'll probably be the same anyway.

    bower install polymer/core-icons
    

    What is the difference between Nexus and Maven?

    Whatever I understood from my learning and what I think it is is here. I am Quoting some part from a book i learnt this things. Nexus Repository Manager and Nexus Repository Manager OSS started as a repository manager supporting the Maven repository format. While it supports many other repository formats now, the Maven repository format is still the most common and well supported format for build and provisioning tools running on the JVM and beyond. This chapter shows example configurations for using the repository manager with Apache Maven and a number of other tools. The setups take advantage of merging many repositories and exposing them via a repository group. Setting this up is documented in the chapter in addition to the configuration used by specific tools.

    Details

    Return value using String result=Command.ExecuteScalar() error occurs when result returns null

    try this :

     string getValue = Convert.ToString(cmd.ExecuteScalar());
    

    duplicate 'row.names' are not allowed error

    Then tell read.table not to use row.names:

    systems <- read.table("http://getfile.pl?test.csv", 
                          header=TRUE, sep=",", row.names=NULL)
    

    and now your rows will simply be numbered.

    Also look at read.csv which is a wrapper for read.table which already sets the sep=',' and header=TRUE arguments so that your call simplifies to

    systems <- read.csv("http://getfile.pl?test.csv", row.names=NULL)
    

    How to change progress bar's progress color in Android

    I'm sorry that it's not the answer, but what's driving the requirement setting it from code ? And .setProgressDrawable should work if it's defined correctly

    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    
    <item android:id="@android:id/background">
        <shape>
            <corners android:radius="5dip" />
            <gradient
                    android:startColor="#ff9d9e9d"
                    android:centerColor="#ff5a5d5a"
                    android:centerY="0.75"
                    android:endColor="#ff747674"
                    android:angle="270"
            />
        </shape>
    </item>
    
    <item android:id="@android:id/secondaryProgress">
        <clip>
            <shape>
                <corners android:radius="5dip" />
                <gradient
                        android:startColor="#80ffd300"
                        android:centerColor="#80ffb600"
                        android:centerY="0.75"
                        android:endColor="#a0ffcb00"
                        android:angle="270"
                />
            </shape>
        </clip>
    </item>
    
    <item android:id="@android:id/progress">
        <clip>
            <shape>
                <corners
                    android:radius="5dip" />
                <gradient
                    android:startColor="@color/progress_start"
                    android:endColor="@color/progress_end"
                    android:angle="270" 
                />
            </shape>
        </clip>
    </item>
    
    </layer-list>
    

    Can I access a form in the controller?

    You can attach the form to some object which is defined in a parent controller. Then you can reach your form even from a child scope.

    Parent controller

    $scope.forms = {};
    

    Some template in a child scope

    <form name="forms.form1">
    </form>
    

    Problem is that the form doesn't have to be defined in the moment when to code in the controller is executed. So you have to do something like this

    $scope.$watch('forms.form1', function(form) {
      if(form) {
        // your code...
      }
    });
    

    Why number 9 in kill -9 command in unix?

    Both are same as kill -sigkill processID, kill -9 processID. Its basically for forced termination of the process.

    Opening Chrome From Command Line

    Have a look into the start command. It should do what you're trying to achieve.

    Also, you might be able to leave out path to chrome. The following works on Windows 7:

    start chrome "site1.com" "site2.com"

    Show two digits after decimal point in c++

    cout << fixed << setprecision(2) << total;
    

    setprecision specifies the minimum precision. So

    cout << setprecision (2) << 1.2; 
    

    will print 1.2

    fixed says that there will be a fixed number of decimal digits after the decimal point

    cout << setprecision (2) << fixed << 1.2;
    

    will print 1.20

    Change Input to Upper Case

    try:

    $('#search input.keywords').bind('change', function(){
        //this.value.toUpperCase();
        //EDIT: As  Mike Samuel suggested, this will be more appropriate for the job
        this.value = this.value.toLocaleUpperCase();
    } );
    

    What's the -practical- difference between a Bare and non-Bare repository?

    This is not a new answer, but it helped me to understand the different aspects of the answers above (and it is too much for a comment).

    Using Git Bash just try:

    me@pc MINGW64 /c/Test
    $ ls -al
    total 16
    drwxr-xr-x 1 myid 1049089 0 Apr  1 11:35 ./
    drwxr-xr-x 1 myid 1049089 0 Apr  1 11:11 ../
    
    me@pc MINGW64 /c/Test
    $ git init
    Initialized empty Git repository in C:/Test/.git/
    
    me@pc MINGW64 /c/Test (master)
    $ ls -al
    total 20
    drwxr-xr-x 1 myid 1049089 0 Apr  1 11:35 ./
    drwxr-xr-x 1 myid 1049089 0 Apr  1 11:11 ../
    drwxr-xr-x 1 myid 1049089 0 Apr  1 11:35 .git/
    
    me@pc MINGW64 /c/Test (master)
    $ cd .git
    
    me@pc MINGW64 /c/Test/.git (GIT_DIR!)
    $ ls -al
    total 15
    drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 ./
    drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 ../
    -rw-r--r-- 1 myid 1049089 130 Apr  1 11:35 config
    -rw-r--r-- 1 myid 1049089  73 Apr  1 11:35 description
    -rw-r--r-- 1 myid 1049089  23 Apr  1 11:35 HEAD
    drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 hooks/
    drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 info/
    drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 objects/
    drwxr-xr-x 1 myid 1049089   0 Apr  1 11:35 refs/
    

    Same with git --bare:

    me@pc MINGW64 /c/Test
    $ ls -al
    total 16
    drwxr-xr-x 1 myid 1049089 0 Apr  1 11:36 ./
    drwxr-xr-x 1 myid 1049089 0 Apr  1 11:11 ../
    
    me@pc MINGW64 /c/Test
    $ git init --bare
    Initialized empty Git repository in C:/Test/
    
    me@pc MINGW64 /c/Test (BARE:master)
    $ ls -al
    total 23
    drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 ./
    drwxr-xr-x 1 myid 1049089   0 Apr  1 11:11 ../
    -rw-r--r-- 1 myid 1049089 104 Apr  1 11:36 config
    -rw-r--r-- 1 myid 1049089  73 Apr  1 11:36 description
    -rw-r--r-- 1 myid 1049089  23 Apr  1 11:36 HEAD
    drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 hooks/
    drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 info/
    drwxr-xr-x 1 myid 1049089   0 Apr  1 11:36 objects/
    

    Why is my xlabel cut off in my matplotlib plot?

    for some reason sharex was set to True so I turned it back to False and it worked fine.

    df.plot(........,sharex=False)
    

    PHP code to convert a MySQL query to CSV

    If you'd like the download to be offered as a download that can be opened directly in Excel, this may work for you: (copied from an old unreleased project of mine)

    These functions setup the headers:

    function setExcelContentType() {
        if(headers_sent())
            return false;
    
        header('Content-type: application/vnd.ms-excel');
        return true;
    }
    
    function setDownloadAsHeader($filename) {
        if(headers_sent())
            return false;
    
        header('Content-disposition: attachment; filename=' . $filename);
        return true;
    }
    

    This one sends a CSV to a stream using a mysql result

    function csvFromResult($stream, $result, $showColumnHeaders = true) {
        if($showColumnHeaders) {
            $columnHeaders = array();
            $nfields = mysql_num_fields($result);
            for($i = 0; $i < $nfields; $i++) {
                $field = mysql_fetch_field($result, $i);
                $columnHeaders[] = $field->name;
            }
            fputcsv($stream, $columnHeaders);
        }
    
        $nrows = 0;
        while($row = mysql_fetch_row($result)) {
            fputcsv($stream, $row);
            $nrows++;
        }
    
        return $nrows;
    }
    

    This one uses the above function to write a CSV to a file, given by $filename

    function csvFileFromResult($filename, $result, $showColumnHeaders = true) {
        $fp = fopen($filename, 'w');
        $rc = csvFromResult($fp, $result, $showColumnHeaders);
        fclose($fp);
        return $rc;
    }
    

    And this is where the magic happens ;)

    function csvToExcelDownloadFromResult($result, $showColumnHeaders = true, $asFilename = 'data.csv') {
        setExcelContentType();
        setDownloadAsHeader($asFilename);
        return csvFileFromResult('php://output', $result, $showColumnHeaders);
    }
    

    For example:

    $result = mysql_query("SELECT foo, bar, shazbot FROM baz WHERE boo = 'foo'");
    csvToExcelDownloadFromResult($result);
    

    How to format a float in javascript?

    There is a problem with all those solutions floating around using multipliers. Both kkyy and Christoph's solutions are wrong unfortunately.

    Please test your code for number 551.175 with 2 decimal places - it will round to 551.17 while it should be 551.18 ! But if you test for ex. 451.175 it will be ok - 451.18. So it's difficult to spot this error at a first glance.

    The problem is with multiplying: try 551.175 * 100 = 55117.49999999999 (ups!)

    So my idea is to treat it with toFixed() before using Math.round();

    function roundFix(number, precision)
    {
        var multi = Math.pow(10, precision);
        return Math.round( (number * multi).toFixed(precision + 1) ) / multi;
    }
    

    "Object doesn't support property or method 'find'" in IE

    As mentioned array.find() is not supported in IE.

    However you can read about a Polyfill here:

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

    This method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations yet. However, you can polyfill Array.prototype.find with the following snippet:

    Code:

    // https://tc39.github.io/ecma262/#sec-array.prototype.find
    if (!Array.prototype.find) {
      Object.defineProperty(Array.prototype, 'find', {
        value: function(predicate) {
         // 1. Let O be ? ToObject(this value).
          if (this == null) {
            throw new TypeError('"this" is null or not defined');
          }
    
          var o = Object(this);
    
          // 2. Let len be ? ToLength(? Get(O, "length")).
          var len = o.length >>> 0;
    
          // 3. If IsCallable(predicate) is false, throw a TypeError exception.
          if (typeof predicate !== 'function') {
            throw new TypeError('predicate must be a function');
          }
    
          // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
          var thisArg = arguments[1];
    
          // 5. Let k be 0.
          var k = 0;
    
          // 6. Repeat, while k < len
          while (k < len) {
            // a. Let Pk be ! ToString(k).
            // b. Let kValue be ? Get(O, Pk).
            // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
            // d. If testResult is true, return kValue.
            var kValue = o[k];
            if (predicate.call(thisArg, kValue, k, o)) {
              return kValue;
            }
            // e. Increase k by 1.
            k++;
          }
    
          // 7. Return undefined.
          return undefined;
        }
      });
    }
    

    How can I switch themes in Visual Studio 2012

    Tools -> Options ->Environment -> General

    Or use new Quick Launch to open Options Use Quick Launch to open Options

    enter image description here

    For more themes, download Microsoft Visual Studio 2012 Color Theme Editor for more themes including good old VS2010 theme.

    Look at this video for a demo.

    How to make the 'cut' command treat same sequental delimiters as one?

    Try:

    tr -s ' ' <text.txt | cut -d ' ' -f4
    

    From the tr man page:

    -s, --squeeze-repeats   replace each input sequence of a repeated character
                            that is listed in SET1 with a single occurrence
                            of that character
    

    Progress Bar with HTML and CSS

    Create an element which shows the left part of the bar (the round part), also create an element for the right part. For the actual progress bar, create a third element with a repeating background and a width which depends on the actual progress. Put it all on top of the background image (containing the empty progress bar).

    But I suppose you already knew that...

    Edit: When creating a progress bar which do not use textual backgrounds. You can use the border-radius to get the round effect, as shown by Rikudo Sennin and RoToRa!

    java.lang.RuntimeException: Unable to start activity ComponentInfo

    It was my own stupidity:

    java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
    

    Putting this inside onCreate() method fixed my problem.

    What data type to use for hashed password field and what length?

    You might find this Wikipedia article on salting worthwhile. The idea is to add a set bit of data to randomize your hash value; this will protect your passwords from dictionary attacks if someone gets unauthorized access to the password hashes.

    How to use 'find' to search for files created on a specific date?

    @Max: is right about the creation time.

    However, if you want to calculate the elapsed days argument for one of the -atime, -ctime, -mtime parameters, you can use the following expression

    ELAPSED_DAYS=$(( ( $(date +%s) - $(date -d '2008-09-24' +%s) ) / 60 / 60 / 24 - 1 ))
    

    Replace "2008-09-24" with whatever date you want and ELAPSED_DAYS will be set to the number of days between then and today. (Update: subtract one from the result to align with find's date rounding.)

    So, to find any file modified on September 24th, 2008, the command would be:

    find . -type f -mtime $(( ( $(date +%s) - $(date -d '2008-09-24' +%s) ) / 60 / 60 / 24 - 1 ))
    

    This will work if your version of find doesn't support the -newerXY predicates mentioned in @Arve:'s answer.

    Could not load file or assembly Exception from HRESULT: 0x80131040

    Finally found the answer!! Go to References --> right cilck on dll file that causing the problem --> select the properties --> check the version --> match the version in properties to web config

    <dependentAssembly>
        <assemblyIdentity name="YourDllFile" publicKeyToken="2780ccd10d57b246"               culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-YourDllFileVersion" newVersion="YourDllFileVersion" />
      </dependentAssembly>
    

    vertical & horizontal lines in matplotlib

    The pyplot functions you are calling, axhline() and axvline() draw lines that span a portion of the axis range, regardless of coordinates. The parameters xmin or ymin use value 0.0 as the minimum of the axis and 1.0 as the maximum of the axis.

    Instead, use plt.plot((x1, x2), (y1, y2), 'k-') to draw a line from the point (x1, y1) to the point (x2, y2) in color k. See pyplot.plot.

    Function inside a function.?

    (4+3)*(4*2) == 56
    

    Note that PHP doesn't really support "nested functions", as in defined only in the scope of the parent function. All functions are defined globally. See the docs.

    How to convert "0" and "1" to false and true

    My solution (vb.net):

    Private Function ConvertToBoolean(p1 As Object) As Boolean
        If p1 Is Nothing Then Return False
        If IsDBNull(p1) Then Return False
        If p1.ToString = "1" Then Return True
        If p1.ToString.ToLower = "true" Then Return True
        Return False
    End Function
    

    Code snippet or shortcut to create a constructor in Visual Studio

    In Visual Studio 2010, if you type "ctor" (without the quotes), IntelliSense should load, showing you "ctor" in the list. Now press TAB twice, and you should have generated an empty constructor.

    Running MSBuild fails to read SDKToolsPath

    I had a similar issue, notably msbuild fails: MSB3086, MSB3091: "AL.exe", "resgen.exe" not found

    On a 64 bits Windows 7 machine, I installed .Net framework 4.5.1 and Windows SDK for Windows 8.1.

    Although the setups for the SDK sayd that it was up to date, probably it was not. I solved the issue by removing all installed versions of SDK, then installing the following, in this order:

    http://www.microsoft.com/en-us/download/details.aspx?id=3138

    http://www.microsoft.com/en-us/download/details.aspx?id=8279

    http://msdn.microsoft.com/en-us/windows/desktop/hh852363.aspx

    http://msdn.microsoft.com/en-us/windows/desktop/aa904949.aspx

    Java 6 Unsupported major.minor version 51.0

    The problem is because you haven't set JDK version properly.You should use jdk 7 for major number 51. Like this:

    JAVA_HOME=/usr/java/jdk1.7.0_79

    Find an element in DOM based on an attribute value

    Here is an example , How to search images in a document by src attribute :

    document.querySelectorAll("img[src='https://pbs.twimg.com/profile_images/........jpg']");
    

    word-wrap break-word does not work in this example

    Use this code (taken from css-tricks) that will work on all browser

    overflow-wrap: break-word;
    word-wrap: break-word;
    
    -ms-word-break: break-all;
    /* This is the dangerous one in WebKit, as it breaks things wherever */
    word-break: break-all;
    /* Instead use this non-standard one: */
    word-break: break-word;
    
    /* Adds a hyphen where the word breaks, if supported (No Blink) */
    -ms-hyphens: auto;
    -moz-hyphens: auto;
    -webkit-hyphens: auto;
    hyphens: auto;
    

    Best way to convert pdf files to tiff files

    Maybe also try this? PDF Focus

    This .Net library allows you to solve the problem :)

    This code will help (Convert 1000 PDF files to 300-dpi TIFF files in C#):

        SautinSoft.PdfFocus f = new SautinSoft.PdfFocus();
    
        string[] pdfFiles = Directory.GetFiles(@"d:\Folder with 1000 pdfs\", "*.pdf");
        string folderWithTiffs = @"d:\Folder with TIFFs\";
    
        foreach (string pdffile in pdfFiles)
        {
            f.OpenPdf(pdffile);
    
            if (f.PageCount > 0)
            {
                //save all pages to tiff files with 300 dpi
                f.ToImage(folderWithTiffs, Path.GetFileNameWithoutExtension(pdffile), System.Drawing.Imaging.ImageFormat.Tiff, 300);
            }
            f.ClosePdf();
        }
    

    The simplest way to comma-delimit a list?

    public static String join (List<String> list, String separator) {
      String listToString = "";
    
      if (list == null || list.isEmpty()) {
       return listToString;
      }
    
      for (String element : list) {
       listToString += element + separator;
      }
    
      listToString = listToString.substring(0, separator.length());
    
      return listToString;
    }
    

    WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."

    None of the above answers worked for me, or where unsafe (as some pointed out, using Allow from all can make your files and data accessible to the outside world).

    Open the c:\wamp\alias\phpmyadmin.conf file and change

    Allow from 127.0.0.1
    

    to

    Allow from 127.0.0.1  ::1
    

    Explanation:

    • On most computer systems, localhost resolves to the IP address 127.0.0.1, which is the most commonly used IPv4 loopback address, and to the IPv6 loopback address ::1 (source: https://en.wikipedia.org/wiki/Localhost)
    • The resolution of the name localhost into one or more IP addresses is configured by the following lines in the operating system's hosts file:

      127.0.0.1    localhost
      ::1          localhost
      
    • to see your hosts file, go to c:\Windows\System32\drivers\etc\HOSTS

    • notice the above lines are commented out with the note: # localhost name resolution is handled within DNS itself.

    On my machine, on Win7, I also noticed the following:

    • localhost\phpmyadmin did not work on Chrome, but worked on IE11
    • 127.0.0.1\phpmyadmin worked on Chrome

    What is the difference between display: inline and display: inline-block?

    One thing not mentioned in answers is inline element can break among lines while inline-block can't (and obviously block)! So inline elements can be useful to style sentences of text and blocks inside them, but as they can't be padded you can use line-height instead.

    _x000D_
    _x000D_
    <div style="width: 350px">_x000D_
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
      <div style="display: inline; background: #F00; color: #FFF">_x000D_
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
      </div>_x000D_
      Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
    </div>_x000D_
    <hr/>_x000D_
    <div style="width: 350px">_x000D_
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
      <div style="display: inline-block; background: #F00; color: #FFF">_x000D_
        Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
      </div>_x000D_
      Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

    enter image description here

    T-SQL - function with default parameters

    you have to call it like this

    SELECT dbo.CheckIfSFExists(23, default)
    

    From Technet:

    When a parameter of the function has a default value, the keyword DEFAULT must be specified when the function is called in order to retrieve the default value. This behaviour is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value. An exception to this behaviour is when invoking a scalar function by using the EXECUTE statement. When using EXECUTE, the DEFAULT keyword is not required.

    JavaScript associative array to JSON

    I posted a fix for this here

    You can use this function to modify JSON.stringify to encode arrays, just post it near the beginning of your script (check the link above for more detail):

    // Upgrade for JSON.stringify, updated to allow arrays
    (function(){
        // Convert array to object
        var convArrToObj = function(array){
            var thisEleObj = new Object();
            if(typeof array == "object"){
                for(var i in array){
                    var thisEle = convArrToObj(array[i]);
                    thisEleObj[i] = thisEle;
                }
            }else {
                thisEleObj = array;
            }
            return thisEleObj;
        };
        var oldJSONStringify = JSON.stringify;
        JSON.stringify = function(input){
            if(oldJSONStringify(input) == '[]')
                return oldJSONStringify(convArrToObj(input));
            else
                return oldJSONStringify(input);
        };
    })();
    

    Is the ternary operator faster than an "if" condition in Java

    It's best to use whatever one reads better - there's in all practical effect 0 difference between performance.

    In this case I think the last statement reads better than the first if statement, but careful not to overuse the ternary operator - sometimes it can really make things a lot less clear.

    Insert current date in datetime format mySQL

    set the type of column named dateposted as DATETIME and run the following query:

    INSERT INTO table (`dateposted`) VALUES (CURRENT_TIMESTAMP)
    

    Operator overloading ==, !=, Equals

    public class BOX
    {
        double height, length, breadth;
    
        public static bool operator == (BOX b1, BOX b2)
        {
            if (b1 is null)
                return b2 is null;
    
            return b1.Equals(b2);
        }
    
        public static bool operator != (BOX b1, BOX b2)
        {
            return !(b1 == b2);
        }
    
        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;
    
            return obj is BOX b2? (length == b2.length && 
                                   breadth == b2.breadth && 
                                   height == b2.height): false;
    
        }
    
        public override int GetHashCode()
        {
            return (height,length,breadth).GetHashCode();
        }
    }
    

    How can I check the size of a file in a Windows batch script?

    I like @Anders answer because the explanation of the %~z1 secret sauce. However, as pointed out, that only works when the filename is passed as the first parameter to the batch file.

    @Anders worked around this by using FOR, which, is a great 1-liner fix to the problem, but, it's somewhat harder to read.

    Instead, we can go back to a simpler answer with %~z1 by using CALL. If you have a filename stored in an environment variable it will become %1 if you use it as a parameter to a routine in your batch file:

    @echo off
    setlocal
    set file=test.cmd
    set maxbytesize=1000
    
    call :setsize %file%
    
    if %size% lss %maxbytesize% (
        echo File is less than %maxbytesize% bytes
    ) else (
        echo File is greater than or equal %maxbytesize% bytes
    )
    goto :eof
    
    :setsize
    set size=%~z1
    goto :eof
    

    I've been curious about J. Bouvrie's concern regarding 32-bit limitations. It appears he is talking about an issue with using LSS not on the filesize logic itself. To deal with J. Bouvrie's concern, I've rewritten the solution to use a padded string comparison:

    @echo on
    setlocal
    set file=test.cmd
    set maxbytesize=1000
    
    call :setsize %file%
    
    set checksize=00000000000000000000%size%
    set checkmaxbytesize=00000000000000000000%maxbytesize%
    if "%checksize:~-20%" lss "%checkmaxbytesize:~-20%" (
        echo File is less than %maxbytesize% bytes
    ) else (
        echo File is greater than or equal %maxbytesize% bytes
    )
    goto :eof
    
    :setsize
    set size=%~z1
    goto :eof
    

    Why does the html input with type "number" allow the letter 'e' to be entered in the field?

    A simple solution to exclude everything but integer numbers

    _x000D_
    _x000D_
    <input  
        type="number"
        min="1" 
        step="1"
        onkeypress="return event.keyCode === 8 || event.charCode >= 48 && event.charCode <= 57">
    _x000D_
    _x000D_
    _x000D_

    Determine the number of rows in a range

    Sheet1.Range("myrange").Rows.Count
    

    Sound alarm when code finishes

    import subprocess
    
    subprocess.call(['D:\greensoft\TTPlayer\TTPlayer.exe', "E:\stridevampaclip.mp3"])
    

    Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?

    A static library(.a) is a library that can be linked directly into the final executable produced by the linker,it is contained in it and there is no need to have the library into the system where the executable will be deployed.

    A shared library(.so) is a library that is linked but not embedded in the final executable, so will be loaded when the executable is launched and need to be present in the system where the executable is deployed.

    A dynamic link library on windows(.dll) is like a shared library(.so) on linux but there are some differences between the two implementations that are related to the OS (Windows vs Linux) :

    A DLL can define two kinds of functions: exported and internal. The exported functions are intended to be called by other modules, as well as from within the DLL where they are defined. Internal functions are typically intended to be called only from within the DLL where they are defined.

    An SO library on Linux doesn't need special export statement to indicate exportable symbols, since all symbols are available to an interrogating process.

    How to start/stop/restart a thread in Java?

    Once a thread stops you cannot restart it. However, there is nothing stopping you from creating and starting a new thread.

    Option 1: Create a new thread rather than trying to restart.

    Option 2: Instead of letting the thread stop, have it wait and then when it receives notification you can allow it to do work again. This way the thread never stops and will never need to be restarted.

    Edit based on comment:

    To "kill" the thread you can do something like the following.

    yourThread.setIsTerminating(true); // tell the thread to stop
    yourThread.join(); // wait for the thread to stop
    

    How do I send an HTML email?

    you have to call

    msg.saveChanges();
    

    after setting content type.

    How do I make a fixed size formatted string in python?

    Sure, use the .format method. E.g.,

    print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
    print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
    print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))
    

    will print

    xxx        123    98.00
    yyyy         3     1.00
    zz          42   123.34
    

    You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

    10s format a string with 10 spaces, left justified by default

    3d format an integer reserving 3 spaces, right justified by default

    7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

    There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

    Update for f-string mode. E.g.,

    text, number, other_number = 'xxx', 123, 98
    print(f'{text:10} {number:3d}  {other_number:7.2f}')
    

    For right alignment

    print(f'{text:>10} {number:3d}  {other_number:7.2f}')
    

    How to find the size of an int[]?

    when u pass any array to some function. u are just passing it's starting address, so for it to work u have to pass it size also for it to work properly. it's the same reason why we pass argc with argv[] in command line arguement.

    LINQ equivalent of foreach for IEnumerable<T>

    Keep your Side Effects out of my IEnumerable

    I'd like to do the equivalent of the following in LINQ, but I can't figure out how:

    As others have pointed out here and abroad LINQ and IEnumerable methods are expected to be side-effect free.

    Do you really want to "do something" to each item in the IEnumerable? Then foreach is the best choice. People aren't surprised when side-effects happen here.

    foreach (var i in items) i.DoStuff();
    

    I bet you don't want a side-effect

    However in my experience side-effects are usually not required. More often than not there is a simple LINQ query waiting to be discovered accompanied by a StackOverflow.com answer by either Jon Skeet, Eric Lippert, or Marc Gravell explaining how to do what you want!

    Some examples

    If you are actually just aggregating (accumulating) some value then you should consider the Aggregate extension method.

    items.Aggregate(initial, (acc, x) => ComputeAccumulatedValue(acc, x));
    

    Perhaps you want to create a new IEnumerable from the existing values.

    items.Select(x => Transform(x));
    

    Or maybe you want to create a look-up table:

    items.ToLookup(x, x => GetTheKey(x))
    

    The list (pun not entirely intended) of possibilities goes on and on.