Programs & Examples On #Tcpserver

A tcp server uses raw tcp sockets to communicate with its client (usually without using a higher level protocol such as HTTP or IMAP).

python socket.error: [Errno 98] Address already in use

There is obviously another process listening on the port. You might find out that process by using the following command:

$ lsof -i :8000

or change your tornado app's port. tornado's error info not Explicitly on this.

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

The value you have passed as the file descriptor is not valid. It is either negative or does not represent a currently open file or socket.

So you have either closed the socket before calling write() or you have corrupted the value of 'sockfd' somewhere in your code.

It would be useful to trace all calls to close(), and the value of 'sockfd' prior to the write() calls.

Your technique of only printing error messages in debug mode seems to me complete madness, and in any case calling another function between a system call and perror() is invalid, as it may disturb the value of errno. Indeed it may have done so in this case, and the real underlying error may be different.

java.net.ConnectException: Connection refused

It could be that there is a previous instance of the client still running and listening on port 5000.

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

Rails server says port already used, how to kill that process?

Assuming you're looking to kill whatever is on port 3000 (which is what webrick normally uses), type this in your terminal to find out the PID of the process:

$ lsof -wni tcp:3000

Then, use the number in the PID column to kill the process:

$ kill -9 PID

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

I just encountered the same issue, my system is Win7. just use the command on terminal like: netstat -na|findstr port, you will see the port has been used. So if you want to start the server without this message, you can change other port that not been used.

Simple Java Client/Server Program

import java.io.*;
import java.net.*;
class serversvi1
{
  public static void main(String svi[]) throws IOException
  {
    try
    {
      ServerSocket servsock=new ServerSocket(5510);
      DataInputStream dis=new DataInputStream(System.in);

      System.out.println("enter the file name");

      String fil=dis.readLine();
      System.out.println(fil+" :is file transfer");

      File myfile=new File(fil);
      while(true)
      {
        Socket sock=servsock.accept();
        byte[] mybytearray=new byte[(int)myfile.length()];

        BufferedInputStream bis=new BufferedInputStream(new FileInputStream(myfile));

        bis.read(mybytearray,0,mybytearray.length);

        OutputStream os=sock.getOutputStream();
        os.write(mybytearray,0,mybytearray.length);
        os.flush();

        sock.close();
      }
    }
    catch(Exception saranvi)
    {
      System.out.print(saranvi);
    }
  }
}


import java.io.*;
import java.net.*;

class clientsvi1
{
  public static void main(String svi[])throws IOException
  {
    try
    {
      Socket sock=new Socket("localhost",5510);
      byte[] bytearray=new byte[1024];

      InputStream is=sock.getInputStream();
      DataInputStream dis=new DataInputStream(System.in);
      System.out.println("enter the file name");

      String fil=dis.readLine();
      FileOutputStream fos=new FileOutputStream(fil);
      BufferedOutputStream bos=new  BufferedOutputStream(fos);
      int bytesread=is.read(bytearray,0,bytearray.length);
      bos.write(bytearray,0,bytesread);
      System.out.println("out.txt file is received");
      bos.close();
      sock.close();
    }
    catch(Exception SVI)
    {
      System.out.print(SVI);
    }
  }
}

Python socket receive - incoming packets always have a different size

The answer by Larry Hastings has some great general advice about sockets, but there are a couple of mistakes as it pertains to how the recv(bufsize) method works in the Python socket module.

So, to clarify, since this may be confusing to others looking to this for help:

  1. The bufsize param for the recv(bufsize) method is not optional. You'll get an error if you call recv() (without the param).
  2. The bufferlen in recv(bufsize) is a maximum size. The recv will happily return fewer bytes if there are fewer available.

See the documentation for details.

Now, if you're receiving data from a client and want to know when you've received all of the data, you're probably going to have to add it to your protocol -- as Larry suggests. See this recipe for strategies for determining end of message.

As that recipe points out, for some protocols, the client will simply disconnect when it's done sending data. In those cases, your while True loop should work fine. If the client does not disconnect, you'll need to figure out some way to signal your content length, delimit your messages, or implement a timeout.

I'd be happy to try to help further if you could post your exact client code and a description of your test protocol.

Event handlers for Twitter Bootstrap dropdowns?

Try this:

$('div.btn-group ul.dropdown-menu li a').click(function (e) {
    var $div = $(this).parent().parent().parent(); 
    var $btn = $div.find('button');
    $btn.html($(this).text() + ' <span class="caret"></span>');
    $div.removeClass('open');
    e.preventDefault();
    return false;
});

Redirect in Spring MVC

i know this is late , but you should try redirecting to a path and not to a file ha ha

What does "restore purchases" in In-App purchases mean?

Is it as optional functionality.

If you won't provide it when user will try to purchase non-consumable product AppStore will restore old transaction. But your app will think that this is new transaction.

If you will provide restore mechanism then your purchase manager will see restored transaction.

If app should distinguish this options then you should provide functionality for restoring previously purchased products.

How to get the host name of the current machine as defined in the Ansible hosts file?

The necessary variable is inventory_hostname.

- name: Install this only for local dev machine
  pip: name=pyramid
  when: inventory_hostname == "local"

It is somewhat hidden in the documentation at the bottom of this section.

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

If you happen to be an iOS developer:

Check how many simulators that you have downloaded as they take up a lot of space:

Go to: ~/Library/Developer/Xcode/iOS DeviceSupport

Also delete old archived apps:

Go to: ~/Library/Developer/Xcode/Archives

I cleared 100GB doing this.

How to use moment.js library in angular 2 typescript app?

The following worked for me.

First, install the type definitions for moment.

typings install moment --save

(Note: NOT --ambient)

Then, to work around the lack of a proper export:

import * as moment from 'moment';

What is the easiest way to encrypt a password when I save it to the registry?

If it's a password used for authentication by your application, then hash the password as others suggest.

If you're storing passwords for an external resource, you'll often want to be able to prompt the user for these credentials and give him the opportunity to save them securely. Windows provides the Credentials UI (CredUI) for this purpose - there are a number of samples showing how to use this in .NET, including this one on MSDN.

org.hibernate.MappingException: Unknown entity

use below line of code in the case of spring boot applications.

@EntityScan(basePackageClasses=YourClassName.class)

How to quickly edit values in table in SQL Server Management Studio?

Go to Tools > Options. In the tree on the left, select SQL Server Object Explorer. Set the option "Value for Edit Top Rows command" to 0. It'll now allow you to view and edit the entire table from the context menu.

How to .gitignore all files/folder in a folder, but not the folder itself?

You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.

For example, add an empty file called .gitkeep to the folder you want to keep, then in your .gitignore file write:

# exclude everything
somefolder/*

# exception to the rule
!somefolder/.gitkeep 

Commit your .gitignore and .gitkeep files and this should resolve your issue.

How to use GNU Make on Windows?

As an alternative, if you just want to install make, you can use the chocolatey package manager to install gnu make by using

choco install make -y

This deals with any path issues that you might have.

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

in simple manner we all know, we can inherit(extends) one class but we can implements so many interfaces.. that is because in interfaces we don't give an implementation just say the functionality. suppose if java can extends so many classes and those have same methods.. in this point if we try to invoke super class method in the sub class what method suppose to run??, compiler get confused example:- try to multiple extends but in interfaces those methods don't have bodies we should implement those in sub class.. try to multiple implements so no worries..

Reverse a string in Python

This is also an interesting way:

def reverse_words_1(s):
    rev = ''
    for i in range(len(s)):
        j = ~i  # equivalent to j = -(i + 1)
        rev += s[j]
    return rev

or similar:

def reverse_words_2(s):
    rev = ''
    for i in reversed(range(len(s)):
        rev += s[i]
    return rev

Another more 'exotic' way using byterarray which supports .reverse()

b = bytearray('Reverse this!', 'UTF-8')
b.reverse()
b.decode('UTF-8')

will produce:

'!siht esreveR'

How to restrict user to type 10 digit numbers in input element?

Use maxlength

<input type="text" maxlength="10" />

Compare two MySQL databases

dbSolo, it is paid but this feature might be the one you are looking for http://www.dbsolo.com/help/compare.html

It works with Oracle, Microsoft SQL Server, Sybase, DB2, Solid, PostgreSQL, H2 and MySQL alt text

String Resource new line /n not possible?

When using the translations editor in Android Studio just click the icon to the right (or use Shift-Enter on Windows, Alt/Option-Enter on MacOS) and then add line breaks using return.

This will insert \n correctly in the localized strings.xml.

Drop data frame columns by name

within(df, rm(x))

is probably easiest, or for multiple variables:

within(df, rm(x, y))

Or if you're dealing with data.tables (per How do you delete a column by name in data.table?):

dt[, x := NULL]   # Deletes column x by reference instantly.

dt[, !"x"]   # Selects all but x into a new data.table.

or for multiple variables

dt[, c("x","y") := NULL]

dt[, !c("x", "y")]

I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array

  1. What exactly doesn't work?
  2. Why are you using a 2d array?
  3. If you must use a 2d array:

    int numOfPairs = 10;  String[][] array = new String[numOfPairs][2]; for(int i = 0; i < array.length; i++){     for(int j = 0; j < array[i].length; j++){         array[i] = new String[2];         array[i][0] = "original word";         array[i][1] = "rearranged word";     }    } 

Does this give you a hint?

What is the proper way to re-throw an exception in C#?

I know this is an old question, but I'm going to answer it because I have to disagree with all the answers here.

Now, I'll agree that most of the time you either want to do a plain throw, to preserve as much information as possible about what went wrong, or you want to throw a new exception that may contain that as an inner-exception, or not, depending on how likely you are to want to know about the inner events that caused it.

There is an exception though. There are several cases where a method will call into another method and a condition that causes an exception in the inner call should be considered the same exception on the outer call.

One example is a specialised collection implemented by using another collection. Let's say it's a DistinctList<T> that wraps a List<T> but refuses duplicate items.

If someone called ICollection<T>.CopyTo on your collection class, it might just be a straight call to CopyTo on the inner collection (if say, all the custom logic only applied to adding to the collection, or setting it up). Now, the conditions in which that call would throw are exactly the same conditions in which your collection should throw to match the documentation of ICollection<T>.CopyTo.

Now, you could just not catch the execption at all, and let it pass through. Here though the user gets an exception from List<T> when they were calling something on a DistinctList<T>. Not the end of the world, but you may want to hide those implementation details.

Or you could do your own checking:

public CopyTo(T[] array, int arrayIndex)
{
  if(array == null)
    throw new ArgumentNullException("array");
  if(arrayIndex < 0)
    throw new ArgumentOutOfRangeException("arrayIndex", "Array Index must be zero or greater.");
  if(Count > array.Length + arrayIndex)
    throw new ArgumentException("Not enough room in array to copy elements starting at index given.");
  _innerList.CopyTo(array, arrayIndex);
}

That's not the worse code because it's boilerplate and we can probably just copy it from some other implementation of CopyTo where it wasn't a simple pass-through and we had to implement it ourselves. Still, it's needlessly repeating the exact same checks that are going to be done in _innerList.CopyTo(array, arrayIndex), so the only thing it has added to our code is 6 lines where there could be a bug.

We could check and wrap:

public CopyTo(T[] array, int arrayIndex)
{
  try
  {
    _innerList.CopyTo(array, arrayIndex);
  }
  catch(ArgumentNullException ane)
  {
    throw new ArgumentNullException("array", ane);
  }
  catch(ArgumentOutOfRangeException aore)
  {
    throw new ArgumentOutOfRangeException("Array Index must be zero or greater.", aore);
  }
  catch(ArgumentException ae)
  {
    throw new ArgumentException("Not enough room in array to copy elements starting at index given.", ae);
  }
}

In terms of new code added that could potentially be buggy, this is even worse. And we don't gain a thing from the inner exceptions. If we pass a null array to this method and receive an ArgumentNullException, we're not going to learn anything by examining the inner exception and learning that a call to _innerList.CopyTo was passed a null array and threw an ArgumentNullException.

Here, we can do everything we want with:

public CopyTo(T[] array, int arrayIndex)
{
  try
  {
    _innerList.CopyTo(array, arrayIndex);
  }
  catch(ArgumentException ae)
  {
    throw ae;
  }
}

Every one of the exceptions that we expect to have to throw if the user calls it with incorrect arguments, will correctly be thrown by that re-throw. If there's a bug in the logic used here, it's in one of two lines - either we were wrong in deciding this was a case where this approach works, or we were wrong in having ArgumentException as the exception type looked for. It's the only two bugs that the catch block can possibly have.

Now. I still agree that most of the time you either want a plain throw; or you want to construct your own exception to more directly match the problem from the perspective of the method in question. There are cases like the above where re-throwing like this makes more sense, and there are plenty of other cases. E.g. to take a very different example, if an ATOM file reader implemented with a FileStream and an XmlTextReader receives a file error or invalid XML, then it will perhaps want to throw exactly the same exception it received from those classes, but it should look to the caller that it is AtomFileReader that is throwing a FileNotFoundException or XmlException, so they might be candidates for similarly re-throwing.

Edit:

We can also combine the two:

public CopyTo(T[] array, int arrayIndex)
{
  try
  {
    _innerList.CopyTo(array, arrayIndex);
  }
  catch(ArgumentException ae)
  {
    throw ae;
  }
  catch(Exception ex)
  {
    //we weren't expecting this, there must be a bug in our code that put
    //us into an invalid state, and subsequently let this exception happen.
    LogException(ex);
    throw;
  }
}

How can I set a custom baud rate on Linux?

You can set a custom baud rate using the stty command on Linux. For example, to set a custom baud rate of 567890 on your serial port /dev/ttyX0, use the command:

stty -F /dev/ttyX0 567890

In Python, what is the difference between ".append()" and "+= []"?

In the example you gave, there is no difference, in terms of output, between append and +=. But there is a difference between append and + (which the question originally asked about).

>>> a = []
>>> id(a)
11814312
>>> a.append("hello")
>>> id(a)
11814312

>>> b = []
>>> id(b)
11828720
>>> c = b + ["hello"]
>>> id(c)
11833752
>>> b += ["hello"]
>>> id(b)
11828720

As you can see, append and += have the same result; they add the item to the list, without producing a new list. Using + adds the two lists and produces a new list.

Rollback transaction after @Test

Just add @Transactional annotation on top of your test:

@RunWith(SpringJUnit4ClassRunner.class)  
@ContextConfiguration(locations = {"testContext.xml"})
@Transactional
public class StudentSystemTest {

By default Spring will start a new transaction surrounding your test method and @Before/@After callbacks, rolling back at the end. It works by default, it's enough to have some transaction manager in the context.

From: 10.3.5.4 Transaction management (bold mine):

In the TestContext framework, transactions are managed by the TransactionalTestExecutionListener. Note that TransactionalTestExecutionListener is configured by default, even if you do not explicitly declare @TestExecutionListeners on your test class. To enable support for transactions, however, you must provide a PlatformTransactionManager bean in the application context loaded by @ContextConfiguration semantics. In addition, you must declare @Transactional either at the class or method level for your tests.

*ngIf else if in template

_x000D_
_x000D_
<ion-row *ngIf="cat === 1;else second"></ion-row>_x000D_
<ng-template #second>_x000D_
    <ion-row *ngIf="cat === 2;else third"></ion-row>_x000D_
</ng-template>_x000D_
<ng-template #third>_x000D_
_x000D_
</ng-template>
_x000D_
_x000D_
_x000D_

Angular is already using ng-template under the hood in many of the structural directives that we use all the time: ngIf, ngFor and ngSwitch.

> What is ng-template in Angular

https://www.angularjswiki.com/angular/what-is-ng-template-in-angular/

How do I install boto?

  1. If necessary, install pip:

    sudo apt-get install python-pip

  2. Then install boto:

    pip install -U boto

What is the difference between task and thread?

Thread

The bare metal thing, you probably don't need to use it, you probably can use a LongRunning task and take the benefits from the TPL - Task Parallel Library, included in .NET Framework 4 (february, 2002) and above (also .NET Core).

Tasks

Abstraction above the Threads. It uses the thread pool (unless you specify the task as a LongRunning operation, if so, a new thread is created under the hood for you).

Thread Pool

As the name suggests: a pool of threads. Is the .NET framework handling a limited number of threads for you. Why? Because opening 100 threads to execute expensive CPU operations on a Processor with just 8 cores definitely is not a good idea. The framework will maintain this pool for you, reusing the threads (not creating/killing them at each operation), and executing some of them in parallel, in a way that your CPU will not burn.

OK, but when to use each one?

In resume: always use tasks.

Task is an abstraction, so it is a lot easier to use. I advise you to always try to use tasks and if you face some problem that makes you need to handle a thread by yourself (probably 1% of the time) then use threads.

BUT be aware that:

  • I/O Bound: For I/O bound operations (database calls, read/write files, APIs calls, etc) avoid using normal tasks, use LongRunning tasks (or threads if you need to). Because using tasks would lead you to a thread pool with a few threads busy and a lot of another tasks waiting for its turn to take the pool.
  • CPU Bound: For CPU bound operations just use the normal tasks (that internally will use the thread pool) and be happy.

How to properly use unit-testing's assertRaises() with NoneType objects?

The problem is the TypeError gets raised 'before' assertRaises gets called since the arguments to assertRaises need to be evaluated before the method can be called. You need to pass a lambda expression like:

self.assertRaises(TypeError, lambda: self.testListNone[:1])

How to do if-else in Thymeleaf?

I tried this code to find out if a customer is logged in or anonymous. I did using the th:if and th:unless conditional expressions. Pretty simple way to do it.

<!-- IF CUSTOMER IS ANONYMOUS -->
<div th:if="${customer.anonymous}">
   <div>Welcome, Guest</div>
</div>
<!-- ELSE -->
<div th:unless="${customer.anonymous}">
   <div th:text=" 'Hi,' + ${customer.name}">Hi, User</div>
</div>

How do I create a HTTP Client Request with a cookie?

The use of http.createClient is now deprecated. You can pass Headers in options collection as below.

var options = { 
    hostname: 'example.com',
    path: '/somePath.php',
    method: 'GET',
    headers: {'Cookie': 'myCookie=myvalue'}
};
var results = ''; 
var req = http.request(options, function(res) {
    res.on('data', function (chunk) {
        results = results + chunk;
        //TODO
    }); 
    res.on('end', function () {
        //TODO
    }); 
});

req.on('error', function(e) {
        //TODO
});

req.end();

Nested select statement in SQL Server

You need to alias the subquery.

SELECT name FROM (SELECT name FROM agentinformation) a  

or to be more explicit

SELECT a.name FROM (SELECT name FROM agentinformation) a  

html button to send email

As David notes, his suggestion does not actually fulfill the OP's request, which was an email with subject and message. It doesn't work because most, maybe all, combinations of browsers plus e-mail clients do not accept the subject and body attributes of the mailto: URI when supplied as a <form>'s action.

But here's a working example:

HTML (with Bootstrap styles):

<p><input id="subject" type="text" placeholder="type your subject here" 
    class="form-control"></p>
<p><input id="message" type="text" placeholder="type your message here" 
    class="form-control"></p>
<p><a id="mail-link" class="btn btn-primary">Create email</a></p>

JavaScript (with jQuery):

<script type="text/javascript">
    function loadEvents() {
        var mailString;
        function updateMailString() {
            mailString = '?subject=' + encodeURIComponent($('#subject').val())
                + '&body=' + encodeURIComponent($('#message').val());
            $('#mail-link').attr('href',  'mailto:[email protected]' + mailString);
        }
        $( "#subject" ).focusout(function() { updateMailString(); });
        $( "#message" ).focusout(function() { updateMailString(); });
        updateMailString();
    }
</script>

Notes:

  • The <form> element with associated action attribute is not used.
  • The <input> element of type button is also not used.
    • <a> styled as a button (here using Bootstrap) replaces <input type="button">
    • focusout() with updateMailString() is necessary because the <a> tag's href attribute does not automatically update when the input fields' values change.
    • updateMailString() is also called when document is loaded in case the input fields are prepopulated.
  • Also encodeURIComponent() is used to get characters such as the quotation mark (") across to Outlook.

In this approach, the mailto: URI is supplied (with subject and body attributes) in an a element's href tag. This works in all combinations of browsers and e-mail clients I have tested, which are recent (2015) versions of:

  • Browsers: Firefox/Win&OSX, Chrome/Win&OSX, IE/Win, Safari/OSX&iOS, Opera/OSX
  • E-mail clients: Outlook/Win, Mail.app/OSX&iOS, Sparrow/OSX

Bonus tip: In my use cases, I add some contextual text to the e-mail body. More often than not, I want that text to contain line breaks. %0D%0A (carriage return and linefeed) works in my tests.

Razor Views not seeing System.Web.Mvc.HtmlHelper

In the contracting world I'm often using machines that are using older images. After trying everything above I decided to update my VS 2013 to the most recent version (Update 4). After 90 minutes and a restart the references are working just fine now! Hope this helps!

Codeigniter - multiple database connections

Use this.

$dsn1 = 'mysql://user:password@localhost/db1';
$this->db1 = $this->load->database($dsn1, true);     

$dsn2 = 'mysql://user:password@localhost/db2';
$this->db2= $this->load->database($dsn2, true);     

$dsn3 = 'mysql://user:password@localhost/db3';
$this->db3= $this->load->database($dsn3, true);   

Usage

$this->db1 ->insert('tablename', $insert_array);
$this->db2->insert('tablename', $insert_array);
$this->db3->insert('tablename', $insert_array);

The storage engine for the table doesn't support repair. InnoDB or MyISAM?

InnoDB works slightly different that MyISAM and they both are viable options. You should use what you think it fits the project.

Some keypoints will be:

  1. InnoDB does ACID-compliant transaction. http://en.wikipedia.org/wiki/ACID
  2. InnoDB does Referential Integrity (foreign key relations) http://www.w3resource.com/sql/joins/joining-tables-through-referential-integrity.php
  3. MyIsam does full text search, InnoDB doesn't
  4. I have been told InnoDB is faster on executing writes but slower than MyISAM doing reads (I cannot back this up and could not find any article that analyses this, I do however have the guy that told me this in high regard), feel free to ignore this point or do your own research.
  5. Default configuration does not work very well for InnoDB needs to be tweaked accordingly, run a tool like http://mysqltuner.pl/mysqltuner.pl to help you.

Notes:

  • In my opinion the second point is probably the one were InnoDB has a huge advantage over MyISAM.
  • Full text search not working with InnoDB is a bit of a pain, You can mix different storage engines but be careful when doing so.

Notes2: - I am reading this book "High performance MySQL", the author says "InnoDB loads data and creates indexes slower than MyISAM", this could also be a very important factor when deciding what to use.

How to check if a class inherits another class without instantiating it?

To check for assignability, you can use the Type.IsAssignableFrom method:

typeof(SomeType).IsAssignableFrom(typeof(Derived))

This will work as you expect for type-equality, inheritance-relationships and interface-implementations but not when you are looking for 'assignability' across explicit / implicit conversion operators.

To check for strict inheritance, you can use Type.IsSubclassOf:

typeof(Derived).IsSubclassOf(typeof(SomeType))

Vertically centering Bootstrap modal window

No need to us javascript. Boostrap modal adds .in class when it appears. Just modify this class combination with modalclassName.fade.in with flex css and you are done.

add this css to center your modal vertically and horizontally.

.modal.fade.in {
    display: flex !important;
    justify-content: center;
    align-items: center;
}
.modal.fade.in .modal-dialog {
    width: 100%;
}

scrollbars in JTextArea

As Fredrik mentions in his answer, the simple way to achieve this is to place the JTextArea in a JScrollPane. This will allow scrolling of the view area of the JTextArea.

Just for the sake of completeness, the following is how it could be achieved:

JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);   // JTextArea is placed in a JScrollPane.

Once the JTextArea is included in the JScrollPane, the JScrollPane should be added to where the text area should be. In the following example, the text area with the scroll bars is added to a JFrame:

JFrame f = new JFrame();
f.getContentPane().add(sp);

Thank you kd304 for mentioning in the comments that one should add the JScrollPane to the container rather than the JTextArea -- I feel it's a common error to add the text area itself to the destination container rather than the scroll pane with text area.

The following articles from The Java Tutorials has more details:

What is the `zero` value for time.Time in Go?

The zero value for time.Time is 0001-01-01 00:00:00 +0000 UTC See http://play.golang.org/p/vTidOlmb9P

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

I'd create the array and then append the object literals to it.

var myColumnDefs = [];

for ( var i=0 ; i < oFullResponse.results.length; i++) {

    console.log(oFullResponse.results[i].label);
    myColumnDefs[myColumnDefs.length] = {key:oFullResponse.results[i].label, sortable:true, resizeable:true};
}

eclipse won't start - no java virtual machine was found

My solution is Include JDK's "bin" Directory in the PATH

To edit the PATH environment variable in Windows 7/8/10:

  1. Launch "Control Panel" ? (Optional) System and Security ? System ? Click "Advanced system settings" on the left pane.
  2. Switch to "Advanced" tab ? Push "Environment Variables" button. Under "System Variables" (the bottom pane), scroll down to select "Path" ? Click "Edit...".
  3. Copy the JDK bin directory from JAVA folder and paste to "Edit..."

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

I made use of variables defined in :root inside CSS to modify the :after (the same applies to :before) pseudo-element, in particular to change the background-color value for a styled anchor defined by .sliding-middle-out:hover:after and the content value for another anchor (#reference) in the following demo that generates random colors by using JavaScript/jQuery:

HTML

<a href="#" id="changeColor" class="sliding-middle-out" title="Generate a random color">Change link color</a>
<span id="log"></span>
<h6>
  <a href="https://stackoverflow.com/a/52360188/2149425" id="reference" class="sliding-middle-out" target="_blank" title="Stack Overflow topic">Reference</a>
</h6>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/davidmerfield/randomColor/master/randomColor.js"></script>

CSS

:root {
    --anchorsFg: #0DAFA4;
}
a, a:visited, a:focus, a:active {
    text-decoration: none;
    color: var(--anchorsFg);
    outline: 0;
    font-style: italic;

    -webkit-transition: color 250ms ease-in-out;
    -moz-transition: color 250ms ease-in-out;
    -ms-transition: color 250ms ease-in-out;
    -o-transition: color 250ms ease-in-out;
    transition: color 250ms ease-in-out;
}
.sliding-middle-out {
    display: inline-block;
    position: relative;
    padding-bottom: 1px;
}
.sliding-middle-out:after {
    content: '';
    display: block;
    margin: auto;
    height: 1px;
    width: 0px;
    background-color: transparent;

    -webkit-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
    -moz-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
    -ms-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
    -o-transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
    transition: width 250ms ease-in-out, background-color 250ms ease-in-out;
}
.sliding-middle-out:hover:after {
    width: 100%;
    background-color: var(--anchorsFg);
    outline: 0;
}
#reference {
  margin-top: 20px;
}
.sliding-middle-out:before {
  content: attr(data-content);
  display: attr(data-display);
}

JS/jQuery

var anchorsFg = randomColor();
$( ".sliding-middle-out" ).hover(function(){
    $( ":root" ).css({"--anchorsFg" : anchorsFg});
});

$( "#reference" ).hover(
 function(){
    $(this).attr("data-content", "Hello World!").attr("data-display", "block").html("");
 },
 function(){
    $(this).attr("data-content", "Reference").attr("data-display", "inline").html("");
 }
);

Use jQuery to change an HTML tag?

The following function does the trick and keeps all the attributes. You use it for example like this: changeTag("div", "p")

function changeTag(originTag, destTag) {
  while($(originTag).length) {
    $(originTag).replaceWith (function () {
      var attributes = $(this).prop("attributes");
      var $newEl = $(`<${destTag}>`)
      $.each(attributes, function() {
        $newEl.attr(this.name, this.value);
      });  
      return $newEl.html($(this).html())
    })
  }
}

To be sure that it works, check the following example

_x000D_
_x000D_
function changeTag(originTag, destTag) {_x000D_
  while($(originTag).length) {_x000D_
    $(originTag).replaceWith (function () {_x000D_
      var attributes = $(this).prop("attributes");_x000D_
      var $newEl = $(`<${destTag}>`)_x000D_
      $.each(attributes, function() {_x000D_
        $newEl.attr(this.name, this.value);_x000D_
      });  _x000D_
      return $newEl.html($(this).html())_x000D_
    })_x000D_
  }_x000D_
}_x000D_
_x000D_
changeTag("div", "p")_x000D_
_x000D_
console.log($("body").html())
_x000D_
<body>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="A" style="font-size:1em">_x000D_
  <div class="B" style="font-size:1.1em">A</div>_x000D_
</div>_x000D_
<div class="C" style="font-size:1.2em">_x000D_
  B_x000D_
</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

How to get JSON from webpage into Python script

This gets a dictionary in JSON format from a webpage with Python 2.X and Python 3.X:

#!/usr/bin/env python

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

import json


def get_jsonparsed_data(url):
    """
    Receive the content of ``url``, parse it as JSON and return the object.

    Parameters
    ----------
    url : str

    Returns
    -------
    dict
    """
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return json.loads(data)


url = ("http://maps.googleapis.com/maps/api/geocode/json?"
       "address=googleplex&sensor=false")
print(get_jsonparsed_data(url))

See also: Read and write example for JSON

Proper way to exit iPhone application?

This has gotten a good answer but decided to expand a bit:

You can't get your application accepted to AppStore without reading Apple's iOS Human Interface Guidelines well. (they retain the right to reject you for doing anything against them) The section "Don't Quit Programmatically" http://developer.apple.com/library/ios/#DOCUMENTATION/UserExperience/Conceptual/MobileHIG/UEBestPractices/UEBestPractices.html is an exact guideline in how you should treat in this case.

If you ever have a problem with Apple platform you can't easily find a solution for, consult HIG. It's possible Apple simply doesn't want you to do it and they usually (I'm not Apple so I can't guarantee always) do say so in their documentation.

Differences between unique_ptr and shared_ptr

unique_ptr is the light-weight smart pointer of choice if you just have a dynamic object somewhere for which one consumer has sole (hence "unique") responsibility -- maybe a wrapper class that needs to maintain some dynamically allocated object. unique_ptr has very little overhead. It is not copyable, but movable. Its type is template <typename D, typename Deleter> class unique_ptr;, so it depends on two template parameters.

unique_ptr is also what auto_ptr wanted to be in the old C++ but couldn't because of that language's limitations.

shared_ptr on the other hand is a very different animal. The obvious difference is that you can have many consumers sharing responsibility for a dynamic object (hence "shared"), and the object will only be destroyed when all shared pointers have gone away. Additionally you can have observing weak pointers which will intelligently be informed if the shared pointer they're following has disappeared.

Internally, shared_ptr has a lot more going on: There is a reference count, which is updated atomically to allow the use in concurrent code. Also, there's plenty of allocation going on, one for an internal bookkeeping "reference control block", and another (often) for the actual member object.

But there's another big difference: The shared pointers type is always template <typename T> class shared_ptr;, and this is despite the fact that you can initialize it with custom deleters and with custom allocators. The deleter and allocator are tracked using type erasure and virtual function dispatch, which adds to the internal weight of the class, but has the enormous advantage that different sorts of shared pointers of type T are all compatible, no matter the deletion and allocation details. Thus they truly express the concept of "shared responsibility for T" without burdening the consumer with the details!

Both shared_ptr and unique_ptr are designed to be passed by value (with the obvious movability requirement for the unique pointer). Neither should make you worried about the overhead, since their power is truly astounding, but if you have a choice, prefer unique_ptr, and only use shared_ptr if you really need shared responsibility.

HTTP URL Address Encoding in Java

Unfortunately, org.apache.commons.httpclient.util.URIUtil is deprecated, and the replacement org.apache.commons.codec.net.URLCodec does coding suitable for form posts, not in actual URL's. So I had to write my own function, which does a single component (not suitable for entire query strings that have ?'s and &'s)

public static String encodeURLComponent(final String s)
{
  if (s == null)
  {
    return "";
  }

  final StringBuilder sb = new StringBuilder();

  try
  {
    for (int i = 0; i < s.length(); i++)
    {
      final char c = s.charAt(i);

      if (((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')) ||
          ((c >= '0') && (c <= '9')) ||
          (c == '-') ||  (c == '.')  || (c == '_') || (c == '~'))
      {
        sb.append(c);
      }
      else
      {
        final byte[] bytes = ("" + c).getBytes("UTF-8");

        for (byte b : bytes)
        {
          sb.append('%');

          int upper = (((int) b) >> 4) & 0xf;
          sb.append(Integer.toHexString(upper).toUpperCase(Locale.US));

          int lower = ((int) b) & 0xf;
          sb.append(Integer.toHexString(lower).toUpperCase(Locale.US));
        }
      }
    }

    return sb.toString();
  }
  catch (UnsupportedEncodingException uee)
  {
    throw new RuntimeException("UTF-8 unsupported!?", uee);
  }
}

How to extract HTTP response body from a Python requests call?


import requests

site_request = requests.get("https://abhiunix.in")

site_response = str(site_request.content)

print(site_response)

You can do it either way.

WCF error - There was no endpoint listening at

Different case but may help someone,

In my case Window firewall was enabled on Server,

Two thinks can be done,

1) Disable windows firewall (your on risk but it will get thing work)

2) Add port in inbound rule.

Thanks .

Find common substring between two strings

In case we have a list of words that we need to find all common substrings I check some of the codes above and the best was https://stackoverflow.com/a/42882629/8520109 but it has some bugs for example 'histhome' and 'homehist'. In this case, we should have 'hist' and 'home' as a result. Furthermore, it differs if the order of arguments is changed. So I change the code to find every block of substring and it results a set of common substrings:

main = input().split(" ")    #a string of words separated by space
def longestSubstringFinder(string1, string2):
    '''Find the longest matching word'''
    answer = ""
    len1, len2 = len(string1), len(string2)
    for i in range(len1):
        for j in range(len2):
            lcs_temp=0
            match=''
            while ((i+lcs_temp < len1) and (j+lcs_temp<len2) and string1[i+lcs_temp] == string2[j+lcs_temp]):
                match += string2[j+lcs_temp]
                lcs_temp+=1         
            if (len(match) > len(answer)):
                answer = match              
    return answer

def listCheck(main):
    '''control the input for finding substring in a list of words'''
    string1 = main[0]
    result = []
    for i in range(1, len(main)):
        string2 = main[i]
        res1 = longestSubstringFinder(string1, string2)
        res2 = longestSubstringFinder(string2, string1)
        result.append(res1)
        result.append(res2)
    result.sort()
    return result

first_answer = listCheck(main)

final_answer  = []


for item1 in first_answer:    #to remove some incorrect match
    string1 = item1
    double_check = True
    for item2 in main:
        string2 = item2
        if longestSubstringFinder(string1, string2) != string1:
            double_check = False
    if double_check:
        final_answer.append(string1)

print(set(final_answer))

main = 'ABACDAQ BACDAQA ACDAQAW XYZCDAQ' #>>> {'CDAQ'}
main = 'homehist histhome' #>>> {'hist', 'home'}

How to view the current heap size that an application is using?

You can Use the tool : Eclipse Memory Analyzer Tool http://www.eclipse.org/mat/ .

It is very useful.

Difference between scaling horizontally and vertically for databases

Scaling horizontally ===> Thousands of minions will do the work together for you.

Scaling vertically ===> One big hulk will do all the work for you.

enter image description here

How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

you can use this code to open (test.xlsx) file and modify A1 cell and then save it with a new name

import openpyxl
xfile = openpyxl.load_workbook('test.xlsx')

sheet = xfile.get_sheet_by_name('Sheet1')
sheet['A1'] = 'hello world'
xfile.save('text2.xlsx')

Safest way to get last record ID from a table

Safest way will be to output or return the scope_identity() within the procedure inserting the row, and then retrieve the row based on that ID. Use of @@Identity is to be avoided since you can get the incorrect ID when triggers are in play.

Any technique of asking for the maximum value / top 1 suffers a race condition where 2 people adding at the same time, would then get the same ID back when they looked for the highest ID.

Asp Net Web API 2.1 get client IP address

If you're self-hosting with Asp.Net 2.1 using the OWIN Self-host NuGet package you can use the following code:

 private string getClientIp(HttpRequestMessage request = null)
    {
        if (request == null)
        {
            return null;
        }

        if (request.Properties.ContainsKey("MS_OwinContext"))
        {
            return ((OwinContext) request.Properties["MS_OwinContext"]).Request.RemoteIpAddress;
        }
        return null;
    }

How to have click event ONLY fire on parent DIV, not children?

I did not get the accepted answer to work, but this seems to do the trick, at least in vanilla JS.

if(e.target !== e.currentTarget) return;

How can I add items to an empty set in python

>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>

What you've made is a dictionary and not a Set.

The update method in dictionary is used to update the new dictionary from a previous one, like so,

>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}

Whereas in sets, it is used to add elements to the set.

>>> D.update([1, 2])
>>> D
set([1, 2])

How to implement private method in ES6 class with Traceur

You can always use normal functions:

function myPrivateFunction() {
  console.log("My property: " + this.prop);
}

class MyClass() {
  constructor() {
    this.prop = "myProp";
    myPrivateFunction.bind(this)();
  }
}

new MyClass(); // 'My property: myProp'

%matplotlib line magic causes SyntaxError in Python script

Because line magics are only supported by the IPython command line not by Python cl, use: 'exec(%matplotlib inline)' instead of %matplotlib inline

PG::ConnectionBad - could not connect to server: Connection refused

If you hit this problem after doing a brew upgrade which upgraded postgres to a new major version (f.ex 9.3.0 to 9.4.0 or higher), then do this:

@dmitrygusev's fix from https://github.com/Homebrew/homebrew/issues/35240

Following official [Postgresql] migration guide helped:

brew switch postgres 9.3.5    # presuming you already installed 9.4.1
pg_dumpall > outputfile
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist
mv /usr/local/var/postgres /usr/local/var/postgres.old
brew switch postgres 9.4.1
initdb -D /usr/local/var/postgres
psql -d postgres -f outputfile

That's all. Check if import went well, then delete backups:

rm outputfile
rm -Rf /usr/local/var/postgres.old

The issue here is that on a major version upgrade of postgres, it's necessary to recreate/migrate your database. And possibly chown directories or manually call initdb.

See also: How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?


Some other tips, that might come in handy, in case you're not using Homebrew:

Stop PG server manually:

pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log stop

Start PG server manually:

pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start

Convert MySql DateTime stamp into JavaScript's Date format

There is a simpler way, sql timestamp string:

2018-07-19 00:00:00

The closest format to timestamp for Date() to receive is the following, so replace blank space for "T":

var dateString = media.intervention.replace(/\s/g, "T");

"2011-10-10T14:48:00"

Then, create the date object:

var date = new Date(dateString);

result would be the date object:

Thu Jul 19 2018 00:00:00 GMT-0300 (Horário Padrão de Brasília)

How do I kill background processes / jobs when my shell script exits?

To clean up some mess, trap can be used. It can provide a list of stuff executed when a specific signal arrives:

trap "echo hello" SIGINT

but can also be used to execute something if the shell exits:

trap "killall background" EXIT

It's a builtin, so help trap will give you information (works with bash). If you only want to kill background jobs, you can do

trap 'kill $(jobs -p)' EXIT

Watch out to use single ', to prevent the shell from substituting the $() immediately.

How to check if a network port is open on linux?

You can using the socket module to simply check if a port is open or not.

It would look something like this.

import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('127.0.0.1',80))
if result == 0:
   print "Port is open"
else:
   print "Port is not open"
sock.close()

Functional style of Java 8's Optional.ifPresent and if-not-Present?

Java 9 introduces

ifPresentOrElse if a value is present, performs the given action with the value, otherwise performs the given empty-based action.

See excellent Optional in Java 8 cheat sheet.

It provides all answers for most use cases.

Short summary below

ifPresent() - do something when Optional is set

opt.ifPresent(x -> print(x)); 
opt.ifPresent(this::print);

filter() - reject (filter out) certain Optional values.

opt.filter(x -> x.contains("ab")).ifPresent(this::print);

map() - transform value if present

opt.map(String::trim).filter(t -> t.length() > 1).ifPresent(this::print);

orElse()/orElseGet() - turning empty Optional to default T

int len = opt.map(String::length).orElse(-1);
int len = opt.
    map(String::length).
    orElseGet(() -> slowDefault());     //orElseGet(this::slowDefault)

orElseThrow() - lazily throw exceptions on empty Optional

opt.
filter(s -> !s.isEmpty()).
map(s -> s.charAt(0)).
orElseThrow(IllegalArgumentException::new);

Are PDO prepared statements sufficient to prevent SQL injection?

No this is not enough (in some specific cases)! By default PDO uses emulated prepared statements when using MySQL as a database driver. You should always disable emulated prepared statements when using MySQL and PDO:

$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

Another thing that always should be done it set the correct encoding of the database:

$dbh = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');

Also see this related question: How can I prevent SQL injection in PHP?

Also note that that only is about the database side of the things you would still have to watch yourself when displaying the data. E.g. by using htmlspecialchars() again with the correct encoding and quoting style.

Android 'Unable to add window -- token null is not for an application' exception

Use this and context not worked for me..but MyActivityName.this worked. Hope this helps anyone who need it.

MySQL Error 1093 - Can't specify target table for update in FROM clause

Recently i had to update records in the same table i did it like below:

UPDATE skills AS s, (SELECT id  FROM skills WHERE type = 'Programming') AS p
SET s.type = 'Development' 
WHERE s.id = p.id;

The response content cannot be parsed because the Internet Explorer engine is not available, or

To make it work without modifying your scripts:

I found a solution here: http://wahlnetwork.com/2015/11/17/solving-the-first-launch-configuration-error-with-powershells-invoke-webrequest-cmdlet/

The error is probably coming up because IE has not yet been launched for the first time, bringing up the window below. Launch it and get through that screen, and then the error message will not come up any more. No need to modify any scripts.

ie first launch window

How to send an email with Gmail as provider using Python?

You down with OOP?

#!/usr/bin/env python


import smtplib

class Gmail(object):
    def __init__(self, email, password):
        self.email = email
        self.password = password
        self.server = 'smtp.gmail.com'
        self.port = 587
        session = smtplib.SMTP(self.server, self.port)        
        session.ehlo()
        session.starttls()
        session.ehlo
        session.login(self.email, self.password)
        self.session = session

    def send_message(self, subject, body):
        ''' This must be removed '''
        headers = [
            "From: " + self.email,
            "Subject: " + subject,
            "To: " + self.email,
            "MIME-Version: 1.0",
           "Content-Type: text/html"]
        headers = "\r\n".join(headers)
        self.session.sendmail(
            self.email,
            self.email,
            headers + "\r\n\r\n" + body)


gm = Gmail('Your Email', 'Password')

gm.send_message('Subject', 'Message')

Android activity life cycle - what are all these methods for?

See it in Activity Lifecycle (at Android Developers).

Enter image description here

onCreate():

Called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state, if there was one. Always followed by onStart().

onRestart():

Called after your activity has been stopped, prior to it being started again. Always followed by onStart()

onStart():

Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground.

onResume():

Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it. Always followed by onPause().

onPause ():

Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed. The counterpart to onResume(). When activity B is launched in front of activity A, this callback will be invoked on A. B will not be created until A's onPause() returns, so be sure to not do anything lengthy here.

onStop():

Called when you are no longer visible to the user. You will next receive either onRestart(), onDestroy(), or nothing, depending on later user activity. Note that this method may never be called, in low memory situations where the system does not have enough memory to keep your activity's process running after its onPause() method is called.

onDestroy():

The final call you receive before your activity is destroyed. This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between> these two scenarios with the isFinishing() method.

When the Activity first time loads the events are called as below:

onCreate()
onStart()
onResume()

When you click on Phone button the Activity goes to the background and the below events are called:

onPause()
onStop()

Exit the phone dialer and the below events will be called:

onRestart()
onStart()
onResume()

When you click the back button OR try to finish() the activity the events are called as below:

onPause()
onStop()
onDestroy()

Activity States

The Android OS uses a priority queue to assist in managing activities running on the device. Based on the state a particular Android activity is in, it will be assigned a certain priority within the OS. This priority system helps Android identify activities that are no longer in use, allowing the OS to reclaim memory and resources. The following diagram illustrates the states an activity can go through, during its lifetime:

These states can be broken into three main groups as follows:

Active or Running - Activities are considered active or running if they are in the foreground, also known as the top of the activity stack. This is considered the highest priority activity in the Android Activity stack, and as such will only be killed by the OS in extreme situations, such as if the activity tries to use more memory than is available on the device as this could cause the UI to become unresponsive.

Paused - When the device goes to sleep, or an activity is still visible but partially hidden by a new, non-full-sized or transparent activity, the activity is considered paused. Paused activities are still alive, that is, they maintain all state and member information, and remain attached to the window manager. This is considered to be the second highest priority activity in the Android Activity stack and, as such, will only be killed by the OS if killing this activity will satisfy the resource requirements needed to keep the Active/Running Activity stable and responsive.

Stopped - Activities that are completely obscured by another activity are considered stopped or in the background. Stopped activities still try to retain their state and member information for as long as possible, but stopped activities are considered to be the lowest priority of the three states and, as such, the OS will kill activities in this state first to satisfy the resource requirements of higher priority activities.

*Sample activity to understand the life cycle**

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends Activity {
    String tag = "LifeCycleEvents";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       Log.d(tag, "In the onCreate() event");
    }
    public void onStart()
    {
       super.onStart();
       Log.d(tag, "In the onStart() event");
    }
    public void onRestart()
    {
       super.onRestart();
       Log.d(tag, "In the onRestart() event");
    }
    public void onResume()
    {
       super.onResume();
       Log.d(tag, "In the onResume() event");
    }
    public void onPause()
    {
       super.onPause();
       Log.d(tag, "In the onPause() event");
    }
    public void onStop()
    {
       super.onStop();
       Log.d(tag, "In the onStop() event");
    }
    public void onDestroy()
    {
       super.onDestroy();
       Log.d(tag, "In the onDestroy() event");
    }
}

remove first element from array and return the array minus the first element

This can be done in one line with lodash _.tail:

_x000D_
_x000D_
var arr = ["item 1", "item 2", "item 3", "item 4"];_x000D_
console.log(_.tail(arr));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

No input file specified

It worked for me..add on top of .htaccess file. It would disable FastCGI on godaddy shared hosting account.

Options +ExecCGI

addhandler x-httpd-php5-cgi .php

How do I do a HTTP GET in Java?

Technically you could do it with a straight TCP socket. I wouldn't recommend it however. I would highly recommend you use Apache HttpClient instead. In its simplest form:

GetMethod get = new GetMethod("http://httpcomponents.apache.org");
// execute method and handle any error responses.
...
InputStream in = get.getResponseBodyAsStream();
// Process the data from the input stream.
get.releaseConnection();

and here is a more complete example.

Using Composer's Autoload

The composer documentation states that:

After adding the autoload field, you have to re-run install to re-generate the vendor/autoload.php file.

Assuming your "src" dir resides at the same level as "vendor" dir:

  • src
    • AppName
  • vendor
  • composer.json

the following config is absolutely correct:

{
    "autoload": {
        "psr-0": {"AppName": "src/"}
    }
}

but you must re-update/install dependencies to make it work for you, i.e. run:

php composer.phar update

This command will get the latest versions of the dependencies and update the file "vendor/composer/autoload_namespaces.php" to match your configuration.

Also as noted by @Dom, you can use composer dump-autoload to update the autoloader without having to go through an update.

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

Doing Project -> Clean... fixed it for me.

My eclipse had stopped working so I cleaned workspace directory and after I run eclipse when I import the project I had this problem. Other solutions suggested here didn't work.

Where is android studio building my .apk file?

When you have android studio make your signed apk file it uses

    <property name="ExportedApkPath" value="$PROJECT_DIR$/PROJNAME/APPNAME.apk" />

inside workspace.xml to find out where to place it. However, if you use ./gradlew assembleRelease it places it inside PROJNAME/build/apk. I have the same problem. For some reason my android studio will not show me anything inside the apk subdirectory so the apk is for all intents and purposes missing. But if you search with finder it's most definitely there.

Create a string with n characters

How about this?

char[] bytes = new char[length];
Arrays.fill(bytes, ' ');
String str = new String(bytes);

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

Use oracle.jdbc.OracleDriver, not oracle.jdbc.driver.OracleDriver. You do not need to register it if the driver jar file is in the "WEB-INF\lib" directory, if you are using Tomcat. Save this as test.jsp and put it in your web directory, and redeploy your web app folder in Tomcat manager:

<%@ page import="java.sql.*" %>

<HTML>
<HEAD>
<TITLE>Simple JSP Oracle Test</TITLE>
</HEAD><BODY>
<%
Connection conn = null;
try {
    Class.forName("oracle.jdbc.OracleDriver");
    conn = DriverManager.getConnection("jdbc:oracle:thin:@XXX.XXX.XXX.XXX:XXXX:dbName", "user", "password");
    Statement stmt = conn.createStatement();
    out.println("Connection established!");
}
catch (Exception ex)
{
    out.println("Exception: " + ex.getMessage() + "");

}
finally
{
    if (conn != null) {
        try {
            conn.close();   
        }
        catch (Exception ignored) {
            // ignore
        }
    }
}

%>

Querying DynamoDB by date

You could make the Hash key something along the lines of a 'product category' id, then the range key as a combination of a timestamp with a unique id appended on the end. That way you know the hash key and can still query the date with greater than.

How to copy multiple files in one layer using a Dockerfile?

simple

COPY README.md  package.json gulpfile.js __BUILD_NUMBER ./

from the doc

If multiple resources are specified, either directly or due to the use of a wildcard, then must be a directory, and it must end with a slash /.

How do I set the default page of my application in IIS7?

On IIS Manager--> Http view--> double click on Default and write the name of your desired startup page, Thats it

How to Set the Background Color of a JButton on the Mac OS

Based on your own purposes, you can do that based on setOpaque(true/false) and setBorderPainted(true/false); try and combine them to fit your purpose

Placeholder Mixin SCSS/CSS

I found the approach given by cimmanon and Kurt Mueller almost worked, but that I needed a parent reference (i.e., I need to add the '&' prefix to each vendor prefix); like this:

@mixin placeholder {
    &::-webkit-input-placeholder {@content}
    &:-moz-placeholder           {@content}
    &::-moz-placeholder          {@content}
    &:-ms-input-placeholder      {@content}  
}

I use the mixin like this:

input {
    @include placeholder {
        font-family: $base-font-family;
        color: red;
    }
}

With the parent reference in place, then correct css gets generated, e.g.:

input::-webkit-input-placeholder {
    font-family: Constantia, "Lucida Bright", Lucidabright, "Lucida Serif", Lucida, "DejaVu Serif", "Liberation Serif", Georgia, serif;
    color: red;
}

Without the parent reference (&), then a space is inserted before the vendor prefix and the CSS processor ignores the declaration; that looks like this:

input::-webkit-input-placeholder {
    font-family: Constantia, "Lucida Bright", Lucidabright, "Lucida Serif", Lucida, "DejaVu Serif", "Liberation Serif", Georgia, serif;
    color: red;
}

jQuery Upload Progress and AJAX file upload

Uploading files is actually possible with AJAX these days. Yes, AJAX, not some crappy AJAX wannabes like swf or java.

This example might help you out: https://webblocks.nl/tests/ajax/file-drag-drop.html

(It also includes the drag/drop interface but that's easily ignored.)

Basically what it comes down to is this:

<input id="files" type="file" />

<script>
document.getElementById('files').addEventListener('change', function(e) {
    var file = this.files[0];
    var xhr = new XMLHttpRequest();
    (xhr.upload || xhr).addEventListener('progress', function(e) {
        var done = e.position || e.loaded
        var total = e.totalSize || e.total;
        console.log('xhr progress: ' + Math.round(done/total*100) + '%');
    });
    xhr.addEventListener('load', function(e) {
        console.log('xhr upload complete', e, this.responseText);
    });
    xhr.open('post', '/URL-HERE', true);
    xhr.send(file);
});
</script>

(demo: http://jsfiddle.net/rudiedirkx/jzxmro8r/)

So basically what it comes down to is this =)

xhr.send(file);

Where file is typeof Blob: http://www.w3.org/TR/FileAPI/

Another (better IMO) way is to use FormData. This allows you to 1) name a file, like in a form and 2) send other stuff (files too), like in a form.

var fd = new FormData;
fd.append('photo1', file);
fd.append('photo2', file2);
fd.append('other_data', 'foo bar');
xhr.send(fd);

FormData makes the server code cleaner and more backward compatible (since the request now has the exact same format as normal forms).

All of it is not experimental, but very modern. Chrome 8+ and Firefox 4+ know what to do, but I don't know about any others.

This is how I handled the request (1 image per request) in PHP:

if ( isset($_FILES['file']) ) {
    $filename = basename($_FILES['file']['name']);
    $error = true;

    // Only upload if on my home win dev machine
    if ( isset($_SERVER['WINDIR']) ) {
        $path = 'uploads/'.$filename;
        $error = !move_uploaded_file($_FILES['file']['tmp_name'], $path);
    }

    $rsp = array(
        'error' => $error, // Used in JS
        'filename' => $filename,
        'filepath' => '/tests/uploads/' . $filename, // Web accessible
    );
    echo json_encode($rsp);
    exit;
}

HTML 'td' width and height

The width attribute of <td> is deprecated in HTML 5.

Use CSS. e.g.

 <td style="width:100px">

in detail, like this:

<table >
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td style="width:70%">January</td>
    <td style="width:30%">$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

How to get different colored lines for different plots in a single figure?

Matplotlib does this by default.

E.g.:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)
plt.show()

Basic plot demonstrating color cycling

And, as you may already know, you can easily add a legend:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)

plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')

plt.show()

Basic plot with legend

If you want to control the colors that will be cycled through:

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

plt.gca().set_color_cycle(['red', 'green', 'blue', 'yellow'])

plt.plot(x, x)
plt.plot(x, 2 * x)
plt.plot(x, 3 * x)
plt.plot(x, 4 * x)

plt.legend(['y = x', 'y = 2x', 'y = 3x', 'y = 4x'], loc='upper left')

plt.show()

Plot showing control over default color cycling

If you're unfamiliar with matplotlib, the tutorial is a good place to start.

Edit:

First off, if you have a lot (>5) of things you want to plot on one figure, either:

  1. Put them on different plots (consider using a few subplots on one figure), or
  2. Use something other than color (i.e. marker styles or line thickness) to distinguish between them.

Otherwise, you're going to wind up with a very messy plot! Be nice to who ever is going to read whatever you're doing and don't try to cram 15 different things onto one figure!!

Beyond that, many people are colorblind to varying degrees, and distinguishing between numerous subtly different colors is difficult for more people than you may realize.

That having been said, if you really want to put 20 lines on one axis with 20 relatively distinct colors, here's one way to do it:

import matplotlib.pyplot as plt
import numpy as np

num_plots = 20

# Have a look at the colormaps here and decide which one you'd like:
# http://matplotlib.org/1.2.1/examples/pylab_examples/show_colormaps.html
colormap = plt.cm.gist_ncar
plt.gca().set_prop_cycle(plt.cycler('color', plt.cm.jet(np.linspace(0, 1, num_plots))))

# Plot several different functions...
x = np.arange(10)
labels = []
for i in range(1, num_plots + 1):
    plt.plot(x, i * x + 5 * i)
    labels.append(r'$y = %ix + %i$' % (i, 5*i))

# I'm basically just demonstrating several different legend options here...
plt.legend(labels, ncol=4, loc='upper center', 
           bbox_to_anchor=[0.5, 1.1], 
           columnspacing=1.0, labelspacing=0.0,
           handletextpad=0.0, handlelength=1.5,
           fancybox=True, shadow=True)

plt.show()

Unique colors for 20 lines based on a given colormap

Factorial using Recursion in Java

result is a local variable of the fact method. So each time the fact method is called, the result is stored in a different variable than the previous fact invocation.

So when fact is invoked with 3 as argument, you can imagine that its result is

 result3 = fact(2) * 3
 result3 = result2 * 3
 result3 = 1 * 2 * 3

How to change navigation bar color in iOS 7 or 6?

Based on posted answered, this worked for me:

/* check for iOS 6 or 7 */
if ([[self navigationController].navigationBar respondsToSelector:@selector(setBarTintColor:)]) {
    [[self navigationController].navigationBar setBarTintColor:[UIColor whiteColor]];

} else {
    /* Set background and foreground */
    [[self navigationController].navigationBar setTintColor:[UIColor whiteColor]];
    [self navigationController].navigationBar.titleTextAttributes = [[NSDictionary alloc] initWithObjectsAndKeys:[UIColor blackColor],UITextAttributeTextColor,nil];
}

