Programs & Examples On #Ipaper

How to give a user only select permission on a database

You can use Create USer to create a user

CREATE LOGIN sam
    WITH PASSWORD = '340$Uuxwp7Mcxo7Khy';
USE AdventureWorks;
CREATE USER sam FOR LOGIN sam;
GO 

and to Grant (Read-only access) you can use the following

GRANT SELECT TO sam

Hope that helps.

Skipping Incompatible Libraries at compile

That message isn't actually an error - it's just a warning that the file in question isn't of the right architecture (e.g. 32-bit vs 64-bit, wrong CPU architecture). The linker will keep looking for a library of the right type.

Of course, if you're also getting an error along the lines of can't find lPI-Http then you have a problem :-)

It's hard to suggest what the exact remedy will be without knowing the details of your build system and makefiles, but here are a couple of shots in the dark:

  1. Just to check: usually you would add flags to CFLAGS rather than CTAGS - are you sure this is correct? (What you have may be correct - this will depend on your build system!)
  2. Often the flag needs to be passed to the linker too - so you may also need to modify LDFLAGS

If that doesn't help - can you post the full error output, plus the actual command (e.g. gcc foo.c -m32 -Dxxx etc) that was being executed?

How to install the JDK on Ubuntu Linux

The following used to work before the Oracle Java license changes in early 2019.

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer

The PPA is discontinued, until the author finds a workaround for the license issues.

Git blame -- prior commits?

I wrote ublame python tool that returns a naive history of a file commits that impacted a given search term, you'll find more information on the þroject page.

Text-align class for inside a table

In Bootstrap version 4. There some inbuilt classes to position text.

For centering table header and data text:

 <table>
    <tr>
      <th class="text-center">Text align center.</th>
    </tr>
    <tr>
      <td class="text-center">Text align center.</td>
    </tr>
  </table>

You can also use this classes to position any text.

<p class="text-left">Left aligned text on all viewport sizes.</p>
<p class="text-center">Center aligned text on all viewport sizes.</p>
<p class="text-right">Right aligned text on all viewport sizes.</p>

<p class="text-sm-left">Left aligned text on viewports sized SM (small) or wider.</p>
<p class="text-md-left">Left aligned text on viewports sized MD (medium) or wider.</p>
<p class="text-lg-left">Left aligned text on viewports sized LG (large) or wider.</p>
<p class="text-xl-left">Left aligned text on viewports sized XL (extra-large) or wider</p>

For more details

Hope it's help you.

How do I solve this "Cannot read property 'appendChild' of null" error?

Just reorder or make sure, the (DOM or HTML) is loaded before the JavaScript.

Grep for beginning and end of line?

You probably want egrep. Try:

egrep '^[d-]rwx.*[0-9]$' usrLog.txt

Max size of an iOS application

As of June 2019, if your user's are on iOS 13 the cellular download limit has been lifted. User's just get a warning now. Read here

In case the article is removed here are screen shots of it below

enter image description here

enter image description here

enter image description here

SQL Server convert select a column and convert it to a string

You can do it like this:

Fiddle demo

declare @results varchar(500)

select @results = coalesce(@results + ',', '') +  convert(varchar(12),col)
from t
order by col

select @results as results

| RESULTS |
-----------
| 1,3,5,9 |

Adding a Time to a DateTime in C#

Using https://github.com/FluentDateTime/FluentDateTime

DateTime dateTime = DateTime.Now;
DateTime combined = dateTime + 36.Hours();
Console.WriteLine(combined);

How do I make a dictionary with multiple keys to one value?

If you're going to be adding to this dictionary frequently you'd want to take a class based approach, something similar to @Latty's answer in this SO question 2d-dictionary-with-many-keys-that-will-return-the-same-value.

However, if you have a static dictionary, and you need only access values by multiple keys then you could just go the very simple route of using two dictionaries. One to store the alias key association and one to store your actual data:

alias = {
    'a': 'id1',
    'b': 'id1',
    'c': 'id2',
    'd': 'id2'
}

dictionary = {
    'id1': 1,
    'id2': 2
}

dictionary[alias['a']]

If you need to add to the dictionary you could write a function like this for using both dictionaries:

def add(key, id, value=None)
    if id in dictionary:
        if key in alias:
            # Do nothing
            pass
        else:
            alias[key] = id
    else:
        dictionary[id] = value
        alias[key] = id

add('e', 'id2')
add('f', 'id3', 3)

While this works, I think ultimately if you want to do something like this writing your own data structure is probably the way to go, though it could use a similar structure.

Python 2: AttributeError: 'list' object has no attribute 'strip'

One possible solution I have tried right now is: (Make sure do it in general way using for, while with index)

>>> l=['Facebook;Google+;MySpace', 'Apple;Android']
>>> new1 = l[0].split(';')
>>> new1
['Facebook', 'Google+', 'MySpace']
>>> new2= l[1].split(';')`enter code here`
>>> new2
['Apple', 'Android']
>>> totalnew = new1 + new2
>>> totalnew
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

SQL Server 2008- Get table constraints

SELECT
    [oj].[name] [TableName],
    [ac].[name] [ColumnName],
    [dc].[name] [DefaultConstraintName],
    [dc].[definition]
FROM
    sys.default_constraints [dc],
    sys.all_objects [oj],
    sys.all_columns [ac]
WHERE
    (
        ([oj].[type] IN ('u')) AND
        ([oj].[object_id] = [dc].[parent_object_id]) AND
        ([oj].[object_id] = [ac].[object_id]) AND
        ([dc].[parent_column_id] = [ac].[column_id])
    )

Print an ArrayList with a for-each loop

Your code works. If you don't have any output, you may have "forgotten" to add some values to the list:

// add values
list.add("one");
list.add("two");

// your code
for (String object: list) {
    System.out.println(object);
}

What's the difference between interface and @interface in java?

interface:

In general, an interface exposes a contract without exposing the underlying implementation details. In Object Oriented Programming, interfaces define abstract types that expose behavior, but contain no logic. Implementation is defined by the class or type that implements the interface.

@interface : (Annotation type)

Take the below example, which has a lot of comments:

public class Generation3List extends Generation2List {

   // Author: John Doe
   // Date: 3/17/2002
   // Current revision: 6
   // Last modified: 4/12/2004
   // By: Jane Doe
   // Reviewers: Alice, Bill, Cindy

   // class code goes here

}

Instead of this, you can declare an annotation type

 @interface ClassPreamble {
   String author();
   String date();
   int currentRevision() default 1;
   String lastModified() default "N/A";
   String lastModifiedBy() default "N/A";
   // Note use of array
   String[] reviewers();
}

which can then annotate a class as follows:

@ClassPreamble (
   author = "John Doe",
   date = "3/17/2002",
   currentRevision = 6,
   lastModified = "4/12/2004",
   lastModifiedBy = "Jane Doe",
   // Note array notation
   reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {

// class code goes here

}

PS: Many annotations replace comments in code.

Reference: http://docs.oracle.com/javase/tutorial/java/annotations/declaring.html

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

I know this is a bit old but I think there might be a much simpler solution that requires no additional coding:

Instead of transposing, redimming and transposing again, and if we talk about a two dimensional array, why not just store the values transposed to begin with. In that case redim preserve actually increases the right (second) dimension from the start. Or in other words, to visualise it, why not store in two rows instead of two columns if only the nr of columns can be increased with redim preserve.

the indexes would than be 00-01, 01-11, 02-12, 03-13, 04-14, 05-15 ... 0 25-1 25 etcetera instead of 00-01, 10-11, 20-21, 30-31, 40-41 etcetera.

As long as there is only one dimension that needs to be redimmed-preserved the approach would still work: just put that dimension last.

As only the second (or last) dimension can be preserved while redimming, one could maybe argue that this is how arrays are supposed to be used to begin with. I have not seen this solution anywhere so maybe I'm overlooking something?

(Posted earlier on similar question regarding two dimensions, extended answer here for more dimensions)

How do I get the coordinates of a mouse click on a canvas element?

Here is some modifications of the above Ryan Artecona's solution.

function myGetPxStyle(e,p)
{
    var r=window.getComputedStyle?window.getComputedStyle(e,null)[p]:"";
    return parseFloat(r);
}

function myGetClick=function(ev)
{
    // {x:ev.layerX,y:ev.layerY} doesn't work when zooming with mac chrome 27
    // {x:ev.clientX,y:ev.clientY} not supported by mac firefox 21
    // document.body.scrollLeft and document.body.scrollTop seem required when scrolling on iPad
    // html is not an offsetParent of body but can have non null offsetX or offsetY (case of wordpress 3.5.1 admin pages for instance)
    // html.offsetX and html.offsetY don't work with mac firefox 21

    var offsetX=0,offsetY=0,e=this,x,y;
    var htmls=document.getElementsByTagName("html"),html=(htmls?htmls[0]:0);

    do
    {
        offsetX+=e.offsetLeft-e.scrollLeft;
        offsetY+=e.offsetTop-e.scrollTop;
    } while (e=e.offsetParent);

    if (html)
    {
        offsetX+=myGetPxStyle(html,"marginLeft");
        offsetY+=myGetPxStyle(html,"marginTop");
    }

    x=ev.pageX-offsetX-document.body.scrollLeft;
    y=ev.pageY-offsetY-document.body.scrollTop;
    return {x:x,y:y};
}

csv.Error: iterator should return strings, not bytes

You open the file in text mode.

More specifically:

ifile  = open('sample.csv', "rt", encoding=<theencodingofthefile>)

Good guesses for encoding is "ascii" and "utf8". You can also leave the encoding off, and it will use the system default encoding, which tends to be UTF8, but may be something else.

How to "flatten" a multi-dimensional array to simple one in PHP?

You can use the flatten function from Non-standard PHP library (NSPL). It works with arrays and any iterable data structures.

assert([1, 2, 3, 4, 5, 6, 7, 8, 9] === flatten([[1, [2, [3]]], [[[4, 5, 6]]], 7, 8, [9]]));

Chrome Fullscreen API

In Google's closure library project , there is a module which has do the job , below is the API and source code.

Closure library fullscreen.js API

Closure libray fullscreen.js Code

How can I position my jQuery dialog to center?

open: function () {

    var win = $(window);

    $(this).parent().css({
        position: 'absolute',
        left: (win.width() - $(this).parent().outerWidth()) / 2,
        top: (win.height() - $(this).parent().outerHeight()) / 2
    });
}

How do I make a stored procedure in MS Access?

If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:

 PARAMETERS SomeParam Text(10);
 SELECT Field FROM Table
 WHERE OtherField=SomeParam

You can also say:

CREATE PROCEDURE ProcedureName
   (Parameter1 datatype, Parameter2 datatype) AS
   SQLStatement

From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs

Note that the procedure contains only one statement.

Cropping an UIImage

To crop retina images while keeping the same scale and orientation, use the following method in a UIImage category (iOS 4.0 and above):

- (UIImage *)crop:(CGRect)rect {
    if (self.scale > 1.0f) {
        rect = CGRectMake(rect.origin.x * self.scale,
                          rect.origin.y * self.scale,
                          rect.size.width * self.scale,
                          rect.size.height * self.scale);
    }

    CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, rect);
    UIImage *result = [UIImage imageWithCGImage:imageRef scale:self.scale orientation:self.imageOrientation];
    CGImageRelease(imageRef);
    return result;
}

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

I ran into the same error, when I just forgot to declare my custom component in my NgModule - check there, if the others solutions won't work for you.

Print multiple arguments in Python

There are many ways to print that.

Let's have a look with another example.

a = 10
b = 20
c = a + b

#Normal string concatenation
print("sum of", a , "and" , b , "is" , c) 

#convert variable into str
print("sum of " + str(a) + " and " + str(b) + " is " + str(c)) 

# if you want to print in tuple way
print("Sum of %s and %s is %s: " %(a,b,c))  

#New style string formatting
print("sum of {} and {} is {}".format(a,b,c)) 

#in case you want to use repr()
print("sum of " + repr(a) + " and " + repr(b) + " is " + repr(c))

EDIT :

#New f-string formatting from Python 3.6:
print(f'Sum of {a} and {b} is {c}')

Forbidden You don't have permission to access /wp-login.php on this server

I had a similar error, which was fixed by adding:

Options FollowSymLinks

... in the apps/[app-name]/conf/httpd-app.conf file. This is because, in my case, an .htaccess file wants to use rewrite rules, that are not allowed with FollowSymLinks AND SymLinksIfOwnerMatch turned off.

If your conf file already has a line with Options ..., you can just add FollowSymLinks to the list of options. You could end up with something like this:

Options Indexes MultiViews FollowSymLinks

How do I link a JavaScript file to a HTML file?

this is demo code but it will help 

<!DOCTYPE html>
<html>
<head>
<title>APITABLE 3</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>


$(document).ready(function(){

$.ajax({
    type: "GET",
    url: "https://reqres.in/api/users/",

    data: '$format=json',

    dataType: 'json',
    success: function (data) {
 $.each(data.data,function(d,results){
     console.log(data);

 $("#apiData").append(
                        "<tr>"
                          +"<td>"+results.first_name+"</td>"
                          +"<td>"+results.last_name+"</td>"
                          +"<td>"+results.id+"</td>"
                          +"<td>"+results.email+"</td>"
  +"<td>"+results.bentrust+"</td>"
                        +"</tr>" )
                    })
 } 

});

});


</script>
</head>
<body>


    <table id="apiTable">

        <thead>
            <tr>
            <th>Id</th>
            <br>
            <th>Email</th>
            <br>
            <th>Firstname</th>
            <br>
            <th>Lastname</th>
        </tr>
        </thead>
        <tbody id="apiData"></tbody>    





</body>
</html> 

How do I position an image at the bottom of div?

Using flexbox:

HTML:

<div class="wrapper">
    <img src="pikachu.gif"/>
</div>

CSS:

.wrapper {
    height: 300px;
    width: 300px;
    display: flex;
    align-items: flex-end;
}

As requested in some comments on another answer, the image can also be horizontally centred with justify-content: center;

Try-catch block in Jenkins pipeline script

try like this (no pun intended btw)

script {
  try {
      sh 'do your stuff'
  } catch (Exception e) {
      echo 'Exception occurred: ' + e.toString()
      sh 'Handle the exception!'
  }
}

