Programs & Examples On #Relative date

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

Easiest way to copy a table from one database to another?

Try mysqldbcopy (documentation)

Or you can create a "federated table" on your target host. Federated tables allow you to see a table from a different database server as if it was a local one. (documentation)

After creating the federated table, you can copy data with the usual insert into TARGET select * from SOURCE

Find the paths between two given nodes?

Dijkstra's algorithm applies more to weighted paths and it sounds like the poster was wanting to find all paths, not just the shortest.

For this application, I'd build a graph (your application sounds like it wouldn't need to be directed) and use your favorite search method. It sounds like you want all paths, not just a guess at the shortest one, so use a simple recursive algorithm of your choice.

The only problem with this is if the graph can be cyclic.

With the connections:

  • 1, 2
  • 1, 3
  • 2, 3
  • 2, 4

While looking for a path from 1->4, you could have a cycle of 1 -> 2 -> 3 -> 1.

In that case, then I'd keep a stack as traversing the nodes. Here's a list with the steps for that graph and the resulting stack (sorry for the formatting - no table option):

current node (possible next nodes minus where we came from) [stack]

  1. 1 (2, 3) [1]
  2. 2 (3, 4) [1, 2]
  3. 3 (1) [1, 2, 3]
  4. 1 (2, 3) [1, 2, 3, 1] //error - duplicate number on the stack - cycle detected
  5. 3 () [1, 2, 3] // back-stepped to node three and popped 1 off the stack. No more nodes to explore from here
  6. 2 (4) [1, 2] // back-stepped to node 2 and popped 1 off the stack.
  7. 4 () [1, 2, 4] // Target node found - record stack for a path. No more nodes to explore from here
  8. 2 () [1, 2] //back-stepped to node 2 and popped 4 off the stack. No more nodes to explore from here
  9. 1 (3) [1] //back-stepped to node 1 and popped 2 off the stack.
  10. 3 (2) [1, 3]
  11. 2 (1, 4) [1, 3, 2]
  12. 1 (2, 3) [1, 3, 2, 1] //error - duplicate number on the stack - cycle detected
  13. 2 (4) [1, 3, 2] //back-stepped to node 2 and popped 1 off the stack
  14. 4 () [1, 3, 2, 4] Target node found - record stack for a path. No more nodes to explore from here
  15. 2 () [1, 3, 2] //back-stepped to node 2 and popped 4 off the stack. No more nodes
  16. 3 () [1, 3] // back-stepped to node 3 and popped 2 off the stack. No more nodes
  17. 1 () [1] // back-stepped to node 1 and popped 3 off the stack. No more nodes
  18. Done with 2 recorded paths of [1, 2, 4] and [1, 3, 2, 4]

Visual c++ can't open include file 'iostream'

quick fix for small programs:

add: #include <cstdlib>

how to set start page in webconfig file in asp.net c#

You can achieve it by code also, In you Global.asax file in Session_Start event write response.redirect to your start page like following.

void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started

            Response.Redirect("~/Index.aspx");

        }

You can get redirect page name from database or any other storage to change the application start page while application is running no need to edit web.config or change any IIS settings

Android - Pulling SQlite database android device

On a rooted device you can:

// check that db is there
>adb shell
# ls /data/data/app.package.name/databases
db_name.sqlite // a custom named db
# exit
// pull it
>adb pull /data/app.package.name/databases/db_name.sqlite

How to set Navigation Drawer to be opened from right to left

SOLUTION


your_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="end">

    <include layout="@layout/app_bar_root"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:fitsSystemWindows="true"
        app:itemTextColor="@color/black"
        app:menu="@menu/activity_root_drawer" />

</android.support.v4.widget.DrawerLayout>

YourActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
//...
toolbar = (Toolbar) findViewById(R.id.toolbar);

drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

toolbar.setNavigationOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (drawer.isDrawerOpen(Gravity.RIGHT)) {
                drawer.closeDrawer(Gravity.RIGHT);
            } else {
                drawer.openDrawer(Gravity.RIGHT);
            }
        }
    });
//...
}

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

How do I rename a file using VBScript?

Yes you can do that.
Here I am renaming a .exe file to .txt file

rename a file

Dim objFso  
Set objFso= CreateObject("Scripting.FileSystemObject")  
objFso.MoveFile "D:\testvbs\autorun.exe", "D:\testvbs\autorun.txt"

numbers not allowed (0-9) - Regex Expression in javascript

\D is a non-digit, and so then \D* is any number of non-digits in a row. So your whole string should match ^\D*$.

Check on http://rubular.com/r/AoWBmrbUkN it works perfectly.

You can also try on http://regexpal.com/ OR http://www.regextester.com/

how to implement Pagination in reactJs

   Sample pagination react js working code 
    import React, { Component } from 'react';
    import {
    Pagination,
    PaginationItem,
    PaginationLink
    } from "reactstrap";


    let prev  = 0;
    let next  = 0;
    let last  = 0;
    let first = 0;
    export default class SamplePagination extends Component {
       constructor() {
         super();
         this.state = {
           todos: ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','T','v','u','w','x','y','z'],
           currentPage: 1,
           todosPerPage: 3,

         };
         this.handleClick = this.handleClick.bind(this);
         this.handleLastClick = this.handleLastClick.bind(this);
         this.handleFirstClick = this.handleFirstClick.bind(this);
       }

       handleClick(event) {
         event.preventDefault();
         this.setState({
           currentPage: Number(event.target.id)
         });
       }

       handleLastClick(event) {
         event.preventDefault();
         this.setState({
           currentPage:last
         });
       }
       handleFirstClick(event) {
         event.preventDefault();
         this.setState({
           currentPage:1
         });
       }
       render() {
         let { todos, currentPage, todosPerPage } = this.state;

         // Logic for displaying current todos
         let indexOfLastTodo = currentPage * todosPerPage;
         let indexOfFirstTodo = indexOfLastTodo - todosPerPage;
         let currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);
          prev  = currentPage > 0 ? (currentPage -1) :0;
          last = Math.ceil(todos.length/todosPerPage);
          next  = (last === currentPage) ?currentPage: currentPage +1;

         // Logic for displaying page numbers
         let pageNumbers = [];
         for (let i = 1; i <=last; i++) {
           pageNumbers.push(i);
         }

          return (
           <div>
             <ul>
              {
                currentTodos.map((todo,index) =>{
                  return <li key={index}>{todo}</li>;
                })
              }
             </ul><ul id="page-numbers">
             <nav>
              <Pagination>
              <PaginationItem>
              { prev === 0 ? <PaginationLink disabled>First</PaginationLink> :
                  <PaginationLink onClick={this.handleFirstClick} id={prev} href={prev}>First</PaginationLink>
              }
              </PaginationItem>
              <PaginationItem>
              { prev === 0 ? <PaginationLink disabled>Prev</PaginationLink> :
                  <PaginationLink onClick={this.handleClick} id={prev} href={prev}>Prev</PaginationLink>
              }
              </PaginationItem>
                 {
                  pageNumbers.map((number,i) =>
                  <Pagination key= {i}>
                  <PaginationItem active = {pageNumbers[currentPage-1] === (number) ? true : false} >
                   <PaginationLink onClick={this.handleClick} href={number} key={number} id={number}>
                   {number}
                   </PaginationLink>
                   </PaginationItem>
                  </Pagination>
                )}

             <PaginationItem>
             {
               currentPage === last ? <PaginationLink disabled>Next</PaginationLink> :
               <PaginationLink onClick={this.handleClick} id={pageNumbers[currentPage]} href={pageNumbers[currentPage]}>Next</PaginationLink>
             }
             </PaginationItem>

             <PaginationItem>
             {
               currentPage === last ? <PaginationLink disabled>Last</PaginationLink> :
               <PaginationLink onClick={this.handleLastClick} id={pageNumbers[currentPage]} href={pageNumbers[currentPage]}>Last</PaginationLink>
             }
             </PaginationItem>
             </Pagination>
              </nav>
             </ul>
           </div>
         );
       }
     }

     ReactDOM.render(
      <SamplePagination />,
      document.getElementById('root')
    );

Calling ASP.NET MVC Action Methods from JavaScript

Javascript Function

function AddToCart(id) {
 $.ajax({
   url: '@Url.Action("AddToCart", "ControllerName")',
   type: 'GET',
   dataType: 'json',
   cache: false,
   data: { 'id': id },
   success: function (results) {
        alert(results)
   },
   error: function () {
    alert('Error occured');
   }
   });
   }

Controller Method to call

[HttpGet]
  public JsonResult AddToCart(string id)
  {
    string newId = id;
     return Json(newId, JsonRequestBehavior.AllowGet);
  }

Select all from table with Laravel and Eloquent

There are 3 ways that one can do that.

1.

$entireTable = TableModelName::all();

eg,

$posts = Posts::get(); 
  1. put this line before the class in the controller

    use Illuminate\Support\Facades\DB; // this will import the DB facade into your controller class

Now in the class

$posts = DB::table('posts')->get(); // it will get the entire table
  1. put this line before the class in the controller

    Same import the DB facade like method 2

Now in the controller

$posts = DB::select('SELECT * FROM posts');

Check existence of input argument in a Bash shell script

In some cases you need to check whether the user passed an argument to the script and if not, fall back to a default value. Like in the script below:

scale=${2:-1}
emulator @$1 -scale $scale

Here if the user hasn't passed scale as a 2nd parameter, I launch Android emulator with -scale 1 by default. ${varname:-word} is an expansion operator. There are other expansion operators as well:

  • ${varname:=word} which sets the undefined varname instead of returning the word value;
  • ${varname:?message} which either returns varname if it's defined and is not null or prints the message and aborts the script (like the first example);
  • ${varname:+word} which returns word only if varname is defined and is not null; returns null otherwise.

Error handling in AngularJS http get then construct

Try this

function sendRequest(method, url, payload, done){

        var datatype = (method === "JSONP")? "jsonp" : "json";
        $http({
                method: method,
                url: url,
                dataType: datatype,
                data: payload || {},
                cache: true,
                timeout: 1000 * 60 * 10
        }).then(
            function(res){
                done(null, res.data); // server response
            },
            function(res){
                responseHandler(res, done);
            }
        );

    }
    function responseHandler(res, done){
        switch(res.status){
            default: done(res.status + ": " + res.statusText);
        }
    }

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

I know it's a "very long time" since this question was first asked. Just in case, if it helps someone,

