Programs & Examples On #Uitextview

The UITextView class implements the behavior for a scrollable, multiline text region in iOS. The class supports the display of text using a custom font, color, and alignment and also supports text editing. You typically use a text view to display multiple lines of text, such as when displaying the body of a large text document.

Multiple lines of text in UILabel

You can do that via the Storyboard too:

  1. Select the Label on the view controller
  2. In the Attribute Inspector, increase the value of the Line option (Press Alt+Cmd+4 to show Attributes Inspector)
  3. Double click the Label in the view controller and write or paste your text
  4. Resize the Label and/or increase the font size so that the whole text could be shown

How can I make a clickable link in an NSAttributedString?

Swift 4:

var string = "Google"
var attributedString = NSMutableAttributedString(string: string, attributes:[NSAttributedStringKey.link: URL(string: "http://www.google.com")!])

yourTextView.attributedText = attributedString

Swift 3.1:

var string = "Google"
var attributedString = NSMutableAttributedString(string: string, attributes:[NSLinkAttributeName: URL(string: "http://www.google.com")!])

yourTextView.attributedText = attributedString

How do I size a UITextView to its content?

In iOS6, you can check the contentSize property of UITextView right after you set the text. In iOS7, this will no longer work. If you want to restore this behavior for iOS7, place the following code in a subclass of UITextView.

- (void)setText:(NSString *)text
{
    [super setText:text];

    if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
        CGRect rect = [self.textContainer.layoutManager usedRectForTextContainer:self.textContainer];
        UIEdgeInsets inset = self.textContainerInset;
        self.contentSize = UIEdgeInsetsInsetRect(rect, inset).size;
    }
}

How to lose margin/padding in UITextView?

Latest Swift:

self.textView.textContainerInset = .init(top: -2, left: 0, bottom: 0, right: 0)
self.textView.textContainer.lineFragmentPadding = 0

UITextView that expands to text using auto layout

BTW, I built an expanding UITextView using a subclass and overriding intrinsic content size. I discovered a bug in UITextView that you might want to investigate in your own implementation. Here is the problem:

The expanding text view would grow down to accommodate the growing text if you type single letters at a time. But if you paste a bunch of text into it, it would not grow down but the text would scroll up and the text at the top was out of view.

The solution: Override setBounds: in your subclass. For some unknown reason, the pasting caused the bounds.origin.y value to be non-zee (33 in every case that I saw). So I overrode setBounds: to always set the bounds.origin.y to zero. Fixed the problem.

Add placeholder text inside UITextView in Swift?

I believe this is a very clean solution. It adds a dummy text view underneath the actual text view and shows or hides it depending on the text in the actual text view:

import Foundation
import UIKit

class TextViewWithPlaceholder: UITextView {

    private var placeholderTextView: UITextView = UITextView()

    var placeholder: String? {
        didSet {
            placeholderTextView.text = placeholder
        }
    }

    override var text: String! {
        didSet {
            placeholderTextView.isHidden = text.isEmpty == false
        }
    }

    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        commonInit()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        commonInit()
    }

    private func commonInit() {
        applyCommonTextViewAttributes(to: self)
        configureMainTextView()
        addPlaceholderTextView()
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(textDidChange),
                                               name: UITextView.textDidChangeNotification,
                                               object: nil)
    }

    func addPlaceholderTextView() {
        applyCommonTextViewAttributes(to: placeholderTextView)
        configurePlaceholderTextView()
        insertSubview(placeholderTextView, at: 0)
    }

    private func applyCommonTextViewAttributes(to textView: UITextView) {
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.textContainer.lineFragmentPadding = 0
        textView.textContainerInset = UIEdgeInsets(top: 10,
                                                   left: 10,
                                                   bottom: 10,
                                                   right: 10)
    }

    private func configureMainTextView() {
        // Do any configuration of the actual text view here
    }

    private func configurePlaceholderTextView() {
        placeholderTextView.text = placeholder
        placeholderTextView.font = font
        placeholderTextView.textColor = UIColor.lightGray
        placeholderTextView.frame = bounds
        placeholderTextView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        placeholderTextView.frame = bounds
    }

    @objc func textDidChange() {
        placeholderTextView.isHidden = !text.isEmpty
    }

}

Placeholder in UITextView

I read through all of these, but came up with a very short, Swift 3, solution that has worked in all of my tests. It could stand a little more generality, but the process is simple. Here's the entire thing which I call "TextViewWithPlaceholder".

import UIKit

class TextViewWithPlaceholder: UITextView {

    public var placeholder: String?
    public var placeholderColor = UIColor.lightGray

    private var placeholderLabel: UILabel?

    // Set up notification listener when created from a XIB or storyboard.
    // You can also set up init() functions if you plan on creating
    // these programmatically.
    override func awakeFromNib() {
        super.awakeFromNib()

        NotificationCenter.default.addObserver(self,
                                           selector: #selector(TextViewWithPlaceholder.textDidChangeHandler(notification:)),
                                           name: .UITextViewTextDidChange,
                                           object: self)

        placeholderLabel = UILabel()
        placeholderLabel?.alpha = 0.85
        placeholderLabel?.textColor = placeholderColor
    }

    // By using layoutSubviews, you can size and position the placeholder
    // more accurately. I chose to hard-code the size of the placeholder
    // but you can combine this with other techniques shown in previous replies.
    override func layoutSubviews() {
        super.layoutSubviews()

        placeholderLabel?.textColor = placeholderColor
        placeholderLabel?.text = placeholder

        placeholderLabel?.frame = CGRect(x: 6, y: 4, width: self.bounds.size.width-16, height: 24)

        if text.isEmpty {
            addSubview(placeholderLabel!)
            bringSubview(toFront: placeholderLabel!)
        } else {
            placeholderLabel?.removeFromSuperview()
        }
    }

    // Whenever the text changes, just trigger a new layout pass.
    func textDidChangeHandler(notification: Notification) {
        layoutSubviews()
    }
}

How to style UITextview to like Rounded Rect text field?

You can create a Text Field that doesn't accept any events on top of a Text View like this:

CGRect frameRect = descriptionTextField.frame;
frameRect.size.height = 50;
descriptionTextField.frame = frameRect;
descriptionTextView.frame = frameRect;
descriptionTextField.backgroundColor = [UIColor clearColor];
descriptionTextField.enabled = NO;
descriptionTextView.layer.cornerRadius = 5;
descriptionTextView.clipsToBounds = YES;

Change UITextField and UITextView Cursor / Caret Color

Swift 4

In viewDidLoad() just call below code:

CODE SAMPLE

//txtVComplaint is a textView

txtVComplaint.tintColor = UIColor.white

txtVComplaint.tintColorDidChange()

Swift: Display HTML data in a label or textView

Swift 3.0

var attrStr = try! NSAttributedString(
        data: "<b><i>text</i></b>".data(using: String.Encoding.unicode, allowLossyConversion: true)!,
        options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil)
label.attributedText = attrStr

how to make UITextView height dynamic according to text length?

Swift 5, Use extension:

extension UITextView {
    func adjustUITextViewHeight() {
        self.translatesAutoresizingMaskIntoConstraints = true
        self.sizeToFit()
        self.isScrollEnabled = false
    }
}

Usecase:

textView.adjustUITextViewHeight()

And don't care about the height of texeView in the storyboard (just use a constant at first)

How to dismiss keyboard for UITextView with return key?

Add this method in your view controller.

Swift:

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    if text == "\n" {
        textView.resignFirstResponder()
        return false
    }
    return true
}

This method also can be helpful for you:

/**
Dismiss keyboard when tapped outside the keyboard or textView

:param: touches the touches
:param: event   the related event
*/
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    if let touch = touches.anyObject() as? UITouch {
        if touch.phase == UITouchPhase.Began {
            textField?.resignFirstResponder()
        }
    }
}

Display html text in uitextview

For Swift 4, Swift 4.2: and Swift 5

let htmlString = """
    <html>
        <head>
            <style>
                body {
                    background-color : rgb(230, 230, 230);
                    font-family      : 'Arial';
                    text-decoration  : none;
                }
            </style>
        </head>
        <body>
            <h1>A title</h1>
            <p>A paragraph</p>
            <b>bold text</b>
        </body>
    </html>
    """

let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)

let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]

let attributedString = try! NSAttributedString(data: htmlData!, options: options, documentAttributes: nil)

textView.attributedText = attributedString

For Swift 3:

let htmlString = """
    <html>
        <head>
            <style>
                body {
                    background-color : rgb(230, 230, 230);
                    font-family      : 'Arial';
                    text-decoration  : none;
                }
            </style>
        </head>
        <body>
            <h1>A title</h1>
            <p>A paragraph</p>
            <b>bold text</b>
        </body>
    </html>
    """

let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)

let attributedString = try! NSAttributedString(data: htmlData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)

textView.attributedText = attributedString

How to create a multiline UITextfield?

Besides from the multiple line behaviour, the main difference between UITextView and UITextField is that the UITextView does not propose a placeholder. To bypass this limitation, you can use a UITextView with a "fake placeholder."

See this SO question for details: Placeholder in UITextView.

Convert varchar into datetime in SQL Server

use Try_Convert:Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.

DECLARE @DateString VARCHAR(10) ='20160805'
SELECT TRY_CONVERT(DATETIME,@DateString)

SET @DateString ='Invalid Date'
SELECT TRY_CONVERT(DATETIME,@DateString)

Link:MSDN TRY_CONVERT (Transact-SQL)

Copying text outside of Vim with set mouse=a enabled

You can use :set mouse& in the vim command line to enable copy/paste of text selected using the mouse. You can then simply use the middle mouse button or shiftinsert to paste it.

SVG: text inside rect

Programmatically display text over rect using basic Javascript

_x000D_
_x000D_
 var svg = document.getElementsByTagNameNS('http://www.w3.org/2000/svg', 'svg')[0];_x000D_
_x000D_
        var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');_x000D_
        text.setAttribute('x', 20);_x000D_
        text.setAttribute('y', 50);_x000D_
        text.setAttribute('width', 500);_x000D_
        text.style.fill = 'red';_x000D_
        text.style.fontFamily = 'Verdana';_x000D_
        text.style.fontSize = '35';_x000D_
        text.innerHTML = "Some text line";_x000D_
_x000D_
        svg.appendChild(text);_x000D_
_x000D_
        var text2 = document.createElementNS('http://www.w3.org/2000/svg', 'text');_x000D_
        text2.setAttribute('x', 20);_x000D_
        text2.setAttribute('y', 100);_x000D_
        text2.setAttribute('width', 500);_x000D_
        text2.style.fill = 'green';_x000D_
        text2.style.fontFamily = 'Calibri';_x000D_
        text2.style.fontSize = '35';_x000D_
        text2.style.fontStyle = 'italic';_x000D_
        text2.innerHTML = "Some italic line";_x000D_
_x000D_
       _x000D_
        svg.appendChild(text2);_x000D_
_x000D_
        var text3 = document.createElementNS('http://www.w3.org/2000/svg', 'text');_x000D_
        text3.setAttribute('x', 20);_x000D_
        text3.setAttribute('y', 150);_x000D_
        text3.setAttribute('width', 500);_x000D_
        text3.style.fill = 'green';_x000D_
        text3.style.fontFamily = 'Calibri';_x000D_
        text3.style.fontSize = '35';_x000D_
        text3.style.fontWeight = 700;_x000D_
        text3.innerHTML = "Some bold line";_x000D_
_x000D_
       _x000D_
        svg.appendChild(text3);
_x000D_
    <svg width="510" height="250" xmlns="http://www.w3.org/2000/svg">_x000D_
        <rect x="0" y="0" width="510" height="250" fill="aquamarine" />_x000D_
    </svg>
_x000D_
_x000D_
_x000D_

enter image description here

How do I fetch multiple columns for use in a cursor loop?

Here is slightly modified version. Changes are noted as code commentary.

BEGIN TRANSACTION

declare @cnt int
declare @test nvarchar(128)
-- variable to hold table name
declare @tableName nvarchar(255)
declare @cmd nvarchar(500) 
-- local means the cursor name is private to this code
-- fast_forward enables some speed optimizations
declare Tests cursor local fast_forward for
 SELECT COLUMN_NAME, TABLE_NAME
   FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE COLUMN_NAME LIKE 'pct%' 
    AND TABLE_NAME LIKE 'TestData%'

open Tests
-- Instead of fetching twice, I rather set up no-exit loop
while 1 = 1
BEGIN
  -- And then fetch
  fetch next from Tests into @test, @tableName
  -- And then, if no row is fetched, exit the loop
  if @@fetch_status <> 0
  begin
     break
  end
  -- Quotename is needed if you ever use special characters
  -- in table/column names. Spaces, reserved words etc.
  -- Other changes add apostrophes at right places.
  set @cmd = N'exec sp_rename ''' 
           + quotename(@tableName) 
           + '.' 
           + quotename(@test) 
           + N''',''' 
           + RIGHT(@test,LEN(@test)-3) 
           + '_Pct''' 
           + N', ''column''' 

  print @cmd

  EXEC sp_executeSQL @cmd
END

close Tests 
deallocate Tests

ROLLBACK TRANSACTION
--COMMIT TRANSACTION

What is the point of the diamond operator (<>) in Java 7?

The issue with

List<String> list = new LinkedList();

is that on the left hand side, you are using the generic type List<String> where on the right side you are using the raw type LinkedList. Raw types in Java effectively only exist for compatibility with pre-generics code and should never be used in new code unless you absolutely have to.

Now, if Java had generics from the beginning and didn't have types, such as LinkedList, that were originally created before it had generics, it probably could have made it so that the constructor for a generic type automatically infers its type parameters from the left-hand side of the assignment if possible. But it didn't, and it must treat raw types and generic types differently for backwards compatibility. That leaves them needing to make a slightly different, but equally convenient, way of declaring a new instance of a generic object without having to repeat its type parameters... the diamond operator.

As far as your original example of List<String> list = new LinkedList(), the compiler generates a warning for that assignment because it must. Consider this:

List<String> strings = ... // some list that contains some strings

// Totally legal since you used the raw type and lost all type checking!
List<Integer> integers = new LinkedList(strings);

Generics exist to provide compile-time protection against doing the wrong thing. In the above example, using the raw type means you don't get this protection and will get an error at runtime. This is why you should not use raw types.

// Not legal since the right side is actually generic!
List<Integer> integers = new LinkedList<>(strings);

The diamond operator, however, allows the right hand side of the assignment to be defined as a true generic instance with the same type parameters as the left side... without having to type those parameters again. It allows you to keep the safety of generics with almost the same effort as using the raw type.

I think the key thing to understand is that raw types (with no <>) cannot be treated the same as generic types. When you declare a raw type, you get none of the benefits and type checking of generics. You also have to keep in mind that generics are a general purpose part of the Java language... they don't just apply to the no-arg constructors of Collections!

Keystore type: which one to use?