The key is to put try...catch in a script block in declarative pipeline syntax. Then it will work. This might be useful if you want to say continue pipeline execution despite failure (eg: test failed, still you need reports..)

Display special characters when using print statement

Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a raw string by prefixing it with r: r"Hello\tWorld\nHello World".

>>> a = r"Hello\tWorld\nHello World"
>>> a # in the interpreter, this calls repr()
'Hello\\tWorld\\nHello World'
>>> print a
Hello\tWorld\nHello World

Also, \s is not an escape character, except in regular expressions, and then it still has a much different meaning than what you're using it for.

TLS 1.2 not working in cURL

I has similar problem in context of Stripe:

Error: Stripe no longer supports API requests made with TLS 1.0. Please initiate HTTPS connections with TLS 1.2 or later. You can learn more about this at https://stripe.com/blog/upgrading-tls.

Forcing TLS 1.2 using CURL parameter is temporary solution or even it can't be applied because of lack of room to place an update. By default TLS test function https://gist.github.com/olivierbellone/9f93efe9bd68de33e9b3a3afbd3835cf showed following configuration:

SSL version: NSS/3.21 Basic ECC
SSL version number: 0
OPENSSL_VERSION_NUMBER: 1000105f
TLS test (default): TLS 1.0
TLS test (TLS_v1): TLS 1.2
TLS test (TLS_v1_2): TLS 1.2

I updated libraries using following command:

yum update nss curl openssl

and then saw this:

SSL version: NSS/3.21 Basic ECC
SSL version number: 0
OPENSSL_VERSION_NUMBER: 1000105f
TLS test (default): TLS 1.2
TLS test (TLS_v1): TLS 1.2
TLS test (TLS_v1_2): TLS 1.2

Please notice that default TLS version changed to 1.2! That globally solved problem. This will help PayPal users too: https://www.paypal.com/au/webapps/mpp/tls-http-upgrade (update before end of June 2017)

What is the difference between compileSdkVersion and targetSdkVersion?

The compileSdkVersion should be newest stable version. The targetSdkVersion should be fully tested and less or equal to compileSdkVersion.

How to install a Mac application using Terminal

Probably not exactly your issue..

Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments

sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /

How to supply value to an annotation from a Constant java

Does someone know how I can use a String constant or String[] constant to supply value to an annotation?

Unfortunately, you can't do this with arrays. With non-array variables, the value must be final static.

JavaScript/jQuery: replace part of string?

You need to set the text after the replace call:

_x000D_
_x000D_
$('.element span').each(function() {_x000D_
  console.log($(this).text());_x000D_
  var text = $(this).text().replace('N/A, ', '');_x000D_
  $(this).text(text);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="element">_x000D_
  <span>N/A, Category</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Here's another cool way you can do it (hat tip @Felix King):

$(".element span").text(function(index, text) {
    return text.replace("N/A, ", "");
});

How can I create a blank/hardcoded column in a sql query?

SELECT
    hat,
    shoe,
    boat,
    0 as placeholder
FROM
    objects

And '' as placeholder for strings.

How can you represent inheritance in a database?

Alternatively, consider using a document databases (such as MongoDB) which natively support rich data structures and nesting.

Counting null and non-null values in a single query

Here is a quick and dirty version that works on Oracle :

select sum(case a when null then 1 else 0) "Null values",
       sum(case a when null then 0 else 1) "Non-null values"
from us

JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

Go to control panel, uninstall the java related stuff(close eclipse if opened), then re-install java and open eclipse, clean projects.

generate a random number between 1 and 10 in c

Generating a single random number in a program is problematic. Random number generators are only "random" in the sense that repeated invocations produce numbers from a given probability distribution.

Seeding the RNG won't help, especially if you just seed it from a low-resolution timer. You'll just get numbers that are a hash function of the time, and if you call the program often, they may not change often. You might improve a little bit by using srand(time(NULL) + getpid()) (_getpid() on Windows), but that still won't be random.

The ONLY way to get numbers that are random across multiple invocations of a program is to get them from outside the program. That means using a system service such as /dev/random (Linux) or CryptGenRandom() (Windows), or from a service like random.org.

Convert True/False value read from file to boolean

If you want to be case-insensitive, you can just do:

b = True if bool_str.lower() == 'true' else False

Example usage:

>>> bool_str = 'False'
>>> b = True if bool_str.lower() == 'true' else False
>>> b
False
>>> bool_str = 'true'
>>> b = True if bool_str.lower() == 'true' else False
>>> b
True

How to scroll to the bottom of a UITableView on the iPhone before the view appears

Details

  • Xcode 8.3.2, swift 3.1
  • Xcode 10.2 (10E125), Swift 5

Code

import UIKit

extension UITableView {
    func scrollToBottom(animated: Bool) {
        let y = contentSize.height - frame.size.height
        if y < 0 { return }
        setContentOffset(CGPoint(x: 0, y: y), animated: animated)
    }
}

Usage

tableView.scrollToBottom(animated: true)

Full sample

Do not forget to paste solution code!

import UIKit

class ViewController: UIViewController {

    private weak var tableView: UITableView?
    private lazy var cellReuseIdentifier = "CellReuseIdentifier"

    override func viewDidLoad() {
        super.viewDidLoad()
        let tableView = UITableView(frame: view.frame)
        view.addSubview(tableView)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
        self.tableView = tableView
        tableView.dataSource = self
        tableView.performBatchUpdates(nil) { [weak self] result in
            if result { self?.tableView?.scrollToBottom(animated: true) }
        }
    }
}

extension ViewController: UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 100
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier, for: indexPath )
        cell.textLabel?.text = "\(indexPath)"
        return cell
    }
}

What are the differences between Pandas and NumPy+SciPy in Python?

Numpy is required by pandas (and by virtually all numerical tools for Python). Scipy is not strictly required for pandas but is listed as an "optional dependency". I wouldn't say that pandas is an alternative to Numpy and/or Scipy. Rather, it's an extra tool that provides a more streamlined way of working with numerical and tabular data in Python. You can use pandas data structures but freely draw on Numpy and Scipy functions to manipulate them.

Increase max_execution_time in PHP?

Theres a setting max_input_time (on Apache) for many webservers that defines how long they will wait for post data, regardless of the size. If this time runs out the connection is closed without even touching the php.

So your problem is not necessarily solvable with php only but you will need to change the server settings too.

Is there a way to specify a max height or width for an image?

If you only specify either the height or the width, but not both, most browsers will honor the aspect ratio.

Because you are working with an ASP.NET server control, you may consider executing logic on the server side prior to rendering to decide which (height or width) attribute you want to specify; that is, if you want a fixed height under one condition or a fixed width under another.

How to send an HTTP request using Telnet

For posterity, your question was how to send an http request to https://stackoverflow.com/questions. The real answer is: you cannot with telnet, cause this is an https-only reachable url.

So, you might want to use openssl instead of telnet, like this for instance

$ openssl s_client -connect stackoverflow.com:443
...
---
GET /questions HTTP/1.1
Host: stackoverflow.com

This will give you the https response.

How to remove illegal characters from path and filenames?

Here is my small contribution. A method to replace within the same string without creating new strings or stringbuilders. It's fast, easy to understand and a good alternative to all mentions in this post.

private static HashSet<char> _invalidCharsHash;
private static HashSet<char> InvalidCharsHash
{
  get { return _invalidCharsHash ?? (_invalidCharsHash = new HashSet<char>(Path.GetInvalidFileNameChars())); }
}

private static string ReplaceInvalidChars(string fileName, string newValue)
{
  char newChar = newValue[0];

  char[] chars = fileName.ToCharArray();
  for (int i = 0; i < chars.Length; i++)
  {
    char c = chars[i];
    if (InvalidCharsHash.Contains(c))
      chars[i] = newChar;
  }

  return new string(chars);
}

You can call it like this:

string illegal = "\"M<>\"\\a/ry/ h**ad:>> a\\/:*?\"<>| li*tt|le|| la\"mb.?";
string legal = ReplaceInvalidChars(illegal);

and returns:

_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._

It's worth to note that this method will always replace invalid chars with a given value, but will not remove them. If you want to remove invalid chars, this alternative will do the trick:

private static string RemoveInvalidChars(string fileName, string newValue)
{
  char newChar = string.IsNullOrEmpty(newValue) ? char.MinValue : newValue[0];
  bool remove = newChar == char.MinValue;

  char[] chars = fileName.ToCharArray();
  char[] newChars = new char[chars.Length];
  int i2 = 0;
  for (int i = 0; i < chars.Length; i++)
  {
    char c = chars[i];
    if (InvalidCharsHash.Contains(c))
    {
      if (!remove)
        newChars[i2++] = newChar;
    }
    else
      newChars[i2++] = c;

  }

  return new string(newChars, 0, i2);
}

BENCHMARK

I executed timed test runs with most methods found in this post, if performance is what you are after. Some of these methods don't replace with a given char, since OP was asking to clean the string. I added tests replacing with a given char, and some others replacing with an empty char if your intended scenario only needs to remove the unwanted chars. Code used for this benchmark is at the end, so you can run your own tests.

Note: Methods Test1 and Test2 are both proposed in this post.

First Run

replacing with '_', 1000000 iterations

Results:

============Test1===============
Elapsed=00:00:01.6665595
Result=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._

============Test2===============
Elapsed=00:00:01.7526835
Result=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._

============Test3===============
Elapsed=00:00:05.2306227
Result=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._

============Test4===============
Elapsed=00:00:14.8203696
Result=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._

============Test5===============
Elapsed=00:00:01.8273760
Result=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._

============Test6===============
Elapsed=00:00:05.4249985
Result=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._

============Test7===============
Elapsed=00:00:07.5653833
Result=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._

============Test8===============
Elapsed=00:12:23.1410106
Result=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._

============Test9===============
Elapsed=00:00:02.1016708
Result=_M ____a_ry_ h__ad___ a_________ li_tt_le__ la_mb._

============Test10===============
Elapsed=00:00:05.0987225
Result=M ary had a little lamb.

============Test11===============
Elapsed=00:00:06.8004289
Result=M ary had a little lamb.

Second Run

removing invalid chars, 1000000 iterations

Note: Test1 will not remove, only replace.

Results:

============Test1===============
Elapsed=00:00:01.6945352
Result= M     a ry  h  ad    a          li tt le   la mb.

============Test2===============
Elapsed=00:00:01.4798049
Result=M ary had a little lamb.

============Test3===============
Elapsed=00:00:04.0415688
Result=M ary had a little lamb.

============Test4===============
Elapsed=00:00:14.3397960
Result=M ary had a little lamb.

============Test5===============
Elapsed=00:00:01.6782505
Result=M ary had a little lamb.

============Test6===============
Elapsed=00:00:04.9251707
Result=M ary had a little lamb.

============Test7===============
Elapsed=00:00:07.9562379
Result=M ary had a little lamb.

============Test8===============
Elapsed=00:12:16.2918943
Result=M ary had a little lamb.

============Test9===============
Elapsed=00:00:02.0770277
Result=M ary had a little lamb.

============Test10===============
Elapsed=00:00:05.2721232
Result=M ary had a little lamb.

============Test11===============
Elapsed=00:00:05.2802903
Result=M ary had a little lamb.

BENCHMARK RESULTS

Methods Test1, Test2 and Test5 are the fastest. Method Test8 is the slowest.

CODE

Here's the complete code of the benchmark:

private static HashSet<char> _invalidCharsHash;
private static HashSet<char> InvalidCharsHash
{
  get { return _invalidCharsHash ?? (_invalidCharsHash = new HashSet<char>(Path.GetInvalidFileNameChars())); }
}

private static string _invalidCharsValue;
private static string InvalidCharsValue
{
  get { return _invalidCharsValue ?? (_invalidCharsValue = new string(Path.GetInvalidFileNameChars())); }
}

private static char[] _invalidChars;
private static char[] InvalidChars
{
  get { return _invalidChars ?? (_invalidChars = Path.GetInvalidFileNameChars()); }
}

static void Main(string[] args)
{
  string testPath = "\"M <>\"\\a/ry/ h**ad:>> a\\/:*?\"<>| li*tt|le|| la\"mb.?";

  int max = 1000000;
  string newValue = "";

  TimeBenchmark(max, Test1, testPath, newValue);
  TimeBenchmark(max, Test2, testPath, newValue);
  TimeBenchmark(max, Test3, testPath, newValue);
  TimeBenchmark(max, Test4, testPath, newValue);
  TimeBenchmark(max, Test5, testPath, newValue);
  TimeBenchmark(max, Test6, testPath, newValue);
  TimeBenchmark(max, Test7, testPath, newValue);
  TimeBenchmark(max, Test8, testPath, newValue);
  TimeBenchmark(max, Test9, testPath, newValue);
  TimeBenchmark(max, Test10, testPath, newValue);
  TimeBenchmark(max, Test11, testPath, newValue);

  Console.Read();
}

private static void TimeBenchmark(int maxLoop, Func<string, string, string> func, string testString, string newValue)
{
  var sw = new Stopwatch();
  sw.Start();
  string result = string.Empty;

  for (int i = 0; i < maxLoop; i++)
    result = func?.Invoke(testString, newValue);

  sw.Stop();

  Console.WriteLine($"============{func.Method.Name}===============");
  Console.WriteLine("Elapsed={0}", sw.Elapsed);
  Console.WriteLine("Result={0}", result);
  Console.WriteLine("");
}

private static string Test1(string fileName, string newValue)
{
  char newChar = string.IsNullOrEmpty(newValue) ? char.MinValue : newValue[0];

  char[] chars = fileName.ToCharArray();
  for (int i = 0; i < chars.Length; i++)
  {
    if (InvalidCharsHash.Contains(chars[i]))
      chars[i] = newChar;
  }

  return new string(chars);
}

private static string Test2(string fileName, string newValue)
{
  char newChar = string.IsNullOrEmpty(newValue) ? char.MinValue : newValue[0];
  bool remove = newChar == char.MinValue;

  char[] chars = fileName.ToCharArray();
  char[] newChars = new char[chars.Length];
  int i2 = 0;
  for (int i = 0; i < chars.Length; i++)
  {
    char c = chars[i];
    if (InvalidCharsHash.Contains(c))
    {
      if (!remove)
        newChars[i2++] = newChar;
    }
    else
      newChars[i2++] = c;

  }

  return new string(newChars, 0, i2);
}