How to add content to html body using JS?

Try the following syntax:

document.body.innerHTML += "<p>My new content</p>";

How to override and extend basic Django admin templates?

Update:

Read the Docs for your version of Django. e.g.

https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#admin-overriding-templates https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#admin-overriding-templates https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#admin-overriding-templates

Original answer from 2011:

I had the same issue about a year and a half ago and I found a nice template loader on djangosnippets.org that makes this easy. It allows you to extend a template in a specific app, giving you the ability to create your own admin/index.html that extends the admin/index.html template from the admin app. Like this:

{% extends "admin:admin/index.html" %}

{% block sidebar %}
    {{block.super}}
    <div>
        <h1>Extra links</h1>
        <a href="/admin/extra/">My extra link</a>
    </div>
{% endblock %}

I've given a full example on how to use this template loader in a blog post on my website.

Django - limiting query results

Yes. If you want to fetch a limited subset of objects, you can with the below code:

Example:

obj=emp.objects.all()[0:10]

The beginning 0 is optional, so

obj=emp.objects.all()[:10]

The above code returns the first 10 instances.

How to have a default option in Angular.js select box

This working for me

ng-selected="true" 

HttpClient 4.0.1 - how to release connection?

If the response is not to be consumed, then the request can be aborted using the code below:

// Low level resources should be released before initiating a new request
HttpEntity entity = response.getEntity();

