Programs & Examples On #Backticks

For questions relating to the backtick character (`), also known as the backquote, which has various special meanings in computing.

Usage of the backtick character (`) in JavaScript

This is a feature called template literals.

They were called "template strings" in prior editions of the ECMAScript 2015 specification.

Template literals are supported by Firefox 34, Chrome 41, and Edge 12 and above, but not by Internet Explorer.

Template literals can be used to represent multi-line strings and may use "interpolation" to insert variables:

var a = 123, str = `---
   a is: ${a}
---`;
console.log(str);

Output:

---
   a is: 123
---

What is more important, they can contain not just a variable name, but any JavaScript expression:

var a = 3, b = 3.1415;

console.log(`PI is nearly ${Math.max(a, b)}`);

How do I check/uncheck all checkboxes with a button using jQuery?

Here is a link, which is used to check and uncheck the parent checkbox and all the child checkboxes are getting selected and deselected.

jquery check uncheck all checkboxes Using Jquery With Demo

$(function () {
        $("#select-all").on("click", function () {
            var all = $(this);
            $('input:checkbox').each(function () {
                $(this).prop("checked", all.prop("checked"));
            });
        });
    });

Get the selected value in a dropdown using jQuery.

The above solutions didn't work for me. Here is what I finally came up with:

$( "#ddl" ).find( "option:selected" ).text();           // Text
$( "#ddl" ).find( "option:selected" ).prop("value");    // Value

How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?

To disable swipe

mViewPager.beginFakeDrag();

To enable swipe

mViewPager.endFakeDrag();

Merging arrays with the same keys

Two entries in an array can't share a key, you'll need to change the key for the duplicate

Display PNG image as response to jQuery AJAX request

Method 1

You should not make an ajax call, just put the src of the img element as the url of the image.

This would be useful if you use GET instead of POST

<script type="text/javascript" > 

  $(document).ready( function() { 
      $('.div_imagetranscrits').html('<img src="get_image_probes_via_ajax.pl?id_project=xxx" />')
  } );

</script>

Method 2

If you want to POST to that image and do it the way you do (trying to parse the contents of the image on the client side, you could try something like this: http://en.wikipedia.org/wiki/Data_URI_scheme

You'll need to encode the data to base64, then you could put data:[<MIME-type>][;charset=<encoding>][;base64],<data> into the img src

as example:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot img" />

To encode to base64:

Using PHP to upload file and add the path to MySQL database

mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;

These are deprecated use the following..

 // Connects to your Database
            $link = mysqli_connect("localhost", "root", "", "");

and to insert data use the following

 $sql = "INSERT INTO  Table-Name (Column-Name)
VALUES ('$filename')" ;

Force IE compatibility mode off using tags

If you're working with a page in the Intranet Zone, you may find that IE9 no matter what you do, is going into IE7 Compat mode.

This is due to the setting within IE Compatibility settings which says that all Intranet sites should run in compatibility mode. You can untick this via a group policy (or just plain unticking it in IE), or you can set the following:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

This works (as detailed in other answers), but may not initially appear so: it needs to come before the stylesheets are declared. If you don't, it is ignored.

Byte Array and Int conversion in Java

I took a long look at many questions like this, and found this post... I didn't like the fact that the conversion code is duplicated for each type, so I've made a generic method to perform the task:

public static byte[] toByteArray(long value, int n)
{
    byte[] ret = new byte[n];
    ret[n-1] = (byte) ((value >> (0*8) & 0xFF);   
    ret[n-2] = (byte) ((value >> (1*8) & 0xFF);   
    ...
    ret[1] = (byte) ((value >> ((n-2)*8) & 0xFF);   
    ret[0] = (byte) ((value >> ((n-1)*8) & 0xFF);   
    return ret;
}

See full post.

`getchar()` gives the same output as the input string

According to the definition of getchar(), it reads a character from the standard input. Unfortunately stdin is mistaken for keyboard which might not be the case for getchar. getchar uses a buffer as stdin and reads a single character at a time. In your case since there is no EOF, the getchar and putchar are running multiple times and it looks to you as it the whole string is being printed out at a time. Make a small change and you will understand:

putchar(c);
printf("\n");     
c = getchar();

Now look at the output compared to the original code.

Another example that will explain you the concept of getchar and buffered stdin :

void main(){
int c;
printf("Enter character");
c = getchar();
putchar();
c = getchar();
putchar();
}

Enter two characters in the first case. The second time when getchar is running are you entering any character? NO but still putchar works.

This ultimately means there is a buffer and when ever you are typing something and click enter this goes and settles in the buffer. getchar uses this buffer as stdin.

ReactJS - Does render get called any time "setState" is called?

Not All Components.

the state in component looks like the source of the waterfall of state of the whole APP.

So the change happens from where the setState called. The tree of renders then get called from there. If you've used pure component, the render will be skipped.

Parse an HTML string with JS

var doc = new DOMParser().parseFromString(html, "text/html");
var links = doc.querySelectorAll("a");

How to change the URL from "localhost" to something else, on a local system using wampserver?

WINDOWS + WAMP solution

Step 1
Go to C:\wamp\bin\apache\Apache2.2.17\conf\
open httpd.conf file and change
#Include conf/extra/httpd-vhosts.conf
to
Include conf/extra/httpd-vhosts.conf
i.e. uncomment the line so that it can includes the virtual hosts file.

Step 2
Go to C:\wamp\bin\apache\Apache2.2.17\conf\extra
and open httpd-vhosts.conf file and add the following code

<VirtualHost myWebsite.local>
    DocumentRoot "C:/wamp/www/myWebsite/"
    ServerName myWebsite.local
    ServerAlias myWebsite.local
    <Directory "C:/wamp/www/myWebsite/">
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

change myWebsite.local and C:/wamp/www/myWebsite/ as per your requirements.

Step 3
Open hosts file in C:/Windows/System32/drivers/etc/ and add the following line ( Don't delete anything )

127.0.0.1 myWebsite.local

change myWebsite.local as per your name requirements

Step 4
restart your server. That's it


WINDOWS + XAMPP solution

Same steps as that of WAMP just change the paths according to XAMPP which corresponds to path in WAMP

Detect end of ScrollView

I went through the solutions on the internet. Mostly solutions didn't work in the project I'm working on. Following solutions work fine for me.

Using onScrollChangeListener (works on API 23):

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {

                int bottom =   (scrollView.getChildAt(scrollView.getChildCount() - 1)).getHeight()-scrollView.getHeight()-scrollY;

                if(scrollY==0){
                    //top detected
                }
                if(bottom==0){
                    //bottom detected
                }
            }
        });
    }

using scrollChangeListener on TreeObserver

 scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            int bottom =   (scrollView.getChildAt(scrollView.getChildCount() - 1)).getHeight()-scrollView.getHeight()-scrollView.getScrollY();

            if(scrollView.getScrollY()==0){
                //top detected
            }
            if(bottom==0) {
                //bottom detected
            }
        }
    });

Hope this solution helps :)

SQL Combine Two Columns in Select Statement

If your address1 = '123 Center St' and address2 = 'Apt 3B' then even if you combine and do a LIKE, you cannot search on searchstring as 'Center St 3B'. However, if your searchstring was 'Center St Apt', then you can do it using -

WHERE (address1 + ' ' + address2) LIKE '%searchstring%'

iOS start Background Thread

Swift 2.x answer:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
        self.getResultSetFromDB(docids)
    }

force line break in html table cell

Try using

<table  border="1" cellspacing="0" cellpadding="0" class="template-table" 
style="table-layout: fixed; width: 100%"> 

as table style along with

<td style="word-break:break-word">long text</td>

for td it works for normal/real scenario text with words, not for random typed letters without gaps

When does Java's Thread.sleep throw InterruptedException?

You should generally NOT ignore the exception. Take a look at the following paper:

Don't swallow interrupts

Sometimes throwing InterruptedException is not an option, such as when a task defined by Runnable calls an interruptible method. In this case, you can't rethrow InterruptedException, but you also do not want to do nothing. When a blocking method detects interruption and throws InterruptedException, it clears the interrupted status. If you catch InterruptedException but cannot rethrow it, you should preserve evidence that the interruption occurred so that code higher up on the call stack can learn of the interruption and respond to it if it wants to. This task is accomplished by calling interrupt() to "reinterrupt" the current thread, as shown in Listing 3. At the very least, whenever you catch InterruptedException and don't rethrow it, reinterrupt the current thread before returning.

public class TaskRunner implements Runnable {
    private BlockingQueue<Task> queue;

    public TaskRunner(BlockingQueue<Task> queue) { 
        this.queue = queue; 
    }

    public void run() { 
        try {
             while (true) {
                 Task task = queue.take(10, TimeUnit.SECONDS);
                 task.execute();
             }
         }
         catch (InterruptedException e) { 
             // Restore the interrupted status
             Thread.currentThread().interrupt();
         }
    }
}

See the entire paper here:

http://www.ibm.com/developerworks/java/library/j-jtp05236/index.html?ca=drs-

EF Code First "Invalid column name 'Discriminator'" but no inheritance

Another scenario where this occurs is when you have a base class and one or more subclasses, where at least one of the subclasses introduce extra properties:

class Folder {
  [key]
  public string Id { get; set; }

  public string Name { get; set; }
}

// Adds no props, but comes from a different view in the db to Folder:
class SomeKindOfFolder: Folder {
}

// Adds some props, but comes from a different view in the db to Folder:
class AnotherKindOfFolder: Folder {
  public string FolderAttributes { get; set; }
}

If these are mapped in the DbContext like below, the "'Invalid column name 'Discriminator'" error occurs when any type based on Folder base type is accessed:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
  modelBuilder.Entity<Folder>().ToTable("All_Folders");
  modelBuilder.Entity<SomeKindOfFolder>().ToTable("Some_Kind_Of_Folders");
  modelBuilder.Entity<AnotherKindOfFolder>().ToTable("Another_Kind_Of_Folders");
}

I found that to fix the issue, we extract the props of Folder to a base class (which is not mapped in OnModelCreating()) like so - OnModelCreating should be unchanged:

class FolderBase {
  [key]
  public string Id { get; set; }

  public string Name { get; set; }
}

class Folder: FolderBase {
}

class SomeKindOfFolder: FolderBase {
}

class AnotherKindOfFolder: FolderBase {
  public string FolderAttributes { get; set; }
}

This eliminates the issue, but I don't know why!

How to make a script wait for a pressed key?

The python manual provides the following:

import termios, fcntl, sys, os
fd = sys.stdin.fileno()

oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

try:
    while 1:
        try:
            c = sys.stdin.read(1)
            print "Got character", repr(c)
        except IOError: pass
finally:
    termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

which can be rolled into your use case.

How do I pass multiple ints into a vector at once?

You can also use Boost.Assignment:

const list<int> primes = list_of(2)(3)(5)(7)(11);

vector<int> v; 
v += 1,2,3,4,5,6,7,8,9;

ISO time (ISO 8601) in Python

I found the datetime.isoformat in the documentation. It seems to do what you want:

datetime.isoformat([sep])

Return a string representing the date and time in ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm or, if microsecond is 0, YYYY-MM-DDTHH:MM:SS

If utcoffset() does not return None, a 6-character string is appended, giving the UTC offset in (signed) hours and minutes: YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM or, if microsecond is 0 YYYY-MM-DDTHH:MM:SS+HH:MM

The optional argument sep (default 'T') is a one-character separator, placed between the date and time portions of the result. For example,
>>>

>>> from datetime import tzinfo, timedelta, datetime
>>> class TZ(tzinfo):
...     def utcoffset(self, dt): return timedelta(minutes=-399)
...
>>> datetime(2002, 12, 25, tzinfo=TZ()).isoformat(' ')
'2002-12-25 00:00:00-06:39'

An attempt was made to access a socket in a way forbidden by its access permissions

If You need to access SQL server on hostgator remotely using SSMS, you need to white list your IP in hostgator. Usually it takes 1 hour to open port for the whitelisted IP

Regarding Java switch statements - using return and omitting breaks in each case

Assigning a value to a local variable and then returning that at the end is considered a good practice. Methods having multiple exits are harder to debug and can be difficult to read.

That said, thats the only plus point left to this paradigm. It was originated when only low-level procedural languages were around. And it made much more sense at that time.

While we are on the topic you must check this out. Its an interesting read.

Twitter-Bootstrap-2 logo image on top of navbar

If you do not increase the height of navbar..

 .navbar .brand {
 position: fixed;    
 overflow: visible;
 padding-left: 0;    
 padding-top: 0;
 }

see http://jsfiddle.net/petrfox/S84wP/

Difference between web server, web container and application server

Web Container + HTTP request handling = WebServer

Web Server + EJB + (Messaging + Transactions+ etc) = ApplicaitonServer

Change color of PNG image via CSS?

When changing a picture from black to white, or white to black the hue rotate filter does not work, because black and white are not technically colors. Instead, black and white color changes (from black to white or vice-versa) must be done with the invert filter property.

.img1 { filter: invert(100%); }

"java.lang.OutOfMemoryError: PermGen space" in Maven build

When you say you increased MAVEN_OPTS, what values did you increase? Did you increase the MaxPermSize, as in example:

export MAVEN_OPTS="-Xmx512m -XX:MaxPermSize=128m"

(or on Windows:)

set MAVEN_OPTS=-Xmx512m -XX:MaxPermSize=128m

You can also specify these JVM options in each maven project separately.

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

System.Net.ServicePointManager.Expect100Continue = false;

This issue sometime occurs due the reason of proxy server implemented on web server. To bypass the proxy server by putting this line before calling the send service.

Convert JavaScript String to be all lower case?

In case you want to build it yourself:

function toLowerCase(string) {

let lowerCaseString = "";

for (let i = 0; i < string.length; i++) {
    //find ASCII charcode
    let charcode = string.charCodeAt(i);

    //if uppercase
    if (charcode > 64 && charcode < 97){
        //convert to lowercase
        charcode = charcode + 32
    }

    //back to char
    let lowercase = String.fromCharCode(charcode);

    //append
    lowerCaseString = lowerCaseString.concat(lowercase);
}

return lowerCaseString

}

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

My problem was fideloper proxy version.

when i upgraded laravel 5.5 to 5.8 this happened

just sharing if anybody get help

change you composer json fideloper version:

"fideloper/proxy": "^4.0",

After that you need to run update composer that's it.

composer update

How to hide "Showing 1 of N Entries" with the dataTables.js library

If you also need to disable the drop-down (not to hide the text) then set the lengthChange option to false

$('#datatable').dataTable( {
  "lengthChange": false
} );

Works for DataTables 1.10+

Read more in the official documentation

Adding a rule in iptables in debian to open a new port

(I presume that you've concluded that it's an iptables problem by dropping the firewall completely (iptables -P INPUT ACCEPT; iptables -P OUTPUT ACCEPT; iptables -F) and confirmed that you can connect to the MySQL server from your Windows box?)

Some previous rule in the INPUT table is probably rejecting or dropping the packet. You can get around that by inserting the new rule at the top, although you might want to review your existing rules to see whether that's sensible:

iptables -I INPUT 1 -p tcp --dport 3306 -j ACCEPT

Note that iptables-save won't save the new rule persistently (i.e. across reboots) - you'll need to figure out something else for that. My usual route is to store the iptables-save output in a file (/etc/network/iptables.rules or similar) and then load then with a pre-up statement in /etc/network/interfaces).

XAMPP Start automatically on Windows 7 startup

I just placed a short-cut to the XAMPP control panel in my startup folder. That works just fine on Window 7. Start -> All Programs -> Startup. There is also an option to start XAMPP control panel minimized, that is very useful for getting a clean unobstructed view of your desktop at start-up.**