private static string Test3(string filename, string newValue)
{
  foreach (char c in InvalidCharsValue)
  {
    filename = filename.Replace(c.ToString(), newValue);
  }

  return filename;
}

private static string Test4(string filename, string newValue)
{
  Regex r = new Regex(string.Format("[{0}]", Regex.Escape(InvalidCharsValue)));
  filename = r.Replace(filename, newValue);
  return filename;
}

private static string Test5(string filename, string newValue)
{
  return string.Join(newValue, filename.Split(InvalidChars));
}

private static string Test6(string fileName, string newValue)
{
  return InvalidChars.Aggregate(fileName, (current, c) => current.Replace(c.ToString(), newValue));
}

private static string Test7(string fileName, string newValue)
{
  string regex = string.Format("[{0}]", Regex.Escape(InvalidCharsValue));
  return Regex.Replace(fileName, regex, newValue, RegexOptions.Compiled);
}

private static string Test8(string fileName, string newValue)
{
  string regex = string.Format("[{0}]", Regex.Escape(InvalidCharsValue));
  Regex removeInvalidChars = new Regex(regex, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant);
  return removeInvalidChars.Replace(fileName, newValue);
}

private static string Test9(string fileName, string newValue)
{
  StringBuilder sb = new StringBuilder(fileName.Length);
  bool changed = false;

  for (int i = 0; i < fileName.Length; i++)
  {
    char c = fileName[i];
    if (InvalidCharsHash.Contains(c))
    {
      changed = true;
      sb.Append(newValue);
    }
    else
      sb.Append(c);
  }

  if (sb.Length == 0)
    return newValue;

  return changed ? sb.ToString() : fileName;
}

private static string Test10(string fileName, string newValue)
{
  if (!fileName.Any(c => InvalidChars.Contains(c)))
  {
    return fileName;
  }

  return new string(fileName.Where(c => !InvalidChars.Contains(c)).ToArray());
}

private static string Test11(string fileName, string newValue)
{
  string invalidCharsRemoved = new string(fileName
    .Where(x => !InvalidChars.Contains(x))
    .ToArray());

  return invalidCharsRemoved;
}

What are the recommendations for html <base> tag?

Drupal initially relied on the <base> tag, and later on took the decision to not use due to problems with HTTP crawlers & caches.

I generally don't like to post links. But this one is really worth sharing as it could benefit those looking for the details of a real-world experience with the <base> tag:

http://drupal.org/node/13148

Time complexity of accessing a Python dict

My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic.

I use a dictionary to memoize values. That seems to be a bottleneck.

This is evidence of a bug in your memoization method.

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

They are called ifdef or include guards.

If writing a small program it might seems that it is not needed, but as the project grows you could intentionally or unintentionally include one file many times, which can result in compilation warning like variable already declared.

#ifndef checks whether HEADERFILE_H is not declared.
#define will declare HEADERFILE_H once #ifndef generates true.
#endif is to know the scope of #ifndef i.e end of #ifndef

If it is not declared which means #ifndef generates true then only the part between #ifndef and #endif executed otherwise not. This will prevent from again declaring the identifiers, enums, structure, etc...

Delete all nodes and relationships in neo4j 1.8

As of 2.3.0 and up to 3.3.0

MATCH (n)
DETACH DELETE n

Docs

Pre 2.3.0

MATCH (n)
OPTIONAL MATCH (n)-[r]-()
DELETE n,r

Docs

Assembly Language - How to do Modulo?

An easy way to see what a modulus operator looks like on various architectures is to use the Godbolt Compiler Explorer.

https://godbolt.org/z/64zKGr

Better way to check variable for null or empty string?

to be more robust (tabulation, return…), I define:

function is_not_empty_string($str) {
    if (is_string($str) && trim($str, " \t\n\r\0") !== '')
        return true;
    else
        return false;
}

// code to test
$values = array(false, true, null, 'abc', '23', 23, '23.5', 23.5, '', ' ', '0', 0);
foreach ($values as $value) {
    var_export($value);
    if (is_not_empty_string($value)) 
        print(" is a none empty string!\n");
    else
        print(" is not a string or is an empty string\n");
}

sources:

How do you select the entire excel sheet with Range using VBA?

I believe you want to find the current region of A1 and surrounding cells - not necessarily all cells on the sheet. If so - simply use... Range("A1").CurrentRegion

How to add an object to an ArrayList in Java

change Date to Object which is between parenthesis

Multi-statement Table Valued Function vs Inline Table Valued Function

In researching Matt's comment, I have revised my original statement. He is correct, there will be a difference in performance between an inline table valued function (ITVF) and a multi-statement table valued function (MSTVF) even if they both simply execute a SELECT statement. SQL Server will treat an ITVF somewhat like a VIEW in that it will calculate an execution plan using the latest statistics on the tables in question. A MSTVF is equivalent to stuffing the entire contents of your SELECT statement into a table variable and then joining to that. Thus, the compiler cannot use any table statistics on the tables in the MSTVF. So, all things being equal, (which they rarely are), the ITVF will perform better than the MSTVF. In my tests, the performance difference in completion time was negligible however from a statistics standpoint, it was noticeable.

In your case, the two functions are not functionally equivalent. The MSTV function does an extra query each time it is called and, most importantly, filters on the customer id. In a large query, the optimizer would not be able to take advantage of other types of joins as it would need to call the function for each customerId passed. However, if you re-wrote your MSTV function like so:

CREATE FUNCTION MyNS.GetLastShipped()
RETURNS @CustomerOrder TABLE
    (
    SaleOrderID    INT         NOT NULL,
    CustomerID      INT         NOT NULL,
    OrderDate       DATETIME    NOT NULL,
    OrderQty        INT         NOT NULL
    )
AS
BEGIN
    INSERT @CustomerOrder
    SELECT a.SalesOrderID, a.CustomerID, a.OrderDate, b.OrderQty
    FROM Sales.SalesOrderHeader a 
        INNER JOIN Sales.SalesOrderHeader b
            ON a.SalesOrderID = b.SalesOrderID
        INNER JOIN Production.Product c 
            ON b.ProductID = c.ProductID
    WHERE a.OrderDate = (
                        Select Max(SH1.OrderDate)
                        FROM Sales.SalesOrderHeader As SH1
                        WHERE SH1.CustomerID = A.CustomerId
                        )
    RETURN
END
GO

In a query, the optimizer would be able to call that function once and build a better execution plan but it still would not be better than an equivalent, non-parameterized ITVS or a VIEW.

ITVFs should be preferred over a MSTVFs when feasible because the datatypes, nullability and collation from the columns in the table whereas you declare those properties in a multi-statement table valued function and, importantly, you will get better execution plans from the ITVF. In my experience, I have not found many circumstances where an ITVF was a better option than a VIEW but mileage may vary.

Thanks to Matt.

Addition

Since I saw this come up recently, here is an excellent analysis done by Wayne Sheffield comparing the performance difference between Inline Table Valued functions and Multi-Statement functions.

His original blog post.

Copy on SQL Server Central

SELECT from nothing?

It's not consistent across vendors - Oracle, MySQL, and DB2 support dual:

SELECT 'Hello world'
  FROM DUAL

...while SQL Server, PostgreSQL, and SQLite don't require the FROM DUAL:

SELECT 'Hello world'

MySQL does support both ways.

PHP errors NOT being displayed in the browser [Ubuntu 10.10]

it's should overlap, so it turned off. Try to open in your text editor and find display_errors and turn it on. It works for me

How to remove RVM (Ruby Version Manager) from my system

There's a simple command built-in that will pull it:

rvm implode

This will remove the rvm/ directory and all the rubies built within it. In order to remove the final trace of rvm, you need to remove the rvm gem, too:

gem uninstall rvm

If you've made modifications to your PATH you might want to pull those, too. Check your .bashrc, .profile and .bash_profile files, among other things.

You may also have an /etc/rvmrc file, or one in your home directory ~/.rvmrc that may need to be removed as well.

Checking the equality of two slices

This is just example using reflect.DeepEqual() that is given in @VictorDeryagin's answer.

package main

import (
    "fmt"
    "reflect"
)

func main() {
    a := []int {4,5,6}
    b := []int {4,5,6}
    c := []int {4,5,6,7}

    fmt.Println(reflect.DeepEqual(a, b))
    fmt.Println(reflect.DeepEqual(a, c))

}

Result:

true
false

Try it in Go Playground

ls command: how can I get a recursive full-path listing, one line per file?

If the directory is passed as a relative path and you will need to convert it to an absolute path before calling find. In the following example, the directory is passed as the first parameter to the script:

#!/bin/bash

# get absolute path
directory=`cd $1; pwd`
# print out list of files and directories
find $directory

How to make certain text not selectable with CSS

The CSS below stops users from being able to select text.

-webkit-user-select: none; /* Safari */        
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE10+/Edge */
user-select: none; /* Standard */

To target IE9 downwards the html attribute unselectable must be used instead:

<p unselectable="on">Test Text</p>

Ifelse statement in R with multiple conditions

another solution using dplyr is:

df <- ## your data ##
df <- df %>%
        mutate(Den = ifelse(any(is.na(Den)) | any(Den != 1), 0, 1))

How to replace a character with a newline in Emacs?

More explicitly:

To replace the semi colon character (;) with a newline, follow these exact steps.

  1. locate cursor at upper left of buffer containing text you want to change
  2. Type m-x replace-string and hit RETURN
  3. the mini-buffer will display something like this: Replace string (default ^ -> ):
  4. Type in the character you want to replace. In this case, ; and hit RETURN
  5. the mini-buffer will display something like this: string ; with:
  6. Now execute C-q C-j
  7. All instances of semi-colon will be replaced a newline (from the cursor location to the end of the buffer will now appear)

Bit more to it than the original explanation says.

Creating a timer in python

I want to create a kind of stopwatch that when minutes reach 20 minutes, brings up a dialog box.

All you need is to sleep the specified time. time.sleep() takes seconds to sleep, so 20 * 60 is 20 minutes.

import time
run = raw_input("Start? > ")
time.sleep(20 * 60)
your_code_to_bring_up_dialog_box()

Split string on the first white space occurrence

Whenever I need to get a class from a list of classes or a part of a class name or id, I always use split() then either get it specifically with the array index or, most often in my case, pop() to get the last element or shift() to get the first.

This example gets the div's classes "gallery_148 ui-sortable" and returns the gallery id 148.

var galleryClass = $(this).parent().prop("class"); // = gallery_148 ui-sortable
var galleryID = galleryClass.split(" ").shift(); // = gallery_148
galleryID = galleryID.split("_").pop(); // = 148
//or
galleryID = galleryID.substring(8); // = 148 also, but less versatile 

I'm sure it could be compacted into less lines but I left it expanded for readability.

UITapGestureRecognizer - single tap and double tap

You need to use the requireGestureRecognizerToFail: method. Something like this:

[singleTapRecognizer requireGestureRecognizerToFail:doubleTapRecognizer];

psql: FATAL: role "postgres" does not exist

I became stuck on this issue having executed brew services stop postgresql the day prior.
The day following: brew services start postgresql would not work. This is because as is shown when you install using homebrew. postgresql uses a launchd ... which loads when your computer is powered on.

resolution:
brew services start postgresql
Restart your computer.

Allowing Untrusted SSL Certificates with HttpClient

If you are using System.Net.Http.HttpClient I believe correct pattern is

var handler = new HttpClientHandler() 
{ 
    ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
};

var http = new HttpClient(handler);
var res = http.GetAsync(url);

Checkout one file from Subversion

Since none of the other answers worked for me I did it using this hack:

$ cd /yourfolder
svn co https://path-to-folder-which-has-your-files/ --depth files

This will create a new local folder which has only the files from the remote path. Then you can do a symbolic link to the files you want to have here.

A default document is not configured for the requested URL, and directory browsing is not enabled on the server

I faced the same error posted by OP while trying to debug my ASP.NET website using IIS Express server. IIS Express is used by Visual Studio to run the website when we press F5.

Open solution explorer in Visual Studio -> Expand the web application project node (StudentInfo in my case) -> Right click on the web page which you want to get loaded when your website starts(StudentPortal.aspx in my case) -> Select Set as Start Page option from the context menu as shown below. It started to work from the next run.

enter image description here

Root cause: I concluded that the start page which is the default document for the website wasn't set correctly or had got messed up somehow during development.

What is a reasonable length limit on person "Name" fields?

I usually go with varchar(255) (255 being the maximum length of a varchar type in MySQL).

Detect changes in the DOM

Use the MutationObserver interface as shown in Gabriele Romanato's blog

Chrome 18+, Firefox 14+, IE 11+, Safari 6+

// The node to be monitored
var target = $( "#content" )[0];

// Create an observer instance
var observer = new MutationObserver(function( mutations ) {
  mutations.forEach(function( mutation ) {
    var newNodes = mutation.addedNodes; // DOM NodeList
    if( newNodes !== null ) { // If there are new nodes added
        var $nodes = $( newNodes ); // jQuery set
        $nodes.each(function() {
            var $node = $( this );
            if( $node.hasClass( "message" ) ) {
                // do something
            }
        });
    }
  });    
});

// Configuration of the observer:
var config = { 
    attributes: true, 
    childList: true, 
    characterData: true 
};

// Pass in the target node, as well as the observer options
observer.observe(target, config);

// Later, you can stop observing
observer.disconnect();

How to apply Hovering on html area tag?

for complete this script , the function for draw circle ,

    function drawCircle(coordon)
    {
        var coord = coordon.split(',');

        var c = document.getElementById("myCanvas");
        var hdc = c.getContext("2d");
        hdc.beginPath();

        hdc.arc(coord[0], coord[1], coord[2], 0, 2 * Math.PI);
        hdc.stroke();
    }

Multiple linear regression in Python

Scikit-learn is a machine learning library for Python which can do this job for you. Just import sklearn.linear_model module into your script.

Find the code template for Multiple Linear Regression using sklearn in Python:

import numpy as np
import matplotlib.pyplot as plt #to plot visualizations
import pandas as pd

# Importing the dataset
df = pd.read_csv(<Your-dataset-path>)
# Assigning feature and target variables
X = df.iloc[:,:-1]
y = df.iloc[:,-1]

# Use label encoders, if you have any categorical variable
from sklearn.preprocessing import LabelEncoder
labelencoder = LabelEncoder()
X['<column-name>'] = labelencoder.fit_transform(X['<column-name>'])

