Programs & Examples On #Astoria

Astoria is the code name given to what is now WCF Data Services or ADO.NET Data Services. It is a component of the .NET Framework that uses the OData protocol to transport data over the Internet using REST-ful paradigms.

GitHub: invalid username or password

Just Try this:

# git remote set-url origin [email protected]:username/repository

Hope this help

Python Pandas - Find difference between two data frames

A slight variation of the nice @liangli's solution that does not require to change the index of existing dataframes:

newdf = df1.drop(df1.join(df2.set_index('Name').index))

Using std::max_element on a vector<double>

min/max_element return the iterator to the min/max element, not the value of the min/max element. You have to dereference the iterator in order to get the value out and assign it to a double. That is:

cLower = *min_element(C.begin(), C.end());

ImportError: No module named site on Windows

Locate site.py and add its path in PYTHONPATH. This will solve your problem.

Getting "The remote certificate is invalid according to the validation procedure" when SMTP server has a valid certificate

Old post, but I thought I would share my solution because there aren't many solutions out there for this issue.

If you're running an old Windows Server 2003 machine, you likely need to install a hotfix (KB938397).

This problem occurs because the Cryptography API 2 (CAPI2) in Windows Server 2003 does not support the SHA2 family of hashing algorithms. CAPI2 is the part of the Cryptography API that handles certificates.

https://support.microsoft.com/en-us/kb/938397

For whatever reason, Microsoft wants to email you this hotfix instead of allowing you to download directly. Here's a direct link to the hotfix from the email:

http://hotfixv4.microsoft.com/Windows Server 2003/sp3/Fix200653/3790/free/315159_ENU_x64_zip.exe

Git: How do I list only local branches?

Here's how to list local branches that do not have a remote branch in origin with the same name:

git branch | sed 's|* |  |' | sort > local
git branch -r | sed 's|origin/||' | sort > remote
comm -23 local remote

Can we pass parameters to a view in SQL?

You can bypass just to run the view, SQL will wine and cry but just do this and run it! You can't save.

create or replace view v_emp(eno number) as select * from emp where (emp_id = @Parameter1);

What is the best way to search the Long datatype within an Oracle database?

Don't use LONGs, use CLOB instead. You can index and search CLOBs like VARCHAR2.

Additionally, querying with a leading wildcard(%) will ALWAYS result in a full-table-scan. Look into Oracle Text indexes instead.

Compiling with g++ using multiple cores

make will do this for you. Investigate the -j and -l switches in the man page. I don't think g++ is parallelizable.

Finding the direction of scrolling in a UIScrollView?

Short & Easy would be, just check the velocity value, if its greater than zero then its scrolling left else right:

func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

    var targetOffset = Float(targetContentOffset.memory.x)
    println("TargetOffset: \(targetOffset)")
    println(velocity)

    if velocity.x < 0 {
        scrollDirection = -1 //scrolling left
    } else {
        scrollDirection = 1 //scrolling right
    }
}

PowerShell: how to grep command output?

I think this solution is easier and better, use directly the function findstr:

alias | findstr -i Write

You can also make an alias to use grep word:

new-alias grep findstr

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

****Following solution is working for me**** Manually deleted all files from C:\Users\Admin.gradle\wrapper\dists\

where Admin is my user name

How to determine tables size in Oracle

Here is a query, you can run it in SQL Developer (or SQL*Plus):

SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
  FROM DBA_SEGMENTS DS
  WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
 GROUP BY DS.TABLESPACE_NAME,
       SEGMENT_NAME;

Error 5 : Access Denied when starting windows service

Click the Start menu and choose Run or use the keyboard shortcut of Win+R.

In the dialog box, type lusrmgr.msc. When this application opens, click Users in the left-hand panel and then right click Administrator in the right-hand panel. Click Properties in the menu.

In the Administrator Properties dialog, choose the Member Of tab, then click the Add... button at the lower right. From the next dialog, choose Advanced...

Another dialog will appear. From there click Find Now on the right. A list of search results will appear at the bottom of the dialog. Select Network Services from this list and click OK on each of the open dialogs.

How to have Android Service communicate with Activity

Binding is another way to communicate

Create a callback

public interface MyCallBack{

   public void getResult(String result);

}

Activity side:

  1. Implement the interface in the Activity

  2. Provide the implementation for the method

  3. Bind the Activity to Service

  4. Register and Unregister Callback when the Service gets bound and unbound with Activity.

    public class YourActivity extends AppCompatActivity implements MyCallBack{
    
          private Intent notifyMeIntent;
          private GPSService gpsService;
          private boolean bound = false;
    
          @Override
          public void onCreate(Bundle sis){
    
              // activity code ...
    
              startGPSService();
    
          }
    
          @Override
          public void getResult(String result){
           // show in textView textView.setText(result);
          }
    
          @Override
          protected void onStart()
          {
              super.onStart();
              bindService();
          }
    
          @Override
          protected void onStop() {
              super.onStop();
              unbindService();
          }
    
          private ServiceConnection serviceConnection = new ServiceConnection() {
    
                @Override
                public void onServiceConnected(ComponentName className, IBinder service) {
    
                      GPSService.GPSBinder binder = (GPSService.GPSBinder) service;
                      gpsService= binder.getService();
                      bound = true;
                      gpsService.registerCallBack(YourActivity.this); // register
    
               }
    
               @Override
               public void onServiceDisconnected(ComponentName arg0) {
                      bound = false;
               }
          };
    
          private void bindService() {
    
               bindService(notifyMeIntent, serviceConnection, Context.BIND_AUTO_CREATE);
          }
    
          private void unbindService(){
               if (bound) {
                     gpsService.registerCallBack(null); // unregister            
                     unbindService(serviceConnection);
                     bound = false;
                }
          }
    
          // Call this method somewhere to start Your GPSService
          private void startGPSService(){
               notifyMeIntent = new Intent(this, GPSService.class);
               startService(myIntent );
          }
    
     }
    

Service Side:

  1. Initialize callback

  2. Invoke the callback method whenever needed

     public class GPSService extends Service{
    
         private MyCallBack myCallback;
         private IBinder serviceBinder = new GPSBinder();
    
         public void registerCallBack(MyCallBack myCallback){
              this.myCallback= myCallback;
         }
    
         public class GPSBinder extends Binder{
    
             public GPSService getService(){
                  return GPSService.this;
             }
        }
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent){
             return serviceBinder;
        }
     }
    

How to detect the device orientation using CSS media queries?

I would go for aspect-ratio, it offers way more possibilities.

/* Exact aspect ratio */
@media (aspect-ratio: 2/1) {
    ...
}

/* Minimum aspect ratio */
@media (min-aspect-ratio: 16/9) {
    ...
}

/* Maximum aspect ratio */
@media (max-aspect-ratio: 8/5) {
    ...
}

Both, orientation and aspect-ratio depend on the actual size of the viewport and have nothing todo with the device orientation itself.

Read more: https://dev.to/ananyaneogi/useful-css-media-query-features-o7f

CSS Display an Image Resized and Cropped

You could use a combination of both methods eg.

_x000D_
_x000D_
    .crop {_x000D_
        width: 200px;_x000D_
        height: 150px;_x000D_
        overflow: hidden;_x000D_
    }_x000D_
_x000D_
    .crop img {_x000D_
        width: 400px;_x000D_
        height: 300px;_x000D_
        margin: -75px 0 0 -100px;_x000D_
    }
_x000D_
    <div class="crop">_x000D_
        <img src="https://i.stack.imgur.com/wPh0S.jpg" alt="Donald Duck">_x000D_
    </div>
_x000D_
_x000D_
_x000D_

You can use negative margin to move the image around within the <div/>.

Arithmetic operation resulted in an overflow. (Adding integers)

The maximum size for an int is 2147483647. You could use an Int64/Long which is far larger.

OnItemCLickListener not working in listview

if you have textviews, buttons or stg clickable or selectable in your row view only

android:descendantFocusability="blocksDescendants"

is not enough. You have to set

android:textIsSelectable="false"

to your textviews and

android:focusable="false"

to your buttons and other focusable items.

Sharing url link does not show thumbnail image on facebook

The answers above are good and they should fix most of the problems you have. But to see the errors directly from facebook you can use the link https://developers.facebook.com/tools/debug/sharing/

that way you're sure of the steps you need to take.

I found out the URL for the og:image meta has to be an absolute url

How do I import a Swift file from another Swift file?

I had the same problem, also in my XCTestCase files, but not in the regular project files.

To get rid of the:

Use of unresolved identifier 'PrimeNumberModel'

I needed to import the base module in the test file. In my case, my target is called 'myproject' and I added import myproject and the class was recognised.

How to abort an interactive rebase if --abort doesn't work?

Try to follow the advice you see on the screen, and first reset your master's HEAD to the commit it expects.

git update-ref refs/heads/master b918ac16a33881ce00799bea63d9c23bf7022d67

Then, abort the rebase again.

Chrome: Uncaught SyntaxError: Unexpected end of input

I had this error and fixed it by adding the guard on readyState and status shown here:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
          // Your code here
   }
};

Is there a way to use SVG as content in a pseudo element :before or :after

You can add the SVG as background-image of an empty :after or :before.

Here you go:

.anchor:before {
  display: block;
  content: ' ';
  background-image: url('../images/anchor.svg');
  background-size: 28px 28px;
  height: 28px;
  width: 28px;
}

Drawing an image from a data URL to a canvas

Just to add to the other answers: In case you don't like the onload callback approach, you can "promisify" it like so:

let url = "data:image/gif;base64,R0lGODl...";
let img = new Image();
await new Promise(r => img.onload=r, img.src=url);
// now do something with img

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

I had the same problem and which got resolved by using ./ before the directory name in my node.js app, i.e.

app.use(express.static('./public'));

How to write data with FileOutputStream without losing old data?

Use the constructor that takes a File and a boolean

FileOutputStream(File file, boolean append) 

and set the boolean to true. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.

Progress Bar with HTML and CSS

.bar {
background - color: blue;
height: 40 px;
width: 40 px;
border - style: solid;
border - right - width: 1300 px;
border - radius: 40 px;
animation - name: Load;
animation - duration: 11 s;
position: relative;
animation - iteration - count: 1;
animation - fill - mode: forwards;
}

@keyframes Load {
100 % {
    width: 1300 px;border - right - width: 5;
}

How to draw lines in Java

a simple line , after that you can see also a doted line 

import java.awt.*;

import javax.swing.*;

import java.awt.Graphics.*;

import java.awt.Graphics2D.*;

import javax.swing.JFrame;

import javax.swing.JPanel;

import java.awt.BasicStroke;

import java.awt.Event.*;

import java.awt.Component.*;

import javax.swing.SwingUtilities;


/**
 *
 * @author junaid
 */
public class JunaidLine extends JPanel{


//private Graphics Graphics;

private void doDrawing(Graphics g){

Graphics2D g2d=(Graphics2D) g;

float[] dash1 = {2f,0f,2f};

g2d.drawLine(20, 40, 250, 40);

BasicStroke bs1 = new BasicStroke(1,BasicStroke.CAP_BUTT,

                    BasicStroke.JOIN_ROUND,1.0f,dash1,2f);

g2d.setStroke(bs1);

g2d.drawLine(20, 80, 250, 80);

    }

@Override

public void paintComponent(Graphics g){

super.paintComponent( g);

doDrawing(g);

}


}

class BasicStrokes extends JFrame{

public  BasicStrokes(){

initUI();

}

private void initUI(){

setTitle("line");

setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

add(new JunaidLine());

setSize(280,270);

setLocationRelativeTo(null);

}

/**

* @param args the command line arguments

*/

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable(){   

@Override

public void run(){

BasicStrokes bs = new BasicStrokes();

bs.setVisible(true);

}                

});

}


}

Write a function that returns the longest palindrome in a given string

For linear solution, you can use Manacher's algorithm. There is another algorithm call Gusfield's Algorithm, and below is the code in java:

public class Solution {  
    char[] temp;   
    public int match(int a, int b,int len){   
        int i = 0;   
        while (a-i>=0 && b+i<len && temp[a-i] == temp[b+i]) i++;   
        return i;   
    }  

    public String longestPalindrome(String s) {  

        //This makes use of the assumption that the string has not more than 1000 characters.  
        temp=new char[1001*2];  
        int[] z=new int[1001 * 2];  
        int L=0, R=0;  
        int len=s.length();  

        for(int i=0;i<len*2+1;i++){  
            temp[i]='.';  
        }  

        for(int i=0;i<len;++i){  
            temp[i*2+1] = s.charAt(i);  
        }  

        z[0]=1;  
        len=len*2+1;  

        for(int i=0;i<len;i++){  
            int ii = L - (i - L);     
            int n = R + 1 - i;  
            if (i > R)  
            {  
                z[i] = match(i, i,len);  
                L = i;  
                R = i + z[i] - 1;  
            }  
            else if (z[ii] == n)  
            {  
                z[i] = n + match(i-n, i+n,len);  
                L = i;  
                R = i + z[i] - 1;  
            }  
            else  
            {  
                z[i] = (z[ii]<= n)? z[ii]:n;  
            }   
        }  

        int n = 0, p = 0;  
        for (int i=0; i<len; ++i)  
            if (z[i] > n)  
                n = z[p = i];  

        StringBuilder result=new StringBuilder();  
        for (int i=p-z[p]+1; i<=p+z[p]-1; ++i)  
            if(temp[i]!='.')  
                result.append(String.valueOf(temp[i]));  

        return result.toString();  
    }  
}  

You can find more on other solutions such as the best O(n^2) solution or Manacher's algorithm from my own blog.

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

I encountered the same problem and finally found out that the <tx:annotaion-driven /> was not defined within the [dispatcher]-servlet.xml where component-scan element enabled @service annotated class.

Simply put <tx:annotaion-driven /> with component-scan element together, the problem disappeared.

How to set underline text on textview?

Simple and easy way to display underline in TextView is:

yourTextView.getPaint().setUnderlineText(true);