How can I see the request headers made by curl when sending a request to the server?

Here is my http client in php to make post queries with cookies included:

function http_login_client($url, $params = "", $cookies_send = "" ){

    // Vars
    $cookies = array();
    $headers = getallheaders();

    // Perform a http post request to $ur1 using $params
    $ch = curl_init($url);
    $options = array(   CURLOPT_POST => 1,
                        CURLINFO_HEADER_OUT => true,
                        CURLOPT_POSTFIELDS => $params,
                        CURLOPT_RETURNTRANSFER => 1,
                        CURLOPT_HEADER => 1,
                        CURLOPT_COOKIE => $cookies_send,
                        CURLOPT_USERAGENT => $headers['User-Agent']
                    );

    curl_setopt_array($ch, $options);

    $response = curl_exec($ch);

/// DEBUG info echo $response; var_dump (curl_getinfo($ch)); ///

    // Parse response and read cookies
    preg_match_all('/^Set-Cookie: (.*?)=(.*?);/m', $response, $matches);

    // Build an array with cookies
    foreach( $matches[1] as $index => $cookie )
        $cookies[$cookie] = $matches[2][$index];

    return $cookies;
} // end http_login_client

Writing an Excel file in EPPlus

Have you looked at the samples provided with EPPlus?

This one shows you how to create a file http://epplus.codeplex.com/wikipage?title=ContentSheetExample

This one shows you how to use it to stream back a file http://epplus.codeplex.com/wikipage?title=WebapplicationExample

This is how we use the package to generate a file.

var newFile = new FileInfo(ExportFileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{                       
    // do work here                            
    xlPackage.Save();
}

How to detect when keyboard is shown and hidden

Swift 5

There answers above are correct. Although I would prefer to create a helper to wrap up the notification's observers.

The benefit:

  1. You don't have to repeat each time you handle the keyboard behaviors.
  2. You can extend other notification by implement other enum value
  3. It's useful when you have to deal with keyboard in several controllers.

Sample code:

extension KeyboardHelper {
    enum Animation {
        case keyboardWillShow
        case keyboardWillHide
    }

    typealias HandleBlock = (_ animation: Animation, _ keyboardFrame: CGRect, _ duration: TimeInterval) -> Void
}

final class KeyboardHelper {
    private let handleBlock: HandleBlock

    init(handleBlock: @escaping HandleBlock) {
        self.handleBlock = handleBlock
        setupNotification()
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    private func setupNotification() {
        _ = NotificationCenter.default
            .addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { [weak self] notification in
                self?.handle(animation: .keyboardWillShow, notification: notification)
            }

        _ = NotificationCenter.default
            .addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { [weak self] notification in
                self?.handle(animation: .keyboardWillHide, notification: notification)
            }
    }

    private func handle(animation: Animation, notification: Notification) {
        guard let userInfo = notification.userInfo,
            let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
            let duration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double
        else { return }

        handleBlock(animation, keyboardFrame, duration)
    }
}

How to use:

private var keyboardHelper: KeyboardHelper?
...

override func viewDidLoad() {
   ...
   keyboardHelper = KeyboardHelper { [unowned self] animation, keyboardFrame, duration in
        switch animation {
        case .keyboardWillShow:
            print("keyboard will show")
        case .keyboardWillHide:
            print("keyboard will hide")
        }
    }

}

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

For whatever reason $('.panel-collapse').collapse({'toggle': true, 'parent': '#accordion'}); only seems to work the first time and it only works to expand the collapsible. (I tried to start with a expanded collapsible and it wouldn't collapse.)

It could just be something that runs once the first time you initialize collapse with those parameters.

You will have more luck using the show and hide methods.

Here is an example:

$(function() {

  var $active = true;

  $('.panel-title > a').click(function(e) {
    e.preventDefault();
  });

  $('.collapse-init').on('click', function() {
    if(!$active) {
      $active = true;
      $('.panel-title > a').attr('data-toggle', 'collapse');
      $('.panel-collapse').collapse('hide');
      $(this).html('Click to disable accordion behavior');
    } else {
      $active = false;
      $('.panel-collapse').collapse('show');
      $('.panel-title > a').attr('data-toggle','');
      $(this).html('Click to enable accordion behavior');
    }
  });

});

http://bootply.com/98201

Update

Granted KyleMit seems to have a way better handle on this then me. I'm impressed with his answer and understanding.

I don't understand what's going on or why the show seemed to be toggling in some places.

But After messing around for a while.. Finally came with the following solution:

$(function() {
  var transition = false;
  var $active = true;

  $('.panel-title > a').click(function(e) {
    e.preventDefault();
  });

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

  $('#accordion').on('hidden.bs.collapse',function(){
    if(transition){
        transition = false;
        $('.panel-collapse').collapse('show');
    }
  });

  $('.collapse-init').on('click', function() {
    $('.collapse-init').prop('disabled','true');
    if(!$active) {
      $active = true;
      $('.panel-title > a').attr('data-toggle', 'collapse');
      $('.panel-collapse').collapse('hide');
      $(this).html('Click to disable accordion behavior');
    } else {
      $active = false;
      if($('.panel-collapse.in').length){
        transition = true;
        $('.panel-collapse.in').collapse('hide');       
      }
      else{
        $('.panel-collapse').collapse('show');
      }
      $('.panel-title > a').attr('data-toggle','');
      $(this).html('Click to enable accordion behavior');
    }
    setTimeout(function(){
        $('.collapse-init').prop('disabled','');
    },800);
  });
});

http://bootply.com/98239

Parse date string and change format

Just for the sake of completion: when parsing a date using strptime() and the date contains the name of a day, month, etc, be aware that you have to account for the locale.

It's mentioned as a footnote in the docs as well.

As an example:

import locale
print(locale.getlocale())

>> ('nl_BE', 'ISO8859-1')

from datetime import datetime
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')

>> ValueError: time data '6-Mar-2016' does not match format '%d-%b-%Y'

locale.setlocale(locale.LC_ALL, 'en_US')
datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')

>> '2016-03-06'

forEach is not a function error with JavaScript array

If you are trying to loop over a NodeList like this:

const allParagraphs = document.querySelectorAll("p");

I highly recommend loop it this way:

Array.prototype.forEach.call(allParagraphs , function(el) {
    // Write your code here
})

Personally, I've tried several ways but most of them didn't work as I wanted to loop over a NodeList, but this one works like a charm, give it a try!

The NodeList isn't an Array, but we treat it as an Array, using Array. So, you need to know that it is not supported in older browsers!

Need more information about NodeList? Please read its documentation on MDN.

How can I solve Exception in thread "main" java.lang.NullPointerException error

This is the problem

double a[] = null;

Since a is null, NullPointerException will arise every time you use it until you initialize it. So this:

a[i] = var;

will fail.

A possible solution would be initialize it when declaring it:

double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7

IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.

java.lang.NullPointerException

This exception means there's a variable with null value being used. How to solve? Just make sure the variable is not null before being used.

at twoten.TwoTenB.(TwoTenB.java:29)

This line has two parts:

  • First, shows the class and method where the error was thrown. In this case, it was at <init> method in class TwoTenB declared in package twoten. When you encounter an error message with SomeClassName.<init>, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
  • Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file TwoTenB.java, line number 29. This seems to be a[i] = var;.

From this line, other lines will be similar to tell you where the error arose. So when reading this:

at javapractice.JavaPractice.main(JavaPractice.java:32)

It means that you were trying to instantiate a TwoTenB object reference inside the main method of your class JavaPractice declared in javapractice package.

Error:(1, 0) Plugin with id 'com.android.application' not found

Root-gradle file:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:x.x.x'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

Gradle-wrapper.properties file:

distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-x.x-all.zip

Passing 'this' to an onclick event

Yeah first method will work on any element called from elsewhere since it will always take the target element irrespective of id.

check this fiddle

http://jsfiddle.net/8cvBM/

Can't compare naive and aware datetime.now() <= challenge.datetime_end

One line of code solution

if timezone_aware_var <= datetime.datetime.now(timezone_aware_var.tzinfo):
    pass #some code

Explained version

# Timezone info of your timezone aware variable
timezone = your_timezone_aware_variable.tzinfo

# Current datetime for the timezone of your variable
now_in_timezone = datetime.datetime.now(timezone)

# Now you can do a fair comparison, both datetime variables have the same time zone
if your_timezone_aware_variable <= now_in_timezone:
    pass #some code

Summary

You must add the timezone info to your now() datetime.
However, you must add the same timezone of the reference variable; that is why I first read the tzinfo attribute.

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

For other future users who do not want to make their controllers asynchronous, or cannot access the HttpContext, or are using dotnet core (this answer is the first I found on Google trying to do this), the following worked for me:

[HttpPut("{pathId}/{subPathId}"),
public IActionResult Put(int pathId, int subPathId, [FromBody] myViewModel viewModel)
{

    var body = new StreamReader(Request.Body);
    //The modelbinder has already read the stream and need to reset the stream index
    body.BaseStream.Seek(0, SeekOrigin.Begin); 
    var requestBody = body.ReadToEnd();
    //etc, we use this for an audit trail
}

How to save LogCat contents to file?

To save LogCat log to file programmatically on your device use for example this code:

String filePath = Environment.getExternalStorageDirectory() + "/logcat.txt";
Runtime.getRuntime().exec(new String[]{"logcat", "-f", filepath, "MyAppTAG:V", "*:S"});

"MyAppTAG:V" sets the priority level for all tags to Verbose (lowest priority)

"*:S" sets the priority level for all tags to "silent"

More information about logcat here.

How to go from Blob to ArrayBuffer

This is an async method which first checks for the availability of arrayBuffer method. This function is backward compatible and future proof.

async function blobToArrayBuffer(blob) {
    if ('arrayBuffer' in blob) return await blob.arrayBuffer();
    
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = () => reject;
        reader.readAsArrayBuffer(blob);
    });
}

How can query string parameters be forwarded through a proxy_pass with nginx?

To redirect Without Query String add below lines in Server block under listen port line:

if ($uri ~ .*.containingString$) {
           return 301 https://$host/$uri/;
}

With Query String:

if ($uri ~ .*.containingString$) {
           return 301 https://$host/$uri/?$query_string;
}

DBNull if statement

At first use ExecuteScalar

 objConn = new SqlConnection(strConnection);
 objConn.Open();
 objCmd = new SqlCommand(strSQL, objConn);
 object result = cmd.ExecuteScalar();
 if(result == null)
     strLevel = "";
 else 
     strLevel = result.ToString();

Getting "TypeError: failed to fetch" when the request hasn't actually failed

Note that there is an unrelated issue in your code but that could bite you later: you should return res.json() or you will not catch any error occurring in JSON parsing or your own function processing data.

Back to your error: You cannot have a TypeError: failed to fetch with a successful request. You probably have another request (check your "network" panel to see all of them) that breaks and causes this error to be logged. Also, maybe check "Preserve log" to be sure the panel is not cleared by any indelicate redirection. Sometimes I happen to have a persistent "console" panel, and a cleared "network" panel that leads me to have error in console which is actually unrelated to the visible requests. You should check that.

Or you (but that would be vicious) actually have a hardcoded console.log('TypeError: failed to fetch') in your final .catch ;) and the error is in reality in your .then() but it's hard to believe.

Best way to style a TextBox in CSS

You Also wanna put some text (placeholder) in the empty input box for the

_x000D_
_x000D_
.myClass {_x000D_
   ::-webkit-input-placeholder {_x000D_
    color: #f00;_x000D_
  }_x000D_
   ::-moz-placeholder {_x000D_
    color: #f00;_x000D_
  }_x000D_
  /* firefox 19+ */_x000D_
   :-ms-input-placeholder {_x000D_
    color: #f00;_x000D_
  }_x000D_
  /* ie */_x000D_
  input:-moz-placeholder {_x000D_
    color: #f00;_x000D_
  }_x000D_
}
_x000D_
<input type="text" class="myClass" id="fname" placeholder="Enter First Name Here!">
_x000D_
_x000D_
_x000D_

user to understand what to type.

Resolving MSB3247 - Found conflicts between different versions of the same dependent assembly

As mentioned here, you need to remove the unused references and the warnings will go.

Bootstrap: How to center align content inside column?

Want to center an image? Very easy, Bootstrap comes with two classes, .center-block and text-center.

Use the former in the case of your image being a BLOCK element, for example, adding img-responsive class to your img makes the img a block element. You should know this if you know how to navigate in the web console and see applied styles to an element.

Don't want to use a class? No problem, here is the CSS bootstrap uses. You can make a custom class or write a CSS rule for the element to match the Bootstrap class.

 // In case you're dealing with a block element apply this to the element itself 
.center-block {
   margin-left:auto;
   margin-right:auto;
   display:block;
}

// In case you're dealing with a inline element apply this to the parent 
.text-center {
   text-align:center
}

Execute and get the output of a shell command in node.js

You can use the util library that comes with nodejs to get a promise from the exec command and can use that output as you need. Use restructuring to store the stdout and stderr in variables.

_x000D_
_x000D_
const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function lsExample() {
  const {
    stdout,
    stderr
  } = await exec('ls');
  console.log('stdout:', stdout);
  console.error('stderr:', stderr);
}
lsExample();
_x000D_
_x000D_
_x000D_

How to set default value for HTML select?

You first need to add values to your select options and for easy targetting give the select itself an id.

Let's make option b the default:

<select id="mySelect">
    <option>a</option>
    <option selected="selected">b</option>
    <option>c</option>
</select>

Now you can change the default selected value with JavaScript like this:

<script>
var temp = "a";
var mySelect = document.getElementById('mySelect');

for(var i, j = 0; i = mySelect.options[j]; j++) {
    if(i.value == temp) {
        mySelect.selectedIndex = j;
        break;
    }
}
</script>

See it in action on codepen.

How can I dismiss the on screen keyboard?

You can use unfocus() method from FocusNode class.

import 'package:flutter/material.dart';

class MyHomePage extends StatefulWidget {
  MyHomePageState createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  TextEditingController _controller = new TextEditingController();
  FocusNode _focusNode = new FocusNode(); //1 - declare and initialize variable

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.send),
        onPressed: () {
            _focusNode.unfocus(); //3 - call this method here
        },
      ),
      body: new Container(
        alignment: FractionalOffset.center,
        padding: new EdgeInsets.all(20.0),
        child: new TextFormField(
          controller: _controller,
          focusNode: _focusNode, //2 - assign it to your TextFormField
          decoration: new InputDecoration(labelText: 'Example Text'),
        ),
      ),
    );
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

void main() {
  runApp(new MyApp());
}

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

Try this. The scope of local variables defined by "template" directive.

<table>
  <template ngFor let-group="$implicit" [ngForOf]="groups">
    <tr>
      <td>
        <h2>{{group.name}}</h2>
      </td>
    </tr>
    <tr *ngFor="let item of group.items">
                <td>{{item}}</td>
            </tr>
  </template>
</table>

Android: keep Service running when app is killed

inside onstart command put START_STICKY... This service won't kill unless it is doing too much task and kernel wants to kill it for it...

@Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i("LocalService", "Received start id " + startId + ": " + intent);
            // We want this service to continue running until it is explicitly
            // stopped, so return sticky.
            return START_STICKY;
        }

I want to remove double quotes from a String

This works...