from sklearn.preprocessing import OneHotEncoder
onehotencoder = OneHotEncoder(categorical_features = ['<index-value>'])
X = onehotencoder.fit_transform(X).toarray()

# Avoiding the dummy variable trap
X = X[:,1:] # Usually done by the algorithm itself

#Spliting the data into test and train set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y, random_state = 0, test_size = 0.2)

# Fitting the model
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)

# Predicting the test set results
y_pred = regressor.predict(X_test)

That's it. You can use this code as a template for implementing Multiple Linear Regression in any dataset. For a better understanding with an example, Visit: Linear Regression with an example

How to add a new line of text to an existing file in Java?

Starting from Java 7:

Define a path and the String containing the line separator at the beginning:

Path p = Paths.get("C:\\Users\\first.last\\test.txt");
String s = System.lineSeparator() + "New Line!";

and then you can use one of the following approaches:

  1. Using Files.write (small files):

    try {
        Files.write(p, s.getBytes(), StandardOpenOption.APPEND);
    } catch (IOException e) {
        System.err.println(e);
    }
    
  2. Using Files.newBufferedWriter(text files):

    try (BufferedWriter writer = Files.newBufferedWriter(p, StandardOpenOption.APPEND)) {
        writer.write(s);
    } catch (IOException ioe) {
        System.err.format("IOException: %s%n", ioe);
    }
    
  3. Using Files.newOutputStream (interoperable with java.io APIs):

    try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(p, StandardOpenOption.APPEND))) {
        out.write(s.getBytes());
    } catch (IOException e) {
        System.err.println(e);
    }
    
  4. Using Files.newByteChannel (random access files):

    try (SeekableByteChannel sbc = Files.newByteChannel(p, StandardOpenOption.APPEND)) {
        sbc.write(ByteBuffer.wrap(s.getBytes()));
    } catch (IOException e) {
        System.err.println(e);
    }
    
  5. Using FileChannel.open (random access files):

    try (FileChannel sbc = FileChannel.open(p, StandardOpenOption.APPEND)) {
        sbc.write(ByteBuffer.wrap(s.getBytes()));
    } catch (IOException e) {
        System.err.println(e);
    }
    

Details about these methods can be found in the Oracle's tutorial.

Is it possible to set the stacking order of pseudo-elements below their parent element?