And if you want to remove underlining for that view, you can write below code:

yourTextView.getPaint().setUnderlineText(false);

It will work even though you set android:textAllCaps="true"

How do I base64 encode (decode) in C?

This is a decoder that is specifically written to avoid the need for a buffer, by writing directly to a putchar function. This is based on wikibook's implementation https://en.wikibooks.org/wiki/Algorithm_Implementation/Miscellaneous/Base64#C

This is not as easy to use as other options above. However, it can be of use in embedded systems, where you want to dump a large file without allocating another large buffer to store the resultant base64 datauri string. (It's a pity that datauri does not let you specify the filename).

void datauriBase64EncodeBufferless(int (*putchar_fcptr)(int), const char* type_strptr, const void* data_buf, const size_t dataLength)
{
  const char base64chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  const uint8_t *data = (const uint8_t *)data_buf;
  size_t x = 0;
  uint32_t n = 0;
  int padCount = dataLength % 3;
  uint8_t n0, n1, n2, n3;

  size_t outcount = 0;
  size_t line = 0;

  putchar_fcptr((int)'d');
  putchar_fcptr((int)'a');
  putchar_fcptr((int)'t');
  putchar_fcptr((int)'a');
  putchar_fcptr((int)':');
  outcount += 5;

  while (*type_strptr != '\0')
  {
    putchar_fcptr((int)*type_strptr);
    type_strptr++;
    outcount++;
  }

  putchar_fcptr((int)';');
  putchar_fcptr((int)'b');
  putchar_fcptr((int)'a');
  putchar_fcptr((int)'s');
  putchar_fcptr((int)'e');
  putchar_fcptr((int)'6');
  putchar_fcptr((int)'4');
  putchar_fcptr((int)',');
  outcount += 8;

  /* increment over the length of the string, three characters at a time */
  for (x = 0; x < dataLength; x += 3)
  {
    /* these three 8-bit (ASCII) characters become one 24-bit number */
    n = ((uint32_t)data[x]) << 16; //parenthesis needed, compiler depending on flags can do the shifting before conversion to uint32_t, resulting to 0

    if((x+1) < dataLength)
       n += ((uint32_t)data[x+1]) << 8;//parenthesis needed, compiler depending on flags can do the shifting before conversion to uint32_t, resulting to 0

    if((x+2) < dataLength)
       n += data[x+2];

    /* this 24-bit number gets separated into four 6-bit numbers */
    n0 = (uint8_t)(n >> 18) & 63;
    n1 = (uint8_t)(n >> 12) & 63;
    n2 = (uint8_t)(n >> 6) & 63;
    n3 = (uint8_t)n & 63;

    /*
     * if we have one byte available, then its encoding is spread
     * out over two characters
     */

    putchar_fcptr((int)base64chars[n0]);
    putchar_fcptr((int)base64chars[n1]);
    outcount += 2;

    /*
     * if we have only two bytes available, then their encoding is
     * spread out over three chars
     */
    if((x+1) < dataLength)
    {
      putchar_fcptr((int)base64chars[n2]);
      outcount += 1;
    }

    /*
     * if we have all three bytes available, then their encoding is spread
     * out over four characters
     */
    if((x+2) < dataLength)
    {
      putchar_fcptr((int)base64chars[n3]);
      outcount += 1;
    }

    /* Breaking up the line so it's easier to copy and paste */
    int curr_line = (outcount/80);
    if( curr_line != line )
    {
      line = curr_line;
      putchar_fcptr((int)'\r');
      putchar_fcptr((int)'\n');
    }
  }

  /*
  * create and add padding that is required if we did not have a multiple of 3
  * number of characters available
  */
  if (padCount > 0)
  {
    for (; padCount < 3; padCount++)
    {
      putchar_fcptr((int)'=');
    }
  }

  putchar_fcptr((int)'\r');
  putchar_fcptr((int)'\n');
}

Here is the test

#include <stdio.h>
#include <stdint.h>
#include <string.h>

int main(void)
{
  char str[] = "test";
  datauriBase64EncodeBufferless(putchar, "text/plain;charset=utf-8", str, strlen(str));
  return 0;
}

Expected Output: data:text/plain;charset=utf-8;base64,dGVzdA==

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Because C will promote floats to doubles for functions that take variable arguments. Pointers aren't promoted to anything, so you should be using %lf, %lg or %le (or %la in C99) to read in doubles.

How to declare global variables in Android?

The approach of subclassing has also been used by the BARACUS framework. From my point of view subclassing Application was intended to work with the lifecycles of Android; this is what any Application Container does. Instead of having globals then, I register beans to this context an let them beeing injected into any class manageable by the context. Every injected bean instance actually is a singleton.

See this example for details

Why do manual work if you can have so much more?

Rotate a div using javascript

Can be pretty easily done assuming you're using jQuery and css3:

http://jsfiddle.net/S7JDU/8/

HTML:

<div id="clicker">Click Here</div>
<div id="rotating"></div>

CSS:

#clicker { 
    width: 100px; 
    height: 100px; 
    background-color: Green; 
}

#rotating { 
    width: 100px; 
    height: 100px; 
    background-color: Red; 
    margin-top: 50px; 
    -webkit-transition: all 0.3s ease-in-out;
    -moz-transition: all 0.3s ease-in-out;
    -o-transition: all 0.3s ease-in-out;
    transition: all 0.3s ease-in-out;
}

.rotated { 
    transform:rotate(25deg); 
    -webkit-transform:rotate(25deg); 
    -moz-transform:rotate(25deg); 
    -o-transform:rotate(25deg); 
}

JS:

$(document).ready(function() {
    $('#clicker').click(function() {
        $('#rotating').toggleClass('rotated');
    });
});

ActiveXObject creation error " Automation server can't create object"

i also have same problem and solve it. Please go through the link

add your site to trusted zone and change following options in ie Tools Menu -> Internet Options -> Security -> Custom level -> "Initialize and script ActiveX controls not marked as safe for scripting"

http://forums.codeguru.com/showthread.php?t=256114

Creating an array of objects in Java

Yes, it creates only references, which are set to their default value null. That is why you get a NullPointerException You need to create objects separately and assign the reference. There are 3 steps to create arrays in Java -

Declaration – In this step, we specify the data type and the dimensions of the array that we are going to create. But remember, we don't mention the sizes of dimensions yet. They are left empty.

Instantiation – In this step, we create the array, or allocate memory for the array, using the new keyword. It is in this step that we mention the sizes of the array dimensions.

Initialization – The array is always initialized to the data type’s default value. But we can make our own initializations.

Declaring Arrays In Java

This is how we declare a one-dimensional array in Java –

int[] array;
int array[];

Oracle recommends that you use the former syntax for declaring arrays. Here are some other examples of legal declarations –

// One Dimensional Arrays
int[] intArray;             // Good
double[] doubleArray;

// One Dimensional Arrays
byte byteArray[];           // Ugly!
long longArray[];

// Two Dimensional Arrays
int[][] int2DArray;         // Good
double[][] double2DArray;

// Two Dimensional Arrays
byte[] byte2DArray[];       // Ugly
long[] long2DArray[];

And these are some examples of illegal declarations –

int[5] intArray;       // Don't mention size!
double{} doubleArray;  // Square Brackets please!

Instantiation

This is how we “instantiate”, or allocate memory for an array –

int[] array = new int[5];

When the JVM encounters the new keyword, it understands that it must allocate memory for something. And by specifying int[5], we mean that we want an array of ints, of size 5. So, the JVM creates the memory and assigns the reference of the newly allocated memory to array which a “reference” of type int[]

Initialization

Using a Loop – Using a for loop to initialize elements of an array is the most common way to get the array going. There’s no need to run a for loop if you are going to assign the default value itself, because JVM does it for you.

All in One..! – We can Declare, Instantiate and Initialize our array in one go. Here’s the syntax –

int[] arr = {1, 2, 3, 4, 5};

Here, we don’t mention the size, because JVM can see that we are giving 5 values.

So, until we instantiate the references remain null. I hope my answer has helped you..! :)

Source - Arrays in Java

Nested Git repositories?

git-subtree will help you work with multiple projects in a single tree and keep separable history for them.

Renaming files using node.js

  1. fs.readdir(path, callback)
  2. fs.rename(old,new,callback)

Go through http://nodejs.org/api/fs.html

One important thing - you can use sync functions also. (It will work like C program)

performing HTTP requests with cURL (using PROXY)

From man curl:

-x, --proxy <[protocol://][user:password@]proxyhost[:port]>

     Use the specified HTTP proxy. 
     If the port number is not specified, it is assumed at port 1080.

General way:

export http_proxy=http://your.proxy.server:port/

Then you can connect through proxy from (many) application.

And, as per comment below, for https:

export https_proxy=https://your.proxy.server:port/

Position Absolute + Scrolling

position: fixed; will solve your issue. As an example, review my implementation of a fixed message area overlay (populated programmatically):

#mess {
    position: fixed;
    background-color: black;
    top: 20px;
    right: 50px;
    height: 10px;
    width: 600px;
    z-index: 1000;
}

And in the HTML

<body>
    <div id="mess"></div>
    <div id="data">
        Much content goes here.
    </div>
</body>

When #data becomes longer tha the sceen, #mess keeps its position on the screen, while #data scrolls under it.

How to add elements of a Java8 stream into an existing List

Erik Allik already gave very good reasons, why you will most likely not want to collect elements of a stream into an existing List.

Anyway, you can use the following one-liner, if you really need this functionality.

But as Stuart Marks explains in his answer, you should never do this, if the streams might be parallel streams - use at your own risk...

list.stream().collect(Collectors.toCollection(() -> myExistingList));

Proper use of the IDisposable interface

The point of Dispose is to free unmanaged resources. It needs to be done at some point, otherwise they will never be cleaned up. The garbage collector doesn't know how to call DeleteHandle() on a variable of type IntPtr, it doesn't know whether or not it needs to call DeleteHandle().

Note: What is an unmanaged resource? If you found it in the Microsoft .NET Framework: it's managed. If you went poking around MSDN yourself, it's unmanaged. Anything you've used P/Invoke calls to get outside of the nice comfy world of everything available to you in the .NET Framework is unmanaged – and you're now responsible for cleaning it up.

The object that you've created needs to expose some method, that the outside world can call, in order to clean up unmanaged resources. The method can be named whatever you like:

public void Cleanup()

or

public void Shutdown()

But instead there is a standardized name for this method:

public void Dispose()

There was even an interface created, IDisposable, that has just that one method:

public interface IDisposable
{
   void Dispose()
}

So you make your object expose the IDisposable interface, and that way you promise that you've written that single method to clean up your unmanaged resources:

public void Dispose()
{
   Win32.DestroyHandle(this.CursorFileBitmapIconServiceHandle);
}

And you're done. Except you can do better.


What if your object has allocated a 250MB System.Drawing.Bitmap (i.e. the .NET managed Bitmap class) as some sort of frame buffer? Sure, this is a managed .NET object, and the garbage collector will free it. But do you really want to leave 250MB of memory just sitting there – waiting for the garbage collector to eventually come along and free it? What if there's an open database connection? Surely we don't want that connection sitting open, waiting for the GC to finalize the object.

If the user has called Dispose() (meaning they no longer plan to use the object) why not get rid of those wasteful bitmaps and database connections?

So now we will:

  • get rid of unmanaged resources (because we have to), and
  • get rid of managed resources (because we want to be helpful)

So let's update our Dispose() method to get rid of those managed objects:

public void Dispose()
{
   //Free unmanaged resources
   Win32.DestroyHandle(this.CursorFileBitmapIconServiceHandle);

   //Free managed resources too
   if (this.databaseConnection != null)
   {
      this.databaseConnection.Dispose();
      this.databaseConnection = null;
   }
   if (this.frameBufferImage != null)
   {
      this.frameBufferImage.Dispose();
      this.frameBufferImage = null;
   }
}

And all is good, except you can do better!


What if the person forgot to call Dispose() on your object? Then they would leak some unmanaged resources!

Note: They won't leak managed resources, because eventually the garbage collector is going to run, on a background thread, and free the memory associated with any unused objects. This will include your object, and any managed objects you use (e.g. the Bitmap and the DbConnection).

If the person forgot to call Dispose(), we can still save their bacon! We still have a way to call it for them: when the garbage collector finally gets around to freeing (i.e. finalizing) our object.

Note: The garbage collector will eventually free all managed objects. When it does, it calls the Finalize method on the object. The GC doesn't know, or care, about your Dispose method. That was just a name we chose for a method we call when we want to get rid of unmanaged stuff.

The destruction of our object by the Garbage collector is the perfect time to free those pesky unmanaged resources. We do this by overriding the Finalize() method.

Note: In C#, you don't explicitly override the Finalize() method. You write a method that looks like a C++ destructor, and the compiler takes that to be your implementation of the Finalize() method:

~MyObject()
{
    //we're being finalized (i.e. destroyed), call Dispose in case the user forgot to
    Dispose(); //<--Warning: subtle bug! Keep reading!
}

But there's a bug in that code. You see, the garbage collector runs on a background thread; you don't know the order in which two objects are destroyed. It is entirely possible that in your Dispose() code, the managed object you're trying to get rid of (because you wanted to be helpful) is no longer there:

public void Dispose()
{
   //Free unmanaged resources
   Win32.DestroyHandle(this.gdiCursorBitmapStreamFileHandle);

   //Free managed resources too
   if (this.databaseConnection != null)
   {
      this.databaseConnection.Dispose(); //<-- crash, GC already destroyed it
      this.databaseConnection = null;
   }
   if (this.frameBufferImage != null)
   {
      this.frameBufferImage.Dispose(); //<-- crash, GC already destroyed it
      this.frameBufferImage = null;
   }
}

So what you need is a way for Finalize() to tell Dispose() that it should not touch any managed resources (because they might not be there anymore), while still freeing unmanaged resources.

The standard pattern to do this is to have Finalize() and Dispose() both call a third(!) method; where you pass a Boolean saying if you're calling it from Dispose() (as opposed to Finalize()), meaning it's safe to free managed resources.