_x000D_
_x000D_
var string1 = "'foo'";_x000D_
var string2 = '"bar"';_x000D_
_x000D_
function removeFirstAndLastQuotes(str){_x000D_
  var firstChar = str.charAt(0);_x000D_
  var lastChar = str[str.length -1];_x000D_
  //double quotes_x000D_
  if(firstChar && lastChar === String.fromCharCode(34)){_x000D_
    str = str.slice(1, -1);_x000D_
  }_x000D_
  //single quotes_x000D_
  if(firstChar && lastChar === String.fromCharCode(39)){_x000D_
    str = str.slice(1, -1);_x000D_
  }_x000D_
  return str;_x000D_
}_x000D_
console.log(removeFirstAndLastQuotes(string1));_x000D_
console.log(removeFirstAndLastQuotes(string2));
_x000D_
_x000D_
_x000D_

How do I get the opposite (negation) of a Boolean in Python?

You can just compare the boolean array. For example

X = [True, False, True]

then

Y = X == False

would give you

Y = [False, True, False]

Electron: jQuery is not defined

For this issue, Use JQuery and other js same as you are using in Web Page. However, Electron has node integration so it will not find your js objects. You have to set module = undefined until your js objects are loaded properly. See below example

<!-- Insert this line above local script tags  -->
<script>if (typeof module === 'object') {window.module = module; module = 
undefined;}</script>

<!-- normal script imports etc  -->
<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>    

<!-- Insert this line after script tags -->
<script>if (window.module) module = window.module;</script>

After importing like given, you will be able to use the JQuery and other things in electron.

How to include External CSS and JS file in Laravel 5

CORRECT & SECURED WAY


If you have a external .css or .js file to add into your page!

My version : Laravel Framework 5.7

If you want to add a External .js file..

  1. Copy your External codes.
  2. Run command npm install in your terminal.
  3. When the above command is executed you can see a folder named node_modules.
  4. Then go to resources/js.
  5. Open file app.js.
  6. Scroll down to the bottom and paste your External JS.
  7. Finally run command npm run dev in your terminal.

your scripts will be updated and its compiled and moved to public/js/app.js . by adding a .js file in public folder will not effect on your page.


If you want to add a External .css file..

  1. Copy your External styles.
  2. Run command npm install in your terminal.
  3. When the above command is executed you can see a folder named node_modules.
  4. Then go to resources/sass.
  5. Open file app.scss.
  6. Scroll down to the bottom and paste your External Styles.
  7. Finally run command npm run dev in your terminal.

your scripts will be updated and its compiled and moved to public/css/app.css . by adding a .css file in public folder will not effect on your page.

  • Easiest and the safest way to add your external .css and .js.

Laravel JavaScript & CSS Scaffolding

YouTube Compiling Assets

How to build a query string for a URL in C#?

While not elegant, I opted for a simpler version that doesn't use NameValueCollecitons - just a builder pattern wrapped around StringBuilder.

public class UrlBuilder
{
    #region Variables / Properties

    private readonly StringBuilder _builder;

    #endregion Variables / Properties

    #region Constructor

    public UrlBuilder(string urlBase)
    {
        _builder = new StringBuilder(urlBase);
    }

    #endregion Constructor

    #region Methods

    public UrlBuilder AppendParameter(string paramName, string value)
    {
        if (_builder.ToString().Contains("?"))
            _builder.Append("&");
        else
            _builder.Append("?");

        _builder.Append(HttpUtility.UrlEncode(paramName));
        _builder.Append("=");
        _builder.Append(HttpUtility.UrlEncode(value));

        return this;
    }

    public override string ToString()
    {
        return _builder.ToString();
    }

    #endregion Methods
}

Per existing answers, I made sure to use HttpUtility.UrlEncode calls. It's used like so:

string url = new UrlBuilder("http://www.somedomain.com/")
             .AppendParameter("a", "true")
             .AppendParameter("b", "muffin")
             .AppendParameter("c", "muffin button")
             .ToString();
// Result: http://www.somedomain.com?a=true&b=muffin&c=muffin%20button

Get root password for Google Cloud Engine VM

This work at least in the Debian Jessie image hosted by Google:

The way to enable to switch from you regular to the root user (AKA “super user”) after authentificating with your Google Computer Engine (GCE) User in the local environment (your Linux server in GCE) is pretty straight forward, in fact it just involves just one command to enable it and another every time to use it:

$ sudo passwd
Enter the new UNIX password: <your new root password>
Retype the new UNIX password: <your new root password>
passwd: password updated successfully

After executing the previous command and once logged with your GCE User you will be able to switch to root anytime by just entering the following command:

$ su
Password: <your newly created root password>
root@intance:/#

As we say in economics “caveat emptor” or buyer be aware: Using the root user is far from a best practice in system’s administration. Using it can be the cause a lot of trouble, from wiping everything in your drives and boot disks without a hiccup to many other nasty stuff that would be laborious to backtrack, troubleshoot and rebuilt. On the other hand, I have never met a SysAdmin that doesn’t think he knows better and root more than he should.

REMEMBER: We humans are programmed in such a way that given enough time at one at some point or another are going to press enter without taking into account that we have escalated to root and I can assure you that it will great source of pain, regret and extra work. PLEASE USE ROOT PRIVILEGES SPARSELY AND WITH EXTREME CARE.

Having said all the boring stuff, Have fun, live on the edge, life is short, you only get to live it once, the more you break the more you learn.

How to clear form after submit in Angular 2?

this.myForm.reset();

This is all enough...You can get the desired output

Rename package in Android Studio

If your package name is more than two dot separated, say com.hello.world and moreover, you did not put anything in com/ and com/hello/. All of your classes are putting into com/hello/world/, you might DO the following steps to refactoring your package name(s) in Android Studio or IntelliJ:

  • [FIRST] Add something under your directories(com/, com/hello/). You can achieve this by first add two files to package com.hello.world, say
   com.hello.world.PackageInfo1.java
   com.hello.world.PackageInfo2.java

then refactor them by moving them to com and com.hello respectively. You will see com and com.hello sitting there at the Project(Alt+1 or Command+1 for shortcut) and rename directories refactoring is waiting there as you expected.

  • Refactor to rename one or more of these directories to reach your aim. The only thing you should notice here is you must choose the directories rather than Packages when a dialog ask you.

  • If you've got lots of classes in your project, it will take you a while to wait for its auto-scan-and-rename.

  • Besides, you need to rename the package name inside the AndroidManifest.xml manually, I guess, such that other names in this file can benefit the prefix.

  • [ALSO], it might need you to replace all com.hello.world.R to the new XXX.XXX.XXX.R(Command+Shift+R for short)

  • Rebuild and run your project to see whether it work. And use "Find in Path" to find other non-touch names you'd like to rename.

  • Enjoy it.

How to check if directory exist using C++ and winAPI

This code might work:

//if the directory exists
 DWORD dwAttr = GetFileAttributes(str);
 if(dwAttr != 0xffffffff && (dwAttr & FILE_ATTRIBUTE_DIRECTORY)) 

Get UTC time in seconds

One might consider adding this line to ~/.bash_profile (or similar) in order to can quickly get the current UTC both as current time and as seconds since the epoch.

alias utc='date -u && date -u +%s'

A formula to copy the values from a formula to another column

Copy the cell. Paste special as link. Will update with original. No formula though.

How to know a Pod's own IP address from inside a container in the Pod?

kubectl describe pods <name of pod> will give you some information including the IP

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

Yes. You need to use Assembly.LoadFrom to load the assembly into memory, then you can use Activator.CreateInstance to create an instance of your preferred type. You'll need to look the type up first using reflection. Here is a simple example:

Assembly assembly = Assembly.LoadFrom("MyNice.dll");

Type type = assembly.GetType("MyType");

object instanceOfMyType = Activator.CreateInstance(type);

Update

When you have the assembly file name and the type name, you can use Activator.CreateInstance(assemblyName, typeName) to ask the .NET type resolution to resolve that into a type. You could wrap that with a try/catch so that if it fails, you can perform a search of directories where you may specifically store additional assemblies that otherwise might not be searched. This would use the preceding method at that point.

What is the difference between user variables and system variables?

Right-click My Computer and go to Properties->Advanced->Environmental Variables...

What's above are user variables, and below are system variables. The elements are combined when creating the environment for an application. System variables are shared for all users, but user variables are only for your account/profile.