Speaking with regard to the spec (http://www.w3.org/TR/CSS2/zindex.html), since a.someSelector is positioned it creates a new stacking context that its children can't break out of. Leave a.someSelector unpositioned and then child a.someSelector:after may be positioned in the same context as a.someSelector.

Remove useless zero digits from decimals in PHP

$value = preg_replace('~\.0+$~','',$value);

iTerm 2: How to set keyboard shortcuts to jump to beginning/end of line?

The old fashion emacs bindings can still work in iterm2 and os x terminal:

Preferences -> Profiles -> Keys (sub tab in profiles)

  • Set Left/Right option <kbd>?</kbd> key acts as +Esc (similar in os x terminal)

This should enable alt-f and alt-b for moving words by words. (Still ctrl-a and ctrl-e always work as usual)

If set as meta those old bindings will work while some iterm2 bindings unavailable.

Utilizing multi core for tar+gzip/bzip compression/decompression

You can use pigz instead of gzip, which does gzip compression on multiple cores. Instead of using the -z option, you would pipe it through pigz:

tar cf - paths-to-archive | pigz > archive.tar.gz

By default, pigz uses the number of available cores, or eight if it could not query that. You can ask for more with -p n, e.g. -p 32. pigz has the same options as gzip, so you can request better compression with -9. E.g.

tar cf - paths-to-archive | pigz -9 -p 32 > archive.tar.gz

SQL Server Management Studio – tips for improving the TSQL coding process

For Sub Queries

object explorer > right-click a table > Script table as > SELECT to > Clipboard

Then you can just paste in the section where you want that as a sub query.

Templates / Snippets

Create you own templates with only a code snippet. Then instead opening the template as a new document just drag it to you current query to insert the snippet.

A snippet can simply be a set of header with comments or just some simple piece of code.

Implicit transactions

If you wont remember to start a transaction before your delete statemens you can go to options and set implicit transactions by default in all your queries. They require always an explicit commit / rollback.

Isolation level

Go to options and set isolation level to READ_UNCOMMITED by default. This way you dont need to type a NOLOCK in all your ad hoc queries. Just dont forget to place the table hint when writing a new view or stored procedure.

Default database

Your login has a default database set by the DBA (To me is usually the undesired one almost every time).

If you want it to be a different one because of the project you are currently working on.

In 'Registered Servers pane' > Right click > Properties > Connection properties tab > connect to database.

Multiple logins

(These you might already have done though)

Register the server multiple times, each with a different login. You can then have the same server in the object browser open multiple times (each with a different login).

To execute the same query you already wrote with a different login, instead of copying the query just do a right click over the query pane > Connection > Change connection.

Java: Rotating Images

public static BufferedImage rotateCw( BufferedImage img )
{
    int         width  = img.getWidth();
    int         height = img.getHeight();
    BufferedImage   newImage = new BufferedImage( height, width, img.getType() );

    for( int i=0 ; i < width ; i++ )
        for( int j=0 ; j < height ; j++ )
            newImage.setRGB( height-1-j, i, img.getRGB(i,j) );

    return newImage;
}

from https://coderanch.com/t/485958/java/Rotating-buffered-image

How to install a specific version of a ruby gem?

for Ruby 1.9+ use colon.

gem install sinatra:1.4.4 prawn:0.13.0

Call a stored procedure with parameter in c#

Here is my technique I'd like to share. Works well so long as your clr property types are sql equivalent types eg. bool -> bit, long -> bigint, string -> nchar/char/varchar/nvarchar, decimal -> money

public void SaveTransaction(Transaction transaction) 
{
    using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConString"].ConnectionString))
    {
        using (var cmd = new SqlCommand("spAddTransaction", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            foreach (var prop in transaction.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
                cmd.Parameters.AddWithValue("@" + prop.Name, prop.GetValue(transaction, null));
            con.Open();
            cmd.ExecuteNonQuery();
        }
    }
}

Selecting only numeric columns from a data frame

library(purrr)
x <- x %>% keep(is.numeric)

Filter items which array contains any of given values

Edit: The bitset stuff below is maybe an interesting read, but the answer itself is a bit dated. Some of this functionality is changing around in 2.x. Also Slawek points out in another answer that the terms query is an easy way to DRY up the search in this case. Refactored at the end for current best practices. —nz

You'll probably want a Bool Query (or more likely Filter alongside another query), with a should clause.

The bool query has three main properties: must, should, and must_not. Each of these accepts another query, or array of queries. The clause names are fairly self-explanatory; in your case, the should clause may specify a list filters, a match against any one of which will return the document you're looking for.

From the docs:

In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.

Here's an example of what that Bool query might look like in isolation:

{
  "bool": {
    "should": [
      { "term": { "tag": "c" }},
      { "term": { "tag": "d" }}
    ]
  }
}

And here's another example of that Bool query as a filter within a more general-purpose Filtered Query:

{
  "filtered": {
    "query": {
      "match": { "title": "hello world" }
    },
    "filter": {
      "bool": {
        "should": [
          { "term": { "tag": "c" }},
          { "term": { "tag": "d" }}
        ]
      }
    }
  }
}

Whether you use Bool as a query (e.g., to influence the score of matches), or as a filter (e.g., to reduce the hits that are then being scored or post-filtered) is subjective, depending on your requirements.

It is generally preferable to use Bool in favor of an Or Filter, unless you have a reason to use And/Or/Not (such reasons do exist). The Elasticsearch blog has more information about the different implementations of each, and good examples of when you might prefer Bool over And/Or/Not, and vice-versa.

Elasticsearch blog: All About Elasticsearch Filter Bitsets

Update with a refactored query...

Now, with all of that out of the way, the terms query is a DRYer version of all of the above. It does the right thing with respect to the type of query under the hood, it behaves the same as the bool + should using the minimum_should_match options, and overall is a bit more terse.

Here's that last query refactored a bit:

{
  "filtered": {
    "query": {
      "match": { "title": "hello world" }
    },
    "filter": {
      "terms": {
        "tag": [ "c", "d" ],
        "minimum_should_match": 1
      }
    }
  }
}

Angular 2 : No NgModule metadata found

I had this error even though I had everything that the answers above suggested in place. A simple edit in the app.module.ts file ( like delete a bracket and put it back) did the trick.

How to select and change value of table cell with jQuery?

You can do this :

<table id="table_header">
<tr>
   <td contenteditable="true">a</td>
   <td contenteditable="true">b</td>
   <td contenteditable="true">c</td>
</tr>
</table>

What is a .NET developer?

I'd say the minimum would be to

  • know one of the .Net Languages (C#, VB.NET, etc.)
  • know the basic working of the .Net runtime
  • know and understand the core parts of the .Net class libraries
  • have an understanding about what additional classes and functions are available as part of the .Net class libraries

Execute JavaScript using Selenium WebDriver in C#

You could also do:

public static IWebElement FindElementByJs(this IWebDriver driver, string jsCommand)
{
    return (IWebElement)((IJavaScriptExecutor)driver).ExecuteScript(jsCommand);
}

public static IWebElement FindElementByJsWithWait(this IWebDriver driver, string jsCommand, int timeoutInSeconds)
{
    if (timeoutInSeconds > 0)
    {
        var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
        wait.Until(d => d.FindElementByJs(jsCommand));
    }
    return driver.FindElementByJs(jsCommand);
}

public static IWebElement FindElementByJsWithWait(this IWebDriver driver, string jsCommand)
{
    return FindElementByJsWithWait(driver, jsCommand, s_PageWaitSeconds);
}

Java converting int to hex and back again

It overflows, because the number is negative.

Try this and it will work:

int n = (int) Long.parseLong("ffff8000", 16);

How can I get a file's size in C++?

While not necessarily the most popular method, I've heard that the ftell, fseek method may not always give accurate results in some circumstances. Specifically, if an already opened file is used and the size needs to be worked out on that and it happens to be opened as a text file, then it's going to give out wrong answers.

The following methods should always work as stat is part of the c runtime library on Windows, Mac and Linux.

long GetFileSize(std::string filename)
{
    struct stat stat_buf;
    int rc = stat(filename.c_str(), &stat_buf);
    return rc == 0 ? stat_buf.st_size : -1;
}

or 

long FdGetFileSize(int fd)
{
    struct stat stat_buf;
    int rc = fstat(fd, &stat_buf);
    return rc == 0 ? stat_buf.st_size : -1;
}

On some systems there is also a stat64/fstat64. So if you need this for very large files you may want to look at using those.

How to call a Parent Class's method from Child Class in Python?

class department:
    campus_name="attock"
    def printer(self):
        print(self.campus_name)

class CS_dept(department):
    def overr_CS(self):
        department.printer(self)
        print("i am child class1")

c=CS_dept()
c.overr_CS()

How to remove a newline from a string in Bash

What worked for me was echo $testVar | tr "\n" " "

Where testVar contained my variable/script-output

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Your regex only allows exactly 8 characters. Use {8,} to specify eight or more instead of {8}.

But why would you limit the allowed character range for your passwords? 8-character alphanumeric passwords can be bruteforced by my phone within minutes.

How can I use external JARs in an Android project?

I know the OP ends his question with reference to the Eclipse plugin, but I arrived here with a search that didn't specify Eclipse. So here goes for Android Studio:

  1. Add jar file to libs directory (such as copy/paste)
  2. Right-Click on jar file and select "Add as Library..."
  3. click "Ok" on next dialog or renamed if you choose to.

That's it!

XML Schema Validation : Cannot find the declaration of element

The targetNamespace of your XML Schema does not match the namespace of the Root element (dot in Test.Namespace vs. comma in Test,Namespace)

Once you make the above agree, you have to consider that your element2 has an attribute order that is not in your XSD.

generate random string for div id

I also needed a random id, I went with using base64 encoding:

btoa(Math.random()).substring(0,12)

Pick however many characters you want, the result is usually at least 24 characters.

Adding close button in div to close the box

You can use this jsFiddle

And HTML:

<div id="previewBox">
    <button id="closeButton">Close</button>
<a class="fragment" href="google.com">
    <div>
    <img src ="http://placehold.it/116x116" alt="some description"/> 
    <h3>the title will go here</h3>
        <h4> www.myurlwill.com </h4>
    <p class="text">
        this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etc this is a short description yada yada peanuts etcthis is a short description yada yada peanuts etc 
    </p>
</div>
</a>
</div>

With JS (jquery required):

$(document).ready(function() {
    $('#closeButton').on('click', function(e) { 
        $('#previewBox').remove(); 
    });
});

What is the convention in JSON for empty vs. null?

There is the question whether we want to differentiate between cases:

  1. "phone" : "" = the value is empty

  2. "phone" : null = the value for "phone" was not set yet

If we want differentiate I would use null for this. Otherwise we would need to add a new field like "isAssigned" or so. This is an old Database issue.

Plotting time-series with Date labels on x-axis

It's possible in ggplot and you can use scale_date for this task

 library(ggplot2)  
 Lines <- "Date            Visits
    11/1/2010   696537
    11/2/2010   718748
    11/3/2010   799355
    11/4/2010   805800
    11/5/2010   701262
    11/6/2010   531579
    11/7/2010   690068
    11/8/2010   756947
    11/9/2010   718757
    11/10/2010  701768
    11/11/2010  820113
    11/12/2010  645259"
    dm <- read.table(textConnection(Lines), header = TRUE)
    dm <- mutate(dm, Date = as.Date(dm$Date, "%m/%d/%Y"))
    ggplot(data = dm, aes(Date, Visits)) + 
    geom_line() + 
    scale_x_date(format = "%b %d", major =  "1 day")

CSS: How can I set image size relative to parent height?

Original Answer:

If you are ready to opt for CSS3, you can use css3 translate property. Resize based on whatever is bigger. If your height is bigger and width is smaller than container, width will be stretch to 100% and height will be trimmed from both side. Same goes for larger width as well.

Your need, HTML:

<div class="img-wrap">
  <img src="http://lorempixel.com/300/160/nature/" />
</div>
<div class="img-wrap">
  <img src="http://lorempixel.com/300/200/nature/" />
</div>
<div class="img-wrap">
  <img src="http://lorempixel.com/200/300/nature/" />
</div>

And CSS:

.img-wrap {
  width: 200px;
  height: 150px;
  position: relative;
  display: inline-block;
  overflow: hidden;
  margin: 0;
}

div > img {
  display: block;
  position: absolute;
  top: 50%;
  left: 50%;
  min-height: 100%;
  min-width: 100%;
  transform: translate(-50%, -50%);
}

Voila! Working: http://jsfiddle.net/shekhardesigner/aYrhG/

Explanation

DIV is set to the relative position. This means all the child elements will get the starting coordinates (origins) from where this DIV starts.

The image is set as a BLOCK element, min-width/height both set to 100% means to resize the image no matter of its size to be the minimum of 100% of it's parent. min is the key. If by min-height, the image height exceeded the parent's height, no problem. It will look for if min-width and try to set the minimum height to be 100% of parents. Both goes vice-versa. This ensures there are no gaps around the div but image is always bit bigger and gets trimmed by overflow:hidden;

Now image, this is set to an absolute position with left:50% and top:50%. Means push the image 50% from the top and left making sure the origin is taken from DIV. Left/Top units are measured from the parent.

Magic moment:

transform: translate(-50%, -50%);

Now, this translate function of CSS3 transform property moves/repositions an element in question. This property deals with the applied element hence the values (x, y) OR (-50%, -50%) means to move the image negative left by 50% of image size and move to the negative top by 50% of image size.

Eg. if Image size was 200px × 150px, transform:translate(-50%, -50%) will calculated to translate(-100px, -75px). % unit helps when we have various size of image.

This is just a tricky way to figure out centroid of the image and the parent DIV and match them.

Apologies for taking too long to explain!

Resources to read more:

Python: How to use RegEx in an if statement?

if re.search(r'pattern', string):

Simple if-test:

if re.search(r'ing\b', "seeking a great perhaps"):     # any words end with ing?
    print("yes")

Pattern check, extract a substring, case insensitive:

match_object = re.search(r'^OUGHT (.*) BE$', "ought to be", flags=re.IGNORECASE)
if match_object:
    assert "to" == match_object.group(1)     # what's between ought and be?

Notes:

  • Use re.search() not re.match. Match restricts to the start of strings, a confusing convention if you ask me. If you do want a string-starting match, use caret or \A instead, re.search(r'^...', ...)

  • Use raw string syntax r'pattern' for the first parameter. Otherwise you would need to double up backslashes, as in re.search('ing\\b', ...)

  • In this example, \b is a special sequence meaning word-boundary in regex. Not to be confused with backspace.

  • re.search() returns None if it doesn't find anything, which is always falsy.

  • re.search() returns a Match object if it finds anything, which is always truthy.

  • a group is what matched inside parentheses

  • group numbering starts at 1

  • Specs

  • Tutorial

Bootstrap Alert Auto Close

I found this to be a better solution

$(".alert-dismissible").fadeTo(2000, 500).slideUp(500, function(){
    $(".alert-dismissible").alert('close');
});

Git copy changes from one branch to another

git checkout BranchB
git merge BranchA
git push origin BranchB

This is all if you intend to not merge your changes back to master. Generally it is a good practice to merge all your changes back to master, and create new branches off of that.

Also, after the merge command, you will have some conflicts, which you will have to edit manually and fix.

Make sure you are in the branch where you want to copy all the changes to. git merge will take the branch you specify and merge it with the branch you are currently in.

Adding backslashes without escaping [Python]

Python treats \ in literal string in a special way.
This is so you can type '\n' to mean newline or '\t' to mean tab
Since '\&' doesn't mean anything special to Python, instead of causing an error, the Python lexical analyser implicitly adds the extra \ for you.

Really it is better to use \\& or r'\&' instead of '\&'

The r here means raw string and means that \ isn't treated specially unless it is right before the quote character at the start of the string.

In the interactive console, Python uses repr to display the result, so that is why you see the double '\'. If you print your string or use len(string) you will see that it is really only the 2 characters

Some examples

>>> 'Here\'s a backslash: \\'
"Here's a backslash: \\"
>>> print 'Here\'s a backslash: \\'
Here's a backslash: \
>>> 'Here\'s a backslash: \\. Here\'s a double quote: ".'
'Here\'s a backslash: \\. Here\'s a double quote: ".'
>>> print 'Here\'s a backslash: \\. Here\'s a double quote: ".'
Here's a backslash: \. Here's a double quote ".

To Clarify the point Peter makes in his comment see this link

Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) It is also important to note that the escape sequences marked as “(Unicode only)” in the table above fall into the category of unrecognized escapes for non-Unicode string literals.

Close application and launch home screen on Android

Use the finish method. It is the simpler and easier method.

this.finish();

What are enums and why are they useful?

From Java documents -

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

A common example is to replace a class with a set of private static final int constants (within reasonable number of constants) with an enum type. Basically if you think you know all possible values of "something" at compile time you can represent that as an enum type. Enums provide readability and flexibility over a class with constants.

Few other advantages that I can think of enum types. They is always one instance of a particular enum class (hence the concept of using enums as singleton arrives). Another advantage is you can use enums as a type in switch-case statement. Also you can use toString() on the enum to print them as readable strings.

How to import and use image in a Vue single file component?

You can also use the root shortcut like so

  <template>
   <div class="container">
    <h1>Recipes</h1>
      <img src="@/assets/burger.jpg" />
   </div>
  </template>

Although this was Nuxt, it should be same with Vue CLI.

Managing jQuery plugin dependency in webpack

For global access to jquery then several options exist. In my most recent webpack project, I wanted global access to jquery so I added the following to my plugins declarations:

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

This then means that jquery is accessible from within the JavaScript source code via global references $ and jQuery.

Of course, you need to have also installed jquery via npm:

$ npm i jquery --save

For a working example of this approach please feel free to fork my app on github

Draw an X in CSS

Yet another attempt... this one uses ×. A lot of the examples on this page only show for me as a box, but &times; works

HTML

<div class="close"></div>

CSS

.close {
    height: 100px;
    width: 100px;
    background-color: #FA6900;
    border-radius: 5px;
}
.close:after {
    position:relative;
    content:"\d7";
    font-size:177px;
    color:white;
    font-weight:bold;
    top:-53px;
    left:-2px
}

JSFIDDLE

how to refresh page in angular 2

The simplest possible solution I found was:

In your markup:

<a [href]="location.path()">Reload</a>

and in your component typescript file:

constructor(
        private location: Location
  ) { }

Jar mismatch! Fix your dependencies

In my case there was another directory within my workspace, having the same jar file as the one in my project. I hadn't created that directory or anything in it. It was created by Eclipse I believe. I just erased that directory and it just runs ok.

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

React.Fragment

fixed the issue for me

Error Code:

 return (
            <section className={classes.itemForm}>
             <Card>
             </Card> 
            </section>
      );

Fix

 return (
      <React.Fragment>
        <section className={classes.itemForm}>
         <Card>
         </Card> 
        </section>
      </React.Fragment>
  );

php $_POST array empty upon form submission

OK, I thought that I should put my case here .... I was getting the post array empty in specific cases .. The form works well, but some times users complain that they hit submit button, and nothing happens ..... After digging for a while, I discovered that my hosting company has a security module that checks users inputs and clears the whole post array (not only the malicious data) if it discovers so. In my example, a math teacher was trying to enter the equation: dy + dx + 0 = 0; and data was wiped completely.

To fix this, I just advise him now to enter the data in the text area as dy + dx + 0 = zero, and now it works .... This can save someone some time ..

What is the <leader> in a .vimrc file?

Vim's <leader> key is a way of creating a namespace for commands you want to define. Vim already maps most keys and combinations of Ctrl + (some key), so <leader>(some key) is where you (or plugins) can add custom behavior.

For example, if you find yourself frequently deleting exactly 3 words and 7 characters, you might find it convenient to map a command via nmap <leader>d 3dw7x so that pressing the leader key followed by d will delete 3 words and 7 characters. Because it uses the leader key as a prefix, you can be (relatively) assured that you're not stomping on any pre-existing behavior.

The default key for <leader> is \, but you can use the command :let mapleader = "," to remap it to another key (, in this case).

Usevim's page on the leader key has more information.

XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

You can try putting 'Access-Control-Allow-Origin':'*' in response.writeHead(, {[here]}).

Passing Variable through JavaScript from one html page to another page

You have a few different options:

  • you can use a SPA router like SammyJS, or Angularjs and ui-router, so your pages are stateful.
  • use sessionStorage to store your state.
  • store the values on the URL hash.

Check if a value exists in pandas dataframe index

df = pandas.DataFrame({'g':[1]}, index=['isStop'])

#df.loc['g']

if 'g' in df.index:
    print("find g")

if 'isStop' in df.index:
    print("find a") 

Add line break to ::after or ::before pseudo-element content

You may try this

#headerAgentInfoDetailsPhone
{
    white-space:pre
}
#headerAgentInfoDetailsPhone:after {
    content:"Office: XXXXX \A Mobile: YYYYY ";
}

Js Fiddle

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

Liam's link looks great, but also check out pandas.Timedelta - looks like it plays nicely with NumPy's and Python's time deltas.

https://pandas.pydata.org/pandas-docs/stable/timedeltas.html

pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)

Creating an IFRAME using JavaScript

It is better to process HTML as a template than to build nodes via JavaScript (HTML is not XML after all.) You can keep your IFRAME's HTML syntax clean by using a template and then appending the template's contents into another DIV.

<div id="placeholder"></div>

<script id="iframeTemplate" type="text/html">
    <iframe src="...">
        <!-- replace this line with alternate content -->
    </iframe>
</script>

<script type="text/javascript">
var element,
    html,
    template;

element = document.getElementById("placeholder");
template = document.getElementById("iframeTemplate");
html = template.innerHTML;

element.innerHTML = html;
</script>

JavaScript adding decimal numbers issue

This is common issue with floating points.

Use toFixed in combination with parseFloat.

Here is example in JavaScript:

function roundNumber(number, decimals) {
    var newnumber = new Number(number+'').toFixed(parseInt(decimals));
    return parseFloat(newnumber); 
}

0.1 + 0.2;                    //=> 0.30000000000000004
roundNumber( 0.1 + 0.2, 12 ); //=> 0.3

HttpServletRequest - how to obtain the referring URL?

It's available in the HTTP referer header. You can get it in a servlet as follows:

String referrer = request.getHeader("referer"); // Yes, with the legendary misspelling.

You, however, need to realize that this is a client-controlled value and can thus be spoofed to something entirely different or even removed. Thus, whatever value it returns, you should not use it for any critical business processes in the backend, but only for presentation control (e.g. hiding/showing/changing certain pure layout parts) and/or statistics.

For the interested, background about the misspelling can be found in Wikipedia.

How to run certain task every day at a particular time using ScheduledExecutorService?

I had a similar problem. I had to schedule bunch of tasks that should be executed during a day using ScheduledExecutorService. This was solved by one task starting at 3:30 AM scheduling all other tasks relatively to his current time. And rescheduling himself for the next day at 3:30 AM.

With this scenario daylight savings are not an issue anymore.

How to prevent custom views from losing state across screen orientation changes

The answers here already are great, but don't necessarily work for custom ViewGroups. To get all custom Views to retain their state, you must override onSaveInstanceState() and onRestoreInstanceState(Parcelable state) in each class. You also need to ensure they all have unique ids, whether they're inflated from xml or added programmatically.

What I came up with was remarkably like Kobor42's answer, but the error remained because I was adding the Views to a custom ViewGroup programmatically and not assigning unique ids.

The link shared by mato will work, but it means none of the individual Views manage their own state - the entire state is saved in the ViewGroup methods.

The problem is that when multiple of these ViewGroups are added to a layout, the ids of their elements from the xml are no longer unique (if its defined in xml). At runtime, you can call the static method View.generateViewId() to get a unique id for a View. This is only available from API 17.

Here is my code from the ViewGroup (it is abstract, and mOriginalValue is a type variable):

public abstract class DetailRow<E> extends LinearLayout {

    private static final String SUPER_INSTANCE_STATE = "saved_instance_state_parcelable";
    private static final String STATE_VIEW_IDS = "state_view_ids";
    private static final String STATE_ORIGINAL_VALUE = "state_original_value";

    private E mOriginalValue;
    private int[] mViewIds;

// ...

    @Override
    protected Parcelable onSaveInstanceState() {

        // Create a bundle to put super parcelable in
        Bundle bundle = new Bundle();
        bundle.putParcelable(SUPER_INSTANCE_STATE, super.onSaveInstanceState());
        // Use abstract method to put mOriginalValue in the bundle;
        putValueInTheBundle(mOriginalValue, bundle, STATE_ORIGINAL_VALUE);
        // Store mViewIds in the bundle - initialize if necessary.
        if (mViewIds == null) {
            // We need as many ids as child views
            mViewIds = new int[getChildCount()];
            for (int i = 0; i < mViewIds.length; i++) {
                // generate a unique id for each view
                mViewIds[i] = View.generateViewId();
                // assign the id to the view at the same index
                getChildAt(i).setId(mViewIds[i]);
            }
        }
        bundle.putIntArray(STATE_VIEW_IDS, mViewIds);
        // return the bundle
        return bundle;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {

        // We know state is a Bundle:
        Bundle bundle = (Bundle) state;
        // Get mViewIds out of the bundle
        mViewIds = bundle.getIntArray(STATE_VIEW_IDS);
        // For each id, assign to the view of same index
        if (mViewIds != null) {
            for (int i = 0; i < mViewIds.length; i++) {
                getChildAt(i).setId(mViewIds[i]);
            }
        }
        // Get mOriginalValue out of the bundle
        mOriginalValue = getValueBackOutOfTheBundle(bundle, STATE_ORIGINAL_VALUE);
        // get super parcelable back out of the bundle and pass it to
        // super.onRestoreInstanceState(Parcelable)
        state = bundle.getParcelable(SUPER_INSTANCE_STATE);
        super.onRestoreInstanceState(state);
    } 
}

The most efficient way to remove first N elements in a list?

l = [1, 2, 3, 4, 5]
del l[0:3] # Here 3 specifies the number of items to be deleted.

This is the code if you want to delete a number of items from the list. You might as well skip the zero before the colon. It does not have that importance. This might do as well.

l = [1, 2, 3, 4, 5]
del l[:3] # Here 3 specifies the number of items to be deleted.

Class extending more than one class Java?

Multiple Inheritance

Assume B and C are overriding inherited method and their own implementation. Now D inherits both B & C using multiple inheritance. D should inherit the overridden method.The Question is which overridden method will be used? Will it be from B or C? Here we have an ambiguity. To exclude such situation multiple inheritance was not used in Java.

Combine two pandas Data Frames (join on a common column)

In case anyone needs to try and merge two dataframes together on the index (instead of another column), this also works!

T1 and T2 are dataframes that have the same indices

import pandas as pd
T1 = pd.merge(T1, T2, on=T1.index, how='outer')

P.S. I had to use merge because append would fill NaNs in unnecessarily.

Is it possible to get multiple values from a subquery?

Here are two methods to get more than 1 column in a scalar subquery (or inline subquery) and querying the lookup table only once. This is a bit convoluted but can be the very efficient in some special cases.

  1. You can use concatenation to get several columns at once:

    SELECT x, 
           regexp_substr(yz, '[^^]+', 1, 1) y,
           regexp_substr(yz, '[^^]+', 1, 2) z
      FROM (SELECT a.x,
                   (SELECT b.y || '^' || b.z yz
                      FROM b
                     WHERE b.v = a.v)
                      yz
              FROM a)
    

    You would need to make sure that no column in the list contain the separator character.

  2. You could also use SQL objects:

    CREATE OR REPLACE TYPE b_obj AS OBJECT (y number, z number);
    
    SELECT x, 
           v.yz.y y,
           v.yz.z z
      FROM (SELECT a.x,
                   (SELECT b_obj(y, z) yz
                      FROM b
                     WHERE b.v = a.v)
                      yz
              FROM a) v
    

Default value to a parameter while passing by reference in C++

You can do it for a const reference, but not for a non-const one. This is because C++ does not allow a temporary (the default value in this case) to be bound to non-const reference.

One way round this would be to use an actual instance as the default:

static int AVAL = 1;

void f( int & x = AVAL ) {
   // stuff
} 

int main() {
     f();       // equivalent to f(AVAL);
}

but this is of very limited practical use.

Make outer div be automatically the same height as its floating content

Use clear: both;

I spent over a week trying to figure this out!

Comparing double values in C#

Taking a tip from the Java code base, try using .CompareTo and test for the zero comparison. This assumes the .CompareTo function takes in to account floating point equality in an accurate manner. For instance,

System.Math.PI.CompareTo(System.Math.PI) == 0

This predicate should return true.

How to watch for a route change in AngularJS?

Note: This is a proper answer for a legacy version of AngularJS. See this question for updated versions.

$scope.$on('$routeChangeStart', function($event, next, current) { 
   // ... you could trigger something here ...
 });

The following events are also available (their callback functions take different arguments):

  • $routeChangeSuccess
  • $routeChangeError
  • $routeUpdate - if reloadOnSearch property has been set to false

See the $route docs.

There are two other undocumented events:

  • $locationChangeStart
  • $locationChangeSuccess

See What's the difference between $locationChangeSuccess and $locationChangeStart?

How to run 'sudo' command in windows

in Windows, you can use the runas command. For linux users, there are some alternatives for sudo in windows, you can check this out

http://helpdeskgeek.com/free-tools-review/5-windows-alternatives-linux-sudo-command/

AngularJS How to dynamically add HTML and bind to controller

For those, like me, who did not have the possibility to use angular directive and were "stuck" outside of the angular scope, here is something that might help you.

After hours searching on the web and on the angular doc, I have created a class that compiles HTML, place it inside a targets, and binds it to a scope ($rootScope if there is no $scope for that element)

/**
 * AngularHelper : Contains methods that help using angular without being in the scope of an angular controller or directive
 */
var AngularHelper = (function () {
    var AngularHelper = function () { };

    /**
     * ApplicationName : Default application name for the helper
     */
    var defaultApplicationName = "myApplicationName";

    /**
     * Compile : Compile html with the rootScope of an application
     *  and replace the content of a target element with the compiled html
     * @$targetDom : The dom in which the compiled html should be placed
     * @htmlToCompile : The html to compile using angular
     * @applicationName : (Optionnal) The name of the application (use the default one if empty)
     */
    AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
        var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);

        $injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
            //Get the scope of the target, use the rootScope if it does not exists
            var $scope = $targetDom.html(htmlToCompile).scope();
            $compile($targetDom)($scope || $rootScope);
            $rootScope.$digest();
        }]);
    }

    return AngularHelper;
})();