This internal method could be given some arbitrary name like "CoreDispose", or "MyInternalDispose", but is tradition to call it Dispose(Boolean):

protected void Dispose(Boolean disposing)

But a more helpful parameter name might be:

protected void Dispose(Boolean itIsSafeToAlsoFreeManagedObjects)
{
   //Free unmanaged resources
   Win32.DestroyHandle(this.CursorFileBitmapIconServiceHandle);

   //Free managed resources too, but only if I'm being called from Dispose
   //(If I'm being called from Finalize then the objects might not exist
   //anymore
   if (itIsSafeToAlsoFreeManagedObjects)  
   {    
      if (this.databaseConnection != null)
      {
         this.databaseConnection.Dispose();
         this.databaseConnection = null;
      }
      if (this.frameBufferImage != null)
      {
         this.frameBufferImage.Dispose();
         this.frameBufferImage = null;
      }
   }
}

And you change your implementation of the IDisposable.Dispose() method to:

public void Dispose()
{
   Dispose(true); //I am calling you from Dispose, it's safe
}

and your finalizer to:

~MyObject()
{
   Dispose(false); //I am *not* calling you from Dispose, it's *not* safe
}

Note: If your object descends from an object that implements Dispose, then don't forget to call their base Dispose method when you override Dispose:

public override void Dispose()
{
    try
    {
        Dispose(true); //true: safe to free managed resources
    }
    finally
    {
        base.Dispose();
    }
}

And all is good, except you can do better!


If the user calls Dispose() on your object, then everything has been cleaned up. Later on, when the garbage collector comes along and calls Finalize, it will then call Dispose again.

Not only is this wasteful, but if your object has junk references to objects you already disposed of from the last call to Dispose(), you'll try to dispose them again!

You'll notice in my code I was careful to remove references to objects that I've disposed, so I don't try to call Dispose on a junk object reference. But that didn't stop a subtle bug from creeping in.

When the user calls Dispose(): the handle CursorFileBitmapIconServiceHandle is destroyed. Later when the garbage collector runs, it will try to destroy the same handle again.

protected void Dispose(Boolean iAmBeingCalledFromDisposeAndNotFinalize)
{
   //Free unmanaged resources
   Win32.DestroyHandle(this.CursorFileBitmapIconServiceHandle); //<--double destroy 
   ...
}

The way you fix this is tell the garbage collector that it doesn't need to bother finalizing the object – its resources have already been cleaned up, and no more work is needed. You do this by calling GC.SuppressFinalize() in the Dispose() method:

public void Dispose()
{
   Dispose(true); //I am calling you from Dispose, it's safe
   GC.SuppressFinalize(this); //Hey, GC: don't bother calling finalize later
}

Now that the user has called Dispose(), we have:

  • freed unmanaged resources
  • freed managed resources

There's no point in the GC running the finalizer – everything's taken care of.

Couldn't I use Finalize to cleanup unmanaged resources?

The documentation for Object.Finalize says:

The Finalize method is used to perform cleanup operations on unmanaged resources held by the current object before the object is destroyed.

But the MSDN documentation also says, for IDisposable.Dispose:

Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.

So which is it? Which one is the place for me to cleanup unmanaged resources? The answer is:

It's your choice! But choose Dispose.

You certainly could place your unmanaged cleanup in the finalizer:

~MyObject()
{
   //Free unmanaged resources
   Win32.DestroyHandle(this.CursorFileBitmapIconServiceHandle);

   //A C# destructor automatically calls the destructor of its base class.
}

The problem with that is you have no idea when the garbage collector will get around to finalizing your object. Your un-managed, un-needed, un-used native resources will stick around until the garbage collector eventually runs. Then it will call your finalizer method; cleaning up unmanaged resources. The documentation of Object.Finalize points this out:

The exact time when the finalizer executes is undefined. To ensure deterministic release of resources for instances of your class, implement a Close method or provide a IDisposable.Dispose implementation.

This is the virtue of using Dispose to cleanup unmanaged resources; you get to know, and control, when unmanaged resource are cleaned up. Their destruction is "deterministic".


To answer your original question: Why not release memory now, rather than for when the GC decides to do it? I have a facial recognition software that needs to get rid of 530 MB of internal images now, since they're no longer needed. When we don't: the machine grinds to a swapping halt.

Bonus Reading

For anyone who likes the style of this answer (explaining the why, so the how becomes obvious), I suggest you read Chapter One of Don Box's Essential COM:

In 35 pages he explains the problems of using binary objects, and invents COM before your eyes. Once you realize the why of COM, the remaining 300 pages are obvious, and just detail Microsoft's implementation.

I think every programmer who has ever dealt with objects or COM should, at the very least, read the first chapter. It is the best explanation of anything ever.

Extra Bonus Reading

When everything you know is wrong by Eric Lippert

It is therefore very difficult indeed to write a correct finalizer, and the best advice I can give you is to not try.

Converting cv::Mat to IplImage*

Personaly I think it's not the problem caused by type casting but a buffer overflow problem; it is this line

cvCopy(iplimagearray[i], xyz);   

that I think will cause segment fault, I suggest that you confirm the array iplimagearray[i] have enough size of buffer to receive copyed data

Convert string date to timestamp in Python

Seems to be quite efficient:

import datetime
day, month, year = '01/12/2011'.split('/')
datetime.datetime(int(year), int(month), int(day)).timestamp()

1.61 µs ± 120 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

How to show and update echo on same line

I use printf, is shorter as it doesn't need flags to do the work:

printf "\rMy static $myvars composed text"

How to convert JSON object to an Typescript array?

That's correct, your response is an object with fields:

{
    "page": 1,
    "results": [ ... ]
}

So you in fact want to iterate the results field only:

this.data = res.json()['results'];

... or even easier:

this.data = res.json().results;

How do I find out if the GPS of an Android device is enabled

This method will use the LocationManager service.

Source Link

//Check GPS Status true/false
public static boolean checkGPSStatus(Context context){
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE );
    boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    return statusOfGPS;
};

How can I obfuscate (protect) JavaScript?

As a JavaScript/HTML/CSS obfuscator/compressor you can also try Patu Digua.

How to vertically align a html radio button to it's label?

there are several way, one i would prefer is using a table in html. you can add two coloum three rows table and place the radio buttons and lable.

<table border="0">

<tr>
  <td><input type="radio" name="sex" value="1"></td>
  <td>radio1</td>

</tr>
<tr>
  <td><input type="radio" name="sex" value="2"></td>
  <td>radio2</td>

</tr>
</table>

IDENTITY_INSERT is set to OFF - How to turn it ON?

The Reference: http://technet.microsoft.com/en-us/library/aa259221%28v=sql.80%29.aspx

My table is named Genre with the 3 columns of Id, Name and SortOrder

The code that I used is as:

SET IDENTITY_INSERT Genre ON

INSERT INTO Genre(Id, Name, SortOrder)VALUES (12,'Moody Blues', 20) 

iOS 7 status bar back to iOS 6 default style in iPhone app?

I am late for this Answer, but i just want to share what i did, which is basically the easiest solution

First of all-> Go to your info.plist File and add Status Bar Style->Transparent Black Style(Alpha of 0.5)

Now ,here it Goes:-

Add this code in your AppDelegate.m

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
     //Whatever your code goes here
  if(kDeviceiPad){

     //adding status bar for IOS7 ipad
         if (IS_IOS7) {
              UIView *addStatusBar = [[UIView alloc] init];
              addStatusBar.frame = CGRectMake(0, 0, 1024, 20);
              addStatusBar.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1]; //change this to match your navigation bar
              [self.window.rootViewController.view addSubview:addStatusBar];
                    }
                }
    else{

         //adding status bar for IOS7 iphone
        if (IS_IOS7) {
            UIView *addStatusBar = [[UIView alloc] init];
            addStatusBar.frame = CGRectMake(0, 0, 320, 20);
            addStatusBar.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:1]; //You can give your own color pattern
            [self.window.rootViewController.view addSubview:addStatusBar];
        }

    return YES;
   }

Android offline documentation and sample codes

here is direct link for api 17 documentation. Just extract at under docs folder. Hope it helps.

https://dl-ssl.google.com/android/repository/docs-17_r02.zip   (129 MB)

'this' vs $scope in AngularJS controllers