If you deleted the system ones by accident, bring up the Registry Editor, then go to HKLM\ControlSet002\Control\Session Manager\Environment (assuming your current control set is not ControlSet002). Then find the Path value and copy the data into the Path value of HKLM\CurrentControlSet\Control\Session Manager\Environment. You might need to reboot the computer. (Hopefully, these backups weren't from too long ago, and they contain the info you need.)

Linux command-line call not returning what it should from os.system?

For your requirement, Popen function of subprocess python module is the answer. For example,

import subprocess
..
process = subprocess.Popen("ps -p 2993 -o time --no-headers", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print stdout

What are the differences between Visual Studio Code and Visual Studio?

One huge difference (for me) is that Visual Studio Code is one monitor only. With Visual Studio you can use multi-screen setups.

Throwing exceptions from constructors

#include <iostream>

class bar
{
public:
  bar()
  {
    std::cout << "bar() called" << std::endl;
  }

  ~bar()
  {
    std::cout << "~bar() called" << std::endl;

  }
};
class foo
{
public:
  foo()
    : b(new bar())
  {
    std::cout << "foo() called" << std::endl;
    throw "throw something";
  }

  ~foo()
  {
    delete b;
    std::cout << "~foo() called" << std::endl;
  }

private:
  bar *b;
};


int main(void)
{
  try {
    std::cout << "heap: new foo" << std::endl;
    foo *f = new foo();
  } catch (const char *e) {
    std::cout << "heap exception: " << e << std::endl;
  }

  try {
    std::cout << "stack: foo" << std::endl;
    foo f;
  } catch (const char *e) {
    std::cout << "stack exception: " << e << std::endl;
  }

  return 0;
}

the output:

heap: new foo
bar() called
foo() called
heap exception: throw something
stack: foo
bar() called
foo() called
stack exception: throw something

the destructors are not called, so if a exception need to be thrown in a constructor, a lot of stuff(e.g. clean up?) to do.

PHP call Class method / function

You need to create Object for the class.

$obj = new Functions();
$var = $obj->filter($_GET['params']);

Select from table by knowing only date without time (ORACLE)

DATE is a reserved keyword in Oracle, so I'm using column-name your_date instead.

If you have an index on your_date, I would use

WHERE your_date >= TO_DATE('2010-08-03', 'YYYY-MM-DD')
  AND your_date <  TO_DATE('2010-08-04', 'YYYY-MM-DD')

or BETWEEN:

WHERE your_date BETWEEN TO_DATE('2010-08-03', 'YYYY-MM-DD')
                    AND TO_DATE('2010-08-03 23:59:59', 'YYYY-MM-DD HH24:MI:SS')

If there is no index or if there are not too many records

WHERE TRUNC(your_date) = TO_DATE('2010-08-03', 'YYYY-MM-DD')

should be sufficient. TRUNC without parameter removes hours, minutes and seconds from a DATE.


If performance really matters, consider putting a Function Based Index on that column:

CREATE INDEX trunc_date_idx ON t1(TRUNC(your_date));

How does the JPA @SequenceGenerator annotation work

I have MySQL schema with autogen values. I use strategy=GenerationType.IDENTITY tag and seems to work fine in MySQL I guess it should work most db engines as well.

CREATE TABLE user (
    id bigint NOT NULL auto_increment,
    name varchar(64) NOT NULL default '',
    PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

User.java:

// mark this JavaBean to be JPA scoped class
@Entity
@Table(name="user")
public class User {
    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;    // primary key (autogen surrogate)

    @Column(name="name")
    private String name;

    public long getId() { return id; }
    public void setId(long id) { this.id = id; }

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

python requests get cookies

Alternatively, you can use requests.Session and observe cookies before and after a request:

>>> import requests
>>> session = requests.Session()
>>> print(session.cookies.get_dict())
{}
>>> response = session.get('http://google.com')
>>> print(session.cookies.get_dict())
{'PREF': 'ID=5514c728c9215a9a:FF=0:TM=1406958091:LM=1406958091:S=KfAG0U9jYhrB0XNf', 'NID': '67=TVMYiq2wLMNvJi5SiaONeIQVNqxSc2RAwVrCnuYgTQYAHIZAGESHHPL0xsyM9EMpluLDQgaj3db_V37NjvshV-eoQdA8u43M8UwHMqZdL-S2gjho8j0-Fe1XuH5wYr9v'}

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

Git: See my last commit

Use git show:

git show --summary

This will show the names of created or removed files, but not the names of changed files. The git show command supports a wide variety of output formats that show various types of information about commits.

How can I remove an element from a list?

Removing Null elements from a list in single line :

x=x[-(which(sapply(x,is.null),arr.ind=TRUE))]

Cheers

How to download a file from a website in C#

Sure, you just use a HttpWebRequest.

Once you have the HttpWebRequest set up, you can save the response stream to a file StreamWriter(Either BinaryWriter, or a TextWriter depending on the mimetype.) and you have a file on your hard drive.

EDIT: Forgot about WebClient. That works good unless as long as you only need to use GET to retrieve your file. If the site requires you to POST information to it, you'll have to use a HttpWebRequest, so I'm leaving my answer up.

How should I cast in VB.NET?

MSDN seems to indicate that the Cxxx casts for specific types can improve performance in VB .NET because they are converted to inline code. For some reason, it also suggests DirectCast as opposed to CType in certain cases (the documentations states it's when there's an inheritance relationship; I believe this means the sanity of the cast is checked at compile time and optimizations can be applied whereas CType always uses the VB runtime.)

When I'm writing VB .NET code, what I use depends on what I'm doing. If it's prototype code I'm going to throw away, I use whatever I happen to type. If it's code I'm serious about, I try to use a Cxxx cast. If one doesn't exist, I use DirectCast if I have a reasonable belief that there's an inheritance relationship. If it's a situation where I have no idea if the cast should succeed (user input -> integers, for example), then I use TryCast so as to do something more friendly than toss an exception at the user.

One thing I can't shake is I tend to use ToString instead of CStr but supposedly Cstr is faster.

How to get the separate digits of an int number?

public int[] getDigitsOfANumber(int number) {
    String numStr = String.valueOf(number);
    int retArr[] = new int[numStr.length()];

    for (int i = 0; i < numStr.length(); i++) {
        char c = numStr.charAt(i);
        int digit = c;
        int zero = (char) '0';
        retArr[i] = digit - zero;

    }
    return retArr;
}

SQL Query to find the last day of the month

declare @date datetime;
set @date = getdate(); -- or some date
select dateadd(month,1+datediff(month,0,@date),-1);

hexadecimal string to byte array in python

def hex2bin(s):
    hex_table = ['0000', '0001', '0010', '0011',
                 '0100', '0101', '0110', '0111',
                 '1000', '1001', '1010', '1011',
                 '1100', '1101', '1110', '1111']
    bits = ''
    for i in range(len(s)):
        bits += hex_table[int(s[i], base=16)]
    return bits

Export to CSV using jQuery and html

I am not sure if the above CSV generation code is so great as it appears to skip th cells and also did not appear to allow for commas in the value. So here is my CSV generation code that might be useful.

It does assume you have the $table variable which is a jQuery object (eg. var $table = $('#yourtable');)

$rows = $table.find('tr');

var csvData = "";

for(var i=0;i<$rows.length;i++){
                var $cells = $($rows[i]).children('th,td'); //header or content cells

                for(var y=0;y<$cells.length;y++){
                    if(y>0){
                      csvData += ",";
                    }
                    var txt = ($($cells[y]).text()).toString().trim();
                    if(txt.indexOf(',')>=0 || txt.indexOf('\"')>=0 || txt.indexOf('\n')>=0){
                        txt = "\"" + txt.replace(/\"/g, "\"\"") + "\"";
                    }
                    csvData += txt;
                }
                csvData += '\n';
 }

Insert multiple lines into a file after specified pattern using shell script

sed '/^cdef$/r'<(
    echo "line1"
    echo "line2"
    echo "line3"
    echo "line4"
) -i -- input.txt

Comparing arrays in JUnit assertions, concise built-in way?

Using junit4 and Hamcrest you get a concise method of comparing arrays. It also gives details of where the error is in the failure trace.

import static org.junit.Assert.*
import static org.hamcrest.CoreMatchers.*;

//...

assertThat(result, is(new int[] {56, 100, 2000}));

Failure Trace output:

java.lang.AssertionError: 
   Expected: is [<56>, <100>, <2000>]
   but: was [<55>, <100>, <2000>]

How to add a margin to a table row <tr>

Because margin is ignored on tr, I usually use a workaround, by setting a transparent border-bottom or border-top and setting the background-clip property to padding-box so the background-color does not get painted underneath the border.

table {
   border-collapse: collapse; /* [1] */
}

th, td {
  border-bottom: 5px solid transparent; /* [2] */
  background-color: gold; /* [3] */
  background-clip: padding-box; /* [4] */
}
  1. Makes sure cells share a common border, but is completely optional. The solution works without it.
  2. The 5px value represents the margin that you want to achieve
  3. Sets the background-color of your row/cell
  4. Makes sure the background get not painted underneath the border

see a demo here: http://codepen.io/meodai/pen/MJMVNR?editors=1100

background-clip is supported in all modern browser. (And IE9+)

Alternatively you could use a border-spacing. But this will not work with border-collapse set to collapse.

How to switch to other branch in Source Tree to commit the code?

  1. Go to the log view (to be able to go here go to View -> log view).
  2. Double click on the line with the branch label stating that branch. Automatically, it will switch branch. (A prompt will dropdown and say switching branch.)
  3. If you have two or more branches on the same line, it will ask you via prompt which branch you want to switch. Choose the specific branch from the dropdown and click ok.

To determine which branch you are now on, look at the side bar, under BRANCHES, you are in the branch that is in BOLD LETTERS.

Adding a Button to a WPF DataGrid

XAML :

<DataGrid x:Name="dgv_Students" AutoGenerateColumns="False"  ItemsSource="{Binding People}" Margin="10,20,10,0" Style="{StaticResource AzureDataGrid}" FontFamily="B Yekan" Background="#FFB9D1BA" >
                <DataGrid.Columns>
                    <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button Click="Button_Click_dgvs">Text</Button>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    </DataGrid.Columns>

Code Behind :

       private IEnumerable<DataGridRow> GetDataGridRowsForButtons(DataGrid grid)
{ //IQueryable 
    var itemsSource = grid.ItemsSource as IEnumerable;
    if (null == itemsSource) yield return null;
    foreach (var item in itemsSource)
    {
        var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
        if (null != row & row.IsSelected) yield return row;
    }
}

void Button_Click_dgvs(object sender, RoutedEventArgs e)
{

    for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
        if (vis is DataGridRow)
        {
           // var row = (DataGrid)vis;

            var rows = GetDataGridRowsForButtons(dgv_Students);
            string id;
            foreach (DataGridRow dr in rows)
            {
                id = (dr.Item as tbl_student).Identification_code;
                MessageBox.Show(id);
                 break;
            }
            break;
        }
}

After clicking on the Button, the ID of that row is returned to you and you can use it for your Button name.

How do you set a default value for a MySQL Datetime column?

If you have already created the table then you can use

To change default value to current date time

ALTER TABLE <TABLE_NAME> 
CHANGE COLUMN <COLUMN_NAME> <COLUMN_NAME> DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;

To change default value to '2015-05-11 13:01:01'

ALTER TABLE <TABLE_NAME> 
CHANGE COLUMN <COLUMN_NAME> <COLUMN_NAME> DATETIME NOT NULL DEFAULT '2015-05-11 13:01:01';

How do I increase the RAM and set up host-only networking in Vagrant?

I could not get any of these answers to work. Here's what I ended up putting at the very top of my Vagrantfile, before the Vagrant::Config.run do block:

Vagrant.configure("2") do |config|
  config.vm.provider "virtualbox" do |vb|
    vb.customize ["modifyvm", :id, "--memory", "1024"]
  end
end

I noticed that the shortcut accessor style, "vb.memory = 1024", didn't seem to work.

How to Call a JS function using OnClick event

You are attempting to attach an event listener function before the element is loaded. Place fun() inside an onload event listener function. Call f1() within this function, as the onclick attribute will be ignored.

function f1() {
    alert("f1 called");
    //form validation that recalls the page showing with supplied inputs.    
}
window.onload = function() {
    document.getElementById("Save").onclick = function fun() {
        alert("hello");
        f1();
        //validation code to see State field is mandatory.  
    }
}

JSFiddle

How do you implement a re-try-catch?

Obligatory "enterprisy" solution:

public abstract class Operation {
    abstract public void doIt();
    public void handleException(Exception cause) {
        //default impl: do nothing, log the exception, etc.
    }
}

public class OperationHelper {
    public static void doWithRetry(int maxAttempts, Operation operation) {
        for (int count = 0; count < maxAttempts; count++) {
            try {
                operation.doIt();
                count = maxAttempts; //don't retry
            } catch (Exception e) {
                operation.handleException(e);
            }
        }
    }
}

And to call:

OperationHelper.doWithRetry(5, new Operation() {
    @Override public void doIt() {
        //do some stuff
    }
    @Override public void handleException(Exception cause) {
        //recover from the Exception
    }
});

How to delete or change directory of a cloned git repository on a local computer

  1. Go to working directory where you project folder (cloned folder) is placed.
  2. Now delete the folder.
  3. in windows just right click and do delete.
  4. in command line use rm -r "folder name"
  5. this worked for me

LinkButton Send Value to Code Behind OnClick

Just add to the CommandArgument parameter and read it out on the Click handler:

<asp:LinkButton ID="ENameLinkBtn" runat="server" 
    style="font-weight: 700; font-size: 8pt;" CommandArgument="YourValueHere" 
    OnClick="ENameLinkBtn_Click" >

Then in your click event:

protected void ENameLinkBtn_Click(object sender, EventArgs e)
{
    LinkButton btn = (LinkButton)(sender);
    string yourValue = btn.CommandArgument;
    // do what you need here
}   

Also you can set the CommandArgument argument when binding if you are using the LinkButton in any bindable controls by doing:

CommandArgument='<%# Eval("SomeFieldYouNeedArguementFrom") %>'

Combine multiple JavaScript files into one JS file

This may be a bit of effort but you could download my open-source wiki project from codeplex:

http://shuttlewiki.codeplex.com

It contains a CompressJavascript project (and CompressCSS) that uses the http://yuicompressor.codeplex.com/ project.

The code should be self-explanatory but it makes combining and compressing the files a bit simnpler --- for me anyway :)

The ShuttleWiki project shows how to use it in the post-build event.

How do I store data in local storage using Angularjs?

There is one more alternative module which has more activity than ngStorage

angular-local-storage:

https://github.com/grevory/angular-local-storage

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

What is dynamic programming?

Here is a simple python code example of Recursive, Top-down, Bottom-up approach for Fibonacci series:

Recursive: O(2n)

def fib_recursive(n):
    if n == 1 or n == 2:
        return 1
    else:
        return fib_recursive(n-1) + fib_recursive(n-2)


print(fib_recursive(40))

Top-down: O(n) Efficient for larger input

def fib_memoize_or_top_down(n, mem):
    if mem[n] is not 0:
        return mem[n]
    else:
        mem[n] = fib_memoize_or_top_down(n-1, mem) + fib_memoize_or_top_down(n-2, mem)
        return mem[n]


n = 40
mem = [0] * (n+1)
mem[1] = 1
mem[2] = 1
print(fib_memoize_or_top_down(n, mem))

Bottom-up: O(n) For simplicity and small input sizes

def fib_bottom_up(n):
    mem = [0] * (n+1)
    mem[1] = 1
    mem[2] = 1
    if n == 1 or n == 2:
        return 1

    for i in range(3, n+1):
        mem[i] = mem[i-1] + mem[i-2]

    return mem[n]


print(fib_bottom_up(40))

Get value of a string after last slash in JavaScript

Try this:

_x000D_
_x000D_
const url = "files/images/gallery/image.jpg";_x000D_
_x000D_
console.log(url.split("/").pop());
_x000D_
_x000D_
_x000D_

converting multiple columns from character to numeric format in r

You could use convert from the hablar package:

library(dplyr)
library(hablar)

# Sample df (stolen from the solution by Luca Braglia)
df <- tibble("a" = as.character(0:5),
                 "b" = paste(0:5, ".1", sep = ""),
                 "c" = letters[1:6])

# insert variable names in num()
df %>% convert(num(a, b))

Which gives you:

# A tibble: 6 x 3
      a     b c    
  <dbl> <dbl> <chr>
1    0. 0.100 a    
2    1. 1.10  b    
3    2. 2.10  c    
4    3. 3.10  d    
5    4. 4.10  e    
6    5. 5.10  f   

Or if you are lazy, let retype() from hablar guess the right data type:

df %>% retype()

which gives you:

# A tibble: 6 x 3
      a     b c    
  <int> <dbl> <chr>
1     0 0.100 a    
2     1 1.10  b    
3     2 2.10  c    
4     3 3.10  d    
5     4 4.10  e    
6     5 5.10  f   

How to access a value defined in the application.properties file in Spring Boot

You can use the @Value annotation and access the property in whichever Spring bean you're using

@Value("${userBucket.path}")
private String userBucketPath;

The Externalized Configuration section of the Spring Boot docs, explains all the details that you might need.

Express.js req.body undefined

In my case, it was because of using body-parser after including the routes.

The correct code should be

app.use(bodyParser.urlencoded({extended:true}));
app.use(methodOverride("_method"));
app.use(indexRoutes);
app.use(userRoutes);
app.use(adminRoutes);

Correct way to focus an element in Selenium WebDriver using Java

The focus only works if the window is focused.

Use ((JavascriptExecutor)webDriver).executeScript("window.focus();"); to be sure.

Extracting Ajax return data in jQuery

You can use .filter on a jQuery object that was created from the response:

success: function(data){
    //Create jQuery object from the response HTML.
    var $response=$(data);

    //Query the jQuery object for the values
    var oneval = $response.filter('#one').text();
    var subval = $response.filter('#sub').text();
}

how to load CSS file into jsp

css href link is incorrect. Use relative path instead:

<link href="../css/loginstyle.css" rel="stylesheet" type="text/css">

Match all elements having class name starting with a specific string

The following should do the trick:

div[class^='myclass'], div[class*=' myclass']{
    color: #F00;
}

Edit: Added wildcard (*) as suggested by David

Postgresql Select rows where column = array

In my case, I needed to work with a column that has the data, so using IN() didn't work. Thanks to @Quassnoi for his examples. Here is my solution:

SELECT column(s) FROM table WHERE expr|column = ANY(STRING_TO_ARRAY(column,',')::INT[])

I spent almost 6 hours before I stumble on the post.

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>

How to find out the server IP address (using JavaScript) that the browser is connected to?

I am sure the following code will help you to get ip address.

<script type="application/javascript">
    function getip(json){
      alert(json.ip); // alerts the ip address
    }
</script>

<script type="application/javascript" src="http://www.telize.com/jsonip?callback=getip"></script>

How To Change DataType of a DataColumn in a DataTable?

Once a DataTable has been filled, you can't change the type of a column.

Your best option in this scenario is to add an Int32 column to the DataTable before filling it:

dataTable = new DataTable("Contact");
dataColumn = new DataColumn("Id");
dataColumn.DataType = typeof(Int32);
dataTable.Columns.Add(dataColumn);

Then you can clone the data from your original table to the new table:

DataTable dataTableClone = dataTable.Clone();

Here's a post with more details.

Running Node.js in apache?

You can always do something shell-scripty like:

#!/usr/bin/node

var header = "Content-type: text/plain\n";
var hi = "Hello World from nodetest!";
console.log(header);
console.log(hi);

exit;

how to programmatically fake a touch event to a UIButton?

If you want to do this kind of testing, you’ll love the UI Automation support in iOS 4. You can write JavaScript to simulate button presses, etc. fairly easily, though the documentation (especially the getting-started part) is a bit sparse.

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 can I add an ampersand for a value in a ASP.net/C# app config file value

Have you tried this?

<appSettings>  
  <add key="myurl" value="http://www.myurl.com?&amp;cid=&amp;sid="/>
<appSettings>

iOS download and save image inside app

Although it is true that the other answers here will work, they really aren't solutions that should ever be used in production code. (at least not without modification)

Problems

The problem with these answers is that if they are implemented as is and are not called from a background thread, they will block the main thread while downloading and saving the image. This is bad.

If the main thread is blocked, UI updates won't happen until the downloading/saving of the image is complete. As an example of what this means, say you add a UIActivityIndicatorView to your app to show the user that the download is still in progress (I will be using this as an example throughout this answer) with the following rough control flow:

  1. Object responsible for starting the download is loaded.
  2. Tell the activity indicator to start animating.
  3. Start the synchronous download process using +[NSData dataWithContentsOfURL:]
  4. Save the data (image) that was just downloaded.
  5. Tell the activity indicator to stop animating.

Now, this might seem like reasonable control flow, but it is disguising a critical problem.

When you call the activity indicator's startAnimating method on the main (UI) thread, the UI updates for this event won't actually happen until the next time the main run loop updates, and this is where the first major problem is.

Before this update has a chance to happen, the download is triggered, and since this is a synchronous operation, it blocks the main thread until it has finished download (saving has the same problem). This will actually prevent the activity indicator from starting its animation. After that you call the activity indicator's stopAnimating method and expect all to be good, but it isn't.

At this point, you'll probably find yourself wondering the following.

Why doesn't my activity indicator ever show up?

Well, think about it like this. You tell the indicator to start but it doesn't get a chance before the download starts. After the download completes, you tell the indicator to stop animating. Since the main thread was blocked through the whole operation, the behavior you actually see is more along the lines telling the indicator to start and then immediately telling it to stop, even though there was a (possibly) large download task in between.

Now, in the best case scenario, all this does is cause a poor user experience (still really bad). Even if you think this isn't a big deal because you're only downloading a small image and the download happens almost instantaneously, that won't always be the case. Some of your users may have slow internet connections, or something may be wrong server side keeping the download from starting immediately/at all.

In both of these cases, the app won't be able to process UI updates, or even touch events while your download task sits around twiddling its thumbs waiting for the download to complete or for the server to respond to its request.

What this means is that synchronously downloading from the main thread prevents you from possibly implementing anything to indicate to the user that a download is currently in progress. And since touch events are processed on the main thread as well, this throws out the possibility of adding any kind of cancel button as well.

Then in the worst case scenario, you'll start receiving crash reports stating the following.

Exception Type: 00000020 Exception Codes: 0x8badf00d

These are easy to identify by the exception code 0x8badf00d, which can be read as "ate bad food". This exception is thrown by the watch dog timer, whose job is to watch for long running tasks that block the main thread, and to kill the offending app if this goes on for too long. Arguably, this is still a poor user experience issue, but if this starts to occur, the app has crossed the line between bad user experience, and terrible user experience.

Here's some more info on what can cause this to happen from Apple's Technical Q&A about synchronous networking (shortened for brevity).

The most common cause for watchdog timeout crashes in a network application is synchronous networking on the main thread. There are four contributing factors here:

  1. synchronous networking — This is where you make a network request and block waiting for the response.
  2. main thread — Synchronous networking is less than ideal in general, but it causes specific problems if you do it on the main thread. Remember that the main thread is responsible for running the user interface. If you block the main thread for any significant amount of time, the user interface becomes unacceptably unresponsive.
  3. long timeouts — If the network just goes away (for example, the user is on a train which goes into a tunnel), any pending network request won't fail until some timeout has expired....

...

  1. watchdog — In order to keep the user interface responsive, iOS includes a watchdog mechanism. If your application fails to respond to certain user interface events (launch, suspend, resume, terminate) in time, the watchdog will kill your application and generate a watchdog timeout crash report. The amount of time the watchdog gives you is not formally documented, but it's always less than a network timeout.

One tricky aspect of this problem is that it's highly dependent on the network environment. If you always test your application in your office, where network connectivity is good, you'll never see this type of crash. However, once you start deploying your application to end users—who will run it in all sorts of network environments—crashes like this will become common.

Now at this point, I'll stop rambling about why the provided answers might be problematic and will start offering up some alternative solutions. Keep in mind that I've used the URL of a small image in these examples and you'll notice a larger difference when using a higher resolution image.


Solutions

I'll start by showing a safe version of the other answers, with the addition of how to handle UI updates. This will be the first of several examples, all of which will assume that the class in which they are implemented has valid properties for a UIImageView, a UIActivityIndicatorView, as well as the documentsDirectoryURL method to access the documents directory. In production code, you may want to implement your own method to access the documents directory as a category on NSURL for better code reusability, but for these examples, this will be fine.

- (NSURL *)documentsDirectoryURL
{
    NSError *error = nil;
    NSURL *url = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory
                                                        inDomain:NSUserDomainMask
                                               appropriateForURL:nil
                                                          create:NO
                                                           error:&error];
    if (error) {
        // Figure out what went wrong and handle the error.
    }
    
    return url;
}

These examples will also assume that the thread that they start off on is the main thread. This will likely be the default behavior unless you start your download task from somewhere like the callback block of some other asynchronous task. If you start your download in a typical place, like a lifecycle method of a view controller (i.e. viewDidLoad, viewWillAppear:, etc.) this will produce the expected behavior.

This first example will use the +[NSData dataWithContentsOfURL:] method, but with some key differences. For one, you'll notice that in this example, the very first call we make is to tell the activity indicator to start animating, then there is an immediate difference between this and the synchronous examples. Immediately, we use dispatch_async(), passing in the global concurrent queue to move execution to the background thread.

At this point, you've already greatly improved your download task. Since everything within the dispatch_async() block will now happen off the main thread, your interface will no longer lock up, and your app will be free to respond to touch events.

What is important to notice here is that all of the code within this block will execute on the background thread, up until the point where the downloading/saving of the image was successful, at which point you might want to tell the activity indicator to stopAnimating, or apply the newly saved image to a UIImageView. Either way, these are updates to the UI, meaning you must dispatch back the the main thread using dispatch_get_main_queue() to perform them. Failing to do so results in undefined behavior, which may cause the UI to update after an unexpected period of time, or may even cause a crash. Always make sure you move back to the main thread before performing UI updates.

// Start the activity indicator before moving off the main thread
[self.activityIndicator startAnimating];
// Move off the main thread to start our blocking tasks.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Create the image URL from a known string.
    NSURL *imageURL = [NSURL URLWithString:@"http://www.google.com/images/srpr/logo3w.png"];
    
    NSError *downloadError = nil;
    // Create an NSData object from the contents of the given URL.
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL
                                              options:kNilOptions
                                                error:&downloadError];
    // ALWAYS utilize the error parameter!
    if (downloadError) {
        // Something went wrong downloading the image. Figure out what went wrong and handle the error.
        // Don't forget to return to the main thread if you plan on doing UI updates here as well.
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.activityIndicator stopAnimating];
            NSLog(@"%@",[downloadError localizedDescription]);
        });
    } else {
        // Get the path of the application's documents directory.
        NSURL *documentsDirectoryURL = [self documentsDirectoryURL];
        // Append the desired file name to the documents directory path.
        NSURL *saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:@"GCD.png"];

        NSError *saveError = nil;
        BOOL writeWasSuccessful = [imageData writeToURL:saveLocation
                                                options:kNilOptions
                                                  error:&saveError];
        // Successful or not we need to stop the activity indicator, so switch back the the main thread.
        dispatch_async(dispatch_get_main_queue(), ^{
            // Now that we're back on the main thread, you can make changes to the UI.
            // This is where you might display the saved image in some image view, or
            // stop the activity indicator.
            
            // Check if saving the file was successful, once again, utilizing the error parameter.
            if (writeWasSuccessful) {
                // Get the saved image data from the file.
                NSData *imageData = [NSData dataWithContentsOfURL:saveLocation];
                // Set the imageView's image to the image we just saved.
                self.imageView.image = [UIImage imageWithData:imageData];
            } else {
                NSLog(@"%@",[saveError localizedDescription]);
                // Something went wrong saving the file. Figure out what went wrong and handle the error.
            }
            
            [self.activityIndicator stopAnimating];
        });
    }
});