Adding relationships is well supported by MS via SQL Server Compact Tool Box (https://sqlcetoolbox.codeplex.com/). Just install it, then you would get the option to connect to the Compact Database using the Server Explorer Window. Right click on the primary table , select "Table Properties". You should have the following window, which contains "Add Relations" tab allowing you to add relations.

Add Relations Tab - SQL Server Compact Tool Box

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

TLDR; Neither use the synchronized modifier nor the synchronized(this){...} expression but synchronized(myLock){...} where myLock is a final instance field holding a private object.


The difference between using the synchronized modifier on the method declaration and the synchronized(..){ } expression in the method body are this:

  • The synchronized modifier specified on the method's signature
    1. is visible in the generated JavaDoc,
    2. is programmatically determinable via reflection when testing a method's modifier for Modifier.SYNCHRONIZED,
    3. requires less typing and indention compared to synchronized(this) { .... }, and
    4. (depending on your IDE) is visible in the class outline and code completion,
    5. uses the this object as lock when declared on non-static method or the enclosing class when declared on a static method.
  • The synchronized(...){...} expression allows you
    1. to only synchronize the execution of parts of a method's body,
    2. to be used within a constructor or a (static) initialization block,
    3. to choose the lock object which controls the synchronized access.

However, using the synchronized modifier or synchronized(...) {...} with this as the lock object (as in synchronized(this) {...}), have the same disadvantage. Both use it's own instance as the lock object to synchronize on. This is dangerous because not only the object itself but any other external object/code that holds a reference to that object can also use it as a synchronization lock with potentially severe side effects (performance degradation and deadlocks).

Therefore best practice is to neither use the synchronized modifier nor the synchronized(...) expression in conjunction with this as lock object but a lock object private to this object. For example:

public class MyService {
    private final lock = new Object();

    public void doThis() {
       synchronized(lock) {
          // do code that requires synchronous execution
        }
    }

    public void doThat() {
       synchronized(lock) {
          // do code that requires synchronous execution
        }
    }
}

You can also use multiple lock objects but special care needs to be taken to ensure this does not result in deadlocks when used nested.

public class MyService {
    private final lock1 = new Object();
    private final lock2 = new Object();

    public void doThis() {
       synchronized(lock1) {
          synchronized(lock2) {
              // code here is guaranteed not to be executes at the same time
              // as the synchronized code in doThat() and doMore().
          }
    }

    public void doThat() {
       synchronized(lock1) {
              // code here is guaranteed not to be executes at the same time
              // as the synchronized code in doThis().
              // doMore() may execute concurrently
        }
    }

    public void doMore() {
       synchronized(lock2) {
              // code here is guaranteed not to be executes at the same time
              // as the synchronized code in doThis().
              // doThat() may execute concurrently
        }
    }
}

Math constant PI value in C

In C Pi is defined in math.h: #define M_PI 3.14159265358979323846

Vertical (rotated) text in HTML table

Alternate Solution?

Instead of rotating the text, would it work to have it written "top to bottom?"

Like this:

S  
O  
M  
E  

T  
E  
X  
T  

I think that would be a lot easier - you can pick a string of text apart and insert a line break after each character.

This could be done via JavaScript in the browser like this:

"SOME TEXT".split("").join("\n")

... or you could do it server-side, so it wouldn't depend on the client's JS capabilities. (I assume that's what you mean by "portable?")

Also the user doesn't have to turn his/her head sideways to read it. :)

Update

This thread is about doing this with jQuery.

How to increase timeout for a single test case in mocha

Here you go: http://mochajs.org/#test-level

it('accesses the network', function(done){
  this.timeout(500);
  [Put network code here, with done() in the callback]
})

For arrow function use as follows:

it('accesses the network', (done) => {
  [Put network code here, with done() in the callback]
}).timeout(500);

What does .class mean in Java?

That means a Class with a type of anything (unknown).

You should read java generics tutorial to get to understand it better

node.js - how to write an array to file

We can simply write the array data to the filesystem but this will raise one error in which ',' will be appended to the end of the file. To handle this below code can be used:

var fs = require('fs');

var file = fs.createWriteStream('hello.txt');
file.on('error', function(err) { Console.log(err) });
data.forEach(value => file.write(`${value}\r\n`));
file.end();

\r\n

is used for the new Line.

\n

won't help. Please refer this

When to use EntityManager.find() vs EntityManager.getReference() with JPA

This makes me wonder, when is it advisable to use the EntityManager.getReference() method instead of the EntityManager.find() method?

EntityManager.getReference() is really an error prone method and there is really very few cases where a client code needs to use it.
Personally, I never needed to use it.

EntityManager.getReference() and EntityManager.find() : no difference in terms of overhead

I disagree with the accepted answer and particularly :

If i call find method, JPA provider, behind the scenes, will call

SELECT NAME, AGE FROM PERSON WHERE PERSON_ID = ?

UPDATE PERSON SET AGE = ? WHERE PERSON_ID = ?

If i call getReference method, JPA provider, behind the scenes, will call

UPDATE PERSON SET AGE = ? WHERE PERSON_ID = ?

It is not the behavior that I get with Hibernate 5 and the javadoc of getReference() doesn't say such a thing :

Get an instance, whose state may be lazily fetched. If the requested instance does not exist in the database, the EntityNotFoundException is thrown when the instance state is first accessed. (The persistence provider runtime is permitted to throw the EntityNotFoundException when getReference is called.) The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open.

EntityManager.getReference() spares a query to retrieve the entity in two cases :

1) if the entity is stored in the Persistence context, that is the first level cache.
And this behavior is not specific to EntityManager.getReference(), EntityManager.find() will also spare a query to retrieve the entity if the entity is stored in the Persistence context.

You can check the first point with any example.
You can also rely on the actual Hibernate implementation.
Indeed, EntityManager.getReference() relies on the createProxyIfNecessary() method of the org.hibernate.event.internal.DefaultLoadEventListener class to load the entity.
Here is its implementation :

private Object createProxyIfNecessary(
        final LoadEvent event,
        final EntityPersister persister,
        final EntityKey keyToLoad,
        final LoadEventListener.LoadType options,
        final PersistenceContext persistenceContext) {
    Object existing = persistenceContext.getEntity( keyToLoad );
    if ( existing != null ) {
        // return existing object or initialized proxy (unless deleted)
        if ( traceEnabled ) {
            LOG.trace( "Entity found in session cache" );
        }
        if ( options.isCheckDeleted() ) {
            EntityEntry entry = persistenceContext.getEntry( existing );
            Status status = entry.getStatus();
            if ( status == Status.DELETED || status == Status.GONE ) {
                return null;
            }
        }
        return existing;
    }
    if ( traceEnabled ) {
        LOG.trace( "Creating new proxy for entity" );
    }
    // return new uninitialized proxy
    Object proxy = persister.createProxy( event.getEntityId(), event.getSession() );
    persistenceContext.getBatchFetchQueue().addBatchLoadableEntityKey( keyToLoad );
    persistenceContext.addProxy( keyToLoad, proxy );
    return proxy;
}

The interesting part is :

Object existing = persistenceContext.getEntity( keyToLoad );

2) If we don't effectively manipulate the entity, echoing to the lazily fetched of the javadoc.
Indeed, to ensure the effective loading of the entity, invoking a method on it is required.
So the gain would be related to a scenario where we want to load a entity without having the need to use it ? In the frame of applications, this need is really uncommon and in addition the getReference() behavior is also very misleading if you read the next part.

Why favor EntityManager.find() over EntityManager.getReference()

In terms of overhead, getReference() is not better than find() as discussed in the previous point.
So why use the one or the other ?

Invoking getReference() may return a lazily fetched entity.
Here, the lazy fetching doesn't refer to relationships of the entity but the entity itself.
It means that if we invoke getReference() and then the Persistence context is closed, the entity may be never loaded and so the result is really unpredictable. For example if the proxy object is serialized, you could get a null reference as serialized result or if a method is invoked on the proxy object, an exception such as LazyInitializationException is thrown.

It means that the throw of EntityNotFoundException that is the main reason to use getReference() to handle an instance that does not exist in the database as an error situation may be never performed while the entity is not existing.

EntityManager.find() doesn't have the ambition of throwing EntityNotFoundException if the entity is not found. Its behavior is both simple and clear. You will never have surprise as it returns always a loaded entity or null (if the entity is not found) but never an entity under the shape of a proxy that may not be effectively loaded.
So EntityManager.find() should be favored in the very most of cases.

Run Bash Command from PHP

Your shell_exec is executed by www-data user, from its directory. You can try

putenv("PATH=/home/user/bin/:" .$_ENV["PATH"]."");

Where your script is located in /home/user/bin Later on you can

$output = "<pre>".shell_exec("scriptname v1 v2")."</pre>";
echo $output;

To display the output of command. (Alternatively, without exporting path, try giving entire path of your script instead of just ./script.sh

Git submodule head 'reference is not a tree' error

Possible cause

This can happens when:

  1. Submodule(s) have been edited in place
  2. Submodule(s) committed, which updates the hash of the submodule being pointed to
  3. Submodule(s) not pushed.

e.g. something like this happened:

$ cd submodule
$ emacs my_source_file  # edit some file(s)
$ git commit -am "Making some changes but will forget to push!"

Should have submodule pushed at this point.

$ cd .. # back to parent repository
$ git commit -am "updates to parent repository"
$ git push origin master

As a result, the missing commits could not possibly be found by the remote user because they are still on the local disk.

Solution

Informa the person who modified the submodule to push, i.e.

$ cd submodule
$ git push

How to obtain image size using standard Python class (without using external library)?

That code does accomplish 2 things:

  • Getting the image dimension

  • Find the real EOF of a jpg file

Well when googling I was more interest in the later one. The task was to cut out a jpg file from a datastream. Since I I didn't find any way to use Pythons 'image' to a way to get the EOF of so jpg-File I made up this.

Interesting things /changes/notes in this sample:

  • extending the normal Python file class with the method uInt16 making source code better readable and maintainable. Messing around with struct.unpack() quickly makes code to look ugly

  • Replaced read over'uninteresting' areas/chunk with seek

  • Incase you just like to get the dimensions you may remove the line:

    hasChunk = ord(byte) not in range( 0xD0, 0xDA) + [0x00] 
    

    ->since that only get's important when reading over the image data chunk and comment in

    #break
    

    to stop reading as soon as the dimension were found. ...but smile what I'm telling - you're the Coder ;)

      import struct
      import io,os
    
      class myFile(file):
    
          def byte( self ):
               return file.read( self,  1);
    
          def uInt16( self ):
               tmp = file.read( self,  2)
               return struct.unpack( ">H", tmp )[0];
    
      jpeg = myFile('grafx_ui.s00_\\08521678_Unknown.jpg', 'rb')
    
      try:
          height = -1
          width  = -1
          EOI    = -1
    
          type_check = jpeg.read(2)
          if type_check != b'\xff\xd8':
            print("Not a JPG")
    
          else:
    
            byte = jpeg.byte()
    
            while byte != b"":
    
              while byte != b'\xff': byte = jpeg.byte()
              while byte == b'\xff': byte = jpeg.byte()
    
    
              # FF D8       SOI Start of Image
              # FF D0..7  RST DRI Define Restart Interval inside CompressedData
              # FF 00           Masked FF inside CompressedData
              # FF D9       EOI End of Image
              # http://en.wikipedia.org/wiki/JPEG#Syntax_and_structure
              hasChunk = ord(byte) not in range( 0xD0, 0xDA) + [0x00]
              if hasChunk:
                   ChunkSize   =  jpeg.uInt16()  - 2
                   ChunkOffset =  jpeg.tell()
                   Next_ChunkOffset = ChunkOffset + ChunkSize
    
    
              # Find bytes \xFF \xC0..C3 That marks the Start of Frame
              if (byte >= b'\xC0' and byte <= b'\xC3'):
    
                # Found  SOF1..3 data chunk - Read it and quit
                jpeg.seek(1, os.SEEK_CUR)
                h = jpeg.uInt16()
                w = jpeg.uInt16()
    
    
                #break
    
    
              elif (byte == b'\xD9'):
                   # Found End of Image
                   EOI = jpeg.tell()
                   break
              else:
                  # Seek to next data chunk
                 print "Pos: %.4x %x" % (jpeg.tell(), ChunkSize)
    
              if hasChunk:       
                 jpeg.seek(Next_ChunkOffset)
    
              byte = jpeg.byte()
    
            width  = int(w)
            height = int(h)
    
            print("Width: %s, Height: %s  JpgFileDataSize: %x" % (width, height, EOI))
      finally:
          jpeg.close()
    

How can I force input to uppercase in an ASP.NET textbox?

You can intercept the key press events, cancel the lowercase ones, and append their uppercase versions to the input:

window.onload = function () {
    var input = document.getElementById("test");

    input.onkeypress = function () {
        // So that things work both on Firefox and Internet Explorer.
        var evt = arguments[0] || event;
        var char = String.fromCharCode(evt.which || evt.keyCode);

        // Is it a lowercase character?
        if (/[a-z]/.test(char)) {
            // Append its uppercase version
            input.value += char.toUpperCase();

            // Cancel the original event
            evt.cancelBubble = true;
            return false;
        }
    }
};

This works in both Firefox and Internet Explorer. You can see it in action here.

HashMap - getting First Key value

Note that you should note that your logic flow must never rely on accessing the HashMap elements in some order, simply put because HashMaps are not ordered Collections and that is not what they are aimed to do. (You can read more about odered and sorter collections in this post).

Back to the post, you already did half the job by loading the first element key:

Object myKey = statusName.keySet().toArray()[0];

Just call map.get(key) to get the respective value:

Object myValue = statusName.get(myKey);

PhpMyAdmin not working on localhost

Same Object Not Found problem here - both in Xampp as well as in Wamp. It turns out the root name of "phpmyadmin" was "PhpMyAdmin". I got rid of all the capitals, renaming the folder to "phpmyadmin", and after a couple of reloads phpmyadmin was working.

Convert java.util.date default format to Timestamp in Java

You can use the Calendar class to convert Date

public long getDifference()
{
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy");
    Date d = sdf.parse("Mon May 27 11:46:15 IST 2013");

    Calendar c = Calendar.getInstance();
    c.setTime(d);
    long time = c.getTimeInMillis();
    long curr = System.currentTimeMillis();
    long diff = curr - time;    //Time difference in milliseconds
    return diff/1000;
}

jQuery .each() index?

jQuery takes care of this for you. The first argument to your .each() callback function is the index of the current iteration of the loop. The second being the current matched DOM element So:

$('#list option').each(function(index, element){
  alert("Iteration: " + index)
});

How to do parallel programming in Python?

The solution, as others have said, is to use multiple processes. Which framework is more appropriate, however, depends on many factors. In addition to the ones already mentioned, there is also charm4py and mpi4py (I am the developer of charm4py).

There is a more efficient way to implement the above example than using the worker pool abstraction. The main loop sends the same parameters (including the complete graph G) over and over to workers in each of the 1000 iterations. Since at least one worker will reside on a different process, this involves copying and sending the arguments to the other process(es). This could be very costly depending on the size of the objects. Instead, it makes sense to have workers store state and simply send the updated information.

For example, in charm4py this can be done like this:

class Worker(Chare):

    def __init__(self, Q, G, n):
        self.G = G
        ...

    def setinner(self, node1, node2):
        self.updateGraph(node1, node2)
        ...


def solve(Q, G, n):
    # create 2 workers, each on a different process, passing the initial state
    worker_a = Chare(Worker, onPE=0, args=[Q, G, n])
    worker_b = Chare(Worker, onPE=1, args=[Q, G, n])
    while i < 1000:
        result_a = worker_a.setinner(node1, node2, ret=True)  # execute setinner on worker A
        result_b = worker_b.setouter(node1, node2, ret=True)  # execute setouter on worker B

        inneropt, partition, x = result_a.get()  # wait for result from worker A
        outeropt = result_b.get()  # wait for result from worker B
        ...

Note that for this example we really only need one worker. The main loop could execute one of the functions, and have the worker execute the other. But my code helps to illustrate a couple of things:

  1. Worker A runs in process 0 (same as the main loop). While result_a.get() is blocked waiting on the result, worker A does the computation in the same process.
  2. Arguments are automatically passed by reference to worker A, since it is in the same process (there is no copying involved).

SQL Server - Return value after INSERT

INSERT INTO files (title) VALUES ('whatever'); 
SELECT * FROM files WHERE id = SCOPE_IDENTITY();

Is the safest bet since there is a known issue with OUTPUT Clause conflict on tables with triggers. Makes this quite unreliable as even if your table doesn't currently have any triggers - someone adding one down the line will break your application. Time Bomb sort of behaviour.

See msdn article for deeper explanation:

http://blogs.msdn.com/b/sqlprogrammability/archive/2008/07/11/update-with-output-clause-triggers-and-sqlmoreresults.aspx

IllegalArgumentException or NullPointerException for a null parameter?

Actually, the question of throwing IllegalArgumentException or NullPointerException is in my humble view only a "holy war" for a minority with an incomlete understanding of exception handling in Java. In general, the rules are simple, and as follows:

  • argument constraint violations must be indicated as fast as possible (-> fast fail), in order to avoid illegal states which are much harder to debug
  • in case of an invalid null pointer for whatever reason, throw NullPointerException
  • in case of an illegal array/collection index, throw ArrayIndexOutOfBounds
  • in case of a negative array/collection size, throw NegativeArraySizeException
  • in case of an illegal argument that is not covered by the above, and for which you don't have another more specific exception type, throw IllegalArgumentException as a wastebasket
  • on the other hand, in case of a constraint violation WITHIN A FIELD that could not be avoided by fast fail for some valid reason, catch and rethrow as IllegalStateException or a more specific checked exception. Never let pass the original NullPointerException, ArrayIndexOutOfBounds, etc in this case!

There are at least three very good reasons against the case of mapping all kinds of argument constraint violations to IllegalArgumentException, with the third probably being so severe as to mark the practice bad style:

(1) A programmer cannot a safely assume that all cases of argument constraint violations result in IllegalArgumentException, because the large majority of standard classes use this exception rather as a wastebasket if there is no more specific kind of exception available. Trying to map all cases of argument constraint violations to IllegalArgumentException in your API only leads to programmer frustration using your classes, as the standard libraries mostly follow different rules that violate yours, and most of your API users will use them as well!

(2) Mapping the exceptions actually results in a different kind of anomaly, caused by single inheritance: All Java exceptions are classes, and therefore support single inheritance only. Therefore, there is no way to create an exception that is truly say both a NullPointerException and an IllegalArgumentException, as subclasses can only inherit from one or the other. Throwing an IllegalArgumentException in case of a null argument therefore makes it harder for API users to distinguish between problems whenever a program tries to programmatically correct the problem, for example by feeding default values into a call repeat!

(3) Mapping actually creates the danger of bug masking: In order to map argument constraint violations into IllegalArgumentException, you'll need to code an outer try-catch within every method that has any constrained arguments. However, simply catching RuntimeException in this catch block is out of the question, because that risks mapping documented RuntimeExceptions thrown by libery methods used within yours into IllegalArgumentException, even if they are no caused by argument constraint violations. So you need to be very specific, but even that effort doesn't protect you from the case that you accidentally map an undocumented runtime exception of another API (i.e. a bug) into an IllegalArgumentException of your API. Even the most careful mapping therefore risks masking programming errors of other library makers as argument constraint violations of your method's users, which is simply hillareous behavior!

With the standard practice on the other hand, the rules stay simple, and exception causes stay unmasked and specific. For the method caller, the rules are easy as well: - if you encounter a documented runtime exception of any kind because you passed an illegal value, either repeat the call with a default (for this specific exceptions are neccessary), or correct your code - if on the other hand you enccounter a runtime exception that is not documented to happen for a given set of arguments, file a bug report to the method's makers to ensure that either their code or their documentation is fixed.

When should I use the new keyword in C++?

Method 1 (using new)

  • Allocates memory for the object on the free store (This is frequently the same thing as the heap)
  • Requires you to explicitly delete your object later. (If you don't delete it, you could create a memory leak)
  • Memory stays allocated until you delete it. (i.e. you could return an object that you created using new)
  • The example in the question will leak memory unless the pointer is deleted; and it should always be deleted, regardless of which control path is taken, or if exceptions are thrown.

Method 2 (not using new)

  • Allocates memory for the object on the stack (where all local variables go) There is generally less memory available for the stack; if you allocate too many objects, you risk stack overflow.
  • You won't need to delete it later.
  • Memory is no longer allocated when it goes out of scope. (i.e. you shouldn't return a pointer to an object on the stack)

As far as which one to use; you choose the method that works best for you, given the above constraints.

Some easy cases:

  • If you don't want to worry about calling delete, (and the potential to cause memory leaks) you shouldn't use new.
  • If you'd like to return a pointer to your object from a function, you must use new

Create two-dimensional arrays and access sub-arrays in Ruby

Here's a 3D array case

class Array3D
   def initialize(d1,d2,d3)
    @data = Array.new(d1) { Array.new(d2) { Array.new(d3) } }
   end

  def [](x, y, z)
    @data[x][y][z]
  end

  def []=(x, y, z, value)
    @data[x][y][z] = value
  end
end

You can access subsections of each array just like any other Ruby array. @data[0..2][3..5][8..10] = 0 etc

Extracting columns from text file with different delimiters in Linux

If the command should work with both tabs and spaces as the delimiter I would use awk:

awk '{print $100,$101,$102,$103,$104,$105}' myfile > outfile

As long as you just need to specify 5 fields it is imo ok to just type them, for longer ranges you can use a for loop:

awk '{for(i=100;i<=105;i++)print $i}' myfile > outfile

If you want to use cut, you need to use the -f option:

cut -f100-105 myfile > outfile

If the field delimiter is different from TAB you need to specify it using -d:

cut -d' ' -f100-105 myfile > outfile

Check the man page for more info on the cut command.

catch specific HTTP error in python

Tims answer seems to me as misleading. Especially when urllib2 does not return expected code. For example this Error will be fatal (believe or not - it is not uncommon one when downloading urls):

AttributeError: 'URLError' object has no attribute 'code'

Fast, but maybe not the best solution would be code using nested try/except block:

import urllib2
try:
    urllib2.urlopen("some url")
except urllib2.HTTPError, err:
    try:
        if err.code == 404:
            # Handle the error
        else:
            raise
    except:
        ...

More information to the topic of nested try/except blocks Are nested try/except blocks in python a good programming practice?

How to remove border of drop down list : CSS

select#xyz {
  border:0px;
  outline:0px;
}

Exact solution.

Remove trailing newline from the elements of a string list

All other answers, and mainly about list comprehension, are great. But just to explain your error:

strip_list = []
for lengths in range(1,20):
    strip_list.append(0) #longest word in the text file is 20 characters long
for a in lines:
    strip_list.append(lines[a].strip())

a is a member of your list, not an index. What you could write is this:

[...]
for a in lines:
    strip_list.append(a.strip())

Another important comment: you can create an empty list this way:

strip_list = [0] * 20

But this is not so useful, as .append appends stuff to your list. In your case, it's not useful to create a list with defaut values, as you'll build it item per item when appending stripped strings.

So your code should be like:

strip_list = []
for a in lines:
    strip_list.append(a.strip())

But, for sure, the best one is this one, as this is exactly the same thing:

stripped = [line.strip() for line in lines]

In case you have something more complicated than just a .strip, put this in a function, and do the same. That's the most readable way to work with lists.

How to get Locale from its String representation in Java?

Since Java 7 there is factory method Locale.forLanguageTag and instance method Locale.toLanguageTag using IETF language tags.

Place input box at the center of div

The catch is that input elements are inline. We have to make it block (display:block) before positioning it to center : margin : 0 auto. Please see the code below :

<html>
<head>
    <style>
        div.wrapper {
            width: 300px;
            height:300px;
            border:1px solid black;
        }

        input[type="text"] {
             display: block;
             margin : 0 auto;
        }

    </style>
</head>
<body>

    <div class='wrapper'>
        <input type='text' name='ok' value='ok'>
    </div>    


</body>
</html>

But if you have a div which is positioned = absolute then we need to do the things little bit differently.Now see this!

  <html>
     <head>
    <style>
        div.wrapper {
            position:  absolute;
            top : 200px;
            left: 300px;
            width: 300px;
            height:300px;
            border:1px solid black;
        }

        input[type="text"] {
             position: relative;
             display: block;
             margin : 0 auto;
        }

    </style>
</head>
<body>

    <div class='wrapper'>
        <input type='text' name='ok' value='ok'>
    </div>  

</body>
</html>

Hoping this can be helpful.Thank you.

Why has it failed to load main-class manifest attribute from a JAR file?

You can run with:

java -cp .;app.jar package.MainClass

It works for me if there is no manifest in the JAR file.

OS X Framework Library not loaded: 'Image not found'

I think there is no fixed way to solve this problem since it might be caused by different reason. I also had this problem last week, I don't know when and exactly what cause this problem, only when I run it on simulator with Xcode or try to install it onto the phone, then it reports such kind of error, But when I run it with react-native run-ios with terminal, there is no problem.

I checked all the ways posted on the internet, like renew certificate, change settings in Xcode (all of ways mentions above), actually all of settings in Xcode were already set as it requested before, none of ways works for me. Until this morning when I delete the pods and reinstall, the error finally gonna after a week. If you are also using cocoapod and then error was just show up without any specific reason, maybe you can try my way.

  1. Check my cocoapods version.
  2. Update it if there is new version available.
  3. Go to your project folder, delete your Podfile.lock , Pods file, project xcworkspace.
  4. Run pod install

Reset select2 value and show placeholder

Use this :

$('.select').val([]).trigger('change');

Open-Source Examples of well-designed Android Applications?

I recommend the Last.fm for Android application: http://github.com/c99koder/lastfm-android

UPDATE: I'm not sure this is a good example anymore, it hasn't been updated in 2-3 years.

A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it?

Don't use document.write, here is workaround:

var script = document.createElement('script');  
script.src = "....";  
document.head.appendChild(script);

Creating a dictionary from a CSV file

You can use this, it is pretty cool:

import dataconverters.commas as commas
filename = 'test.csv'
with open(filename) as f:
      records, metadata = commas.parse(f)
      for row in records:
            print 'this is row in dictionary:'+rowenter code here

Use string in switch case in java

To reduce cyclomatic complexity use a map:

Map<String,Callable<Object>> map = new HashMap < > ( ) ;
map . put ( "apple" , new Callable<Object> () { public Object call ( method1 ( ) ; return null ; } ) ;
...
map . get ( x ) . call ( ) ;

or polymorphism

MySQL: How to reset or change the MySQL root password?

In my case this option helped : https://stackoverflow.com/a/49610152/13760371
Thank you, Rahul.

except for the following moment, when I try entered command:

UPDATE mysql.user SET authentication_string=PASSWORD('YOURNEWPASSWORD'), plugin='mysql_native_password' WHERE User='root' AND Host='%';

the console issued a warning:

1681 'password' is deprecated and will be removed in a future release

cured with this command:

UPDATE mysql.user SET authentication_string=CONCAT('*', UPPER(SHA1(UNHEX(SHA1('NEWPASSWORD'))))), plugin='mysql_native_password' WHERE User='root' AND Host='localhost';

MySQL version 5.7.X

My variant:

1. > sudo service mysql stop
2. > sudo mkdir /var/run/mysqld
3. > sudo chown mysql: /var/run/mysqld
4. > sudo mysqld_safe --skip-grant-tables --skip-networking &
5. > mysql -uroot mysql
6. > UPDATE mysql.user SET authentication_string=CONCAT('*', UPPER(SHA1(UNHEX(SHA1('NEWPASSWORD'))))), plugin='mysql_native_password' WHERE User='root' AND Host='localhost';
7. > \q;
8. > sudo mysqladmin -S /var/run/mysqld/mysqld.sock shutdown
9. > sudo service mysql start

Reduce size of legend area in barplot

The cex parameter will do that for you.

a <- c(3, 2, 2, 2, 1, 2 )
barplot(a, beside = T,
        col = 1:6, space = c(0, 2))
legend("topright", 
       legend = c("a", "b", "c", "d", "e", "f"), 
       fill = 1:6, ncol = 2,
       cex = 0.75)

The plot

When should I use nil and NULL in Objective-C?

I've found the following:

objc.h

#define Nil __DARWIN_NULL   /* id of Nil class */
#define nil __DARWIN_NULL   /* id of Nil instance */

_types.h

#define __DARWIN_NULL ((void *)0)

stddef.h

#undef NULL
#ifdef __cplusplus
#undef __null  // VC++ hack.
#define NULL __null
#else
#define NULL ((void*)0)
#endif

MacTypes.h

#ifndef NULL
#define NULL    __DARWIN_NULL
#endif /* ! NULL */
#ifndef nil
    #define nil NULL
#endif /* ! nil */

The way it looks, there's no difference but a conceptual one.

Create an array of strings

You need to use cell-arrays:

names = cell(10,1);
for i=1:10
    names{i} = ['Sample Text ' num2str(i)];
end

nodemon command is not recognized in terminal for node js server

Just install Globally

 npm install -g  nodemon

It worked for me on Windows 10.

nodemon app.js

How to read attribute value from XmlNode in C#?

If you use chldNode as XmlElement instead of XmlNode, you can use

var attributeValue = chldNode.GetAttribute("Name");

The return value will just be an empty string, in case the attribute name does not exist.

So your loop could look like this:

XmlDocument document = new XmlDocument();
var nodes = document.SelectNodes("//Node/N0de/node");

foreach (XmlElement node in nodes)
{
    var attributeValue = node.GetAttribute("Name");
}

This will select all nodes <node> surrounded by <Node><N0de></N0de><Node> tags and subsequently loop through them and read the attribute "Name".

virtualbox Raw-mode is unavailable courtesy of Hyper-V windows 10

After Windows 10 update in July of 2018 I suddenly experienced this issue with Virtual Box losing 64-Bit OS options resulting in the error.

virtualbox Raw-mode is unavailable courtesy of Hyper-V windows 10

Existing Laravel Homestead Boxes rendered un-bootable as a result event though HYPER-V is Disabled / Not Installed...

The FIX! (That worked for me) Drum Roll....

Install Hyper-V... Reboot, Uninstall it again... Reboot... The end

Bootstrap 4 img-circle class not working

It's now called rounded-circle as explained here in the BS4 docs

<img src="img/gallery2.JPG" class="rounded-circle">

Demo

Convert json data to a html table

You can use simple jQuery jPut plugin

http://plugins.jquery.com/jput/

<script>
$(document).ready(function(){

var json = [{"name": "name1","email":"[email protected]"},{"name": "name2","link":"[email protected]"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
    jsonData:json,
    //ajax_url:"youfile.json",  if you want to call from a json file
    name:"tbody_template",
});

});
</script>   

<table jput="t_template">
 <tbody jput="tbody_template">
     <tr>
         <td>{{name}}</td>
         <td>{{email}}</td>
     </tr>
 </tbody>
</table>

<table>
 <tbody id="tbody">
 </tbody>
</table>

Remove border from buttons

$(".myButtonClass").css(["border:none; background-color:white; padding:0"]);

Breaking out of nested loops

for x in xrange(10):
    for y in xrange(10):
        print x*y
        if x*y > 50:
            break
    else:
        continue  # only executed if the inner loop did NOT break
    break  # only executed if the inner loop DID break

The same works for deeper loops:

for x in xrange(10):
    for y in xrange(10):
        for z in xrange(10):
            print x,y,z
            if x*y*z == 30:
                break
        else:
            continue
        break
    else:
        continue
    break

IF function with 3 conditions

You can simplify the 5 through 21 part:

=IF(E9>21,"Text1",IF(E9>4,"Text2","Text3"))

Oracle Installer:[INS-13001] Environment does not meet minimum requirements

 $ yum -y install comapt-libstdc* libstdc++ libstdc++-devel libbaio-devel glib-devel glibc-headers glib-common kernel-header

$ yum -y install compat-libcap1 gcc gcc-c++ ksh compat-libstdc++-33 libaio-devel 

How to pass a user / password in ansible command

you can use --extra-vars like this:

$ ansible all --inventory=10.0.1.2, -m ping \
    --extra-vars "ansible_user=root ansible_password=yourpassword"

If you're authenticating to a Linux host that's joined to a Microsoft Active Directory domain, this command line works.

ansible --module-name ping --extra-vars 'ansible_user=domain\user ansible_password=PASSWORD' --inventory 10.10.6.184, all

Config Error: This configuration section cannot be used at this path

I had an issue where I was putting in the override = "Allow" values (mentioned here already)......but on a x64 bit system.......my 32 notepad++ was phantom saving them. Switching to Notepad (which is a 64bit application on a x64 bit O/S) allowed me to save the settings.

See :

http://dpotter.net/technical/2009/11/editing-applicationhostconfig-on-64-bit-windows/

The relevant text:

One of the problems I’m running down required that I view and possibly edit applicationHost.config. This file is located at %SystemRoot%\System32\inetsrv\config. Seems simple enough. I was able to find it from the command line easily, but when I went to load it in my favorite editor (Notepad++) I got a file not found error. Turns out that the System32 folder is redirected for 32-bit applications to SysWOW64. There appears to be no way to view the System32 folder using a 32-bit app. Go figure. Fortunately, 64-bit versions of Windows ship with a 64-bit version of Notepad. As much as I dislike it, at least it works.

Sorting int array in descending order

Guava has a method Ints.asList() for creating a List<Integer> backed by an int[] array. You can use this with Collections.sort to apply the Comparator to the underlying array.

List<Integer> integersList = Ints.asList(arr);
Collections.sort(integersList, Collections.reverseOrder());

Note that the latter is a live list backed by the actual array, so it should be pretty efficient.

How to get URI from an asset File?

InputStream is = getResources().getAssets().open("terms.txt");
String textfile = convertStreamToString(is);
    
public static String convertStreamToString(InputStream is)
        throws IOException {

    Writer writer = new StringWriter();
    char[] buffer = new char[2048];

    try {
        Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        int n;
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        is.close();
    }

    String text = writer.toString();
    return text;
}

How to list all the files in a commit?

Display the log.

COMMIT can be blank ("") or the sha-1 or the sha-1 shortened.

git log COMMIT -1 --name-only

This will list just the files, very useful for further processing.

git log COMMIT -1 --name-only --pretty=format:"" | grep "[^\s]"

MavenError: Failed to execute goal on project: Could not resolve dependencies In Maven Multimodule project

In my case I forgot it was packaging conflict jar vs pom. I forgot to write

<packaging>pom</packaging>

In every child pom.xml file

How to yum install Node.JS on Amazon Linux

As others mentioned using epel gives a really outdated version, here is a little script I just wrote instead to add to the CI pipeline or pass it to ec2 user-data to install the latest version of node, simply replace the version with what you want, and the appropriate distro of Linux you are using.

The following example is for amazon-Linux-2-AMI

#!/bin/bash

version='v14.13.1'
distro='linux-x64'
package_name="node-$version-$distro"
package_location="/usr/local/lib/"

curl -O https://nodejs.org/download/release/latest/$package_name.tar.gz
tar -xvf $package_name.tar.gz -C $package_location
rm -rfv $package_name.tar.gz

echo "export PATH=$package_location/$package_name/bin:\$PATH" >> ~/.profile

if you want to test it in the same shell simply run

. ~/.profile

Can you force Visual Studio to always run as an Administrator in Windows 8?

After looking on Super User I found this question which explains how to do this with the shortcut on the start screen. Similarly you can do the same when Visual Studio is pinned to the task bar. In either location:

  1. Right click the Visual Studio icon
  2. Go to Properties
  3. Under the Shortcut tab select Advanced
  4. Check Run as administrator

setting default operation in admin mode

Unlike in Windows 7 this only works if you launch the application from the shortcut you changed. After updating both Visual Studio shortcuts it seems to also work when you open a solution file from Explorer.

Update Warning: It looks like one of the major flaws in running Visual Studio with elevated permissions is since Explorer isn't running with them as well you can't drag and drop files into Visual Studio for editing. You need to open them through the file open dialog. Nor can you double click any file associated to Visual Studio and have it open in Visual Studio (aside from solutions it seems) because you'll get an error message saying There was a problem sending the command to the program. Once I uncheck to always start with elevated permissions (using VSCommands) then I'm able to open files directly and drop them into an open instance of Visual Studio.

Update For The Daring: Despite there being no UI to turn off UAC like in the past, that I saw at least, you can still do so through the registry. The key to edit is:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
EnableLUA - DWORD 1-Enabled, 0-Disabled

After changing this Windows will prompt you to restart. Once restarted you'll be back to everything running with admin permissions if you're an admin. The issues I reported above are now gone as well.

How to decode a Base64 string?

This page shows up when you google how to convert to base64, so for completeness:

$b  = [System.Text.Encoding]::UTF8.GetBytes("blahblah")
[System.Convert]::ToBase64String($b)

Getting fb.me URL

I'm not aware of any way to programmatically create these URLs, but the existing username space (www.facebook.com/something) works on fb.me also (e.g. http://fb.me/facebook )

Get MIME type from filename extension

To make the post more comprehensive, for .NET Core devs there is FileExtensionContentTypeProvider class, which covers the official MIME content types.

It works behind the scene - sets ContentType in the Http Response headers based on the filename extension.

In case you need special MIME types, see example on customising the MIME types:

public void Configure(IApplicationBuilder app)
{
    // Set up custom content types -associating file extension to MIME type
    var provider = new FileExtensionContentTypeProvider();
    // Add new mappings
    provider.Mappings[".myapp"] = "application/x-msdownload";
    provider.Mappings[".htm3"] = "text/html";
    provider.Mappings[".image"] = "image/png";
    // Replace an existing mapping
    provider.Mappings[".rtf"] = "application/x-msdownload";
    // Remove MP4 videos.
    provider.Mappings.Remove(".mp4");

    app.UseStaticFiles(new StaticFileOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
        RequestPath = new PathString("/MyImages"),
        ContentTypeProvider = provider
    });

    app.UseDirectoryBrowser(new DirectoryBrowserOptions()
    {
        FileProvider = new PhysicalFileProvider(
            Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot", "images")),
        RequestPath = new PathString("/MyImages")
    });
}

Python: 'ModuleNotFoundError' when trying to import module from imported package

FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A.

...

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path.

You need to set it up to something like this:

man
|- __init__.py
|- Mans
   |- __init__.py
   |- man1.py
|- MansTest
   |- __init.__.py
   |- SoftLib
      |- Soft
         |- __init__.py
         |- SoftWork
            |- __init__.py
            |- manModules.py
      |- Unittests
         |- __init__.py
         |- man1test.py

SECOND, for the "ModuleNotFoundError: No module named 'Soft'" error caused by from ...Mans import man1 in man1test.py, the documented solution to that is to add man1.py to sys.path since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path directly, you can also modify PYTHONPATH:

sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • The installation-dependent default.

THIRD, for from ...MansTest.SoftLib import Soft which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.

With that said, here's how I got it to work.

man1.py:

from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH

def foo():
    print("called foo in man1.py")
    print("foo call module1 from manModules: " + module1())

man1test.py

# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1

man1.foo()

manModules.py

def module1():
    return "module1 in manModules"

Terminal output:

$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
  ...
    from ...Mans import man1
  File "/temp/man/Mans/man1.py", line 2, in <module>
    from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'

$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules 

As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).

How to create the pom.xml for a Java project with Eclipse

You should use the new available m2e plugin for Maven integration in Eclipse. With help of that plugin, you should create a new project and move your sources into that project. These are the steps:

  • Check if m2e (or the former m2eclipse) are installed in your Eclipse distribution. If not, install it.
  • Open the "New Project Wizard": File > New > Project...
  • Open Maven and select Maven Project and click Next.
  • Select Create a simple project (to skip the archetype selection).
  • Add the necessary information: Group Id, Artifact Id, Packaging == jar, and a Name.
  • Finish the Wizard.
  • Your new Maven project is now generated, and you are able to move your sources and test packages to the relevant location in your workspace.
  • After that, you can build your project (inside Eclipse) by selecting your project, then calling from the context menu Run as > Maven install.

How to check command line parameter in ".bat" file?

You are comparing strings. If an arguments are omitted, %1 expands to a blank so the commands become IF =="-b" GOTO SPECIFIC for example (which is a syntax error). Wrap your strings in quotes (or square brackets).

REM this is ok
IF [%1]==[/?] GOTO BLANK

REM I'd recommend using quotes exclusively
IF "%1"=="-b" GOTO SPECIFIC

IF NOT "%1"=="-b" GOTO UNKNOWN

How to read a text file?

It depends on what you are trying to do.

file, err := os.Open("file.txt")
fmt.print(file)

The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File), not file-content. To obtain file-content, you may READ from a file-descriptor.


To read all file content(in bytes) to memory, ioutil.ReadAll

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "log"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


  b, err := ioutil.ReadAll(file)
  fmt.Print(b)
}