In this course(https://www.codeschool.com/courses/shaping-up-with-angular-js) they explain how to use "this" and many other stuff.

If you add method to the controller through "this" method, you have to call it in the view with controller's name "dot" your property or method.

For example using your controller in the view you may have code like this:

    <div data-ng-controller="YourController as aliasOfYourController">

       Your first pane is {{aliasOfYourController.panes[0]}}

    </div>

When can I use a forward declaration?

As, Luc Touraille has already explained it very well where to use and not use forward declaration of the class.

I will just add to that why we need to use it.

We should be using Forward declaration wherever possible to avoid the unwanted dependency injection.

As #include header files are added on multiple files therefore, if we add a header into another header file it will add unwanted dependency injection in various parts of source code which can be avoided by adding #include header into .cpp files wherever possible rather than adding to another header file and use class forward declaration wherever possible in header .h files.

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

How can I get the number of records affected by a stored procedure?

Turns out for me that SET NOCOUNT ON was set in the stored procedure script (by default on SQL Server Management Studio) and SqlCommand.ExecuteNonQuery(); always returned -1.

I just set it off: SET NOCOUNT OFF without needing to use @@ROWCOUNT.

More details found here : SqlCommand.ExecuteNonQuery() returns -1 when doing Insert / Update / Delete

What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

One way to get this error in Eclipse :

  1. Define a class A in src/test/java.
  2. Define another class B in src/main/java that uses class A.

Result : Eclipse will compile the code, but maven will give "Cannot find symbol".

Underlying cause : Eclipse is using a combined build path for the main and test trees. Unfortunately, it does not support using different build paths for different parts of an Eclipse project, which is what Maven requires.

Solution :

  1. Don't define your dependencies that way; i.e. don't make this mistake.
  2. Regularly build your codebase using Maven so that you pick up this mistake early. One way to do that is to use a CI server.

JavaScript require() on client side

Some answers already - but I would like to point you to YUI3 and its on-demand module loading. It works on both server (node.js) and client, too - I have a demo website using the exact same JS code running on either client or server to build the pages, but that's another topic.

YUI3: http://developer.yahoo.com/yui/3/

Videos: http://developer.yahoo.com/yui/theater/

Example:

(precondition: the basic YUI3 functions in 7k yui.js have been loaded)

YUI({
    //configuration for the loader
}).use('node','io','own-app-module1', function (Y) {
    //sandboxed application code
    //...

    //If you already have a "Y" instance you can use that instead
    //of creating a new (sandbox) Y:
    //  Y.use('moduleX','moduleY', function (Y) {
    //  });
    //difference to YUI().use(): uses the existing "Y"-sandbox
}

This code loads the YUI3 modules "node" and "io", and the module "own-app-module1", and then the callback function is run. A new sandbox "Y" with all the YUI3 and own-app-module1 functions is created. Nothing appears in the global namespace. The loading of the modules (.js files) is handled by the YUI3 loader. It also uses (optional, not show here) configuration to select a -debug or -min(ified) version of the modules to load.

AES Encryption for an NSString on the iPhone

@owlstead, regarding your request for "a cryptographically secure variant of one of the given answers," please see RNCryptor. It was designed to do exactly what you're requesting (and was built in response to the problems with the code listed here).

RNCryptor uses PBKDF2 with salt, provides a random IV, and attaches HMAC (also generated from PBKDF2 with its own salt. It support synchronous and asynchronous operation.

Check if a Python list item contains a string inside another string

If you only want to check for the presence of abc in any string in the list, you could try

some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any("abc" in s for s in some_list):
    # whatever

If you really want to get all the items containing abc, use

matching = [s for s in some_list if "abc" in s]

Convert json data to a html table

I have rewritten your code in vanilla-js, using DOM methods to prevent html injection.

Demo

_x000D_
_x000D_
var _table_ = document.createElement('table'),_x000D_
  _tr_ = document.createElement('tr'),_x000D_
  _th_ = document.createElement('th'),_x000D_
  _td_ = document.createElement('td');_x000D_
_x000D_
// Builds the HTML Table out of myList json data from Ivy restful service._x000D_
function buildHtmlTable(arr) {_x000D_
  var table = _table_.cloneNode(false),_x000D_
    columns = addAllColumnHeaders(arr, table);_x000D_
  for (var i = 0, maxi = arr.length; i < maxi; ++i) {_x000D_
    var tr = _tr_.cloneNode(false);_x000D_
    for (var j = 0, maxj = columns.length; j < maxj; ++j) {_x000D_
      var td = _td_.cloneNode(false);_x000D_
      cellValue = arr[i][columns[j]];_x000D_
      td.appendChild(document.createTextNode(arr[i][columns[j]] || ''));_x000D_
      tr.appendChild(td);_x000D_
    }_x000D_
    table.appendChild(tr);_x000D_
  }_x000D_
  return table;_x000D_
}_x000D_
_x000D_
// Adds a header row to the table and returns the set of columns._x000D_
// Need to do union of keys from all records as some records may not contain_x000D_
// all records_x000D_
function addAllColumnHeaders(arr, table) {_x000D_
  var columnSet = [],_x000D_
    tr = _tr_.cloneNode(false);_x000D_
  for (var i = 0, l = arr.length; i < l; i++) {_x000D_
    for (var key in arr[i]) {_x000D_
      if (arr[i].hasOwnProperty(key) && columnSet.indexOf(key) === -1) {_x000D_
        columnSet.push(key);_x000D_
        var th = _th_.cloneNode(false);_x000D_
        th.appendChild(document.createTextNode(key));_x000D_
        tr.appendChild(th);_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
  table.appendChild(tr);_x000D_
  return columnSet;_x000D_
}_x000D_
_x000D_
document.body.appendChild(buildHtmlTable([{_x000D_
    "name": "abc",_x000D_
    "age": 50_x000D_
  },_x000D_
  {_x000D_
    "age": "25",_x000D_
    "hobby": "swimming"_x000D_
  },_x000D_
  {_x000D_
    "name": "xyz",_x000D_
    "hobby": "programming"_x000D_
  }_x000D_
]));
_x000D_
_x000D_
_x000D_

Adding link a href to an element using css

You don't need CSS for this.

     <img src="abc"/>

now with link:

     <a href="#myLink"><img src="abc"/></a>

Or with jquery, later on, you can use the wrap property, see these questions answer:

how to add a link to an image using jquery?

How to use EOF to run through a text file in C?

One possible C loop would be:

#include <stdio.h>
int main()
{
    int c;
    while ((c = getchar()) != EOF)
    {
        /*
        ** Do something with c, such as check against '\n'
        ** and increment a line counter.
        */
    }
}

For now, I would ignore feof and similar functions. Exprience shows that it is far too easy to call it at the wrong time and process something twice in the belief that eof hasn't yet been reached.

Pitfall to avoid: using char for the type of c. getchar returns the next character cast to an unsigned char and then to an int. This means that on most [sane] platforms the value of EOF and valid "char" values in c don't overlap so you won't ever accidentally detect EOF for a 'normal' char.

How to check whether dynamically attached event listener exists or not?

I just wrote a script that lets you achieve this. It gives you two global functions: hasEvent(Node elm, String event) and getEvents(Node elm) which you can utilize. Be aware that it modifies the EventTarget prototype method add/RemoveEventListener, and does not work for events added through HTML markup or javascript syntax of elm.on_event = ...

More info at GitHub

Live Demo

Script:

var hasEvent,getEvents;!function(){function b(a,b,c){c?a.dataset.events+=","+b:a.dataset.events=a.dataset.events.replace(new RegExp(b),"")}function c(a,c){var d=EventTarget.prototype[a+"EventListener"];return function(a,e,f,g,h){this.dataset.events||(this.dataset.events="");var i=hasEvent(this,a);return c&&i||!c&&!i?(h&&h(),!1):(d.call(this,a,e,f),b(this,a,c),g&&g(),!0)}}hasEvent=function(a,b){var c=a.dataset.events;return c?new RegExp(b).test(c):!1},getEvents=function(a){return a.dataset.events.replace(/(^,+)|(,+$)/g,"").split(",").filter(function(a){return""!==a})},EventTarget.prototype.addEventListener=c("add",!0),EventTarget.prototype.removeEventListener=c("remove",!1)}();

How to check if iframe is loaded or it has a content?

I got a trick working as follows: [have not tested cross-browser!]

Define iframe's onload event handler defined as

_x000D_
_x000D_
$('#myIframe').on('load', function() {_x000D_
    setTimeout(function() {_x000D_
        try {_x000D_
            console.log($('#myIframe')[0].contentWindow.document);_x000D_
        } catch (e) {_x000D_
            console.log(e);_x000D_
            if (e.message.indexOf('Blocked a frame with origin') > -1 || e.message.indexOf('from accessing a cross-origin frame.') > -1) {_x000D_
                alert('Same origin Iframe error found!!!');_x000D_
                //Do fallback handling if you want here_x000D_
            }_x000D_
        }_x000D_
    }, 1000);_x000D_
_x000D_
});
_x000D_
_x000D_
_x000D_

Disclaimer: It works only for SAME ORIGIN IFRAME documents.

How to increase storage for Android Emulator? (INSTALL_FAILED_INSUFFICIENT_STORAGE)

Try choosing project -> clean. A simple clean may fix it up.

Python syntax for "if a or b or c but not all of them"

I'd go for:

conds = iter([a, b, c])
if any(conds) and not any(conds):
    # okay...

I think this should short-circuit fairly efficiently

Explanation

By making conds an iterator, the first use of any will short circuit and leave the iterator pointing to the next element if any item is true; otherwise, it will consume the entire list and be False. The next any takes the remaining items in the iterable, and makes sure than there aren't any other true values... If there are, the whole statement can't be true, thus there isn't one unique element (so short circuits again). The last any will either return False or will exhaust the iterable and be True.

note: the above checks if only a single condition is set


If you want to check if one or more items, but not every item is set, then you can use:

not all(conds) and any(conds)

"Multiple definition", "first defined here" errors

Maybe you included the .c file in makefile multiple times.

Why is JavaFX is not included in OpenJDK 8 on Ubuntu Wily (15.10)?

I use ubuntu 16.04 and because I already had openJDK installed, this command have solved the problem. Don't forget that JavaFX is part of OpenJDK.

sudo apt-get install openjfx

Converting an int to a binary string representation in Java?

public class Main  {

   public static String toBinary(int n, int l ) throws Exception {
       double pow =  Math.pow(2, l);
       StringBuilder binary = new StringBuilder();
        if ( pow < n ) {
            throw new Exception("The length must be big from number ");
        }
       int shift = l- 1;
       for (; shift >= 0 ; shift--) {
           int bit = (n >> shift) & 1;
           if (bit == 1) {
               binary.append("1");
           } else {
               binary.append("0");
           }
       }
       return binary.toString();
   }

    public static void main(String[] args) throws Exception {
        System.out.println(" binary = " + toBinary(7, 4));
        System.out.println(" binary = " + Integer.toString(7,2));
    }
}

Bootstrap 4 navbar color

<nav class="navbar navbar-toggleable-md navbar-light bg-danger">

So you have this code here, you must be knowing that bg-danger gives some sort of color. Now if you want to give some custom color to your page then simply change bg-danger to bg-color. Then either create a separate css-file or you can workout with style element in same tag . Just do this-

`<nav class="navbar navbar-toggleable-md navbar-light bg-color" style="background-color: cyan;">` . 

That would do.

addEventListener for keydown on Canvas

Edit - This answer is a solution, but a much simpler and proper approach would be setting the tabindex attribute on the canvas element (as suggested by hobberwickey).

You can't focus a canvas element. A simple work around this, would be to make your "own" focus.

var lastDownTarget, canvas;
window.onload = function() {
    canvas = document.getElementById('canvas');

    document.addEventListener('mousedown', function(event) {
        lastDownTarget = event.target;
        alert('mousedown');
    }, false);

    document.addEventListener('keydown', function(event) {
        if(lastDownTarget == canvas) {
            alert('keydown');
        }
    }, false);
}

JSFIDDLE

Linux command to print directory structure in the form of a tree

I'm prettifying the output of @Hassou's answer with:

ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/-/+/' -e '$s/+/+/'

This is much like the output of tree now:

.
+-pkcs11
+-pki
+---ca-trust
+-----extracted
+-------java
+-------openssl
+-------pem
+-----source
+-------anchors
+-profile.d
+-ssh

You can also make an alias of it:

alias ltree=$'ls -R | grep ":$" | sed -e \'s/:$//\' -e \'s/[^-][^\/]*\//--/g\' -e \'s/-/+/\' -e \'$s/+/+/\''

BTW, tree is not available in some environment, like MinGW. So the alternate is helpful.

REACT - toggle class onclick

Thanks to @cssko for providing the correct answer, but if you tried it yourself you will realise it does not work. A suggestion has been made by @Matei Radu, but was rejected by @cssko, so the code remains unrunnable (it will throw error 'Cannot read property bind of undefined'). Below is the working correct answer:

_x000D_
_x000D_
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.addActiveClass = this.addActiveClass.bind(this);
    this.state = {
      active: false,
    };
  }
  addActiveClass() {
    const currentState = this.state.active;
    this.setState({
      active: !currentState
    });
  };

  render() {
    return ( <
      div className = {
        this.state.active ? 'your_className' : null
      }
      onClick = {
        this.addActiveClass
      } >
      <
      p > {
        this.props.text
      } < /p> < /
      div >
    )
  }
}

class Test extends React.Component {
  render() {
    return ( <
      div >
      <
      MyComponent text = {
        'Clicking this will toggle the opacity through css class'
      }
      /> < /
      div >
    );
  }
}

ReactDOM.render( <
  Test / > ,
  document.body
);
_x000D_
.your_className {
  opacity: 0.3
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
_x000D_
_x000D_
_x000D_

How to Code Double Quotes via HTML Codes

There really aren't any differences.

&quot; is processed as &#34; which is the decimal equivalent of &x22; which is the ISO 8859-1 equivalent of ".

The only reason you may be against using &quot; is because it was mistakenly omitted from the HTML 3.2 specification.

Otherwise it all boils down to personal preference.

How do I get the command-line for an Eclipse run configuration?

I found a solution on Stack Overflow for Java program run configurations which also works for JUnit run configurations.

You can get the full command executed by your configuration on the Debug tab, or more specifically the Debug view.

  1. Run your application
  2. Go to your Debug perspective
  3. There should be an entry in there (in the Debug View) for the app you've just executed
  4. Right-click the node which references java.exe or javaw.exe and select Properties In the dialog that pops up you'll see the Command Line which includes all jars, parameters, etc

How to put an image next to each other

try putting both images next to each other. Like this:

    <div id="icons"><a href="http://www.facebook.com/"><img src="images/facebook.png"></a><a href="https://twitter.com"><img src="images/twitter.png"></a>
    </div>

How to change default timezone for Active Record in Rails?

I came to the same conclusion as Dean Perry after much anguish. config.time_zone = 'Adelaide' and config.active_record.default_timezone = :local was the winning combination. Here's what I found during the process.

What is the default access modifier in Java?

Default access modifier - If a class has no modifier (the default, also known as package-private), it is visible only within its own package (packages are named groups of related classes).

How to get your Netbeans project into Eclipse

You should be using Maven, as the structure is standardized. To do that (Once you have created your Maven project in Netbeans, just

  1. Go to File -> Import
  2. Open Maven tree node
  3. Select Existing Maven Project
  4. Browse to find your project from NetBeans
  5. Check Add project to Working Set
  6. Click finish.

As long as the project has no errors, I usually get none transferring to eclipse. This works for Maven web projects and regular projects.

How do I install a color theme for IntelliJ IDEA 7.0.x

Themes downloaded from IntelliJ can be installed as a Plugin.

Take these steps:

Preferences -> Plugins -> GearIcon -> Install Plugin from disk -> Reset your IDE ->  Preferences -> Appearance -> Theme -> Select your theme.

Rename multiple files in cmd

Step 1:

Select all files (ctrl + A)

Step 2 :

Then choose rename option

enter image description here

Step 3:

Choose your filename... for ex: myfile

it automatically rename to myfile (01),myfile (02),,.....

If you want to replace spaces & bracket.. continue step 4

Step 4:

Open Windows Powershell from your current folder

enter image description here

Step 5:

For replace empty space to underscore (_)

 dir | rename-item -NewName {$_.name -replace [Regex]::Escape(" "),"_"}

Step 6:

For replace open bracket

 dir | rename-item -NewName {$_.name -replace [Regex]::Escape("("),""}

For replace close bracket

 dir | rename-item -NewName {$_.name -replace [Regex]::Escape(")"),""}

CSS media queries: max-width OR max-height

yes, using and, like:

@media screen and (max-width: 800px), 
       screen and (max-height: 600px) {
  ...
}

How to determine day of week by passing specific date?

import java.text.SimpleDateFormat;
import java.util.Scanner;

class DayFromDate {

    public static void main(String args[]) {

        System.out.println("Enter the date(dd/mm/yyyy):");
        Scanner scan = new Scanner(System.in);
        String Date = scan.nextLine();

        try {
            boolean dateValid = dateValidate(Date);

            if(dateValid == true) {
                SimpleDateFormat df = new SimpleDateFormat( "dd/MM/yy" );  
                java.util.Date date = df.parse( Date );   
                df.applyPattern( "EEE" );  
                String day= df.format( date ); 

                if(day.compareTo("Sat") == 0 || day.compareTo("Sun") == 0) {
                    System.out.println(day + ": Weekend");
                } else {
                    System.out.println(day + ": Weekday");
                }
            } else {
                System.out.println("Invalid Date!!!");
            }
        } catch(Exception e) {
            System.out.println("Invalid Date Formats!!!");
        }
     }

    static public boolean dateValidate(String d) {

        String dateArray[] = d.split("/");
        int day = Integer.parseInt(dateArray[0]);
        int month = Integer.parseInt(dateArray[1]);
        int year = Integer.parseInt(dateArray[2]);
        System.out.print(day + "\n" + month + "\n" + year + "\n");
        boolean leapYear = false;

        if((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0)) {
            leapYear = true;
        }

        if(year > 2099 || year < 1900)
            return false;

        if(month < 13) {
            if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
                if(day > 31)
                    return false;
            } else if(month == 4 || month == 6 || month == 9 || month == 11) {
                if(day > 30)
                    return false;
            } else if(leapYear == true && month == 2) {
                if(day > 29)
                    return false;
            } else if(leapYear == false && month == 2) {
                if(day > 28)
                    return false;
            }

            return true;    
        } else return false;
    }
}

Vim and Ctags tips and tricks

The command I am using most is C-] which jumps to the definition of the function under the cursor. You can use it more often to follow more calls. After that, C-o will bring you back one level, C-i goes deeper again.

How to increase heap size for jBoss server

Add following option in jboss in bin/standalone.conf.bat

   set "JAVA_OPTS=-Xms1G -Xmx1G -XX:MetaspaceSize=96M -XX:MaxMetaspaceSize=1024m"

Reload chart data via JSON with Highcharts

EDIT: The response down below is more correct!

https://stackoverflow.com/a/8408466/387285

http://www.highcharts.com/ref/#series-object

HTML:

<SELECT id="list">
<OPTION VALUE="A">Data Set A
<OPTION VALUE="B">Data Set B
</SELECT>
<button id="change">Refresh Table</button>

<div id="container" style="height: 400px"></div>

Javascript:

var options = {
    chart: {
        renderTo: 'container',
        defaultSeriesType: 'spline'
    },
    series: []
};

$("#change").click(function() {
    if ($("#list").val() == "A") {
        options.series = [{name: 'A', data: [1,2,3,2,1]}]
        // $.get('/dough/includes/live-chart.php?mode=month'
    } else {
        options.series = [{name: 'B', data: [3,2,1,2,3]}]
        // $.get('/dough/includes/live-chart.php?mode=newmode'
    } 

    var chart = new Highcharts.Chart(options);    
});

This is a very simple example since I don't have my files here with me but the basic idea is that every time the user selects new options for the stuff they want to see, you're going to have replace the .series data object with the new information from your server and then recreate the chart using the new Highcharts.Chart();.

Hope this helps! John

EDIT:

Check this out, its from something I've worked on in the past:

$("table#tblGeneralInfo2 > tbody > tr").each(function (index) {
    if (index != 0) {
        var chartnumbervalue = parseInt($(this).find("td:last").text());
        var charttextvalue = $(this).find("td:first").text();
        chartoptions.series[0].data.push([charttextvalue, chartnumbervalue]);
    }
});

I had a table with information in the first and last tds that I needed to add to the pie chart. I loop through each of the rows and push in the values. Note: I use chartoptions.series[0].data since pie charts only have 1 series.

How to run SQL in shell script

#!/bin/ksh
variable1=$( 
echo "set feed off
set pages 0
select count(*) from table;
exit
"  | sqlplus -s username/password@oracle_instance
)
echo "found count = $variable1"

Eclipse reported "Failed to load JNI shared library"

Yep, in Windows 7 64 bit you have C:\Program Files and C:\Program Files (x86). You can find Java folders in both of them, but you must add C:\Program Files\Java\jre7\bin to environment variable PATH.

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

One thing to note when using uuid1, if you use the default call (without giving clock_seq parameter) you have a chance of running into collisions: you have only 14 bit of randomness (generating 18 entries within 100ns gives you roughly 1% chance of a collision see birthday paradox/attack). The problem will never occur in most use cases, but on a virtual machine with poor clock resolution it will bite you.

JavaScript: Passing parameters to a callback function

Code from a question with any number of parameters and a callback context:

function SomeFunction(name) {
    this.name = name;
}
function tryMe(param1, param2) {
    console.log(this.name + ":  " + param1 + " and " + param2);
}
function tryMeMore(param1, param2, param3) {
    console.log(this.name + ": " + param1 + " and " + param2 + " and even " + param3);
}
function callbackTester(callback, callbackContext) {
    callback.apply(callbackContext, Array.prototype.splice.call(arguments, 2));
}
callbackTester(tryMe, new SomeFunction("context1"), "hello", "goodbye");
callbackTester(tryMeMore, new SomeFunction("context2"), "hello", "goodbye", "hasta la vista");

// context1: hello and goodbye
// context2: hello and goodbye and even hasta la vista

Content is not allowed in Prolog SAXParserException

Check the XML. It is not a valid xml.

Prolog is the first line with xml version info. It ok not to include it in your xml.

This error is thrown when the parser reads an invalid tag at the start of the document. Normally where the prolog resides.

e.g.

  1. Root/><document>
  2. Root<document>

How to Serialize a list in java?

All standard implementations of java.util.List already implement java.io.Serializable.

So even though java.util.List itself is not a subtype of java.io.Serializable, it should be safe to cast the list to Serializable, as long as you know it's one of the standard implementations like ArrayList or LinkedList.

If you're not sure, then copy the list first (using something like new ArrayList(myList)), then you know it's serializable.

Object passed as parameter to another class, by value or reference?

Objects will be passed by reference irrespective of within methods of same class or another class. Here is a modified version of same sample code to help you understand. The value will be changed to 'xyz.'

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class Employee
    {
        public string Name { get; set; }
    }

    public class MyClass
    {
        public Employee EmpObj;

        public void SetObject(Employee obj)
        {
            EmpObj = obj;
        }
    }

    public class Program
    {
       static void Main(string[] args)
        {
            Employee someTestObj = new Employee();
            someTestObj.Name = "ABC";

            MyClass cls = new MyClass();
            cls.SetObject(someTestObj);

            Console.WriteLine("Changing Emp Name To xyz");
            someTestObj.Name = "xyz";

            Console.WriteLine("Accessing Assigned Emp Name");
            Console.WriteLine(cls.EmpObj.Name); 

           Console.ReadLine();
       }       
    }
 }

How to close TCP and UDP ports via windows command line

Use TCPView: http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx
or CurrPorts: https://www.nirsoft.net/utils/cports.html

Alternatively, if you don't want to use EXTERNAL SOFTWARE (these tools don't require an installation by the way), you can simply FIRST run the netstat command (preferably netstat -b ) & then setup Local Security Policy to block the IP address of the user's machine in question, that's what I have been doing with unwanted or even unknown connections - that allows you doing everything WITHOUT ANY EXTERNAL SOFTWARE (everything comes with Windows)...

NLS_NUMERIC_CHARACTERS setting for decimal

Jaanna, the session parameters in Oracle SQL Developer are dependent on your client computer, while the NLS parameters on PL/SQL is from server.

For example the NLS_NUMERIC_CHARACTERS on client computer can be ',.' while it's '.,' on server.

So when you run script from PL/SQL and Oracle SQL Developer the decimal separator can be completely different for the same script, unless you alter session with your expected NLS_NUMERIC_CHARACTERS in the script.

One way to easily test your session parameter is to do:

select to_number(5/2) from dual;

What is the difference between call and apply?

We can differentiate call and apply methods as below

CALL : A function with argument provide individually. If you know the arguments to be passed or there are no argument to pass you can use call.

APPLY : Call a function with argument provided as an array. You can use apply if you don't know how many argument are going to pass to the function.

There is a advantage of using apply over call, we don't need to change the number of argument only we can change a array that is passed.

There is not big difference in performance. But we can say call is bit faster as compare to apply because an array need to evaluate in apply method.

Jquery checking success of ajax post

The documentation is here: http://docs.jquery.com/Ajax/jQuery.ajax

But, to summarize, the ajax call takes a bunch of options. the ones you are looking for are error and success.

You would call it like this:

$.ajax({
  url: 'mypage.html',
  success: function(){
    alert('success');
  },
  error: function(){
    alert('failure');
  }
});

I have shown the success and error function taking no arguments, but they can receive arguments.

The error function can take three arguments: XMLHttpRequest, textStatus, and errorThrown.

The success function can take two arguments: data and textStatus. The page you requested will be in the data argument.

Converting a double to an int in Javascript without rounding

I find the "parseInt" suggestions to be pretty curious, because "parseInt" operates on strings by design. That's why its name has the word "parse" in it.

A trick that avoids a function call entirely is

var truncated = ~~number;

The double application of the "~" unary operator will leave you with a truncated version of a double-precision value. However, the value is limited to 32 bit precision, as with all the other JavaScript operations that implicitly involve considering numbers to be integers (like array indexing and the bitwise operators).

edit — In an update quite a while later, another alternative to the ~~ trick is to bitwise-OR the value with zero:

var truncated = number|0;

Parsing a JSON string in Ruby

It looks like a JSON string. You can use one of many JSON libraries and it's as simple as doing:

JSON.parse(string)

What's the difference between ISO 8601 and RFC 3339 Date Formats?

Is one just an extension?

Pretty much, yes - RFC 3339 is listed as a profile of ISO 8601. Most notably RFC 3339 specifies a complete representation of date and time (only fractional seconds are optional). The RFC also has some small, subtle differences. For example truncated representations of years with only two digits are not allowed -- RFC 3339 requires 4-digit years, and the RFC only allows a period character to be used as the decimal point for fractional seconds. The RFC also allows the "T" to be replaced by a space (or other character), while the standard only allows it to be omitted (and only when there is agreement between all parties using the representation).

I wouldn't worry too much about the differences between the two, but on the off-chance your use case runs in to them, it'd be worth your while taking a glance at:

How to make blinking/flashing text with CSS 3

Use the alternate value for animation-direction (and you don't need to add any keframes this way).

alternate

The animation should reverse direction each cycle. When playing in reverse, the animation steps are performed backward. In addition, timing functions are also reversed; for example, an ease-in animation is replaced with an ease-out animation when played in reverse. The count to determinate if it is an even or an odd iteration starts at one.

CSS:

.waitingForConnection {
  animation: blinker 1.7s cubic-bezier(.5, 0, 1, 1) infinite alternate;  
}
@keyframes blinker { to { opacity: 0; } }

I've removed the from keyframe. If it's missing, it gets generated from the value you've set for the animated property (opacity in this case) on the element, or if you haven't set it (and you haven't in this case), from the default value (which is 1 for opacity).

And please don't use just the WebKit version. Add the unprefixed one after it as well. If you just want to write less code, use the shorthand.

_x000D_
_x000D_
.waitingForConnection {
  animation: blinker 1.7s cubic-bezier(.5, 0, 1, 1) infinite alternate;  
}
@keyframes blinker { to { opacity: 0; } }

.waitingForConnection2 {
  animation: blinker2 0.6s cubic-bezier(1, 0, 0, 1) infinite alternate;  
}
@keyframes blinker2 { to { opacity: 0; } }

.waitingForConnection3 {
  animation: blinker3 1s ease-in-out infinite alternate;  
}
@keyframes blinker3 { to { opacity: 0; } }
_x000D_
<div class="waitingForConnection">X</div>
<div class="waitingForConnection2">Y</div>
<div class="waitingForConnection3">Z</div>
_x000D_
_x000D_
_x000D_

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

Installing the following package on Ubuntu fixed the issue for me

sudo apt-get install libssl-dev

How to use ArrayList's get() method

Would this help?

final List<String> l = new ArrayList<String>();
for (int i = 0; i < 10; i++) l.add("Number " + i);
for (int i = 0; i < 10; i++) System.out.println(l.get(i));

Decrypt password created with htpasswd

.htpasswd entries are HASHES. They are not encrypted passwords. Hashes are designed not to be decryptable. Hence there is no way (unless you bruteforce for a loooong time) to get the password from the .htpasswd file.

What you need to do is apply the same hash algorithm to the password provided to you and compare it to the hash in the .htpasswd file. If the user and hash are the same then you're a go.

onchange file input change img src and change image color

in your HTML : <input type="file" id="yourFile"> don't forget to reference your js file or put the following script between <script></script> in your script :

var fileToRead = document.getElementById("yourFile");

fileToRead.addEventListener("change", function(event) {
    var files = fileToRead.files;
    if (files.length) {
        console.log("Filename: " + files[0].name);
        console.log("Type: " + files[0].type);
        console.log("Size: " + files[0].size + " bytes");
    }

}, false);

SQLite UPSERT / UPDATE OR INSERT

This is a late answer. Starting from SQLIte 3.24.0, released on June 4, 2018, there is finally a support for UPSERT clause following PostgreSQL syntax.

INSERT INTO players (user_name, age)
  VALUES('steven', 32) 
  ON CONFLICT(user_name) 
  DO UPDATE SET age=excluded.age;

Note: For those having to use a version of SQLite earlier than 3.24.0, please reference this answer below (posted by me, @MarqueIV).

However if you do have the option to upgrade, you are strongly encouraged to do so as unlike my solution, the one posted here achieves the desired behavior in a single statement. Plus you get all the other features, improvements and bug fixes that usually come with a more recent release.

What uses are there for "placement new"?

It's used by std::vector<> because std::vector<> typically allocates more memory than there are objects in the vector<>.

How to convert an entire MySQL database characterset and collation to UTF-8?

DELIMITER $$  

CREATE PROCEDURE `databasename`.`update_char_set`()  

BEGIN  
 DECLARE done INT DEFAULT 0;  
 DECLARE t_sql VARCHAR(256);  
 DECLARE tableName VARCHAR(128);  
 DECLARE lists CURSOR FOR SELECT table_name FROM `information_schema`.`TABLES` WHERE table_schema = 'databasename';  
 DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;  
 OPEN lists;  
 FETCH lists INTO tableName;  
 REPEAT  
    SET @t_sql = CONCAT('ALTER TABLE ', tableName, ' CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci');  
    PREPARE stmt FROM @t_sql;  
    EXECUTE stmt;  
    DEALLOCATE PREPARE stmt;  
 FETCH lists INTO tableName;  
 UNTIL done END REPEAT;  
 CLOSE lists;  
END$$  

DELIMITER ;  

CALL databasename.update_char_set();

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

I just updated to High Sierra and I couldn't just run xcode-select --install. First, I had to actually install xcode from the app store. Then I ran xcode-select --install. Then I had to run sudo xcodebuild -license, agree to the terms, then I could finally run git commands again.

Show red border for all invalid fields after submitting form angularjs

Reference article: Show red color border for invalid input fields angualrjs

I used ng-class on all input fields.like below

<input type="text" ng-class="{submitted:newEmployee.submitted}" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/>

when I click on save button I am changing newEmployee.submitted value to true(you can check it in my question). So when I click on save, a class named submitted gets added to all input fields(there are some other classes initially added by angularjs).

So now my input field contains classes like this

class="ng-pristine ng-invalid submitted"

now I am using below css code to show red border on all invalid input fields(after submitting the form)

input.submitted.ng-invalid
{
  border:1px solid #f00;
}

Thank you !!

Update:

We can add the ng-class at the form element instead of applying it to all input elements. So if the form is submitted, a new class(submitted) gets added to the form element. Then we can select all the invalid input fields using the below selector

form.submitted .ng-invalid
{
    border:1px solid #f00;
}

How to remove files and directories quickly via terminal (bash shell)

rm -rf *

Would remove everything (folders & files) in the current directory.

But be careful! Only execute this command if you are absolutely sure, that you are in the right directory.

NSRange from Swift Range?

I love the Swift language, but using NSAttributedString with a Swift Range that is not compatible with NSRange has made my head hurt for too long. So to get around all that garbage I devised the following methods to return an NSMutableAttributedString with the highlighted words set with your color.

This does not work for emojis. Modify if you must.

extension String {
    func getRanges(of string: String) -> [NSRange] {
        var ranges:[NSRange] = []
        if contains(string) {
            let words = self.components(separatedBy: " ")
            var position:Int = 0
            for word in words {
                if word.lowercased() == string.lowercased() {
                    let startIndex = position
                    let endIndex = word.characters.count
                    let range = NSMakeRange(startIndex, endIndex)
                    ranges.append(range)
                }
                position += (word.characters.count + 1) // +1 for space
            }
        }
        return ranges
    }
    func highlight(_ words: [String], this color: UIColor) -> NSMutableAttributedString {
        let attributedString = NSMutableAttributedString(string: self)
        for word in words {
            let ranges = getRanges(of: word)
            for range in ranges {
                attributedString.addAttributes([NSForegroundColorAttributeName: color], range: range)
            }
        }
        return attributedString
    }
}

Usage:

// The strings you're interested in
let string = "The dog ran after the cat"
let words = ["the", "ran"]

// Highlight words and get back attributed string
let attributedString = string.highlight(words, this: .yellow)

// Set attributed string
label.attributedText = attributedString

How can I remove a child node in HTML using JavaScript?

Use the following code:

//for Internet Explorer
document.getElementById("FirstDiv").removeNode(true);

//for other browsers
var fDiv = document.getElementById("FirstDiv");
fDiv.removeChild(fDiv.childNodes[0]); //first check on which node your required node exists, if it is on [0] use this, otherwise use where it exists.

Using Gradle to build a jar with dependencies

Simple sulution

jar {
    manifest {
        attributes 'Main-Class': 'cova2.Main'
    } 
    doFirst {
        from { configurations.runtime.collect { it.isDirectory() ? it : zipTree(it) } }
    }
}

Running Tensorflow in Jupyter Notebook

  1. Install Anaconda
  2. Run Anaconda command prompt
  3. write "activate tensorflow" for windows
  4. pip install tensorflow
  5. pip install jupyter notebook
  6. jupyter notebook.

Only this solution worked for me. Tried 7 8 solutions. Using Windows platform.

How to VueJS router-link active style

Just add to @Bert's solution to make it more clear:

    const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes,
  linkExactActiveClass: "active" // active class for *exact* links.
})

As one can see, this line should be removed:

linkActiveClass: "active", // active class for non-exact links.

this way, ONLY the current link is hi-lighted. This should apply to most of the cases.

David

How to configure custom PYTHONPATH with VM and PyCharm?

For PyCharm 5 (or 2016.1), you can:

  1. select Preferences > Project Interpreter
  2. to the right of interpreter selector there is a "..." button, click it
  3. select "more..."
  4. pop up a new "Project Interpreters" window
  5. select the rightest button (named "show paths for the selected interpreter")
  6. pop up a "Interpreter Paths" window
  7. click the "+" buttom > select your desired PYTHONPATH directory (the folder which contains python modules) and click OK
  8. Done! Enjoy it!

enter image description here

enter image description here

enter image description here enter image description here

How to use phpexcel to read data and insert into database?

Here is a very recent answer to this question from the file: 07reader.php

<?php


error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />');

date_default_timezone_set('Europe/London');

/** Include PHPExcel_IOFactory */
require_once '../Classes/PHPExcel/IOFactory.php';


if (!file_exists("05featuredemo.xlsx")) {
    exit("Please run 05featuredemo.php first." . EOL);
}

echo date('H:i:s') , " Load from Excel2007 file" , EOL;
$callStartTime = microtime(true);

$objPHPExcel = PHPExcel_IOFactory::load("05featuredemo.xlsx");

$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;
echo 'Call time to read Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
// Echo memory usage
echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;


echo date('H:i:s') , " Write to Excel2007 format" , EOL;
$callStartTime = microtime(true);

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));