if (entity != null) {
    // Do not need the rest
    httpPost.abort();
}

Reference: http://hc.apache.org/httpcomponents-client-ga/tutorial/html/fundamentals.html#d5e143

Apache HttpClient Version: 4.1.3

Android BroadcastReceiver within Activity

Extends the ToastDisplay class with BroadcastReceiver and register the receiver in the manifest file,and dont register your broadcast receiver in onResume() .

<application
  ....
  <receiver android:name=".ToastDisplay">
    <intent-filter>
      <action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
    </intent-filter>
  </receiver>
</application>

if you want to register in activity then register in the onCreate() method e.g:

onCreate(){

    sentSmsBroadcastCome = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "SMS SENT!!", Toast.LENGTH_SHORT).show();
        }
    };
    IntentFilter filterSend = new IntentFilter();
    filterSend.addAction("m.sent");
    registerReceiver(sentSmsBroadcastCome, filterSend);
}

Java Web Service client basic authentication

If you are using a JAX-WS implementation for your client, such as Metro Web Services, the following code shows how to pass username and password in the HTTP headers:

 MyService port = new MyService();
 MyServiceWS service = port.getMyServicePort();

 Map<String, List<String>> credentials = new HashMap<String,List<String>>();

 credentials.put("username", Collections.singletonList("username"));
 credentials.put("password", Collections.singletonList("password"));

 ((BindingProvider)service).getRequestContext().put(MessageContext.HTTP_REQUEST_HEADERS, credentials);