But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read from *os.File

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()


    buf := make([]byte, 32*1024) // define your buffer size here.

    for {
        n, err := file.Read(buf)

        if n > 0 {
            fmt.Print(buf[:n]) // your read buffer.
        }

        if err == io.EOF {
            break
        }
        if err != nil {
            log.Printf("read %d bytes: %v", n, err)
            break
        }
    }

}

Otherwise, you could also use the standard util package: bufio, try Scanner. A Scanner reads your file in tokens: separator.

By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).

package main

import (
    "fmt"
    "os"
    "log"
    "bufio"
)

func main() {
    file, err := os.Open("file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err = f.Close(); err != nil {
            log.Fatal(err)
        }
    }()

    scanner := bufio.NewScanner(file)

    for scanner.Scan() {             // internally, it advances token based on sperator
        fmt.Println(scanner.Text())  // token in unicode-char
        fmt.Println(scanner.Bytes()) // token in bytes

    }
}

Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.

CSS body background image fixed to full screen even when zooming in/out

I've used these techniques before and they both work well. If you read the pros/cons of each you can decide which is right for your site.

Alternatively you could use the full size background image jQuery plugin if you want to get away from the bugs in the above.

Javascript search inside a JSON object

You could just loop through the array and find the matches:

var results = [];
var searchField = "name";
var searchVal = "my Name";
for (var i=0 ; i < obj.list.length ; i++)
{
    if (obj.list[i][searchField] == searchVal) {
        results.push(obj.list[i]);
    }
}