Now keep in mind, that the method shown above is still not an ideal solution considering it can't be cancelled prematurely, it gives you no indication of the progress of the download, it can't handle any kind of authentication challenge, it can't be given a specific timeout interval, etc. (lots and lots of reasons). I'll cover a few of the better options below.

In these examples, I'll only be covering solutions for apps targeting iOS 7 and up considering (at time of writing) iOS 8 is the current major release, and Apple is suggesting only supporting versions N and N-1. If you need to support older iOS versions, I recommend looking into the NSURLConnection class, as well as the 1.0 version of AFNetworking. If you look at the revision history of this answer, you can find basic examples using NSURLConnection and ASIHTTPRequest, although it should be noted that ASIHTTPRequest is no longer being maintained, and should not be used for new projects.


NSURLSession

Lets start with NSURLSession, which was introduced in iOS 7, and greatly improves the ease with which networking can be done in iOS. With NSURLSession, you can easily perform asynchronous HTTP requests with a callback block and handle authentication challenges with its delegate. But what makes this class really special is that it also allows for download tasks to continue running even if the application is sent to the background, gets terminated, or even crashes. Here's a basic example of its usage.

// Start the activity indicator before starting the download task.
[self.activityIndicator startAnimating];

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// Use a session with a custom configuration
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
// Create the image URL from some known string.
NSURL *imageURL = [NSURL URLWithString:@"http://www.google.com/images/srpr/logo3w.png"];
// Create the download task passing in the URL of the image.
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:imageURL completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    // Get information about the response if neccessary.
    if (error) {
        NSLog(@"%@",[error localizedDescription]);
        // Something went wrong downloading the image. Figure out what went wrong and handle the error.
        // Don't forget to return to the main thread if you plan on doing UI updates here as well.
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.activityIndicator stopAnimating];
        });
    } else {
        NSError *openDataError = nil;
        NSData *downloadedData = [NSData dataWithContentsOfURL:location
                                                       options:kNilOptions
                                                         error:&openDataError];
        if (openDataError) {
            // Something went wrong opening the downloaded data. Figure out what went wrong and handle the error.
            // Don't forget to return to the main thread if you plan on doing UI updates here as well.
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"%@",[openDataError localizedDescription]);
                [self.activityIndicator stopAnimating];
            });
        } else {
            // Get the path of the application's documents directory.
            NSURL *documentsDirectoryURL = [self documentsDirectoryURL];
            // Append the desired file name to the documents directory path.
            NSURL *saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:@"NSURLSession.png"];
            NSError *saveError = nil;
            
            BOOL writeWasSuccessful = [downloadedData writeToURL:saveLocation
                                                          options:kNilOptions
                                                            error:&saveError];
            // Successful or not we need to stop the activity indicator, so switch back the the main thread.
            dispatch_async(dispatch_get_main_queue(), ^{
                // Now that we're back on the main thread, you can make changes to the UI.
                // This is where you might display the saved image in some image view, or
                // stop the activity indicator.
                
                // Check if saving the file was successful, once again, utilizing the error parameter.
                if (writeWasSuccessful) {
                    // Get the saved image data from the file.
                    NSData *imageData = [NSData dataWithContentsOfURL:saveLocation];
                    // Set the imageView's image to the image we just saved.
                    self.imageView.image = [UIImage imageWithData:imageData];
                } else {
                    NSLog(@"%@",[saveError localizedDescription]);
                    // Something went wrong saving the file. Figure out what went wrong and handle the error.
                }
                
                [self.activityIndicator stopAnimating];
            });
        }
    }
}];

// Tell the download task to resume (start).
[task resume];

From this you'll notice that the downloadTaskWithURL: completionHandler: method returns an instance of NSURLSessionDownloadTask, on which an instance method -[NSURLSessionTask resume] is called. This is the method that actually tells the download task to start. This means that you can spin up your download task, and if desired, hold off on starting it (if needed). This also means that as long as you store a reference to the task, you can also utilize its cancel and suspend methods to cancel or pause the task if need be.

What's really cool about NSURLSessionTasks is that with a little bit of KVO, you can monitor the values of its countOfBytesExpectedToReceive and countOfBytesReceived properties, feed these values to an NSByteCountFormatter, and easily create a download progress indicator to your user with human readable units (e.g. 42 KB of 100 KB).

Before I move away from NSURLSession though, I'd like to point out that the ugliness of having to dispatch_async back to the main threads at several different points in the download's callback block can be avoided. If you chose to go this route, you can initialize the session with its initializer that allows you to specify the delegate, as well as the delegate queue. This will require you to use the delegate pattern instead of the callback blocks, but this may be beneficial because it is the only way to support background downloads.

NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration
                                                      delegate:self
                                                 delegateQueue:[NSOperationQueue mainQueue]];

AFNetworking 2.0

If you've never heard of AFNetworking, it is IMHO the end-all of networking libraries. It was created for Objective-C, but it works in Swift as well. In the words of its author:

AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of the Foundation URL Loading System, extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.

AFNetworking 2.0 supports iOS 6 and up, but in this example, I will be using its AFHTTPSessionManager class, which requires iOS 7 and up due to its usage of all the new APIs around the NSURLSession class. This will become obvious when you read the example below, which shares a lot of code with the NSURLSession example above.

There are a few differences that I'd like to point out though. To start off, instead of creating your own NSURLSession, you'll create an instance of AFURLSessionManager, which will internally manage a NSURLSession. Doing so allows you take advantage of some of its convenience methods like -[AFURLSessionManager downloadTaskWithRequest:progress:destination:completionHandler:]. What is interesting about this method is that it lets you fairly concisely create a download task with a given destination file path, a completion block, and an input for an NSProgress pointer, on which you can observe information about the progress of the download. Here's an example.

// Use the default session configuration for the manager (background downloads must use the delegate APIs)
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// Use AFNetworking's NSURLSessionManager to manage a NSURLSession.
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

// Create the image URL from some known string.
NSURL *imageURL = [NSURL URLWithString:@"http://www.google.com/images/srpr/logo3w.png"];
// Create a request object for the given URL.
NSURLRequest *request = [NSURLRequest requestWithURL:imageURL];
// Create a pointer for a NSProgress object to be used to determining download progress.
NSProgress *progress = nil;

// Create the callback block responsible for determining the location to save the downloaded file to.
NSURL *(^destinationBlock)(NSURL *targetPath, NSURLResponse *response) = ^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    // Get the path of the application's documents directory.
    NSURL *documentsDirectoryURL = [self documentsDirectoryURL];
    NSURL *saveLocation = nil;
    
    // Check if the response contains a suggested file name
    if (response.suggestedFilename) {
        // Append the suggested file name to the documents directory path.
        saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:response.suggestedFilename];
    } else {
        // Append the desired file name to the documents directory path.
        saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:@"AFNetworking.png"];
    }

    return saveLocation;
};

// Create the completion block that will be called when the image is done downloading/saving.
void (^completionBlock)(NSURLResponse *response, NSURL *filePath, NSError *error) = ^void (NSURLResponse *response, NSURL *filePath, NSError *error) {
    dispatch_async(dispatch_get_main_queue(), ^{
        // There is no longer any reason to observe progress, the download has finished or cancelled.
        [progress removeObserver:self
                      forKeyPath:NSStringFromSelector(@selector(fractionCompleted))];
        
        if (error) {
            NSLog(@"%@",error.localizedDescription);
            // Something went wrong downloading or saving the file. Figure out what went wrong and handle the error.
        } else {
            // Get the data for the image we just saved.
            NSData *imageData = [NSData dataWithContentsOfURL:filePath];
            // Get a UIImage object from the image data.
            self.imageView.image = [UIImage imageWithData:imageData];
        }
    });
};

// Create the download task for the image.
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request
                                                         progress:&progress
                                                      destination:destinationBlock
                                                completionHandler:completionBlock];
// Start the download task.
[task resume];

// Begin observing changes to the download task's progress to display to the user.
[progress addObserver:self
           forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
              options:NSKeyValueObservingOptionNew
              context:NULL];

Of course since we've added the class containing this code as an observer to one of the NSProgress instance's properties, you'll have to implement the -[NSObject observeValueForKeyPath:ofObject:change:context:] method. In this case, I've included an example of how you might update a progress label to display the download's progress. It's really easy. NSProgress has an instance method localizedDescription which will display progress information in a localized, human readable format.

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    // We only care about updates to fractionCompleted
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(fractionCompleted))]) {
        NSProgress *progress = (NSProgress *)object;
        // localizedDescription gives a string appropriate for display to the user, i.e. "42% completed"
        self.progressLabel.text = progress.localizedDescription;
    } else {
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                               change:change
                              context:context];
    }
}

Don't forget, if you want to use AFNetworking in your project, you'll need to follow its installation instructions and be sure to #import <AFNetworking/AFNetworking.h>.

Alamofire

And finally, I'd like to give a final example using Alamofire. This is a the library that makes networking in Swift a cake-walk. I'm out of characters to go into great detail about the contents of this sample, but it does pretty much the same thing as the last examples, just in an arguably more beautiful way.

// Create the destination closure to pass to the download request. I haven't done anything with them
// here but you can utilize the parameters to make adjustments to the file name if neccessary.
let destination = { (url: NSURL!, response: NSHTTPURLResponse!) -> NSURL in
    var error: NSError?
    // Get the documents directory
    let documentsDirectory = NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory,
        inDomain: .UserDomainMask,
        appropriateForURL: nil,
        create: false,
        error: &error
    )
    
    if let error = error {
        // This could be bad. Make sure you have a backup plan for where to save the image.
        println("\(error.localizedDescription)")
    }
    
    // Return a destination of .../Documents/Alamofire.png
    return documentsDirectory!.URLByAppendingPathComponent("Alamofire.png")
}

Alamofire.download(.GET, "http://www.google.com/images/srpr/logo3w.png", destination)
    .validate(statusCode: 200..<299) // Require the HTTP status code to be in the Successful range.
    .validate(contentType: ["image/png"]) // Require the content type to be image/png.
    .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
        // Create an NSProgress object to represent the progress of the download for the user.
        let progress = NSProgress(totalUnitCount: totalBytesExpectedToRead)
        progress.completedUnitCount = totalBytesRead
        
        dispatch_async(dispatch_get_main_queue()) {
            // Move back to the main thread and update some progress label to show the user the download is in progress.
            self.progressLabel.text = progress.localizedDescription
        }
    }
    .response { (request, response, _, error) in
        if error != nil {
            // Something went wrong. Handle the error.
        } else {
            // Open the newly saved image data.
            if let imageData = NSData(contentsOfURL: destination(nil, nil)) {
                dispatch_async(dispatch_get_main_queue()) {
                    // Move back to the main thread and add the image to your image view.
                    self.imageView.image = UIImage(data: imageData)
                }
            }
        }
    }