Then subsequent calls to the service will be authenticated. Beware that the password is only encoded using Base64, so I encourage you to use other additional mechanism like client certificates to increase security.

Google Maps API v3: How to remove all markers?

Most voted answer at top is correct but in case if you have only one marker at a time (like I had in my situation) and every time you need to kill the previous location of that marker and add a new one then you don't need to create whole array of markers and manage it on every push and pop, you can simply just create a variable to store your marker's previous location and can set that to null on creation of new one.

// Global variable to hold marker location.

var previousMarker;

//while adding a new marker

    if(previousMarker != null)
previousMarker.setMap(null);

var marker = new google.maps.Marker({map: resultsMap, position: new google.maps.LatLng(lat_, lang_)});
previousMarker = marker;

One line if-condition-assignment

Here is what i can suggest. Use another variable to derive the if clause and assign it to num1.

Code:

num2 =20 if someBoolValue else num1
num1=num2

How can I count the number of matches for a regex?

matcher.find() does not find all matches, only the next match.

Solution for Java 9+

long matches = matcher.results().count();

Solution for Java 8 and older

You'll have to do the following. (Starting from Java 9, there is a nicer solution)

int count = 0;
while (matcher.find())
    count++;

Btw, matcher.groupCount() is something completely different.

Complete example:

import java.util.regex.*;

class Test {
    public static void main(String[] args) {
        String hello = "HelloxxxHelloxxxHello";
        Pattern pattern = Pattern.compile("Hello");
        Matcher matcher = pattern.matcher(hello);

        int count = 0;
        while (matcher.find())
            count++;

        System.out.println(count);    // prints 3
    }
}

Handling overlapping matches

When counting matches of aa in aaaa the above snippet will give you 2.

aaaa
aa
  aa

To get 3 matches, i.e. this behavior:

aaaa
aa
 aa
  aa

You have to search for a match at index <start of last match> + 1 as follows:

String hello = "aaaa";
Pattern pattern = Pattern.compile("aa");
Matcher matcher = pattern.matcher(hello);

int count = 0;
int i = 0;
while (matcher.find(i)) {
    count++;
    i = matcher.start() + 1;
}

System.out.println(count);    // prints 3

Node.js + Nginx - What now?

You can also setup multiple domain with nginx, forwarding to multiple node.js processes.

For example to achieve these:

These ports (4000 and 5000) should be used to listen the app requests in your app code.

/etc/nginx/sites-enabled/domain1

server {
    listen 80;
    listen [::]:80;
    server_name domain1.com;
    access_log /var/log/nginx/domain1.access.log;
    location / {
        proxy_pass    http://127.0.0.1:4000/;
    }
}

In /etc/nginx/sites-enabled/domain2

server {
    listen 80;
    listen [::]:80;
    server_name domain2.com;
    access_log /var/log/nginx/domain2.access.log;
    location / {
        proxy_pass    http://127.0.0.1:5000/;
    }
}

Can't ping a local VM from the host

try to drop the firewall on your laptop and see if there is difference. Maybe Your laptop is firewall blocking some broadcasts that prevents local network name resolution.

How to enable curl in xampp?

1) C:\Program Files\xampp\php\php.ini

2) Uncomment the following line on your php.ini file by removing the semicolon.

;extension=php_curl.dll

3) Restart your apache server.

what is the use of xsi:schemaLocation?

If you go into any of those locations, then you will find what is defined in those schema. For example, it tells you what is the data type of the ini-method key words value.

How to return an array from a function?

It is not possible to return an array from a C++ function. 8.3.5[dcl.fct]/6:

Functions shall not have a return type of type array or function[...]

Most commonly chosen alternatives are to return a value of class type where that class contains an array, e.g.

struct ArrayHolder
{
    int array[10];
};

ArrayHolder test();

Or to return a pointer to the first element of a statically or dynamically allocated array, the documentation must indicate to the user whether he needs to (and if so how he should) deallocate the array that the returned pointer points to.

E.g.

int* test2()
{
    return new int[10];
}

int* test3()
{
    static int array[10];
    return array;
}

While it is possible to return a reference or a pointer to an array, it's exceedingly rare as it is a more complex syntax with no practical advantage over any of the above methods.

int (&test4())[10]
{
        static int array[10];
        return array;
}

int (*test5())[10]
{
        static int array[10];
        return &array;
}

Java SE 6 vs. JRE 1.6 vs. JDK 1.6 - What do these mean?

Java SE Runtime is for end user, so you need Java JRE version, the first version of Java was the 1, then 1.1 - 1.2 - 1.3 - 1.4 - 1.5 - 1.6 etc and usually each version is named by version so JRE 6 means Java jre 1.6, anyway there is the update version, for example 1.6 update 45, which is named java jre 6u45.

From what I know, they preferred to use the number 6 instead using 1.6 to better reflect the level of maturity, stability, scalability, security and more

Turn Pandas Multi-Index into column

I ran into Karl's issue as well. I just found myself renaming the aggregated column then resetting the index.

df = pd.DataFrame(df.groupby(['arms', 'success'])['success'].sum()).rename(columns={'success':'sum'})

enter image description here

df = df.reset_index()

enter image description here

javascript, for loop defines a dynamic variable name

I think you could do it by creating parameters in an object maybe?

var myObject = {}; for(var i=0;i<myArray.length;i++) {     myObject[ myArray[i] ]; } 

If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.

How to register multiple implementations of the same interface in Asp.Net Core?

While the out of the box implementation doesn't offer it, here's a sample project that allows you to register named instances, and then inject INamedServiceFactory into your code and pull out instances by name. Unlike other facory solutions here, it will allow you to register multiple instances of same implementation but configured differently

https://github.com/macsux/DotNetDINamedInstances

Bootstrap modal - close modal when "call to action" button is clicked

Use data-dismiss="modal". In the version of Bootstrap I am using v3.3.5, when data-dismiss="modal" is added to the desired button like shown below it calls my external Javascript (JQuery) function beautifully and magically closes the modal. Its soo Sweet, I was worried I would have to call some modal hide in another function and chain that to the real working function

 <a href="#" id="btnReleaseAll" class="btn btn-primary btn-default btn-small margin-right pull-right" data-dismiss="modal">Yes</a>