Postgresql: password authentication failed for user "postgres"

The response of staff is correct, but if you want to further automate can do:

$ sudo -u postgres psql -c "ALTER USER postgres PASSWORD 'postgres';"

Done! You saved User = postgres and password = postgres.

If you do not have a password for the User postgres ubuntu do:

$ sudo passwd postgres

Set background image in CSS using jquery

You have to remove the semicolon in the css rule string:

$(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");

What is the difference between the kernel space and the user space?

Memory get's divided into two distinct areas:

  • The user space, which is a set of locations where normal user processes run (i.e everything other than the kernel). The role of the kernel is to manage applications running in this space from messing with each other, and the machine.
  • The kernel space, which is the location where the code of the kernel is stored, and executes under.

Processes running under the user space have access only to a limited part of memory, whereas the kernel has access to all of the memory. Processes running in user space also don't have access to the kernel space. User space processes can only access a small part of the kernel via an interface exposed by the kernel - the system calls.If a process performs a system call, a software interrupt is sent to the kernel, which then dispatches the appropriate interrupt handler and continues its work after the handler has finished.

How to compare variables to undefined, if I don’t know whether they exist?

if (document.getElementById('theElement')) // do whatever after this

For undefined things that throw errors, test the property name of the parent object instead of just the variable name - so instead of:

if (blah) ...

do:

if (window.blah) ...

Definition of int64_t

a) Can you explain to me the difference between int64_t and long (long int)? In my understanding, both are 64 bit integers. Is there any reason to choose one over the other?

The former is a signed integer type with exactly 64 bits. The latter is a signed integer type with at least 32 bits.

b) I tried to look up the definition of int64_t on the web, without much success. Is there an authoritative source I need to consult for such questions?

http://cppreference.com covers this here: http://en.cppreference.com/w/cpp/types/integer. The authoritative source, however, is the C++ standard (this particular bit can be found in §18.4 Integer types [cstdint]).

c) For code using int64_t to compile, I am including <iostream>, which doesn't make much sense to me. Are there other includes that provide a declaration of int64_t?

It is declared in <cstdint> or <cinttypes> (under namespace std), or in <stdint.h> or <inttypes.h> (in the global namespace).

How do I set bold and italic on UILabel of iPhone/iPad?

You can set any font style, family, size for the label, by clicking on letter "T" in Font field.

Label font settings

Declaring variables inside or outside of a loop

The str variable will be available and reserved some space in memory even after while executed below code.

 String str;
    while(condition){
        str = calculateStr();
        .....
    }

The str variable will not be available and also the memory will be released which was allocated for str variable in below code.

while(condition){
    String str = calculateStr();
    .....
}

If we followed the second one surely this will reduce our system memory and increase performance.

vba pass a group of cells as range to function

As written, your function accepts only two ranges as arguments.

To allow for a variable number of ranges to be used in the function, you need to declare a ParamArray variant array in your argument list. Then, you can process each of the ranges in the array in turn.

For example,

Function myAdd(Arg1 As Range, ParamArray Args2() As Variant) As Double
    Dim elem As Variant
    Dim i As Long
    For Each elem In Arg1
        myAdd = myAdd + elem.Value
    Next elem
    For i = LBound(Args2) To UBound(Args2)
        For Each elem In Args2(i)
            myAdd = myAdd + elem.Value
        Next elem
    Next i
End Function

This function could then be used in the worksheet to add multiple ranges.

myAdd usage

For your function, there is the question of which of the ranges (or cells) that can passed to the function are 'Sessions' and which are 'Customers'.

The easiest case to deal with would be if you decided that the first range is Sessions and any subsequent ranges are Customers.

Function calculateIt(Sessions As Range, ParamArray Customers() As Variant) As Double
    'This function accepts a single Sessions range and one or more Customers
    'ranges
    Dim i As Long
    Dim sessElem As Variant
    Dim custElem As Variant
    For Each sessElem In Sessions
        'do something with sessElem.Value, the value of each
        'cell in the single range Sessions
        Debug.Print "sessElem: " & sessElem.Value
    Next sessElem
    'loop through each of the one or more ranges in Customers()
    For i = LBound(Customers) To UBound(Customers)
        'loop through the cells in the range Customers(i)
        For Each custElem In Customers(i)
            'do something with custElem.Value, the value of
            'each cell in the range Customers(i)
            Debug.Print "custElem: " & custElem.Value
         Next custElem
    Next i
End Function

If you want to include any number of Sessions ranges and any number of Customers range, then you will have to include an argument that will tell the function so that it can separate the Sessions ranges from the Customers range.

This argument could be set up as the first, numeric, argument to the function that would identify how many of the following arguments are Sessions ranges, with the remaining arguments implicitly being Customers ranges. The function's signature would then be:

Function calculateIt(numOfSessionRanges, ParamAray Args() As Variant)

Or it could be a "guard" argument that separates the Sessions ranges from the Customers ranges. Then, your code would have to test each argument to see if it was the guard. The function would look like:

Function calculateIt(ParamArray Args() As Variant)

Perhaps with a call something like:

calculateIt(sessRange1,sessRange2,...,"|",custRange1,custRange2,...)

The program logic might then be along the lines of:

Function calculateIt(ParamArray Args() As Variant) As Double
   ...
   'loop through Args
   IsSessionArg = True
   For i = lbound(Args) to UBound(Args)
       'only need to check for the type of the argument
       If TypeName(Args(i)) = "String" Then
          IsSessionArg = False
       ElseIf IsSessionArg Then
          'process Args(i) as Session range
       Else
          'process Args(i) as Customer range
       End if
   Next i
   calculateIt = <somevalue>
End Function

In Firebase, is there a way to get the number of children of a node without loading all the node data?

The code snippet you gave does indeed load the entire set of data and then counts it client-side, which can be very slow for large amounts of data.

Firebase doesn't currently have a way to count children without loading data, but we do plan to add it.

For now, one solution would be to maintain a counter of the number of children and update it every time you add a new child. You could use a transaction to count items, like in this code tracking upvodes:

var upvotesRef = new Firebase('https://docs-examples.firebaseio.com/android/saving-data/fireblog/posts/-JRHTHaIs-jNPLXOQivY/upvotes');
upvotesRef.transaction(function (current_value) {
  return (current_value || 0) + 1;
});

For more info, see https://www.firebase.com/docs/transactions.html

UPDATE: Firebase recently released Cloud Functions. With Cloud Functions, you don't need to create your own Server. You can simply write JavaScript functions and upload it to Firebase. Firebase will be responsible for triggering functions whenever an event occurs.

If you want to count upvotes for example, you should create a structure similar to this one:

{
  "posts" : {
    "-JRHTHaIs-jNPLXOQivY" : {
      "upvotes_count":5,
      "upvotes" : {
      "userX" : true,
      "userY" : true,
      "userZ" : true,
      ...
    }
    }
  }
}

And then write a javascript function to increase the upvotes_count when there is a new write to the upvotes node.

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.countlikes = functions.database.ref('/posts/$postid/upvotes').onWrite(event => {
  return event.data.ref.parent.child('upvotes_count').set(event.data.numChildren());
});

You can read the Documentation to know how to Get Started with Cloud Functions.

Also, another example of counting posts is here: https://github.com/firebase/functions-samples/blob/master/child-count/functions/index.js

Update January 2018

The firebase docs have changed so instead of event we now have change and context.

The given example throws an error complaining that event.data is undefined. This pattern seems to work better:

exports.countPrescriptions = functions.database.ref(`/prescriptions`).onWrite((change, context) => {
    const data = change.after.val();
    const count = Object.keys(data).length;
    return change.after.ref.child('_count').set(count);
});