Install php-mcrypt on CentOS 6

To install mcrypt from http://namhuy.net/641/centos-6-install-mcrypt-for-phpmyadmin.html

i386

rpm -Uvh http://dl.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm

x86_64

http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm

then just use yum command to install the mcrypt package

yum install php-mcrypt

How can I make SMTP authenticated in C#

Ensure you set SmtpClient.Credentials after calling SmtpClient.UseDefaultCredentials = false.

The order is important as setting SmtpClient.UseDefaultCredentials = false will reset SmtpClient.Credentials to null.

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

How to remove lines in a Matplotlib plot

I'm showing that a combination of lines.pop(0) l.remove() and del l does the trick.

from matplotlib import pyplot
import numpy, weakref
a = numpy.arange(int(1e3))
fig = pyplot.Figure()
ax  = fig.add_subplot(1, 1, 1)
lines = ax.plot(a)

l = lines.pop(0)
wl = weakref.ref(l)  # create a weak reference to see if references still exist
#                      to this object
print wl  # not dead
l.remove()
print wl  # not dead
del l
print wl  # dead  (remove either of the steps above and this is still live)

I checked your large dataset and the release of the memory is confirmed on the system monitor as well.

Of course the simpler way (when not trouble-shooting) would be to pop it from the list and call remove on the line object without creating a hard reference to it:

lines.pop(0).remove()

Android: Quit application when press back button

In order to exit from the app on pressing back button you have to first clear all the top activities and then start the ACTION_MAIN of android phone

So, you have to write all these code only which is mentioned below :

Note : In your case MainActivity get replaced by YourActivity

@Override
public void onBackPressed() {

        new AlertDialog.Builder(this)
                .setTitle("Really Exit?")
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MainActivity.super.onBackPressed();
                        quit();
                    }
                }).create().show();
    }


public void quit() {
        Intent start = new Intent(Intent.ACTION_MAIN);
        start.addCategory(Intent.CATEGORY_HOME);
        start.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        start.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(start);
    }

python selenium click on button

open a website https://adviserinfo.sec.gov/compilation and click on button to download the file and even i want to close the pop up if it comes using python selenium

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from selenium.webdriver.chrome.options import Options 

#For Mac - If you use windows change the chromedriver location
chrome_path = '/usr/local/bin/chromedriver'
driver = webdriver.Chrome(chrome_path)

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--disable-popup-blocking")

driver.maximize_window()
driver.get("https://adviserinfo.sec.gov/compilation")

# driver.get("https://adviserinfo.sec.gov/")
# tabName = driver.find_element_by_link_text("Investment Adviser Data")
# tabName.click()

time.sleep(3)

# report1 = driver.find_element_by_xpath("//div[@class='compilation-container ng-scope layout-column flex']//div[1]//div[1]//div[1]//div[2]//button[1]")

report1 = driver.find_element_by_xpath("//button[@analytics-label='IAPD - SEC Investment Adviser Report (GZIP)']")

# print(report1)
report1.click()

time.sleep(5)

driver.close()

php resize image on upload

Here is another nice and easy solution:

$maxDim = 800;
$file_name = $_FILES['myFile']['tmp_name'];
list($width, $height, $type, $attr) = getimagesize( $file_name );
if ( $width > $maxDim || $height > $maxDim ) {
    $target_filename = $file_name;
    $ratio = $width/$height;
    if( $ratio > 1) {
        $new_width = $maxDim;
        $new_height = $maxDim/$ratio;
    } else {
        $new_width = $maxDim*$ratio;
        $new_height = $maxDim;
    }
    $src = imagecreatefromstring( file_get_contents( $file_name ) );
    $dst = imagecreatetruecolor( $new_width, $new_height );
    imagecopyresampled( $dst, $src, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
    imagedestroy( $src );
    imagepng( $dst, $target_filename ); // adjust format as needed
    imagedestroy( $dst );
}

Reference: PHP resize image proportionally with max width or weight

Edit: Cleaned up and simplified the code a bit. Thanks @jan-mirus for your comment.

How to terminate script execution when debugging in Google Chrome?

If you have a rogue loop, pause the code in Google Chrome debugger (the small "||" button while in Sources tab).

Switch back to Chrome itself, open "Task Manager" (Shift+ESC), select your tab, click the "End Process" button.

You will get the Aww Snap message and then you can reload (F5).

As others have noted, reloading the page at the point of pausing is the same as restarting the rogue loop and can cause nasty lockups if the debugger also then locks (in some cases leading to restarting chrome or even the PC). The debugger needs a "Stop" button. Nb: The accepted answer is out of date in that some aspects of it are now apparently wrong. If you vote me down, pls explain :).

SCCM 2012 application install "Failed" in client Software Center

I'm assuming you figured this out already but:

Technical Reference for Log Files in Configuration Manager

That's a list of client-side logs and what they do. They are located in Windows\CCM\Logs

AppEnforce.log will show you the actual command-line executed and the resulting exit code for each Deployment Type (only for the new style ConfigMgr Applications)

This is my go-to for troubleshooting apps. Haven't really found any other logs that are exceedingly useful.

htaccess - How to force the client's browser to clear the cache?

As other answers have said, changing the URL is a good cache busting technique, however it is alot of work to go through a bigger site, change all the URLs and also move the files.

A similar technique is to just add a version parameter to the URL string which is either a random string / number or a version number, and target the changed files only.

For instance if you change your sites CSS and it looks wonky until you do a force refresh, simply add ?ver=1.1 to the CSS import at the head of the file. This to the browser is a different file, but you only need to change the import, not the actual location or name of the file.

e.g:

<link href="assets/css/style.css" rel="stylesheet" type="text/css" />

becomes

<link href="assets/css/style.css?ver=1.1" rel="stylesheet" type="text/css" />

Works great for javascript files also.

Any implementation of Ordered Set in Java?

IndexedTreeSet from the indexed-tree-map project provides this functionality (ordered/sorted set with list-like access by index).

Using an index to get an item, Python

What you show, ('A','B','C','D','E'), is not a list, it's a tuple (the round parentheses instead of square brackets show that). Nevertheless, whether it to index a list or a tuple (for getting one item at an index), in either case you append the index in square brackets.

So:

thetuple = ('A','B','C','D','E')
print thetuple[0]

prints A, and so forth.

Tuples (differently from lists) are immutable, so you couldn't assign to thetuple[0] etc (as you could assign to an indexing of a list). However you can definitely just access ("get") the item by indexing in either case.

How to start an application using android ADB tools?

Also, I want to mention one more thing.

When you start an application from adb shell am, it automatically adds FLAG_ACTIVITY_NEW_TASK flag which makes behavior change. See the code.

For example, if you launch Play Store activity from adb shell am, pressing 'Back' button(hardware back button) wouldn't take you your app, instead it would take you previous Play Store activity if there was some(If there was not Play store task, then it would take you your app). FLAG_ACTIVITY_NEW_TASK documentation says :

if a task is already running for the activity you are now starting, then a new activity will not be started; instead, the current task will simply be brought to the front of the screen with the state it was last in

This caused me to spend a few hours to find out what went wrong.

So, keep in mind that adb shell am add FLAG_ACTIVITY_NEW_TASK flag.

Pure JavaScript Send POST Data Without a Form

const data = { username: 'example' };

fetch('https://example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
 '           Content-Type': 'application/json',
           },
  body: JSON.stringify(data),
})
  .then(response => response.json())
  .then(data => {
      console.log('Success:', data);
     })
 .catch((error) => {
         console.error('Error:', error);
   });

How to get a complete list of ticker symbols from Yahoo Finance?

i had a similar problem. yahoo doesn't offer it, but you can get one by looking through the document.write statements on nyse.com's list and finding the .js file where they just happen to store the list of companies starting with the given letter as a js array literal. you can also get nice tidy csv files from nasdaq.com here: http://www.nasdaq.com/screening/companies-by-name.aspx?letter=0&exchange=nasdaq&render=download (replace exchange=nasdaq with exchange=nyse for nyse symbols).

403 - Forbidden: Access is denied. ASP.Net MVC

I just had this issue, it was because the IIS site was pointing at the wrong Application Pool.

'innerText' works in IE, but not in Firefox

Firefox uses the W3C-compliant textContent property.

I'd guess Safari and Opera also support this property.

Override standard close (X) button in a Windows Form

as Jon B said, but you'll also want to check for the ApplicationExitCall and TaskManagerClosing CloseReason:

protected override void OnFormClosing(FormClosingEventArgs e)
{
    if (  e.CloseReason == CloseReason.WindowsShutDown 
        ||e.CloseReason == CloseReason.ApplicationExitCall
        ||e.CloseReason == CloseReason.TaskManagerClosing) { 
       return; 
    }
    e.Cancel = true;
    //assuming you want the close-button to only hide the form, 
    //and are overriding the form's OnFormClosing method:
    this.Hide();
}

Bind TextBox on Enter-key press

You can make yourself a pure XAML approach by creating an attached behaviour.

Something like this:

public static class InputBindingsManager
{

    public static readonly DependencyProperty UpdatePropertySourceWhenEnterPressedProperty = DependencyProperty.RegisterAttached(
            "UpdatePropertySourceWhenEnterPressed", typeof(DependencyProperty), typeof(InputBindingsManager), new PropertyMetadata(null, OnUpdatePropertySourceWhenEnterPressedPropertyChanged));

    static InputBindingsManager()
    {

    }

    public static void SetUpdatePropertySourceWhenEnterPressed(DependencyObject dp, DependencyProperty value)
    {
        dp.SetValue(UpdatePropertySourceWhenEnterPressedProperty, value);
    }

    public static DependencyProperty GetUpdatePropertySourceWhenEnterPressed(DependencyObject dp)
    {
        return (DependencyProperty)dp.GetValue(UpdatePropertySourceWhenEnterPressedProperty);
    }

    private static void OnUpdatePropertySourceWhenEnterPressedPropertyChanged(DependencyObject dp, DependencyPropertyChangedEventArgs e)
    {
        UIElement element = dp as UIElement;

        if (element == null)
        {
            return;
        }

        if (e.OldValue != null)
        {
            element.PreviewKeyDown -= HandlePreviewKeyDown;
        }

        if (e.NewValue != null)
        {
            element.PreviewKeyDown += new KeyEventHandler(HandlePreviewKeyDown);
        }
    }

    static void HandlePreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            DoUpdateSource(e.Source);
        }
    }

    static void DoUpdateSource(object source)
    {
        DependencyProperty property =
            GetUpdatePropertySourceWhenEnterPressed(source as DependencyObject);

        if (property == null)
        {
            return;
        }

        UIElement elt = source as UIElement;

        if (elt == null)
        {
            return;
        }

        BindingExpression binding = BindingOperations.GetBindingExpression(elt, property);

        if (binding != null)
        {
            binding.UpdateSource();
        }
    }
}

Then in your XAML you set the InputBindingsManager.UpdatePropertySourceWhenEnterPressedProperty property to the one you want updating when the Enter key is pressed. Like this

<TextBox Name="itemNameTextBox"
         Text="{Binding Path=ItemName, UpdateSourceTrigger=PropertyChanged}"
         b:InputBindingsManager.UpdatePropertySourceWhenEnterPressed="TextBox.Text"/>

(You just need to make sure to include an xmlns clr-namespace reference for "b" in the root element of your XAML file pointing to which ever namespace you put the InputBindingsManager in).

Select rows where column is null

I'm not sure if this answers your question, but using the IS NULL construct, you can test whether any given scalar expression is NULL:

SELECT * FROM customers WHERE first_name IS NULL

On MS SQL Server, the ISNULL() function returns the first argument if it's not NULL, otherwise it returns the second. You can effectively use this to make sure a query always yields a value instead of NULL, e.g.:

SELECT ISNULL(column1, 'No value found') FROM mytable WHERE column2 = 23

Other DBMSes have similar functionality available.

If you want to know whether a column can be null (i.e., is defined to be nullable), without querying for actual data, you should look into information_schema.

Stop setInterval call in JavaScript

Use setTimeOut to stop the interval after some time.

var interVal = setInterval(function(){console.log("Running")  }, 1000);
 setTimeout(function (argument) {
    clearInterval(interVal);
 },10000);

how to create a logfile in php?

create a logfile in php, to do it you need to pass data on function and it will create log file for you.

function wh_log($log_msg)
{
    $log_filename = "log";
    if (!file_exists($log_filename)) 
    {
        // create directory/folder uploads.
        mkdir($log_filename, 0777, true);
    }
    $log_file_data = $log_filename.'/log_' . date('d-M-Y') . '.log';
    // if you don't add `FILE_APPEND`, the file will be erased each time you add a log
    file_put_contents($log_file_data, $log_msg . "\n", FILE_APPEND);
} 
// call to function
wh_log("this is my log message");

Case insensitive 'Contains(string)'

OrdinalIgnoreCase, CurrentCultureIgnoreCase or InvariantCultureIgnoreCase?

Since this is missing, here are some recommendations about when to use which one:

Dos

  • Use StringComparison.OrdinalIgnoreCase for comparisons as your safe default for culture-agnostic string matching.
  • Use StringComparison.OrdinalIgnoreCase comparisons for increased speed.
  • Use StringComparison.CurrentCulture-based string operations when displaying the output to the user.
  • Switch current use of string operations based on the invariant culture to use the non-linguistic StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase when the comparison is
    linguistically irrelevant (symbolic, for example).
  • Use ToUpperInvariant rather than ToLowerInvariant when normalizing strings for comparison.

Don'ts

  • Use overloads for string operations that don't explicitly or implicitly specify the string comparison mechanism.
  • Use StringComparison.InvariantCulture -based string
    operations in most cases; one of the few exceptions would be
    persisting linguistically meaningful but culturally-agnostic data.

Based on these rules you should use:

string title = "STRING";
if (title.IndexOf("string", 0, StringComparison.[YourDecision]) != -1)
{
    // The string exists in the original
}

whereas [YourDecision] depends on the recommendations from above.

link of source: http://msdn.microsoft.com/en-us/library/ms973919.aspx

Connecting to remote URL which requires authentication using Java

Since Java 9, you can do this

URL url = new URL("http://www.example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setAuthenticator(new Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication ("USER", "PASS".toCharArray());
    }
});

What is default session timeout in ASP.NET?

It depends on either the configuration or programmatic change.
Therefore the most reliable way to check the current value is at runtime via code.

See the HttpSessionState.Timeout property; default value is 20 minutes.

You can access this propery in ASP.NET via HttpContext:

this.HttpContext.Session.Timeout // ASP.NET MVC controller
Page.Session.Timeout // ASP.NET Web Forms code-behind
HttpContext.Current.Session.Timeout // Elsewhere

Quick way to clear all selections on a multiselect enabled <select> with jQuery?

This is the best way to clear a multi-select or list box:

 $("#drp_assign_list option[value]").remove();

How do I pass variables and data from PHP to JavaScript?

Here is is the trick:

  1. Here is your 'PHP' to use that variable:

    <?php
        $name = 'PHP variable';
        echo '<script>';
        echo 'var name = ' . json_encode($name) . ';';
        echo '</script>';
    ?>
    
  2. Now you have a JavaScript variable called 'name', and here is your JavaScript code to use that variable:

    <script>
         console.log("I am everywhere " + name);
    </script>
    