$callEndTime = microtime(true);
$callTime = $callEndTime - $callStartTime;

echo date('H:i:s') , " File written to " , str_replace('.php', '.xlsx', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL;
echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL;
// Echo memory usage
echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL;


// Echo memory peak usage
echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL;

// Echo done
echo date('H:i:s') , " Done writing file" , EOL;
echo 'File has been created in ' , getcwd() , EOL;

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

Redirect to specified URL on PHP script completion?

<?php

// do something here

header("Location: http://example.com/thankyou.php");
?>

Error "The input device is not a TTY"

when using 'git bash',

1) I execute the command:

docker exec -it 726fe4999627 /bin/bash

I have the error:

the input device is not a TTY.  If you are using mintty, try prefixing the command with 'winpty'

2) then, I execute the command:

winpty docker exec -it 726fe4999627 /bin/bash

I have another error:

OCI runtime exec failed: exec failed: container_linux.go:344: starting container process caused "exec: \"D:/Git/usr/bin/
bash.exe\": stat D:/Git/usr/bin/bash.exe: no such file or directory": unknown

3) third, I execute the:

winpty docker exec -it 726fe4999627 bash

it worked.

when I using 'powershell', all worked well.

C# get string from textbox

In C#, unlike java we do not have to use any method. TextBox property Text is used to get or set its text.