There are a few more types than what's listed in the standard name list you've linked to. You can find more in the cryptographic providers documentation. The most common are certainly JKS (the default) and PKCS12 (for PKCS#12 files, often with extension .p12 or sometimes .pfx).

JKS is the most common if you stay within the Java world. PKCS#12 isn't Java-specific, it's particularly convenient to use certificates (with private keys) backed up from a browser or coming from OpenSSL-based tools (keytool wasn't able to convert a keystore and import its private keys before Java 6, so you had to use other tools).

If you already have a PKCS#12 file, it's often easier to use the PKCS12 type directly. It's possible to convert formats, but it's rarely necessary if you can choose the keystore type directly.

In Java 7, PKCS12 was mainly useful as a keystore but less for a truststore (see the difference between a keystore and a truststore), because you couldn't store certificate entries without a private key. In contrast, JKS doesn't require each entry to be a private key entry, so you can have entries that contain only certificates, which is useful for trust stores, where you store the list of certificates you trust (but you don't have the private key for them).

This has changed in Java 8, so you can now have certificate-only entries in PKCS12 stores too. (More details about these changes and further plans can be found in JEP 229: Create PKCS12 Keystores by Default.)

There are a few other keystore types, perhaps less frequently used (depending on the context), those include:

  • PKCS11, for PKCS#11 libraries, typically for accessing hardware cryptographic tokens, but the Sun provider implementation also supports NSS stores (from Mozilla) through this.
  • BKS, using the BouncyCastle provider (commonly used for Android).
  • Windows-MY/Windows-ROOT, if you want to access the Windows certificate store directly.
  • KeychainStore, if you want to use the OSX keychain directly.

CR LF notepad++ removal

View -> Show Symbol -> uncheck Show All characters

Image change every 30 seconds - loop

setInterval function is the one that has to be used. Here is an example for the same without any fancy fading option. Simple Javascript that does an image change every 30 seconds. I have assumed that the images were kept in a separate images folder and hence _images/ is present at the beginning of every image. You can have your own path as required to be set.

CODE:

var im = document.getElementById("img");

var images = ["_images/image1.jpg","_images/image2.jpg","_images/image3.jpg"];
var index=0;

function changeImage()
{
  im.setAttribute("src", images[index]);
  index++;
  if(index >= images.length)
  {
    index=0;
  }
}

setInterval(changeImage, 30000);

Gem Command not found

FWIW, the equivalent package for RHEL/Fedora/CentOS/etc and SuSE/OpenSuSE appears to be called 'rubygems'.

Static array vs. dynamic array in C++

static is a keyword in C and C++, so rather than a general descriptive term, static has very specific meaning when applied to a variable or array. To compound the confusion, it has three distinct meanings within separate contexts. Because of this, a static array may be either fixed or dynamic.

Let me explain:

The first is C++ specific:

  • A static class member is a value that is not instantiated with the constructor or deleted with the destructor. This means the member has to be initialized and maintained some other way. static member may be pointers initialized to null and then allocated the first time a constructor is called. (Yes, that would be static and dynamic)

Two are inherited from C:

  • within a function, a static variable is one whose memory location is preserved between function calls. It is static in that it is initialized only once and retains its value between function calls (use of statics makes a function non-reentrant, i.e. not threadsafe)

  • static variables declared outside of functions are global variables that can only be accessed from within the same module (source code file with any other #include's)

The question (I think) you meant to ask is what the difference between dynamic arrays and fixed or compile-time arrays. That is an easier question, compile-time arrays are determined in advance (when the program is compiled) and are part of a functions stack frame. They are allocated before the main function runs. dynamic arrays are allocated at runtime with the "new" keyword (or the malloc family from C) and their size is not known in advance. dynamic allocations are not automatically cleaned up until the program stops running.

Difference between <span> and <div> with text-align:center;?

Like other have said, span is an in-line element.

See here: http://www.w3.org/TR/CSS2/visuren.html

Additionally, you can make a span behave like a div by applying a

style="display: block; margin: 0px auto; text-align: center;"

Using import fs from 'fs'

It's not supported just yet... If you want to use it you will have to install Babel.

How to check 'undefined' value in jQuery

Note that typeof always returns a string, and doesn't generate an error if the variable doesn't exist at all.

function A(val){
  if(typeof(val)  === "undefined") 
    //do this
  else
   //do this
}

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

This is now no longer needed for Java 9, nor for any recent release of Java 6, 7, or 8. Finally! :)

Per JDK-8170157, the unlimited cryptographic policy is now enabled by default.

Specific versions from the JIRA issue:

  • Java 9 (10, 11, etc..): Any official release!
  • Java 8u161 or later (Available now)
  • Java 7u171 or later (Only available through 'My Oracle Support')
  • Java 6u181 or later (Only available through 'My Oracle Support')

Note that if for some odd reason the old behavior is needed in Java 9, it can be set using:

Security.setProperty("crypto.policy", "limited");

Copy or rsync command

Especially if you use a copy-on-write filesystem like BTRFS or ZFS, rsync is much better.

I use BTRFS, and I have this in my ~/.bashrc:

alias cp="rsync -ah --inplace --no-whole-file --info=progress2"

The important flag here for CoW FSs like BTRFS is --inplace because it only copies the changed part of the files, doesn't create new for small changes between files inodes, etc. See this.

How can I generate a list of files with their absolute path in Linux?

If you give find an absolute path to start with, it will print absolute paths. For instance, to find all .htaccess files in the current directory:

find "$(pwd)" -name .htaccess

or if your shell expands $PWD to the current directory:

find "$PWD" -name .htaccess

find simply prepends the path it was given to a relative path to the file from that path.

Greg Hewgill also suggested using pwd -P if you want to resolve symlinks in your current directory.

Trigger insert old values- values that was updated

In SQL Server 2008 you can use Change Data Capture for this. Details of how to set it up on a table are here http://msdn.microsoft.com/en-us/library/cc627369.aspx

Django: Display Choice Value

Others have pointed out that a get_FOO_display method is what you need. I'm using this:

def get_type(self):
    return [i[1] for i in Item._meta.get_field('type').choices if i[0] == self.type][0]

which iterates over all of the choices that a particular item has until it finds the one that matches the items type

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

How to delete row based on cell value

You could copy down a formula like the following in a new column...

=IF(ISNUMBER(FIND("-",A1)),1,0)

... then sort on that column, highlight all the rows where the value is 1 and delete them.

ITextSharp HTML to PDF?

I would one-up'd mightymada's answer if I had the reputation - I just implemented an asp.net HTML to PDF solution using Pechkin. results are wonderful.

There is a nuget package for Pechkin, but as the above poster mentions in his blog (http://codeutil.wordpress.com/2013/09/16/convert-html-to-pdf/ - I hope she doesn't mind me reposting it), there's a memory leak that's been fixed in this branch:

https://github.com/tuespetre/Pechkin

The above blog has specific instructions for how to include this package (it's a 32 bit dll and requires .net4). here is my code. The incoming HTML is actually assembled via HTML Agility pack (I'm automating invoice generations):

public static byte[] PechkinPdf(string html)
{
  //Transform the HTML into PDF
  var pechkin = Factory.Create(new GlobalConfig());
  var pdf = pechkin.Convert(new ObjectConfig()
                          .SetLoadImages(true).SetZoomFactor(1.5)
                          .SetPrintBackground(true)
                          .SetScreenMediaType(true)
                          .SetCreateExternalLinks(true), html);

  //Return the PDF file
  return pdf;
}

again, thank you mightymada - your answer is fantastic.

Clearing <input type='file' /> using jQuery

It's easy lol (works in all browsers [except opera]):

$('input[type=file]').each(function(){
    $(this).after($(this).clone(true)).remove();
});

JS Fiddle: http://jsfiddle.net/cw84x/1/

Get lengths of a list in a jinja2 template

<span>You have {{products|length}} products</span>

You can also use this syntax in expressions like

{% if products|length > 1 %}

jinja2's builtin filters are documented here; and specifically, as you've already found, length (and its synonym count) is documented to:

Return the number of items of a sequence or mapping.

So, again as you've found, {{products|count}} (or equivalently {{products|length}}) in your template will give the "number of products" ("length of list")

Update Top 1 record in table sql server

For those who are finding for a thread safe solution, take a look here.

Code:

UPDATE Account 
SET    sg_status = 'A'
OUTPUT INSERTED.AccountId --You only need this if you want to return some column of the updated item
WHERE  AccountId = 
(
    SELECT TOP 1 AccountId 
    FROM Account WITH (UPDLOCK) --this is what makes the query thread safe!
    ORDER  BY CreationDate 
)

How can I pass a parameter to a Java Thread?

This answer comes very late, but maybe someone will find it useful. It is about how to pass a parameter(s) to a Runnable without even declaring named class (handy for inliners):

    String someValue = "Just a demo, really...";

    new Thread(new Runnable() {
        private String myParam;

        public Runnable init(String myParam) {
            this.myParam = myParam;
            return this;
        }

        @Override
        public void run() {
            System.out.println("This is called from another thread.");
            System.out.println(this.myParam);
        }
    }.init(someValue)).start();

Of course you can postpone execution of start to some more convenient or appropriate moment. And it is up to you what will be the signature of init method (so it may take more and/or different arguments) and of course even its name, but basically you get an idea.

In fact there is also another way of passing a parameter to an anonymous class, with the use of the initializer blocks. Consider this:

    String someValue = "Another demo, no serious thing...";
    int anotherValue = 42;

    new Thread(new Runnable() {
        private String myParam;
        private int myOtherParam;
        // instance initializer
        {
            this.myParam = someValue;
            this.myOtherParam = anotherValue;
        }

        @Override
        public void run() {
            System.out.println("This comes from another thread.");
            System.out.println(this.myParam + ", " + this.myOtherParam);
        }
    }).start();

So all happens inside of the initializer block.

How to list active / open connections in Oracle?

select 
    count(1) "NO. Of DB Users", 
    to_char(sysdate,'DD-MON-YYYY:HH24:MI:SS') sys_time
from 
    v$session 
where 
    username is NOT  NULL;

What is the purpose of the single underscore "_" variable in Python?

Underscore _ is considered as "I don't Care" or "Throwaway" variable in Python

  • The python interpreter stores the last expression value to the special variable called _.

    >>> 10 
    10
    
    >>> _ 
    10
    
    >>> _ * 3 
    30
    
  • The underscore _ is also used for ignoring the specific values. If you don’t need the specific values or the values are not used, just assign the values to underscore.

    Ignore a value when unpacking

    x, _, y = (1, 2, 3)
    
    >>> x
    1
    
    >>> y 
    3
    

    Ignore the index

    for _ in range(10):     
        do_something()
    

Save results to csv file with Python

Use csv.writer:

import csv

with open('thefile.csv', 'rb') as f:
  data = list(csv.reader(f))

import collections
counter = collections.defaultdict(int)
for row in data:
    counter[row[0]] += 1


writer = csv.writer(open("/path/to/my/csv/file", 'w'))
for row in data:
    if counter[row[0]] >= 4:
        writer.writerow(row)

CS1617: Invalid option ‘6’ for /langversion; must be ISO-1, ISO-2, 3, 4, 5 or Default

If you'd like to use C# 6.0:

  1. Make sure your project's .NET version is higher than 4.5.2.
  2. And then check your .config file to perform the following modifications.

Look for the system.codedom and modify it so that it will look as shown below:

<system.codedom>
 <compilers>
  <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
  <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
 </compilers>
</system.codedom>

CAML query with nested ANDs and ORs for multiple fields

Since you are not allowed to put more than two conditions in one condition group (And | Or) you have to create an extra nested group (MSDN). The expression A AND B AND C looks like this:

<And>
    A
    <And>
        B
        C
    </And>
</And>

Your SQL like sample translated to CAML (hopefully with matching XML tags ;) ):

<Where>
    <And>
        <Or>
            <Eq>
                <FieldRef Name='FirstName' />
                <Value Type='Text'>John</Value>
            </Eq>
            <Or>
                <Eq>
                    <FieldRef Name='LastName' />
                    <Value Type='Text'>John</Value>
                </Eq>
                <Eq>
                    <FieldRef Name='Profile' />
                    <Value Type='Text'>John</Value>
                </Eq>
            </Or>
        </Or>
        <And>       
            <Or>
                <Eq>
                    <FieldRef Name='FirstName' />
                    <Value Type='Text'>Doe</Value>
                </Eq>
                <Or>
                    <Eq>
                        <FieldRef Name='LastName' />
                        <Value Type='Text'>Doe</Value>
                    </Eq>
                    <Eq>
                        <FieldRef Name='Profile' />
                        <Value Type='Text'>Doe</Value>
                    </Eq>
                </Or>
            </Or>
            <Or>
                <Eq>
                    <FieldRef Name='FirstName' />
                    <Value Type='Text'>123</Value>
                </Eq>
                <Or>
                    <Eq>
                        <FieldRef Name='LastName' />
                        <Value Type='Text'>123</Value>
                    </Eq>
                    <Eq>
                        <FieldRef Name='Profile' />
                        <Value Type='Text'>123</Value>
                    </Eq>
                </Or>
            </Or>
        </And>
    </And>
</Where>

Android toolbar center title and custom font

To use a custom title in your Toolbar you can add a custom title like :

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:elevation="5dp"
    app:contentInsetLeft="0dp"
    app:contentInsetStart="0dp"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.Dark">


        <LinearLayout
            android:id="@+id/lnrTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
            android:orientation="vertical">

            <TextView
                android:id="@+id/txvHeader"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal|center"
                android:gravity="center"
                android:ellipsize="end"
                android:maxLines="1"
                android:text="Header"
                android:textColor="@color/white"
                android:textSize="18sp" />


        </LinearLayout>


</android.support.v7.widget.Toolbar>

Java Code:

Toolbar toolbar = findViewById(R.id.toolbar);

setSupportActionBar(toolbar);

if (getSupportActionBar() == null)
    return;

getSupportActionBar().setTitle("Title");

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

How to add /usr/local/bin in $PATH on Mac

I tend to find this neat

sudo mkdir -p /etc/paths.d   # was optional in my case
echo /usr/local/git/bin  | sudo tee /etc/paths.d/mypath1

Curl not recognized as an internal or external command, operable program or batch file

Method 1:\

add "C:\Program Files\cURL\bin" path into system variables Path right-click My Computer and click Properties >advanced > Environment Variables enter image description here

Method 2: (if method 1 not work then)

simple open command prompt with "run as administrator"

How to make lists contain only distinct element in Python?

The simplest is to convert to a set then back to a list:

my_list = list(set(my_list))

One disadvantage with this is that it won't preserve the order. You may also want to consider if a set would be a better data structure to use in the first place, instead of a list.

Use of min and max functions in C++

There is an important difference between std::min, std::max and fmin and fmax.

std::min(-0.0,0.0) = -0.0
std::max(-0.0,0.0) = -0.0

whereas

fmin(-0.0, 0.0) = -0.0
fmax(-0.0, 0.0) =  0.0

So std::min is not a 1-1 substitute for fmin. The functions std::min and std::max are not commutative. To get the same result with doubles with fmin and fmax one should swap the arguments

fmin(-0.0, 0.0) = std::min(-0.0,  0.0)
fmax(-0.0, 0.0) = std::max( 0.0, -0.0)

But as far as I can tell all these functions are implementation defined anyway in this case so to be 100% sure you have to test how they are implemented.


There is another important difference. For x ! = NaN:

std::max(Nan,x) = NaN
std::max(x,NaN) = x
std::min(Nan,x) = NaN
std::min(x,NaN) = x

whereas

fmax(Nan,x) = x
fmax(x,NaN) = x
fmin(Nan,x) = x
fmin(x,NaN) = x

fmax can be emulated with the following code

double myfmax(double x, double y)
{
   // z > nan for z != nan is required by C the standard
   int xnan = isnan(x), ynan = isnan(y);
   if(xnan || ynan) {
        if(xnan && !ynan) return y;
        if(!xnan && ynan) return x;
        return x;
   }
   // +0 > -0 is preferred by C the standard 
   if(x==0 && y==0) {
       int xs = signbit(x), ys = signbit(y);
       if(xs && !ys) return y;
       if(!xs && ys) return x;
       return x;
   }
   return std::max(x,y);
}

This shows that std::max is a subset of fmax.

Looking at the assembly shows that Clang uses builtin code for fmax and fmin whereas GCC calls them from a math library. The assembly for clang for fmax with -O3 is

movapd  xmm2, xmm0
cmpunordsd      xmm2, xmm2
movapd  xmm3, xmm2
andpd   xmm3, xmm1
maxsd   xmm1, xmm0
andnpd  xmm2, xmm1
orpd    xmm2, xmm3
movapd  xmm0, xmm2

whereas for std::max(double, double) it is simply

maxsd   xmm0, xmm1

However, for GCC and Clang using -Ofast fmax becomes simply

maxsd   xmm0, xmm1

So this shows once again that std::max is a subset of fmax and that when you use a looser floating point model which does not have nan or signed zero then fmax and std::max are the same. The same argument obviously applies to fmin and std::min.

What is the most efficient way to store tags in a database?

I'd suggest using intermediary third table for storing tags<=>items associations, since we have many-to-many relations between tags and items, i.e. one item can be associated with multiple tags and one tag can be associated with multiple items. HTH, Valve.

CSS centred header image

I think this is what you need if I'm understanding you correctly:

<div id="wrapperHeader">
 <div id="header">
  <img src="images/logo.png" alt="logo" />
 </div> 
</div>



div#wrapperHeader {
 width:100%;
 height;200px; /* height of the background image? */
 background:url(images/header.png) repeat-x 0 0;
 text-align:center;
}

div#wrapperHeader div#header {
 width:1000px;
 height:200px;
 margin:0 auto;
}