It covered all of my cases, but if you find something that I should add to it, feel free to comment or edit.

Hope it will help.

How to simulate key presses or a click with JavaScript?

Focus might be what your looking for. With tabbing or clicking I think u mean giving the element the focus. Same code as Russ (Sorry i stole it :P) but firing an other event.

// this must be done after input1 exists in the DOM
var element = document.getElementById("input1");

if (element) element.focus();

How can I position my div at the bottom of its container?

If you do not know the height of child block:

_x000D_
_x000D_
#parent {_x000D_
    background:green;_x000D_
    width:200px;_x000D_
    height:200px;_x000D_
    display:table-cell;_x000D_
    vertical-align:bottom;_x000D_
}_x000D_
.child {_x000D_
    background:red;_x000D_
    vertical-align:bottom;_x000D_
}
_x000D_
<div id="parent">_x000D_
    <div class="child">child_x000D_
    </div> _x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsbin.com/ULUXIFon/3/edit

If you know the height of the child block add the child block then add padding-top/margin-top:

_x000D_
_x000D_
#parent {_x000D_
    background:green;_x000D_
    width:200px;_x000D_
    height:130px;_x000D_
    padding-top:70px;_x000D_
}_x000D_
.child {_x000D_
    background:red;_x000D_
    vertical-align:_x000D_
    bottom;_x000D_
    height:130px;_x000D_
}
_x000D_
<div id="parent">_x000D_
    <div class="child">child_x000D_
    </div> _x000D_
</div>  
_x000D_
_x000D_
_x000D_

Downloading a large file using curl

You can use this function, which creates a tempfile in the filesystem and returns the path to the downloaded file if everything worked fine:

function getFileContents($url)
{
    // Workaround: Save temp file
    $img = tempnam(sys_get_temp_dir(), 'pdf-');
    $img .= '.' . pathinfo($url, PATHINFO_EXTENSION);

    $fp = fopen($img, 'w+');

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    $result = curl_exec($ch);
    curl_close($ch);

    fclose($fp);

    return $result ? $img : false;
}

How to stop PHP code execution?

You could try to kill the PHP process:

exec('kill -9 ' . getmypid());

Python: Binary To Decimal Conversion

You can use int casting which allows the base specification.

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

Apache giving 403 forbidden errors

restorecon command works as below :

restorecon -v -R /var/www/html/

How do I escape spaces in path for scp copy in Linux?

works

scp localhost:"f/a\ b\ c" .

scp localhost:'f/a\ b\ c' .

does not work

scp localhost:'f/a b c' .

The reason is that the string is interpreted by the shell before the path is passed to the scp command. So when it gets to the remote the remote is looking for a string with unescaped quotes and it fails

To see this in action, start a shell with the -vx options ie bash -vx and it will display the interpolated version of the command as it runs it.

Android WSDL/SOAP service client

Android doesn't come with SOAP library. However, you can download 3rd party library here:
https://github.com/simpligility/ksoap2-android

If you need help using it, you might find this thread helpful:
How to call a .NET Webservice from Android using KSOAP2?

How can I make a float top with CSS?

This works, apply in ul:

display:flex;
flex-direction:column;
flex-wrap:wrap;

How to use background thread in swift?

Good answers though, anyway I want to share my Object Oriented solution Up to date for swift 5.

please check it out: AsyncTask

Conceptually inspired by android's AsyncTask, I've wrote my own class in Swift

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread.

Here are few usage examples

Example 1 -

AsyncTask(backgroundTask: {(p:String)->Void in//set BGParam to String and BGResult to Void
        print(p);//print the value in background thread
    }).execute("Hello async");//execute with value 'Hello async'

Example 2 -

let task2=AsyncTask(beforeTask: {
           print("pre execution");//print 'pre execution' before backgroundTask
        },backgroundTask:{(p:Int)->String in//set BGParam to Int & BGResult to String
            if p>0{//check if execution value is bigger than zero
               return "positive"//pass String "poitive" to afterTask
            }
            return "negative";//otherwise pass String "negative"
        }, afterTask: {(p:String) in
            print(p);//print background task result
    });
    task2.execute(1);//execute with value 1

It has 2 generic types:

  • BGParam - the type of the parameter sent to the task upon execution.

  • BGResult - the type of the result of the background computation.

    When you create an AsyncTask you can those types to whatever you need to pass in and out of the background task, but if you don't need those types, you can mark it as unused with just setting it to: Void or with shorter syntax: ()

When an asynchronous task is executed, it goes through 3 steps:

  1. beforeTask:()->Void invoked on the UI thread just before the task is executed.
  2. backgroundTask: (param:BGParam)->BGResult invoked on the background thread immediately after
  3. afterTask:(param:BGResult)->Void invoked on the UI thread with result from the background task

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

I had this problem and it was because the panel was outside of the [data-role="page"] element.

how to get the ipaddress of a virtual box running on local machine

Login to virtual machine use below command to check ip address. (anyone will work)

  1. ifconfig
  2. ip addr show

If you used NAT for your virtual machine settings(your machine ip will be 10.0.2.15), then you have to use port forwarding to connect to machine. IP address will be 127.0.0.1

If you used bridged networking/Host only networking, then you will have separate Ip address. Use that IP address to connect virtual machine

How To Add An "a href" Link To A "div"?

try to implement with javascript this:

<div id="mydiv" onclick="myhref('http://web.com');" >some stuff </div>
<script type="text/javascript">
    function myhref(web){
      window.location.href = web;}
</script>

HTML5 and frameborder

Since the frameborder attribute is only necessary for IE, there is another way to get around the validator. This is a lightweight way that doesn't require Javascript or any DOM manipulation.

<!--[if IE]>
   <iframe src="source" frameborder="0">?</iframe>
<![endif]-->
<!--[if !IE]>-->
   <iframe src="source" style="border:none">?</iframe>
<!-- <![endif]-->

How would one write object-oriented code in C?

Yes, but I have never seen anyone attempt to implement any sort of polymorphism with C.

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

http://www.aspsnippets.com/Articles/The-OLE-DB-provider-Microsoft.Ace.OLEDB.12.0-for-linked-server-null.aspx

This solves the issue. For some reason SQL Server does not like the default MSSQLSERVER account. Switching it to a local user account resolves the issue.

Saving binary data as file using JavaScript from a browser

To do this task download.js library can be used. Here is an example from library docs:

download("data:image/gif;base64,R0lGODlhRgAVAIcAAOfn5+/v7/f39////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////yH5BAAAAP8ALAAAAABGABUAAAj/AAEIHAgggMGDCAkSRMgwgEKBDRM+LBjRoEKDAjJq1GhxIMaNGzt6DAAypMORJTmeLKhxgMuXKiGSzPgSZsaVMwXUdBmTYsudKjHuBCoAIc2hMBnqRMqz6MGjTJ0KZcrz5EyqA276xJrVKlSkWqdGLQpxKVWyW8+iJcl1LVu1XttafTs2Lla3ZqNavAo37dm9X4eGFQtWKt+6T+8aDkxUqWKjeQUvfvw0MtHJcCtTJiwZsmLMiD9uplvY82jLNW9qzsy58WrWpDu/Lp0YNmPXrVMvRm3T6GneSX3bBt5VeOjDemfLFv1XOW7kncvKdZi7t/S7e2M3LkscLcvH3LF7HwSuVeZtjuPPe2d+GefPrD1RpnS6MGdJkebn4/+oMSAAOw==", "dlDataUrlBin.gif", "image/gif");

How to align LinearLayout at the center of its parent?

add layout_gravity="center" or "center_horizontal" to the parent layout.

On a side note, your LinearLayout inside your TableRow seems un-necessary, as a TableRow is already an horizontal LinearLayout.

How to find children of nodes using BeautifulSoup

"How to find all a which are children of <li class=test> but not any others?"

Given the HTML below (I added another <a> to show te difference between select and select_one):

<div>
  <li class="test">
    <a>link1</a>
    <ul>
      <li>
        <a>link2</a>
      </li>
    </ul>
    <a>link3</a>
  </li>
</div>

The solution is to use child combinator (>) that is placed between two CSS selectors:

>>> soup.select('li.test > a')
[<a>link1</a>, <a>link3</a>]

In case you want to find only the first child:

>>> soup.select_one('li.test > a')
<a>link1</a>

Removing element from array in component state

I want to chime in here even though this question has already been answered correctly by @pscl in case anyone else runs into the same issue I did. Out of the 4 methods give I chose to use the es6 syntax with arrow functions due to it's conciseness and lack of dependence on external libraries:

Using Array.prototype.filter with ES6 Arrow Functions

removeItem(index) {
  this.setState((prevState) => ({
    data: prevState.data.filter((_, i) => i != index)
  }));
}

As you can see I made a slight modification to ignore the type of index (!== to !=) because in my case I was retrieving the index from a string field.

Another helpful point if you're seeing weird behavior when removing an element on the client side is to NEVER use the index of an array as the key for the element:

// bad
{content.map((content, index) =>
  <p key={index}>{content.Content}</p>
)}

When React diffs with the virtual DOM on a change, it will look at the keys to determine what has changed. So if you're using indices and there is one less in the array, it will remove the last one. Instead, use the id's of the content as keys, like this.

// good
{content.map(content =>
  <p key={content.id}>{content.Content}</p>
)}

The above is an excerpt from this answer from a related post.

Happy Coding Everyone!

Remove all special characters except space from a string using JavaScript

Try this:

const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);

Decrementing for loops

range step should be -1

   for k in range(10,0,-1):
      print k

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

What's "tools:context" in Android layout files?

This is the activity the tools UI editor uses to render your layout preview. It is documented here:

This attribute declares which activity this layout is associated with by default. This enables features in the editor or layout preview that require knowledge of the activity, such as what the layout theme should be in the preview and where to insert onClick handlers when you make those from a quickfix