Get

string username = txtusername.Text;
string password = txtpassword.Text;

Set

txtusername.Text = "my_username";
txtpassword.Text = "12345";

Check if a string is a valid Windows directory (folder) path

I actually disagree with SLaks. That solution did not work for me. Exception did not happen as expected. But this code worked for me:

if(System.IO.Directory.Exists(path))
{
    ...
}

Force youtube embed to start in 720p

(This answer was updated, as the previous method using vq isn't recognized anymore.)

Specifying the height of the video will change the quality accordingly. example for html 5;

<iframe style='width:100%; height:800px;' src='https://www.youtube.com/embed/xxxxxxxx'></iframe>

If you don't want to hardcode the width and height you can add a class to the iframe for css media queries.

Tested on a working server + passes the w3.org nuhtml validator.

How do I use TensorFlow GPU?

I tried following the above tutorial. Thing is tensorflow changes a lot and so do the NVIDIA versions needed for running on a GPU. The next issue is that your driver version determines your toolkit version etc. As of today this information about the software requirements should shed some light on how they interplay:

NVIDIA® GPU drivers —CUDA 9.0 requires 384.x or higher.
CUDA® Toolkit —TensorFlow supports CUDA 9.0.
CUPTI ships with the CUDA Toolkit.
cuDNN SDK (>= 7.2) Note: Make sure your GPU has compute compatibility >3.0
(Optional) NCCL 2.2 for multiple GPU support.
(Optional) TensorRT 4.0 to improve latency and throughput for inference on some models.

And here you'll find the up-to-date requirements stated by tensorflow (which will hopefully be updated by them on a regular basis).

What is the purpose of "&&" in a shell command?

command-line - what is the purpose of &&?

In shell, when you see

$ command one && command two

the intent is to execute the command that follows the && only if the first command is successful. This is idiomatic of Posix shells, and not only found in Bash.

It intends to prevent the running of the second process if the first fails.

You may notice I've used the word "intent" - that's for good reason. Not all programs have the same behavior, so for this to work, you need to understand what the program considers a "failure" and how it handles it by reading the documentation and, if necessary, the source code.

Your shell considers a return value of 0 for true, other positive numbers for false

Programs return a signal on exiting. They should return 0 if they exit successfully, or greater than zero if they do not. This allows a limited amount of communication between processes.

The && is referred to as AND_IF in the posix shell grammar, which is part of an and_or list of commands, which also include the || which is an OR_IF with similar semantics.

Grammar symbols, quoted from the documentation:

%token  AND_IF    OR_IF    DSEMI
/*      '&&'      '||'     ';;'    */

And the Grammar (also quoted from the documentation), which shows that any number of AND_IFs (&&) and/or OR_IFs (||) can be be strung together (as and_or is defined recursively):

and_or           :                         pipeline
                 | and_or AND_IF linebreak pipeline
                 | and_or OR_IF  linebreak pipeline

Both operators have equal precedence and are evaluated left to right (they are left associative). As the docs say:

An AND-OR list is a sequence of one or more pipelines separated by the operators "&&" and "||" .

A list is a sequence of one or more AND-OR lists separated by the operators ';' and '&' and optionally terminated by ';', '&', or .

The operators "&&" and "||" shall have equal precedence and shall be evaluated with left associativity. For example, both of the following commands write solely bar to standard output:

$ false && echo foo || echo bar
$ true || echo foo && echo bar
  1. In the first case, the false is a command that exits with the status of 1

    $ false
    $ echo $?
    1
    

    which means echo foo does not run (i.e., shortcircuiting echo foo). Then the command echo bar is executed.

  2. In the second case, true exits with a code of 0

    $ true
    $ echo $?
    0
    

    and therefore echo foo is not executed, then echo bar is executed.

Is there a template engine for Node.js?

Try "vash" - asp.net mvc like razor syntax for node.js

https://github.com/kirbysayshi/Vash

also checkout: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx


// sample
var tmpl = vash.compile('<hr/>@model.a,@model.b<hr/>');
var html = tmpl({"a": "hello", "b": "world"});
res.write(html);

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

build and listener objects are presenting during system groovy execution. You can do this:

def myVar = build.getEnvironment(listener).get('myVar')

Make selected block of text uppercase

Standard keybinding for VS Code on macOS:

Selection to upper case ?+K, ?+U and to lower case: ?+K, ?+L.

All key combinations can be opened with ?+K ?+S (like Keyboard Settings), where you can also search for specific key combinations.

AngularJS : When to use service instead of factory

The concept for all these providers is much simpler than it initially appears. If you dissect a provider you and pull out the different parts it becomes very clear.

To put it simply each one of these providers is a specialized version of the other, in this order: provider > factory > value / constant / service.

So long the provider does what you can you can use the provider further down the chain which would result in writing less code. If it doesn't accomplish what you want you can go up the chain and you'll just have to write more code.

This image illustrates what I mean, in this image you will see the code for a provider, with the portions highlighted showing you which portions of the provider could be used to create a factory, value, etc instead.

AngularJS providers, factories, services, etc are all the same thing
(source: simplygoodcode.com)

For more details and examples from the blog post where I got the image from go to: http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/

Android "hello world" pushnotification example

Overview of gcm: You send a request to google server from your android phone. You receive a registration id as a response. You will then have to send this registration id to the server from where you wish to send notifications to the mobile. Using this registration id you can then send notification to the device.

Answer:

  1. To send a notification you send the data(message) with the registration id of the device to https://android.googleapis.com/gcm/send. (use curl in php).
  2. To receive notification and registration etc, thats all you will be requiring.
  3. You will have to store the registration id on the device as well as on server. If you use GCM.jar the registration id is stored in preferences. If you wish you can save it in your local database as well.

Gerrit error when Change-Id in commit messages are missing

This can also happen if you have this restriction:

Please enter the commit message for your changes. Lines starting with '#' will be ignored, and an empty message aborts the commit.

and you do like me: write a commit message starting with "#" .....

I had the same error, but I already had the commit-msg and did the rebase and everything. Very silly mistake though :D

create a text file using javascript

You have to specify the folder where you are saving it and it has to exist, in other case it will throw an error.

var s = txt.CreateTextFile("c:\\11.txt", true);

How to I say Is Not Null in VBA

you can do like follows. Remember, IsNull is a function which returns TRUE if the parameter passed to it is null, and false otherwise.

Not IsNull(Fields!W_O_Count.Value)

How to set bootstrap navbar active class with Angular JS?

Use an object as a switch variable.
You can do this inline quite simply with:

<ul class="nav navbar-nav">
   <li ng-class="{'active':switch.linkOne}" ng-click="switch = {linkOne: true}"><a href="/">Link One</a></li>
   <li ng-class="{'active':switch.linkTwo}" ng-click="switch = {link-two: true}"><a href="/link-two">Link Two</a></li>
</ul>

Each time you click on a link the switch object is replaced by a new object where only the correct switch object property is true. The undefined properties will evaluate as false and so the elements which depend on them will not have the active class assigned.

Clear the entire history stack and start a new activity on Android

In API level 11 a new Intent Flag was added just for this: Intent.FLAG_ACTIVITY_CLEAR_TASK

Just to clarify, use this:

Java

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

Kotlin

intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK

Unfortunately for API lvl <= 10, I haven't yet found a clean solution to this. The "DontHackAndroidLikeThis" solution is indeed pure hackery. You should not do that. :)

Edit: As per @Ben Pearson's comment, for API <=10 now one can use IntentCompat class for the same. One can use IntentCompat.FLAG_ACTIVITY_CLEAR_TASK flag to clear task. So you can support pre API level 11 as well.

Applying styles to tables with Twitter Bootstrap

Bootstrap offers various table styles. Have a look at Base CSS - Tables for documentation and examples.

The following style gives great looking tables:

<table class="table table-striped table-bordered table-condensed">
  ...
</table>

Render HTML string as real HTML in a React component

If you have control to the {this.props.match.description} and if you are using JSX. I would recommend not to use "dangerouslySetInnerHTML".

// In JSX, you can define a html object rather than a string to contain raw HTML
let description = <h1>Hi there!</h1>;

// Here is how you print
return (
    {description}
);

Format numbers in django templates

If you don't want to get involved with locales here is a function that formats numbers:

def int_format(value, decimal_points=3, seperator=u'.'):
    value = str(value)
    if len(value) <= decimal_points:
        return value
    # say here we have value = '12345' and the default params above
    parts = []
    while value:
        parts.append(value[-decimal_points:])
        value = value[:-decimal_points]
    # now we should have parts = ['345', '12']
    parts.reverse()
    # and the return value should be u'12.345'
    return seperator.join(parts)

Creating a custom template filter from this function is trivial.

Check OS version in Swift?

Swift 5

We dont need to create extension since ProcessInfo gives us the version info. You can see sample code for iOS as below.

let os = ProcessInfo().operatingSystemVersion

switch (os.majorVersion, os.minorVersion, os.patchVersion) {
case (let x, _, _) where x < 8:
    print("iOS < 8.0.0")

case (8, 0, _):
    print("iOS >= 8.0.0, < 8.1.0")

case (8, _, _):
    print("iOS >= 8.1.0, < 9.0")

case (9, _, _):
    print("iOS >= 9.0.0")

default:
    print("iOS >= 10.0.0")
}

Reference: http://nshipster.com/swift-system-version-checking/

Download file and automatically save it to folder

Well, your solution almost works. There are a few things to take into account to keep it simple:

  • Cancel the default navigation only for specific URLs you know a download will occur, or the user won't be able to navigate anywhere. This means you musn't change your website download URLs.

  • DownloadFileAsync doesn't know the name reported by the server in the Content-Disposition header so you have to specify one, or compute one from the original URL if that's possible. You cannot just specify the folder and expect the file name to be retrieved automatically.

  • You have to handle download server errors from the DownloadCompleted callback because the web browser control won't do it for you anymore.

Sample piece of code, that will download into the directory specified in textBox1, but with a random file name, and without any additional error handling:

private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) {
    /* change this to match your URL. For example, if the URL always is something like "getfile.php?file=xxx", try e.Url.ToString().Contains("getfile.php?") */
    if (e.Url.ToString().EndsWith(".zip")) {
        e.Cancel = true;
        string filePath = Path.Combine(textBox1.Text, Path.GetRandomFileName());
        var client = new WebClient();
        client.DownloadFileCompleted += client_DownloadFileCompleted;
        client.DownloadFileAsync(e.Url, filePath);
    }
}