In some external script file, and in my doc ready there is of course a function for the click of that identifier ID

 $("#divExamListHeader").on('click', '#btnReleaseAll', function () {
               // Do DatabaseMagic Here for a call a MVC ActionResult

How to install mongoDB on windows?

You might want to check https://github.com/Thor1Khan/mongo.git it uses a minimal workaround the 32 bit atomic operations on 64 bits operands (could use assembly but it doesn't seem to be mandatory here) Only digital bugs were harmed before committing

Color a table row with style="color:#fff" for displaying in an email

Try to use the <font> tag

?<table> 
    <thead> 
        <tr> 
            <th><font color="#FFF">Header 1</font></th> 
            <th><font color="#FFF">Header 1</font></th> 
            <th><font color="#FFF">Header 1</font></th> 
        </tr> 
    </thead> 
    <tbody> 
        <tr> 
            <td>blah blah</td> 
            <td>blah blah</td> 
            <td>blah blah</td> 
        </tr> 
    </tbody> 
</table>

But I think this should work, too:

?<table> 
    <thead> 
        <tr> 
            <th color="#FFF">Header 1</th> 
            <th color="#FFF">Header 1</th> 
            <th color="#FFF">Header 1</th> 
        </tr> 
    </thead> 
    <tbody> 
        <tr> 
            <td>blah blah</td> 
            <td>blah blah</td> 
            <td>blah blah</td> 
        </tr> 
    </tbody> 
</table>

EDIT:

Crossbrowser solution:

use capitals in HEX-color.

<th bgcolor="#5D7B9D" color="#FFFFFF"><font color="#FFFFFF">Header 1</font></th>

VB.NET - If string contains "value1" or "value2"

You need this

If strMyString.Contains("Something") or strMyString.Contains("Something2") Then
    'Code
End if

Trying Gradle build - "Task 'build' not found in root project"

Check your file: settings.gradle for presence lines with included subprojects (for example: include chapter1-bookstore )

Using python PIL to turn a RGB image into a pure black and white image

A PIL only solution for creating a bi-level (black and white) image with a custom threshold:

from PIL import Image
img = Image.open('mB96s.png')
thresh = 200
fn = lambda x : 255 if x > thresh else 0
r = img.convert('L').point(fn, mode='1')
r.save('foo.png')

With just

r = img.convert('1')
r.save('foo.png')

you get a dithered image.

From left to right the input image, the black and white conversion result and the dithered result:

Input Image Black and White Result Dithered Result

You can click on the images to view the unscaled versions.

Prompt Dialog in Windows Forms

There is no such thing natively in Windows Forms.

You have to create your own form for that or:

use the Microsoft.VisualBasic reference.

Inputbox is legacy code brought into .Net for VB6 compatibility - so i advise to not do this.

How to automatically reload a page after a given period of inactivity

use JavaScript setInterval method:

setInterval(function(){ location.reload(); }, 3000);

Custom alert and confirm box in jquery

I made custom messagebox using jquery UI component. Here is demo http://jsfiddle.net/eraj2587/Pm5Fr/14/

You have to pass just the parameters like caption name, message, button's text. You can specify trigger function on any button click. This will helpful for you.

How to get the currently logged in user's user id in Django?

FOR WITHIN TEMPLATES

This is how I usually get current logged in user and their id in my templates.

<p>Your Username is : {{user}} </p>
<p>Your User Id is  : {{user.id}} </p>

Obtain smallest value from array in Javascript?

I think I have an easy-to-understand solution for this, using only the basics of javaScript.

function myFunction() {
            var i = 0;
            var smallestNumber = justPrices[0];
            for(i = 0; i < justPrices.length; i++) {
                if(justPrices[i] < smallestNumber) {
                    smallestNumber = justPrices[i];
                }
            }
            return smallestNumber;
        }

The variable smallestNumber is set to the first element of justPrices, and the for loop loops through the array (I'm just assuming that you know how a for loop works; if not, look it up). If an element of the array is smaller than the current smallestNumber (which at first is the first element), it will replace it's value. When the whole array has gone through the loop, smallestNumber will contain the smallest number in the array.

How to check if bootstrap modal is open, so I can use jquery validate?

Check if a modal is open

$('.modal:visible').length && $('body').hasClass('modal-open')

To attach an event listener

$(document).on('show.bs.modal', '.modal', function () {
    // run your validation... ( or shown.bs.modal )
});

Templated check for the existence of a class member function?

The standard C++ solution presented here by litb will not work as expected if the method happens to be defined in a base class.

For a solution that handles this situation refer to :

In Russian : http://www.rsdn.ru/forum/message/2759773.1.aspx

English Translation by Roman.Perepelitsa : http://groups.google.com/group/comp.lang.c++.moderated/tree/browse_frm/thread/4f7c7a96f9afbe44/c95a7b4c645e449f?pli=1

It is insanely clever. However one issue with this solutiion is that gives compiler errors if the type being tested is one that cannot be used as a base class (e.g. primitive types)

In Visual Studio, I noticed that if working with method having no arguments, an extra pair of redundant ( ) needs to be inserted around the argments to deduce( ) in the sizeof expression.

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

if the service is http.sys

You need to change the binded IP address for http.sys

netsh http add iplisten ipaddress=::

Work fine without restart the os.

Printing without newline (print 'a',) prints a space, how to remove?

WOW!!!

It's pretty long time ago

Now, In python 3.x it will be pretty easy

code:

for i in range(20):
      print('a',end='') # here end variable will clarify what you want in 
                        # end of the code

output:

aaaaaaaaaaaaaaaaaaaa 

More about print() function

print(value1,value2,value3,sep='-',end='\n',file=sys.stdout,flush=False)

Here:

value1,value2,value3

you can print multiple values using commas

sep = '-'

3 values will be separated by '-' character

you can use any character instead of that even string like sep='@' or sep='good'

end='\n'

by default print function put '\n' charater at the end of output

but you can use any character or string by changing end variale value

like end='$' or end='.' or end='Hello'

file=sys.stdout

this is a default value, system standard output

using this argument you can create a output file stream like

print("I am a Programmer", file=open("output.txt", "w"))

by this code you will create a file named output.txt where your output I am a Programmer will be stored

flush = False

It's a default value using flush=True you can forcibly flush the stream

How to join components of a path when you are constructing a URL in Python

I know this is a bit more than the OP asked for, However I had the pieces to the following url, and was looking for a simple way to join them:

>>> url = 'https://api.foo.com/orders/bartag?spamStatus=awaiting_spam&page=1&pageSize=250'

Doing some looking around:

>>> split = urlparse.urlsplit(url)
>>> split
SplitResult(scheme='https', netloc='api.foo.com', path='/orders/bartag', query='spamStatus=awaiting_spam&page=1&pageSize=250', fragment='')
>>> type(split)
<class 'urlparse.SplitResult'>
>>> dir(split)
['__add__', '__class__', '__contains__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__getstate__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_asdict', '_fields', '_make', '_replace', 'count', 'fragment', 'geturl', 'hostname', 'index', 'netloc', 'password', 'path', 'port', 'query', 'scheme', 'username']
>>> split[0]
'https'
>>> split = (split[:])
>>> type(split)
<type 'tuple'>

So in addition to the path joining which has already been answered in the other answers, To get what I was looking for I did the following:

>>> split
('https', 'api.foo.com', '/orders/bartag', 'spamStatus=awaiting_spam&page=1&pageSize=250', '')
>>> unsplit = urlparse.urlunsplit(split)
>>> unsplit
'https://api.foo.com/orders/bartag?spamStatus=awaiting_spam&page=1&pageSize=250'

According to the documentation it takes EXACTLY a 5 part tuple.

With the following tuple format:

scheme 0 URL scheme specifier empty string

netloc 1 Network location part empty string

path 2 Hierarchical path empty string

query 3 Query component empty string

fragment 4 Fragment identifier empty string

How to use sed to remove the last n lines of a file

It can be done in 3 steps:

a) Count the number of lines in the file you want to edit:

 n=`cat myfile |wc -l`

b) Subtract from that number the number of lines to delete:

 x=$((n-3))

c) Tell sed to delete from that line number ($x) to the end:

 sed "$x,\$d" myfile

Reading NFC Tags with iPhone 6 / iOS 8

At the moment, Apple has not opened any access to the embedded NFC chip to developers as suggested by many articles such as these ones :

The list goes on. The main reason seems (like lots the other hardware features added to the iPhone in the past) that Apple wants to ensure the security of such technology before releasing any API for developers to let them do whatever they want. So at first, they will use it internally for their needs only (such as Apple Pay at launch time).

"At the moment, there isn't any open access to the NFC controller," said RapidNFC, a provider of NFC tags. "There are currently no NFC APIs in the iOS 8 GM SDK".

But eventually, I think we can all agree that they will develop such API, it's only a matter of time.

How to rotate a 3D object on axis three.js?

Just in case...in r52 the method is called setEulerFromRotationMatrix instead of getRotationFromMatrix

LINQ query to find if items in a list are contained in another list

List<string> test1 = new List<string> { "@bob.com", "@tom.com" };
List<string> test2 = new List<string> { "[email protected]", "[email protected]", "[email protected]" };

var result = (from t2 in test2
              where test1.Any(t => t2.Contains(t)) == false
              select t2);

If query form is what you want to use, this is legible and more or less as "performant" as this could be.

What i mean is that what you are trying to do is an O(N*M) algorithm, that is, you have to traverse N items and compare them against M values. What you want is to traverse the first list only once, and compare against the other list just as many times as needed (worst case is when the email is valid since it has to compare against every black listed domain).

from t2 in test we loop the email list once.

test1.Any(t => t2.Contains(t)) == false we compare with the blacklist and when we found one match return (hence not comparing against the whole list if is not needed)

select t2 keep the ones that are clean.

So this is what I would use.

Open a local HTML file using window.open in Chrome

First, make sure that the source page and the target page are both served through the file URI scheme. You can't force an http page to open a file page (but it works the other way around).

Next, your script that calls window.open() should be invoked by a user-initiated event, such as clicks, keypresses and the like. Simply calling window.open() won't work.

You can test this right here in this question page. Run these in Chrome's JavaScript console:

// Does nothing
window.open('http://google.com');

// Click anywhere within this page and the new window opens
$(document.body).unbind('click').click(function() { window.open('http://google.com'); });

// This will open a new window, but it would be blank
$(document.body).unbind('click').click(function() { window.open('file:///path/to/a/local/html/file.html'); });

You can also test if this works with a local file. Here's a sample HTML file that simply loads jQuery:

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
    </head>
    <body>
        <h5>Feel the presha</h5>
        <h3>Come play my game, I'll test ya</h3>
        <h1>Psycho- somatic- addict- insane!</h1>
    </body>
</html>

Then open Chrome's JavaScript console and run the statements above. The 3rd one will now work.

SCP Permission denied (publickey). on EC2 only when using -r flag on directories

If you want to upload the file /Applications/XAMPP/htdocs/keypairfile.pem to ec2-user@publicdns:/var/www/html, you can simply do:

scp -Cr /Applications/XAMPP/htdocs/keypairfile.pem/uploads/ ec2-user@publicdns:/var/www/html/

Where:

  • -C - Compress data
  • -r - Recursive

Can I pass a JavaScript variable to another browser window?

One can pass a message from the 'parent' window to the 'child' window:

in the 'parent window' open the child

    var win = window.open(<window.location.href>, '_blank');    
       setTimeout(function(){
                    win.postMessage(SRFBfromEBNF,"*")
                  },1000);
    win.focus();

the to be replaced according to the context

In the 'child'

    window.addEventListener('message', function(event) {
        if(event.srcElement.location.href==window.location.href){
        /* do what you want with event.data */
        }
    }); 

The if test must be changed according to the context

How prevent CPU usage 100% because of worker process in iis

If it is not necessary turn off 'Enable 32-bit Applications' from your respective application pool of your website.

This worked for me on my local machine

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325

Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.

Make sure that you have checked it to work properly with the IE version you specify.

How do I collapse sections of code in Visual Studio Code for Windows?

If none of the shortcuts are working (like for me), as a workaround you can also open the command palette (Ctrl + 3 or View -> Command Palette...) and type in fold all:

enter image description here

Looping through a hash, or using an array in PowerShell

You can also do this without a variable

@{
  'foo' = 222
  'bar' = 333
  'baz' = 444
  'qux' = 555
} | % getEnumerator | % {
  $_.key
  $_.value
}

How do I pass a variable to the layout using Laravel' Blade templating?

Simplest way to solve:

view()->share('title', 'My Title Here');

Or using view Facade:

use View;

...

View::share('title', 'My Title Here');

Change MySQL default character set to UTF-8 in my.cnf?

I also have found out that after setting default-character-set = utf8 under [mysqld] title, MySQL 5.5.x would not start under Ubuntu 12.04 (Precise Pangolin).

How to declare a global variable in JavaScript

If you have to generate global variables in production code (which should be avoided) always declare them explicitly:

window.globalVar = "This is global!";

While it is possible to define a global variable by just omitting var (assuming there is no local variable of the same name), doing so generates an implicit global, which is a bad thing to do and would generate an error in strict mode.

Stop a youtube video with jquery?

Simple like that.

include the following line in the function to close pop.

$('#youriframeid').remove();

How do I use Ruby for shell scripting?

There's a lot of good advice here, so I wanted to add a tiny bit more.

  1. Backticks (or back-ticks) let you do some scripting stuff a lot easier. Consider

    puts `find . | grep -i lib`
    
  2. If you run into problems with getting the output of backticks, the stuff is going to standard err instead of standard out. Use this advice

    out = `git status 2>&1`
    
  3. Backticks do string interpolation:

    blah = 'lib'
    `touch #{blah}`
    
  4. You can pipe inside Ruby, too. It's a link to my blog, but it links back here so it's okay :) There are probably more advanced things out there on this topic.

  5. As other people noted, if you want to get serious there is Rush: not just as a shell replacement (which is a bit too zany for me) but also as a library for your use in shell scripts and programs.


On Mac, Use Applescript inside Ruby for more power. Here's my shell_here script:

#!/usr/bin/env ruby
`env | pbcopy` 
cmd =  %Q@tell app "Terminal" to do script "$(paste_env)"@
puts cmd

`osascript -e "${cmd}"`

INSERT INTO TABLE from comma separated varchar-list

Something like this should work:

INSERT INTO #IMEIS (imei) VALUES ('val1'), ('val2'), ...

UPDATE:

Apparently this syntax is only available starting on SQL Server 2008.

How do I use tools:overrideLibrary in a build.gradle file?

Open Android Studio -> Open Manifest File

add <uses-sdk tools:overrideLibrary="android.support.v17.leanback"/> don't forget to include xmlns:tools="http://schemas.android.com/tools" too, before the <application> tag

enter image description here

When can I use a forward declaration?

Put yourself in the compiler's position: when you forward declare a type, all the compiler knows is that this type exists; it knows nothing about its size, members, or methods. This is why it's called an incomplete type. Therefore, you cannot use the type to declare a member, or a base class, since the compiler would need to know the layout of the type.

Assuming the following forward declaration.

class X;

Here's what you can and cannot do.

What you can do with an incomplete type:

  • Declare a member to be a pointer or a reference to the incomplete type:

    class Foo {
        X *p;
        X &r;
    };
    
  • Declare functions or methods which accept/return incomplete types:

    void f1(X);
    X    f2();
    
  • Define functions or methods which accept/return pointers/references to the incomplete type (but without using its members):

    void f3(X*, X&) {}
    X&   f4()       {}
    X*   f5()       {}
    