MongoDB: Is it possible to make a case-insensitive query?

The aggregation framework was introduced in mongodb 2.2 . You can use the string operator "$strcasecmp" to make a case-insensitive comparison between strings. It's more recommended and easier than using regex.

Here's the official document on the aggregation command operator: https://docs.mongodb.com/manual/reference/operator/aggregation/strcasecmp/#exp._S_strcasecmp .

How to bind Close command to a button

For .NET 4.5 SystemCommands class will do the trick (.NET 4.0 users can use WPF Shell Extension google - Microsoft.Windows.Shell or Nicholas Solution).

    <Window.CommandBindings>
        <CommandBinding Command="{x:Static SystemCommands.CloseWindowCommand}" 
                        CanExecute="CloseWindow_CanExec" 
                        Executed="CloseWindow_Exec" />
    </Window.CommandBindings>
    <!-- Binding Close Command to the button control -->
    <Button ToolTip="Close Window" Content="Close" Command="{x:Static SystemCommands.CloseWindowCommand}"/>

In the Code Behind you can implement the handlers like this:

    private void CloseWindow_CanExec(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }

    private void CloseWindow_Exec(object sender, ExecutedRoutedEventArgs e)
    {
        SystemCommands.CloseWindow(this);
    }

MySQL - length() vs char_length()

varchar(10) will store 10 characters, which may be more than 10 bytes. In indexes, it will allocate the maximium length of the field - so if you are using UTF8-mb4, it will allocate 40 bytes for the 10 character field.

Java Date cut off time information

I did the truncation with new java8 API. I faced up with one strange thing but in general it's truncate...

Instant instant = date.toInstant();
instant = instant.truncatedTo(ChronoUnit.DAYS);
date = Date.from(instant);

How to keep :active css style after click a button

I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY

We're going to to be using a hidden checkbox.
This example includes one "on click - off click 'hover / active' state"

--

To make content itself clickable:

HTML

<input type="checkbox" id="activate-div">
  <label for="activate-div">
   <div class="my-div">
      //MY DIV CONTENT
   </div>
  </label>

CSS

#activate-div{display:none}    