private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) {
    MessageBox.Show("File downloaded");
}

This solution should work but can be broken very easily. Try to consider some web service listing the available files for download and make a custom UI for it. It'll be simpler and you will control the whole process.

Bootstrap 3 unable to display glyphicon properly

Did you choose the customized version of Bootstrap? There is an issue that the font files included in the customized package are broken (see https://github.com/twbs/bootstrap/issues/9925). If you do not want to use the CDN, you have to download them manually and replace your own fonts with the downloaded ones:

https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.svg https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.woff https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.ttf https://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot

After that try a strong reload (CTRL + F5), hope it helps.

CSS horizontal scroll

try using table structure, it's more back compatible. Check this outHorizontal Scrolling using Tables

Why is $$ returning the same id as the parent process?

$$ is defined to return the process ID of the parent in a subshell; from the man page under "Special Parameters":

$ Expands to the process ID of the shell. In a () subshell, it expands to the process ID of the current shell, not the subshell.

In bash 4, you can get the process ID of the child with BASHPID.

~ $ echo $$
17601
~ $ ( echo $$; echo $BASHPID )
17601
17634

docker-compose up for only certain containers

You can start containers by using:

$ docker-compose up -d client

This will run containers in the background and output will be avaiable from

$ docker-compose logs

and it will consist of all your started containers

How to append binary data to a buffer in node.js

Buffers are always of fixed size, there is no built in way to resize them dynamically, so your approach of copying it to a larger Buffer is the only way.

However, to be more efficient, you could make the Buffer larger than the original contents, so it contains some "free" space where you can add data without reallocating the Buffer. That way you don't need to create a new Buffer and copy the contents on each append operation.

DataGrid get selected rows' column values

After hours of finding ways on how to get the data from the row selected on a WPF DataGrid Control, as I was using MongoDB. I found this post and used Tony's answer. I revised the code to be relevant to my project. Maybe someone can use this to get an idea.

private void selectionChanged(object sender, SelectionChangedEventArgs e)
    {
        facultyData row = (facultyData)facultyDataGrid.SelectedItem;
        facultyID_Textbox.Text = row.facultyID;
        lastName_TextBox.Text = row.lastName;
        firstName_TextBox.Text = row.firstName;
        middleName_TextBox.Text = row.middleName;
        age_TextBox.Text = row.age.ToString();
    }

}

class facultyData
{
    public ObjectId _id { get; set; }
    public string facultyID { get; set; }
    public string acadYear { get; set; }
    public string program { get; set; }   
}

CSS Pseudo-classes with inline styles

No, this is not possible. In documents that make use of CSS, an inline style attribute can only contain property declarations; the same set of statements that appears in each ruleset in a stylesheet. From the Style Attributes spec:

The value of the style attribute must match the syntax of the contents of a CSS declaration block (excluding the delimiting braces), whose formal grammar is given below in the terms and conventions of the CSS core grammar:

declaration-list
  : S* declaration? [ ';' S* declaration? ]*
  ;

Neither selectors (including pseudo-elements), nor at-rules, nor any other CSS construct are allowed.

Think of inline styles as the styles applied to some anonymous super-specific ID selector: those styles only apply to that one very element with the style attribute. (They take precedence over an ID selector in a stylesheet too, if that element has that ID.) Technically it doesn't work like that; this is just to help you understand why the attribute doesn't support pseudo-class or pseudo-element styles (it has more to do with how pseudo-classes and pseudo-elements provide abstractions of the document tree that can't be expressed in the document language).

Note that inline styles participate in the same cascade as selectors in rule sets, and take highest precedence in the cascade (!important notwithstanding). So they take precedence even over pseudo-class states. Allowing pseudo-classes or any other selectors in inline styles would possibly introduce a new cascade level, and with it a new set of complications.

Note also that very old revisions of the Style Attributes spec did originally propose allowing this, however it was scrapped, presumably for the reason given above, or because implementing it was not a viable option.

What is the C# equivalent of NaN or IsNumeric?

In addition to the previous correct answers it is probably worth pointing out that "Not a Number" (NaN) in its general usage is not equivalent to a string that cannot be evaluated as a numeric value. NaN is usually understood as a numeric value used to represent the result of an "impossible" calculation - where the result is undefined. In this respect I would say the Javascript usage is slightly misleading. In C# NaN is defined as a property of the single and double numeric types and is used to refer explicitly to the result of diving zero by zero. Other languages use it to represent different "impossible" values.

Convert byte slice to io.Reader

To get a type that implements io.Reader from a []byte slice, you can use bytes.NewReader in the bytes package:

r := bytes.NewReader(byteData)

This will return a value of type bytes.Reader which implements the io.Reader (and io.ReadSeeker) interface.

Don't worry about them not being the same "type". io.Reader is an interface and can be implemented by many different types. To learn a little bit more about interfaces in Go, read Effective Go: Interfaces and Types.

Indent starting from the second line of a paragraph with CSS

Is it literally just the second line you want to indent, or is it from the second line (ie. a hanging indent)?

If it is the latter, something along the lines of this JSFiddle would be appropriate.

_x000D_
_x000D_
    div {_x000D_
        padding-left: 1.5em;_x000D_
        text-indent:-1.5em;_x000D_
    }_x000D_
    _x000D_
    span {_x000D_
        padding-left: 1.5em;_x000D_
        text-indent:-1.5em;_x000D_
    }
_x000D_
<div>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</div>_x000D_
_x000D_
<span>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</span>
_x000D_
_x000D_
_x000D_

This example shows how using the same CSS syntax in a DIV or SPAN produce different effects.

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

I dug deeper into this and found the best solutions are here.

http://blog.notdot.net/2010/07/Getting-unicode-right-in-Python

In my case I solved "UnicodeEncodeError: 'charmap' codec can't encode character "

original code:

print("Process lines, file_name command_line %s\n"% command_line))

New code:

print("Process lines, file_name command_line %s\n"% command_line.encode('utf-8'))  

Java FileOutputStream Create File if not exists

Before creating a file, it's needed to create all the parent's directories.

Use yourFile.getParentFile().mkdirs()

SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified

The answer is in the error message itself:

Error Locating Server/Instance Specified

Basically, you've got the wrong server\instance in the connection string, i.e. this bit:

Data Source=MSSQL2008-1

is wrong and not pointing to the server, or the servername doesn't resolve to an IP address. Two other posibilities: (1) the SQL Browser Service on the box running SQL Server isn't running or (2) Windows Firewall (or some other firewall) on the SQL box is denying incoming connections.

Ultimately, if the servername is correct, then it turns into a networking problem, and you need to find out why the client cannot connect to the server (and this will be more likely to be a basic networking problem than a SQL Server configuration problem).

What is PHPSESSID?

PHPSESSID reveals you are using PHP. If you don't want this you can easily change the name using the session.name in your php.ini file or using the session_name() function.

Why XML-Serializable class need a parameterless constructor

First of all, this what is written in documentation. I think it is one of your class fields, not the main one - and how you want deserialiser to construct it back w/o parameterless construction ?

I think there is a workaround to make constructor private.

Add characters to a string in Javascript

You can also keep adding strings to an existing string like so:

var myString = "Hello ";
myString += "World";
myString += "!";

the result would be -> Hello World!

Resize on div element

// this is a Jquery plugin function that fires an event when the size of an element is changed
// usage: $().sizeChanged(function(){})

(function ($) {

$.fn.sizeChanged = function (handleFunction) {
    var element = this;
    var lastWidth = element.width();
    var lastHeight = element.height();

    setInterval(function () {
        if (lastWidth === element.width()&&lastHeight === element.height())
            return;
        if (typeof (handleFunction) == 'function') {
            handleFunction({ width: lastWidth, height: lastHeight },
                           { width: element.width(), height: element.height() });
            lastWidth = element.width();
            lastHeight = element.height();
        }
    }, 100);


    return element;
};

}(jQuery));

How to link a folder with an existing Heroku app

Use heroku's fork

  1. Use the new "heroku fork" command! It will copy all the environment and you have to update the github repo after!

    heroku fork -a sourceapp targetapp
    
  2. Clone it local

    git clone [email protected]:youamazingapp.git
    
  3. Make a new repo on github and add it

    git remote add origin https://github.com/yourname/your_repo.git
    
  4. Push on github

    git push origin master
    

How do I reset the setInterval timer?

If by "restart", you mean to start a new 4 second interval at this moment, then you must stop and restart the timer.

function myFn() {console.log('idle');}

var myTimer = setInterval(myFn, 4000);

// Then, later at some future time, 
// to restart a new 4 second interval starting at this exact moment in time
clearInterval(myTimer);
myTimer = setInterval(myFn, 4000);

You could also use a little timer object that offers a reset feature:

function Timer(fn, t) {
    var timerObj = setInterval(fn, t);

    this.stop = function() {
        if (timerObj) {
            clearInterval(timerObj);
            timerObj = null;
        }
        return this;
    }

    // start timer using current settings (if it's not already running)
    this.start = function() {
        if (!timerObj) {
            this.stop();
            timerObj = setInterval(fn, t);
        }
        return this;
    }

    // start with new or original interval, stop current interval
    this.reset = function(newT = t) {
        t = newT;
        return this.stop().start();
    }
}

Usage:

var timer = new Timer(function() {
    // your function here
}, 5000);


// switch interval to 10 seconds
timer.reset(10000);

// stop the timer
timer.stop();

// start the timer
timer.start();

Working demo: https://jsfiddle.net/jfriend00/t17vz506/

Can two Java methods have same name with different return types?

According the JLS, you cannot however due to a feature/bug in the Java 6/7 compiler (Oracle's JDK, OpenJDK, IBM's JDK) you can have different return types for the same method signature if you use generics.

public class Main {
    public static void main(String... args) {
        Main.<Integer>print();
        Main.<Short>print();
        Main.<Byte>print();
        Main.<Void>print();
    }

    public static <T extends Integer> int print() {
        System.out.println("here - Integer");
        return 0;
    }
    public static <T extends Short> short print() {
        System.out.println("here - Short");
        return 0;
    }
    public static <T extends Byte> byte print() {
        System.out.println("here - Byte");
        return 0;
    }
    public static <T extends Void> void print() {
        System.out.println("here - Void");
    }
}

Prints

here - Integer
here - Short
here - Byte
here - Void

For more details, read my article here

How to convert UTF-8 byte[] to string?

To my knowledge none of the given answers guarantee correct behavior with null termination. Until someone shows me differently I wrote my own static class for handling this with the following methods:

// Mimics the functionality of strlen() in c/c++
// Needed because niether StringBuilder or Encoding.*.GetString() handle \0 well
static int StringLength(byte[] buffer, int startIndex = 0)
{
    int strlen = 0;
    while
    (
        (startIndex + strlen + 1) < buffer.Length // Make sure incrementing won't break any bounds
        && buffer[startIndex + strlen] != 0       // The typical null terimation check
    )
    {
        ++strlen;
    }
    return strlen;
}

// This is messy, but I haven't found a built-in way in c# that guarentees null termination
public static string ParseBytes(byte[] buffer, out int strlen, int startIndex = 0)
{
    strlen = StringLength(buffer, startIndex);
    byte[] c_str = new byte[strlen];
    Array.Copy(buffer, startIndex, c_str, 0, strlen);
    return Encoding.UTF8.GetString(c_str);
}

The reason for the startIndex was in the example I was working on specifically I needed to parse a byte[] as an array of null terminated strings. It can be safely ignored in the simple case

Error to run Android Studio

The problem is a bug on Fedora 20. The bug is very odd: if I have Google Talk plugin installed then Eclipse crashes (https://bugs.eclipse.org/bugs/show_bug.cgi?id=334466). It's crazy for me. I thought that was Java version and with Java 6 my eclipse was still crashing. To solve this I should use gnome/GTK instead KDE. Now it works "well" (in gnome environment). Thanks for all answers.

How to set an iframe src attribute from a variable in AngularJS

I suspect looking at the excerpt that the function trustSrc from trustSrc(currentProject.url) is not defined in the controller.

You need to inject the $sce service in the controller and trustAsResourceUrl the url there.

In the controller:

function AppCtrl($scope, $sce) {
    // ...
    $scope.setProject = function (id) {
      $scope.currentProject = $scope.projects[id];
      $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
    }
}

In the Template:

<iframe ng-src="{{currentProjectUrl}}"> <!--content--> </iframe>

Maven: mvn command not found

If you are on windows, what i suppose you need to do set the PATH like this:

SET PATH=%M2%

furthermore i assume you need to set your path to something like C:...\apache-maven-3.0.3\ cause this is the default folder for the windows archive. On the other i assume you need to add the path of maven to your and not set it to only maven so you setting should look like this:

SET PATH=%PATH%;%M2%

JAVA_HOME directory in Linux

Just another solution, this one's cross platform (uses java), and points you to the location of the jre.

java -XshowSettings:properties -version 2>&1 > /dev/null | grep 'java.home'

Outputs all of java's current settings, and finds the one called java.home.

For windows, you can go with findstr instead of grep.

java -XshowSettings:properties -version 2>&1 | findstr "java.home"

javascript: calculate x% of a number

Best thing is to memorize balance equation in natural way.

Amount / Whole = Percentage / 100

usually You have one variable missing, in this case it is Amount

Amount / 10000 = 35.8 / 100

then you have high school math (proportion) to multiple outer from both sides and inner from both sides.

Amount * 100 = 358 000

Amount = 3580

It works the same in all languages and on paper. JavaScript is no exception.

The transaction manager has disabled its support for remote/network transactions

In my scenario, the exception was being thrown because I was trying to create a new connection instance within a TransactionScope on an already existing connection:

Example:

void someFunction()
{
    using (var db = new DBContext(GetConnectionString()))
    {
        using (var transaction = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted }))
        {
            someOtherFunction(); // This function opens a new connection within this transaction, causing the exception.
        }
    }
}