```

What is the fastest way to compare two sets in Java?

There is a method in Guava Sets which can help here:

public static <E>  boolean equals(Set<? extends E> set1, Set<? extends E> set2){
return Sets.symmetricDifference(set1,set2).isEmpty();
}

WPF What is the correct way of using SVG files as icons in WPF

Use the SvgImage or the SvgImageConverter extensions, the SvgImageConverter supports binding. See the following link for samples demonstrating both extensions.

https://github.com/ElinamLLC/SharpVectors/tree/master/TutorialSamples/ControlSamplesWpf

How to exclude a directory in find . command

For those of you on older versions of UNIX who cannot use -path or -not

Tested on SunOS 5.10 bash 3.2 and SunOS 5.11 bash 4.4

find . -type f -name "*" -o -type d -name "*excluded_directory*" -prune -type f

json call with C#

If your function resides in an mvc controller u can use the below code with a dictionary object of what you want to convert to json

Json(someDictionaryObj, JsonRequestBehavior.AllowGet);

Also try and look at system.web.script.serialization.javascriptserializer if you are using .net 3.5

as for your web request...it seems ok at first glance..

I would use something like this..

public void WebRequestinJson(string url, string postData)
    {
    StreamWriter requestWriter;

    var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;
    if (webRequest != null)
    {
        webRequest.Method = "POST";
        webRequest.ServicePoint.Expect100Continue = false;
        webRequest.Timeout = 20000;

        webRequest.ContentType = "application/json";
        //POST the data.
        using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
        {
            requestWriter.Write(postData);
        }
    }
}

May be you can make the post and json string a parameter and use this as a generic webrequest method for all calls.

Oracle: how to INSERT if a row doesn't exist

If name is a PK, then just insert and catch the error. The reason to do this rather than any check is that it will work even with multiple clients inserting at the same time. If you check and then insert, you have to hold a lock during that time, or expect the error anyway.

The code for this would be something like

BEGIN
  INSERT INTO table( name, age )
    VALUES( 'johnny', null );
EXCEPTION
  WHEN dup_val_on_index
  THEN
    NULL; -- Intentionally ignore duplicates
END;

Saving awk output to variable

I think the $() syntax is easier to read...

variable=$(ps -ef | grep "port 10 -" | grep -v "grep port 10 -"| awk '{printf "%s", $12}')

But the real issue is probably that $12 should not be qouted with ""

Edited since the question was changed, This returns valid data, but it is not clear what the expected output of ps -ef is and what is expected in variable.

How to get pixel data from a UIImage (Cocoa Touch) or CGImage (Core Graphics)?

FYI, I combined Keremk's answer with my original outline, cleaned-up the typos, generalized it to return an array of colors and got the whole thing to compile. Here is the result:

+ (NSArray*)getRGBAsFromImage:(UIImage*)image atX:(int)x andY:(int)y count:(int)count
{
    NSMutableArray *result = [NSMutableArray arrayWithCapacity:count];

    // First get the image into your data buffer
    CGImageRef imageRef = [image CGImage];
    NSUInteger width = CGImageGetWidth(imageRef);
    NSUInteger height = CGImageGetHeight(imageRef);
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
    NSUInteger bytesPerPixel = 4;
    NSUInteger bytesPerRow = bytesPerPixel * width;
    NSUInteger bitsPerComponent = 8;
    CGContextRef context = CGBitmapContextCreate(rawData, width, height,
                    bitsPerComponent, bytesPerRow, colorSpace,
                    kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
    CGColorSpaceRelease(colorSpace);

    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
    CGContextRelease(context);

    // Now your rawData contains the image data in the RGBA8888 pixel format.
    NSUInteger byteIndex = (bytesPerRow * y) + x * bytesPerPixel;
    for (int i = 0 ; i < count ; ++i)
    {
        CGFloat alpha = ((CGFloat) rawData[byteIndex + 3] ) / 255.0f;
        CGFloat red   = ((CGFloat) rawData[byteIndex]     ) / alpha;
        CGFloat green = ((CGFloat) rawData[byteIndex + 1] ) / alpha;
        CGFloat blue  = ((CGFloat) rawData[byteIndex + 2] ) / alpha;
        byteIndex += bytesPerPixel;

        UIColor *acolor = [UIColor colorWithRed:red green:green blue:blue alpha:alpha];
        [result addObject:acolor];
    }

  free(rawData);

  return result;
}

Google Play Services Missing in Emulator (Android 4.4.2)

http://developer.android.com/google/play-services/setup.html

Quoting docs

If you want to test your app on the emulator, expand the directory for Android 4.2.2 (API 17) or a higher version, select Google APIs, and install it. Then create a new AVD with Google APIs as the platform target.

Needs Emulator of Google API"S

See the target in the snap

Snap

enter image description here

I prefer testing on a real device which has google play services installed

Backporting Python 3 open(encoding="utf-8") to Python 2

1. To get an encoding parameter in Python 2:

If you only need to support Python 2.6 and 2.7 you can use io.open instead of open. io is the new io subsystem for Python 3, and it exists in Python 2,6 ans 2.7 as well. Please be aware that in Python 2.6 (as well as 3.0) it's implemented purely in python and very slow, so if you need speed in reading files, it's not a good option.

If you need speed, and you need to support Python 2.6 or earlier, you can use codecs.open instead. It also has an encoding parameter, and is quite similar to io.open except it handles line-endings differently.

2. To get a Python 3 open() style file handler which streams bytestrings:

open(filename, 'rb')

Note the 'b', meaning 'binary'.

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

I totally agree with the solution provided, but I think a little clarification is important I think, might be necessary.

For each process (read also: vshost.exe, yourWinformApplication.exe.svchost, or the name of your application.exe) that will need to add a DWORD with the value provided, in my case I leave 9000 (in decimal) in application name and running smoothly and error-free script.

the most common mistake is to believe that it is necessary to add "contoso.exe" AS IS and think it all work!

Is the NOLOCK (Sql Server hint) bad practice?

As a professional Developer I'd say it depends. But I definitely follow GATS and OMG Ponies advice. Know What You are doing, know when it helps and when it hurts and

read hints and other poor ideas

what might make You understand the sql server deeper. I generally follow the rule that SQL Hints are EVIL, but unfortunately I use them every now and then when I get fed up with forcing SQL server do things... But these are rare cases.

luke

How can I make the browser wait to display the page until it's fully loaded?

I know this is an old thread, but still. Another simple option is this library: http://gayadesign.com/scripts/queryLoader2/

How to select bottom most rows?

It is unnecessary. You can use an ORDER BY and just change the sort to DESC to get the same effect.

Error "library not found for" after putting application in AdMob

I was getting similar bugs on library not found. Ultimately this is how I was able to resolve it

  1. Before starting with Xcode Archive, used flutter build iOS
  2. Changed the IOS Deployment Target to a higher target iOS 11.2 . Earlier I had something like 8.0 which was giving all the above errors.
  3. Made sure that the IOS deployment targets in Xcode are same in the Project, Target and Pods

MySQL select with CONCAT condition

There is an alternative to repeating the CONCAT expression or using subqueries. You can make use of the HAVING clause, which recognizes column aliases.

SELECT 
  neededfield, CONCAT(firstname, ' ', lastname) AS firstlast 
FROM
  users 
HAVING firstlast = "Bob Michael Jones"

Here is a working SQL Fiddle.

How can I remove time from date with Moment.js?

Okay, so I know I'm way late to the party. Like 6 years late but this was something I needed to figure out and have it formatted YYYY-MM-DD.

moment().format(moment.HTML5_FMT.DATE); // 2019-11-08

You can also pass in a parameter like, 2019-11-08T17:44:56.144.

moment("2019-11-08T17:44:56.144").format(moment.HTML5_FMT.DATE); // 2019-11-08

https://momentjs.com/docs/#/parsing/special-formats/

PHP date add 5 year to current date

try this ,

$presentyear = '2013-08-16 12:00:00';

$nextyear  = date("M d,Y",mktime(0, 0, 0, date("m",strtotime($presentyear )),   date("d",strtotime($presentyear )),   date("Y",strtotime($presentyear ))+5));

echo $nextyear;

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

I know this doesn't help you, but I have to say that this is one of the reasons I jumped from XAMPP to WampServer. WampServer lets you install multiple versions of PHP, Apache and/or MySQL, and switch between them all via a menu option.

How can I pad a String in Java?

Apache StringUtils has several methods: leftPad, rightPad, center and repeat.

But please note that — as others have mentioned and demonstrated in this answerString.format() and the Formatter classes in the JDK are better options. Use them over the commons code.

What is the difference between compileSdkVersion and targetSdkVersion?

Not answering to your direct questions, since there are already a lot of detailed answers, but it's worth mentioning, that to the contrary of Android documentation, Android Studio is suggesting to use the same version for compileSDKVersion and targetSDKVersion.

enter image description here

How to get the number of columns from a JDBC ResultSet?

After establising the connection and executing the query try this:

 ResultSet resultSet;
 int columnCount = resultSet.getMetaData().getColumnCount();
 System.out.println("column count : "+columnCount);

How to initailize byte array of 100 bytes in java with all 0's

byte [] arr = new byte[100] 

Each element has 0 by default.

You could find primitive default values here:

Data Type   Default Value
byte        0
short       0
int         0
long        0L
float       0.0f
double      0.0d
char        '\u0000'
boolean     false

How to add a line break within echo in PHP?

You may want to try \r\n for carriage return / line feed

How do I get client IP address in ASP.NET CORE?

Running .NET core (3.1.4) on IIS behind a Load balancer did not work with other suggested solutions.

Manually reading the X-Forwarded-For header does.

IPAddress ip;
var headers = Request.Headers.ToList();
if (headers.Exists((kvp) => kvp.Key == "X-Forwarded-For"))
{
    // when running behind a load balancer you can expect this header
    var header = headers.First((kvp) => kvp.Key == "X-Forwarded-For").Value.ToString();
    ip = IPAddress.Parse(header);
}
else
{
    // this will always have a value (running locally in development won't have the header)
    ip = Request.HttpContext.Connection.RemoteIpAddress;
}

How do you easily create empty matrices javascript?

var matrix = [];
for(var i=0; i<9; i++) {
    matrix[i] = new Array(9);
}

... or:

var matrix = [];
for(var i=0; i<9; i++) {
    matrix[i] = [];
    for(var j=0; j<9; j++) {
        matrix[i][j] = undefined;
    }
}

"Exception has been thrown by the target of an invocation" error (mscorlib)

This can happen when invoking a method that doesn't exist.

Regular expression for address field validation

See the answer to this question on address validating with regex: regex street address match

The problem is, street addresses vary so much in formatting that it's hard to code against them. If you are trying to validate addresses, finding if one isn't valid based on its format is mighty hard to do. This would return the following address (253 N. Cherry St. ), anything with its same format:

\d{1,5}\s\w.\s(\b\w*\b\s){1,2}\w*\.

This allows 1-5 digits for the house number, a space, a character followed by a period (for N. or S.), 1-2 words for the street name, finished with an abbreviation (like st. or rd.).

Because regex is used to see if things meet a standard or protocol (which you define), you probably wouldn't want to allow for the addresses provided above, especially the first one with the dash, since they aren't very standard. you can modify my above code to allow for them if you wish--you could add

(-?)

to allow for a dash but not require one.

In addition, http://rubular.com/ is a quick and interactive way to learn regex. Try it out with the addresses above.

How to find and replace all occurrences of a string recursively in a directory tree?

On macOS, none of the answers worked for me. I discovered that was due to differences in how sed works on macOS and other BSD systems compared to GNU.

In particular BSD sed takes the -i option but requires a suffix for the backup (but an empty suffix is permitted)

grep version from this answer.

grep -rl 'foo' ./ | LC_ALL=C xargs sed -i '' 's/foo/bar/g'

find version from this answer.

find . \( ! -regex '.*/\..*' \) -type f | LC_ALL=C xargs sed -i '' 's/foo/bar/g'

Don't omit the Regex to ignore . folders if you're in a Git repo. I realized that the hard way!

That LC_ALL=C option is to avoid getting sed: RE error: illegal byte sequence if sed finds a byte sequence that is not a valid UTF-8 character. That's another difference between BSD and GNU. Depending on the kind of files you are dealing with, you may not need it.

For some reason that is not clear to me, the grep version found more occurrences than the find one, which is why I recommend to use grep.

How to check if the docker engine and a docker container are running?

on a Mac you might see the image:

enter image description here

if you right click on the docker icon then you see:

enter image description here

alternatively:

docker ps

and

docker run hello-world

MySQL - Get row number on select

You can use MySQL variables to do it. Something like this should work (though, it consists of two queries).

SELECT 0 INTO @x;

SELECT itemID, 
       COUNT(*) AS ordercount, 
       (@x:=@x+1) AS rownumber 
FROM orders 
GROUP BY itemID 
ORDER BY ordercount DESC; 

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

This was the most simple way to do it imo and it worked for me.

.table-hover tbody tr:hover td {
    background: aqua;
}

Not sure why you would want to change the heading color to the same hover color as the rows but if you do then you can use the above solutions. If you just want t

How do I add button on each row in datatable?

take a look here... this was very helpfull to me https://datatables.net/examples/ajax/null_data_source.html

$(document).ready(function() {
    var table = $('#example').DataTable( {
        "ajax": "data/arrays.txt",
        "columnDefs": [ {
        "targets": -1,
        "data": null,
        "defaultContent": "<button>Click!</button>"
    } ]
} );

$('#example tbody').on( 'click', 'button', function () {
    var data = table.row( $(this).parents('tr') ).data();
    alert( data[0] +"'s salary is: "+ data[ 5 ] );
    } );
} );

ArrayList insertion and retrieval order

Yes it remains the same. but why not easily test it? Make an ArrayList, fill it and then retrieve the elements!

Body of Http.DELETE request in Angular2

In Angular 5, I had to use the request method instead of delete to send a body. The documentation for the delete method does not include body, but it is included in the request method.

import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';

this.http.request('DELETE', url, {
    headers: new HttpHeaders({
        'Content-Type': 'application/json',
    }),
    body: { foo: bar }
});

C# using streams

A stream is an object used to transfer data. There is a generic stream class System.IO.Stream, from which all other stream classes in .NET are derived. The Stream class deals with bytes.

The concrete stream classes are used to deal with other types of data than bytes. For example:

  • The FileStream class is used when the outside source is a file
  • MemoryStream is used to store data in memory
  • System.Net.Sockets.NetworkStream handles network data

Reader/writer streams such as StreamReader and StreamWriter are not streams - they are not derived from System.IO.Stream, they are designed to help to write and read data from and to stream!

Routing for custom ASP.NET MVC 404 Error page

I had the same problem, the thing you have to do is, instead of adding the customErrors attribute in the web.config file in your Views folder, you have to add it in the web.config file in your projects root folder

how to open a page in new tab on button click in asp.net?

Use JavaScript for the main form / Button click event. An example is:

Context.Response.Write("<script language='javascript'>window.open('AccountsStmt.aspx?showledger=" & sledgerGrp & "','_newtab');</script>")

Generating a drop down list of timezones with PHP

Editing Tamas' answer to remove all the "other" entries that the php.net site says should no longer be used.

Maybe doesn't matter, but just following best practices. See notice at bottom of: http://fr2.php.net/manual/en/timezones.others.php

Also, though this list has the Azores as GMT -1, in fact I think it's the same (at least sometimes) as GMT, but not sure.

Editing to offer this in sql so you can create the drop down list in a form and have the user's answer be tied to an index instead.

Editing again to remove leading space

CREATE TABLE IF NOT EXISTS `timezones` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(44) DEFAULT NULL,
  `timezone` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=141 ;

--
-- Dumping data for table `timezones`
--

INSERT INTO `timezones` (`id`, `name`, `timezone`) VALUES
(1, '(GMT-11:00) Midway Island ', 'Pacific/Midway'),
(2, '(GMT-11:00) Samoa ', 'Pacific/Samoa'),
(3, '(GMT-10:00) Hawaii ', 'Pacific/Honolulu'),
(4, '(GMT-09:00) Alaska ', 'America/Anchorage'),
(5, '(GMT-08:00) Pacific Time (US &amp; Canada) ', 'America/Los_Angeles'),
(6, '(GMT-08:00) Tijuana ', 'America/Tijuana'),
(7, '(GMT-07:00) Chihuahua ', 'America/Chihuahua'),
(8, '(GMT-07:00) La Paz ', 'America/Chihuahua'),
(9, '(GMT-07:00) Mazatlan ', 'America/Mazatlan'),
(10, '(GMT-07:00) Mountain Time (US &amp; Canada) ', 'America/Denver'),
(11, '(GMT-06:00) Central America ', 'America/Managua'),
(12, '(GMT-06:00) Central Time (US &amp; Canada) ', 'America/Chicago'),
(13, '(GMT-06:00) Guadalajara ', 'America/Mexico_City'),
(14, '(GMT-06:00) Mexico City ', 'America/Mexico_City'),
(15, '(GMT-06:00) Monterrey ', 'America/Monterrey'),
(16, '(GMT-05:00) Bogota ', 'America/Bogota'),
(17, '(GMT-05:00) Eastern Time (US &amp; Canada) ', 'America/New_York'),
(18, '(GMT-05:00) Lima ', 'America/Lima'),
(19, '(GMT-05:00) Quito ', 'America/Bogota'),
(20, '(GMT-04:00) Atlantic Time (Canada) ', 'Canada/Atlantic'),
(21, '(GMT-04:30) Caracas ', 'America/Caracas'),
(22, '(GMT-04:00) La Paz ', 'America/La_Paz'),
(23, '(GMT-04:00) Santiago ', 'America/Santiago'),
(24, '(GMT-03:30) Newfoundland ', 'America/St_Johns'),
(25, '(GMT-03:00) Brasilia ', 'America/Sao_Paulo'),
(26, '(GMT-03:00) Buenos Aires ', 'America/Argentina/Buenos_Aires'),
(27, '(GMT-03:00) Georgetown ', 'America/Argentina/Buenos_Aires'),
(28, '(GMT-03:00) Greenland ', 'America/Godthab'),
(29, '(GMT-02:00) Mid-Atlantic ', 'America/Noronha'),
(30, '(GMT-01:00) Azores ', 'Atlantic/Azores'),
(31, '(GMT-01:00) Cape Verde Is. ', 'Atlantic/Cape_Verde'),
(32, '(GMT+00:00) Casablanca ', 'Africa/Casablanca'),
(33, '(GMT+00:00) Edinburgh ', 'Europe/London'),
(34, '(GMT+00:00) Dublin ', 'Europe/Dublin'),
(35, '(GMT+00:00) Lisbon ', 'Europe/Lisbon'),
(36, '(GMT+00:00) London ', 'Europe/London'),
(37, '(GMT+00:00) Monrovia ', 'Africa/Monrovia'),
(38, '(GMT+00:00) UTC ', 'UTC'),
(39, '(GMT+01:00) Amsterdam ', 'Europe/Amsterdam'),
(40, '(GMT+01:00) Belgrade ', 'Europe/Belgrade'),
(41, '(GMT+01:00) Berlin ', 'Europe/Berlin'),
(42, '(GMT+01:00) Bern ', 'Europe/Berlin'),
(43, '(GMT+01:00) Bratislava ', 'Europe/Bratislava'),
(44, '(GMT+01:00) Brussels ', 'Europe/Brussels'),
(45, '(GMT+01:00) Budapest ', 'Europe/Budapest'),
(46, '(GMT+01:00) Copenhagen ', 'Europe/Copenhagen'),
(47, '(GMT+01:00) Ljubljana ', 'Europe/Ljubljana'),
(48, '(GMT+01:00) Madrid ', 'Europe/Madrid'),
(49, '(GMT+01:00) Paris ', 'Europe/Paris'),
(50, '(GMT+01:00) Prague ', 'Europe/Prague'),
(51, '(GMT+01:00) Rome ', 'Europe/Rome'),
(52, '(GMT+01:00) Sarajevo ', 'Europe/Sarajevo'),
(53, '(GMT+01:00) Skopje ', 'Europe/Skopje'),
(54, '(GMT+01:00) Stockholm ', 'Europe/Stockholm'),
(55, '(GMT+01:00) Vienna ', 'Europe/Vienna'),
(56, '(GMT+01:00) Warsaw ', 'Europe/Warsaw'),
(57, '(GMT+01:00) West Central Africa ', 'Africa/Lagos'),
(58, '(GMT+01:00) Zagreb ', 'Europe/Zagreb'),
(59, '(GMT+02:00) Athens ', 'Europe/Athens'),
(60, '(GMT+02:00) Bucharest ', 'Europe/Bucharest'),
(61, '(GMT+02:00) Cairo ', 'Africa/Cairo'),
(62, '(GMT+02:00) Harare ', 'Africa/Harare'),
(63, '(GMT+02:00) Helsinki ', 'Europe/Helsinki'),
(64, '(GMT+02:00) Istanbul ', 'Europe/Istanbul'),
(65, '(GMT+02:00) Jerusalem ', 'Asia/Jerusalem'),
(66, '(GMT+02:00) Kyiv ', 'Europe/Helsinki'),
(67, '(GMT+02:00) Pretoria ', 'Africa/Johannesburg'),
(68, '(GMT+02:00) Riga ', 'Europe/Riga'),
(69, '(GMT+02:00) Sofia ', 'Europe/Sofia'),
(70, '(GMT+02:00) Tallinn ', 'Europe/Tallinn'),
(71, '(GMT+02:00) Vilnius ', 'Europe/Vilnius'),
(72, '(GMT+03:00) Baghdad ', 'Asia/Baghdad'),
(73, '(GMT+03:00) Kuwait ', 'Asia/Kuwait'),
(74, '(GMT+03:00) Minsk ', 'Europe/Minsk'),
(75, '(GMT+03:00) Nairobi ', 'Africa/Nairobi'),
(76, '(GMT+03:00) Riyadh ', 'Asia/Riyadh'),
(77, '(GMT+03:00) Volgograd ', 'Europe/Volgograd'),
(78, '(GMT+03:30) Tehran ', 'Asia/Tehran'),
(79, '(GMT+04:00) Abu Dhabi ', 'Asia/Muscat'),
(80, '(GMT+04:00) Baku ', 'Asia/Baku'),
(81, '(GMT+04:00) Moscow ', 'Europe/Moscow'),
(82, '(GMT+04:00) Muscat ', 'Asia/Muscat'),
(83, '(GMT+04:00) St. Petersburg ', 'Europe/Moscow'),
(84, '(GMT+04:00) Tbilisi ', 'Asia/Tbilisi'),
(85, '(GMT+04:00) Yerevan ', 'Asia/Yerevan'),
(86, '(GMT+04:30) Kabul ', 'Asia/Kabul'),
(87, '(GMT+05:00) Islamabad ', 'Asia/Karachi'),
(88, '(GMT+05:00) Karachi ', 'Asia/Karachi'),
(89, '(GMT+05:00) Tashkent ', 'Asia/Tashkent'),
(90, '(GMT+05:30) Chennai ', 'Asia/Calcutta'),
(91, '(GMT+05:30) Kolkata ', 'Asia/Kolkata'),
(92, '(GMT+05:30) Mumbai ', 'Asia/Calcutta'),
(93, '(GMT+05:30) New Delhi ', 'Asia/Calcutta'),
(94, '(GMT+05:30) Sri Jayawardenepura ', 'Asia/Calcutta'),
(95, '(GMT+05:45) Kathmandu ', 'Asia/Katmandu'),
(96, '(GMT+06:00) Almaty ', 'Asia/Almaty'),
(97, '(GMT+06:00) Astana ', 'Asia/Dhaka'),
(98, '(GMT+06:00) Dhaka ', 'Asia/Dhaka'),
(99, '(GMT+06:00) Ekaterinburg ', 'Asia/Yekaterinburg'),
(100, '(GMT+06:30) Rangoon ', 'Asia/Rangoon'),
(101, '(GMT+07:00) Bangkok ', 'Asia/Bangkok'),
(102, '(GMT+07:00) Hanoi ', 'Asia/Bangkok'),
(103, '(GMT+07:00) Jakarta ', 'Asia/Jakarta'),
(104, '(GMT+07:00) Novosibirsk ', 'Asia/Novosibirsk'),
(105, '(GMT+08:00) Beijing ', 'Asia/Hong_Kong'),
(106, '(GMT+08:00) Chongqing ', 'Asia/Chongqing'),
(107, '(GMT+08:00) Hong Kong ', 'Asia/Hong_Kong'),
(108, '(GMT+08:00) Krasnoyarsk ', 'Asia/Krasnoyarsk'),
(109, '(GMT+08:00) Kuala Lumpur ', 'Asia/Kuala_Lumpur'),
(110, '(GMT+08:00) Perth ', 'Australia/Perth'),
(111, '(GMT+08:00) Singapore ', 'Asia/Singapore'),
(112, '(GMT+08:00) Taipei ', 'Asia/Taipei'),
(113, '(GMT+08:00) Ulaan Bataar ', 'Asia/Ulan_Bator'),
(114, '(GMT+08:00) Urumqi ', 'Asia/Urumqi'),
(115, '(GMT+09:00) Irkutsk ', 'Asia/Irkutsk'),
(116, '(GMT+09:00) Osaka ', 'Asia/Tokyo'),
(117, '(GMT+09:00) Sapporo ', 'Asia/Tokyo'),
(118, '(GMT+09:00) Seoul ', 'Asia/Seoul'),
(119, '(GMT+09:00) Tokyo ', 'Asia/Tokyo'),
(120, '(GMT+09:30) Adelaide ', 'Australia/Adelaide'),
(121, '(GMT+09:30) Darwin ', 'Australia/Darwin'),
(122, '(GMT+10:00) Brisbane ', 'Australia/Brisbane'),
(123, '(GMT+10:00) Canberra ', 'Australia/Canberra'),
(124, '(GMT+10:00) Guam ', 'Pacific/Guam'),
(125, '(GMT+10:00) Hobart ', 'Australia/Hobart'),
(126, '(GMT+10:00) Melbourne ', 'Australia/Melbourne'),
(127, '(GMT+10:00) Port Moresby ', 'Pacific/Port_Moresby'),
(128, '(GMT+10:00) Sydney ', 'Australia/Sydney'),
(129, '(GMT+10:00) Yakutsk ', 'Asia/Yakutsk'),
(130, '(GMT+11:00) Vladivostok ', 'Asia/Vladivostok'),
(131, '(GMT+12:00) Auckland ', 'Pacific/Auckland'),
(132, '(GMT+12:00) Fiji ', 'Pacific/Fiji'),
(133, '(GMT+12:00) International Date Line West ', 'Pacific/Kwajalein'),
(134, '(GMT+12:00) Kamchatka ', 'Asia/Kamchatka'),
(135, '(GMT+12:00) Magadan ', 'Asia/Magadan'),
(136, '(GMT+12:00) Marshall Is. ', 'Pacific/Fiji'),
(137, '(GMT+12:00) New Caledonia ', 'Asia/Magadan'),
(138, '(GMT+12:00) Solomon Is. ', 'Asia/Magadan'),
(139, '(GMT+12:00) Wellington ', 'Pacific/Auckland'),
(140, '(GMT+13:00) Nuku\\alofa ', 'Pacific/Tongatapu');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Convert LocalDateTime to LocalDateTime in UTC

There is an even simpler way

LocalDateTime.now(Clock.systemUTC())

Regular expressions inside SQL Server

In order to match a digit, you can use [0-9].

So you could use 5[0-9][0-9][0-9][0-9][0-9][0-9] and [0-9][0-9][0-9][0-9]7[0-9][0-9][0-9]. I do this a lot for zip codes.

Circular gradient in android

I always find images helpful when learning a new concept, so this is a supplemental answer.

enter image description here

The %p means a percentage of the parent, that is, a percentage of the narrowest dimension of whatever view we set our drawable on. The images above were generated by changing the gradientRadius in this code

my_gradient_drawable

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient
        android:type="radial"
        android:gradientRadius="10%p"
        android:startColor="#f6ee19"
        android:endColor="#115ede" />
</shape>

Which can be set on a view's background attribute like this

<View
    android:layout_width="200dp"
    android:layout_height="100dp"
    android:background="@drawable/my_gradient_drawable"/>

Center

You can change the center of the radius with

android:centerX="0.2"
android:centerY="0.7"

where the decimals are fractions of the width and height for x and y respectively.

enter image description here

Documentation

Here are some notes from the documentation explaining things a little more.

android:gradientRadius

Radius of the gradient, used only with radial gradient. May be an explicit dimension or a fractional value relative to the shape's minimum dimension.

May be a floating point value, such as "1.2".

May be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), and mm (millimeters).

May be a fractional value, which is a floating point number appended with either % or %p, such as "14.5%". The % suffix always means a percentage of the base size; the optional %p suffix provides a size relative to some parent container.

How to add http:// if it doesn't exist in the URL

The best answer for this would be something like this:

function addhttp($url, $scheme="http://" )
{
  return $url = empty(parse_url($url)['scheme']) ? $scheme . ltrim($url, '/') : $url;
}

The protocol flexible, so the same function can be used with ftp, https, etc.

forEach loop Java 8 for Map entry set

Stream API

public void iterateStreamAPI(Map<String, Integer> map) {
    map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":"e.getValue()));
}

lvalue required as left operand of assignment

Change = to == i.e if (strcmp("hello", "hello") == 0)

You want to compare the result of strcmp() to 0. So you need ==. Assigning it to 0 won't work because rvalues cannot be assigned to.

How to search JSON tree with jQuery

    var GDNUtils = {};

GDNUtils.loadJquery = function () {
    var checkjquery = window.jQuery && jQuery.fn && /^1\.[3-9]/.test(jQuery.fn.jquery);
    if (!checkjquery) {

        var theNewScript = document.createElement("script");
        theNewScript.type = "text/javascript";
        theNewScript.src = "http://code.jquery.com/jquery.min.js";

        document.getElementsByTagName("head")[0].appendChild(theNewScript);

        // jQuery MAY OR MAY NOT be loaded at this stage


    }
};



GDNUtils.searchJsonValue = function (jsonData, keytoSearch, valuetoSearch, keytoGet) {
    GDNUtils.loadJquery();
    alert('here' + jsonData.length.toString());
    GDNUtils.loadJquery();

    $.each(jsonData, function (i, v) {

        if (v[keytoSearch] == valuetoSearch) {
            alert(v[keytoGet].toString());

            return;
        }
    });



};




GDNUtils.searchJson = function (jsonData, keytoSearch, valuetoSearch) {
    GDNUtils.loadJquery();
    alert('here' + jsonData.length.toString());
    GDNUtils.loadJquery();
    var row;
    $.each(jsonData, function (i, v) {

        if (v[keytoSearch] == valuetoSearch) {


            row  = v;
        }
    });

    return row;



}

How to center text vertically with a large font-awesome icon?

Another option to fine-tune the line height of an icon is by using a percentage of the vertical-align property. Usually, 0% is a the bottom, and 100% at the top, but one could use negative values or more than a hundred to create interesting effects.

.my-element i.fa {
    vertical-align: 100%; // top
    vertical-align: 50%; // middle
    vertical-align: 0%; // bottom
}

How do I create a singleton service in Angular 2?

Jason is completely right! It's caused by the way dependency injection works. It's based on hierarchical injectors.

There are several injectors within an Angular2 application:

  • The root one you configure when bootstrapping your application
  • An injector per component. If you use a component inside another one. The component injector is a child of the parent component one. The application component (the one you specify when boostrapping your application) has the root injector as parent one).

When Angular2 tries to inject something in the component constructor:

  • It looks into the injector associated with the component. If there is matching one, it will use it to get the corresponding instance. This instance is lazily created and is a singleton for this injector.
  • If there is no provider at this level, it will look at the parent injector (and so on).

So if you want to have a singleton for the whole application, you need to have the provider defined either at the level of the root injector or the application component injector.

But Angular2 will look at the injector tree from the bottom. This means that the provider at the lowest level will be used and the scope of the associated instance will be this level.

See this question for more details:

How to suppress scientific notation when printing float values?

Using the newer version ''.format (also remember to specify how many digit after the . you wish to display, this depends on how small is the floating number). See this example:

>>> a = -7.1855143557448603e-17
>>> '{:f}'.format(a)
'-0.000000'

as shown above, default is 6 digits! This is not helpful for our case example, so instead we could use something like this:

>>> '{:.20f}'.format(a)
'-0.00000000000000007186'

Update

Starting in Python 3.6, this can be simplified with the new formatted string literal, as follows:

>>> f'{a:.20f}'
'-0.00000000000000007186'

How to insert data using wpdb

Problem in your SQL :

You can construct your sql like this :

$wpdb->prepare(
 "INSERT INTO `wp_submitted_form` 
   (`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`) 
   values ('$name', '$email', '$phone', '$country', 
         '$course', '$message', '$datesent')"
 );

You can also use $wpdb->insert()

$wpdb->insert('table_name', input_array())

Example of Named Pipes

For someone who is new to IPC and Named Pipes, I found the following NuGet package to be a great help.

GitHub: Named Pipe Wrapper for .NET 4.0

To use first install the package:

PS> Install-Package NamedPipeWrapper

Then an example server (copied from the link):

var server = new NamedPipeServer<SomeClass>("MyServerPipe");
server.ClientConnected += delegate(NamedPipeConnection<SomeClass> conn)
    {
        Console.WriteLine("Client {0} is now connected!", conn.Id);
        conn.PushMessage(new SomeClass { Text: "Welcome!" });
    };

server.ClientMessage += delegate(NamedPipeConnection<SomeClass> conn, SomeClass message)
    {
        Console.WriteLine("Client {0} says: {1}", conn.Id, message.Text);
    };

server.Start();

Example client:

var client = new NamedPipeClient<SomeClass>("MyServerPipe");
client.ServerMessage += delegate(NamedPipeConnection<SomeClass> conn, SomeClass message)
    {
        Console.WriteLine("Server says: {0}", message.Text);
    };

client.Start();

Best thing about it for me is that unlike the accepted answer here it supports multiple clients talking to a single server.

how to get the last character of a string?

Use charAt:

The charAt() method returns the character at the specified index in a string.

You can use this method in conjunction with the length property of a string to get the last character in that string.
For example:

_x000D_
_x000D_
const myString = "linto.yahoo.com.";_x000D_
const stringLength = myString.length; // this will be 16_x000D_
console.log('lastChar: ', myString.charAt(stringLength - 1)); // this will be the string
_x000D_
_x000D_
_x000D_

How to make inline plots in Jupyter Notebook larger?

A quick fix to "plot overlap" is to use plt.tight_layout():

Example (in my case)

for i,var in enumerate(categorical_variables):
    plt.title(var)
    plt.xticks(rotation=45)
    df[var].hist()
    plt.subplot(len(categorical_variables)/2, 2, i+1)

plt.tight_layout()

How do I get the name of a Ruby class?

Both result.class.to_s and result.class.name work.

How to vertically align an image inside a div

The only (and the best cross-browser) way as I know is to use an inline-block helper with height: 100% and vertical-align: middle on both elements.

So there is a solution: http://jsfiddle.net/kizu/4RPFa/4570/

_x000D_
_x000D_
.frame {_x000D_
    height: 25px;      /* Equals maximum image height */_x000D_
    width: 160px;_x000D_
    border: 1px solid red;_x000D_
    white-space: nowrap; /* This is required unless you put the helper span closely near the img */_x000D_
_x000D_
    text-align: center;_x000D_
    margin: 1em 0;_x000D_
}_x000D_
_x000D_
.helper {_x000D_
    display: inline-block;_x000D_
    height: 100%;_x000D_
    vertical-align: middle;_x000D_
}_x000D_
_x000D_
img {_x000D_
    background: #3A6F9A;_x000D_
    vertical-align: middle;_x000D_
    max-height: 25px;_x000D_
    max-width: 160px;_x000D_
}
_x000D_
<div class="frame">_x000D_
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=250px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=25px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=23px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=21px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=19px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=17px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=15px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=13px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=11px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=9px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=7px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=5px />_x000D_
</div>_x000D_
<div class="frame">_x000D_
    <span class="helper"></span>_x000D_
    <img src="http://jsfiddle.net/img/logo.png" height=3px />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or, if you don't want to have an extra element in modern browsers and don't mind using Internet Explorer expressions, you can use a pseudo-element and add it to Internet Explorer using a convenient Expression, that runs only once per element, so there won't be any performance issues:

The solution with :before and expression() for Internet Explorer: http://jsfiddle.net/kizu/4RPFa/4571/

_x000D_
_x000D_
.frame {_x000D_
    height: 25px;      /* Equals maximum image height */_x000D_
    width: 160px;_x000D_
    border: 1px solid red;_x000D_
    white-space: nowrap;_x000D_
_x000D_
    text-align: center;_x000D_
    margin: 1em 0;_x000D_
}_x000D_
_x000D_
.frame:before,_x000D_
.frame_before {_x000D_
    content: "";_x000D_
    display: inline-block;_x000D_
    height: 100%;_x000D_
    vertical-align: middle;_x000D_
}_x000D_
_x000D_
img {_x000D_
    background: #3A6F9A;_x000D_
    vertical-align: middle;_x000D_
    max-height: 25px;_x000D_
    max-width: 160px;_x000D_
}_x000D_
_x000D_
/* Move this to conditional comments */_x000D_
.frame {_x000D_
    list-style:none;_x000D_
    behavior: expression(_x000D_
        function(t){_x000D_
            t.insertAdjacentHTML('afterBegin','<span class="frame_before"></span>');_x000D_
            t.runtimeStyle.behavior = 'none';_x000D_
        }(this)_x000D_
    );_x000D_
}
_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=250px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=25px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=23px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=21px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=19px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=17px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=15px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=13px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=11px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=9px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=7px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=5px /></div>_x000D_
<div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=3px /></div>
_x000D_
_x000D_
_x000D_


How it works:

  1. When you have two inline-block elements near each other, you can align each to other's side, so with vertical-align: middle you'll get something like this:

    Two aligned blocks

  2. When you have a block with fixed height (in px, em or another absolute unit), you can set the height of inner blocks in %.

  3. So, adding one inline-block with height: 100% in a block with fixed height would align another inline-block element in it (<img/> in your case) vertically near it.

jQuery vs document.querySelectorAll

document.querySelectorAll() has several inconsistencies across browsers and is not supported in older browsersThis probably won't cause any trouble anymore nowadays. It has a very unintuitive scoping mechanism and some other not so nice features. Also with javascript you have a harder time working with the result sets of these queries, which in many cases you might want to do. jQuery provides functions to work on them like: filter(), find(), children(), parent(), map(), not() and several more. Not to mention the jQuery ability to work with pseudo-class selectors.

However, I would not consider these things as jQuery's strongest features but other things like "working" on the dom (events, styling, animation & manipulation) in a crossbrowser compatible way or the ajax interface.

If you only want the selector engine from jQuery you can use the one jQuery itself is using: Sizzle That way you have the power of jQuerys Selector engine without the nasty overhead.

EDIT: Just for the record, I'm a huge vanilla JavaScript fan. Nonetheless it's a fact that you sometimes need 10 lines of JavaScript where you would write 1 line jQuery.

Of course you have to be disciplined to not write jQuery like this:

$('ul.first').find('.foo').css('background-color', 'red').end().find('.bar').css('background-color', 'green').end();

This is extremely hard to read, while the latter is pretty clear:

$('ul.first')
   .find('.foo')
      .css('background-color', 'red')
.end()
   .find('.bar')
      .css('background-color', 'green')
.end();

The equivalent JavaScript would be far more complex illustrated by the pseudocode above:

1) Find the element, consider taking all element or only the first.

// $('ul.first')
// taking querySelectorAll has to be considered
var e = document.querySelector("ul.first");

2) Iterate over the array of child nodes via some (possibly nested or recursive) loops and check the class (classlist not available in all browsers!)

//.find('.foo')
for (var i = 0;i<e.length;i++){
     // older browser don't have element.classList -> even more complex
     e[i].children.classList.contains('foo');
     // do some more magic stuff here
}

3) apply the css style

// .css('background-color', 'green')
// note different notation
element.style.backgroundColor = "green" // or
element.style["background-color"] = "green"

This code would be at least two times as much lines of code you write with jQuery. Also you would have to consider cross-browser issues which will compromise the severe speed advantage (besides from the reliability) of the native code.

How do I prevent and/or handle a StackOverflowException?

This answer is for @WilliamJockusch.

I'm wondering if there is a general way to track down StackOverflowExceptions. In other words, suppose I have infinite recursion somewhere in my code, but I have no idea where. I want to track it down by some means that is easier than stepping through code all over the place until I see it happening. I don't care how hackish it is. For example, It would be great to have a module I could activate, perhaps even from another thread, that polled the stack depth and complained if it got to a level I considered "too high." For example, I might set "too high" to 600 frames, figuring that if the stack were too deep, that has to be a problem. Is something like that possible. Another example would be to log every 1000th method call within my code to the debug output. The chances this would get some evidence of the overlow would be pretty good, and it likely would not blow up the output too badly. The key is that it cannot involve writing a check wherever the overflow is happening. Because the entire problem is that I don't know where that is. Preferrably the solution should not depend on what my development environment looks like; i.e, it should not assumet that I am using C# via a specific toolset (e.g. VS).

It sounds like you're keen to hear some debugging techniques to catch this StackOverflow so I thought I would share a couple for you to try.

1. Memory Dumps.

Pro's: Memory Dumps are a sure fire way to work out the cause of a Stack Overflow. A C# MVP & I worked together troubleshooting a SO and he went on to blog about it here.

This method is the fastest way to track down the problem.

This method wont require you to reproduce problems by following steps seen in logs.

Con's: Memory Dumps are very large and you have to attach AdPlus/procdump the process.

2. Aspect Orientated Programming.

Pro's: This is probably the easiest way for you to implement code that checks the size of the call stack from any method without writing code in every method of your application. There are a bunch of AOP Frameworks that allow you to Intercept before and after calls.

Will tell you the methods that are causing the Stack Overflow.

Allows you to check the StackTrace().FrameCount at the entry and exit of all methods in your application.

Con's: It will have a performance impact - the hooks are embedded into the IL for every method and you cant really "de-activate" it out.

It somewhat depends on your development environment tool set.

3. Logging User Activity.

A week ago I was trying to hunt down several hard to reproduce problems. I posted this QA User Activity Logging, Telemetry (and Variables in Global Exception Handlers) . The conclusion I came to was a really simple user-actions-logger to see how to reproduce problems in a debugger when any unhandled exception occurs.

Pro's: You can turn it on or off at will (ie subscribing to events).

Tracking the user actions doesn't require intercepting every method.

You can count the number of events methods are subscribed too far more simply than with AOP.

The log files are relatively small and focus on what actions you need to perform to reproduce the problem.

It can help you to understand how users are using your application.

Con's: Isn't suited to a Windows Service and I'm sure there are better tools like this for web apps.

Doesn't necessarily tell you the methods that cause the Stack Overflow.

Requires you to step through logs manually reproducing problems rather than a Memory Dump where you can get it and debug it straight away.

 


Maybe you might try all techniques I mention above and some that @atlaste posted and tell us which one's you found were the easiest/quickest/dirtiest/most acceptable to run in a PROD environment/etc.

Anyway good luck tracking down this SO.

How to add a default "Select" option to this ASP.NET DropDownList control?

Private Sub YourWebPage_PreRenderComplete(sender As Object, e As EventArgs) Handles Me.PreRenderComplete

     If Not IsPostBack Then
     DropDownList1.Items.Insert(0, "Select")
     End If

End Sub

What is the difference between a heuristic and an algorithm?

An algorithm is a self-contained step-by-step set of operations to be performed 4, typically interpreted as a finite sequence of (computer or human) instructions to determine a solution to a problem such as: is there a path from A to B, or what is the smallest path between A and B. In the latter case, you could also be satisfied with a 'reasonably close' alternative solution.

There are certain categories of algorithms, of which the heuristic algorithm is one. Depending on the (proven) properties of the algorithm in this case, it falls into one of these three categories (note 1):

  • Exact: the solution is proven to be an optimal (or exact solution) to the input problem
  • Approximation: the deviation of the solution value is proven to be never further away from the optimal value than some pre-defined bound (for example, never more than 50% larger than the optimal value)
  • Heuristic: the algorithm has not been proven to be optimal, nor within a pre-defined bound of the optimal solution

Notice that an approximation algorithm is also a heuristic, but with the stronger property that there is a proven bound to the solution (value) it outputs.

For some problems, noone has ever found an 'efficient' algorithm to compute the optimal solutions (note 2). One of those problems is the well-known Traveling Salesman Problem. Christophides' algorithm for the Traveling Salesman Problem, for example, used to be called a heuristic, as it was not proven that it was within 50% of the optimal solution. Since it has been proven, however, Christophides' algorithm is more accurately referred to as an approximation algorithm.

Due to restrictions on what computers can do, it is not always possible to efficiently find the best solution possible. If there is enough structure in a problem, there may be an efficient way to traverse the solution space, even though the solution space is huge (i.e. in the shortest path problem).

Heuristics are typically applied to improve the running time of algorithms, by adding 'expert information' or 'educated guesses' to guide the search direction. In practice, a heuristic may also be a sub-routine for an optimal algorithm, to determine where to look first.

(note 1): Additionally, algorithms are characterised by whether they include random or non-deterministic elements. An algorithm that always executes the same way and produces the same answer, is called deterministic.

(note 2): This is called the P vs NP problem, and problems that are classified as NP-complete and NP-hard are unlikely to have an 'efficient' algorithm. Note; as @Kriss mentioned in the comments, there are even 'worse' types of problems, which may need exponential time or space to compute.

There are several answers that answer part of the question. I deemed them less complete and not accurate enough, and decided not to edit the accepted answer made by @Kriss

How to set UICollectionViewCell Width and Height programmatically

Finally got the answer. You should extend UICollectionViewDelegateFlowLayout
This should be working with answers above.

add column to mysql table if it does not exist

Here is my PHP/PDO solution to do that :

function addColumnIfNotExists($db, $table, $col, $type, $null = true) {
    global $pdo;
    if($res = $pdo->query("SHOW COLUMNS FROM `$db`.`$table` WHERE `Field`='$col'")) {
        if(!$res = $res->fetchAll(PDO::FETCH_ASSOC)) {
            $null = ($null ? 'NULL' : 'NOT NULL');
            $pdo->query("ALTER TABLE `$db`.`$table` ADD `$col` $type $null");
        }
    }
}

Note that it will automatically add the column in the end of the table. I havent implemented the DEFAULT part of query.

Why aren't Xcode breakpoints functioning?

There appears to be 3 states for the breakpoints in Xcode. If you click on them they'll go through the different settings. Dark blue is enabled, grayed out is disabled and I've seen a pale blue sometimes that required me to click on the breakpoint again to get it to go to the dark blue color.

Other than this make sure that you're launching it with the debug command not the run command. You can do that by either hitting option + command + return, or the Go (debug) option from the run menu.

Can we install Android OS on any Windows Phone and vice versa, and same with iPhone and vice versa?

Android needs to be compiled for every hardware plattform / every device model seperatly with the specific drivers etc. If you manage to do that you need also break the security arrangements every manufacturer implements to prevent the installation of other software - these are also different between each model / manufacturer. So it is possible at in theory, but only there :-)

How to "git show" a merge commit with combined diff output even when every changed file agrees with one of the parents?

in your case you just need to

git diff HEAD^ HEAD^2

or just hash for you commit:

git diff 0e1329e55^ 0e1329e55^2

Watch multiple $scope attributes

$watch first parameter can be angular expression or function. See documentation on $scope.$watch. It contains a lot of useful info about how $watch method works: when watchExpression is called, how angular compares results, etc.

Get table names using SELECT statement in MySQL

I think it may be helpful to point out that if you want to select tables that contain specific words you can easily do it using the SELECT (instead of SHOW). Below query easily narrows down the search to tables that contain "keyword"

SELECT *
FROM information_schema.tables
WHERE table_name like "%keyword%"

Show / hide div on click with CSS

HTML

<input type="text" value="CLICK TO SHOW CONTENT">
<div id="content">
and the content will show.
</div>

CSS

_x000D_
_x000D_
#content {
  display: none;
}
input[type="text"]{
    color: transparent;
    text-shadow: 0 0 0 #000;
    padding: 6px 12px;
    width: 150px;
    cursor: pointer;
}
input[type="text"]:focus{
    outline: none;
}
input:focus + div#content {
  display: block;
}
_x000D_
<input type="text" value="CLICK TO SHOW CONTENT">
<div id="content">
and the content will show.
</div>
_x000D_
_x000D_
_x000D_

Clear android application user data

If you want to do manually then You also can clear your user data by clicking “Clear Data” button in Settings–>Applications–>Manage Aplications–> YOUR APPLICATION

or Is there any other way to do that?

Then Download code here

enter image description here

How to convert int to float in C?

I routinely multiply by 1.0 if I want floating point, it's easier than remembering the rules.

JSLint is suddenly reporting: Use the function form of "use strict"

There's nothing innately wrong with the string form.

Rather than avoid the "global" strict form for worry of concatenating non-strict javascript, it's probably better to just fix the damn non-strict javascript to be strict.

how to set value of a input hidden field through javascript?

You need to run your script after the element exists. Move the <input type="hidden" name="checkyear" id="checkyear" value=""> to the beginning.

Get the closest number out of an array

A simpler way with O(n) time complexity is to do this in one iteration of the array. This method is intended for unsorted arrays.

Following is a javascript example, here from the array we find the number which is nearest to "58".

_x000D_
_x000D_
var inputArr = [150, 5, 200, 50, 30];
var search = 58;
var min = Math.min();
var result = 0;
for(i=0;i<inputArr.length;i++) {
  let absVal = Math.abs(search - inputArr[i])
  if(min > absVal) {
    min=absVal;
    result = inputArr[i];
  }
}
console.log(result); //expected output 50 if input is 58
_x000D_
_x000D_
_x000D_

This will work for positive, negative, decimal numbers as well.

Math.min() will return Infinity.

The result will store the value nearest to the search element.

Send values from one form to another form

Ok so Form1 has a textbox, first of all you have to set this Form1 textbox to public in textbox property.

Code Form1:

Public button1_click()
{
    Form2 secondForm = new Form2(this);
    secondForm.Show();
}

Pass Form1 as this in the constructor.

Code Form2:

Private Form1 _firstForm;

Public Form2(Form1 firstForm)
{
    _firstForm = firstForm:
}

Public button_click()
{
    _firstForm.textBox.text=label1.text;
    This.Close();
}

Disable same origin policy in Chrome

For windows users with Chrome Versions 60.0.3112.78 (the day the solution was tested and worked) and at least until today 19.01.2019 (ver. 71.0.3578.98). You do not need to close any chrome instance.

  1. Create a shortcut on your desktop
  2. Right-click on the shortcut and click Properties
  3. Edit the Target property
  4. Set it to "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:/ChromeDevSession"
  5. Start chrome and ignore the message that says --disable-web-security is not supported!

BEWARE NOT TO USE THIS PARTICULAR BROWSER INSTANCE FOR BROWSING BECAUSE YOU CAN BE HACKED WITH IT!

Make footer stick to bottom of page using Twitter Bootstrap

As discussed in the comments you have based your code on this solution: https://stackoverflow.com/a/8825714/681807

One of the key parts of this solution is to add height: 100% to html, body so the #footer element has a base height to work from - this is missing from your code:

html,body{
    height: 100%
}

You will also find that you will run into problems with using bottom: -50px as this will push your content under the fold when there isn't much content. You will have to add margin-bottom: 50px to the last element before the #footer.

Where is the Postgresql config file: 'postgresql.conf' on Windows?

On my machine:

C:\Program Files (x86)\OpenERP 6.1-20121026-233219\PostgreSQL\data

How to copy Java Collections list

the simplest way to copy a List is to pass it to the constructor of the new list:

List<String> b = new ArrayList<>(a);

b will be a shallow copy of a

Looking at the source of Collections.copy(List,List) (I'd never seen it before) it seems to be for coping the elements index by index. using List.set(int,E) thus element 0 will over write element 0 in the target list etc etc. Not particularly clear from the javadocs I'd have to admit.

List<String> a = new ArrayList<>(a);
a.add("foo");
b.add("bar");

List<String> b = new ArrayList<>(a); // shallow copy 'a'

// the following will all hold
assert a.get(0) == b.get(0);
assert a.get(1) == b.get(1);
assert a.equals(b);
assert a != b; // 'a' is not the same object as 'b'

Convert varchar into datetime in SQL Server

I found this helpful for my conversion, without string manipulation. https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql

CONVERT(VARCHAR(23), @lastUploadEndDate, 121)

yyyy-mm-dd hh:mi:ss.mmm(24h) was the format I needed.

how to remove untracked files in Git?

User interactive approach:

git clean -i -fd

Remove .classpath [y/N]? N
Remove .gitignore [y/N]? N
Remove .project [y/N]? N
Remove .settings/ [y/N]? N
Remove src/com/amazon/arsdumpgenerator/inspector/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/s3/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/s3/ [y/N]? y

-i for interactive
-f for force
-d for directory
-x for ignored files(add if required)

Note: Add -n or --dry-run to just check what it will do.

How do I vertically align text in a paragraph?

Below styles will vertically center it for you.

p.event_desc {
 font: bold 12px "Helvetica Neue", Helvetica, Arial, sans-serif;
 line-height: 14px;
 height: 35px;
 display: table-cell;
 vertical-align: middle;
 margin: 0px;
}

Using SED with wildcard

So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.

syntax for creating a dictionary into another dictionary in python

You can declare a dictionary inside a dictionary by nesting the {} containers:

d = {'dict1': {'foo': 1, 'bar': 2}, 'dict2': {'baz': 3, 'quux': 4}}

And then you can access the elements using the [] syntax:

print d['dict1']           # {'foo': 1, 'bar': 2}
print d['dict1']['foo']    # 1
print d['dict2']['quux']   # 4

Given the above, if you want to add another dictionary to the dictionary, it can be done like so:

d['dict3'] = {'spam': 5, 'ham': 6}

or if you prefer to add items to the internal dictionary one by one:

d['dict4'] = {}
d['dict4']['king'] = 7
d['dict4']['queen'] = 8

"message failed to fetch from registry" while trying to install any module

For me, it's usually a proxy issue, and I try everything:

npm config set registry http://registry.npmjs.org/
npm config set strict-ssl false

npm config set proxy http://myusername:[email protected]:8080
npm config set https-proxy http://myusername:[email protected]:8080
set HTTPS_PROXY=http://myusername:[email protected]:8080
set HTTP_PROXY=http://myusername:[email protected]:8080
export HTTPS_PROXY=http://myusername:[email protected]:8080
export HTTP_PROXY=http://myusername:[email protected]:8080
export http_proxy=http://myusername:[email protected]:8080

npm --proxy http://myusername:[email protected]:8080 \
--without-ssl --insecure -g install

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

@skaffman nailed it down. They live each in its own context. However, I wouldn't consider using scriptlets as the solution. You'd like to avoid them. If all you want is to concatenate strings in EL and you discovered that the + operator fails for strings in EL (which is correct), then just do:

<c:out value="abc${test}" />

Or if abc is to obtained from another scoped variable named ${resp}, then do:

<c:out value="${resp}${test}" />

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

One follow up to this. I had installed SQL Server 2014 with only Windows Authentication. After enabling Mixed Mode, I couldn't log in with a SQL user and got the same error message as the original poster. I verified that named pipes were enabled but still couldn't log in after several restarts. Using 127.0.0.1 instead of the hostname allowed me to log in, but interestingly, required a password reset prompt on first login:

SQL Server Password Reset Prompt

Once I reset the password the account worked. What's odd, is I specifically disabled password policy and expiration.

How to run an application as "run as administrator" from the command prompt?

It looks like psexec -h is the way to do this:

 -h         If the target system is Windows Vista or higher, has the process
            run with the account's elevated token, if available.

Which... doesn't seem to be listed in the online documentation in Sysinternals - PsExec.

But it works on my machine.

Difference between @Mock and @InjectMocks

This is a sample code on how @Mock and @InjectMocks works.

Say we have Game and Player class.

class Game {

    private Player player;

    public Game(Player player) {
        this.player = player;
    }

    public String attack() {
        return "Player attack with: " + player.getWeapon();
    }

}

class Player {

    private String weapon;

    public Player(String weapon) {
        this.weapon = weapon;
    }

    String getWeapon() {
        return weapon;
    }
}

As you see, Game class need Player to perform an attack.

@RunWith(MockitoJUnitRunner.class)
class GameTest {

    @Mock
    Player player;

    @InjectMocks
    Game game;

    @Test
    public void attackWithSwordTest() throws Exception {
        Mockito.when(player.getWeapon()).thenReturn("Sword");

        assertEquals("Player attack with: Sword", game.attack());
    }

}

Mockito will mock a Player class and it's behaviour using when and thenReturn method. Lastly, using @InjectMocks Mockito will put that Player into Game.

Notice that you don't even have to create a new Game object. Mockito will inject it for you.

// you don't have to do this
Game game = new Game(player);

We will also get same behaviour using @Spy annotation. Even if the attribute name is different.

@RunWith(MockitoJUnitRunner.class)
public class GameTest {

  @Mock Player player;

  @Spy List<String> enemies = new ArrayList<>();

  @InjectMocks Game game;

  @Test public void attackWithSwordTest() throws Exception {
    Mockito.when(player.getWeapon()).thenReturn("Sword");

    enemies.add("Dragon");
    enemies.add("Orc");

    assertEquals(2, game.numberOfEnemies());

    assertEquals("Player attack with: Sword", game.attack());
  }
}

class Game {

  private Player player;

  private List<String> opponents;

  public Game(Player player, List<String> opponents) {
    this.player = player;
    this.opponents = opponents;
  }

  public int numberOfEnemies() {
    return opponents.size();
  }

  // ...

That's because Mockito will check the Type Signature of Game class, which is Player and List<String>.

Check if ADODB connection is open

ADO Recordset has .State property, you can check if its value is adStateClosed or adStateOpen

If Not (rs Is Nothing) Then
  If (rs.State And adStateOpen) = adStateOpen Then rs.Close
  Set rs = Nothing
End If

MSDN about State property

Edit; The reason not to check .State against 1 or 0 is because even if it works 99.99% of the time, it is still possible to have other flags set which will cause the If statement fail the adStateOpen check.

Edit2:

For Late binding without the ActiveX Data Objects referenced, you have few options. Use the value of adStateOpen constant from ObjectStateEnum

If Not (rs Is Nothing) Then
  If (rs.State And 1) = 1 Then rs.Close
  Set rs = Nothing
End If

Or you can define the constant yourself to make your code more readable (defining them all for a good example.)

Const adStateClosed As Long = 0 'Indicates that the object is closed.
Const adStateOpen As Long = 1 'Indicates that the object is open.
Const adStateConnecting As Long = 2 'Indicates that the object is connecting.
Const adStateExecuting As Long = 4 'Indicates that the object is executing a command.
Const adStateFetching As Long = 8 'Indicates that the rows of the object are being retrieved.    

[...]

If Not (rs Is Nothing) Then

    ' ex. If (0001 And 0001) = 0001 (only open flag) -> true
    ' ex. If (1001 And 0001) = 0001 (open and retrieve) -> true
    '    This second example means it is open, but its value is not 1
    '    and If rs.State = 1 -> false, even though it is open
    If (rs.State And adStateOpen) = adStateOpen Then 
        rs.Close
    End If

    Set rs = Nothing
End If

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

We can also use

return $this->db->count_all('table_name');  

or

$this->db->from('table_name');
return $this->db->count_all_result();

or

return $this->db->count_all_result('table_name');

or

$query = $this->db->query('select * from tab');  
return $query->num_rows();

What is the ellipsis (...) for in this method signature?

The three dot (...) notation is actually borrowed from mathematics, and it means "...and so on".

As for its use in Java, it stands for varargs, meaning that any number of arguments can be added to the method call. The only limitations are that the varargs must be at the end of the method signature and there can only be one per method.

In MySQL, how to copy the content of one table to another table within the same database?

INSERT INTO TARGET_TABLE SELECT * FROM SOURCE_TABLE;

EDIT: or if the tables have different structures you can also:

INSERT INTO TARGET_TABLE (`col1`,`col2`) SELECT `col1`,`col2` FROM SOURCE_TABLE;

EDIT: to constrain this..

INSERT INTO TARGET_TABLE (`col1_`,`col2_`) SELECT `col1`,`col2` FROM SOURCE_TABLE WHERE `foo`=1

PHP - check if variable is undefined

JavaScript's 'strict not equal' operator (!==) on comparison with undefined does not result in false on null values.

var createTouch = null;
isTouch = createTouch !== undefined  // true

To achieve an equivalent behaviour in PHP, you can check whether the variable name exists in the keys of the result of get_defined_vars().

// just to simplify output format
const BR = '<br>' . PHP_EOL;

// set a global variable to test independence in local scope
$test = 1;

// test in local scope (what is working in global scope as well)
function test()
{
  // is global variable found?
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test does not exist.

  // is local variable found?
  $test = null;
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test exists.

  // try same non-null variable value as globally defined as well
  $test = 1;
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.' ) . BR;
  // $test exists.

  // repeat test after variable is unset
  unset($test);
  echo '$test ' . ( array_key_exists('test', get_defined_vars())
                    ? 'exists.' : 'does not exist.') . BR;
  // $test does not exist.
}

test();

In most cases, isset($variable) is appropriate. That is aquivalent to array_key_exists('variable', get_defined_vars()) && null !== $variable. If you just use null !== $variable without prechecking for existence, you will mess up your logs with warnings because that is an attempt to read the value of an undefined variable.

However, you can apply an undefined variable to a reference without any warning:

// write our own isset() function
function my_isset(&$var)
{
  // here $var is defined
  // and initialized to null if the given argument was not defined
  return null === $var;
}

// passing an undefined variable by reference does not log any warning
$is_set = my_isset($undefined_variable);   // $is_set is false

How to scroll up or down the page to an anchor using jQuery?

Assuming that your href attribute is linking to a div with the tag id with the same name (as usual), you can use this code:

HTML

<a href="#goto" class="sliding-link">Link to div</a>

<div id="goto">I'm the div</div>

JAVASCRIPT - (Jquery)

$(".sliding-link").click(function(e) {
    e.preventDefault();
    var aid = $(this).attr("href");
    $('html,body').animate({scrollTop: $(aid).offset().top},'slow');
});

C++ "was not declared in this scope" compile error

What's wrong:

The definition of "nonrecursivecountcells" has no parameter named grid. You need to pass the type AND variable name to the function. You only passed the type.

Note if you use the name grid for the parameter, that name has nothing to do with your main() declaration of grid. You could have used any other name as well.

***Also you can't pass arrays as values.


How to fix:

The easy way to fix this is to pass a pointer to an array to the function "nonrecursivecountcells".

int nonrecursivecountcells(color[ROW_SIZE][COL_SIZE], int, int);

better and type safe ->

int nonrecursivecountcells(color (&grid)[ROW_SIZE][COL_SIZE], int, int);

About scope:

A variable created on the stack comes out of scope when the block it is declared in is terminated. A block is anything within an opening and matching closing brace. For example an if() { }, function() { }, while() {}, ...

Note I said variable and not data. For example you can allocate memory on the heap and that data will still remain valid even outside of the scope. But the variable that originally pointed to it would still come out of scope.

Git pull a certain branch from GitHub

git fetch will grab the latest list of branches.

Now you can git checkout MyNewBranch

Done :)


For more info see docs: git fetch

How to display an unordered list in two columns?

Though I found Gabriel answer to work to a degree i did find the following when trying to order the list vertically (first ul A-D and second ul E-G):

  • When the ul had an even number of li's in it, it was not evenly spreading it across the ul's
  • using the data-column in the ul didn't seem to work very well, I had to put 4 for 3 columns and even then it was still only spreading the li's into 2 of the ul generated by the JS

I have revised the JQuery so the above hopefully doesn't happen.

(function ($) {
    var initialContainer = $('.customcolumns'),
        columnItems = $('.customcolumns li'),
        columns = null,
        column = 0;
    function updateColumns() {
        column = 0;
        columnItems.each(function (idx, el) {
            if ($(columns.get(column)).find('li').length >= (columnItems.length / initialContainer.data('columns'))) {
                column += 1;
            }
            $(columns.get(column)).append(el);
        });
    }
    function setupColumns() {
        columnItems.detach();
        while (column++ < initialContainer.data('columns')) {
            initialContainer.clone().insertBefore(initialContainer);
            column++;
        }
        columns = $('.customcolumns');
        updateColumns();
    }

    $(setupColumns);
})(jQuery);
.customcolumns {
  float: left;
  position: relative;
  margin-right: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <ul class="customcolumns" data-columns="3">
    <li>A</li>
    <li>B</li>
    <li>C</li>
    <li>D</li>
    <li>E</li>
    <li>F</li>
    <li>G</li>
    <li>H</li>
    <li>I</li>
    <li>J</li>
    <li>K</li>
    <li>L</li>
    <li>M</li>
  </ul>
</div>

pandas python how to count the number of records or rows in a dataframe

To get the number of rows in a dataframe use:

df.shape[0]

(and df.shape[1] to get the number of columns).

As an alternative you can use

len(df)

or

len(df.index)

(and len(df.columns) for the columns)

shape is more versatile and more convenient than len(), especially for interactive work (just needs to be added at the end), but len is a bit faster (see also this answer).

To avoid: count() because it returns the number of non-NA/null observations over requested axis

len(df.index) is faster

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(24).reshape(8, 3),columns=['A', 'B', 'C'])
df['A'][5]=np.nan
df
# Out:
#     A   B   C
# 0   0   1   2
# 1   3   4   5
# 2   6   7   8
# 3   9  10  11
# 4  12  13  14
# 5 NaN  16  17
# 6  18  19  20
# 7  21  22  23

%timeit df.shape[0]
# 100000 loops, best of 3: 4.22 µs per loop

%timeit len(df)
# 100000 loops, best of 3: 2.26 µs per loop

%timeit len(df.index)
# 1000000 loops, best of 3: 1.46 µs per loop

df.__len__ is just a call to len(df.index)

import inspect 
print(inspect.getsource(pd.DataFrame.__len__))
# Out:
#     def __len__(self):
#         """Returns length of info axis, but here we use the index """
#         return len(self.index)

Why you should not use count()

df.count()
# Out:
# A    7
# B    8
# C    8

How To Upload Files on GitHub

Here are the steps (in-short), since I don't know what exactly you have done:
1. Download and install Git on your system: http://git-scm.com/downloads
2. Using the Git Bash (a command prompt for Git) or your system's native command prompt, set up a local git repository.
3. Use the same console to checkout, commit, push, etc. the files on the Git.

Hope this helps to those who come searching here.

How to detect if numpy is installed

The traditional method for checking for packages in Python is "it's better to beg forgiveness than ask permission", or rather, "it's better to catch an exception than test a condition."

try:
    import numpy
    HAS_NUMPY = True
except ImportError:
    HAS_NUMPY = False

Extracting specific columns in numpy array

One thing I would like to point out is, if the number of columns you want to extract is 1 the resulting matrix would not be a Mx1 Matrix as you might expect but instead an array containing the elements of the column you extracted.

To convert it to Matrix the reshape(M,1) method should be used on the resulting array.

Best Timer for using in a Windows service

I know this thread is a little old but it came in handy for a specific scenario I had and I thought it worth while to note that there is another reason why System.Threading.Timer might be a good approach. When you have to periodically execute a Job that might take a long time and you want to ensure that the entire waiting period is used between jobs or if you don't want the job to run again before the previous job has finished in the case where the job takes longer than the timer period. You could use the following:

using System;
using System.ServiceProcess;
using System.Threading;

    public partial class TimerExampleService : ServiceBase
    {
        private AutoResetEvent AutoEventInstance { get; set; }
        private StatusChecker StatusCheckerInstance { get; set; }
        private Timer StateTimer { get; set; }
        public int TimerInterval { get; set; }

        public CaseIndexingService()
        {
            InitializeComponent();
            TimerInterval = 300000;
        }

        protected override void OnStart(string[] args)
        {
            AutoEventInstance = new AutoResetEvent(false);
            StatusCheckerInstance = new StatusChecker();

            // Create the delegate that invokes methods for the timer.
            TimerCallback timerDelegate =
                new TimerCallback(StatusCheckerInstance.CheckStatus);

            // Create a timer that signals the delegate to invoke 
            // 1.CheckStatus immediately, 
            // 2.Wait until the job is finished,
            // 3.then wait 5 minutes before executing again. 
            // 4.Repeat from point 2.
            Console.WriteLine("{0} Creating timer.\n",
                DateTime.Now.ToString("h:mm:ss.fff"));
            //Start Immediately but don't run again.
            StateTimer = new Timer(timerDelegate, AutoEventInstance, 0, Timeout.Infinite);
            while (StateTimer != null)
            {
                //Wait until the job is done
                AutoEventInstance.WaitOne();
                //Wait for 5 minutes before starting the job again.
                StateTimer.Change(TimerInterval, Timeout.Infinite);
            }
            //If the Job somehow takes longer than 5 minutes to complete then it wont matter because we will always wait another 5 minutes before running again.
        }

        protected override void OnStop()
        {
            StateTimer.Dispose();
        }
    }

    class StatusChecker
        {

            public StatusChecker()
            {
            }

            // This method is called by the timer delegate.
            public void CheckStatus(Object stateInfo)
            {
                AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
                Console.WriteLine("{0} Start Checking status.",
                    DateTime.Now.ToString("h:mm:ss.fff"));
                //This job takes time to run. For example purposes, I put a delay in here.
                int milliseconds = 5000;
                Thread.Sleep(milliseconds);
                //Job is now done running and the timer can now be reset to wait for the next interval
                Console.WriteLine("{0} Done Checking status.",
                    DateTime.Now.ToString("h:mm:ss.fff"));
                autoEvent.Set();
            }
        }

React Router with optional path parameter

The edit you posted was valid for an older version of React-router (v0.13) and doesn't work anymore.


React Router v1, v2 and v3

Since version 1.0.0 you define optional parameters with:

<Route path="to/page(/:pathParam)" component={MyPage} />

and for multiple optional parameters:

<Route path="to/page(/:pathParam1)(/:pathParam2)" component={MyPage} />

You use parenthesis ( ) to wrap the optional parts of route, including the leading slash (/). Check out the Route Matching Guide page of the official documentation.

Note: The :paramName parameter matches a URL segment up to the next /, ?, or #. For more about paths and params specifically, read more here.


React Router v4 and above

React Router v4 is fundamentally different than v1-v3, and optional path parameters aren't explicitly defined in the official documentation either.

Instead, you are instructed to define a path parameter that path-to-regexp understands. This allows for much greater flexibility in defining your paths, such as repeating patterns, wildcards, etc. So to define a parameter as optional you add a trailing question-mark (?).

As such, to define an optional parameter, you do:

<Route path="/to/page/:pathParam?" component={MyPage} />

and for multiple optional parameters:

<Route path="/to/page/:pathParam1?/:pathParam2?" component={MyPage} />

Note: React Router v4 is incompatible with (read more here). Use version v3 or earlier (v2 recommended) instead.

How can I manually set an Angular form field as invalid?

You could also change the viewChild 'type' to NgForm as in:

@ViewChild('loginForm') loginForm: NgForm;

And then reference your controls in the same way @Julia mentioned:

 private login(formData: any): void {
    this.authService.login(formData).subscribe(res => {
      alert(`Congrats, you have logged in. We don't have anywhere to send you right now though, but congrats regardless!`);
    }, error => {
      this.loginFailed = true; // This displays the error message, I don't really like this, but that's another issue.

      this.loginForm.controls['email'].setErrors({ 'incorrect': true});
      this.loginForm.controls['password'].setErrors({ 'incorrect': true});
    });
  }