.my-div{background-color:#FFF} 

#activate-div:checked ~ label 
.my-div{background-color:#000}



To make button change content:

HTML

<input type="checkbox" id="activate-div">
   <div class="my-div">
      //MY DIV CONTENT
   </div>

<label for="activate-div">
   //MY BUTTON STUFF
</label>

CSS

#activate-div{display:none}

.my-div{background-color:#FFF} 

#activate-div:checked + 
.my-div{background-color:#000}

Hope it helps!!

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

Data binding to SelectedItem in a WPF Treeview

There is also a way to create XAML bindable SelectedItem property without using Interaction.Behaviors.

public static class BindableSelectedItemHelper
{
    #region Properties

    public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.RegisterAttached("SelectedItem", typeof(object), typeof(BindableSelectedItemHelper),
        new FrameworkPropertyMetadata(null, OnSelectedItemPropertyChanged));

    public static readonly DependencyProperty AttachProperty = DependencyProperty.RegisterAttached("Attach", typeof(bool), typeof(BindableSelectedItemHelper), new PropertyMetadata(false, Attach));

    private static readonly DependencyProperty IsUpdatingProperty = DependencyProperty.RegisterAttached("IsUpdating", typeof(bool), typeof(BindableSelectedItemHelper));

    #endregion

    #region Implementation

    public static void SetAttach(DependencyObject dp, bool value)
    {
        dp.SetValue(AttachProperty, value);
    }

    public static bool GetAttach(DependencyObject dp)
    {
        return (bool)dp.GetValue(AttachProperty);
    }

    public static string GetSelectedItem(DependencyObject dp)
    {
        return (string)dp.GetValue(SelectedItemProperty);
    }

    public static void SetSelectedItem(DependencyObject dp, object value)
    {
        dp.SetValue(SelectedItemProperty, value);
    }

    private static bool GetIsUpdating(DependencyObject dp)
    {
        return (bool)dp.GetValue(IsUpdatingProperty);
    }

    private static void SetIsUpdating(DependencyObject dp, bool value)
    {
        dp.SetValue(IsUpdatingProperty, value);
    }

    private static void Attach(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        TreeListView treeListView = sender as TreeListView;
        if (treeListView != null)
        {
            if ((bool)e.OldValue)
                treeListView.SelectedItemChanged -= SelectedItemChanged;

            if ((bool)e.NewValue)
                treeListView.SelectedItemChanged += SelectedItemChanged;
        }
    }

    private static void OnSelectedItemPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        TreeListView treeListView = sender as TreeListView;
        if (treeListView != null)
        {
            treeListView.SelectedItemChanged -= SelectedItemChanged;

            if (!(bool)GetIsUpdating(treeListView))
            {
                foreach (TreeViewItem item in treeListView.Items)
                {
                    if (item == e.NewValue)
                    {
                        item.IsSelected = true;
                        break;
                    }
                    else
                       item.IsSelected = false;                        
                }
            }

            treeListView.SelectedItemChanged += SelectedItemChanged;
        }
    }

    private static void SelectedItemChanged(object sender, RoutedEventArgs e)
    {
        TreeListView treeListView = sender as TreeListView;
        if (treeListView != null)
        {
            SetIsUpdating(treeListView, true);
            SetSelectedItem(treeListView, treeListView.SelectedItem);
            SetIsUpdating(treeListView, false);
        }
    }
    #endregion
}

You can then use this in your XAML as:

<TreeView  helper:BindableSelectedItemHelper.Attach="True" 
           helper:BindableSelectedItemHelper.SelectedItem="{Binding SelectedItem, Mode=TwoWay}">

How can I capture the right-click event in JavaScript?

Use the oncontextmenu event.

Here's an example:

<div oncontextmenu="javascript:alert('success!');return false;">
    Lorem Ipsum
</div>

And using event listeners (credit to rampion from a comment in 2011):

el.addEventListener('contextmenu', function(ev) {
    ev.preventDefault();
    alert('success!');
    return false;
}, false);

Don't forget to return false, otherwise the standard context menu will still pop up.

If you are going to use a function you've written rather than javascript:alert("Success!"), remember to return false in BOTH the function AND the oncontextmenu attribute.

document.getElementById(id).focus() is not working for firefox or chrome

I suspect the reason this works is the browser rendering runs on the same thread as javascript, and setTimeout(function(){},0); queues the javascript function inside setTimeout to execute when the browser becomes idle. If anyone has a more in-depth explanation please share it.

setTimeout(function(){ 
 if(document.getElementById('mobileno')){
  document.getElementById('mobileno').focus();
 } 
},0);

How to select a range of the second row to the last row

Sub SelectAllCellsInSheet(SheetName As String)
    lastCol = Sheets(SheetName).Range("a1").End(xlToRight).Column
    Lastrow = Sheets(SheetName).Cells(1, 1).End(xlDown).Row
    Sheets(SheetName).Range("A2", Sheets(SheetName).Cells(Lastrow, lastCol)).Select
End Sub

To use with ActiveSheet:

Call SelectAllCellsInSheet(ActiveSheet.Name)

Why use @PostConstruct?

The main problem is that:

in a constructor, the injection of the dependencies has not yet occurred*

*obviously excluding Constructor Injection


Real-world example:

public class Foo {

    @Inject
    Logger LOG;

    @PostConstruct
    public void fooInit(){
        LOG.info("This will be printed; LOG has already been injected");
    }

    public Foo() {
        LOG.info("This will NOT be printed, LOG is still null");
        // NullPointerException will be thrown here
    }
}

IMPORTANT: @PostConstruct and @PreDestroy have been completely removed in Java 11.

To keep using them, you'll need to add the javax.annotation-api JAR to your dependencies.

Maven

<!-- https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api -->
<dependency>
    <groupId>javax.annotation</groupId>
    <artifactId>javax.annotation-api</artifactId>
    <version>1.3.2</version>
</dependency>

Gradle

// https://mvnrepository.com/artifact/javax.annotation/javax.annotation-api
compile group: 'javax.annotation', name: 'javax.annotation-api', version: '1.3.2'

Extracting time from POSIXct

There have been previous answers that showed the trick. In essence:

  • you must retain POSIXct types to take advantage of all the existing plotting functions

  • if you want to 'overlay' several days worth on a single plot, highlighting the intra-daily variation, the best trick is too ...

  • impose the same day (and month and even year if need be, which is not the case here)

which you can do by overriding the day-of-month and month components when in POSIXlt representation, or just by offsetting the 'delta' relative to 0:00:00 between the different days.

So with times and val as helpfully provided by you:

## impose month and day based on first obs
ntimes <- as.POSIXlt(times)    # convert to 'POSIX list type'
ntimes$mday <- ntimes[1]$mday  # and $mon if it differs too
ntimes <- as.POSIXct(ntimes)   # convert back

par(mfrow=c(2,1))
plot(times,val)   # old times
plot(ntimes,val)  # new times

yields this contrasting the original and modified time scales:

enter image description here

Websocket connections with Postman

This is not possible as of May 2017, because Postman only works with HTTP methods such as POST, GET, PUT, DELETE.

P/S: There is a request for this if you want to upvote: github.com/postmanlabs/postman-app-support/issues/4009

Can a unit test project load the target application's app.config file?

This is a bit old but I found a better solution for this. I was trying the chosen answer here but looks like .testrunconfig is already obsolete.

1. For Unit Tests, Wrap the config is an Interface (IConfig)

for Unit tests, config really shouldn't be part of what your testing so create a mock which you can inject. In this example I was using Moq.

Mock<IConfig> _configMock;
_configMock.Setup(config => config.ConfigKey).Returns("ConfigValue");
var SUT = new SUT(_configMock.Object);

2. For Integration test, dynamically add the config you need

Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if(config.AppSettings.Settings[configName] != null)
{
    config.AppSettings.Settings.Remove(configName);
}
config.AppSettings.Settings.Add(configName, configValue);
config.Save(ConfigurationSaveMode.Modified, true);
ConfigurationManager.RefreshSection("appSettings");

Load dimension value from res/values/dimension.xml from source code

The Resource class also has a method getDimensionPixelSize() which I think will fit your needs.

Running multiple AsyncTasks at the same time -- not possible?

AsyncTask uses a thread pool pattern for running the stuff from doInBackground(). The issue is initially (in early Android OS versions) the pool size was just 1, meaning no parallel computations for a bunch of AsyncTasks. But later they fixed that and now the size is 5, so at most 5 AsyncTasks can run simultaneously. Unfortunately I don't remember in what version exactly they changed that.

UPDATE:

Here is what current (2012-01-27) API says on this:

When first introduced, AsyncTasks were executed serially on a single background thread. Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. After HONEYCOMB, it is planned to change this back to a single thread to avoid common application errors caused by parallel execution. If you truly want parallel execution, you can use the executeOnExecutor(Executor, Params...) version of this method with THREAD_POOL_EXECUTOR; however, see commentary there for warnings on its use.

DONUT is Android 1.6, HONEYCOMB is Android 3.0.

UPDATE: 2

See the comment by kabuko from Mar 7 2012 at 1:27.

It turns out that for APIs where "a pool of threads allowing multiple tasks to operate in parallel" is used (starting from 1.6 and ending on 3.0) the number of simultaneously running AsyncTasks depends on how many tasks have been passed for execution already, but have not finished their doInBackground() yet.

This is tested/confirmed by me on 2.2. Suppose you have a custom AsyncTask that just sleeps a second in doInBackground(). AsyncTasks use a fixed size queue internally for storing delayed tasks. Queue size is 10 by default. If you start 15 your custom tasks in a row, then first 5 will enter their doInBackground(), but the rest will wait in a queue for a free worker thread. As soon as any of the first 5 finishes, and thus releases a worker thread, a task from the queue will start execution. So in this case at most 5 tasks will run simultaneously. However if you start 16 your custom tasks in a row, then first 5 will enter their doInBackground(), the rest 10 will get into the queue, but for the 16th a new worker thread will be created so it'll start execution immediately. So in this case at most 6 tasks will run simultaneously.

There is a limit of how many tasks can be run simultaneously. Since AsyncTask uses a thread pool executor with limited max number of worker threads (128) and the delayed tasks queue has fixed size 10, if you try to execute more than 138 your custom tasks the app will crash with java.util.concurrent.RejectedExecutionException.

Starting from 3.0 the API allows to use your custom thread pool executor via AsyncTask.executeOnExecutor(Executor exec, Params... params) method. This allows, for instance, to configure the size of the delayed tasks queue if default 10 is not what you need.

As @Knossos mentions, there is an option to use AsyncTaskCompat.executeParallel(task, params); from support v.4 library to run tasks in parallel without bothering with API level. This method became deprecated in API level 26.0.0.

UPDATE: 3

Here is a simple test app to play with number of tasks, serial vs. parallel execution: https://github.com/vitkhudenko/test_asynctask

UPDATE: 4 (thanks @penkzhou for pointing this out)

Starting from Android 4.4 AsyncTask behaves differently from what was described in UPDATE: 2 section. There is a fix to prevent AsyncTask from creating too many threads.

Before Android 4.4 (API 19) AsyncTask had the following fields:

private static final int CORE_POOL_SIZE = 5;
private static final int MAXIMUM_POOL_SIZE = 128;
private static final BlockingQueue<Runnable> sPoolWorkQueue =
        new LinkedBlockingQueue<Runnable>(10);

In Android 4.4 (API 19) the above fields are changed to this:

private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final BlockingQueue<Runnable> sPoolWorkQueue =
        new LinkedBlockingQueue<Runnable>(128);

This change increases the size of the queue to 128 items and reduces the maximum number of threads to the number of CPU cores * 2 + 1. Apps can still submit the same number of tasks.

SQL Server: UPDATE a table by using ORDER BY

I ran into the same problem and was able to resolve it in very powerful way that allows unlimited sorting possibilities.

I created a View using (saving) 2 sort orders (*explanation on how to do so below).

After that I simply applied the update queries to the View created and it worked great.

Here are the 2 queries I used on the view:

1st Query:

Update  MyView
Set SortID=0


2nd Query:

DECLARE @sortID int
SET     @sortID = 0
UPDATE  MyView
SET     @sortID = sortID = @sortID + 1


*To be able to save the sorting on the View I put TOP into the SELECT statement. This very useful workaround allows the View results to be returned sorted as set when the View was created when the View is opened. In my case it looked like:

(NOTE: Using this workaround will place an big load on the server if using a large table and it is therefore recommended to include as few fields as possible in the view if working with large tables)

SELECT     TOP (600000) 
dbo.Items.ID, dbo.Items.Code, dbo.Items.SortID, dbo.Supplier.Date, 
dbo.Supplier.Code AS Expr1
FROM         dbo.Items INNER JOIN
                      dbo.Supplier ON dbo.Items.SupplierCode = dbo.Supplier.Code
ORDER BY dbo.Supplier.Date, dbo.Items.ID DESC



Running: SQL Server 2005 on a Windows Server 2003

Additional Keywords: How to Update a SQL column with Ascending or Descending Numbers - Numeric Values / how to set order in SQL update statement / how to save order by in sql view / increment sql update / auto autoincrement sql update / create sql field with ascending numbers

Concatenating variables in Bash

Try doing this, there's no special character to concatenate in bash :

mystring="${arg1}12${arg2}endoffile"

explanations

If you don't put brackets, you will ask to concatenate $arg112 + $argendoffile (I guess that's not what you asked) like in the following example :

mystring="$arg112$arg2endoffile"

The brackets are delimiters for the variables when needed. When not needed, you can use it or not.

another solution

(less portable : require bash > 3.1)

$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

See http://mywiki.wooledge.org/BashFAQ/013

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

Multiple Image Upload PHP form with one input

Multipal image uplode with other taBLE $sql1 = "INSERT INTO event(title) VALUES('$title')";

        $result1 = mysqli_query($connection,$sql1) or die(mysqli_error($connection));
        $lastid= $connection->insert_id;
        foreach ($_FILES["file"]["error"] as $key => $error) {
            if ($error == UPLOAD_ERR_OK ){
                $name = $lastid.$_FILES['file']['name'][$key];
                $target_dir = "photo/";
                $sql2 = "INSERT INTO photos(image,eventid) VALUES ('".$target_dir.$name."','".$lastid."')";
                $result2 = mysqli_query($connection,$sql2) or die(mysqli_error($connection));
                move_uploaded_file($_FILES['file']['tmp_name'][$key],$target_dir.$name);
            }
        }

And how to fetch

$query = "SELECT * FROM event ";
$result = mysqli_query($connection,$query) or die(mysqli_error());


  if($result->num_rows > 0) {
      while($r = mysqli_fetch_assoc($result)){
        $eventid= $r['id'];
        $sqli="select id,image from photos where eventid='".$eventid."'";
        $resulti=mysqli_query($connection,$sqli);
        $image_json_array = array();
        while($row = mysqli_fetch_assoc($resulti)){
            $image_id = $row['id'];
            $image_name = $row['image'];
            $image_json_array[] = array("id"=>$image_id,"name"=>$image_name);
        }
        $msg1[] = array ("imagelist" => $image_json_array);

      }

in ajax $(document).ready(function(){ $('#addCAT').validate({ rules:{name:required:true}submitHandler:function(form){var formurl = $(form).attr('action'); $.ajax({ url: formurl,type: "POST",data: new FormData(form),cache: false,processData: false,contentType: false,success: function(data) {window.location.href="{{ url('admin/listcategory')}}";}}); } })})

php: catch exception and continue execution, is it possible?

Another angle on this is returning an Exception, NOT throwing one, from the processing code.

I needed to do this with a templating framework I'm writing. If the user attempts to access a property that doesn't exist on the data, I return the error from deep within the processing function, rather than throwing it.

Then, in the calling code, I can decide whether to throw this returned error, causing the try() to catch(), or just continue:

// process the template
    try
    {
        // this function will pass back a value, or a TemplateExecption if invalid
            $result = $this->process($value);

        // if the result is an error, choose what to do with it
            if($result instanceof TemplateExecption)
            {
                if(DEBUGGING == TRUE)
                {
                    throw($result); // throw the original error
                }
                else
                {
                    $result = NULL; // ignore the error
                }
            }
    }

// catch TemplateExceptions
    catch(TemplateException $e)
    {
        // handle template exceptions
    }

// catch normal PHP Exceptions
    catch(Exception $e)
    {
        // handle normal exceptions
    }

// if we get here, $result was valid, or ignored
    return $result;

The result of this is I still get the context of the original error, even though it was thrown at the top.

Another option might be to return a custom NullObject or a UnknownProperty object and compare against that before deciding to trip the catch(), but as you can re-throw errors anyway, and if you're fully in control of the overall structure, I think this is a neat way round the issue of not being able to continue try/catches.

How do I change the hover over color for a hover over table in Bootstrap?

try:

.table-hover > tbody > tr.active:hover > th {
                background-color: #color;
            }

'ssh' is not recognized as an internal or external command

For Windows, first install the git base from here: https://git-scm.com/downloads

Next, set the environment variable:

  1. Press Windows+R and type sysdm.cpl
  2. Select advance -> Environment variable
  3. Select path-> edit the path and paste the below line:
C:\Program Files\Git\git-bash.exe

To test it, open the command window: press Windows+R, type cmd and then type ssh.

How to create an array of object literals in a loop?

If you want to go even further than @tetra with ES6 you can use the Object spread syntax and do something like this:

let john = {
    firstName: "John",
    lastName: "Doe",
};

let people = new Array(10).fill().map((e, i) => {(...john, id: i});

Simple Deadlock Examples

I have created an ultra Simple Working DeadLock Example:-

package com.thread.deadlock;

public class ThreadDeadLockClient {

    public static void main(String[] args) {
        ThreadDeadLockObject1 threadDeadLockA = new ThreadDeadLockObject1("threadDeadLockA");
        ThreadDeadLockObject2 threadDeadLockB = new ThreadDeadLockObject2("threadDeadLockB");

        new Thread(new Runnable() {

            @Override
            public void run() {
                threadDeadLockA.methodA(threadDeadLockB);

            }
        }).start();

        new Thread(new Runnable() {

            @Override
            public void run() {
                threadDeadLockB.methodB(threadDeadLockA);

            }
        }).start();
    }
}

package com.thread.deadlock;

public class ThreadDeadLockObject1 {

    private String name;

    ThreadDeadLockObject1(String name){
        this.name = name;
    }

    public  synchronized void methodA(ThreadDeadLockObject2 threadDeadLockObject2) {
        System.out.println("In MethodA "+" Current Object--> "+this.getName()+" Object passed as parameter--> "+threadDeadLockObject2.getName());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        threadDeadLockObject2.methodB(this);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }   
}

package com.thread.deadlock;

public class ThreadDeadLockObject2 {

    private String name;

    ThreadDeadLockObject2(String name){
        this.name = name;
    }

    public  synchronized void methodB(ThreadDeadLockObject1 threadDeadLockObject1) {
        System.out.println("In MethodB "+" Current Object--> "+this.getName()+" Object passed as parameter--> "+threadDeadLockObject1.getName());
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        threadDeadLockObject1.methodA(this);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

In the above example 2 threads are executing the synchronized methods of two different objects. Synchronized methodA is called by object threadDeadLockA and synchronized methodB is called by object threadDeadLockB. In methodA a reference of threadDeadLockB is passed and in methodB a reference of threadDeadLockA is passed. Now each thread tries to get lock on the another object. In methodA the thread who is holding a lock on threadDeadLockA is trying to get lock on object threadDeadLockB and similarly in methodB the thread who is holding a lock on threadDeadLockB is trying to get lock on threadDeadLockA. Thus both the threads will wait forever creating a deadlock.

Perform Button click event when user press Enter key in Textbox

You can try:

In HTML:

    <asp:TextBox ID="TextBox1" runat="server" onKeyDown="submitButton(event)"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />

And javascript:

function submitButton(event) {
        if (event.which == 13) {
            $('#Button1').trigger('click');
        }
    }

Code behind:

protected void Button1_Click(object sender, EventArgs e)
{
        //load data and fill to gridview
} // fixed the function view for users

Hope this help

Best approach to converting Boolean object to string in java

I don't think there would be any significant performance difference between them, but I would prefer the 1st way.

If you have a Boolean reference, Boolean.toString(boolean) will throw NullPointerException if your reference is null. As the reference is unboxed to boolean before being passed to the method.

While, String.valueOf() method as the source code shows, does the explicit null check:

public static String valueOf(Object obj) {
    return (obj == null) ? "null" : obj.toString();
}

Just test this code:

Boolean b = null;

System.out.println(String.valueOf(b));    // Prints null
System.out.println(Boolean.toString(b));  // Throws NPE

For primitive boolean, there is no difference.

Remove background drawable programmatically in Android

This helped me remove background color, hope it helps someone. setBackgroundColor(Color.TRANSPARENT)

HTML5 placeholder css padding

If you want to keep your line-height and force the placeholder to have the same, you can directly edit the placeholder CSS since the newer browser versions. That did the trick for me:

input::-webkit-input-placeholder { /* WebKit browsers */
  line-height: 1.5em;
}
input:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
  line-height: 1.5em;
}
input::-moz-placeholder { /* Mozilla Firefox 19+ */
  line-height: 1.5em;
}
input:-ms-input-placeholder { /* Internet Explorer 10+ */
  line-height: 1.5em;
}

how to pass parameters to query in SQL (Excel)

It depends on the database to which you're trying to connect, the method by which you created the connection, and the version of Excel that you're using. (Also, most probably, the version of the relevant ODBC driver on your computer.)

The following examples are using SQL Server 2008 and Excel 2007, both on my local machine.

When I used the Data Connection Wizard (on the Data tab of the ribbon, in the Get External Data section, under From Other Sources), I saw the same thing that you did: the Parameters button was disabled, and adding a parameter to the query, something like select field from table where field2 = ?, caused Excel to complain that the value for the parameter had not been specified, and the changes were not saved.

When I used Microsoft Query (same place as the Data Connection Wizard), I was able to create parameters, specify a display name for them, and enter values each time the query was run. Bringing up the Connection Properties for that connection, the Parameters... button is enabled, and the parameters can be modified and used as I think you want.

I was also able to do this with an Access database. It seems reasonable that Microsoft Query could be used to create parameterized queries hitting other types of databases, but I can't easily test that right now.

How to parse a month name (string) to an integer for comparison in C#?

If you are using c# 3.0 (or above) you can use extenders

Is there a numpy builtin to reject outliers from a list

I wanted to do something similar, except setting the number to NaN rather than removing it from the data, since if you remove it you change the length which can mess up plotting (i.e. if you're only removing outliers from one column in a table, but you need it to remain the same as the other columns so you can plot them against each other).

To do so I used numpy's masking functions:

def reject_outliers(data, m=2):
    stdev = np.std(data)
    mean = np.mean(data)
    maskMin = mean - stdev * m
    maskMax = mean + stdev * m
    mask = np.ma.masked_outside(data, maskMin, maskMax)
    print('Masking values outside of {} and {}'.format(maskMin, maskMax))
    return mask

How to VueJS router-link active style

Let's make things simple, you don't need to read the document about a "custom tag" (as a 16 years web developer, I have enough this kind of tags, such as in struts, webwork, jsp, rails and now it's vuejs)

just press F12, and you will see the source code like:

    <div>
        <a href="#/topologies" class="luelue">page1</a> 
        <a href="#/" aria-current="page" class="router-link-exact-active router-link-active">page2</a> 
        <a href="#/databases" class="">page3</a>
    </div>

so just add styles for the .router-link-active or router-link-exact-active

if you want more details, check the router-link api:

https://router.vuejs.org/en/api/#router-link

Inserting image into IPython notebook markdown

Last version of jupyter notebook accepts copy/paste of image natively

Send File Attachment from Form Using phpMailer and PHP

Hey guys the code below worked perfectly fine for me. Just replace the setFrom and addAddress with your preference and that's it.

<?php
/**
 * PHPMailer simple file upload and send example.
 */
//Import the PHPMailer class into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
$msg = '';
if (array_key_exists('userfile', $_FILES)) {
    // First handle the upload
    // Don't trust provided filename - same goes for MIME types
    // See http://php.net/manual/en/features.file-upload.php#114004 for more thorough upload validation
    $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $_FILES['userfile']['name']));
    if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) 
    {
        // Upload handled successfully
        // Now create a message

        require 'vendor/autoload.php';
        $mail = new PHPMailer;
        $mail->setFrom('[email protected]', 'CV from Web site');
        $mail->addAddress('[email protected]', 'CV');
        $mail->Subject = 'PHPMailer file sender';
        $mail->Body = 'My message body';

        $filename = $_FILES["userfile"]["name"]; // add this line of code to auto pick the file name
        //$mail->addAttachment($uploadfile, 'My uploaded file'); use the one below instead

        $mail->addAttachment($uploadfile, $filename);
        if (!$mail->send()) 
        {
            $msg .= "Mailer Error: " . $mail->ErrorInfo;
        } 
        else 
        {
            $msg .= "Message sent!";
        }
    } 
        else 
        {
            $msg .= 'Failed to move file to ' . $uploadfile;
        }
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>PHPMailer Upload</title>
</head>
<body>
<?php if (empty($msg)) { ?>
    <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="MAX_FILE_SIZE" value="4194304" />
        <input name="userfile" type="file">
        <input type="submit" value="Send File">
    </form>

<?php } else {
    echo $msg;
} ?>
</body>
</html>

Xcode error - Thread 1: signal SIGABRT

SIGABRT is, as stated in other answers, a general uncaught exception. You should definitely learn a little bit more about Objective-C. The problem is probably in your UITableViewDelegate method didSelectRowAtIndexPath.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

I can't tell you much more until you show us something of the code where you handle the table data source and delegate methods.

Count number of columns in a table row

Count all td in table1:

_x000D_
_x000D_
console.log(_x000D_
table1.querySelectorAll("td").length_x000D_
)
_x000D_
<table id="table1">_x000D_
<tr>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<table>
_x000D_
_x000D_
_x000D_

Count all td into each tr of table1.

_x000D_
_x000D_
table1.querySelectorAll("tr").forEach(function(e){_x000D_
 console.log( e.querySelectorAll("td").length )_x000D_
})
_x000D_
<table id="table1">_x000D_
<tr>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<tr>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
  <td><input type="text" value="" /></td>_x000D_
</tr>_x000D_
<table>
_x000D_
_x000D_
_x000D_