void someOtherFunction()
{
    using (var db = new DBContext(GetConnectionString()))
    {
        db.Whatever // <- Exception.
    }
}

How to put a text beside the image?

make the image float: left; and the text float: right;

Take a look at this fiddle I used a picture online but you can just swap it out for your picture.

WPF chart controls

You can get the Silverlight Chart Controls running on WPF, they're quite nice (and free).

getting the ng-object selected with ng-change

This might give you some ideas

.NET C# View Model

public class DepartmentViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

.NET C# Web Api Controller

public class DepartmentController : BaseApiController
{
    [HttpGet]
    public HttpResponseMessage Get()
    {
        var sms = Ctx.Departments;

        var vms = new List<DepartmentViewModel>();

        foreach (var sm in sms)
        {
            var vm = new DepartmentViewModel()
            {
                Id = sm.Id,
                Name = sm.DepartmentName
            };
            vms.Add(vm);
        }

        return Request.CreateResponse(HttpStatusCode.OK, vms);
    }

}

Angular Controller:

$http.get('/api/department').then(
    function (response) {
        $scope.departments = response.data;
    },
    function (response) {
        toaster.pop('error', "Error", "An unexpected error occurred.");
    }
);

$http.get('/api/getTravelerInformation', { params: { id: $routeParams.userKey } }).then(
   function (response) {
       $scope.request = response.data;
       $scope.travelerDepartment = underscoreService.findWhere($scope.departments, { Id: $scope.request.TravelerDepartmentId });
   },
    function (response) {
        toaster.pop('error', "Error", "An unexpected error occurred.");
    }
);

Angular Template:

<div class="form-group">
    <label>Department</label>
    <div class="left-inner-addon">
        <i class="glyphicon glyphicon-hand-up"></i>
        <select ng-model="travelerDepartment"
                ng-options="department.Name for department in departments track by department.Id"
                ng-init="request.TravelerDepartmentId = travelerDepartment.Id"
                ng-change="request.TravelerDepartmentId = travelerDepartment.Id"
                class="form-control">
            <option value=""></option>
        </select>
    </div>
</div>

Conversion between UTF-8 ArrayBuffer and String

Using TextEncoder and TextDecoder

var uint8array = new TextEncoder("utf-8").encode("Plain Text");
var string = new TextDecoder().decode(uint8array);
console.log(uint8array ,string )

where is gacutil.exe?

gacutil comes with Visual Studio, not with VSTS. It is part of Windows SDK and can be download separately at http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF&displaylang=en . This installation will have gacutil.exe included. But first check it here

C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin

you might have it installed.

As @devi mentioned

If you decide to grab gacutil files from existing installation, note that from .NET 4.0 is three files: gacutil.exe gacutil.exe.config and 1033/gacutlrc.dll

How to hide a <option> in a <select> menu with CSS?

The toggleOption function is not perfect and introduced nasty bugs in my application. jQuery will get confused with .val() and .arraySerialize() Try to select options 4 and 5 to see what I mean:

<select id="t">
<option value="v1">options 1</option>
<option value="v2">options 2</option>
<option value="v3" id="o3">options 3</option>
<option value="v4">options 4</option>
<option value="v5">options 5</option>
</select>
<script>
jQuery.fn.toggleOption = function( show ) {
    jQuery( this ).toggle( show );
    if( show ) {
        if( jQuery( this ).parent( 'span.toggleOption' ).length )
            jQuery( this ).unwrap( );
    } else {
        jQuery( this ).wrap( '<span class="toggleOption" style="display: none;" />' );
    }
};

$("#o3").toggleOption(false); 
$("#t").change(function(e) {
    if($(this).val() != this.value) {
    console.log("Error values not equal", this.value, $(this).val());
    }
});
</script>

Extract XML Value in bash script

As Charles Duffey has stated, XML parsers are best parsed with a proper XML parsing tools. For one time job the following should work.

grep -oPm1 "(?<=<title>)[^<]+"

Test:

$ echo "$data"
<item> 
  <title>15:54:57 - George:</title>
  <description>Diane DeConn? You saw Diane DeConn!</description> 
</item> 
<item> 
  <title>15:55:17 - Jerry:</title> 
  <description>Something huh?</description>
$ title=$(grep -oPm1 "(?<=<title>)[^<]+" <<< "$data")
$ echo "$title"
15:54:57 - George:

How do I add to the Windows PATH variable using setx? Having weird problems

I was having such trouble managing my computer labs when the %PATH% environment variable approached 1024 characters that I wrote a Powershell script to fix it.

You can download the code here: https://gallery.technet.microsoft.com/scriptcenter/Edit-and-shorten-PATH-37ef3189

You can also use it as a simple way to safely add, remove and parse PATH entries. Enjoy.

Spring 3.0: Unable to locate Spring NamespaceHandler for XML schema namespace

In case someone else runs into this problem, I just did using Eclipse; running the project via the right click action. This error occurred in the J2EE view, but did NOT occur in the Java view. Not sure - assuming something with adding libraries to the correct 'lib' directory.

I am also using a Maven project, allowing m2eclipse to manage dependancies.

Prevent double curly brace notation from displaying momentarily before angular.js compiles/interpolates document

I think that you are looking for the ngCloak directive: https://docs.angularjs.org/api/ng/directive/ngCloak

From the documentation:

The ngCloak directive is used to prevent the Angular html template from being briefly displayed by the browser in its raw (uncompiled) form while your application is loading. Use this directive to avoid the undesirable flicker effect caused by the html template display.

The directive can be applied to the <body> element, but the preferred usage is to apply multiple ngCloak directives to small portions of the page to permit progressive rendering of the browser view

Use table name in MySQL SELECT "AS"

To declare a string literal as an output column, leave the Table off and just use Test. It doesn't need to be associated with a table among your joins, since it will be accessed only by its column alias. When using a metadata function like getColumnMeta(), the table name will be an empty string because it isn't associated with a table.

SELECT
  `field1`, 
  `field2`, 
  'Test' AS `field3` 
FROM `Test`;

Note: I'm using single quotes above. MySQL is usually configured to honor double quotes for strings, but single quotes are more widely portable among RDBMS.

If you must have a table alias name with the literal value, you need to wrap it in a subquery with the same name as the table you want to use:

SELECT
  field1,
  field2,
  field3
FROM 
  /* subquery wraps all fields to put the literal inside a table */
  (SELECT field1, field2, 'Test' AS field3 FROM Test) AS Test

Now field3 will come in the output as Test.field3.

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

Change HH to hh as

long timeInMillis = System.currentTimeMillis();
Calendar cal1 = Calendar.getInstance();
cal1.setTimeInMillis(timeInMillis);
SimpleDateFormat dateFormat = new SimpleDateFormat(
                                "dd/MM/yyyy hh:mm:ss a");
dateforrow = dateFormat.format(cal1.getTime());

Note that dd/mm/yyyy - will give you minutes instead of the month.

Calculate difference between two datetimes in MySQL

If your start and end datetimes are on different days use TIMEDIFF.

SELECT TIMEDIFF(datetime1,datetime2)

if datetime1 > datetime2 then

SELECT TIMEDIFF("2019-02-20 23:46:00","2019-02-19 23:45:00")

gives: 24:01:00

and datetime1 < datetime2

SELECT TIMEDIFF("2019-02-19 23:45:00","2019-02-20 23:46:00")

gives: -24:01:00

Capturing browser logs with Selenium WebDriver using Java

Starting with Firefox 65 an about:config flag exists now so console API calls like console.log() land in the output stream and thus the log file (see (https://github.com/mozilla/geckodriver/issues/284#issuecomment-458305621).

profile = new FirefoxProfile();
profile.setPreference("devtools.console.stdout.content", true);

PhoneGap Eclipse Issue - eglCodecCommon glUtilsParamSize: unknow param errors

For those who like to work close to the metal, here is a command that will clear out the unwanted soot, without needing any special tools or scripts:

adb logcat "eglCodecCommon:S"

How do I drop a function if it already exists?

IF EXISTS (
    SELECT * FROM sysobjects WHERE id = object_id(N'function_name') 
    AND xtype IN (N'FN', N'IF', N'TF')
)
    DROP FUNCTION function_name
GO

If you want to avoid the sys* tables, you could instead do (from here in example A):

IF object_id(N'function_name', N'FN') IS NOT NULL
    DROP FUNCTION function_name
GO

The main thing to catch is what type of function you are trying to delete (denoted in the top sql by FN, IF and TF):

  • FN = Scalar Function
  • IF = Inlined Table Function
  • TF = Table Function

AndroidStudio: Failed to sync Install build tools

One of the answers ask you to use buildToolsVersion 23.0.0, but you would get buildToolsVersion 23.0.0 has serious bugs use buildToolsVersion 23.0.3. I did that then I started getting message buildToolsVersion 23.0.3 is too low from project app update to buildToolsVersion 25.0.0 and sync again. So I did that and it worked , So here are the final changes.

Inside app's build.gradle change this

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0 rc2"
}

with this one

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0"
}

Update or Insert (multiple rows and columns) from subquery in PostgreSQL

OMG Ponies's answer works perfectly, but just in case you need something more complex, here is an example of a slightly more advanced update query:

UPDATE table1 
SET col1 = subquery.col2,
    col2 = subquery.col3 
FROM (
    SELECT t2.foo as col1, t3.bar as col2, t3.foobar as col3 
    FROM table2 t2 INNER JOIN table3 t3 ON t2.id = t3.t2_id
    WHERE t2.created_at > '2016-01-01'
) AS subquery
WHERE table1.id = subquery.col1;

SET versus SELECT when assigning variables?

Quote, which summarizes from this article:

  1. SET is the ANSI standard for variable assignment, SELECT is not.
  2. SET can only assign one variable at a time, SELECT can make multiple assignments at once.
  3. If assigning from a query, SET can only assign a scalar value. If the query returns multiple values/rows then SET will raise an error. SELECT will assign one of the values to the variable and hide the fact that multiple values were returned (so you'd likely never know why something was going wrong elsewhere - have fun troubleshooting that one)
  4. When assigning from a query if there is no value returned then SET will assign NULL, where SELECT will not make the assignment at all (so the variable will not be changed from its previous value)
  5. As far as speed differences - there are no direct differences between SET and SELECT. However SELECT's ability to make multiple assignments in one shot does give it a slight speed advantage over SET.

How do I 'git diff' on a certain directory?

To use Beyond Compare as the difftool for directory diff, remember enable follow symbolic links like so:

In a Folder Compare ViewRules (Referee Icon):

Enter image description here

And then, enable follow symbolic links and update session defaults:

Enter image description here


OR,

set up the alias like so:

git config --global alias.diffdir "difftool --dir-diff --tool=bc3 --no-prompt --no-symlinks"

Note that in either case, any edits made to the side (left or right) that refers to the current working tree are preserved.

Bash or KornShell (ksh)?

Bash is the standard for Linux.
My experience is that it is easier to find help for bash than for ksh or csh.

How to properly apply a lambda function into a pandas data frame column

You need to add else in your lambda function. Because you are telling what to do in case your condition(here x < 90) is met, but you are not telling what to do in case the condition is not met.

sample['PR'] = sample['PR'].apply(lambda x: 'NaN' if x < 90 else x) 

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

What about this?

java.sql.Timestamp timestamp = java.sql.Timestamp.valueOf("2007-09-23 10:10:10.0");

Change icons of checked and unchecked for Checkbox for Android

Kind of a mix:

Set it in your layout file :-

 <CheckBox android:layout_width="wrap_content"
           android:layout_height="wrap_content" 
           android:text="new checkbox"
           android:background="@drawable/checkbox_background" 
           android:button="@drawable/checkbox" />

where the @drawable/checkbox will look like:

<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:state_checked="true" android:state_focused="true"
  android:drawable="@drawable/checkbox_on_background_focus_yellow" />
 <item android:state_checked="false" android:state_focused="true"
  android:drawable="@drawable/checkbox_off_background_focus_yellow" />
 <item android:state_checked="false"
  android:drawable="@drawable/checkbox_off_background" />
 <item android:state_checked="true"
  android:drawable="@drawable/checkbox_on_background" />
</selector>

How to un-commit last un-pushed git commit without losing the changes

With me mostly it happens when I push changes to the wrong branch and realize later. And following works in most of the time.

git revert commit-hash
git push

git checkout my-other-branch
git revert revert-commit-hash
git push
  1. revert the commit
  2. (create and) checkout other branch
  3. revert the revert

Error parsing yaml file: mapping values are not allowed here

My issue was a missing set of quotes;

Foo: bar 'baz'

should be

Foo: "bar 'baz'"

Get difference between two dates in months using Java

You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.

Sample snippet for time-diff:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

ORA-06508: PL/SQL: could not find program unit being called

I recompiled the package specification, even though the change was only in the package body. This resolved my issue