Setting the Errors to null will clear out the errors on the UI:

this.loginForm.controls['email'].setErrors(null);

Replace non-ASCII characters with a single space

When we use the ascii() it escapes the non-ascii characters and it doesn't change ascii characters correctly. So my main thought is, it doesn't change the ASCII characters, so I am iterating through the string and checking if the character is changed. If it changed then replacing it with the replacer, what you give.
For example: ' '(a single space) or '?' (with a question mark).

def remove(x, replacer):

     for i in x:
        if f"'{i}'" == ascii(i):
            pass
        else:
            x=x.replace(i,replacer)
     return x
remove('hái',' ')

Result: "h i" (with single space between).

Syntax : remove(str,non_ascii_replacer)
str = Here you will give the string you want to work with.
non_ascii_replacer = Here you will give the replacer which you want to replace all the non ASCII characters with.

How to find if a native DLL file is compiled as x64 or x86?

A quick and probably dirty way to do it is described here: https://superuser.com/a/889267. You open the DLL in an editor and check the first characters after the "PE" sequence.

Using an integer as a key in an associative array in JavaScript

Use an object - with an integer as the key - rather than an array.

Write in body request with HttpClient

If your xml is written by java.lang.String you can just using HttpClient in this way

    public void post() throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.baidu.com");
        String xml = "<xml>xxxx</xml>";
        HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
    }