div#wrapperHeader div#header img {
 width:; /* the width of the logo image */
 height:; /* the height of the logo image */
 margin:0 auto;
}

WCF service startup error "This collection already contains an address with scheme http"

In .Net 4, you can use the multipleSiteBindingsEnabled option:

<system.serviceModel>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true">
    </serviceHostingEnvironment>
</system.serviceModel>

Then, you won't have to specify each address.

http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehostingenvironment.multiplesitebindingsenabled.aspx

Why can't I define a static method in a Java interface?

Let's suppose static methods were allowed in interfaces: * They would force all implementing classes to declare that method. * Interfaces would usually be used through objects, so the only effective methods on those would be the non-static ones. * Any class which knows a particular interface could invoke its static methods. Hence a implementing class' static method would be called underneath, but the invoker class does not know which. How to know it? It has no instantiation to guess that!

Interfaces were thought to be used when working with objects. This way, an object is instantiated from a particular class, so this last matter is solved. The invoking class need not know which particular class is because the instantiation may be done by a third class. So the invoking class knows only the interface.

If we want this to be extended to static methods, we should have the possibility to especify an implementing class before, then pass a reference to the invoking class. This could use the class through the static methods in the interface. But what is the differente between this reference and an object? We just need an object representing what it was the class. Now, the object represents the old class, and could implement a new interface including the old static methods - those are now non-static.

Metaclasses serve for this purpose. You may try the class Class of Java. But the problem is that Java is not flexible enough for this. You can not declare a method in the class object of an interface.

This is a meta issue - when you need to do ass

..blah blah

anyway you have an easy workaround - making the method non-static with the same logic. But then you would have to first create an object to call the method.

Add some word to all or some rows in Excel?

  • Select All cells that want to change.
  • right click and select Format cell.
  • In category select Custom.
  • In Type select General and insert this formol ----> "k"@

CMD command to check connected USB devices

You can use the wmic command:

wmic path CIM_LogicalDevice where "Description like 'USB%'" get /value

Convert an object to an XML string

I realize this is a very old post, but after looking at L.B's response I thought about how I could improve upon the accepted answer and make it generic for my own application. Here's what I came up with:

public static string Serialize<T>(T dataToSerialize)
{
    try
    {
        var stringwriter = new System.IO.StringWriter();
        var serializer = new XmlSerializer(typeof(T));
        serializer.Serialize(stringwriter, dataToSerialize);
        return stringwriter.ToString();
    }
    catch
    {
        throw;
    }
}

public static T Deserialize<T>(string xmlText)
{
    try
    {
        var stringReader = new System.IO.StringReader(xmlText);
        var serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(stringReader);
    }
    catch
    {
        throw;
    }
}

These methods can now be placed in a static helper class, which means no code duplication to every class that needs to be serialized.

Rails: How to run `rails generate scaffold` when the model already exists?

TL;DR: rails g scaffold_controller <name>

Even though you already have a model, you can still generate the necessary controller and migration files by using the rails generate option. If you run rails generate -h you can see all of the options available to you.

Rails:
  controller
  generator
  helper
  integration_test
  mailer
  migration
  model
  observer
  performance_test
  plugin
  resource
  scaffold
  scaffold_controller
  session_migration
  stylesheets

If you'd like to generate a controller scaffold for your model, see scaffold_controller. Just for clarity, here's the description on that:

Stubs out a scaffolded controller and its views. Pass the model name, either CamelCased or under_scored, and a list of views as arguments. The controller name is retrieved as a pluralized version of the model name.

To create a controller within a module, specify the model name as a path like 'parent_module/controller_name'.

This generates a controller class in app/controllers and invokes helper, template engine and test framework generators.

To create your resource, you'd use the resource generator, and to create a migration, you can also see the migration generator (see, there's a pattern to all of this madness). These provide options to create the missing files to build a resource. Alternatively you can just run rails generate scaffold with the --skip option to skip any files which exist :)

I recommend spending some time looking at the options inside of the generators. They're something I don't feel are documented extremely well in books and such, but they're very handy.

MySQL Error 1264: out of range value for column

Work with:

ALTER TABLE `table` CHANGE `cust_fax` `cust_fax` VARCHAR(60) NULL DEFAULT NULL; 

How to select different app.config for several build configurations

You can try the following approach:

  1. Right-click on the project in Solution Explorer and select Unload Project.
  2. The project will be unloaded. Right-click on the project again and select Edit <YourProjectName>.csproj.
  3. Now you can edit the project file inside Visual Studio.
  4. Locate the place in *.csproj file where your application configuration file is included. It will look like:
    <ItemGroup>
        <None Include="App.config"/>
    </ItemGroup>
  1. Replace this lines with following:
    <ItemGroup Condition=" '$(Configuration)' == 'Debug' ">
        <None Include="App.Debug.config"/>
    </ItemGroup>

    <ItemGroup Condition=" '$(Configuration)' == 'Release' ">
        <None Include="App.Release.config"/>
    </ItemGroup>

I have not tried this approach to app.config files, but it worked fine with other items of Visual Studio projects. You can customize the build process in almost any way you like. Anyway, let me know the result.

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

!python 'script.py'

replace script.py with your real file name, DON'T forget ''

TortoiseSVN icons overlay not showing after updating to Windows 10

Registry editor shot

As in current recommended answer mentioned, you need to sort the entries of the overlay identifiers in the registry. I haven't deleted those OneDrive or GoogleDrive entries but renamed all Tortoise Folders by adding 3 spaces to bring them on top. Just restart and even with Tortoise SVN client 1.7.9 you'll see your SVN overlay icons under Windows 10 again.

batch file - counting number of files in folder and storing in a variable

I have used a temporary file to do this in the past, like this below.

DIR /B *.DAT | FIND.EXE /C /V "" > COUNT.TXT

FOR /F "tokens=1" %%f IN (COUNT.TXT) DO (
IF NOT %%f==6 SET _MSG=File count is %%f, and 6 were expected. & DEL COUNT.TXT & ECHO #### ERROR - FILE COUNT WAS %%f AND 6 WERE EXPECTED. #### >> %_LOGFILE% & GOTO SENDMAIL
)

Java 8 Lambda Stream forEach with multiple statements

In the first case alternatively to multiline forEach you can use the peek stream operation:

entryList.stream()
         .peek(entry -> entry.setTempId(tempId))
         .forEach(updatedEntries.add(entityManager.update(entry, entry.getId())));

In the second case I'd suggest to extract the loop body to the separate method and use method reference to call it via forEach. Even without lambdas it would make your code more clear as the loop body is independent algorithm which processes the single entry so it might be useful in other places as well and can be tested separately.

Update after question editing. if you have checked exceptions then you have two options: either change them to unchecked ones or don't use lambdas/streams at this piece of code at all.

YAML mapping values are not allowed in this context

This is valid YAML:

jobs:
 - name: A
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120
 - name: B
   schedule: "0 0/5 * 1/1 * ? *"
   type: mongodb.cluster
   config:
     host: mongodb://localhost:27017/admin?replicaSet=rs
     minSecondaries: 2
     minOplogHours: 100
     maxSecondaryDelay: 120

Note, that every '-' starts new element in the sequence. Also, indentation of keys in the map should be exactly same.

return value after a promise

Use a pattern along these lines:

function getValue(file) {
  return lookupValue(file);
}

getValue('myFile.txt').then(function(res) {
  // do whatever with res here
});

(although this is a bit redundant, I'm sure your actual code is more complicated)

Getting value from table cell in JavaScript...not jQuery

function GetCellValues() {
    var table = document.getElementById('mytable');
    for (var r = 0, n = table.rows.length; r < n; r++) {
        for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
            alert(table.rows[r].cells[c].innerHTML);
        }
    }
}

How do you use a variable in a regular expression?

String.prototype.replaceAll = function (replaceThis, withThis) {
   var re = new RegExp(replaceThis,"g"); 
   return this.replace(re, withThis);
};
var aa = "abab54..aba".replaceAll("\\.", "v");

Test with this tool

Concatenate in jQuery Selector

Your concatenation syntax is correct.

Most likely the callback function isn't even being called. You can test that by putting an alert(), console.log() or debugger line in that function.

If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail() handler after $.post() to find out what the error is, e.g.:

$.post('ajaxskeleton.php', {
    red: text       
}, function(){
    $('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(arguments);
});

load external URL into modal jquery ui dialog

I did it this way, where 'struts2ActionName' is the struts2 action in my case. You may use any url instead.

var urlAdditionCert =${pageContext.request.contextPath}/struts2ActionName";
$("#dialogId").load( urlAdditionCert).dialog({
    modal: true,
    height: $("#body").height(),
    width: $("#body").width()*.8
});

Can't import org.apache.http.HttpResponse in Android Studio

HttpClient was deprecated in Android 5.1 and is removed from the Android SDK in Android 6.0. While there is a workaround to continue using HttpClient in Android 6.0 with Android Studio, you really need to move to something else. That "something else" could be:

Or, depending upon the nature of your HTTP work, you might choose a library that supports higher-order operations (e.g., Retrofit for Web service APIs).

In a pinch, you could enable the legacy APIs, by having useLibrary 'org.apache.http.legacy' in your android closure in your module's build.gradle file. However, Google has been advising people for years to stop using Android's built-in HttpClient, and so at most, this should be a stop-gap move, while you work on a more permanent shift to another API.

How can I check if two segments intersect?

Checking if line segments intersect is very easy with Shapely library using intersects method:

from shapely.geometry import LineString

line = LineString([(0, 0), (1, 1)])
other = LineString([(0, 1), (1, 0)])
print(line.intersects(other))
# True

enter image description here

line = LineString([(0, 0), (1, 1)])
other = LineString([(0, 1), (1, 2)])
print(line.intersects(other))
# False

enter image description here

How to compare two dates to find time difference in SQL Server 2005, date manipulation

I used following logic and it worked for me like marvel:

CONVERT(TIME, DATEADD(MINUTE, DATEDIFF(MINUTE, AP.Time_IN, AP.Time_OUT), 0)) 

Android studio Error "Unsupported Modules Detected: Compilation is not supported for following modules"

  1. Delete .idea/modules.xml
  2. Reload All Gradle Projects

You do not want to remove entire .idea directory, because it contains e.g. dictionaries and shelved changes.

Case insensitive string compare in LINQ-to-SQL

where row.name.StartsWith(q, true, System.Globalization.CultureInfo.CurrentCulture)

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

Uncomment this line (in /conf/logging.properties)

org.apache.jasper.compiler.TldLocationsCache.level = FINE

Work's for me in tomcat 7.0.53!

SyntaxError of Non-ASCII character

You should define source code encoding, add this to the top of your script:

# -*- coding: utf-8 -*-

The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:

import sys
print sys.getdefaultencoding()

Also see:

How to divide flask app into multiple py files?

Dividing the app into blueprints is a great idea. However, if this isn't enough, and if you want to then divide the Blueprint itself into multiple py files, this is also possible using the regular Python module import system, and then looping through all the routes that get imported from the other files.

I created a Gist with the code for doing this:

https://gist.github.com/Jaza/61f879f577bc9d06029e

As far as I'm aware, this is the only feasible way to divide up a Blueprint at the moment. It's not possible to create "sub-blueprints" in Flask, although there's an issue open with a lot of discussion about this:

https://github.com/mitsuhiko/flask/issues/593

Also, even if it were possible (and it's probably do-able using some of the snippets from that issue thread), sub-blueprints may be too restrictive for your use case anyway - e.g. if you don't want all the routes in a sub-module to have the same URL sub-prefix.

Determine number of pages in a PDF file

Docotic.Pdf library may be used to accomplish the task.

Here is sample code:

PdfDocument document = new PdfDocument();
document.Open("file.pdf");
int pageCount = document.PageCount;

The library will parse as little as possible so performance should be ok.

Disclaimer: I work for Bit Miracle.

html select option SELECTED

This is simple example by using ternary operator to set selected=selected

<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $key => $value) { ?>
  <option value="<?php echo $key;?>" <?php echo ($key ==  '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>

How to subtract days from a plain Date?

I made this prototype for Date so that I could pass negative values to subtract days and positive values to add days.

if(!Date.prototype.adjustDate){
    Date.prototype.adjustDate = function(days){
        var date;

        days = days || 0;

        if(days === 0){
            date = new Date( this.getTime() );
        } else if(days > 0) {
            date = new Date( this.getTime() );

            date.setDate(date.getDate() + days);
        } else {
            date = new Date(
                this.getFullYear(),
                this.getMonth(),
                this.getDate() - Math.abs(days),
                this.getHours(),
                this.getMinutes(),
                this.getSeconds(),
                this.getMilliseconds()
            );
        }

        this.setTime(date.getTime());

        return this;
    };
}

So, to use it i can simply write:

var date_subtract = new Date().adjustDate(-4),
    date_add = new Date().adjustDate(4);

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

New Direction on VS 2017 (x64 systems)

"C:\Program Files (x86)\Microsoft Visual Studio\2017\*your lic type*\Common7\IDE\WcfTestClient.exe"

How do I convert strings in a Pandas data frame to a 'date' data type?

Now you can do df['column'].dt.date

Note that for datetime objects, if you don't see the hour when they're all 00:00:00, that's not pandas. That's iPython notebook trying to make things look pretty.

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

Is it possible to specify the schema when connecting to postgres with JDBC?

I don't believe there is a way to specify the schema in the connection string. It appears you have to execute

set search_path to 'schema'

after the connection is made to specify the schema.

Facebook development in localhost

Don't have enough cred to comment on the top voted answer, but at least in my rails environment (running 4), rails s is at http://localhost:3000, not http://www.localhost:3000. When I changed it to http://localhost:3000, it worked just fine. No need to edit any hosts file.

MomentJS getting JavaScript Date in UTC

A timestamp is a point in time. Typically this can be represented by a number of milliseconds past an epoc (the Unix Epoc of Jan 1 1970 12AM UTC). The format of that point in time depends on the time zone. While it is the same point in time, the "hours value" is not the same among time zones and one must take into account the offset from the UTC.

Here's some code to illustrate. A point is time is captured in three different ways.

var moment = require( 'moment' );

var localDate = new Date();
var localMoment = moment();
var utcMoment = moment.utc();
var utcDate = new Date( utcMoment.format() );

//These are all the same
console.log( 'localData unix = ' + localDate.valueOf() );
console.log( 'localMoment unix = ' + localMoment.valueOf() );
console.log( 'utcMoment unix = ' + utcMoment.valueOf() );

//These formats are different
console.log( 'localDate = ' + localDate );
console.log( 'localMoment string = ' + localMoment.format() );
console.log( 'utcMoment string = ' + utcMoment.format() );
console.log( 'utcDate  = ' + utcDate );

//One to show conversion
console.log( 'localDate as UTC format = ' + moment.utc( localDate ).format() );
console.log( 'localDate as UTC unix = ' + moment.utc( localDate ).valueOf() );

Which outputs this:

localData unix = 1415806206570
localMoment unix = 1415806206570
utcMoment unix = 1415806206570
localDate = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localMoment string = 2014-11-12T10:30:06-05:00
utcMoment string = 2014-11-12T15:30:06+00:00
utcDate  = Wed Nov 12 2014 10:30:06 GMT-0500 (EST)
localDate as UTC format = 2014-11-12T15:30:06+00:00
localDate as UTC unix = 1415806206570

In terms of milliseconds, each are the same. It is the exact same point in time (though in some runs, the later millisecond is one higher).

As far as format, each can be represented in a particular timezone. And the formatting of that timezone'd string looks different, for the exact same point in time!

Are you going to compare these time values? Just convert to milliseconds. One value of milliseconds is always less than, equal to or greater than another millisecond value.

Do you want to compare specific 'hour' or 'day' values and worried they "came from" different timezones? Convert to UTC first using moment.utc( existingDate ), and then do operations. Examples of those conversions, when coming out of the DB, are the last console.log calls in the example.

Stop fixed position at footer

Here is the @Sang solution but without Jquery.

_x000D_
_x000D_
var socialFloat = document.querySelector('#social-float');_x000D_
var footer = document.querySelector('#footer');_x000D_
_x000D_
function checkOffset() {_x000D_
  function getRectTop(el){_x000D_
    var rect = el.getBoundingClientRect();_x000D_
    return rect.top;_x000D_
  }_x000D_
  _x000D_
  if((getRectTop(socialFloat) + document.body.scrollTop) + socialFloat.offsetHeight >= (getRectTop(footer) + document.body.scrollTop) - 10)_x000D_
    socialFloat.style.position = 'absolute';_x000D_
  if(document.body.scrollTop + window.innerHeight < (getRectTop(footer) + document.body.scrollTop))_x000D_
    socialFloat.style.position = 'fixed'; // restore when you scroll up_x000D_
  _x000D_
  socialFloat.innerHTML = document.body.scrollTop + window.innerHeight;_x000D_
}_x000D_
_x000D_
document.addEventListener("scroll", function(){_x000D_
  checkOffset();_x000D_
});
_x000D_
div.social-float-parent { width: 100%; height: 1000px; background: #f8f8f8; position: relative; }_x000D_
div#social-float { width: 200px; position: fixed; bottom: 10px; background: #777; }_x000D_
div#footer { width: 100%; height: 200px; background: #eee; }
_x000D_
<div class="social-float-parent">_x000D_
    <div id="social-float">_x000D_
        float..._x000D_
    </div>_x000D_
</div>_x000D_
<div id="footer">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Function to calculate R2 (R-squared) in R

Why not this:

rsq <- function(x, y) summary(lm(y~x))$r.squared
rsq(obs, mod)
#[1] 0.8560185

How to serialize Object to JSON?

You make the http request

HttpResponse response = httpclient.execute(httpget);           
HttpEntity entity = response.getEntity();

inputStream = entity.getContent();

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();

You read the Buffer

String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
Log.d("Result", sb.toString());
result = sb.toString();

Create a JSONObject and pass the result string to the constructor:

JSONObject json = new JSONObject(result);

Parse the json results to your desired variables:

String usuario= json.getString("usuario");
int idperon = json.getInt("idperson");
String nombre = json.getString("nombre");

Do not forget to import:

import org.json.JSONObject;

jQuery: How to get the event object in an event handler function without passing it as an argument?

Write your event handler declaration like this:

<a href="#" onclick="myFunc(event,1,2,3)">click</a>

Then your "myFunc()" function can access the event.

The string value of the "onclick" attribute is converted to a function in a way that's almost exactly the same as the browser (internally) calling the Function constructor:

theAnchor.onclick = new Function("event", theOnclickString);

(except in IE). However, because "event" is a global in IE (it's a window attribute), you'll be able to pass it to the function that way in any browser.

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

The correct way to read a data file into an array

open AAAA,"/filepath/filename.txt";
my @array = <AAAA>; # read the file into an array of lines
close AAAA;

"unrecognized selector sent to instance" error in Objective-C

Including my share. I got stuck on this for a while, until I realized I've created a project with ARC(Automatic counting reference) disabled. A quick set to YES on that option solved my issue.

How to add element in Python to the end of list using list.insert?

list.insert with any index >= len(of_the_list) places the value at the end of list. It behaves like append

Python 3.7.4
>>>lst=[10,20,30]
>>>lst.insert(len(lst), 101)
>>>lst
[10, 20, 30, 101]
>>>lst.insert(len(lst)+50, 202)
>>>lst
[10, 20, 30, 101, 202]

Time complexity, append O(1), insert O(n)

Git merge error "commit is not possible because you have unmerged files"

Since git 2.23 (August 2019) you now have a shortcut to do that: git restore --staged [filepath]. With this command, you could ignore a conflicted file without needing to add and remove that.

Example:

> git status

  ...
  Unmerged paths:
    (use "git add <file>..." to mark resolution)
      both modified:   file.ex

> git restore --staged file.ex

> git status

  ...
  Changes not staged for commit:
    (use "git add <file>..." to update what will be committed)
    (use "git restore <file>..." to discard changes in working directory)
      modified:   file.ex

how to activate a textbox if I select an other option in drop down box

Simply

<select id = 'color2'
        name = 'color'
        onchange = "if ($('#color2').val() == 'others') {
                      $('#color').show();
                    } else {
                      $('#color').hide();
                    }">
  <option value="red">RED</option>
  <option value="blue">BLUE</option>
  <option value="others">others</option>
</select>

<input type = 'text'
       name = 'color'
       id = 'color' />

edit: requires JQuery plugin

CSS transition between left -> right and top -> bottom positions

In more modern browsers (including IE 10+) you can now use calc():

.moveto {
  top: 0px;
  left: calc(100% - 50px);
}

Beamer: How to show images as step-by-step images

\includegraphics<1>{A}%
\includegraphics<2>{B}%
\includegraphics<3>{C}%

The % is important. This will keep all the images fixed.

Calculate date from week number

I have written and tested the following code and is working perfectly fine for me. Please let me know if anyone face trouble with this, I have posted a question as well in order to get the best possible answer. Someone may find it useful.

public static DateTime GetFirstDateOfWeekByWeekNumber(int year, int weekNumber)
        {
            var date = new DateTime(year, 01, 01);
            var firstDayOfYear = date.DayOfWeek;
            var result = date.AddDays(weekNumber * 7);

            if (firstDayOfYear == DayOfWeek.Monday)
                return result.Date;
            if (firstDayOfYear == DayOfWeek.Tuesday)
                return result.AddDays(-1).Date;
            if (firstDayOfYear == DayOfWeek.Wednesday)
                return result.AddDays(-2).Date;
            if (firstDayOfYear == DayOfWeek.Thursday)
                return result.AddDays(-3).Date;
            if (firstDayOfYear == DayOfWeek.Friday)
                return result.AddDays(-4).Date;
            if (firstDayOfYear == DayOfWeek.Saturday)
                return result.AddDays(-5).Date;
            return result.AddDays(-6).Date;
        }

Python def function: How do you specify the end of the function?

To be precise, a block ends when it encounter a non-empty line indented at most the same level with the start. This non empty line is not part of that block For example, the following print ends two blocks at the same time:

def foo():
    if bar:
        print "bar"

print "baz" # ends the if and foo at the same time

The indentation level is less-than-or-equal to both the def and the if, hence it ends them both.

Lines with no statement, no matter the indentation, does not matter

def foo():
    print "The line below has no indentation"

    print "Still part of foo"

But the statement that marks the end of the block must be indented at the same level as any existing indentation. The following, then, is an error:

def foo():
    print "Still correct"
   print "Error because there is no block at this indentation"

Generally, if you're used to curly braces language, just indent the code like them and you'll be fine.

BTW, the "standard" way of indenting is with spaces only, but of course tab only is possible, but please don't mix them both.

git ignore exception

Git ignores folders if you write:

/js

but it can't add exceptions if you do: !/js/jquery or !/js/jquery/ or !/js/jquery/*

You must write:

/js/* 

and only then you can except subfolders like this

!/js/jquery

Bootstrap 3 grid with no gap

Another option would be to create your own special CSS class for whenever you want to apply the "gutterless" columns..

HTML

<div class="container">
    <div class="row no-gutter">
        <div class="col-6 col-sm-6 col-lg-6">Col 1</div>
        <div class="col-6 col-sm-6 col-lg-6">Col 2</div>
    </div>
</div>

CSS

.no-gutter [class*="-6"] {
    padding-left:0;
}

Demo: http://bootply.com/73960

Extract digits from string - StringUtils Java

        String line = "This order was32354 placed for QT ! OK?";
        String regex = "[^\\d]+";

        String[] str = line.split(regex);

        System.out.println(str[1]);

Find Number of CPUs and Cores per CPU using Command Prompt

You can use the environment variable NUMBER_OF_PROCESSORS for the total number of processors:

echo %NUMBER_OF_PROCESSORS%

Why are #ifndef and #define used in C++ header files?

Those are called #include guards.

Once the header is included, it checks if a unique value (in this case HEADERFILE_H) is defined. Then if it's not defined, it defines it and continues to the rest of the page.

When the code is included again, the first ifndef fails, resulting in a blank file.

That prevents double declaration of any identifiers such as types, enums and static variables.

How to run eclipse in clean mode? what happens if we do so?

For Windows users: You can do as RTA said or through command line do this: Navigate to the locaiton of the eclipse executable then run:

 eclipse.lnk -clean

First check the name of your executable using the command 'dir' on its path

How to convert List to Json in Java

jackson provides very helpful and lightweight API to convert Object to JSON and vise versa. Please find the example code below to perform the operation

List<Output> outputList = new ArrayList<Output>();
public static void main(String[] args) {
    try {
        Output output = new Output(1,"2342");
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = objectMapper.writeValueAsString(output);
        System.out.println(jsonString);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
}

there are many other features and nice documentation for Jackson API. you can refer to the links like: https://www.journaldev.com/2324/jackson-json-java-parser-api-example-tutorial..

dependencies to include in the project are

    <!-- Jackson -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.5.1</version>
    </dependency>

Tooltip with HTML content without JavaScript

Pure CSS:

_x000D_
_x000D_
.app-tooltip {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.app-tooltip:before {_x000D_
  content: attr(data-title);_x000D_
  background-color: rgba(97, 97, 97, 0.9);_x000D_
  color: #fff;_x000D_
  font-size: 12px;_x000D_
  padding: 10px;_x000D_
  position: absolute;_x000D_
  bottom: -50px;_x000D_
  opacity: 0;_x000D_
  transition: all 0.4s ease;_x000D_
  font-weight: 500;_x000D_
  z-index: 2;_x000D_
}_x000D_
_x000D_
.app-tooltip:after {_x000D_
  content: '';_x000D_
  position: absolute;_x000D_
  opacity: 0;_x000D_
  left: 5px;_x000D_
  bottom: -16px;_x000D_
  border-style: solid;_x000D_
  border-width: 0 10px 10px 10px;_x000D_
  border-color: transparent transparent rgba(97, 97, 97, 0.9) transparent;_x000D_
  transition: all 0.4s ease;_x000D_
}_x000D_
_x000D_
.app-tooltip:hover:after,_x000D_
.app-tooltip:hover:before {_x000D_
  opacity: 1;_x000D_
}
_x000D_
<div href="#" class="app-tooltip" data-title="Your message here"> Test here</div>
_x000D_
_x000D_
_x000D_

Scrolling a div with jQuery

I know this is ages old, but upon searching for something similar this morning, and reading up on Atømix' response (as this is what we're aiming on achieving), I found this: http://www.switchonthecode.com/tutorials/using-jquery-slider-to-scroll-a-div.

Just putting that there in case anyone else needs a solution. :)

Linear Layout and weight in Android

Like answer of @Manoj Seelan

Replace android:layout_weight With android:weight.

When you use Weight with LinearLayout. you must add weightSum in LinearLayout and according to orientation of your LinearLayout you must setting 0dp for Width/Height to all LinearLayout`s Children views

Example :

If The orientation of Linearlayout is Vertical , then Set Width of all LinearLayout`s Children views with 0dp

 <LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="vertical"
     android:weightSum="3">

     <Button
        android:text="Register"
        android:id="@+id/register"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_weight="2" />

     <Button
        android:text="Not this time"
        android:id="@+id/cancel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_weight="1" />

  </LinearLayout>

If the orientation Linearlayout of is horizontal , then Set Height of all LinearLayout`s Children views with 0dp.

 <LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal"
     android:weightSum="3">

     <Button
        android:text="Register"
        android:id="@+id/register"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:padding="10dip"
        android:layout_weight="2" />

     <Button
        android:text="Not this time"
        android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:padding="10dip"
        android:layout_weight="1" />

  </LinearLayout>

Can we instantiate an abstract class?

Extending a class doesn't mean that you are instantiating the class. Actually, in your case you are creating an instance of the subclass.

I am pretty sure that abstract classes do not allow initiating. So, I'd say no: you can't instantiate an abstract class. But, you can extend it / inherit it.

You can't directly instantiate an abstract class. But it doesn't mean that you can't get an instance of class (not actully an instance of original abstract class) indirectly. I mean you can not instantiate the orginial abstract class, but you can:

  1. Create an empty class
  2. Inherit it from abstract class
  3. Instantiate the dervied class

So you get access to all the methods and properties in an abstract class via the derived class instance.

What is the use of the @ symbol in PHP?

It suppresses errors.

See Error Control Operators in the manual:

PHP supports one error control operator: the at sign (@). When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored.

If you have set a custom error handler function with set_error_handler() then it will still get called, but this custom error handler can (and should) call error_reporting() which will return 0 when the call that triggered the error was preceded by an @...

Oracle 11g Express Edition for Windows 64bit?

Some of more advanced Oracle database features such as session trace do not work properly in Oracle 11g XE 32-bit if installed on Windows 64-bit system. I needed session trace on Windows 7 64-bit.

Apart from that it works well for me in multiple production MS Windows 64-bit systems: Windows Server 2008 R2 and Windows Server 2003 R2.

How do I get the name of the active user via the command line in OS X?

I'm pretty sure the terminal in OS X is just like unix, so the command would be:

whoami

I don't have a mac on me at the moment so someone correct me if I'm wrong.

NOTE - The whoami utility has been obsoleted, and is equivalent to id -un. It will give you the current user

find . -type f -exec chmod 644 {} ;

A good alternative is this:

find . -type f | xargs chmod -v 644

and for directories:

find . -type d | xargs chmod -v 755

and to be more explicit:

find . -type f | xargs -I{} chmod -v 644 {}

How to Join to first row

I know this question was answered a while ago, but when dealing with large data sets, nested queries can be costly. Here is a different solution where the nested query will only be ran once, instead of for each row returned.

SELECT 
  Orders.OrderNumber,
  LineItems.Quantity, 
  LineItems.Description
FROM 
  Orders
  INNER JOIN (
    SELECT
      Orders.OrderNumber,
      Max(LineItem.LineItemID) AS LineItemID
    FROM
      Orders INNER JOIN LineItems
      ON Orders.OrderNumber = LineItems.OrderNumber
    GROUP BY Orders.OrderNumber
  ) AS Items ON Orders.OrderNumber = Items.OrderNumber
  INNER JOIN LineItems 
  ON Items.LineItemID = LineItems.LineItemID

Possible to extend types in Typescript?

May be below approach will be helpful for someone TS with reactjs

interface Event {
   name: string;
   dateCreated: string;
   type: string;
}

interface UserEvent<T> extends Event<T> {
    UserId: string;
}

How can I create a Java method that accepts a variable number of arguments?

You can pass all similar type values in the function while calling it. In the function definition put a array so that all the passed values can be collected in that array. e.g. .

static void demo (String ... stringArray) {
  your code goes here where read the array stringArray
}

Unix command to check the filesize

ls -l --block-size=M 

will give you a long format listing (needed to actually see the file size) and round file sizes up to the nearest MiB. If you want MB (10^6 bytes) rather than MiB (2^20 bytes) units, use --block-size=MB instead.

Or

ls -lah 

-h When used with the -l option, use unit suffixes: Byte, Kilobyte, Megabyte, Gigabyte, Terabyte and Petabyte in order to reduce the number of digits to three or less using base 2 for sizes.

man ls

http://unixhelp.ed.ac.uk/CGI/man-cgi?ls

"Parameter not valid" exception loading System.Drawing.Image

I had the same problem and apparently is solved now, despite this and some other gdi+ exceptions are very misleading, I found that actually the problem was that the parameter being sent to a Bitmap constructor was not valid. I have this code:

using (System.IO.FileStream fs = new System.IO.FileStream(inputImage, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite))
{
    try
    {
        using (Bitmap bitmap = (Bitmap)Image.FromStream(fs, true, false))
        {
            try
            {
                bitmap.Save(OutputImage + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                GC.Collect();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
    catch (ArgumentException aex)
    {
        throw new Exception("The file received from the Map Server is not a valid jpeg image", aex);
    }
}

The following line was causing an error:

Bitmap bitmap = (Bitmap)Image.FromStream(fs, true, false)

The file stream was built from the file downloaded from the Map Server. My app was sending the request incorrectly to get the image, and the server was returning something with the jpg extension, but was actually a html telling me that an error ocurred. So I was taking that image and trying to build a Bitmap with it. The fix was to control/ validate the image for a valid jpeg image.

Hope it helps!

XSLT string replace

Here is the XSLT function which will work similar to the String.Replace() function of C#.

This template has the 3 Parameters as below

text :- your main string

replace :- the string which you want to replace

by :- the string which will reply by new string

Below are the Template

<xsl:template name="string-replace-all">
  <xsl:param name="text" />
  <xsl:param name="replace" />
  <xsl:param name="by" />
  <xsl:choose>
    <xsl:when test="contains($text, $replace)">
      <xsl:value-of select="substring-before($text,$replace)" />
      <xsl:value-of select="$by" />
      <xsl:call-template name="string-replace-all">
        <xsl:with-param name="text" select="substring-after($text,$replace)" />
        <xsl:with-param name="replace" select="$replace" />
        <xsl:with-param name="by" select="$by" />
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of select="$text" />
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

Below sample shows how to call it

<xsl:variable name="myVariable ">
  <xsl:call-template name="string-replace-all">
    <xsl:with-param name="text" select="'This is a {old} text'" />
    <xsl:with-param name="replace" select="'{old}'" />
    <xsl:with-param name="by" select="'New'" />
  </xsl:call-template>
</xsl:variable>

You can also refer the below URL for the details.

Mac OS X and multiple Java versions

The cleanest way to manage multiple java versions on Mac is to use Homebrew.

And within Homebrew, use:

  • homebrew-cask to install the versions of java
  • jenv to manage the installed versions of java

As seen on http://hanxue-it.blogspot.ch/2014/05/installing-java-8-managing-multiple.html , these are the steps to follow.

  1. install homebrew
  2. install homebrew jenv
  3. install homebrew-cask
  4. install a specific java version using cask (see "homebrew-cask versions" paragraph below)
  5. add this version for jenv to manage it
  6. check the version is correctly managed by jenv
  7. repeat steps 4 to 6 for each version of java you need

homebrew-cask versions

Add the homebrew/cask-versions tap to homebrew using:

brew tap homebrew/cask-versions

Then you can look at all the versions available:

brew search java

Then you can install the version(s) you like:

brew cask install java7
brew cask install java6

And add them to be managed by jenv as usual.

jenv add <javaVersionPathHere>

I think this is the cleanest & simplest way to go about it.


Another important thing to note, as mentioned in Mac OS X 10.6.7 Java Path Current JDK confusing :

For different types of JDKs or installations, you will have different paths

You can check the paths of the versions installed using /usr/libexec/java_home -V, see How do I check if the Java JDK is installed on Mac?

On Mac OS X Mavericks, I found as following:

1) Built-in JRE default: /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home

2) JDKs downloaded from Apple: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/

3) JDKs downloaded from Oracle: /Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home


Resources

NSRange from Swift Range?

Swift 4

I think, there are two ways.

1. NSRange(range, in: )

2. NSRange(location:, length: )

Sample code:

let attributedString = NSMutableAttributedString(string: "Sample Text 12345", attributes: [.font : UIFont.systemFont(ofSize: 15.0)])

// NSRange(range, in: )
if let range = attributedString.string.range(of: "Sample")  {
    attributedString.addAttribute(.foregroundColor, value: UIColor.orange, range: NSRange(range, in: attributedString.string))
}

// NSRange(location: , length: )
if let range = attributedString.string.range(of: "12345") {
    attributedString.addAttribute(.foregroundColor, value: UIColor.green, range: NSRange(location: range.lowerBound.encodedOffset, length: range.upperBound.encodedOffset - range.lowerBound.encodedOffset))
}

Screen Shot: enter image description here

Bash checking if string does not contain other string

As mainframer said, you can use grep, but i would use exit status for testing, try this:

#!/bin/bash
# Test if anotherstring is contained in teststring
teststring="put you string here"
anotherstring="string"

echo ${teststring} | grep --quiet "${anotherstring}"
# Exit status 0 means anotherstring was found
# Exit status 1 means anotherstring was not found

if [ $? = 1 ]
then
  echo "$anotherstring was not found"
fi

Android: how to create Switch case from this?

@Override
public void onClick(View v)
{
    switch (v.getId())
    {
        case R.id.:

            break;
        case R.id.:

            break;
        default:
            break;
    }
}

Input mask for numeric and decimal

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

How to uninstall jupyter

When you $ pip install jupyter several dependencies are installed. The best way to uninstall it completely is by running:

  1. $ pip install pip-autoremove
  2. $ pip-autoremove jupyter -y

Kindly refer to this related question.

pip-autoremove removes a package and its unused dependencies. Here are the docs.

jquery json to string?

Most browsers have a native JSON object these days, which includes parse and stringify methods. So just try JSON.stringify({}) and see if you get "{}". You can even pass in parameters to filter out keys or to do pretty-printing, e.g. JSON.stringify({a:1,b:2}, null, 2) puts a newline and 2 spaces in front of each key.

JSON.stringify({a:1,b:2}, null, 2)

gives

"{\n  \"a\": 1,\n  \"b\": 2\n}"

which prints as

{
  "a": 1,
  "b": 2
}

As for the messing around part of your question, use the second parameter. From http://www.javascriptkit.com/jsref/json.shtml :

The replacer parameter can either be a function or an array of String/Numbers. It steps through each member within the JSON object to let you decide what value each member should be changed to. As a function it can return:

  • A number, string, or Boolean, which replaces the property's original value with the returned one.
  • An object, which is serialized then returned. Object methods or functions are not allowed, and are removed instead.
  • Null, which causes the property to be removed.

As an array, the values defined inside it corresponds to the names of the properties inside the JSON object that should be retained when converted into a JSON object.

Auto margins don't center image in page

add display:block; and it'll work. Images are inline by default

To clarify, the default width for a block element is auto, which of course fills the entire available width of the containing element.

By setting the margin to auto, the browser assigns half the remaining space to margin-left and the other half to margin-right.

How to run sql script using SQL Server Management Studio?

Open SQL Server Management Studio > File > Open > File > Choose your .sql file (the one that contains your script) > Press Open > the file will be opened within SQL Server Management Studio, Now all what you need to do is to press Execute button.

Copy Paste Values only( xlPasteValues )

you may use this:

Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False

What does AngularJS do better than jQuery?

Data-Binding

You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).

This is a good understanding of data-binding. I think you've got that down.

DOM Manipulation

For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.

I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.

I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.

This is the markup we want to use. I gave it an intuitive name.

<div rotate-on-click="45"></div>

First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.

Implementation with jQuery

live demo here (click).

function rotate(deg, elem) {
  $(elem).css({
    webkitTransform: 'rotate('+deg+'deg)', 
    mozTransform: 'rotate('+deg+'deg)', 
    msTransform: 'rotate('+deg+'deg)', 
    oTransform: 'rotate('+deg+'deg)', 
    transform: 'rotate('+deg+'deg)'    
  });
}

function addRotateOnClick($elems) {
  $elems.each(function(i, elem) {
    var deg = 0;
    $(elem).click(function() {
      deg+= parseInt($(this).attr('rotate-on-click'), 10);
      rotate(deg, this);
    });
  });
}

addRotateOnClick($('[rotate-on-click]'));

Implementation with Angular

live demo here (click).

app.directive('rotateOnClick', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var deg = 0;
      element.bind('click', function() {
        deg+= parseInt(attrs.rotateOnClick, 10);
        element.css({
          webkitTransform: 'rotate('+deg+'deg)', 
          mozTransform: 'rotate('+deg+'deg)', 
          msTransform: 'rotate('+deg+'deg)', 
          oTransform: 'rotate('+deg+'deg)', 
          transform: 'rotate('+deg+'deg)'    
        });
      });
    }
  };
});

Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link function (or compile function).

Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.

This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?

General differences.

The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.

Angular and jQuery can't reasonably be compared.

Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:

Why use a framework?

Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.

Here are some things that modern frameworks are providing:

  • Templating
  • Data-binding
  • routing (single page app)
  • clean, modular, reusable architecture
  • security
  • additional functions/features for convenience

Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.

If you need to destroy a planet and you have a Death Star, use the Death star.

Angular (revisited).

Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.

DOM reference.

In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:

<clock></clock>

Done.

Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.

MVW Architecure / Modules / Dependency Injection

Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.

It isn't easy to make things "work" in Angular.

THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.

Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.

HTTP Ajax Request via HTTPS Page

This is not possible due to the Same Origin Policy.

You will need to switch the Ajax requests to https, too.

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

Getting unique values in Excel by using formulas only

Solution

I created a function in VBA for you, so you can do this now in an easy way.
Create a VBA code module (macro) as you can see in this tutorial.

  1. Press Alt+F11
  2. Click to Module in Insert.
  3. Paste code.
  4. If Excel says that your file format is not macro friendly than save it as Excel Macro-Enabled in Save As.

Source code

Function listUnique(rng As Range) As Variant
    Dim row As Range
    Dim elements() As String
    Dim elementSize As Integer
    Dim newElement As Boolean
    Dim i As Integer
    Dim distance As Integer
    Dim result As String

    elementSize = 0
    newElement = True

    For Each row In rng.Rows
        If row.Value <> "" Then
            newElement = True
            For i = 1 To elementSize Step 1
                If elements(i - 1) = row.Value Then
                    newElement = False
                End If
            Next i
            If newElement Then
                elementSize = elementSize + 1
                ReDim Preserve elements(elementSize - 1)
                elements(elementSize - 1) = row.Value
            End If
        End If
    Next

    distance = Range(Application.Caller.Address).row - rng.row

    If distance < elementSize Then
        result = elements(distance)
        listUnique = result
    Else
        listUnique = ""
    End If
End Function

Usage

Just enter =listUnique(range) to a cell. The only parameter is range that is an ordinary Excel range. For example: A$1:A$28 or H$8:H$30.

Conditions

  • The range must be a column.
  • The first cell where you call the function must be in the same row where the range starts.

Example

Regular case

  1. Enter data and call function.
    Enter data and call function
  2. Grow it.
    Grow it
  3. Voilà.
    Voilà

Empty cell case

It works in columns that have empty cells in them. Also the function outputs nothing (not errors) if you overwind the cells (calling the function) into places where should be no output, as I did it in the previous example's "2. Grow it" part.

Empty cell case

window.onload vs document.onload

The general idea is that window.onload fires when the document's window is ready for presentation and document.onload fires when the DOM tree (built from the markup code within the document) is completed.

Ideally, subscribing to DOM-tree events, allows offscreen-manipulations through Javascript, incurring almost no CPU load. Contrarily, window.onload can take a while to fire, when multiple external resources have yet to be requested, parsed and loaded.

?Test scenario:

To observe the difference and how your browser of choice implements the aforementioned event handlers, simply insert the following code within your document's - <body>- tag.

<script language="javascript">
window.tdiff = []; fred = function(a,b){return a-b;};
window.document.onload = function(e){ 
    console.log("document.onload", e, Date.now() ,window.tdiff,  
    (window.tdiff[0] = Date.now()) && window.tdiff.reduce(fred) ); 
}
window.onload = function(e){ 
    console.log("window.onload", e, Date.now() ,window.tdiff, 
    (window.tdiff[1] = Date.now()) && window.tdiff.reduce(fred) ); 
}
</script>

?Result:

Here is the resulting behavior, observable for Chrome v20 (and probably most current browsers).

  • No document.onload event.
  • onload fires twice when declared inside the <body>, once when declared inside the <head> (where the event then acts as document.onload ).
  • counting and acting dependent on the state of the counter allows to emulate both event behaviors.
  • Alternatively declare the window.onload event handler within the confines of the HTML-<head> element.

?Example Project:

The code above is taken from this project's codebase (index.html and keyboarder.js).


For a list of event handlers of the window object, please refer to the MDN documentation.

How to use support FileProvider for sharing content to other apps?

I want to share something that blocked us for a couple of days: the fileprovider code MUST be inserted between the application tags, not after it. It may be trivial, but it's never specified, and I thought that I could have helped someone! (thanks again to piolo94)

What is the benefit of zerofill in MySQL?

ZEROFILL

This essentially means that if the integer value 23 is inserted into an INT column with the width of 8 then the rest of the available position will be automatically padded with zeros.

Hence

23

becomes:

00000023

For..In loops in JavaScript - key value pairs

let test = {a: 1, b: 2, c: 3};
Object.entries(test).forEach(([key, value]) => console.log(key, value))

// a 1
// b 2
// c 3

How to get user name using Windows authentication in asp.net?

You can read the Name from WindowsIdentity:

var user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
return Ok(user);

I want to delete all bin and obj folders to force all projects to rebuild everything

To delete bin and obj before build add to project file:

<Target Name="BeforeBuild">
    <!-- Remove obj folder -->
    <RemoveDir Directories="$(BaseIntermediateOutputPath)" />
    <!-- Remove bin folder -->
    <RemoveDir Directories="$(BaseOutputPath)" />
</Target>

Here is article: How to remove bin and/or obj folder before the build or deploy

Microsoft.ACE.OLEDB.12.0 provider is not registered

I'm having same problem. I try to install office 2010 64bit on windows 7 64 bit and then install 2007 Office System Driver : Data Connectivity Components.

after that, visual studio 2008 can opens a connection to an MS-Access 2007 database file.

How to make a view with rounded corners?

In Android L you will be able to just use View.setClipToOutline to get that effect. In previous versions there is no way to just clip the contents of a random ViewGroup in a certain shape.

You will have to think of something that would give you a similar effect:

  • If you only need rounded corners in the ImageView, you can use a shader to 'paint' the image over the shape you are using as background. Take a look at this library for an example.

  • If you really need every children to be clipped, maybe you can another view over your layout? One with a background of whatever color you are using, and a round 'hole' in the middle? You could actually create a custom ViewGroup that draws that shape over every children overriding the onDraw method.

Is there a Python caching library?

I think the python memcached API is the prevalent tool, but I haven't used it myself and am not sure whether it supports the features you need.

What is the difference between H.264 video and MPEG-4 video?

H.264 is a new standard for video compression which has more advanced compression methods than the basic MPEG-4 compression. One of the advantages of H.264 is the high compression rate. It is about 1.5 to 2 times more efficient than MPEG-4 encoding. This high compression rate makes it possible to record more information on the same hard disk.
The image quality is also better and playback is more fluent than with basic MPEG-4 compression. The most interesting feature however is the lower bit-rate required for network transmission.
So the 3 main advantages of H.264 over MPEG-4 compression are:
- Small file size for longer recording time and better network transmission.
- Fluent and better video quality for real time playback
- More efficient mobile surveillance application

H264 is now enshrined in MPEG4 as part 10 also known as AVC

Refer to: http://www.velleman.eu/downloads/3/h264_vs_mpeg4_en.pdf

Hope this helps.

extract the date part from DateTime in C#

When comparing only the date of the datatimes, use the Date property. So this should work fine for you

datetime1.Date == datetime2.Date

Python: Select subset from list based on index set

Use the built in function zip

property_asel = [a for (a, truth) in zip(property_a, good_objects) if truth]

EDIT

Just looking at the new features of 2.7. There is now a function in the itertools module which is similar to the above code.

http://docs.python.org/library/itertools.html#itertools.compress

itertools.compress('ABCDEF', [1,0,1,0,1,1]) =>
  A, C, E, F

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

None of the above worked out for me until I changed the Action as [HttpPost]. and made the ajax type as POST.

    [HttpPost]
    public JsonResult GetSelectedSignalData(string signal1,...)
    {
         JsonResult result = new JsonResult();
         var signalData = GetTheData();
         try
         {
              var serializer = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };

            result.Data = serializer.Serialize(signalData);
            return Json(result, JsonRequestBehavior.AllowGet);
            ..
            ..
            ...

    }

And the ajax call as

$.ajax({
    type: "POST",
    url: some_url,
    data: JSON.stringify({  signal1: signal1,.. }),
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        if (data !== null) {
            setValue();
        }

    },
    failure: function (data) {
        $('#errMessage').text("Error...");
    },
    error: function (data) {
        $('#errMessage').text("Error...");
    }
});

Update a column value, replacing part of a string

UPDATE urls
SET url = REPLACE(url, 'domain1.com/images/', 'domain2.com/otherfolder/')

Can overridden methods differ in return type?

yes It is possible.. returns type can be different only if parent class method return type is
a super type of child class method return type..
means

class ParentClass {
    public Circle() method1() {
        return new Cirlce();
    }
}

class ChildClass extends ParentClass {
    public Square method1() {
        return new Square();
    }
}

Class Circle {

}

class Square extends Circle {

}


If this is the then different return type can be allowed...

Best way to add Gradle support to IntelliJ Project

Just as a future reference, if you already have a Maven project all you need to do is doing a gradle init in your project directory which will generates build.gradle and other dependencies, then do a gradle build in the same directory.

Iterating through a variable length array

for(int i = 0; i < array.length; i++)
{
    System.out.println(array[i]);
}

or

for(String value : array)
{
    System.out.println(value);
}

The second version is a "for-each" loop and it works with arrays and Collections. Most loops can be done with the for-each loop because you probably don't care about the actual index. If you do care about the actual index us the first version.

Just for completeness you can do the while loop this way:

int index = 0;

while(index < myArray.length)
{
  final String value;

  value = myArray[index];
  System.out.println(value);
  index++;
}

But you should use a for loop instead of a while loop when you know the size (and even with a variable length array you know the size... it is just different each time).

Finding the 'type' of an input element

If you want to check the type of input within form, use the following code:

<script>
    function getFind(obj) {
    for (i = 0; i < obj.childNodes.length; i++) {
        if (obj.childNodes[i].tagName == "INPUT") {
            if (obj.childNodes[i].type == "text") {
                alert("this is Text Box.")
            }
            if (obj.childNodes[i].type == "checkbox") {
                alert("this is CheckBox.")
            }
            if (obj.childNodes[i].type == "radio") {
                alert("this is Radio.")
            }
        }
        if (obj.childNodes[i].tagName == "SELECT") {
            alert("this is Select")
        }
    }
}
</script>     

<script>    
    getFind(document.myform);  
</script>

Flutter: Trying to bottom-center an item in a Column, but it keeps left-aligning

Widget _bottom() {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Expanded(
          child: Container(
            color: Colors.amberAccent,
            width: double.infinity,
            child: SingleChildScrollView(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: new List<int>.generate(50, (index) => index + 1)
                    .map((item) {
                  return Text(
                    item.toString(),
                    style: TextStyle(fontSize: 20),
                  );
                }).toList(),
              ),
            ),
          ),
        ),
        Container(
          color: Colors.blue,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'BoTToM',
                textAlign: TextAlign.center,
                style: TextStyle(fontSize: 33),
              ),
            ],
          ),
        ),
      ],
    );
  }

Python concatenate text files

If you have a lot of files in the directory then glob2 might be a better option to generate a list of filenames rather than writing them by hand.

import glob2

filenames = glob2.glob('*.txt')  # list of all .txt files in the directory

with open('outfile.txt', 'w') as f:
    for file in filenames:
        with open(file) as infile:
            f.write(infile.read()+'\n')

display:inline vs display:block

Display:block It very much behaves the same way as 'p' tags and it takes up the entire row and there can't be any element next to it until it's floated. Display:inline It's just uses as much space as required and allows other elements to be aligned alongside itself.

Use these properties in case of forms and you will get a better understanding.

How to remove specific elements in a numpy array

To delete by value :

modified_array = np.delete(original_array, np.where(original_array == value_to_delete))

How do I turn off the output from tar commands on Unix?

Just drop the option v.

-v is for verbose. If you don't use it then it won't display:

tar -zxf tmp.tar.gz -C ~/tmp1

How to inject JPA EntityManager using spring

Yes, although it's full of gotchas, since JPA is a bit peculiar. It's very much worth reading the documentation on injecting JPA EntityManager and EntityManagerFactory, without explicit Spring dependencies in your code:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa

This allows you to either inject the EntityManagerFactory, or else inject a thread-safe, transactional proxy of an EntityManager directly. The latter makes for simpler code, but means more Spring plumbing is required.

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

import android packages cannot be resolved

May be you are using this checking :

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
}

To resolve this you need to import android.provider.DocumentsContract class.

To resolve this issue you'll need to set the build SDK version to 19 (4.4) or higher to have API level 19 symbols available while compiling.

First, use the SDK Manager to download API 19 if you don't have it yet. Then, configure your project to use API 19:

  • In Android Studio: File -> Project Structure -> General Settings -> Project SDK.
  • In Eclipse ADT: Project Properties -> Android -> Project Build Target

I found this answer from here

Thanks .

Matplotlib transparent line plots

Plain and simple:

plt.plot(x, y, 'r-', alpha=0.7)

(I know I add nothing new, but the straightforward answer should be visible).

How can I add some small utility functions to my AngularJS application?

The easiest way to add utility functions is to leave them at the global level:

function myUtilityFunction(x) { return "do something with "+x; }

Then, the simplest way to add a utility function (to a controller) is to assign it to $scope, like this:

$scope.doSomething = myUtilityFunction;

Then you can call it like this:

{{ doSomething(x) }}

or like this:

ng-click="doSomething(x)"

EDIT:

The original question is if the best way to add a utility function is through a service. I say no, if the function is simple enough (like the isNotString() example provided by the OP).

The benefit of writing a service is to replace it with another (via injection) for the purpose of testing. Taken to an extreme, do you need to inject every single utility function into your controller?

The documentation says to simply define behavior in the controller (like $scope.double): http://docs.angularjs.org/guide/controller

C# Ignore certificate errors?

If you are using sockets directly and are authenticating as the client, then the Service Point Manager callback method won't work. Here's what did work for me. PLEASE USE FOR TESTING PURPOSES ONLY.

var activeStream = new SslStream(networkStream, false, (a, b, c, d) => { return true; });
await activeStream.AuthenticateAsClientAsync("computer.local");

The key here, is to provide the remote certificate validation callback right in the constructor of the SSL stream.

How to pass arguments to addEventListener listener function?

There is absolutely nothing wrong with the code you've written. Both some_function and someVar should be accessible, in case they were available in the context where anonymous

function() { some_function(someVar); } 

was created.

Check if the alert gives you the value you've been looking for, be sure it will be accessible in the scope of anonymous function (unless you have more code that operates on the same someVar variable next to the call to addEventListener)

var someVar; 
someVar = some_other_function();
alert(someVar);
someObj.addEventListener("click", function(){
    some_function(someVar);
}, false);

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

I had to go look for ojdbc compatible with version on oracle that was installed this fixed my problem, my bad was thinking one ojdbc would work for all

Error "package android.support.v7.app does not exist"

Using Android Studio you have to add the dependency of the support library that was not indicated in the tutorial

dependencies {

    implementation 'com.android.support:appcompat-v7:22.0.0'
}

Regular expression to find URLs within a string

None of the solutions provided here solved the problems/use-cases I had.

What I have provided here, is the best I have found/made so far. I will update it when I find new edge-cases that it doesn't handle.

\b
  #Word cannot begin with special characters
  (?<![@.,%&#-])
  #Protocols are optional, but take them with us if they are present
  (?<protocol>\w{2,10}:\/\/)?
  #Domains have to be of a length of 1 chars or greater
  ((?:\w|\&\#\d{1,5};)[.-]?)+
  #The domain ending has to be between 2 to 15 characters
  (\.([a-z]{2,15})
       #If no domain ending we want a port, only if a protocol is specified
       |(?(protocol)(?:\:\d{1,6})|(?!)))
\b
#Word cannot end with @ (made to catch emails)
(?![@])
#We accept any number of slugs, given we have a char after the slash
(\/)?
#If we have endings like ?=fds include the ending
(?:([\w\d\?\-=#:%@&.;])+(?:\/(?:([\w\d\?\-=#:%@&;.])+))*)?
#The last char cannot be one of these symbols .,?!,- exclude these
(?<![.,?!-])

How to read single Excel cell value

Please try this. Maybe this could help you. It works for me.

string sValue = (range.Cells[_row, _column] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
//_row,_column your column & row number 
//eg: string sValue = (sheet.Cells[i + 9, 12] as Microsoft.Office.Interop.Excel.Range).Value2.ToString();
//sValue has your value

How to calculate cumulative normal distribution?

Alex's answer shows you a solution for standard normal distribution (mean = 0, standard deviation = 1). If you have normal distribution with mean and std (which is sqr(var)) and you want to calculate:

from scipy.stats import norm

# cdf(x < val)
print norm.cdf(val, m, s)

# cdf(x > val)
print 1 - norm.cdf(val, m, s)

# cdf(v1 < x < v2)
print norm.cdf(v2, m, s) - norm.cdf(v1, m, s)

Read more about cdf here and scipy implementation of normal distribution with many formulas here.

How can I fetch all items from a DynamoDB table without specifying the primary key?

Amazon DynamoDB provides the Scan operation for this purpose, which returns one or more items and its attributes by performing a full scan of a table. Please be aware of the following two constraints:

  • Depending on your table size, you may need to use pagination to retrieve the entire result set:

    Note
    If the total number of scanned items exceeds the 1MB limit, the scan stops and results are returned to the user with a LastEvaluatedKey to continue the scan in a subsequent operation. The results also include the number of items exceeding the limit. A scan can result in no table data meeting the filter criteria.

    The result set is eventually consistent.

  • The Scan operation is potentially costly regarding both performance and consumed capacity units (i.e. price), see section Scan and Query Performance in Query and Scan in Amazon DynamoDB:

    [...] Also, as a table grows, the scan operation slows. The scan operation examines every item for the requested values, and can use up the provisioned throughput for a large table in a single operation. For quicker response times, design your tables in a way that can use the Query, Get, or BatchGetItem APIs, instead. Or, design your application to use scan operations in a way that minimizes the impact on your table's request rate. For more information, see Provisioned Throughput Guidelines in Amazon DynamoDB. [emphasis mine]

You can find more details about this operation and some example snippets in Scanning Tables Using the AWS SDK for PHP Low-Level API for Amazon DynamoDB, with the most simple example illustrating the operation being:

$dynamodb = new AmazonDynamoDB();

$scan_response = $dynamodb->scan(array(
    'TableName' => 'ProductCatalog' 
));

foreach ($scan_response->body->Items as $item)
{
    echo "<p><strong>Item Number:</strong>"
         . (string) $item->Id->{AmazonDynamoDB::TYPE_NUMBER};
    echo "<br><strong>Item Name: </strong>"
         . (string) $item->Title->{AmazonDynamoDB::TYPE_STRING} ."</p>";
}

How to get all selected values from <select multiple=multiple>?

Works everywhere without jquery:

var getSelectValues = function (select) {
    var ret = [];

    // fast but not universally supported
    if (select.selectedOptions != undefined) {
        for (var i=0; i < select.selectedOptions.length; i++) {
            ret.push(select.selectedOptions[i].value);
        }

    // compatible, but can be painfully slow
    } else {
        for (var i=0; i < select.options.length; i++) {
            if (select.options[i].selected) {
                ret.push(select.options[i].value);
            }
        }
    }
    return ret;
};

How do I get the position selected in a RecyclerView?

Personally, the simplest way that I have found and works great for me is as follows:

Create an interface inside your "RecycleAdapter" Class (Subclass)

public interface ClickCallback {
    void onItemClick(int position);
}

Add a variable of the interface as a parameter in the Constructor.

private String[] items;
private ClickCallback callback;

public RecyclerAdapter(String[] items, ClickCallback clickCallback) {
    this.items = items;
    this.callback = clickCallback;
}

Set a Click listener in the ViewHolder (another subclass) and pass the 'position' to through the interface

    AwesomeViewHolder(View itemView) {
        super(itemView);
        itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                callback.onItemClick(getAdapterPosition());
            }
        });
        mTextView = (TextView) itemView.findViewById(R.id.mTextView);
    }

Now, when initializing the recycler adapter in an activity/fragment, just Create a new 'ClickCallback' (interface)

String[] values = {"Hello","World"};
RecyclerAdapter recyclerAdapter = new RecyclerAdapter(values, new RecyclerAdapter.ClickCallback() {
    @Override
    public void onItemClick(int position) {
         // Do anything with the item position
    }
});

That's it for me. :)

Pretty-print a Map in Java

I guess something like this would be cleaner, and provide you with more flexibility with the output format (simply change template):

    String template = "%s=\"%s\",";
    StringBuilder sb = new StringBuilder();
    for (Entry e : map.entrySet()) {
        sb.append(String.format(template, e.getKey(), e.getValue()));
    }
    if (sb.length() > 0) {
        sb.deleteCharAt(sb.length() - 1); // Ugly way to remove the last comma
    }
    return sb.toString();

I know having to remove the last comma is ugly, but I think it's cleaner than alternatives like the one in this solution or manually using an iterator.

create multiple tag docker image

You can't create tags with Dockerfiles but you can create multiple tags on your images via the command line.

Use this to list your image ids:

$ docker images

Then tag away:

$ docker tag 9f676bd305a4 ubuntu:13.10
$ docker tag 9f676bd305a4 ubuntu:saucy
$ docker tag eb601b8965b8 ubuntu:raring
...

How to get input text value on click in ReactJS

First of all, you can't pass to alert second argument, use concatenation instead

alert("Input is " + inputValue);

Example

However in order to get values from input better to use states like this

_x000D_
_x000D_
var MyComponent = React.createClass({_x000D_
  getInitialState: function () {_x000D_
    return { input: '' };_x000D_
  },_x000D_
_x000D_
  handleChange: function(e) {_x000D_
    this.setState({ input: e.target.value });_x000D_
  },_x000D_
_x000D_
  handleClick: function() {_x000D_
    console.log(this.state.input);_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <input type="text" onChange={ this.handleChange } />_x000D_
        <input_x000D_
          type="button"_x000D_
          value="Alert the text input"_x000D_
          onClick={this.handleClick}_x000D_
        />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
  <MyComponent />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

Strip spaces/tabs/newlines - python

import re

mystr = "I want to Remove all white \t spaces, new lines \n and tabs \t"
print re.sub(r"\W", "", mystr)

Output : IwanttoRemoveallwhitespacesnewlinesandtabs

Curl setting Content-Type incorrectly

I think you want to specify

-H "Content-Type:text/xml"

with a colon, not an equals.

Java Try Catch Finally blocks without Catch

If any of the code in the try block can throw a checked exception, it has to appear in the throws clause of the method signature. If an unchecked exception is thrown, it's bubbled out of the method.

The finally block is always executed, whether an exception is thrown or not.

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

Did something like that once:

CREATE TABLE exclusions(excl VARCHAR(250));
INSERT INTO exclusions(excl)
VALUES
       ('%timeline%'),
       ('%Placeholders%'),
       ('%Stages%'),
       ('%master_stage_1205x465%'),
       ('%Accessories%'),
       ('%chosen-sprite.png'),
('%WebResource.axd');
GO
CREATE VIEW ToBeDeleted AS 
SELECT * FROM chunks
       WHERE chunks.file_id IN
       (
       SELECT DISTINCT
             lf.file_id
       FROM LargeFiles lf
       WHERE lf.file_id NOT IN
             (
             SELECT DISTINCT
                    lf.file_id
             FROM LargeFiles lf
                LEFT JOIN exclusions e ON(lf.URL LIKE e.excl)
                WHERE e.excl IS NULL
             )
       );
GO
CHECKPOINT
GO
SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;
WHILE @r>0

BEGIN
    DELETE TOP (10000) FROM ToBeDeleted;
    SET @r = @@ROWCOUNT  
END
GO

Printing all global variables/local variables?

Type info variables to list "All global and static variable names".

Type info locals to list "Local variables of current stack frame" (names and values), including static variables in that function.

Type info args to list "Arguments of the current stack frame" (names and values).

Removing character in list of strings

lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")...]

msg = filter(lambda x : x != "8", lst)

print msg

EDIT: For anyone who came across this post, just for understanding the above removes any elements from the list which are equal to 8.

Supposing we use the above example the first element ("aaaaa8") would not be equal to 8 and so it would be dropped.

To make this (kinda work?) with how the intent of the question was we could perform something similar to this

msg = filter(lambda x: x != "8", map(lambda y: list(y), lst))
  • I am not in an interpreter at the moment so of course mileage may vary, we may have to index so we do list(y[0]) would be the only modification to the above for this explanation purposes.

What this does is split each element of list up into an array of characters so ("aaaa8") would become ["a", "a", "a", "a", "8"].

This would result in a data type that looks like this

msg = [["a", "a", "a", "a"], ["b", "b"]...]

So finally to wrap that up we would have to map it to bring them all back into the same type roughly

msg = list(map(lambda q: ''.join(q), filter(lambda x: x != "8", map(lambda y: list(y[0]), lst))))

I would absolutely not recommend it, but if you were really wanting to play with map and filter, that would be how I think you could do it with a single line.

Sending "User-agent" using Requests library in Python

The user-agent should be specified as a field in the header.

Here is a list of HTTP header fields, and you'd probably be interested in request-specific fields, which includes User-Agent.

If you're using requests v2.13 and newer

The simplest way to do what you want is to create a dictionary and specify your headers directly, like so:

import requests

url = 'SOME URL'

headers = {
    'User-Agent': 'My User Agent 1.0',
    'From': '[email protected]'  # This is another valid field
}

response = requests.get(url, headers=headers)

If you're using requests v2.12.x and older

Older versions of requests clobbered default headers, so you'd want to do the following to preserve default headers and then add your own to them.

import requests

url = 'SOME URL'

# Get a copy of the default headers that requests would use
headers = requests.utils.default_headers()

# Update the headers with your custom ones
# You don't have to worry about case-sensitivity with
# the dictionary keys, because default_headers uses a custom
# CaseInsensitiveDict implementation within requests' source code.
headers.update(
    {
        'User-Agent': 'My User Agent 1.0',
    }
)

response = requests.get(url, headers=headers)

Force add despite the .gitignore file

Another way of achieving it would be to temporary edit the gitignore file, add the file and then revert back the gitignore. A bit hacky i feel

How do emulators work and how are they written?

I've never done anything so fancy as to emulate a game console but I did take a course once where the assignment was to write an emulator for the machine described in Andrew Tanenbaums Structured Computer Organization. That was fun an gave me a lot of aha moments. You might want to pick that book up before diving in to writing a real emulator.

How to create JSON post to api using C#

Try using Web API HttpClient

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://domain.com/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));


            // HTTP POST
            var obj = new MyObject() { Str = "MyString"};
            response = await client.PostAsJsonAsync("POST URL GOES HERE?", obj );
            if (response.IsSuccessStatusCode)
            {
                response.//.. Contains the returned content.
            }
        }
    }

You can find more details here Web API Clients

How to modify a text file?

If you know some unix you could try the following:

Notes: $ means the command prompt

Say you have a file my_data.txt with content as such:

$ cat my_data.txt
This is a data file
with all of my data in it.

Then using the os module you can use the usual sed commands

import os

# Identifiers used are:
my_data_file = "my_data.txt"
command = "sed -i 's/all/none/' my_data.txt"

# Execute the command
os.system(command)

If you aren't aware of sed, check it out, it is extremely useful.

Cannot run the macro... the macro may not be available in this workbook

Delete your name macro and build again. I did this, and the macro worked.

Switch statement multiple cases in JavaScript

This works in regular JavaScript:

function theTest(val) {
  var answer = "";
  switch( val ) {
    case 1: case 2: case 3:
      answer = "Low";
      break;
    case 4: case 5: case 6:
      answer = "Mid";
      break;
    case 7: case 8: case 9:
      answer = "High";
      break;
    default:
      answer = "Massive or Tiny?";
  }
  return answer;
}

theTest(9);

Parsing a pcap file in python

I would use python-dpkt. Here is the documentation: http://www.commercialventvac.com/dpkt.html

This is all I know how to do though sorry.

#!/usr/local/bin/python2.7

import dpkt

counter=0
ipcounter=0
tcpcounter=0
udpcounter=0

filename='sampledata.pcap'

for ts, pkt in dpkt.pcap.Reader(open(filename,'r')):

    counter+=1
    eth=dpkt.ethernet.Ethernet(pkt) 
    if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
       continue

    ip=eth.data
    ipcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_TCP: 
       tcpcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_UDP:
       udpcounter+=1

print "Total number of packets in the pcap file: ", counter
print "Total number of ip packets: ", ipcounter
print "Total number of tcp packets: ", tcpcounter
print "Total number of udp packets: ", udpcounter

Update:

Project on GitHub, documentation here

Subversion ignoring "--password" and "--username" options

I had this same issue and solved it by setting up my ~/.ssh/config file to explicitly use the correct username (i.e. the one you use to login to the server, not your local machine). So, for example:

Host server.hostname
  User username

I found this blog post helpful: http://www.highlevelbits.com/2007/04/svn-over-ssh-prompts-for-wrong-username.html

Set initial value in datepicker with jquery?

Use it after initialization code to get current date (in datepicker format):

$(".ui-datepicker-today").trigger("click");

How do I add the Java API documentation to Eclipse?

Choose one class you want to view its documentation and press Ctrl+click over it, the Javadoc page will inform you that there is no Javadoc file attached and bellow will see a button named "Attach File". Press that button and browse to the directory where JDK is installed, normally for Win is C:\Program files\Java\jdk_xxx and inside this folder there is a src.zip file - sleect it and press OK and all is done - you already have Javadoc attached.

JavaScript and Threads

Here is just a way to simulate multi-threading in Javascript

Now I am going to create 3 threads which will calculate numbers addition, numbers can be divided with 13 and numbers can be divided with 3 till 10000000000. And these 3 functions are not able to run in same time as what Concurrency means. But I will show you a trick that will make these functions run recursively in the same time : jsFiddle

This code belongs to me.

Body Part

    <div class="div1">
    <input type="button" value="start/stop" onclick="_thread1.control ? _thread1.stop() : _thread1.start();" /><span>Counting summation of numbers till 10000000000</span> = <span id="1">0</span>
</div>
<div class="div2">
    <input type="button" value="start/stop" onclick="_thread2.control ? _thread2.stop() : _thread2.start();" /><span>Counting numbers can be divided with 13 till 10000000000</span> = <span id="2">0</span>
</div>
<div class="div3">
    <input type="button" value="start/stop" onclick="_thread3.control ? _thread3.stop() : _thread3.start();" /><span>Counting numbers can be divided with 3 till 10000000000</span> = <span id="3">0</span>
</div>

Javascript Part

var _thread1 = {//This is my thread as object
    control: false,//this is my control that will be used for start stop
    value: 0, //stores my result
    current: 0, //stores current number
    func: function () {   //this is my func that will run
        if (this.control) {      // checking for control to run
            if (this.current < 10000000000) {
                this.value += this.current;   
                document.getElementById("1").innerHTML = this.value;
                this.current++;
            }
        }
        setTimeout(function () {  // And here is the trick! setTimeout is a king that will help us simulate threading in javascript
            _thread1.func();    //You cannot use this.func() just try to call with your object name
        }, 0);
    },
    start: function () {
        this.control = true;   //start function
    },
    stop: function () {
        this.control = false;    //stop function
    },
    init: function () {
        setTimeout(function () {
            _thread1.func();    // the first call of our thread
        }, 0)
    }
};
var _thread2 = {
    control: false,
    value: 0,
    current: 0,
    func: function () {
        if (this.control) {
            if (this.current % 13 == 0) {
                this.value++;
            }
            this.current++;
            document.getElementById("2").innerHTML = this.value;
        }
        setTimeout(function () {
            _thread2.func();
        }, 0);
    },
    start: function () {
        this.control = true;
    },
    stop: function () {
        this.control = false;
    },
    init: function () {
        setTimeout(function () {
            _thread2.func();
        }, 0)
    }
};
var _thread3 = {
    control: false,
    value: 0,
    current: 0,
    func: function () {
        if (this.control) {
            if (this.current % 3 == 0) {
                this.value++;
            }
            this.current++;
            document.getElementById("3").innerHTML = this.value;
        }
        setTimeout(function () {
            _thread3.func();
        }, 0);
    },
    start: function () {
        this.control = true;
    },
    stop: function () {
        this.control = false;
    },
    init: function () {
        setTimeout(function () {
            _thread3.func();
        }, 0)
    }
};

_thread1.init();
_thread2.init();
_thread3.init();

I hope this way will be helpful.

How to get "their" changes in the middle of conflicting Git rebase?

If you want to pull a particular file from another branch just do

git checkout branch1 -- filenamefoo.txt

This will pull a version of the file from one branch into the current tree

How to use vagrant in a proxy environment?

Auto detect your proxy settings and inject them in all your vagrant VM

install the proxy plugin

vagrant plugin install vagrant-proxyconf

add this conf to you private/user VagrantFile (it will be executed for all your projects) :

vi $HOME/.vagrant.d/Vagrantfile

Vagrant.configure("2") do |config|
  puts "proxyconf..."
  if Vagrant.has_plugin?("vagrant-proxyconf")
    puts "find proxyconf plugin !"
    if ENV["http_proxy"]
      puts "http_proxy: " + ENV["http_proxy"]
      config.proxy.http     = ENV["http_proxy"]
    end
    if ENV["https_proxy"]
      puts "https_proxy: " + ENV["https_proxy"]
      config.proxy.https    = ENV["https_proxy"]
    end
    if ENV["no_proxy"]
      config.proxy.no_proxy = ENV["no_proxy"]
    end
  end
end

now up your VM !

Conditional HTML Attributes using Razor MVC3

Note you can do something like this(at least in MVC3):

<td align="left" @(isOddRow ? "class=TopBorder" : "style=border:0px") >

What I believed was razor adding quotes was actually the browser. As Rism pointed out when testing with MVC 4(I haven't tested with MVC 3 but I assume behavior hasn't changed), this actually produces class=TopBorder but browsers are able to parse this fine. The HTML parsers are somewhat forgiving on missing attribute quotes, but this can break if you have spaces or certain characters.

<td align="left" class="TopBorder" >

OR

<td align="left" style="border:0px" >

What goes wrong with providing your own quotes

If you try to use some of the usual C# conventions for nested quotes, you'll end up with more quotes than you bargained for because Razor is trying to safely escape them. For example:

<button type="button" @(true ? "style=\"border:0px\"" : string.Empty)>

This should evaluate to <button type="button" style="border:0px"> but Razor escapes all output from C# and thus produces:

style=&quot;border:0px&quot;

You will only see this if you view the response over the network. If you use an HTML inspector, often you are actually seeing the DOM, not the raw HTML. Browsers parse HTML into the DOM, and the after-parsing DOM representation already has some niceties applied. In this case the Browser sees there aren't quotes around the attribute value, adds them:

style="&quot;border:0px&quot;"

But in the DOM inspector HTML character codes display properly so you actually see:

style=""border:0px""

In Chrome, if you right-click and select Edit HTML, it switch back so you can see those nasty HTML character codes, making it clear you have real outer quotes, and HTML encoded inner quotes.

So the problem with trying to do the quoting yourself is Razor escapes these.

If you want complete control of quotes

Use Html.Raw to prevent quote escaping:

<td @Html.Raw( someBoolean ? "rel='tooltip' data-container='.drillDown a'" : "" )>

Renders as:

<td rel='tooltip' title='Drilldown' data-container='.drillDown a'>

The above is perfectly safe because I'm not outputting any HTML from a variable. The only variable involved is the ternary condition. However, beware that this last technique might expose you to certain security problems if building strings from user supplied data. E.g. if you built an attribute from data fields that originated from user supplied data, use of Html.Raw means that string could contain a premature ending of the attribute and tag, then begin a script tag that does something on behalf of the currently logged in user(possibly different than the logged in user). Maybe you have a page with a list of all users pictures and you are setting a tooltip to be the username of each person, and one users named himself '/><script>$.post('changepassword.php?password=123')</script> and now any other user who views this page has their password instantly changed to a password that the malicious user knows.

What exactly is a Maven Snapshot and why do we need it?

usually in maven we have two types of builds 1)Snapshot builds 2)Release builds

  1. snapshot builds:SNAPSHOT is the special version that indicate current deployment copy not like a regular version, maven checks the version for every build in the remote repository so the snapshot builds are nothing but development builds.

  2. Release builds:Release means removing the SNAPSHOT at the version for the build, these are the regular build versions.

How to display an alert box from C# in ASP.NET?

You can use Message box to show success message. This works great for me.

MessageBox.Show("Data inserted successfully");

How to refresh the data in a jqGrid?

var newdata= //You call Ajax peticion//

$("#idGrid").clearGridData();

$("#idGrid").jqGrid('setGridParam', {data:newdata)});
$("#idGrid").trigger("reloadGrid");

in event update data table

Retrieve column values of the selected row of a multicolumn Access listbox

For multicolumn listbox extract data from any column of selected row by

 listboxControl.List(listboxControl.ListIndex,col_num)

where col_num is required column ( 0 for first column)

append multiple values for one key in a dictionary

If you want a (almost) one-liner:

from collections import deque

d = {}
deque((d.setdefault(year, []).append(value) for year, value in source_of_data), maxlen=0)

Using dict.setdefault, you can encapsulate the idea of "check if the key already exists and make a new list if not" into a single call. This allows you to write a generator expression which is consumed by deque as efficiently as possible since the queue length is set to zero. The deque will be discarded immediately and the result will be in d.

This is something I just did for fun. I don't recommend using it. There is a time and a place to consume arbitrary iterables through a deque, and this is definitely not it.

How to trigger Jenkins builds remotely and to pass parameters

See Jenkins documentation: Parameterized Build

Below is the line you are interested in:

http://server/job/myjob/buildWithParameters?token=TOKEN&PARAMETER=Value

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

Updated Answer

Trying to open multiple panels of a collapse control that is setup as an accordion i.e. with the data-parent attribute set, can prove quite problematic and buggy (see this question on multiple panels open after programmatically opening a panel)

Instead, the best approach would be to:

  1. Allow each panel to toggle individually
  2. Then, enforce the accordion behavior manually where appropriate.

To allow each panel to toggle individually, on the data-toggle="collapse" element, set the data-target attribute to the .collapse panel ID selector (instead of setting the data-parent attribute to the parent control. You can read more about this in the question Modify Twitter Bootstrap collapse plugin to keep accordions open.

Roughly, each panel should look like this:

<div class="panel panel-default">
   <div class="panel-heading">
         <h4 class="panel-title"
             data-toggle="collapse" 
             data-target="#collapseOne">
             Collapsible Group Item #1
         </h4>
    </div>
    <div id="collapseOne" 
         class="panel-collapse collapse">
        <div class="panel-body"></div>
    </div>
</div>

To manually enforce the accordion behavior, you can create a handler for the collapse show event which occurs just before any panels are displayed. Use this to ensure any other open panels are closed before the selected one is shown (see this answer to multiple panels open). You'll also only want the code to execute when the panels are active. To do all that, add the following code:

$('#accordion').on('show.bs.collapse', function () {
    if (active) $('#accordion .in').collapse('hide');
});

Then use show and hide to toggle the visibility of each of the panels and data-toggle to enable and disable the controls.

$('#collapse-init').click(function () {
    if (active) {
        active = false;
        $('.panel-collapse').collapse('show');
        $('.panel-title').attr('data-toggle', '');
        $(this).text('Enable accordion behavior');
    } else {
        active = true;
        $('.panel-collapse').collapse('hide');
        $('.panel-title').attr('data-toggle', 'collapse');
        $(this).text('Disable accordion behavior');
    }
});

Working demo in jsFiddle

Use of "this" keyword in formal parameters for static methods in C#

In addition to Preet Sangha's explanation:
Intellisense displays the extension methods with a blue arrow (e.g. in front of "Aggregate<>"):

enter image description here

You need a

using the.namespace.of.the.static.class.with.the.extension.methods;

for the extension methods to appear and to be available, if they are in a different namespace than the code using them.

ASP.NET postback with JavaScript

Here is a complete solution

Entire form tag of the asp.net page

<form id="form1" runat="server">
    <asp:LinkButton ID="LinkButton1" runat="server" /> <%-- included to force __doPostBack javascript function to be rendered --%>

    <input type="button" id="Button45" name="Button45" onclick="javascript:__doPostBack('ButtonA','')" value="clicking this will run ButtonA.Click Event Handler" /><br /><br />
    <input type="button" id="Button46" name="Button46" onclick="javascript:__doPostBack('ButtonB','')" value="clicking this will run ButtonB.Click Event Handler" /><br /><br />

    <asp:Button runat="server" ID="ButtonA" ClientIDMode="Static" Text="ButtonA" /><br /><br />
    <asp:Button runat="server" ID="ButtonB" ClientIDMode="Static" Text="ButtonB" />
</form>

Entire Contents of the Page's Code-Behind Class

Private Sub ButtonA_Click(sender As Object, e As System.EventArgs) Handles ButtonA.Click
    Response.Write("You ran the ButtonA click event")
End Sub

Private Sub ButtonB_Click(sender As Object, e As System.EventArgs) Handles ButtonB.Click
    Response.Write("You ran the ButtonB click event")
End Sub
  • The LinkButton is included to ensure that the __doPostBack javascript function is rendered to the client. Simply having Button controls will not cause this __doPostBack function to be rendered. This function will be rendered by virtue of having a variety of controls on most ASP.NET pages, so an empty link button is typically not needed

What's going on?

Two input controls are rendered to the client:

<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
  • __EVENTTARGET receives argument 1 of __doPostBack
  • __EVENTARGUMENT receives argument 2 of __doPostBack

The __doPostBack function is rendered out like this:

function __doPostBack(eventTarget, eventArgument) {
    if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
        theForm.__EVENTTARGET.value = eventTarget;
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}
  • As you can see, it assigns the values to the hidden inputs.

When the form submits / postback occurs:

  • If you provided the UniqueID of the Server-Control Button whose button-click-handler you want to run (javascript:__doPostBack('ButtonB',''), then the button click handler for that button will be run.

What if I don't want to run a click handler, but want to do something else instead?

You can pass whatever you want as arguments to __doPostBack

You can then analyze the hidden input values and run specific code accordingly:

If Request.Form("__EVENTTARGET") = "DoSomethingElse" Then
    Response.Write("Do Something else") 
End If

Other Notes

  • What if I don't know the ID of the control whose click handler I want to run?
    • If it is not acceptable to set ClientIDMode="Static", then you can do something like this: __doPostBack('<%= myclientid.UniqueID %>', '').
    • Or: __doPostBack('<%= MYBUTTON.UniqueID %>','')
    • This will inject the unique id of the control into the javascript, should you wish it

How should I edit an Entity Framework connection string?

No, you can't edit the connection string in the designer. The connection string is not part of the EDMX file it is just referenced value from the configuration file and probably because of that it is just readonly in the properties window.

Modifying configuration file is common task because you sometimes wants to make change without rebuilding the application. That is the reason why configuration files exist.

How to install mechanize for Python 2.7?

You need the actual package (the directory containing __init__.py) stored somewhere that's in your system's PYTHONPATH. Normally, packages are distributed with a directory above the package directory, containing setup.py (which you should use to install the package), documentation, etc. This directory is not a package. Additionally, your Python27 directory is probably not in PYTHONPATH; more likely one or more subdirectories of it are.

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

Similar situation. It was working. Then, I started to include pytables. At first view, no reason to errors. I decided to use another function, that has a domain constraint (elipse) and received the following error:

TypeError: 'numpy.float64' object cannot be interpreted as an integer

or

TypeError: 'numpy.float64' object is not iterable

The crazy thing: the previous function I was using, no code changed, started to return the same error. My intermediary function, already used was:

def MinMax(x, mini=0, maxi=1)
    return max(min(x,mini), maxi)

The solution was avoid numpy or math:

def MinMax(x, mini=0, maxi=1)
    x = [x_aux if x_aux > mini else mini for x_aux in x]
    x = [x_aux if x_aux < maxi else maxi for x_aux in x]
    return max(min(x,mini), maxi)

Then, everything calm again. It was like one library possessed max and min!

Forward declaring an enum in C++

Forward declaration of enums is possible since C++11. Previously, the reason enum types couldn't be forward declared is because the size of the enumeration depends on its contents. As long as the size of the enumeration is specified by the application, it can be forward declared:

enum Enum1;                   //Illegal in C++ and C++0x; no size is explicitly specified.
enum Enum2 : unsigned int;    //Legal in C++0x.
enum class Enum3;             //Legal in C++0x, because enum class declarations have a default type of "int".
enum class Enum4: unsigned int; //Legal C++0x.
enum Enum2 : unsigned short;  //Illegal in C++0x, because Enum2 was previously declared with a different type.

How to record phone calls in android?

There is a simple solution to this problem using this library. I store an instance of the CallRecord class in MyService.class. When the service is first initialized, the following code is executed:

public class MyService extends Service {

    public static CallRecord callRecord;

    @Override
    public void onCreate() {
        super.onCreate();

        callRecord = new CallRecord.Builder(this)
                .setRecordFileName("test")
                .setRecordDirName("Download")
                .setRecordDirPath(Environment.getExternalStorageDirectory().getPath()) // optional & default value
                .setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB) // optional & default value
                .setOutputFormat(MediaRecorder.OutputFormat.AMR_NB) // optional & default value
                .setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION) // optional & default value
                .setShowSeed(false) // optional, default=true ->Ex: RecordFileName_incoming.amr || RecordFileName_outgoing.amr
                .build();
        callRecord.enableSaveFile();
        callRecord.startCallReceiver();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        callRecord.stopCallReceiver();
    } 
}

Next, do not forget to specify permissions in the manifest. (I may have some extras here, but keep in mind that some of them are necessary only for newer versions of Android)

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.PROCESS_INCOMING_CALLS" />
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Also it is crucial to request some permissions at the first start of the application. A guide is provided here.

If my code doesn't work, alternative code can be found here. I hope I helped you.