How can I split a shell command over multiple lines when using an IF statement?

The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:

$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
   --forward-agent \
   --disable-known-hosts deploy:$target; then
     echo failed
else
     echo succeeded
fi

$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed

Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.

[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr option that you can set to make it carriage-return-tolerant.

Can I get JSON to load into an OrderedDict?

You could always write out the list of keys in addition to dumping the dict, and then reconstruct the OrderedDict by iterating through the list?

python pandas extract year from datetime: df['year'] = df['date'].year is not working

If you're running a recent-ish version of pandas then you can use the datetime attribute dt to access the datetime components:

In [6]:

df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].dt.year, df['date'].dt.month
df
Out[6]:
        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

EDIT

It looks like you're running an older version of pandas in which case the following would work:

In [18]:

df['date'] = pd.to_datetime(df['date'])
df['year'], df['month'] = df['date'].apply(lambda x: x.year), df['date'].apply(lambda x: x.month)
df
Out[18]:
        date  Count  year  month
0 2010-06-30    525  2010      6
1 2010-07-30    136  2010      7
2 2010-08-31    125  2010      8
3 2010-09-30     84  2010      9
4 2010-10-29   4469  2010     10

Regarding why it didn't parse this into a datetime in read_csv you need to pass the ordinal position of your column ([0]) because when True it tries to parse columns [1,2,3] see the docs

In [20]:

t="""date   Count
6/30/2010   525
7/30/2010   136
8/31/2010   125
9/30/2010   84
10/29/2010  4469"""
df = pd.read_csv(io.StringIO(t), sep='\s+', parse_dates=[0])
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 5 entries, 0 to 4
Data columns (total 2 columns):
date     5 non-null datetime64[ns]
Count    5 non-null int64
dtypes: datetime64[ns](1), int64(1)
memory usage: 120.0 bytes

So if you pass param parse_dates=[0] to read_csv there shouldn't be any need to call to_datetime on the 'date' column after loading.

Applying Comic Sans Ms font style

You need to use quote marks.

font-family: "Comic Sans MS", cursive, sans-serif;

Although you really really shouldn't use comic sans. The font has massive stigma attached to it's use; it's not seen as professional at all.

how to reference a YAML "setting" from elsewhere in the same YAML file?

With Yglu, you can write your example as:

paths:
  root: /path/to/root/
  patha: !? .paths.root + a
  pathb: !? .paths.root + b
  pathc: !? .paths.root + c

Disclaimer: I am the author of Yglu.

Mount current directory as a volume in Docker on Windows 10

  1. Open Settings on Docker Desktop (Docker for Windows).
  2. Select Shared Drives.
  3. Select the drive that you want to use inside your containers (e.g., C).
  4. Click Apply. You may be asked to provide user credentials. Enabling drives for containers on Windows

  5. The command below should now work on PowerShell (command prompt does not support ${PWD}):

    docker run --rm -v ${PWD}:/data alpine ls /data

IMPORTANT: if/when you change your Windows domain password, the mount will stop working silently, that is, -v will work but the container will not see your host folders and files. Solution: go back to Settings, uncheck the shared drives, Apply, check them again, Apply, and enter the new password when prompted.

composer laravel create project

There are two simple methods for creating laravel Project

Method 1

composer create-project --prefer-dist laravel/laravel <project-name>

Method 2

laravel new <project-name>

Method 2 might require you to run one extra command

composer global require laravel/installer

if you face 'laravel command not found' error

How do I create a folder in VB if it doesn't exist?

Under System.IO, there is a class called Directory. Do the following:

If Not Directory.Exists(path) Then
    Directory.CreateDirectory(path)
End If

It will ensure that the directory is there.

Where do I configure log4j in a JUnit test class?

You may want to look into to Simple Logging Facade for Java (SLF4J). It is a facade that wraps around Log4j that doesn't require an initial setup call like Log4j. It is also fairly easy to switch out Log4j for Slf4j as the API differences are minimal.

How to uninstall pip on OSX?

Aditionally to the answer from @srk, you should uninstall package setuptools:

python -m pip uninstall pip setuptools

If you want to uninstall all other packages first, this answer has some hints: https://stackoverflow.com/a/11250821/265954

Note: before you use the commands from that answer, please carefully read the comments about side effects and how to avoid uninstalling pip and setuptools too early. E.g. pip freeze | grep -v "^-e" | grep -v "^(setuptools|pip)" | xargs pip uninstall -y

How to change value of process.env.PORT in node.js?

use the below command to set the port number in node process while running node JS programme:

set PORT =3000 && node file_name.js

The set port can be accessed in the code as

process.env.PORT 

jQuery change input text value

When set the new value of element, you need call trigger change.

$('element').val(newValue).trigger('change');

How to remove hashbang from url?

For Vue 3, change this :

const router = createRouter({
    history: createWebHashHistory(),
    routes,
});

To this :

const router = createRouter({
    history: createWebHistory(),
    routes,
});

Source : https://next.router.vuejs.org/guide/essentials/history-mode.html#hash-mode

how to change text in Android TextView

:) Your using the thread in a wrong way. Just do the following:

private void runthread()
{

splashTread = new Thread() {
            @Override
            public void run() {
                try {
                    synchronized(this){

                        //wait 5 sec
                        wait(_splashTime);
                    }

                } catch(InterruptedException e) {}
                finally {
                    //call the handler to set the text
                }
            }
        };

        splashTread.start(); 
}

That's it.

How to display a loading screen while site content loads

Typically sites that do this by loading content via ajax and listening to the readystatechanged event to update the DOM with a loading GIF or the content.

How are you currently loading your content?

The code would be similar to this:

function load(url) {
    // display loading image here...
    document.getElementById('loadingImg').visible = true;
    // request your data...
    var req = new XMLHttpRequest();
    req.open("POST", url, true);

    req.onreadystatechange = function () {
        if (req.readyState == 4 && req.status == 200) {
            // content is loaded...hide the gif and display the content...
            if (req.responseText) {
                document.getElementById('content').innerHTML = req.responseText;
                document.getElementById('loadingImg').visible = false;
            }
        }
    };
    request.send(vars);
}

There are plenty of 3rd party javascript libraries that may make your life easier, but the above is really all you need.

What parameters should I use in a Google Maps URL to go to a lat-lon?

This works to zoom into an area more then drop a pin: https://www.google.com/maps/@30.2,17.9820525,9z

And the params are:

@lat,lng,zoom

Which concurrent Queue implementation should I use in Java?

ConcurrentLinkedQueue is lock-free, LinkedBlockingQueue is not. Every time you invoke LinkedBlockingQueue.put() or LinkedBlockingQueue.take(), you need acquire the lock first. In other word, LinkedBlockingQueue has poor concurrency. If you care performance, try ConcurrentLinkedQueue + LockSupport.

App.Config Transformation for projects which are not Web Projects in Visual Studio?

I tried several solutions and here is the simplest I personally found.
Dan pointed out in the comments that the original post belongs to Oleg Sychthanks, Oleg!

Here are the instructions:

1. Add an XML file for each configuration to the project.

Typically you will have Debug and Release configurations so name your files App.Debug.config and App.Release.config. In my project, I created a configuration for each kind of environment, so you might want to experiment with that.

2. Unload project and open .csproj file for editing

Visual Studio allows you to edit .csproj files right in the editor—you just need to unload the project first. Then right-click on it and select Edit <ProjectName>.csproj.

3. Bind App.*.config files to main App.config

Find the project file section that contains all App.config and App.*.config references. You'll notice their build actions are set to None:

<None Include="App.config" />
<None Include="App.Debug.config" />
<None Include="App.Release.config" />

First, set build action for all of them to Content.
Next, make all configuration-specific files dependant on the main App.config so Visual Studio groups them like it does designer and code-behind files.

Replace XML above with the one below:

<Content Include="App.config" />
<Content Include="App.Debug.config" >
  <DependentUpon>App.config</DependentUpon>
</Content>
<Content Include="App.Release.config" >
  <DependentUpon>App.config</DependentUpon>
</Content>

4. Activate transformations magic (only necessary for Visual Studio versions pre VS2017)

In the end of file after

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

and before final

</Project>

insert the following XML:

  <UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v$(VisualStudioVersion)\Web\Microsoft.Web.Publishing.Tasks.dll" />
  <Target Name="CoreCompile" Condition="exists('app.$(Configuration).config')">
    <!-- Generate transformed app config in the intermediate directory -->
    <TransformXml Source="app.config" Destination="$(IntermediateOutputPath)$(TargetFileName).config" Transform="app.$(Configuration).config" />
    <!-- Force build process to use the transformed configuration file from now on. -->
    <ItemGroup>
      <AppConfigWithTargetPath Remove="app.config" />
      <AppConfigWithTargetPath Include="$(IntermediateOutputPath)$(TargetFileName).config">
        <TargetPath>$(TargetFileName).config</TargetPath>
      </AppConfigWithTargetPath>
    </ItemGroup>
  </Target>

Now you can reload the project, build it and enjoy App.config transformations!

FYI

Make sure that your App.*.config files have the right setup like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
     <!--magic transformations here-->
</configuration>

How do you calculate log base 2 in Java for integers?

If you are thinking about using floating-point to help with integer arithmetics, you have to be careful.

I usually try to avoid FP calculations whenever possible.

Floating-point operations are not exact. You can never know for sure what will (int)(Math.log(65536)/Math.log(2)) evaluate to. For example, Math.ceil(Math.log(1<<29) / Math.log(2)) is 30 on my PC where mathematically it should be exactly 29. I didn't find a value for x where (int)(Math.log(x)/Math.log(2)) fails (just because there are only 32 "dangerous" values), but it does not mean that it will work the same way on any PC.

The usual trick here is using "epsilon" when rounding. Like (int)(Math.log(x)/Math.log(2)+1e-10) should never fail. The choice of this "epsilon" is not a trivial task.

More demonstration, using a more general task - trying to implement int log(int x, int base):

The testing code:

static int pow(int base, int power) {
    int result = 1;
    for (int i = 0; i < power; i++)
        result *= base;
    return result;
}

private static void test(int base, int pow) {
    int x = pow(base, pow);
    if (pow != log(x, base))
        System.out.println(String.format("error at %d^%d", base, pow));
    if(pow!=0 && (pow-1) != log(x-1, base))
        System.out.println(String.format("error at %d^%d-1", base, pow));
}

public static void main(String[] args) {
    for (int base = 2; base < 500; base++) {
        int maxPow = (int) (Math.log(Integer.MAX_VALUE) / Math.log(base));
        for (int pow = 0; pow <= maxPow; pow++) {
            test(base, pow);
        }
    }
}

If we use the most straight-forward implementation of logarithm,

static int log(int x, int base)
{
    return (int) (Math.log(x) / Math.log(base));
}

this prints:

error at 3^5
error at 3^10
error at 3^13
error at 3^15
error at 3^17
error at 9^5
error at 10^3
error at 10^6
error at 10^9
error at 11^7
error at 12^7
...

To completely get rid of errors I had to add epsilon which is between 1e-11 and 1e-14. Could you have told this before testing? I definitely could not.

How many bytes does one Unicode character take?

Strangely enough, nobody pointed out how to calculate how many bytes is taking one Unicode char. Here is the rule for UTF-8 encoded strings:

Binary    Hex          Comments
0xxxxxxx  0x00..0x7F   Only byte of a 1-byte character encoding
10xxxxxx  0x80..0xBF   Continuation byte: one of 1-3 bytes following the first
110xxxxx  0xC0..0xDF   First byte of a 2-byte character encoding
1110xxxx  0xE0..0xEF   First byte of a 3-byte character encoding
11110xxx  0xF0..0xF7   First byte of a 4-byte character encoding

So the quick answer is: it takes 1 to 4 bytes, depending on the first one which will indicate how many bytes it'll take up.

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81

Your Chrome Driver version needs to match your Chrome Browser version

  1. Get you Chrome Browser version, by typing chrome://version

enter image description here

  1. Download Chrome Driver version that matches you Chrome Browser version, form this website https://chromedriver.chromium.org/downloads

How do I center this form in css?

Another solution (without a wrapper) would be to set the form to display: table, which would make it act like a table so it would have the width of its largest child, and then apply margin: 0 auto to center it.

form {
    display: table;
    margin: 0 auto;
}

Credit goes to: https://stackoverflow.com/a/49378738/7841955

#define in Java

There is preprocessor for Java which provides directives like #define, #ifdef, #ifndef and many others, for instance PostgresJDBC team uses it to generate sources for different cases and to not duplicate code.

Java FileReader encoding issue

Since Java 11 you may use that:

public FileReader(String fileName, Charset charset) throws IOException;

Visual Studio: How to break on handled exceptions?

A technique I use is something like the following. Define a global variable that you can use for one or multiple try catch blocks depending on what you're trying to debug and use the following structure:

if(!GlobalTestingBool)
{
   try
   {
      SomeErrorProneMethod();
   }
   catch (...)
   {
      // ... Error handling ...
   }
}
else
{
   SomeErrorProneMethod();
}

I find this gives me a bit more flexibility in terms of testing because there are still some exceptions I don't want the IDE to break on.

What's the C# equivalent to the With statement in VB?

Not really, you have to assign a variable. So

    var bar = Stuff.Elements.Foo;
    bar.Name = "Bob Dylan";
    bar.Age = 68;
    bar.Location = "On Tour";
    bar.IsCool = True;

Or in C# 3.0:

    var bar = Stuff.Elements.Foo
    {
        Name = "Bob Dylan",
        Age = 68,
        Location = "On Tour",
        IsCool = True
    };

How do you get the magnitude of a vector in Numpy?

use the function norm in scipy.linalg (or numpy.linalg)

>>> from scipy import linalg as LA
>>> a = 10*NP.random.randn(6)
>>> a
  array([  9.62141594,   1.29279592,   4.80091404,  -2.93714318,
          17.06608678, -11.34617065])
>>> LA.norm(a)
    23.36461979210312

>>> # compare with OP's function:
>>> import math
>>> mag = lambda x : math.sqrt(sum(i**2 for i in x))
>>> mag(a)
     23.36461979210312

How to determine the screen width in terms of dp or dip at runtime in Android?

You are missing default density value of 160.

    2 px = 3 dip if dpi == 80(ldpi), 320x240 screen
    1 px = 1 dip if dpi == 160(mdpi), 480x320 screen
    3 px = 2 dip if dpi == 240(hdpi), 840x480 screen

In other words, if you design you layout with width equal to 160dip in portrait mode, it will be half of the screen on all ldpi/mdpi/hdpi devices(except tablets, I think)

How do I set a background-color for the width of text, not the width of the entire element, using CSS?

You can use the HTML5 <mark> tag.

HTML:

<h1><mark>The Last Will and Testament of Eric Jones</mark></h1>

CSS:

mark
{
    background-color: green;
}

How to scroll to bottom in react?

As another option it is worth looking at react scroll component.

What does -1 mean in numpy reshape?

Long story short: you set some dimensions and let NumPy set the remaining(s).

(userDim1, userDim2, ..., -1) -->>

(userDim1, userDim1, ..., TOTAL_DIMENSION - (userDim1 + userDim2 + ...))

Get bitcoin historical data

I have written a java example for this case:

Use json.org library to retrieve JSONObjects and JSONArrays. The example below uses blockchain.info's data which can be obtained as JSONObject.

    public class main 
    {
        public static void main(String[] args) throws MalformedURLException, IOException
        {
            JSONObject data = getJSONfromURL("https://blockchain.info/charts/market-price?format=json");
            JSONArray data_array = data.getJSONArray("values");

            for (int i = 0; i < data_array.length(); i++)
            {
                JSONObject price_point = data_array.getJSONObject(i);

                //  Unix time
                int x = price_point.getInt("x");

                //  Bitcoin price at that time
                double y = price_point.getDouble("y");

                //  Do something with x and y.
            }

        }

        public static JSONObject getJSONfromURL(String URL)
        {
            try
            {
                URLConnection uc;
                URL url = new URL(URL);
                uc = url.openConnection();
                uc.setConnectTimeout(10000);
                uc.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
                uc.connect();

                BufferedReader rd = new BufferedReader(
                        new InputStreamReader(uc.getInputStream(), 
                        Charset.forName("UTF-8")));

                StringBuilder sb = new StringBuilder();
                int cp;
                while ((cp = rd.read()) != -1)
                {
                    sb.append((char)cp);
                }

                String jsonText = (sb.toString());            

                return new JSONObject(jsonText.toString());
            } catch (IOException ex)
            {
                return null;
            }
        }
    }

Matrix multiplication using arrays

Try this,

public static Double[][] multiplicar(Double A[][],Double B[][]){
    Double[][] C= new Double[2][2];
    int i,j,k;
     for (i = 0; i < 2; i++) {
         for (j = 0; j < 2; j++) {
             C[i][j] = 0.00000;
         }
     }
    for(i=0;i<2;i++){
        for(j=0;j<2;j++){
            for (k=0;k<2;k++){
                  C[i][j]+=(A[i][k]*B[k][j]);

            }

        }
    }
    return C;
}

data.table vs dplyr: can one do something well the other can't or does poorly?

Reading Hadley and Arun's answers one gets the impression that those who prefer dplyr's syntax would have in some cases to switch over to data.table or compromise for long running times.

But as some have already mentioned, dplyr can use data.table as a backend. This is accomplished using the dtplyr package which recently had it's version 1.0.0 release. Learning dtplyr incurs practically zero additional effort.

When using dtplyr one uses the function lazy_dt() to declare a lazy data.table, after which standard dplyr syntax is used to specify operations on it. This would look something like the following:

new_table <- mtcars2 %>% 
  lazy_dt() %>%
  filter(wt < 5) %>% 
  mutate(l100k = 235.21 / mpg) %>% # liters / 100 km
  group_by(cyl) %>% 
  summarise(l100k = mean(l100k))

  new_table

#> Source: local data table [?? x 2]
#> Call:   `_DT1`[wt < 5][, `:=`(l100k = 235.21/mpg)][, .(l100k = mean(l100k)), 
#>     keyby = .(cyl)]
#> 
#>     cyl l100k
#>   <dbl> <dbl>
#> 1     4  9.05
#> 2     6 12.0 
#> 3     8 14.9 
#> 
#> # Use as.data.table()/as.data.frame()/as_tibble() to access results

The new_table object is not evaluated until calling on it as.data.table()/as.data.frame()/as_tibble() at which point the underlying data.table operation is executed.

I've recreated a benchmark analysis done by data.table author Matt Dowle back at December 2018 which covers the case of operations over large numbers of groups. I've found that dtplyr indeed enables for the most part those who prefer the dplyr syntax to keep using it while enjoying the speed offered by data.table.

regex error - nothing to repeat

That is a Python bug between "*" and special characters.

Instead of

re.compile(r"\w*")

Try:

re.compile(r"[a-zA-Z0-9]*")

It works, however does not make the same regular expression.

This bug seems to have been fixed between 2.7.5 and 2.7.6.

I want to execute shell commands from Maven's pom.xml

Thanks! Tomer Ben David. it helped me. as I am doing pip install in demo folder as you mentioned npm install

<groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.3.2</version>
            <executions>
              <execution>
                <goals>
                  <goal>exec</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <executable>pip</executable>
              <arguments><argument>install</argument></arguments>                            
             <workingDirectory>${project.build.directory}/Demo</workingDirectory>
            </configuration>

How to change the color of winform DataGridview header?

dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;

How to define relative paths in Visual Studio Project?

Instead of using relative paths, you could also use the predefined macros of VS to achieve this.

$(ProjectDir) points to the directory of your .vcproj file, $(SolutionDir) is the directory of the .sln file.

You get a list of available macros when opening a project, go to
Properties → Configuration Properties → C/C++ → General
and hit the three dots:

project properties

In the upcoming dialog, hit Macros to see the macros that are predefined by the Studio (consult MSDN for their meaning):

additional include directories

You can use the Macros by typing $(MACRO_NAME) (note the $ and the round brackets).

How do I hide an element on a click event anywhere outside of the element?

$( "element" ).focusout(function() {
    //your code on element
})

Match groups in Python

Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), we can now capture the condition value re.search(pattern, statement) in a variable (let's all it match) in order to both check if it's not None and then re-use it within the body of the condition:

if match := re.search('I love (\w+)', statement):
  print(f'He loves {match.group(1)}')
elif match := re.search("Ich liebe (\w+)", statement):
  print(f'Er liebt {match.group(1)}')
elif match := re.search("Je t'aime (\w+)", statement):
  print(f'Il aime {match.group(1)}')

What is the difference between dynamic and static polymorphism in Java?

Following on from Naresh's answer, dynamic polymorphism is only 'dynamic' in Java because of the presence of the virtual machine and its ability to interpret the code at run time rather than the code running natively.

In C++ it must be resolved at compile time if it is being compiled to a native binary using gcc, obviously; however, the runtime jump and thunk in the virtual table is still referred to as a 'lookup' or 'dynamic'. If C inherits B, and you declare B* b = new C(); b->method1();, b will be resolved by the compiler to point to a B object inside C (for a simple class inherits a class situation, the B object inside C and C will start at the same memory address so nothing is required to be done; it will be pointing at the vptr that they both use). If C inherits B and A, the virtual function table of the A object inside C entry for method1 will have a thunk which will offset the pointer to the start of the encapsulating C object and then pass it to the real A::method1() in the text segment which C has overridden. For C* c = new C(); c->method1(), c will be pointing to the outer C object already and the pointer will be passed to C::method1() in the text segment. Refer to: http://www.programmersought.com/article/2572545946/

In java, for B b = new C(); b.method1();, the virtual machine is able to dynamically check the type of the object paired with b and can pass the correct pointer and call the correct method. The extra step of the virtual machine eliminates the need for virtual function tables or the type being resolved at compile time, even when it could be known at compile time. It's just a different way of doing it which makes sense when a virtual machine is involved and code is only compiled to bytecode.

sorting dictionary python 3

A modern and fast solution, for Python 3.7. May also work in some interpreters of Python 3.6.

TLDR

To sort a dictionary by keys use:

sorted_dict = {k: disordered[k] for k in sorted(disordered)}

Almost three times faster than the accepted answer; probably more when you include imports.

Comment on the accepted answer

The example in the accepted answer instead of iterating over the keys only - with key parameter of sorted() or the default behaviour of dict iteration - iterates over tuples (key, value), which suprisingly turns out to be much slower than comparing the keys only and accessing dictionary elements in a list comprehension.

How to sort by key in Python 3.7

The big change in Python 3.7 is that the dictionaries are now ordered by default.

  • You can generate sorted dict using dict comprehensions.
  • Using OrderedDict might still be preferable for the compatibility sake.
  • Do not use sorted(d.items()) without key.

See:

disordered = {10: 'b', 3: 'a', 5: 'c'}

# sort keys, then get values from original - fast
sorted_dict = {k: disordered[k] for k in sorted(disordered)}

# key = itemgetter - slower
from operator import itemgetter
key = itemgetter(0)
sorted_dict = {k: v for k, v in sorted(disordered.items(), key=key)}

# key = lambda - the slowest
key = lambda item: item[0]
sorted_dict = {k: v for k in sorted(disordered.items(), key=key)} 

Timing results:

Best for {k: d[k] for k in sorted(d)}: 7.507327548999456
Best for {k: v for k, v in sorted(d.items(), key=key_getter)}: 12.031082626002899
Best for {k: v for k, v in sorted(d.items(), key=key_lambda)}: 14.22885995300021

Best for dict(sorted(d.items(), key=key_getter)): 11.209122000000207
Best for dict(sorted(d.items(), key=key_lambda)): 13.289728325995384
Best for dict(sorted(d.items())): 14.231471302999125

Best for OrderedDict(sorted(d.items(), key=key_getter)): 16.609151654003654
Best for OrderedDict(sorted(d.items(), key=key_lambda)): 18.52622927199991
Best for OrderedDict(sorted(d.items())): 19.436101284998585

Testing code:

from timeit import repeat

setup_code = """
from operator import itemgetter
from collections import OrderedDict
import random
random.seed(0)
d = {i: chr(i) for i in [random.randint(0, 120) for repeat in range(120)]}
key_getter = itemgetter(0)
key_lambda = lambda item: item[0]
"""

cases = [
    # fast
    '{k: d[k] for k in sorted(d)}',
    '{k: v for k, v in sorted(d.items(), key=key_getter)}',
    '{k: v for k, v in sorted(d.items(), key=key_lambda)}',
    # slower
    'dict(sorted(d.items(), key=key_getter))',
    'dict(sorted(d.items(), key=key_lambda))',
    'dict(sorted(d.items()))',
    # the slowest 
    'OrderedDict(sorted(d.items(), key=key_getter))',
    'OrderedDict(sorted(d.items(), key=key_lambda))',
    'OrderedDict(sorted(d.items()))',
]

for code in cases:
    times = repeat(code, setup=setup_code, repeat=3)
    print(f"Best for {code}: {min(times)}")

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

You can have an auto-Incrementing column that is not the PRIMARY KEY, as long as there is an index (key) on it:

CREATE TABLE members ( 
  id int(11)  UNSIGNED NOT NULL AUTO_INCREMENT,
  memberid VARCHAR( 30 ) NOT NULL , 
  `time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP , 
  firstname VARCHAR( 50 ) NULL , 
  lastname VARCHAR( 50 ) NULL , 
  PRIMARY KEY (memberid) ,
  KEY (id)                          --- or:    UNIQUE KEY (id)
) ENGINE = MYISAM; 

How can I change the default Django date template format?

Just use this:

{{you_date_field|date:'Y-m-d'}}

This will show something like 2016-10-16. You can use the format as you want.

Can I define a class name on paragraph using Markdown?

Raw HTML is actually perfectly valid in markdown. For instance:

Normal *markdown* paragraph.

<p class="myclass">This paragraph has a class "myclass"</p>

Just make sure the HTML is not inside a code block.

Extract digits from a string in Java

Here's a more verbose solution. Less elegant, but probably faster:

public static String stripNonDigits(
            final CharSequence input /* inspired by seh's comment */){
    final StringBuilder sb = new StringBuilder(
            input.length() /* also inspired by seh's comment */);
    for(int i = 0; i < input.length(); i++){
        final char c = input.charAt(i);
        if(c > 47 && c < 58){
            sb.append(c);
        }
    }
    return sb.toString();
}

Test Code:

public static void main(final String[] args){
    final String input = "0-123-abc-456-xyz-789";
    final String result = stripNonDigits(input);
    System.out.println(result);
}

Output:

0123456789

BTW: I did not use Character.isDigit(ch) because it accepts many other chars except 0 - 9.

How to call a method defined in an AngularJS directive?

Although it might be tempting to expose an object on the isolated scope of a directive to facilitate communicating with it, doing can lead to confusing "spaghetti" code, especially if you need to chain this communication through a couple levels (controller, to directive, to nested directive, etc.)

We originally went down this path but after some more research found that it made more sense and resulted in both more maintainable and readable code to expose events and properties that a directive will use for communication via a service then using $watch on that service's properties in the directive or any other controls that would need to react to those changes for communication.

This abstraction works very nicely with AngularJS's dependency injection framework as you can inject the service into any items that need to react to those events. If you look at the Angular.js file, you'll see that the directives in there also use services and $watch in this manner, they don't expose events over the isolated scope.

Lastly, in the case that you need to communicate between directives that are dependent on one another, I would recommend sharing a controller between those directives as the means of communication.

AngularJS's Wiki for Best Practices also mentions this:

Only use .$broadcast(), .$emit() and .$on() for atomic events Events that are relevant globally across the entire app (such as a user authenticating or the app closing). If you want events specific to modules, services or widgets you should consider Services, Directive Controllers, or 3rd Party Libs

  • $scope.$watch() should replace the need for events
  • Injecting services and calling methods directly is also useful for direct communication
  • Directives are able to directly communicate with each other through directive-controllers

Javascript to open popup window and disable parent window

The key term is modal-dialog.

As such there is no built in modal-dialog offered.

But you can use many others available e.g. this

Error "File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it"

I received this error while trying to run Google's Firebase analytics sample app:

Prerequisites:

Add Procedure:

  1. Go to https://firebase.google.com/
  2. Click on "GO TO CONSOLE"
  3. Click on "Add Project"
  4. Project name: Enter: sample-app
  5. Click "Create Project" [Takes about 10 seconds or so...]
  6. Click "Continue"
  7. On the "Getting Started" page, click "Add Firebase to your Android app"
  8. Enter package name for the android app [The full package name appears at the top of the manifest: "com.google.firebase.quickstart.analytics"]
  9. Click on download google-services.json
  10. In file explorer, add google-services.json to the directory: "quickstart/analytics/app" [Warning: Do not rename the file, it must be: google-services.json]
  11. Run 'app'
    • The sample app already contains the necessary Gradle file settings.
    • When adding a new project do: Tools -> Firebase -> Analytics -> Add Event -> Connect App to Firebase.
    • Adding a project via Android Studio ensures that all the Gradle Dependecies are setup.

Remove Procedure:

  1. Go to https://firebase.google.com/
  2. Click on "GO TO CONSOLE"
  3. Settings -> Project Settings -> Delete this App
  4. Settings -> Project Settings -> Delete Project
  5. Enter project ID and press delete

I added and removed the sample app multiple times without any noticeable side effects.

Can I get the name of the currently running function in JavaScript?

Another use case could be an event dispatcher bound at runtime:

MyClass = function () {
  this.events = {};

  // Fire up an event (most probably from inside an instance method)
  this.OnFirstRun();

  // Fire up other event (most probably from inside an instance method)
  this.OnLastRun();

}

MyClass.prototype.dispatchEvents = function () {
  var EventStack=this.events[GetFunctionName()], i=EventStack.length-1;

  do EventStack[i]();
  while (i--);
}

MyClass.prototype.setEvent = function (event, callback) {
  this.events[event] = [];
  this.events[event].push(callback);
  this["On"+event] = this.dispatchEvents;
}

MyObject = new MyClass();
MyObject.setEvent ("FirstRun", somecallback);
MyObject.setEvent ("FirstRun", someothercallback);
MyObject.setEvent ("LastRun", yetanothercallback);

The advantage here is the dispatcher can be easily reused and doesn't have to receive the dispatch queue as an argument, instead it comes implicit with the invocation name...

In the end, the general case presented here would be "using the function name as an argument so you don't have to pass it explicitly", and that could be useful in many cases, such as the jquery animate() optional callback, or in timeouts/intervals callbacks, (ie you only pass a funcion NAME).

How do I make a placeholder for a 'select' box?

I just added a hidden attribute in an option like below. It is working fine for me.

_x000D_
_x000D_
<select>_x000D_
  <option hidden>Sex</option>_x000D_
  <option>Male</option>_x000D_
  <option>Female</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to increase font size in the Xcode editor?

I used cmd+ and it worked well to increase.. Same for decreasing cmq-