pay attention to the Exceptions.

BTW, the example is written by the httpclient version 4.x

Force sidebar height 100% using CSS (with a sticky bottom image)?

I have run into this issue several times on different projects, but I have found a solution that works for me. You have to use four div tags - one that contains the sidebar, the main content, and a footer.

First, style the elements in your stylesheet:

#container {
width: 100%;
background: #FFFAF0;
}

.content {
width: 950px;
float: right;
padding: 10px;
height: 100%;
background: #FFFAF0;
}

.sidebar {
width: 220px;
float: left;
height: 100%;
padding: 5px;
background: #FFFAF0;
}

#footer {
clear:both;
background:#FFFAF0;
}

You can edit the different elements however you want to, just be sure you dont change the footer property "clear:both" - this is very important to leave in.

Then, simply set up your web page like this:

<div id=”container”>
<div class=”sidebar”></div>
<div class=”content”></div>
<div id=”footer”></div>
</div>

I wrote a more in-depth blog post about this at http://blog.thelibzter.com/how-to-make-a-sidebar-extend-the-entire-height-of-its-container. Please let me know if you have any questions. Hope this helps!

TypeError: 'DataFrame' object is not callable

It seems you need DataFrame.var:

Normalized by N-1 by default. This can be changed using the ddof argument

var1 = credit_card.var()

Sample:

#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

var1 = credit_card.var()
print (var1)
A     8.8
B    10.0
C    10.0
D     7.7
E     7.8
dtype: float64

var2 = credit_card.var(axis=1)
print (var2)
0     4.3
1     3.8
2     9.8
3    12.2
4     2.3
dtype: float64

If need numpy solutions with numpy.var:

print (np.var(credit_card.values, axis=0))
[ 7.04  8.    8.    6.16  6.24]

print (np.var(credit_card.values, axis=1))
[ 3.44  3.04  7.84  9.76  1.84]

Differences are because by default ddof=1 in pandas, but you can change it to 0:

var1 = credit_card.var(ddof=0)
print (var1)
A    7.04
B    8.00
C    8.00
D    6.16
E    6.24
dtype: float64

var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0    3.44
1    3.04
2    7.84
3    9.76
4    1.84
dtype: float64