What you cannot do with an incomplete type:

  • Use it as a base class

    class Foo : X {} // compiler error!
    
  • Use it to declare a member:

    class Foo {
        X m; // compiler error!
    };
    
  • Define functions or methods using this type

    void f1(X x) {} // compiler error!
    X    f2()    {} // compiler error!
    
  • Use its methods or fields, in fact trying to dereference a variable with incomplete type

    class Foo {
        X *m;            
        void method()            
        {
            m->someMethod();      // compiler error!
            int i = m->someField; // compiler error!
        }
    };
    

When it comes to templates, there is no absolute rule: whether you can use an incomplete type as a template parameter is dependent on the way the type is used in the template.

For instance, std::vector<T> requires its parameter to be a complete type, while boost::container::vector<T> does not. Sometimes, a complete type is required only if you use certain member functions; this is the case for std::unique_ptr<T>, for example.

A well-documented template should indicate in its documentation all the requirements of its parameters, including whether they need to be complete types or not.

How can I strip HTML tags from a string in ASP.NET?

If it is just stripping all HTML tags from a string, this works reliably with regex as well. Replace:

<[^>]*(>|$)

with the empty string, globally. Don't forget to normalize the string afterwards, replacing:

[\s\r\n]+

with a single space, and trimming the result. Optionally replace any HTML character entities back to the actual characters.

Note:

  1. There is a limitation: HTML and XML allow > in attribute values. This solution will return broken markup when encountering such values.
  2. The solution is technically safe, as in: The result will never contain anything that could be used to do cross site scripting or to break a page layout. It is just not very clean.
  3. As with all things HTML and regex:
    Use a proper parser if you must get it right under all circumstances.

Regular Expression for alphanumeric and underscores

You want to check that each character matches your requirements, which is why we use:

[A-Za-z0-9_]

And you can even use the shorthand version:

\w

Which is equivalent (in some regex flavors, so make sure you check before you use it). Then to indicate that the entire string must match, you use:

^

To indicate the string must start with that character, then use

$

To indicate the string must end with that character. Then use

\w+ or \w*

To indicate "1 or more", or "0 or more". Putting it all together, we have:

^\w*$

How to Migrate to WKWebView?

Use some design patterns, you can mix UIWebView and WKWebView. The key point is to design a unique browser interface. But you should pay more attention to your app's current functionality, for example: if your app using NSURLProtocol to enhance network ability, using WKWebView you have no chance to do the same thing. Because NSURLProtocol only effects the current process, and WKWebView using muliti-process architecture, the networking staff is in a seperate process.

Get a CSS value with JavaScript

You can use getComputedStyle().

var element = document.getElementById('image_1'),
    style = window.getComputedStyle(element),
    top = style.getPropertyValue('top');

jsFiddle.

How to include a class in PHP

Your code should be something like

require_once('class.twitter.php');

$t = new twitter;
$t->username = 'user';
$t->password = 'password';

$data = $t->publicTimeline();

boolean in an if statement

In general, it is cleaner and simpler to omit the === true.

However, in Javascript, those statements are different.

if (booleanValue) will execute if booleanValue is truthy – anything other than 0, false, '', NaN, null, and undefined.

if (booleanValue === true) will only execute if booleanValue is precisely equal to true.

Python: pandas merge multiple dataframes

functools.reduce and pd.concat are good solutions but in term of execution time pd.concat is the best.

from functools import reduce
import pandas as pd

dfs = [df1, df2, df3, ...]
nan_value = 0

# solution 1 (fast)
result_1 = pd.concat(dfs, join='outer', axis=1).fillna(nan_value)

# solution 2
result_2 = reduce(lambda df_left,df_right: pd.merge(df_left, df_right, 
                                              left_index=True, right_index=True, 
                                              how='outer'), 
                  dfs).fillna(nan_value)

how to change any data type into a string in python

str is meant to produce a string representation of the object's data. If you're writing your own class and you want str to work for you, add:

def __str__(self):
    return "Some descriptive string"

print str(myObj) will call myObj.__str__().

repr is a similar method, which generally produces information on the class info. For most core library object, repr produces the class name (and sometime some class information) between angle brackets. repr will be used, for example, by just typing your object into your interactions pane, without using print or anything else.

You can define the behavior of repr for your own objects just like you can define the behavior of str:

def __repr__(self):
    return "Some descriptive string"

>>> myObj in your interactions pane, or repr(myObj), will result in myObj.__repr__()

Converting HTML to plain text in PHP for e-mail

For texts in utf-8, it worked for me mb_convert_encoding. To process everything regardless of errors, make sure you use the "@".

The basic code I use is:

$dom = new DOMDocument();
@$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));

$body = $dom->getElementsByTagName('body')->item(0);
echo $body->textContent;

If you want something more advanced, you can iteratively analyze the nodes, but you will encounter many problems with whitespaces.

I have implemented a converter based on what I say here. If you are interested, you can download it from git https://github.com/kranemora/html2text

It may serve as a reference to make yours

You can use it like this:

$html = <<<EOF
<p>Welcome to <strong>html2text<strong></p>
<p>It's <em>works</em> for you?</p>
EOF;

$html2Text = new \kranemora\Html2Text\Html2Text;
$text = $html2Text->convert($html);

"The public type <<classname>> must be defined in its own file" error in Eclipse

I had two significant errors in my program. From the other answers, I learned in a single java program, one can not declare two classes as "public". So I changed the access specifier, but got another error as added to my question as "EDIT" that "Selection does not contain a main type". Finally I observed I forgot to add "String args[]" part in my main method. That's why the code was not working. After rectification, it worked as expected.

Copy Paste Values only( xlPasteValues )

Personally, I would shorten it a touch too if all you need is the columns:

For i = LBound(arr1) To UBound(arr1)
    Sheets("SheetA").Columns(arr1(i)).Copy
    Sheets("SheetB").Columns(arr2(i)).PasteSpecial xlPasteValues
    Application.CutCopyMode = False
Next

as from this code snippet, there isnt much point in lastrow or firstrowDB

calling a java servlet from javascript

So you want to fire Ajax calls to the servlet? For that you need the XMLHttpRequest object in JavaScript. Here's a Firefox compatible example:

<script>
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var data = xhr.responseText;
            alert(data);
        }
    }
    xhr.open('GET', '${pageContext.request.contextPath}/myservlet', true);
    xhr.send(null);
</script>

This is however very verbose and not really crossbrowser compatible. For the best crossbrowser compatible way of firing ajaxical requests and traversing the HTML DOM tree, I recommend to grab jQuery. Here's a rewrite of the above in jQuery:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    $.get('${pageContext.request.contextPath}/myservlet', function(data) {
        alert(data);
    });
</script>

Either way, the Servlet on the server should be mapped on an url-pattern of /myservlet (you can change this to your taste) and have at least doGet() implemented and write the data to the response as follows:

String data = "Hello World!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);

This should show Hello World! in the JavaScript alert.

You can of course also use doPost(), but then you should use 'POST' in xhr.open() or use $.post() instead of $.get() in jQuery.

Then, to show the data in the HTML page, you need to manipulate the HTML DOM. For example, you have a

<div id="data"></div>

in the HTML where you'd like to display the response data, then you can do so instead of alert(data) of the 1st example:

document.getElementById("data").firstChild.nodeValue = data;

In the jQuery example you could do this in a more concise and nice way:

$('#data').text(data);

To go some steps further, you'd like to have an easy accessible data format to transfer more complex data. Common formats are XML and JSON. For more elaborate examples on them, head to How to use Servlets and Ajax?

How to convert a file into a dictionary?

I had a requirement to take values from text file and use as key value pair. i have content in text file as key = value, so i have used split method with separator as "=" and wrote below code

d = {}
file = open("filename.txt")
for x in file:
    f = x.split("=")
    d.update({f[0].strip(): f[1].strip()})

By using strip method any spaces before or after the "=" separator are removed and you will have the expected data in dictionary format

Work on a remote project with Eclipse via SSH

Try the Remote System Explorer (RSE). It's a set of plug-ins to do exactly what you want.

RSE may already be included in your current Eclipse installation. To check in Eclipse Indigo go to Window > Open Perspective > Other... and choose Remote System Explorer from the Open Perspective dialog to open the RSE perspective.

To create an SSH remote project from the RSE perspective in Eclipse:

  1. Define a new connection and choose SSH Only from the Select Remote System Type screen in the New Connection dialog.
  2. Enter the connection information then choose Finish.
  3. Connect to the new host. (Assumes SSH keys are already setup.)
  4. Once connected, drill down into the host's Sftp Files, choose a folder and select Create Remote Project from the item's context menu. (Wait as the remote project is created.)

If done correctly, there should now be a new remote project accessible from the Project Explorer and other perspectives within eclipse. With the SSH connection set-up correctly passwords can be made an optional part of the normal SSH authentication process. A remote project with Eclipse via SSH is now created.

Getting the SQL from a Django QuerySet

Easy:

print my_queryset.query

For example:

from django.contrib.auth.models import User
print User.objects.filter(last_name__icontains = 'ax').query

It should also be mentioned that if you have DEBUG = True, then all of your queries are logged, and you can get them by accessing connection.queries:

from django.db import connections
connections['default'].queries

The django debug toolbar project uses this to present the queries on a page in a neat manner.

Get local IP address in Node.js

Install a module called ip like:

npm install ip

Then use this code:

var ip = require("ip");
console.log(ip.address());

(WAMP/XAMP) send Mail using SMTP localhost

I prefer using PHPMailer script to send emails from localhost as it lets me use my Gmail account as SMTP. You can find the PHPMailer from http://phpmailer.worxware.com/ . Help regarding how to use gmail as SMTP or any other SMTP can be found at http://www.mittalpatel.co.in/php_send_mail_from_localhost_using_gmail_smtp . Hope this helps!

What's the algorithm to calculate aspect ratio?

bit of a strange way to do this but use the resolution as the aspect. E.G.

1024:768

or you can try

var w = screen.width;
var h = screen.height;
for(var i=1,asp=w/h;i<5000;i++){
  if(asp*i % 1==0){
    i=9999;
    document.write(asp*i,":",1*i);
  }
}

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

DateTime.MinValue and DateTime.MaxValue

DateTime.MinValue = 1/1/0001 12:00:00 AM

DateTime.MaxValue = 23:59:59.9999999, December 31, 9999, 

                exactly one 100-nanosecond tick 

                before 00:00:00, January 1, 10000 

Why doesn't git recognize that my file has been changed, therefore git add not working

Check your .gitignore file. You may find that the file, or extension of the file, or path to the file you are trying to work with matches an entry in .gitignore, which would explain why that file is being ignored (and not recognized as a changed file).

This turned out to be the case for me when I had a similar problem.

WPF C# button style

Here's my attempt. Looks more similar to the OP's sample and provides settable properties for icon (FrameworkElement), title (string) and subtitle (string). The output looks like this:

enter image description here

Here's XAML:

<Button x:Class="Controls.FancyButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Controls"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300" Width="300" Height="80"
          BorderBrush="{x:Null}" BorderThickness="0">
  <Button.Effect>
    <DropShadowEffect BlurRadius="12" Color="Gray" Direction="270" Opacity=".8" ShadowDepth="3" />
  </Button.Effect>

  <Button.Template>
    <ControlTemplate TargetType="Button">
      <Grid Width="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=ActualWidth}"
        Height="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=ActualHeight}">

        <Border x:Name="MainBorder" CornerRadius="3" Grid.ColumnSpan="2" Margin="0,0,4,4" BorderBrush="Black" BorderThickness="1">
          <Border.Background>
            <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
              <GradientStop Color="#FF5E5E5E" Offset="0" />
              <GradientStop Color="#FF040404" Offset="1" />
            </LinearGradientBrush>
          </Border.Background>

          <Grid >
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="1.2*"/>
              <ColumnDefinition Width="3*"/>
            </Grid.ColumnDefinitions>

            <Border CornerRadius="2" Margin="0" BorderBrush="LightGray" BorderThickness="0,1,0,0" Grid.ColumnSpan="2" Grid.RowSpan="2" />

            <Line X1="10" Y1="0" X2="10" Y2="10" Stretch="Fill" Grid.Column="0" HorizontalAlignment="Right" Stroke="#0C0C0C" Grid.RowSpan="2" />
            <Line X1="10" Y1="0" X2="10" Y2="10" Stretch="Fill" Grid.Column="1" HorizontalAlignment="Left" Grid.RowSpan="2">
              <Line.Stroke>
                <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                  <GradientStop Color="#4D4D4D" Offset="0" />
                  <GradientStop Color="#2C2C2C" Offset="1" />
                </LinearGradientBrush>
              </Line.Stroke>
            </Line>

            <ContentControl HorizontalAlignment="Center" VerticalAlignment="Center" Grid.RowSpan="2">
              <ContentControl.Content>
                <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Image">
                  <Binding.FallbackValue>
                    <Path Data="M0,0 L30,15 L0,30Z">
                      <Path.Effect>
                        <DropShadowEffect Direction="50" ShadowDepth="2" />
                      </Path.Effect>
                      <Path.Fill>
                        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
                          <GradientStop Color="#4B86B2" Offset="0" />
                          <GradientStop Color="#477FA8" Offset="1" />
                        </LinearGradientBrush>
                      </Path.Fill>
                    </Path>
                  </Binding.FallbackValue>
                </Binding>
              </ContentControl.Content>
            </ContentControl>


            <Grid Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center">
              <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
              </Grid.RowDefinitions>

              <TextBlock x:Name="Title" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Title, FallbackValue='Watch Now'}" Grid.Column="1" VerticalAlignment="Bottom" FontFamily="Calibri" FontWeight="Bold" FontSize="28" Foreground="White" Margin="20,0,0,0" />
              <TextBlock x:Name="SubTitle" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SubTitle, FallbackValue='Duration: 50 min'}" Grid.Column="1" Grid.Row="1" VerticalAlignment="top" FontFamily="Calibri" FontSize="14" Foreground="White" Margin="20,0,0,0" />
            </Grid>
          </Grid>
        </Border>
      </Grid>

      <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
          <Setter TargetName="Title" Property="TextDecorations" Value="Underline" />
          <Setter TargetName="SubTitle" Property="TextDecorations" Value="Underline" />
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
          <Setter TargetName="MainBorder" Property="Background">
            <Setter.Value>
              <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                <GradientStop Color="#FF5E5E5E" Offset="0" />
                <GradientStop Color="#FFA4A4A4" Offset="1" />
              </LinearGradientBrush>
            </Setter.Value>
          </Setter>
        </Trigger>
      </ControlTemplate.Triggers>
    </ControlTemplate>
  </Button.Template>
</Button>

Here's the code-behind:

using System.Windows;
using System.Windows.Controls;

namespace Controls
{
  public partial class FancyButton : Button
  {
    public FancyButton()
    {
      InitializeComponent();
    }

    public string Title
    {
      get { return (string)GetValue(TitleProperty); }
      set { SetValue(TitleProperty, value); }
    }

    public static readonly DependencyProperty TitleProperty =
        DependencyProperty.Register("Title", typeof(string), typeof(FancyButton), new FrameworkPropertyMetadata("Title", FrameworkPropertyMetadataOptions.AffectsRender));

    public string SubTitle
    {
      get { return (string)GetValue(SubTitleProperty); }
      set { SetValue(SubTitleProperty, value); }
    }

    public static readonly DependencyProperty SubTitleProperty =
        DependencyProperty.Register("SubTitle", typeof(string), typeof(FancyButton), new FrameworkPropertyMetadata("SubTitle", FrameworkPropertyMetadataOptions.AffectsRender));

    public FrameworkElement Image
    {
      get { return (FrameworkElement)GetValue(ImageProperty); }
      set { SetValue(ImageProperty, value); }
    }

    public static readonly DependencyProperty ImageProperty =
        DependencyProperty.Register("Image", typeof(FrameworkElement), typeof(FancyButton), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
  }
}

Here is how to use it:

<controls:FancyButton Grid.Row="1" HorizontalAlignment="Right" Margin="3" Title="Watch Now" SubTitle="Duration: 50 min">
  <controls:FancyButton.Image>
    <Path Data="M0,0 L30,15 L0,30Z">
      <Path.Effect>
        <DropShadowEffect Direction="50" ShadowDepth="2" />
      </Path.Effect>
      <Path.Fill>
        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
          <GradientStop Color="#4B86B2" Offset="0" />
          <GradientStop Color="#477FA8" Offset="1" />
        </LinearGradientBrush>
      </Path.Fill>
    </Path>
  </controls:FancyButton.Image>
</controls:FancyButton>

Running Tensorflow in Jupyter Notebook

It is better to create new environment with new name ($newenv):conda create -n $newenv tensorflow

Then by using anaconda navigator under environment tab you can find newenv in the middle column.

By clicking on the play button open terminal and type: activate tensorflow

Then install tensorflow inside the newenv by typing: pip install tensorflow

Now you have tensorflow inside the new environment so then install jupyter by typing: pip install jupyter notebook

Then just simply type: jupyter notebook to run the jupyter notebook.

Inside of the jupyter notebook type: import tensorflow as tf

To test the the tf you can use THIS LINK

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

How do I delete a Git branch locally and remotely?

If you want to delete a branch, first checkout to the branch other than the branch to be deleted.

git checkout other_than_branch_to_be_deleted

Deleting the local branch:

git branch -D branch_to_be_deleted

Deleting the remote branch:

git push origin --delete branch_to_be_deleted

Fitting a Normal distribution to 1D data

Here you are not fitting a normal distribution. Replacing sns.distplot(data) by sns.distplot(data, fit=norm, kde=False) should do the trick.

How do I clone into a non-empty directory?

This worked for me:

git init
git remote add origin PATH/TO/REPO
git fetch
git reset origin/master  # Required when the versioned files existed in path before "git init" of this repo.
git checkout -t origin/master

NOTE: -t will set the upstream branch for you, if that is what you want, and it usually is.

Make page to tell browser not to cache/preserve input values

This worked for me in newer browsers:

autocomplete="new-password"

Difference between VARCHAR and TEXT in MySQL

There is an important detail that has been omitted in the answer above.

MySQL imposes a limit of 65,535 bytes for the max size of each row. The size of a VARCHAR column is counted towards the maximum row size, while TEXT columns are assumed to be storing their data by reference so they only need 9-12 bytes. That means even if the "theoretical" max size of your VARCHAR field is 65,535 characters you won't be able to achieve that if you have more than one column in your table.

Also note that the actual number of bytes required by a VARCHAR field is dependent on the encoding of the column (and the content). MySQL counts the maximum possible bytes used toward the max row size, so if you use a multibyte encoding like utf8mb4 (which you almost certainly should) it will use up even more of your maximum row size.

Correction: Regardless of how MySQL computes the max row size, whether or not the VARCHAR/TEXT field data is ACTUALLY stored in the row or stored by reference depends on your underlying storage engine. For InnoDB the row format affects this behavior. (Thanks Bill-Karwin)

Reasons to use TEXT:

  • If you want to store a paragraph or more of text
  • If you don't need to index the column
  • If you have reached the row size limit for your table

Reasons to use VARCHAR:

  • If you want to store a few words or a sentence
  • If you want to index the (entire) column
  • If you want to use the column with foreign-key constraints

Vertical align text in block element

According to the CSS Flexible Box Layout Module, you can declare the a element as a flex container (see figure) and use align-items to vertically align text along the cross axis (which is perpendicular to the main axis).

enter image description here

All you need to do is:

display: flex;
align-items: center;

See this fiddle.

Add element to a JSON file?

You can do this.

data[0]['f'] = var

$(document).ready not Working

Instead of using this:

$(document).ready(function() { /* your code */ });

Use this:

jQuery(function($) { /* your code */ })(jQuery);

It is more concise and does the same thing, it also doesn't depend on the $ variable to be the jQuery object.

How do I make a redirect in PHP?

You can attempt to use the PHP header function to do the redirect. You will want to set the output buffer so your browser doesn't throw a redirect warning to the screen.

ob_start();
header("Location: " . $website);
ob_end_flush();

SQL Server ORDER BY date and nulls last

A bit late, but maybe someone finds it useful.

For me, ISNULL was out of question due to the table scan. UNION ALL would need me to repeat a complex query, and due to me selecting only the TOP X it would not have been very efficient.

If you are able to change the table design, you can:

  1. Add another field, just for sorting, such as Next_Contact_Date_Sort.

  2. Create a trigger that fills that field with a large (or small) value, depending on what you need:

    CREATE TRIGGER FILL_SORTABLE_DATE ON YOUR_TABLE AFTER INSERT,UPDATE AS 
    BEGIN
        SET NOCOUNT ON;
        IF (update(Next_Contact_Date)) BEGIN
        UPDATE YOUR_TABLE SET Next_Contact_Date_Sort=IIF(YOUR_TABLE.Next_Contact_Date IS NULL, 99/99/9999, YOUR_TABLE.Next_Contact_Date_Sort) FROM inserted i WHERE YOUR_TABLE.key1=i.key1 AND YOUR_TABLE.key2=i.key2
        END
    END
    

Unity 2d jumping script

Use Addforce() method of a rigidbody compenent, make sure rigidbody is attached to the object and gravity is enabled, something like this

gameObj.rigidbody2D.AddForce(Vector3.up * 10 * Time.deltaTime); or 
gameObj.rigidbody2D.AddForce(Vector3.up * 1000); 

See which combination and what values matches your requirement and use accordingly. Hope it helps

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

Time ( 'now', 'localtime' ) and Date ( 'now', 'localtime' ) works.

How to find the last day of the month from date?

if you want to go back few months you can do something like this as well.

 $list = [
        0, 1, 2, 3
    ];

    $date = new \Datetime();
    $dates = [];
    foreach($list as $item)
    {

        $set = clone $date;
        $set->modify("-$item month ");
       $dates[] = $set->modify("last day of this month");
       
    }
    return $dates;

Html code as IFRAME source rather than a URL

According to W3Schools, HTML 5 lets you do this using a new "srcdoc" attribute, but the browser support seems very limited.

WHERE Clause to find all records in a specific month

As an alternative to the MONTH and YEAR functions, a regular WHERE clause will work too:

select *
from yourtable
where '2009-01-01' <= datecolumn and datecolumn < '2009-02-01'

What is RSS and VSZ in Linux memory management

They are not managed, but measured and possibly limited (see getrlimit system call, also on getrlimit(2)).

RSS means resident set size (the part of your virtual address space sitting in RAM).

You can query the virtual address space of process 1234 using proc(5) with cat /proc/1234/maps and its status (including memory consumption) thru cat /proc/1234/status

add a string prefix to each value in a string column using Pandas

You can use pandas.Series.map :

df['col'].map('str{}'.format)

It will apply the word "str" before all your values.

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

check both tables has same schema InnoDB MyISAM. I made them all the same in my case InnoDB and worked

Can I find events bound on an element with jQuery?

General case:

  • Hit F12 to open Dev Tools
  • Click the Sources tab
  • On right-hand side, scroll down to Event Listener Breakpoints, and expand tree
  • Click on the events you want to listen for.
  • Interact with the target element, if they fire you will get a break point in the debugger

Similarly, you can:

  • right click on the target element -> select "Inspect element"
  • Scroll down on the right side of the dev frame, at the bottom is 'event listeners'.
  • Expand the tree to see what events are attached to the element. Not sure if this works for events that are handled through bubbling (I'm guessing not)

Force HTML5 youtube video

I've found the solution :

You have to add the html5=1 in the src attribute of the iframe :

<iframe src="http://www.youtube.com/embed/dP15zlyra3c?html5=1"></iframe>

The video will be displayed as HTML5 if available, or fallback into flash player.

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

The suggested causes are now proven to be mostly impossible. I'm running SSMS V17.9.2 against SS 2014 and still have the problem. Memory problems have existed with this tool since at least 2006 when I started using SSMS.

Yes, MS 'wants' to get rid of diagramming but users won't let them. I have a feeling they will never fix any of these issues because they want users to be so fed up with the tool that enough of them quit using it and they can abandon it entirely.

Restarting is still a workaround if you can stand doing so numerous times per day.

Change value of input onchange?

You can't access your fieldname as a global variable. Use document.getElementById:

function updateInput(ish){
    document.getElementById("fieldname").value = ish;
}

and

onchange="updateInput(this.value)"

Remove menubar from Electron app

For Electron 7.1.1, you can use this:

const {app, BrowserWindow, Menu} = require('electron')
Menu.setApplicationMenu(false)

while EOF in JAVA?

To read a file Scanner class is recommended.

    Scanner scanner = new Scanner(new FileInputStream(fFileName), fEncoding);
    try {
      while (scanner.hasNextLine()){
         System.out.println(scanner.nextLine());
      }
    }
    finally{
      scanner.close();
    }

How to get position of a certain element in strings vector, to use it as an index in ints vector?

To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin() from the iterator:

ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();

Now you need to check pos against Names.size() to see if it is out of bounds or not:

if(pos >= Names.size()) {
    //old_name_ not found
}

vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.

Starting with C++11 you can use std::distance in place of subtraction for both iterators and pointers:

ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));

range() for floats

I used to use numpy.arange but had some complications controlling the number of elements it returns, due to floating point errors. So now I use linspace, e.g.:

>>> import numpy
>>> numpy.linspace(0, 10, num=4)
array([  0.        ,   3.33333333,   6.66666667,  10.        ])

Removing an item from a select box

I found two pages that seem helpful, it's written for ASP.Net, but the same stuff should apply:

  1. How to add/remove items from a dropdown list using jQuery
  2. jQuery selector expressions

SQL How to remove duplicates within select query?

Select Distinct CAST(FLOOR( CAST(start_date AS FLOAT ) )AS DATETIME) from Table

Best way to encode text data for XML

XmlTextWriter.WriteString() does the escaping.

How to create a signed APK file using Cordova command line interface?

On Mac (osx), I generated two .sh files, one for the first publication and another one for updating :

#!/bin/sh
echo "Ionic to Signed APK ---- [email protected] // Benjamin Rathelot\n"
printf "Project dir : "
read DIR
printf "Project key alias : "
read ALIAS
cd $DIR/
cordova build --release android
cd platforms/android/build/outputs/apk/
keytool -genkey -v -keystore my-release-key.keystore -alias $ALIAS -keyalg RSA -keysize 2048 -validity 10000
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore android-release-unsigned.apk $ALIAS
zipalign -v 4 android-release-unsigned.apk signedApk.apk

And to update your app:

#!/bin/sh
echo "Ionic to Signed APK ---- [email protected] // Benjamin Rathelot\n"
printf "Project dir : "
read DIR
printf "Project key alias : "
read ALIAS
cd $DIR/
cordova build --release android
cd platforms/android/build/outputs/apk/
rm signedApk.apk
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore android-release-unsigned.apk $ALIAS
zipalign -v 4 android-release-unsigned.apk signedApk.apk

Assuming you're in your home folder or a folder topping your apps folders. Make sure to set correctly chmod to use this script. Then :

./ionicToApk.sh # or whatever depending of the name of your file, in CLI

Your signed apk will be in Your App folder/platforms/android/build/outputs/apk/ as SignedApk.apk Make sure to use the correct key alias and password defined with the first script