Programs & Examples On #Google earth

Google's virtual globe application that allows users to view 3D buildings, imagery, terrain, any other information stored in KML files.

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

I solved this issue for myself, I found there's was two files of http-client with different version of other dependent jar files. So there may version were collapsing between libraries files so remove all old/previous libraries files and re-add are jar files from lib folder of this zip file:

Donwload Zip file from here

How to add anchor tags dynamically to a div in Javascript?

<script type="text/javascript" language="javascript">
function createDiv()
{
  var divTag = document.createElement("div");            
  divTag.innerHTML = "Div tag created using Javascript DOM dynamically";        
  document.body.appendChild(divTag);
}
</script>

How to make <input type="file"/> accept only these types?

As stated on w3schools:

audio/* - All sound files are accepted

video/* - All video files are accepted

image/* - All image files are accepted

MIME_type - A valid MIME type, with no parameters. Look at IANA MIME types for a complete list of standard MIME types

text-align: right on <select> or <option>

You could try using the "dir" attribute, but I'm not sure that would produce the desired effect?

<select dir="rtl">
    <option>Foo</option>    
    <option>bar</option>
    <option>to the right</option>
</select>

Demo here: http://jsfiddle.net/fparent/YSJU7/

Change default global installation directory for node.js modules in Windows?

Using a Windows symbolic link from the C:\Users{username}\AppData\Roaming\npm and C:\Users{username}\AppData\Roaming\npm-cache paths to the destination worked great for me.

How to add a symbolic link

enter image description here

error: expected declaration or statement at end of input in c

Normally that error occurs when a } was missed somewhere in the code, for example:

void mi_start_curr_serv(void){
    #if 0
    //stmt
    #endif

would fail with this error due to the missing } at the end of the function. The code you posted doesn't have this error, so it is likely coming from some other part of your source.

Put search icon near textbox using bootstrap

You can do it in pure CSS using the :after pseudo-element and getting creative with the margins.

Here's an example, using Font Awesome for the search icon:

_x000D_
_x000D_
.search-box-container input {_x000D_
  padding: 5px 20px 5px 5px;_x000D_
}_x000D_
_x000D_
.search-box-container:after {_x000D_
    content: "\f002";_x000D_
    font-family: FontAwesome;_x000D_
    margin-left: -25px;_x000D_
    margin-right: 25px;_x000D_
}
_x000D_
<!-- font awesome -->_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<div class="search-box-container">_x000D_
  <input type="text" placeholder="Search..."  />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Inherit CSS class

You could also use the !important feature of css to make qualities you do not want to override in the original class. I am using this on my site to keep some of the essential characteristics of the original class while overriding others:

<div class="foo bar">
.foo {
color: blue;
width: 200px  !important;
}

.bar {
color: red;
width: 400px;
}

This will generate a class "foo bar" element that is red and 200px. This is great if you are using the other two classes individually and just want a piece from each class.

Change Select List Option background colour on hover in html

No, it's not possible.

It's really, if not use native selects, if you create custom select widget from html elements, t.e. "li".

How can I generate random alphanumeric strings?

After reviewing the other answers and considering CodeInChaos' comments, along with CodeInChaos still biased (although less) answer, I thought a final ultimate cut and paste solution was needed. So while updating my answer I decided to go all out.

For an up to date version of this code, please visit the new Hg repository on Bitbucket: https://bitbucket.org/merarischroeder/secureswiftrandom. I recommend you copy and paste the code from: https://bitbucket.org/merarischroeder/secureswiftrandom/src/6c14b874f34a3f6576b0213379ecdf0ffc7496ea/Code/Alivate.SolidSwiftRandom/SolidSwiftRandom.cs?at=default&fileviewer=file-view-default (make sure you click the Raw button to make it easier to copy and make sure you have the latest version, I think this link goes to a specific version of the code, not the latest).

Updated notes:

  1. Relating to some other answers - If you know the length of the output, you don't need a StringBuilder, and when using ToCharArray, this creates and fills the array (you don't need to create an empty array first)
  2. Relating to some other answers - You should use NextBytes, rather than getting one at a time for performance
  3. Technically you could pin the byte array for faster access.. it's usually worth it when your iterating more than 6-8 times over a byte array. (Not done here)
  4. Use of RNGCryptoServiceProvider for best randomness
  5. Use of caching of a 1MB buffer of random data - benchmarking shows cached single bytes access speed is ~1000x faster - taking 9ms over 1MB vs 989ms for uncached.
  6. Optimised rejection of bias zone within my new class.

End solution to question:

static char[] charSet =  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();
static int byteSize = 256; //Labelling convenience
static int biasZone = byteSize - (byteSize % charSet.Length);
public string GenerateRandomString(int Length) //Configurable output string length
{
    byte[] rBytes = new byte[Length]; //Do as much before and after lock as possible
    char[] rName = new char[Length];
    SecureFastRandom.GetNextBytesMax(rBytes, biasZone);
    for (var i = 0; i < Length; i++)
    {
        rName[i] = charSet[rBytes[i] % charSet.Length];
    }
    return new string(rName);
}

But you need my new (untested) class:

/// <summary>
/// My benchmarking showed that for RNGCryptoServiceProvider:
/// 1. There is negligable benefit of sharing RNGCryptoServiceProvider object reference 
/// 2. Initial GetBytes takes 2ms, and an initial read of 1MB takes 3ms (starting to rise, but still negligable)
/// 2. Cached is ~1000x faster for single byte at a time - taking 9ms over 1MB vs 989ms for uncached
/// </summary>
class SecureFastRandom
{
    static byte[] byteCache = new byte[1000000]; //My benchmark showed that an initial read takes 2ms, and an initial read of this size takes 3ms (starting to raise)
    static int lastPosition = 0;
    static int remaining = 0;

    /// <summary>
    /// Static direct uncached access to the RNGCryptoServiceProvider GetBytes function
    /// </summary>
    /// <param name="buffer"></param>
    public static void DirectGetBytes(byte[] buffer)
    {
        using (var r = new RNGCryptoServiceProvider())
        {
            r.GetBytes(buffer);
        }
    }

    /// <summary>
    /// Main expected method to be called by user. Underlying random data is cached from RNGCryptoServiceProvider for best performance
    /// </summary>
    /// <param name="buffer"></param>
    public static void GetBytes(byte[] buffer)
    {
        if (buffer.Length > byteCache.Length)
        {
            DirectGetBytes(buffer);
            return;
        }

        lock (byteCache)
        {
            if (buffer.Length > remaining)
            {
                DirectGetBytes(byteCache);
                lastPosition = 0;
                remaining = byteCache.Length;
            }

            Buffer.BlockCopy(byteCache, lastPosition, buffer, 0, buffer.Length);
            lastPosition += buffer.Length;
            remaining -= buffer.Length;
        }
    }

    /// <summary>
    /// Return a single byte from the cache of random data.
    /// </summary>
    /// <returns></returns>
    public static byte GetByte()
    {
        lock (byteCache)
        {
            return UnsafeGetByte();
        }
    }

    /// <summary>
    /// Shared with public GetByte and GetBytesWithMax, and not locked to reduce lock/unlocking in loops. Must be called within lock of byteCache.
    /// </summary>
    /// <returns></returns>
    static byte UnsafeGetByte()
    {
        if (1 > remaining)
        {
            DirectGetBytes(byteCache);
            lastPosition = 0;
            remaining = byteCache.Length;
        }

        lastPosition++;
        remaining--;
        return byteCache[lastPosition - 1];
    }

    /// <summary>
    /// Rejects bytes which are equal to or greater than max. This is useful for ensuring there is no bias when you are modulating with a non power of 2 number.
    /// </summary>
    /// <param name="buffer"></param>
    /// <param name="max"></param>
    public static void GetBytesWithMax(byte[] buffer, byte max)
    {
        if (buffer.Length > byteCache.Length / 2) //No point caching for larger sizes
        {
            DirectGetBytes(buffer);

            lock (byteCache)
            {
                UnsafeCheckBytesMax(buffer, max);
            }
        }
        else
        {
            lock (byteCache)
            {
                if (buffer.Length > remaining) //Recache if not enough remaining, discarding remaining - too much work to join two blocks
                    DirectGetBytes(byteCache);

                Buffer.BlockCopy(byteCache, lastPosition, buffer, 0, buffer.Length);
                lastPosition += buffer.Length;
                remaining -= buffer.Length;

                UnsafeCheckBytesMax(buffer, max);
            }
        }
    }

    /// <summary>
    /// Checks buffer for bytes equal and above max. Must be called within lock of byteCache.
    /// </summary>
    /// <param name="buffer"></param>
    /// <param name="max"></param>
    static void UnsafeCheckBytesMax(byte[] buffer, byte max)
    {
        for (int i = 0; i < buffer.Length; i++)
        {
            while (buffer[i] >= max)
                buffer[i] = UnsafeGetByte(); //Replace all bytes which are equal or above max
        }
    }
}

For history - my older solution for this answer, used Random object:

    private static char[] charSet =
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();

    static rGen = new Random(); //Must share, because the clock seed only has Ticks (~10ms) resolution, yet lock has only 20-50ns delay.
    static int byteSize = 256; //Labelling convenience
    static int biasZone = byteSize - (byteSize % charSet.Length);
    static bool SlightlyMoreSecurityNeeded = true; //Configuration - needs to be true, if more security is desired and if charSet.Length is not divisible by 2^X.
    public string GenerateRandomString(int Length) //Configurable output string length
    {
      byte[] rBytes = new byte[Length]; //Do as much before and after lock as possible
      char[] rName = new char[Length];
      lock (rGen) //~20-50ns
      {
          rGen.NextBytes(rBytes);

          for (int i = 0; i < Length; i++)
          {
              while (SlightlyMoreSecurityNeeded && rBytes[i] >= biasZone) //Secure against 1/5 increased bias of index[0-7] values against others. Note: Must exclude where it == biasZone (that is >=), otherwise there's still a bias on index 0.
                  rBytes[i] = rGen.NextByte();
              rName[i] = charSet[rBytes[i] % charSet.Length];
          }
      }
      return new string(rName);
    }

Performance:

  1. SecureFastRandom - First single run = ~9-33ms. Imperceptible. Ongoing: 5ms (sometimes it goes up to 13ms) over 10,000 iterations, With a single average iteration= 1.5 microseconds.. Note: Requires generally 2, but occasionally up to 8 cache refreshes - depends on how many single bytes exceed the bias zone
  2. Random - First single run = ~0-1ms. Imperceptible. Ongoing: 5ms over 10,000 iterations. With a single average iteration= .5 microseconds.. About the same speed.

Also check out:

These links are another approach. Buffering could be added to this new code base, but most important was exploring different approaches to removing bias, and benchmarking the speeds and pros/cons.

Auto-redirect to another HTML page

Its a late answer, but as I can see most of the people mentioned about "refresh" method to redirect a webpage. As per W3C, we should not use "refresh" to redirect. Because it could break the "back" button. Imagine that the user presses the "back" button, the refresh would work again, and the user would bounce forward. The user will most likely get very annoyed, and close the window, which is probably not what you, as the author of this page, want.

Use HTTP redirects instead. One can refer the complete documentation here: W3C document

Why does git say "Pull is not possible because you have unmerged files"?

There was same issue with me
In my case, steps are as below-

  1. Removed all file which was being start with U (unmerged) symbol. as-

U   project/app/pages/file1/file.ts
U   project/www/assets/file1/file-name.html
  1. Pull code from master

$ git pull origin master
  1. Checked for status

 $ git status

Here is the message which It appeared-
and have 2 and 1 different commit each, respectively.
(use "git pull" to merge the remote branch into yours)
You have unmerged paths.
(fix conflicts and run "git commit")

Unmerged paths:
(use "git add ..." to mark resolution)

both modified:   project/app/pages/file1/file.ts
both modified:   project/www/assets/file1/file-name.html
  1. Added all new changes -

    $ git add project/app/pages/file1/file.ts
project/www/assets/file1/file-name.html
  1. Commit changes on head-

$ git commit -am "resolved conflict of the app."
  1. Pushed the code -

$ git push origin master

Which turn may issue resolved with this image - enter image description here

What is the simplest method of inter-process communication between 2 C# processes?

necromancing

it's just way more easy to make a shared file if possible!

//out
File.AppendAllText("sharedFile.txt", "payload text here");
// in
File.ReadAllText("sharedFile.txt");

Configuring angularjs with eclipse IDE

  1. Make sure the project is extracted on your hard disk.
  2. In Eclipse go to the menu: File->New->Project.
  3. Select "General->Project" and click on the next button.
  4. Enter the project name in the "Project name:" field
  5. Disable "Use default location" Click on the "Browse ..." button and select the folder that contains the project (the one from step 1)
  6. Click on the "Finish" button
  7. Right-click with the mouse on you're new project and click "Configure->Convert to AngularJS Project.."
  8. Enable you're project goodies and click on the "OK" button.

Upgrading Node.js to latest version

Windows 10

Open CMD in folder C:\Program Files\nodejs\node_modules and type npm i npm

Creating a comma separated list from IList<string> or IEnumerable<string>

Something a bit fugly, but it works:

string divisionsCSV = String.Join(",", ((List<IDivisionView>)divisions).ConvertAll<string>(d => d.DivisionID.ToString("b")).ToArray());

Gives you a CSV from a List after you give it the convertor (in this case d => d.DivisionID.ToString("b")).

Hacky but works - could be made into an extension method perhaps?

How to convert a number to string and vice versa in C++

How to convert a number to a string in C++03

  1. Do not use the itoa or itof functions because they are non-standard and therefore not portable.
  2. Use string streams

     #include <sstream>  //include this to use string streams
     #include <string> 
    
    int main()
    {    
        int number = 1234;
    
        std::ostringstream ostr; //output string stream
        ostr << number; //use the string stream just like cout,
        //except the stream prints not to stdout but to a string.
    
        std::string theNumberString = ostr.str(); //the str() function of the stream 
        //returns the string.
    
        //now  theNumberString is "1234"  
    }
    

    Note that you can use string streams also to convert floating-point numbers to string, and also to format the string as you wish, just like with cout

    std::ostringstream ostr;
    float f = 1.2;
    int i = 3;
    ostr << f << " + " i << " = " << f + i;   
    std::string s = ostr.str();
    //now s is "1.2 + 3 = 4.2" 
    

    You can use stream manipulators, such as std::endl, std::hex and functions std::setw(), std::setprecision() etc. with string streams in exactly the same manner as with cout

    Do not confuse std::ostringstream with std::ostrstream. The latter is deprecated

  3. Use boost lexical cast. If you are not familiar with boost, it is a good idea to start with a small library like this lexical_cast. To download and install boost and its documentation go here. Although boost isn't in C++ standard many libraries of boost get standardized eventually and boost is widely considered of the best C++ libraries.

    Lexical cast uses streams underneath, so basically this option is the same as the previous one, just less verbose.

    #include <boost/lexical_cast.hpp>
    #include <string>
    
    int main()
    {
       float f = 1.2;
       int i = 42;
       std::string sf = boost::lexical_cast<std::string>(f); //sf is "1.2"
       std::string si = boost::lexical_cast<std::string>(i); //sf is "42"
    }
    

How to convert a string to a number in C++03

  1. The most lightweight option, inherited from C, is the functions atoi (for integers (alphabetical to integer)) and atof (for floating-point values (alphabetical to float)). These functions take a C-style string as an argument (const char *) and therefore their usage may be considered a not exactly good C++ practice. cplusplus.com has easy-to-understand documentation on both atoi and atof including how they behave in case of bad input. However the link contains an error in that according to the standard if the input number is too large to fit in the target type, the behavior is undefined.

    #include <cstdlib> //the standard C library header
    #include <string>
    int main()
    {
        std::string si = "12";
        std::string sf = "1.2";
        int i = atoi(si.c_str()); //the c_str() function "converts" 
        double f = atof(sf.c_str()); //std::string to const char*
    }
    
  2. Use string streams (this time input string stream, istringstream). Again, istringstream is used just like cin. Again, do not confuse istringstream with istrstream. The latter is deprecated.

    #include <sstream>
    #include <string>
    int main()
    {
       std::string inputString = "1234 12.3 44";
       std::istringstream istr(inputString);
       int i1, i2;
       float f;
       istr >> i1 >> f >> i2;
       //i1 is 1234, f is 12.3, i2 is 44  
    }
    
  3. Use boost lexical cast.

    #include <boost/lexical_cast.hpp>
    #include <string>
    
    int main()
    {
       std::string sf = "42.2"; 
       std::string si = "42";
       float f = boost::lexical_cast<float>(sf); //f is 42.2
       int i = boost::lexical_cast<int>(si);  //i is 42
    }       
    

    In case of a bad input, lexical_cast throws an exception of type boost::bad_lexical_cast

Play audio with Python

Your best bet is probably to use pygame/SDL. It's an external library, but it has great support across platforms.

pygame.mixer.init()
pygame.mixer.music.load("file.mp3")
pygame.mixer.music.play()

You can find more specific documentation about the audio mixer support in the pygame.mixer.music documentation

How to create python bytes object from long hex string?

You can do this with the hex codec. ie:

>>> s='000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44'
>>> s.decode('hex')
'\x00\x00\x00\x00\x00\x00HB@\xfa\x06=\xe5\xd0\xb7D\xad\xbe\xd6:\x81\xfa\xea9\x00\x00\xc8B\x86@\xa4=P\x05\xbdD'

Current Subversion revision command

There is also a more convenient (for some) svnversion command.

Output might be a single revision number or something like this (from -h):

  4123:4168     mixed revision working copy
  4168M         modified working copy
  4123S         switched working copy
  4123:4168MS   mixed revision, modified, switched working copy

I use this python code snippet to extract revision information:

import re
import subprocess

p = subprocess.Popen(["svnversion"], stdout = subprocess.PIPE, 
    stderr = subprocess.PIPE)
p.wait()
m = re.match(r'(|\d+M?S?):?(\d+)(M?)S?', p.stdout.read())
rev = int(m.group(2))
if m.group(3) == 'M':
    rev += 1

How can I change the color of AlertDialog title and the color of the line under it

If your using custom title layout then you can use it like alertDialog.setCustomTitle(customTitle);

Example

On UI thread use dialog like:

 LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
 View customTitle = inflater.inflate(R.layout.customtitlebar, null);
 AlertDialog.Builder d = new AlertDialog.Builder(this);
 d.setCustomTitle(customTitle);
 d.setMessage("Message");
 d.setNeutralButton("OK", null);
 d.show();

customtitlebar.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="#525f67">

    <ImageView
        android:id="@+id/icon"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/ic_launcher"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true" >
    </ImageView>

    <TextView
        android:id="@+id/customtitlebar"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:textColor="#ffffff"
        android:text="Title Name"
        android:padding="3px"
        android:textStyle="bold" 
        android:layout_toRightOf="@id/icon"
        android:layout_alignParentTop="true"
        android:gravity="center_vertical"/>

     <ImageView
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:background="#ff0000" 
        android:layout_below="@id/icon"><!-- This is line below the title -->
    </ImageView>

</RelativeLayout>

How to ping an IP address

It will work for sure

import java.io.*;
import java.util.*;

public class JavaPingExampleProgram
{

  public static void main(String args[]) 
  throws IOException
  {
    // create the ping command as a list of strings
    JavaPingExampleProgram ping = new JavaPingExampleProgram();
    List<String> commands = new ArrayList<String>();
    commands.add("ping");
    commands.add("-c");
    commands.add("5");
    commands.add("74.125.236.73");
    ping.doCommand(commands);
  }

  public void doCommand(List<String> command) 
  throws IOException
  {
    String s = null;

    ProcessBuilder pb = new ProcessBuilder(command);
    Process process = pb.start();

    BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));

    // read the output from the command
    System.out.println("Here is the standard output of the command:\n");
    while ((s = stdInput.readLine()) != null)
    {
      System.out.println(s);
    }

    // read any errors from the attempted command
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null)
    {
      System.out.println(s);
    }
  }

}

Sequelize OR condition object

Seems there is another format now

where: {
    LastName: "Doe",
    $or: [
        {
            FirstName: 
            {
                $eq: "John"
            }
        }, 
        {
            FirstName: 
            {
                $eq: "Jane"
            }
        }, 
        {
            Age: 
            {
                $gt: 18
            }
        }
    ]
}

Will generate

WHERE LastName='Doe' AND (FirstName = 'John' OR FirstName = 'Jane' OR Age > 18)

See the doc: http://docs.sequelizejs.com/en/latest/docs/querying/#where

Difference between Inheritance and Composition

Inheritence means reusing the complete functionality of a class, Here my class have to use all the methods of the super class and my class will be titely coupled with the super class and code will be duplicated in both the classes in case of inheritence.

But we can overcome from all these problem when we use composition to talk with another class . composition is declaring an attribute of another class into my class to which we want to talk. and what functionality we want from that class we can get by using that attribute.

How to find out whether a file is at its `eof`?

You can compare the returned value of fp.tell() before and after calling the read method. If they return the same value, fp is at eof.

Furthermore, I don't think your example code actually works. The read method to my knowledge never returns None, but it does return an empty string on eof.

Get only the date in timestamp in mysql

You can convert that time in Unix timestamp by using

select UNIX_TIMESTAMP('2013-11-26 01:24:34')

then convert it in the readable format in whatever format you need

select from_unixtime(UNIX_TIMESTAMP('2013-11-26 01:24:34'),"%Y-%m-%d");

For in detail you can visit link

Combine hover and click functions (jQuery)?

You can use .bind() or .live() whichever is appropriate, but no need to name the function:

$('#target').bind('click hover', function () {
 // common operation
});

or if you were doing this on lots of element (not much sense for an IE unless the element changes):

$('#target').live('click hover', function () {
 // common operation
});

Note, this will only bind the first hover argument, the mouseover event, it won't hook anything to the mouseleave event.

Access props inside quotes in React JSX

If you want to use the es6 template literals, you need braces around the tick marks as well:

<img className="image" src={`images/${this.props.image}`} />

How do I create a comma-separated list using a SQL query?

To be agnostic, drop back and punt.

Select a.name as a_name, r.name as r_name
  from ApplicationsResource ar, Applications a, Resources r
 where a.id = ar.app_id
   and r.id = ar.resource_id
 order by r.name, a.name;

Now user your server programming language to concatenate a_names while r_name is the same as the last time.

Definition of "downstream" and "upstream"

In terms of source control, you're "downstream" when you copy (clone, checkout, etc) from a repository. Information flowed "downstream" to you.

When you make changes, you usually want to send them back "upstream" so they make it into that repository so that everyone pulling from the same source is working with all the same changes. This is mostly a social issue of how everyone can coordinate their work rather than a technical requirement of source control. You want to get your changes into the main project so you're not tracking divergent lines of development.

Sometimes you'll read about package or release managers (the people, not the tool) talking about submitting changes to "upstream". That usually means they had to adjust the original sources so they could create a package for their system. They don't want to keep making those changes, so if they send them "upstream" to the original source, they shouldn't have to deal with the same issue in the next release.

Groovy write to file (newline)

As @Steven points out, a better way would be:

public void writeToFile(def directory, def fileName, def extension, def infoList) {
  new File("$directory/$fileName$extension").withWriter { out ->
    infoList.each {
      out.println it
    }
  }
}

As this handles the line separator for you, and handles closing the writer as well

(and doesn't open and close the file each time you write a line, which could be slow in your original version)

Error 'tunneling socket' while executing npm install

Following commands may solve your issue:

npm config set proxy false
npm cache clean

It solved my same issue.

VBA array sort function?

Dim arr As Object
Dim InputArray

'Creating a array list
Set arr = CreateObject("System.Collections.ArrayList")

'String
InputArray = Array("d", "c", "b", "a", "f", "e", "g")

'number
'InputArray = Array(6, 5, 3, 4, 2, 1)

' adding the elements in the array to array_list
For Each element In InputArray
    arr.Add element
Next

'sorting happens
arr.Sort

'Converting ArrayList to an array
'so now a sorted array of elements is stored in the array sorted_array.

sorted_array = arr.toarray

Remove all unused resources from an android project

Since ADT 16 you can use Android Lint. It is really amazing tool.

Android Lint is a new tool for ADT 16 (and Tools 16) which scans Android project sources for potential bugs.

Here are some examples of the types of errors that it looks for:

  • Missing translations (and unused translations)
  • Layout performance problems (all the issues the old layoutopt tool used to find, and more)
  • Unused resources
  • Inconsistent array sizes (when arrays are defined in multiple configurations)
  • Accessibility and internationalization problems (hardcoded strings, missing contentDescription, etc)
  • Icon problems (like missing densities, duplicate icons, wrong sizes, etc)
  • Usability problems (like not specifying an input type on a text field)
  • Manifest errors and many more.

However, it has some issues (don't know if they're already fixed) and if you want to delete hundreds of supposedly unused resources I'd recommend to manually compile project several times during resource removing to be sure that Lint didn't remove something needed.

How to add pandas data to an existing csv file?

You can append to a csv by opening the file in append mode:

with open('my_csv.csv', 'a') as f:
    df.to_csv(f, header=False)

If this was your csv, foo.csv:

,A,B,C
0,1,2,3
1,4,5,6

If you read that and then append, for example, df + 6:

In [1]: df = pd.read_csv('foo.csv', index_col=0)

In [2]: df
Out[2]:
   A  B  C
0  1  2  3
1  4  5  6

In [3]: df + 6
Out[3]:
    A   B   C
0   7   8   9
1  10  11  12

In [4]: with open('foo.csv', 'a') as f:
             (df + 6).to_csv(f, header=False)

foo.csv becomes:

,A,B,C
0,1,2,3
1,4,5,6
0,7,8,9
1,10,11,12

How to secure RESTful web services?

HTTP Basic + HTTPS is one common method.

Real escape string and PDO

Use prepared statements. Those keep the data and syntax apart, which removes the need for escaping MySQL data. See e.g. this tutorial.

Configuration System Failed to Initialize

If you've added your own custom configuration sections to your App.Config, make sure you have defined the section in the <configSections> element. I added the my config XML but forgot to declare the configuration section up top - which caused the exception "Configuration system failed to initialize" for me.

How to add a list item to an existing unordered list?

jQuery comes with the following options which could fulfil your need in this case:

append is used to add an element at the end of the parent div specified in the selector:

$('ul.tabs').append('<li>An element</li>');

prepend is used to add an element at the top/start of the parent div specified in the selector:

$('ul.tabs').prepend('<li>An element</li>');

insertAfter lets you insert an element of your selection next after an element you specify. Your created element will then be put in the DOM after the specified selector closing tag:

$('<li>An element</li>').insertAfter('ul.tabs>li:last');
will result in:
<li><a href="/user/edit"><span class="tab">Edit</span></a></li>
<li>An element</li>

insertBefore will do the opposite of the above:

$('<li>An element</li>').insertBefore('ul.tabs>li:last');
will result in:
<li>An element</li>
<li><a href="/user/edit"><span class="tab">Edit</span></a></li>

Have a reloadData for a UITableView animate when changing

All of these answers assume that you are using a UITableView with only 1 section.

To accurately handle situations where you have more than 1 section use:

NSRange range = NSMakeRange(0, myTableView.numberOfSections);
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
[myTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];

(Note: you should make sure that you have more than 0 sections!)

Another thing to note is that you may run into a NSInternalInconsistencyException if you attempt to simultaneously update your data source with this code. If this is the case, you can use logic similar to this:

int sectionNumber = 0; //Note that your section may be different

int nextIndex = [currentItems count]; //starting index of newly added items

[myTableView beginUpdates];

for (NSObject *item in itemsToAdd) {
    //Add the item to the data source
    [currentItems addObject:item];

    //Add the item to the table view
    NSIndexPath *path = [NSIndexPath indexPathForRow:nextIndex++ inSection:sectionNumber];
    [myTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:path] withRowAnimation:UITableViewRowAnimationAutomatic];
}

[myTableView endUpdates];

Windows git "warning: LF will be replaced by CRLF", is that warning tail backward?

All of this assumes core.autocrlf=true

Original error:

warning: LF will be replaced by CRLF
The file will have its original line endings in your working directory.

What the error SHOULD read:

warning: LF will be replaced by CRLF in your working directory
The file will have its original LF line endings in the git repository

Explanation here:

The side-effect of this convenient conversion, and this is what the warning you're seeing is about, is that if a text file you authored originally had LF endings instead of CRLF, it will be stored with LF as usual, but when checked out later it will have CRLF endings. For normal text files this is usually just fine. The warning is a "for your information" in this case, but in case git incorrectly assesses a binary file to be a text file, it is an important warning because git would then be corrupting your binary file.

Basically, a local file that was previously LF will now have CRLF locally

LabelEncoder: TypeError: '>' not supported between instances of 'float' and 'str'

This is due to the series df[cat] containing elements that have varying data types e.g.(strings and/or floats). This could be due to the way the data is read, i.e. numbers are read as float and text as strings or the datatype was float and changed after the fillna operation.

In other words

pandas data type 'Object' indicates mixed types rather than str type

so using the following line:

df[cat] = le.fit_transform(df[cat].astype(str))


should help

"An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page..."

First, set customErrors = "Off" in the web.config and redeploy to get a more detailed error message that will help us diagnose the problem. You could also RDP into the instance and browse to the site from IIS locally to view the errors.

<system.web>
      <customErrors mode="Off" />

First guess though - you have some references (most likely Azure SDK references) that are not set to Copy Local = true. So, all your dependencies are not getting deployed.

Get to the detailed error first and update your question.

UPDATE: A second option now available in VS2013 is Remote Debugging a Cloud Service or Virtual Machine.

How to use jQuery in chrome extension?

Its very easy just do the following:

add the following line in your manifest.json

"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'",

Now you are free to load jQuery directly from url

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

Source: google doc

No Such Element Exception?

Looks like your file.next() line in the while loop is throwing the NoSuchElementException since the scanner reached the end of file. Read the next() java API here

Also you should not call next() in the loop and also in the while condition. In the while condition you should check if next token is available and inside the while loop check if its equal to treasure.

Get list of certificates from the certificate store in C#

Try this:

//using System.Security.Cryptography.X509Certificates;
public static X509Certificate2 selectCert(StoreName store, StoreLocation location, string windowTitle, string windowMsg)
{

    X509Certificate2 certSelected = null;
    X509Store x509Store = new X509Store(store, location);
    x509Store.Open(OpenFlags.ReadOnly);

    X509Certificate2Collection col = x509Store.Certificates;
    X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, windowTitle, windowMsg, X509SelectionFlag.SingleSelection);

    if (sel.Count > 0)
    {
        X509Certificate2Enumerator en = sel.GetEnumerator();
        en.MoveNext();
        certSelected = en.Current;
    }

    x509Store.Close();

    return certSelected;
}

window.onunload is not working properly in Chrome browser. Can any one help me?

I know this is old but I found the way to make unload work using Chrome

window.onbeforeunload = function () {
  myFunction();
};

How to switch between frames in Selenium WebDriver using Java

There is also possibility to use WebDriverWait with ExpectedConditions (to make sure that Frame will be available).

  1. With string as parameter

    (new WebDriverWait(driver, 5)).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("frame-name"));
    
  2. With locator as a parameter

    (new WebDriverWait(driver, 5)).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id("frame-id")));
    

More info can be found here

AFNetworking Post Request

For AFNetworking 3.0 and Swift. Maybe we can use like this:

let configutation = NSURLSessionConfiguration.defaultSessionConfiguration()
manager = AFHTTPSessionManager(sessionConfiguration: configutation)

let urlString = "url"
manager.POST(urlString, parameters: [params here], progress: nil, success: { (dataTask: NSURLSessionDataTask, response: AnyObject?) -> Void in
        print(dataTask)
        print(response)
        }) { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
        print(error)
}

Hope this will help other find answer like me!

Update query using Subquery in Sql Server

The title of this thread asks how a subquery can be used in an update. Here's an example of that:

update [dbName].[dbo].[MyTable] 
set MyColumn = 1 
where 
    (
        select count(*) 
        from [dbName].[dbo].[MyTable] mt2 
        where
            mt2.ID > [dbName].[dbo].[MyTable].ID
            and mt2.Category = [dbName].[dbo].[MyTable].Category
    ) > 0

Python: SyntaxError: keyword can't be an expression

sum.up is not a valid keyword argument name. Keyword arguments must be valid identifiers. You should look in the documentation of the library you are using how this argument really is called – maybe sum_up?

How to give the background-image path in CSS?

You need to get 2 folders back from your css file.

Try:

background-image: url("../../images/image.png");

Can I set up HTML/Email Templates with ASP.NET?

Here is one more alternative that uses XSL transformations for more complex email templates: Sending HTML-based email from .NET applications.

Are there any style options for the HTML5 Date picker?

You can use the following CSS to style the input element.

_x000D_
_x000D_
input[type="date"] {_x000D_
  background-color: red;_x000D_
  outline: none;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-clear-button {_x000D_
  font-size: 18px;_x000D_
  height: 30px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-inner-spin-button {_x000D_
  height: 28px;_x000D_
}_x000D_
_x000D_
input[type="date"]::-webkit-calendar-picker-indicator {_x000D_
  font-size: 15px;_x000D_
}
_x000D_
<input type="date" value="From" name="from" placeholder="From" required="" />
_x000D_
_x000D_
_x000D_

SSIS cannot convert because a potential loss of data

I had the same issue, multiple data type values in single column, package load only numeric values. Remains all it updated as null.

Solution

To fix this changing the excel data type is one of the solution. In Excel Copy the column data and paste in different file. Delete that column and insert new column as Text datatype and paste that copied data in new column.

Now in ssis package delete and recreate the Excel source and destination table change the column data type as varchar.

This will work.

How to get the anchor from the URL using jQuery?

You can use the .indexOf() and .substring(), like this:

var url = "www.aaa.com/task1/1.3.html#a_1";
var hash = url.substring(url.indexOf("#")+1);

You can give it a try here, if it may not have a # in it, do an if(url.indexOf("#") != -1) check like this:

var url = "www.aaa.com/task1/1.3.html#a_1", idx = url.indexOf("#");
var hash = idx != -1 ? url.substring(idx+1) : "";

If this is the current page URL, you can just use window.location.hash to get it, and replace the # if you wish.

Javascript: Setting location.href versus location

A couple of years ago, location did not work for me in IE and location.href did (and both worked in other browsers). Since then I have always just used location.href and never had trouble again. I can't remember which version of IE that was.

codeigniter model error: Undefined property

It solved throung second parameter in Model load:

$this->load->model('user','User');

first parameter is the model's filename, and second it defining the name of model to be used in the controller:

function alluser() 
{
$this->load->model('User');
$result = $this->User->showusers();
}

ComboBox: Adding Text and Value to an Item (no Binding Source)

You can use anonymous class like this:

comboBox.DisplayMember = "Text";
comboBox.ValueMember = "Value";

comboBox.Items.Add(new { Text = "report A", Value = "reportA" });
comboBox.Items.Add(new { Text = "report B", Value = "reportB" });
comboBox.Items.Add(new { Text = "report C", Value = "reportC" });
comboBox.Items.Add(new { Text = "report D", Value = "reportD" });
comboBox.Items.Add(new { Text = "report E", Value = "reportE" });

UPDATE: Although above code will properly display in combo box, you will not be able to use SelectedValue or SelectedText properties of ComboBox. To be able to use those, bind combo box as below:

comboBox.DisplayMember = "Text";
comboBox.ValueMember = "Value";

var items = new[] { 
    new { Text = "report A", Value = "reportA" }, 
    new { Text = "report B", Value = "reportB" }, 
    new { Text = "report C", Value = "reportC" },
    new { Text = "report D", Value = "reportD" },
    new { Text = "report E", Value = "reportE" }
};

comboBox.DataSource = items;

Excel 2013 horizontal secondary axis

You should follow the guidelines on Add a secondary horizontal axis:

Add a secondary horizontal axis

To complete this procedure, you must have a chart that displays a secondary vertical axis. To add a secondary vertical axis, see Add a secondary vertical axis.

  1. Click a chart that displays a secondary vertical axis. This displays the Chart Tools, adding the Design, Layout, and Format tabs.

  2. On the Layout tab, in the Axes group, click Axes.

    enter image description here

  3. Click Secondary Horizontal Axis, and then click the display option that you want.

enter image description here


Add a secondary vertical axis

You can plot data on a secondary vertical axis one data series at a time. To plot more than one data series on the secondary vertical axis, repeat this procedure for each data series that you want to display on the secondary vertical axis.

  1. In a chart, click the data series that you want to plot on a secondary vertical axis, or do the following to select the data series from a list of chart elements:

    • Click the chart.

      This displays the Chart Tools, adding the Design, Layout, and Format tabs.

    • On the Format tab, in the Current Selection group, click the arrow in the Chart Elements box, and then click the data series that you want to plot along a secondary vertical axis.

      enter image description here

  2. On the Format tab, in the Current Selection group, click Format Selection. The Format Data Series dialog box is displayed.

    Note: If a different dialog box is displayed, repeat step 1 and make sure that you select a data series in the chart.

  3. On the Series Options tab, under Plot Series On, click Secondary Axis and then click Close.

    A secondary vertical axis is displayed in the chart.

  4. To change the display of the secondary vertical axis, do the following:

    • On the Layout tab, in the Axes group, click Axes.

    • Click Secondary Vertical Axis, and then click the display option that you want.

  5. To change the axis options of the secondary vertical axis, do the following:

    • Right-click the secondary vertical axis, and then click Format Axis.

    • Under Axis Options, select the options that you want to use.

Regular Expression to match valid dates

Perl 6 version

rx{
  ^

  $<month> = (\d ** 1..2)
  { $<month> <= 12 or fail }

  '/'

  $<day> = (\d ** 1..2)
  {
    given( +$<month> ){
      when 1|3|5|7|8|10|12 {
        $<day> <= 31 or fail
      }
      when 4|6|9|11 {
        $<day> <= 30 or fail
      }
      when 2 {
        $<day> <= 29 or fail
      }
      default { fail }
    }
  }

  '/'

  $<year> = (\d ** 4)

  $
}

After you use this to check the input the values are available in $/ or individually as $<month>, $<day>, $<year>. ( those are just syntax for accessing values in $/ )

No attempt has been made to check the year, or that it doesn't match the 29th of Feburary on non leap years.

Javascript Object push() function

    tempData.push( data[index] );

I agree with the correct answer above, but.... your still not giving the index value for the data that you want to add to tempData. Without the [index] value the whole array will be added.

What does $@ mean in a shell script?

$@ is nearly the same as $*, both meaning "all command line arguments". They are often used to simply pass all arguments to another program (thus forming a wrapper around that other program).

The difference between the two syntaxes shows up when you have an argument with spaces in it (e.g.) and put $@ in double quotes:

wrappedProgram "$@"
# ^^^ this is correct and will hand over all arguments in the way
#     we received them, i. e. as several arguments, each of them
#     containing all the spaces and other uglinesses they have.
wrappedProgram "$*"
# ^^^ this will hand over exactly one argument, containing all
#     original arguments, separated by single spaces.
wrappedProgram $*
# ^^^ this will join all arguments by single spaces as well and
#     will then split the string as the shell does on the command
#     line, thus it will split an argument containing spaces into
#     several arguments.

Example: Calling

wrapper "one two    three" four five "six seven"

will result in:

"$@": wrappedProgram "one two    three" four five "six seven"
"$*": wrappedProgram "one two    three four five six seven"
                             ^^^^ These spaces are part of the first
                                  argument and are not changed.
$*:   wrappedProgram one two three four five six seven

Need to make a clickable <div> button

There are two solutions posted on that page. The one with lower votes I would recommend if possible.

If you are using HTML5 then it is perfectly valid to put a div inside of a. As long as the div doesn't also contain some other specific elements like other link tags.

<a href="Music.html">
  <div id="music" class="nav">
    Music I Like
  </div>
</a>

The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index at all from that example.

div { position: relative; }
.hyperspan {
    position:absolute;
    width:100%;
    height:100%;
    left:0;
    top:0;
}

<div id="music" class="nav">Music I Like 
    <a href="http://www.google.com"> 
        <span class="hyperspan"></span>
    </a>   
</div>

http://jsfiddle.net/rBKXM/9

When you give absolute positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative to the parent div you tell the span to only be as big as that.

Moment JS - check if a date is today or in the future

You can use the isSame function:

var iscurrentDate = startTime.isSame(new Date(), "day");
if(iscurrentDate) {

}

Zsh: Conda/Pip installs command not found

Simply copy your Anaconda bin directory and paste it at the bottom of ~/.zshrc.

For me the path is /home/theorangeguy/miniconda3/bin, so I ran:

echo ". /home/theorangeguy/miniconda3/bin" >> ~/.zshrc

This edited the ~/.zshrc. Now do:

source ~/.zshrc

It worked like a charm.

How to downgrade the installed version of 'pip' on windows?

pip itself is just a normal python package. Thus you can install pip with pip.

Of cource, you don't want to affect the system's pip, install it inside a virtualenv.

pip install pip==1.2.1

How to get Selected Text from select2 when using <input>

This one is working fine using V 4.0.3

var vv = $('.mySelect2');     
var label = $(vv).children("option[value='"+$(vv).select2("val")+"']").first().html();
console.log(label); 

JavaScript equivalent of PHP's in_array()

If you are going to use it in a class, and if you prefer it to be functional (and work in all browsers):

inArray: function(needle, haystack)
{
    var result = false;

    for (var i in haystack) {
        if (haystack[i] === needle) {
            result = true;
            break;
        }
    }

    return result;
}

Hope it helps someone :-)

How to filter by string in JSONPath?

The browser testing tools while convenient can be a bit deceiving. Consider:

{
  "resourceType": "Encounter",
  "id": "EMR56788",
  "text": {
    "status": "generated",
    "div": "Patient admitted with chest pains</div>"
  },
  "status": "in-progress",
  "class": "inpatient",
  "patient": {
    "reference": "Patient/P12345",
    "display": "Roy Batty"
  }
}

Most tools returned this as false:

$[?(@.class==inpatient)]

But when I executed against

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>1.2.0</version>
</dependency>

It returned true. I recommend writing a simple unit test to verify rather than rely on the browser testing tools.

Can't drop table: A foreign key constraint fails

This should do the trick:

SET FOREIGN_KEY_CHECKS=0; DROP TABLE bericht; SET FOREIGN_KEY_CHECKS=1;

As others point out, this is almost never what you want, even though it's whats asked in the question. A more safe solution is to delete the tables depending on bericht before deleting bericht. See CloudyMarble answer on how to do that. I use bash and the method in my post to drop all tables in a database when I don't want to or can't delete and recreate the database itself.

The #1217 error happens when other tables has foreign key constraints to the table you are trying to delete and you are using the InnoDB database engine. This solution temporarily disables checking the restraints and then re-enables them. Read the documentation for more. Be sure to delete foreign key restraints and fields in tables depending on bericht, otherwise you might leave your database in a broken state.

BASH Syntax error near unexpected token 'done'

Had similar problems just now and these are two separate instances and solutions that worked for me:

Case 1. Basically, had a space after the last command within my newline-separated for-loop, eg. (imagining that | here represents the carat in a text editor showing where you are writing), this is what I saw when clicking around the end of the line of the last command in the loop:

for f in $pathToFiles
do
   $stuff |
done

Notice the space before before the carat (so far as I know, this is something cat has no option do display visually (one way you could test is with something like od -bc yourscript.sh)). Changing the code to

for f in $pathToFiles
do
   $stuff| <--- notice the carat shows no ending space before the newline
done

fixed the problem.

Case 2. Was using a pseudo try-catch block for the for-loop (see https://stackoverflow.com/a/22010339/8236733) like

{
for f in $pathToFiles
do
   { $stuff } || { echo "Failed to complete stuff"; exit 255; }
done
} || { echo "Failed to complete loop"; exit 255; }

and apparently bash did not like the nested {}s. Changing to

{
for f in $pathToFiles
do
   $stuff
done
} || { echo "Failed to complete loop"; exit 255; }

fixed the problem in this case. If anyone can further explain either of these cases, please let me know more about them in the comments.

HTML/Javascript change div content

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <input type="radio" name="radiobutton" value="A" onclick = "populateData(event)">
  <input type="radio" name="radiobutton" value="B" onclick = "populateData(event)">

    <div id="content"></div>
</body>
</html>

-----------------JS- code------------

var targetDiv = document.getElementById('content');
    var htmlContent = '';

    function populateData(event){
      switch(event.target.value){
        case 'A':{
         htmlContent = 'Content for A';
          break;
        }
        case 'B':{
          htmlContent = "content for B";
break;
        }
      }
      targetDiv.innerHTML = htmlContent;
    }

Step1: on click of the radio button it calls function populate data, with event (an object that has event details such as name of the element, value etc..);

Step2: I extracted the value through event.target.value and then simple switch will give me freedom to add custom text.

Live Code

https://jsbin.com/poreway/edit?html,js,output

Apache gives me 403 Access Forbidden when DocumentRoot points to two different drives

For Apache 2.4.2: I was getting 403: Forbidden continuously when I was trying to access WAMP on my Windows 7 desktop from my iPhone on WiFi. On one blog, I found the solution - add Require all granted after Allow all in the <Directory> section. So this is how my <Directory> section looks like inside <VirtualHost>

<Directory "C:/wamp/www">
    Options Indexes FollowSymLinks MultiViews Includes ExecCGI
    AllowOverride All
    Order Allow,Deny
    Allow from all
    Require all granted
</Directory>

CSS to stop text wrapping under image

Since this question is gaining lots of views and this was the accepted answer, I felt the need to add the following disclaimer:

This answer was specific to the OP's question (Which had the width set in the examples). While it works, it requires you to have a width on each of the elements, the image and the paragraph. Unless that is your requirement, I recommend using Joe Conlin's solution which is posted as another answer on this question.

The span element is an inline element, you can't change its width in CSS.

You can add the following CSS to your span so you will be able to change its width.

display: block;

Another way, which usually makes more sense, is to use a <p> element as a parent for your <span>.

<li id="CN2787">
  <img class="fav_star" src="images/fav.png">
  <p>
     <span>Text, text and more text</span>
  </p>
</li>

Since <p> is a block element, you can set its width using CSS, without having to change anything.

But in both cases, since you have a block element now, you will need to float the image so that your text doesn't all go below your image.

li p{width: 100px; margin-left: 20px}
.fav_star {width: 20px;float:left}

P.S. Instead of float:left on the image, you can also put float:right on li p but in that case, you will also need text-align:left to realign the text correctly.

P.S.S. If you went ahead with the first solution of not adding a <p> element, your CSS should look like so:

li span{width: 100px; margin-left: 20px;display:block}
.fav_star {width: 20px;float:left}

Reading Space separated input in python

For python 3 use this

inp = list(map(int,input().split()))
#input => java is a programming language
#return as => ("java","is","a","programming","language")

input() accepts a string from STDIN.

split() splits the string about whitespace character and returns a list of strings.

map() passes each element of the 2nd argument to the first argument and returns a map object

Finally list() converts the map to a list

How to validate an Email in PHP?

You can use the filter_var() function, which gives you a lot of handy validation and sanitization options.

filter_var($email, FILTER_VALIDATE_EMAIL)

If you don't want to change your code that relied on your function, just do:

function isValidEmail($email){ 
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

Note: For other uses (where you need Regex), the deprecated ereg function family (POSIX Regex Functions) should be replaced by the preg family (PCRE Regex Functions). There are a small amount of differences, reading the Manual should suffice.

Update 1: As pointed out by @binaryLV:

PHP 5.3.3 and 5.2.14 had a bug related to FILTER_VALIDATE_EMAIL, which resulted in segfault when validating large values. Simple and safe workaround for this is using strlen() before filter_var(). I'm not sure about 5.3.4 final, but it is written that some 5.3.4-snapshot versions also were affected.

This bug has already been fixed.

Update 2: This method will of course validate bazmega@kapa as a valid email address, because in fact it is a valid email address. But most of the time on the Internet, you also want the email address to have a TLD: [email protected]. As suggested in this blog post (link posted by @Istiaque Ahmed), you can augment filter_var() with a regex that will check for the existence of a dot in the domain part (will not check for a valid TLD though):

function isValidEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) 
        && preg_match('/@.+\./', $email);
}

As @Eliseo Ocampos pointed out, this problem only exists before PHP 5.3, in that version they changed the regex and now it does this check, so you do not have to.

Scroll to a specific Element Using html

<!-- HTML -->
<a href="#google"></a>
<div id="google"></div>

/*CSS*/
html { scroll-behavior: smooth; } 

Additionally, you can add html { scroll-behavior: smooth; } to your CSS to create a smooth scroll.

Make footer stick to bottom of page using Twitter Bootstrap

Here is an example using css3:

CSS:

html, body {
    height: 100%;
    margin: 0;
}
#wrap {
    padding: 10px;
    min-height: -webkit-calc(100% - 100px);     /* Chrome */
    min-height: -moz-calc(100% - 100px);     /* Firefox */
    min-height: calc(100% - 100px);     /* native */
}
.footer {
    position: relative;
    clear:both;
}

HTML:

<div id="wrap">
    <div class="container clear-top">
       body content....
    </div>
</div>
<footer class="footer">
    footer content....
</footer>

fiddle

Android: alternate layout xml for landscape mode

The layouts in /res/layout are applied to both portrait and landscape, unless you specify otherwise. Let’s assume we have /res/layout/home.xml for our homepage and we want it to look differently in the 2 layout types.

  1. create folder /res/layout-land (here you will keep your landscape adjusted layouts)
  2. copy home.xml there
  3. make necessary changes to it

Source

Directory index forbidden by Options directive

The Problem

Indexes visible in a web browser for directories that do not contain an index.html or index.php file.

I had a lot of trouble with the configuration on Scientific Linux's httpd web server to stop showing these indexes.

The Configuration that did not work

httpd.conf virtual host directory directives:

<Directory /home/mydomain.com/htdocs>
    Options FollowSymLinks
    AllowOverride all
    Require all granted
</Directory>

and the addition of the following line to .htaccess:

Options -Indexes

Directory indexes were still showing up. .htaccess settings weren't working!

How could that be, other settings in .htaccess were working, so why not this one? What's going? It should be working! %#$&^$%@# !!

The Fix

Change httpd.conf's Options line to:

Options +FollowSymLinks

and restart the webserver.

From Apache's core mod page: ( https://httpd.apache.org/docs/2.4/mod/core.html#options )

Mixing Options with a + or - with those without is not valid syntax and will be rejected during server startup by the syntax check with an abort.

Voilà directory indexes were no longer showing up for directories that did not contain an index.html or index.php file.

Now What! A New Wrinkle

New entries started to show up in the 'error_log' when such a directory access was attempted:

[Fri Aug 19 02:57:39.922872 2016] [autoindex:error] [pid 12479] [client aaa.bbb.ccc.ddd:xxxxx] AH01276: Cannot serve directory /home/mydomain.com/htdocs/dir-without-index-file/: No matching DirectoryIndex (index.html,index.php) found, and server-generated directory index forbidden by Options directive

This entry is from the Apache module 'autoindex' with a LogLevel of 'error' as indicated by [autoindex:error] of the error message---the format is [module_name:loglevel].

To stop these new entries from being logged, the LogLevel needs to be changed to a higher level (e.g. 'crit') to log fewer---only more serious error messages.

Apache 2.4 LogLevels

See Apache 2.4's core directives for LogLevel.

emerg, alert, crit, error, warn, notice, info, debug, trace1, trace2, trace3, tracr4, trace5, trace6, trace7, trace8

Each level deeper into the list logs all the messages of any previous level(s).

Apache 2.4's default level is 'warn'. Therefore, all messages classified as emerg, alert, crit, error, and warn are written to error_log.

Additional Fix to Stop New error_log Entries

Added the following line inside the <Directory>..</Directory> section of httpd.conf:

LogLevel crit

The Solution 1

My virtual host's httpd.conf <Directory>..</Directory> configuration:

<Directory /home/mydomain.com/htdocs>
    Options +FollowSymLinks
    AllowOverride all
    Require all granted
    LogLevel crit
</Directory>

and adding to /home/mydomain.com/htdocs/.htaccess, the root directory of your website's .htaccess file:

Options -Indexes

If you don't mind the 'error' level messages, omit

LogLevel crit

Scientific Linux - Solution 2 - Disables mod_autoindex

No more autoindex'ing of directories inside your web space. No changes to .htaccess. But, need access to the httpd configuration files in /etc/httpd

  1. Edit /etc/httpd/conf.modules.d/00-base.conf and comment the line:

    LoadModule autoindex_module modules/mod_autoindex.so
    

    by adding a # in front of it then save the file.

  2. In the directory /etc/httpd/conf.d rename (mv)

    sudo mv autoindex.conf autoindex.conf.<something_else>
    
  3. Restart httpd:

    sudo httpd -k restart
    

    or

    sudo apachectl restart
    

The autoindex_mod is now disabled.

Linux distros with ap2dismod/ap2enmod Commands

Disable autoindex module enter the command

    sudo a2dismod autoindex

to enable autoindex module enter

    sudo a2enmod autoindex

Undefined reference to 'vtable for xxx'

it suggests that you fail to link the explicitly instantiated basetype public gameCore (whereas the header file forward declares it).

Since we know nothing about your build config/library dependencies, we can't really tell which link flags/source files are missing, but I hope the hint alone helps you fix ti.

What is the best way to call a script from another script?

This is an example with subprocess library:

import subprocess

python_version = '3'
path_to_run = './'
py_name = '__main__.py'

# args = [f"python{python_version}", f"{path_to_run}{py_name}"]  # Avaible in python3
args = ["python{}".format(python_version), "{}{}".format(path_to_run, py_name)]

res = subprocess.Popen(args, stdout=subprocess.PIPE)
output, error_ = res.communicate()

if not error_:
    print(output)
else:
    print(error_)

What is the equivalent of Java's final in C#?

It depends on the context.

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

This happens when you are trying to run application on emulator. Emulator does not have shared google maps library.

inherit from two classes in C#

Make two interfaces IA and IB:

public interface IA
{
    public void methodA(int value);
}

public interface IB
{
    public void methodB(int value);
}

Next make A implement IA and B implement IB.

public class A : IA
{
    public int fooA { get; set; }
    public void methodA(int value) { fooA = value; }
}

public class B : IB
{
    public int fooB { get; set; }
    public void methodB(int value) { fooB = value; }
}

Then implement your C class as follows:

public class C : IA, IB
{
    private A _a;
    private B _b;

    public C(A _a, B _b)
    {
        this._a = _a;
        this._b = _b;
    }

    public void methodA(int value) { _a.methodA(value); }
    public void methodB(int value) { _b.methodB(value); }
}

Generally this is a poor design overall because you can have both A and B implement a method with the same name and variable types such as foo(int bar) and you will need to decide how to implement it, or if you just call foo(bar) on both _a and _b. As suggested elsewhere you should consider a .A and .B properties instead of combining the two classes.

How to get the index of an item in a list in a single step?

  1. Simple solution to find index for any string value in the List.

Here is code for List Of String:

int indexOfValue = myList.FindIndex(a => a.Contains("insert value from list"));
  1. Simple solution to find index for any Integer value in the List.

Here is Code for List Of Integer:

    int indexOfNumber = myList.IndexOf(/*insert number from list*/);

Unit testing click event in Angular

Events can be tested using the async/fakeAsync functions provided by '@angular/core/testing', since any event in the browser is asynchronous and pushed to the event loop/queue.

Below is a very basic example to test the click event using fakeAsync.

The fakeAsync function enables a linear coding style by running the test body in a special fakeAsync test zone.

Here I am testing a method that is invoked by the click event.

it('should', fakeAsync( () => {
    fixture.detectChanges();
    spyOn(componentInstance, 'method name'); //method attached to the click.
    let btn = fixture.debugElement.query(By.css('button'));
    btn.triggerEventHandler('click', null);
    tick(); // simulates the passage of time until all pending asynchronous activities finish
    fixture.detectChanges();
    expect(componentInstance.methodName).toHaveBeenCalled();
}));

Below is what Angular docs have to say:

The principle advantage of fakeAsync over async is that the test appears to be synchronous. There is no then(...) to disrupt the visible flow of control. The promise-returning fixture.whenStable is gone, replaced by tick()

There are limitations. For example, you cannot make an XHR call from within a fakeAsync

How to find which columns contain any NaN value in Pandas dataframe

i use these three lines of code to print out the column names which contain at least one null value:

for column in dataframe:
    if dataframe[column].isnull().any():
       print('{0} has {1} null values'.format(column, dataframe[column].isnull().sum()))

How to update Ruby Version 2.0.0 to the latest version in Mac OSX Yosemite?

I recommend rbenv* https://github.com/rbenv/rbenv

* If this meets your criteria: https://github.com/rbenv/rbenv/wiki/Why-rbenv?:

rbenv does…

  • Provide support for specifying application-specific Ruby versions.
  • Let you change the global Ruby version on a per-user basis.
  • Allow you to override the Ruby version with an environment variable.

In contrast with RVM, rbenv does not…

  • Need to be loaded into your shell. Instead, rbenv's shim approach works by adding a directory to your $PATH.
  • Override shell commands like cd or require prompt hacks. That's dangerous and error-prone.
  • Have a configuration file. There's nothing to configure except which version of Ruby you want to use.
  • Install Ruby. You can build and install Ruby yourself, or use ruby-build to automate the process.
  • Manage gemsets. Bundler is a better way to manage application dependencies. If you have projects that are not yet using Bundler you can install the rbenv-gemset plugin.
  • Require changes to Ruby libraries for compatibility. The simplicity of rbenv means as long as it's in your $PATH, nothing else needs to know about it.

INSTALLATION

Install Homebrew http://brew.sh

Then:

$ brew update
$ brew install rbenv 
$ brew install rbenv ruby-build

# Add rbenv to bash so that it loads every time you open a terminal
echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.bash_profile
source ~/.bash_profile

UPDATE
There's one additional step after brew install rbenv Run rbenv init and add one line to .bash_profile as it states. After that reopen your terminal window […] SGI Sep 30 at 12:01 —https://stackoverflow.com/users/119770

$ rbenv install --list
Available versions:
 1.8.5-p113
 1.8.5-p114
 […]
 2.3.1
 2.4.0-dev
 jruby-1.5.6
 […]
$ rbenv install 2.3.1
[…]

Set the global version:

$ rbenv global 2.3.1
$ ruby -v
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]

Set the local version of your repo by adding .ruby-version to your repo's root dir:

$ cd ~/whatevs/projects/new_repo
$ echo "2.3.1" > .ruby-version

For MacOS visit this link

Pandas sort by group aggregate and column

Groupby A:

In [0]: grp = df.groupby('A')

Within each group, sum over B and broadcast the values using transform. Then sort by B:

In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
          B
2 -2.829710
5 -2.829710
1  0.253651
4  0.253651
0  0.551377
3  0.551377

Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:

In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]

In [3]: sort1
Out[3]:
     A         B      C
2  baz -0.528172  False
5  baz -2.301539   True
1  bar -0.611756   True
4  bar  0.865408  False
0  foo  1.624345  False
3  foo -1.072969   True

Finally, sort the 'C' values within groups of 'A' using the sort=False option to preserve the A sort order from step 1:

In [4]: f = lambda x: x.sort('C', ascending=False)

In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)

In [6]: sort2
Out[6]:
         A         B      C
A
baz 5  baz -2.301539   True
    2  baz -0.528172  False
bar 1  bar -0.611756   True
    4  bar  0.865408  False
foo 3  foo -1.072969   True
    0  foo  1.624345  False

Clean up the df index by using reset_index with drop=True:

In [7]: sort2.reset_index(0, drop=True)
Out[7]:
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

CSS text-transform capitalize on all caps

The PHP solution, in backend:

$string = `UPPERCASE`
$lowercase = strtolower($string);
echo ucwords($lowercase);

NameError: name 'self' is not defined

If you have arrived here via google, please make sure to check that you have given self as the first parameter to a class function. Especially if you try to reference values for that object instance inside the class function.

def foo():
    print(self.bar)

>NameError: name 'self' is not defined

def foo(self):
    print(self.bar)

linux execute command remotely

 ssh user@machine 'bash -s' < local_script.sh

or you can just

 ssh user@machine "remote command to run" 

How to add "active" class to Html.ActionLink in ASP.NET MVC

I realized that this problem was a common problem for some of us, so I published my own solution using nuget package. Below you can see how it works. I hope that will be useful.

Note:This nuget package is my first package. So if you see a mistake, please give feedback. Thank you.

  1. Install Package or download source code and add your Project

    -Install-Package Betalgo.MvcMenuNavigator
    
  2. Add your pages to an enum

    public enum HeaderTop
    {
        Dashboard,
        Product
    }
    public enum HeaderSub
    {
        Index
    }
    
  3. Put Filter to top of your Controllor or Action

    [MenuNavigator(HeaderTop.Product, HeaderSub.Index)]
    public class ProductsController : Controller
    {
        public async Task<ActionResult> Index()
        {
            return View();
        }
    
        [MenuNavigator(HeaderTop.Dashboard, HeaderSub.Index)]
        public async Task<ActionResult> Dashboard()
        {
            return View();
        }
    }
    
  4. And use it In your header layout like this

    @{
    var headerTop = (HeaderTop?)MenuNavigatorPageDataNavigatorPageData.HeaderTop;
    var headerSub = (HeaderSub?)MenuNavigatorPageDataNavigatorPageData.HeaderSub;
    }
    <div class="nav-collapse collapse navbar-collapse navbar-responsive-collapse">
    <ul class="nav navbar-nav">
        <li class="@(headerTop==HeaderTop.Dashboard?"active selected open":"")">
            <a href="@Url.Action("Index","Home")">Dashboard</a>
        </li>
        <li class="@(headerTop==HeaderTop.Product?"active selected open":"")">
            <a href="@Url.Action("Index", "Products")">Products</a>
        </li>
    </ul>
    

More Info: https://github.com/betalgo/MvcMenuNavigator

Remove directory which is not empty

My modified answer from @oconnecp (https://stackoverflow.com/a/25069828/3027390)

Uses path.join for better cross-platform experience. So, don't forget to require it.

var path = require('path');

Also renamed function to rimraf ;)

/**
 * Remove directory recursively
 * @param {string} dir_path
 * @see https://stackoverflow.com/a/42505874/3027390
 */
function rimraf(dir_path) {
    if (fs.existsSync(dir_path)) {
        fs.readdirSync(dir_path).forEach(function(entry) {
            var entry_path = path.join(dir_path, entry);
            if (fs.lstatSync(entry_path).isDirectory()) {
                rimraf(entry_path);
            } else {
                fs.unlinkSync(entry_path);
            }
        });
        fs.rmdirSync(dir_path);
    }
}

groovy: safely find a key in a map and return its value

Groovy maps can be used with the property property, so you can just do:

def x = mymap.likes

If the key you are looking for (for example 'likes.key') contains a dot itself, then you can use the syntax:

def x = mymap.'likes.key'

Custom Card Shape Flutter SDK

An Alternative Solution to the above

Card(
  shape: RoundedRectangleBorder(
     borderRadius: BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20))),
  color: Colors.white,
  child: ...
)

You can use BorderRadius.only() to customize the corners you wish to manage.

PersistenceContext EntityManager injection NullPointerException

If you have any NamedQueries in your entity classes, then check the stack trace for compilation errors. A malformed query which cannot be compiled can cause failure to load the persistence context.

Get current URL path in PHP

it should be :

$_SERVER['REQUEST_URI'];

Take a look at : Get the full URL in PHP

What's the difference between using "let" and "var"?

It also appears that, at least in Visual Studio 2015, TypeScript 1.5, "var" allows multiple declarations of the same variable name in a block, and "let" doesn't.

This won't generate a compile error:

var x = 1;
var x = 2;

This will:

let x = 1;
let x = 2;

How to insert element into arrays at specific position?

I recently wrote a function to do something similar to what it sounds like you're attempting, it's a similar approach to clasvdb's answer.

function magic_insert($index,$value,$input_array ) {
  if (isset($input_array[$index])) {
    $output_array = array($index=>$value);
    foreach($input_array as $k=>$v) {
      if ($k<$index) {
        $output_array[$k] = $v;
      } else {
        if (isset($output_array[$k]) ) {
          $output_array[$k+1] = $v;
        } else {
          $output_array[$k] = $v;
        }
      } 
    }

  } else {
    $output_array = $input_array;
    $output_array[$index] = $value;
  }
  ksort($output_array);
  return $output_array;
}

Basically it inserts at a specific point, but avoids overwriting by shifting all items down.

The filename, directory name, or volume label syntax is incorrect inside batch

set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
  • The single quotes do not indicate a string, they make it starts: 'C:\ instead of C:\ so

  • %name% is the usual syntax for expanding a variable, the !name! syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION first, or by running the command prompt with CMD /V:ON.

  • Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4 to keep the current PATH content, and add something to the end.

What is JSON and why would I use it?

Understanding JSON

JSON is just a text format that most REST APIs use to return their data. Another common format is XML, but XML is quite a bit more verbose.

Here’s a small example of JSON:

// JSON object
{
  "name": "John",
  "age": 20
}

// JSON array
[
  {
    "name": "John",
    "age": 20
  },
  {
    "name": "Peter",
    "age": 22
  }
]

Notice that the snippet starts with a brace {, which indicates an object. JSON can also start as an array, which uses the square bracket [ symbol to signify the start of the array. JSON needs to be properly formatted, so all beginning { and [ symbols need to have their ending symbols: } and ].

JSON can contain object or array. An object in JSON is wrapped inside the braces { … }, while an array is wrapped inside square brackets [ … ].

JSON structures data by key-value. Key is always a string, but value could be anything (String, number, JSON object, JSON array…). This will affect the way we parse JSON in the next steps.

Convert timedelta to total seconds

You can use mx.DateTime module

import mx.DateTime as mt

t1 = mt.now() 
t2 = mt.now()
print int((t2-t1).seconds)

final keyword in method parameters

final means you can't change the value of that variable once it was assigned.

Meanwhile, the use of final for the arguments in those methods means it won't allow the programmer to change their value during the execution of the method. This only means that inside the method the final variables can not be reassigned.

Using arrays or std::vectors in C++, what's the performance gap?

The performance difference between the two is very much implementation dependent - if you compare a badly implemented std::vector to an optimal array implementation, the array would win, but turn it around and the vector would win...

As long as you compare apples with apples (either both the array and the vector have a fixed number of elements, or both get resized dynamically) I would think that the performance difference is negligible as long as you follow got STL coding practise. Don't forget that using standard C++ containers also allows you to make use of the pre-rolled algorithms that are part of the standard C++ library and most of them are likely to be better performing than the average implementation of the same algorithm you build yourself.

That said, IMHO the vector wins in a debug scenario with a debug STL as most STL implementations with a proper debug mode can at least highlight/cathc the typical mistakes made by people when working with standard containers.

Oh, and don't forget that the array and the vector share the same memory layout so you can use vectors to pass data to legacy C or C++ code that expects basic arrays. Keep in mind that most bets are off in that scenario, though, and you're dealing with raw memory again.

Return file in ASP.Net Core Web API

You can return FileResult with this methods:

1: Return FileStreamResult

    [HttpGet("get-file-stream/{id}"]
    public async Task<FileStreamResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/...."; 
        var stream = await GetFileStreamById(id);

        return new FileStreamResult(stream, mimeType)
        {
            FileDownloadName = fileName
        };
    }

2: Return FileContentResult

    [HttpGet("get-file-content/{id}"]
    public async Task<FileContentResult> DownloadAsync(string id)
    {
        var fileName="myfileName.txt";
        var mimeType="application/...."; 
        var fileBytes = await GetFileBytesById(id);

        return new FileContentResult(fileBytes, mimeType)
        {
            FileDownloadName = fileName
        };
    }

Creating columns in listView and add items

Your first problem is that you are passing -3 to the 2nd parameter of Columns.Add. It needs to be -2 for it to auto-size the column. Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columns.aspx (look at the comments on the code example at the bottom)

private void initListView()
{
    // Add columns
    lvRegAnimals.Columns.Add("Id", -2,HorizontalAlignment.Left);
    lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
    lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);
}

You can also use the other overload, Add(string). E.g:

lvRegAnimals.Columns.Add("Id");
lvRegAnimals.Columns.Add("Name");
lvRegAnimals.Columns.Add("Age");

Reference for more overloads: http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.columnheadercollection.aspx

Second, to add items to the ListView, you need to create instances of ListViewItem and add them to the listView's Items collection. You will need to use the string[] constructor.

var item1 = new ListViewItem(new[] {"id123", "Tom", "24"});
var item2 = new ListViewItem(new[] {person.Id, person.Name, person.Age});
lvRegAnimals.Items.Add(item1);
lvRegAnimals.Items.Add(item2);

You can also store objects in the item's Tag property.

item2.Tag = person;

And then you can extract it

var person = item2.Tag as Person;

Let me know if you have any questions and I hope this helps!

Does Hibernate create tables in the database automatically

Hibernate can create a table, hibernate sequence and tables used for many-to-many mapping on your behalf but you have to explicitly configure it by calling setProperty("hibernate.hbm2ddl.auto", "create") of the Configuration object. By Default, it just validates the schema with DB and fails if anything not already exists by giving error "ORA-00942: table or view does not exist".

If you do above configuration then order of performed actions will be:- a) Drop all tables and sequence and do not give an error if they are not already present. b) create all table and sequence c) alter tables with constraints d) insert data into it.

What does ||= (or-equals) mean in Ruby?

In short, a||=b means: If a is undefined, nil or false, assign b to a. Otherwise, keep a intact.

Convert hex color value ( #ffffff ) to integer value

Answer is really simple guys, in android if you want to convert hex color in to int, just use android Color class, example shown as below

this is for light gray color

Color.parseColor("#a8a8a8");

Thats it and you will get your result.

How to compare two Carbon Timestamps?

First, Eloquent automatically converts it's timestamps (created_at, updated_at) into carbon objects. You could just use updated_at to get that nice feature, or specify edited_at in your model in the $dates property:

protected $dates = ['edited_at'];

Now back to your actual question. Carbon has a bunch of comparison functions:

  • eq() equals
  • ne() not equals
  • gt() greater than
  • gte() greater than or equals
  • lt() less than
  • lte() less than or equals

Usage:

if($model->edited_at->gt($model->created_at)){
    // edited at is newer than created at
}

Set default time in bootstrap-datetimepicker

Hello developers,

Please try this code

var default_date=  new Date(); // or your date
$('#datetimepicker').datetimepicker({
    format: 'DD/MM/YYYY HH:mm', // format you want to show on datetimepicker
    useCurrent:false, // default this is set to true
    defaultDate: default_date
});

if you want to set default date then please set useCurrent to false otherwise setDate or defaultDate like methods will not work.

HTML5 - mp4 video does not play in IE9

If any of these answers above don't work, and you're on an apache server, adding the following to your .htaccess file:

//most of the common formats, add any that apply
AddType video/mp4 .mp4 
AddType audio/mp4 .m4a
AddType video/mp4 .m4v
AddType video/ogg .ogv 
AddType video/ogg .ogg
AddType video/webm .webm

I had a similar problem and adding this solved all my playback issues.

How to put a List<class> into a JSONObject and then read that object?

You could use a JSON serializer/deserializer like flexjson to do the conversion for you.

Show message box in case of exception

There are many ways, for example:

Method one:

public string test()
{
string ErrMsg = string.Empty;
 try
    {
        int num = int.Parse("gagw");
    }
    catch (Exception ex)
    {
        ErrMsg = ex.Message;
    }
return ErrMsg
}

Method two:

public void test(ref string ErrMsg )
{

    ErrMsg = string.Empty;
     try
        {
            int num = int.Parse("gagw");
        }
        catch (Exception ex)
        {
            ErrMsg = ex.Message;
        }
}

How do you push just a single Git branch (and no other branches)?

Minor update on top of Karthik Bose's answer - you can configure git globally, to affect all of your workspaces to behave that way:

git config --global push.default upstream

Getting the IP address of the current machine using Java

You can use java's InetAddress class for this purpose.

InetAddress IP=InetAddress.getLocalHost();
System.out.println("IP of my system is := "+IP.getHostAddress());

Output for my system = IP of my system is := 10.100.98.228

getHostAddress() returns

Returns the IP address string in textual presentation.

OR you can also do

InetAddress IP=InetAddress.getLocalHost();
System.out.println(IP.toString());

Output = IP of my system is := RanRag-PC/10.100.98.228

ADB not recognising Nexus 4 under Windows 7

For me, it was Nexus 4 and Windows 7. I reinstalled the drivers, changed to PTP - basically went through everything.

Clicking the tab that said MainActivity.java rather than activity_main.xml in Eclipse fixed it for me.

How do I get rid of the b-prefix in a string in python?

you need to decode the bytes of you want a string:

b = b'1234'
print(b.decode('utf-8'))  # '1234'

Delete a row from a table by id

Something quick and dirty:

<script type='text/javascript'>
function del_tr(remtr)  
{   
    while((remtr.nodeName.toLowerCase())!='tr')
        remtr = remtr.parentNode;

    remtr.parentNode.removeChild(remtr);
}
function del_id(id)  
{   
        del_tr(document.getElementById(id));
}
</script>

if you place

<a href='' onclick='del_tr(this);return false;'>x</a>

anywhere within the row you want to delete, than its even working without any ids

How to continue a Docker container which has exited

If you want to do it in multiple, easy-to-remember commands:

  1. list stopped containers:

docker ps -a

  1. copy the name or the container id of the container you want to attach to, and start the container with:

docker start -i <name/id>

The -i flag tells docker to attach to the container's stdin.

If the container wasn't started with an interactive shell to connect to, you need to do this to run a shell:

docker start <name/id>
docker exec -it <name/id> /bin/sh

The /bin/sh is the shell usually available with alpine-based images.

MySQL CURRENT_TIMESTAMP on create and on update

I would say you don't need to have the DEFAULT CURRENT_TIMESTAMP on your ts_update: if it is empty, then it is not updated, so your 'last update' is the ts_create.

Java Spring - How to use classpath to specify a file location?

From an answer of @NimChimpsky in similar question:

Resource resource = new ClassPathResource("storedProcedures.sql");
InputStream resourceInputStream = resource.getInputStream();

Using ClassPathResource and interface Resource. And make sure you are adding the resources directory correctly (adding /src/main/resources/ into the classpath).

Note that Resource have a method to get a java.io.File so you can also use:

Resource resource = new ClassPathResource("storedProcedures.sql");
FileReader fr = new FileReader(resource.getFile());

Intent.putExtra List

Assuming that your List is a list of strings make data an ArrayList<String> and use intent.putStringArrayListExtra("data", data)

Here is a skeleton of the code you need:

  1. Declare List

    private List<String> test;
    
  2. Init List at appropriate place

    test = new ArrayList<String>();
    

    and add data as appropriate to test.

  3. Pass to intent as follows:

    Intent intent = getIntent();  
    intent.putStringArrayListExtra("test", (ArrayList<String>) test);
    
  4. Retrieve data as follows:

    ArrayList<String> test = getIntent().getStringArrayListExtra("test");
    

Hope that helps.

Eclipse: Enable autocomplete / content assist

If you are only unfamiliar with the auto-complete while typing syntax or inbuilt methods in the eclipse you can simply type the desired syntax or method name and press Ctrl+Space that will display the list of desired options and you can select one of them.

If the auto-complete option is not enabled then you have to check your settings from Windows menu -> Preferences -> Java -> Editor -> Content assist

How do I format my oracle queries so the columns don't wrap?

Never mind, figured it out:

set wrap off
set linesize 3000 -- (or to a sufficiently large value to hold your results page)

Which I found by:

show all

And looking for some option that seemed relevant.

Swift double to string

This function will let you specify the number of decimal places to show:

func doubleToString(number:Double, numberOfDecimalPlaces:Int) -> String {
    return String(format:"%."+numberOfDecimalPlaces.description+"f", number)
}

Usage:

let numberString = doubleToStringDecimalPlacesWithDouble(number: x, numberOfDecimalPlaces: 2)

Countdown timer using Moment js

In the last statement you are converting the duration to time which also considers the timezone. I assume that your timezone is +530, so 5 hours and 30 minutes gets added to 30 minutes. You can do as given below.

var eventTime= 1366549200; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTime = 1366547400; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT
var diffTime = eventTime - currentTime;
var duration = moment.duration(diffTime*1000, 'milliseconds');
var interval = 1000;

setInterval(function(){
  duration = moment.duration(duration - interval, 'milliseconds');
    $('.countdown').text(duration.hours() + ":" + duration.minutes() + ":" + duration.seconds())
}, interval);

How to add a custom HTTP header to every WCF call?

This works for me

TestService.ReconstitutionClient _serv = new TestService.TestClient();

using (OperationContextScope contextScope = new OperationContextScope(_serv.InnerChannel))
{
   HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();

   requestMessage.Headers["apiKey"] = ConfigurationManager.AppSettings["apikey"]; 
   OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = 
      requestMessage;
   _serv.Method(Testarg);
}

7-zip commandline

Since 7-zip version 9.25 alpha there is a new -spf switch that can be used to store the full file paths including drive letter to the archive.

7zG.exe a -spf c:\BAckup\backup.zip @c:\temp\tmpFileList.txt

should be working just fine now.

How do I specify different layouts for portrait and landscape orientations?

The last line below is an example for applying two quantifiers: landscape and smallest width(600dp) screen. Update 600dp with the ones you need.

res/layout/main_activity.xml                # For handsets
res/layout-land/main_activity.xml           # For handsets in landscape
res/layout-sw600dp/main_activity.xml        # For 7” tablets
res/layout-sw600dp-land/main_activity.xml   # For 7” tablets in landscape

The above applies to dimens as well

res/values/dimens.xml                # For handsets
res/values-land/dimens.xml           # For handsets in landscape
res/values-sw600dp/dimens.xml        # For 7” tablets
res/values-sw600dp-land/dimens.xml   # For 7” tablets in landscape

A useful device metrics: https://material.io/tools/devices/

Eclipse - "Workspace in use or cannot be created, chose a different one."

Running eclipse in Administrator Mode fixed it for me. You can do this by [Right Click] -> Run as Administrator on the eclipse.exe from your install dir.

I was on a working environment with win7 machine having restrictive permission. I also did remove the .lock and .log files but that did not help. It can be a combination of all as well that made it work.

Refresh image with a new one at the same url

Simple solution: add this header to the response:

Cache-control: no-store

Why this works is clearly explained at this authoritative page: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control

It also explains why no-cache does not work.

Other answers do not work because:

Caching.delete is about a new cache that you may create for off-line work, see: https://web.dev/cache-api-quick-guide/

Fragments using a # in the URL do not work because the # tells the browser to not send a request to the server.

A cache-buster with a random part added to the url works, but will also fill the browser cache. In my app, I wanted to download a 5 MB picture every few seconds from a web cam. It will take just an hour or less to completely freeze your pc. I still don't know why the browser cache is not limited to a reasonable max, but this is definitely a disadvantage.

import android packages cannot be resolved

May be you are using this checking :

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
}

To resolve this you need to import android.provider.DocumentsContract class.

To resolve this issue you'll need to set the build SDK version to 19 (4.4) or higher to have API level 19 symbols available while compiling.

First, use the SDK Manager to download API 19 if you don't have it yet. Then, configure your project to use API 19:

  • In Android Studio: File -> Project Structure -> General Settings -> Project SDK.
  • In Eclipse ADT: Project Properties -> Android -> Project Build Target

I found this answer from here

Thanks .

How do I check if a Sql server string is null or empty

You can use ISNULL and check the answer against the known output:

SELECT case when ISNULL(col1, '') = '' then '' else col1 END AS COL1 FROM TEST

React Native Responsive Font Size

I recently ran into this problem and ended up using react-native-extended-stylesheet

You can set you rem value and additional size conditions based on screen size. As per the docs:

// component
const styles = EStyleSheet.create({
  text: {
    fontSize: '1.5rem',
    marginHorizontal: '2rem'
  }
});
// app entry
let {height, width} = Dimensions.get('window');
EStyleSheet.build({
  $rem: width > 340 ? 18 : 16
});

mongodb, replicates and error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

You have to set "secondary okay" mode to let the mongo shell know that you're allowing reads from a secondary. This is to protect you and your applications from performing eventually consistent reads by accident. You can do this in the shell with:

rs.secondaryOk()

After that you can query normally from secondaries.

A note about "eventual consistency": under normal circumstances, replica set secondaries have all the same data as primaries within a second or less. Under very high load, data that you've written to the primary may take a while to replicate to the secondaries. This is known as "replica lag", and reading from a lagging secondary is known as an "eventually consistent" read, because, while the newly written data will show up at some point (barring network failures, etc), it may not be immediately available.

Edit: You only need to set secondaryOk when querying from secondaries, and only once per session.

Maven is not working in Java 8 when Javadoc tags are incomplete

Added below

JAVA_TOOL_OPTIONS=-DadditionalJOption=-Xdoclint:none

Into Jenkins job :

Configuration > Build Environment > Inject environment variables to the build process > Properties Content

Solved my problem of code building through Jenkins Maven :-)

VBA - If a cell in column A is not blank the column B equals

Use the function IF :

=IF ( logical_test, value_if_true, value_if_false )

How to compare the contents of two string objects in PowerShell

You can do it in two different ways.

Option 1: The -eq operator

>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False

Option 2: The .Equals() method of the string object. Because strings in PowerShell are .Net System.String objects, any method of that object can be called directly.

>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method

List of System.String methods follows.

How to flush route table in windows?

In Microsoft Windows, you can go through by route -f command to delete your current Gateway, check route / ? for more advance option, like add / delete etc and also can write a batch to add route on specific time as well but if you need to delete IP cache, then you have the option to use arp command.

How to take the nth digit of a number in python

Here's my take on this problem.

I have defined a function 'index' which takes the number and the input index and outputs the digit at the desired index.

The enumerate method operates on the strings, therefore the number is first converted to a string. Since the indexing in Python starts from zero, but the desired functionality requires it to start with 1, therefore a 1 is placed in the enumerate function to indicate the start of the counter.

def index(number, i):

    for p,num in enumerate(str(number),1):

        if p == i:
            print(num)

Set timeout for ajax (jQuery)

Here's some examples that demonstrate setting and detecting timeouts in jQuery's old and new paradigmes.

Live Demo

Promise with jQuery 1.8+

Promise.resolve(
  $.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
  })
).then(function(){
  //do something
}).catch(function(e) {
  if(e.statusText == 'timeout')
  {     
    alert('Native Promise: Failed from timeout'); 
    //do something. Try again perhaps?
  }
});

jQuery 1.8+

$.ajax({
    url: '/getData',
    timeout:3000 //3 second timeout
}).done(function(){
    //do something
}).fail(function(jqXHR, textStatus){
    if(textStatus === 'timeout')
    {     
        alert('Failed from timeout'); 
        //do something. Try again perhaps?
    }
});?

jQuery <= 1.7.2

$.ajax({
    url: '/getData',
    error: function(jqXHR, textStatus){
        if(textStatus === 'timeout')
        {     
             alert('Failed from timeout');         
            //do something. Try again perhaps?
        }
    },
    success: function(){
        //do something
    },
    timeout:3000 //3 second timeout
});

Notice that the textStatus param (or jqXHR.statusText) will let you know what the error was. This may be useful if you want to know that the failure was caused by a timeout.

error(jqXHR, textStatus, errorThrown)

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests.

src: http://api.jquery.com/jQuery.ajax/

Get Specific Columns Using “With()” Function in Laravel Eloquent

I came across this issue but with a second layer of related objects. @Awais Qarni's answer holds up with the inclusion of the appropriate foreign key in the nested select statement. Just as an id is required in the first nested select statement to reference the related model, the foreign key is required to reference the second degree of related models; in this example the Company model.

Post::with(['user' => function ($query) {
        $query->select('id','company_id', 'username');
    }, 'user.company' => function ($query) {
        $query->select('id', 'name');
    }])->get();

Additionally, if you want to select specific columns from the Post model you would need to include the user_id column in the select statement in order to reference it.

Post::with(['user' => function ($query) {
        $query->select('id', 'username');
    }])
    ->select('title', 'content', 'user_id')
    ->get();

Where to change default pdf page width and font size in jspdf.debug.js?

Besides using one of the default formats you can specify any size you want in the unit you specify.

For example:

// Document of 210mm wide and 297mm high
new jsPDF('p', 'mm', [297, 210]);
// Document of 297mm wide and 210mm high
new jsPDF('l', 'mm', [297, 210]);
// Document of 5 inch width and 3 inch high
new jsPDF('l', 'in', [3, 5]);

The 3rd parameter of the constructor can take an array of the dimensions. However they do not correspond to width and height, instead they are long side and short side (or flipped around).

Your 1st parameter (landscape or portrait) determines what becomes the width and the height.

In the sourcecode on GitHub you can see the supported units (relative proportions to pt), and you can also see the default page formats (with their sizes in pt).

How to write to Console.Out during execution of an MSTest test

You better setup a single test and create a performance test from this test. This way you can monitor the progress using the default tool set.

Not equal <> != operator on NULL

<> is Standard SQL-92; != is its equivalent. Both evaluate for values, which NULL is not -- NULL is a placeholder to say there is the absence of a value.

Which is why you can only use IS NULL/IS NOT NULL as predicates for such situations.

This behavior is not specific to SQL Server. All standards-compliant SQL dialects work the same way.

Note: To compare if your value is not null, you use IS NOT NULL, while to compare with not null value, you use <> 'YOUR_VALUE'. I can't say if my value equals or not equals to NULL, but I can say if my value is NULL or NOT NULL. I can compare if my value is something other than NULL.

Abstract methods in Java

If you use the java keyword abstract you cannot provide an implementation.

Sometimes this idea comes from having a background in C++ and mistaking the virtual keyword in C++ as being "almost the same" as the abstract keyword in Java.

In C++ virtual indicates that a method can be overridden and polymorphism will follow, but abstract in Java is not the same thing. In Java abstract is more like a pure virtual method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.

Now to protect a method from being overridden, Java uses the keyword final in coordination with the method declaration to indicate that subclasses cannot override the method.

Calling a Variable from another Class

That would just be:

 Console.WriteLine(Variables.name);

and it needs to be public also:

public class Variables
{
   public static string name = "";
}

Capture iframe load complete event

Step 1: Add iframe in template.

<iframe id="uvIFrame" src="www.google.com"></iframe>

Step 2: Add load listener in Controller.

document.querySelector('iframe#uvIFrame').addEventListener('load', function () {
  $scope.loading = false;
  $scope.$apply();
});

Using grep to search for hex strings in a file

There's also a pretty handy tool called binwalk, written in python, which provides for binary pattern matching (and quite a lot more besides). Here's how you would search for a binary string, which outputs the offset in decimal and hex (from the docs):

$ binwalk -R "\x00\x01\x02\x03\x04" firmware.bin
DECIMAL     HEX         DESCRIPTION
--------------------------------------------------------------------------
377654      0x5C336     Raw string signature

How do I upgrade PHP in Mac OS X?

You can use curl to update php version.

curl -s http://php-osx.liip.ch/install.sh | bash -s 7.3

Last Step:

export PATH=/usr/local/php5/bin:$PATH

Check the upgraded version

php -v

How to write a Python module/package?

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py

create hello.py then write the following function as its content:

def helloworld():
   print "hello"

Then you can import hello:

>>> import hello
>>> hello.helloworld()
'hello'
>>>

To group many .py files put them in a folder. Any folder with an __init__.py is considered a module by python and you can call them a package

|-HelloModule
  |_ __init__.py
  |_ hellomodule.py

You can go about with the import statement on your module the usual way.

For more information, see 6.4. Packages.

Creating virtual directories in IIS express

I had something else, the files itself where inaccessible in a SBS envirenment.

Delete the files in the config folder (if you can't open them!) and replace them with a copy of the folder on your own local pc.

Fixed it for me :)

Case insensitive std::string.find()

Since you're doing substring searches (std::string) and not element (character) searches, there's unfortunately no existing solution I'm aware of that's immediately accessible in the standard library to do this.

Nevertheless, it's easy enough to do: simply convert both strings to upper case (or both to lower case - I chose upper in this example).

std::string upper_string(const std::string& str)
{
    string upper;
    transform(str.begin(), str.end(), std::back_inserter(upper), toupper);
    return upper;
}

std::string::size_type find_str_ci(const std::string& str, const std::string& substr)
{
    return upper(str).find(upper(substr) );
}

This is not a fast solution (bordering into pessimization territory) but it's the only one I know of off-hand. It's also not that hard to implement your own case-insensitive substring finder if you are worried about efficiency.

Additionally, I need to support std::wstring/wchar_t. Any ideas?

tolower/toupper in locale will work on wide-strings as well, so the solution above should be just as applicable (simple change std::string to std::wstring).

[Edit] An alternative, as pointed out, is to adapt your own case-insensitive string type from basic_string by specifying your own character traits. This works if you can accept all string searches, comparisons, etc. to be case-insensitive for a given string type.

Removing specific rows from a dataframe

This boils down to two distinct steps:

  1. Figure out when your condition is true, and hence compute a vector of booleans, or, as I prefer, their indices by wrapping it into which()
  2. Create an updated data.frame by excluding the indices from the previous step.

Here is an example:

R> set.seed(42)
R> DF <- data.frame(sub=rep(1:4, each=4), day=sample(1:4, 16, replace=TRUE))
R> DF
   sub day
1    1   4
2    1   4
3    1   2
4    1   4
5    2   3
6    2   3
7    2   3
8    2   1
9    3   3
10   3   3
11   3   2
12   3   3
13   4   4
14   4   2
15   4   2
16   4   4
R> ind <- which(with( DF, sub==2 & day==3 ))
R> ind
[1] 5 6 7
R> DF <- DF[ -ind, ]
R> table(DF)
   day
sub 1 2 3 4
  1 0 1 0 3
  2 1 0 0 0
  3 0 1 3 0
  4 0 2 0 2
R> 

And we see that sub==2 has only one entry remaining with day==1.

Edit The compound condition can be done with an 'or' as follows:

ind <- which(with( DF, (sub==1 & day==2) | (sub=3 & day=4) ))

and here is a new full example

R> set.seed(1)
R> DF <- data.frame(sub=rep(1:4, each=5), day=sample(1:4, 20, replace=TRUE))
R> table(DF)
   day
sub 1 2 3 4
  1 1 2 1 1
  2 1 0 2 2
  3 2 1 1 1
  4 0 2 1 2
R> ind <- which(with( DF, (sub==1 & day==2) | (sub==3 & day==4) ))
R> ind
[1]  1  2 15
R> DF <- DF[-ind, ]
R> table(DF)
   day
sub 1 2 3 4
  1 1 0 1 1
  2 1 0 2 2
  3 2 1 1 0
  4 0 2 1 2
R> 

Insert current date into a date column using T-SQL?

You could use getdate() in a default as this SO question's accepted answer shows. This way you don't provide the date, you just insert the rest and that date is the default value for the column.

You could also provide it in the values list of your insert and do it manually if you wish.

How can I make my flexbox layout take 100% vertical space?

set the wrapper to height 100%

.vwrapper {
  display: flex;
  flex-direction: column;

  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: stretch;
  align-content: stretch;

  height: 100%;
}

and set the 3rd row to flex-grow

#row3 {
   background-color: green;
   flex: 1 1 auto;
   display: flex;
}

demo

Apply function to each column in a data frame observing each columns existing data type

If you want to learn your data summary (df) provides the min, 1st quantile, median and mean, 3rd quantile and max of numerical columns and the frequency of the top levels of the factor columns.

Mutex example / tutorial?

While a mutex may be used to solve other problems, the primary reason they exist is to provide mutual exclusion and thereby solve what is known as a race condition. When two (or more) threads or processes are attempting to access the same variable concurrently, we have potential for a race condition. Consider the following code

//somewhere long ago, we have i declared as int
void my_concurrently_called_function()
{
  i++;
}

The internals of this function look so simple. It's only one statement. However, a typical pseudo-assembly language equivalent might be:

load i from memory into a register
add 1 to i
store i back into memory

Because the equivalent assembly-language instructions are all required to perform the increment operation on i, we say that incrementing i is a non-atmoic operation. An atomic operation is one that can be completed on the hardware with a gurantee of not being interrupted once the instruction execution has begun. Incrementing i consists of a chain of 3 atomic instructions. In a concurrent system where several threads are calling the function, problems arise when a thread reads or writes at the wrong time. Imagine we have two threads running simultaneoulsy and one calls the function immediately after the other. Let's also say that we have i initialized to 0. Also assume that we have plenty of registers and that the two threads are using completely different registers, so there will be no collisions. The actual timing of these events may be:

thread 1 load 0 into register from memory corresponding to i //register is currently 0
thread 1 add 1 to a register //register is now 1, but not memory is 0
thread 2 load 0 into register from memory corresponding to i
thread 2 add 1 to a register //register is now 1, but not memory is 0
thread 1 write register to memory //memory is now 1
thread 2 write register to memory //memory is now 1

What's happened is that we have two threads incrementing i concurrently, our function gets called twice, but the outcome is inconsistent with that fact. It looks like the function was only called once. This is because the atomicity is "broken" at the machine level, meaning threads can interrupt each other or work together at the wrong times.

We need a mechanism to solve this. We need to impose some ordering to the instructions above. One common mechanism is to block all threads except one. Pthread mutex uses this mechanism.

Any thread which has to execute some lines of code which may unsafely modify shared values by other threads at the same time (using the phone to talk to his wife), should first be made acquire a lock on a mutex. In this way, any thread that requires access to the shared data must pass through the mutex lock. Only then will a thread be able to execute the code. This section of code is called a critical section.

Once the thread has executed the critical section, it should release the lock on the mutex so that another thread can acquire a lock on the mutex.

The concept of having a mutex seems a bit odd when considering humans seeking exclusive access to real, physical objects but when programming, we must be intentional. Concurrent threads and processes don't have the social and cultural upbringing that we do, so we must force them to share data nicely.

So technically speaking, how does a mutex work? Doesn't it suffer from the same race conditions that we mentioned earlier? Isn't pthread_mutex_lock() a bit more complex that a simple increment of a variable?

Technically speaking, we need some hardware support to help us out. The hardware designers give us machine instructions that do more than one thing but are guranteed to be atomic. A classic example of such an instruction is the test-and-set (TAS). When trying to acquire a lock on a resource, we might use the TAS might check to see if a value in memory is 0. If it is, that would be our signal that the resource is in use and we do nothing (or more accurately, we wait by some mechanism. A pthreads mutex will put us into a special queue in the operating system and will notify us when the resource becomes available. Dumber systems may require us to do a tight spin loop, testing the condition over and over). If the value in memory is not 0, the TAS sets the location to something other than 0 without using any other instructions. It's like combining two assembly instructions into 1 to give us atomicity. Thus, testing and changing the value (if changing is appropriate) cannot be interrupted once it has begun. We can build mutexes on top of such an instruction.

Note: some sections may appear similar to an earlier answer. I accepted his invite to edit, he preferred the original way it was, so I'm keeping what I had which is infused with a little bit of his verbiage.

What does HTTP/1.1 302 mean exactly?

A simple way of looking at HTTP 301 vs. 302 redirects is:

Suppose you have a bookmark to "http://sample.com/sample". You use a browser to go there.

A 302 redirect to a different URL at this point would mean that you should keep your bookmark to "http://sample.com/sample". This is because the destination URL may change in the future.

A 301 redirect to a different URL would mean that your bookmark should change to point to the new URL as it is a permanent redirect.

How to customise the Jackson JSON mapper implicitly used by Spring Boot?

spring.jackson.serialization-inclusion=non_null used to work for us

But when we upgraded spring boot version to 1.4.2.RELEASE or higher, it stopped working.

Now, another property spring.jackson.default-property-inclusion=non_null is doing the magic.

in fact, serialization-inclusion is deprecated. This is what my intellij throws at me.

Deprecated: ObjectMapper.setSerializationInclusion was deprecated in Jackson 2.7

So, start using spring.jackson.default-property-inclusion=non_null instead

Select All checkboxes using jQuery

$(document).ready(function() {
    $('#ckbCheckAll').click(function() {
        $('.checkBoxClass').each(function() {
            $(this).attr('checked',!$(this).attr('checked'));
        });
    });
});

OR

$(function () {
    $('#ckbCheckAll').toggle(
        function() {
            $('.checkBoxClass').prop('checked', true);
        },
        function() {
            $('.checkBoxClass').prop('checked', false);
        }
    );
});

Any way to make a WPF textblock selectable?

Use a TextBox with these settings instead to make it read only and to look like a TextBlock control.

<TextBox Background="Transparent"
         BorderThickness="0"
         Text="{Binding Text, Mode=OneWay}"
         IsReadOnly="True"
         TextWrapping="Wrap" />

How to give a time delay of less than one second in excel vba?

To pause for 0.8 of a second:

Sub main()
    startTime = Timer
    Do
    Loop Until Timer - startTime >= 0.8
End Sub

Explanation of the UML arrows

If you are more of a MOOC person, one free course that I'd recommend that teaches you all the in and outs of most UML diagrams is this one from Udacity: https://www.udacity.com/course/software-architecture-design--ud821

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's an old discussion thread where I listed the main differences and the conditions in which you should use each of these methods. I think you may find it useful to go through the discussion.

To explain the differences as relevant to your posted example:

a. When you use RegisterStartupScript, it will render your script after all the elements in the page (right before the form's end tag). This enables the script to call or reference page elements without the possibility of it not finding them in the Page's DOM.

Here is the rendered source of the page when you invoke the RegisterStartupScript method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <div> <span id="lblDisplayDate">Label</span>
            <br />
            <input type="submit" name="btnPostback" value="Register Startup Script" id="btnPostback" />
            <br />
            <input type="submit" name="btnPostBack2" value="Register" id="btnPostBack2" />
        </div>
        <div>
            <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="someViewstategibberish" />
        </div>
        <!-- Note this part -->
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            lbl.style.color = 'red';
        </script>
    </form>
    <!-- Note this part -->
</body>
</html>

b. When you use RegisterClientScriptBlock, the script is rendered right after the Viewstate tag, but before any of the page elements. Since this is a direct script (not a function that can be called, it will immediately be executed by the browser. But the browser does not find the label in the Page's DOM at this stage and hence you should receive an "Object not found" error.

Here is the rendered source of the page when you invoke the RegisterClientScriptBlock method:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1"><title></title></head>
<body>
    <form name="form1" method="post" action="StartupScript.aspx" id="form1">
        <div>
            <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="someViewstategibberish" />
        </div>
        <script language='javascript'>
            var lbl = document.getElementById('lblDisplayDate');
            // Error is thrown in the next line because lbl is null.
            lbl.style.color = 'green';

Therefore, to summarize, you should call the latter method if you intend to render a function definition. You can then render the call to that function using the former method (or add a client side attribute).

Edit after comments:


For instance, the following function would work:

protected void btnPostBack2_Click(object sender, EventArgs e) 
{ 
  System.Text.StringBuilder sb = new System.Text.StringBuilder(); 
  sb.Append("<script language='javascript'>function ChangeColor() {"); 
  sb.Append("var lbl = document.getElementById('lblDisplayDate');"); 
  sb.Append("lbl.style.color='green';"); 
  sb.Append("}</script>"); 

  //Render the function definition. 
  if (!ClientScript.IsClientScriptBlockRegistered("JSScriptBlock")) 
  {
    ClientScript.RegisterClientScriptBlock(this.GetType(), "JSScriptBlock", sb.ToString()); 
  }

  //Render the function invocation. 
  string funcCall = "<script language='javascript'>ChangeColor();</script>"; 

  if (!ClientScript.IsStartupScriptRegistered("JSScript"))
  { 
    ClientScript.RegisterStartupScript(this.GetType(), "JSScript", funcCall); 
  } 
} 

Calling @Html.Partial to display a partial view belonging to a different controller

As GvS said, but I also find it useful to use strongly typed views so that I can write something like

@Html.Partial(MVC.Student.Index(), model)

without magic strings.

How do I get a human-readable file size in bytes abbreviation using .NET?

I assume you're looking for "1.4 MB" instead of "1468006 bytes"?

I don't think there is a built-in way to do that in .NET. You'll need to just figure out which unit is appropriate, and format it.

Edit: Here's some sample code to do just that:

http://www.codeproject.com/KB/cpp/formatsize.aspx

How do I REALLY reset the Visual Studio window layout?

I tried most of the suggestions, and none of them worked. I didn't get a chance to try /resetuserdata. Finally I reinstalled the plugin and uninstalled it again, and the windows went away.

How to consume a SOAP web service in Java

There are many options to consume a SOAP web service with Stub or Java classes created based on WSDL. But if anyone wants to do this without any Java class created, this article is very helpful. Code Snippet from the article:

public String someMethod() throws MalformedURLException, IOException {

//Code to make a webservice HTTP request
String responseString = "";
String outputString = "";
String wsURL = "<Endpoint of the webservice to be consumed>";
URL url = new URL(wsURL);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)connection;
ByteArrayOutputStream bout = new ByteArrayOutputStream();
String xmlInput = "entire SOAP Request";

byte[] buffer = new byte[xmlInput.length()];
buffer = xmlInput.getBytes();
bout.write(buffer);
byte[] b = bout.toByteArray();
String SOAPAction = "<SOAP action of the webservice to be consumed>";
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty("Content-Length",
String.valueOf(b.length));
httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction", SOAPAction);
httpConn.setRequestMethod("POST");
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
OutputStream out = httpConn.getOutputStream();
//Write the content of the request to the outputstream of the HTTP Connection.
out.write(b);
out.close();
//Ready with sending the request.

//Read the response.
InputStreamReader isr = null;
if (httpConn.getResponseCode() == 200) {
  isr = new InputStreamReader(httpConn.getInputStream());
} else {
  isr = new InputStreamReader(httpConn.getErrorStream());
}

BufferedReader in = new BufferedReader(isr);

//Write the SOAP message response to a String.
while ((responseString = in.readLine()) != null) {
outputString = outputString + responseString;
}
//Parse the String output to a org.w3c.dom.Document and be able to reach every node with the org.w3c.dom API.
Document document = parseXmlFile(outputString); // Write a separate method to parse the xml input.
NodeList nodeLst = document.getElementsByTagName("<TagName of the element to be retrieved>");
String elementValue = nodeLst.item(0).getTextContent();
System.out.println(elementValue);

//Write the SOAP message formatted to the console.
String formattedSOAPResponse = formatXML(outputString); // Write a separate method to format the XML input.
System.out.println(formattedSOAPResponse);
return elementValue;
}

For those who're looking for a similar kind of solution with file upload while consuming a SOAP API, please refer to this post: How to attach a file (pdf, jpg, etc) in a SOAP POST request?

MySQL: Get column name or alias from query

Similar to @James answer, a more pythonic way can be:

fields = map(lambda x:x[0], cursor.description)
result = [dict(zip(fields,row))   for row in cursor.fetchall()]

You can get a single column with map over the result:

extensions = map(lambda x: x['ext'], result)

or filter results:

filter(lambda x: x['filesize'] > 1024 and x['filesize'] < 4096, result)

or accumulate values for filtered columns:

totalTxtSize = reduce(
        lambda x,y: x+y,
        filter(lambda x: x['ext'].lower() == 'txt', result)
)

Split string based on a regular expression

The str.split method will automatically remove all white space between items:

>>> str1 = "a    b     c      d"
>>> str1.split()
['a', 'b', 'c', 'd']

Docs are here: http://docs.python.org/library/stdtypes.html#str.split

How to set different colors in HTML in one statement?

_x000D_
_x000D_
.rainbow {_x000D_
  background-image: -webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
  background-image: gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
  color:transparent;_x000D_
  -webkit-background-clip: text;_x000D_
  background-clip: text;_x000D_
}
_x000D_
<h2><span class="rainbow">Rainbows are colorful and scalable and lovely</span></h2>
_x000D_
_x000D_
_x000D_

MySql Query Replace NULL with Empty String in Select

Try COALESCE. It returns the first non-NULL value.

SELECT COALESCE(`prereq`, ' ') FROM `test`

Regex to extract substring, returning 2 results for some reason

match returns an array.

The default string representation of an array in JavaScript is the elements of the array separated by commas. In this case the desired result is in the second element of the array:

var tesst = "afskfsd33j"
var test = tesst.match(/a(.*)j/);
alert (test[1]);

How many files can I put in a directory?

The question comes down to what you're going to do with the files.

Under Windows, any directory with more than 2k files tends to open slowly for me in Explorer. If they're all image files, more than 1k tend to open very slowly in thumbnail view.

At one time, the system-imposed limit was 32,767. It's higher now, but even that is way too many files to handle at one time under most circumstances.

unique combinations of values in selected columns in pandas data frame and count

Placing @EdChum's very nice answer into a function count_unique_index. The unique method only works on pandas series, not on data frames. The function below reproduces the behavior of the unique function in R:

unique returns a vector, data frame or array like x but with duplicate elements/rows removed.

And adds a count of the occurrences as requested by the OP.

df1 = pd.DataFrame({'A':['yes','yes','yes','yes','no','no','yes','yes','yes','no'],                                                                                             
                    'B':['yes','no','no','no','yes','yes','no','yes','yes','no']})                                                                                               
def count_unique_index(df, by):                                                                                                                                                 
    return df.groupby(by).size().reset_index().rename(columns={0:'count'})                                                                                                      

count_unique_index(df1, ['A','B'])                                                                                                                                              
     A    B  count                                                                                                                                                                  
0   no   no      1                                                                                                                                                                  
1   no  yes      2                                                                                                                                                                  
2  yes   no      4                                                                                                                                                                  
3  yes  yes      3

Reading file from Workspace in Jenkins with Groovy script

Based on your comments, you would be better off with Text-finder plugin.

It allows to search file(s), as well as console, for a regular expression and then set the build either unstable or failed if found.

As for the Groovy, you can use the following to access ${WORKSPACE} environment variable:
def workspace = manager.build.getEnvVars()["WORKSPACE"]

How to change JFrame icon

Add the following code within the constructor like so:

public Calculator() {
    initComponents();
//the code to be added        this.setIconImage(newImageIcon(getClass().getResource("color.png")).getImage());     }

Change "color.png" to the file name of the picture you want to insert. Drag and drop this picture onto the package (under Source Packages) of your project.

Run your project.

Maven does not find JUnit tests to run

In case someone has searched and I do not solve it, I had a library for different tests:

<dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>${org.junit.jupiter.version}</version>
        <scope>test</scope>
    </dependency>

When I installed junit everything worked, I hope and help this:

<dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.11</version>
        <scope>test</scope>
    </dependency>

Python: fastest way to create a list of n lists

The list comprehensions actually are implemented more efficiently than explicit looping (see the dis output for example functions) and the map way has to invoke an ophaque callable object on every iteration, which incurs considerable overhead overhead.

Regardless, [[] for _dummy in xrange(n)] is the right way to do it and none of the tiny (if existent at all) speed differences between various other ways should matter. Unless of course you spend most of your time doing this - but in that case, you should work on your algorithms instead. How often do you create these lists?

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

What is dtype('O'), in pandas?

It means "a python object", i.e. not one of the builtin scalar types supported by numpy.

np.array([object()]).dtype
=> dtype('O')

How do I fix PyDev "Undefined variable from import" errors?

I was having a similar problem with an Eclipse/PyDev project. In this project the root directory of the python code was a sub-directory of the project.

--> MyProject
 + --> src         Root of python code
   + --> module1     A module 
   + --> module2     Another module
 + --> docs
 + --> test

When the project was debugged or run everything was fine as the working directory was set to the correct place. However the PyDev code analysis was failing to find any imports from module1 or module2.

Solution was to edit the project properties -> PyDev - PYTHONPATH section and remove /MyProject from the source folders tab and add /MyProject/src to it instead.

JAVA_HOME should point to a JDK not a JRE

do it thru cmd -

echo %JAVA_HOME% set set JAVA_HOME=C:\Program Files\Java\jdk1.8.0 echo %JAVA_HOME%

How can I parse a time string containing milliseconds in it with python?

from python mailing lists: parsing millisecond thread. There is a function posted there that seems to get the job done, although as mentioned in the author's comments it is kind of a hack. It uses regular expressions to handle the exception that gets raised, and then does some calculations.

You could also try do the regular expressions and calculations up front, before passing it to strptime.

Swift addsubview and remove it

Assuming you have access to it via outlets or programmatic code, you can remove it by referencing your view foo and the removeFromSuperview method

foo.removeFromSuperview()

How to search for an element in an stl list?

What you can do and what you should do are different matters.

If the list is very short, or you are only ever going to call find once then use the linear approach above.

However linear-search is one of the biggest evils I find in slow code, and consider using an ordered collection (set or multiset if you allow duplicates). If you need to keep a list for other reasons eg using an LRU technique or you need to maintain the insertion order or some other order, create an index for it. You can actually do that using a std::set of the list iterators (or multiset) although you need to maintain this any time your list is modified.

What is the largest TCP/IP network port number allowable for IPv4?

Just a followup to smashery's answer. The ephemeral port range (on Linux at least, and I suspect other Unices as well) is not a fixed. This can be controlled by writing to /proc/sys/net/ipv4/ip_local_port_range

The only restriction (as far as IANA is concerned) is that ports below 1024 are designated to be well-known ports. Ports above that are free for use. Often you'll find that ports below 1024 are restricted to superuser access, I believe for this very reason.

URL to load resources from the classpath in Java

I try to avoid the URL class and instead rely on URI. Thus for things that need URL where I would like to do Spring Resource like lookup with out Spring I do the following:

public static URL toURL(URI u, ClassLoader loader) throws MalformedURLException {
    if ("classpath".equals(u.getScheme())) {
        String path = u.getPath();
        if (path.startsWith("/")){
            path = path.substring("/".length());
        }
        return loader.getResource(path);
    }
    else if (u.getScheme() == null && u.getPath() != null) {
        //Assume that its a file.
        return new File(u.getPath()).toURI().toURL();
    }
    else {
        return u.toURL();
    }
}

To create a URI you can use URI.create(..). This way is also better because you control the ClassLoader that will do the resource lookup.

I noticed some other answers trying to parse the URL as a String to detect the scheme. I think its better to pass around URI and use it to parse instead.

I have actually filed an issue a while ago with Spring Source begging them to separate out their Resource code from core so that you don't need all the other Spring stuff.

Internal and external fragmentation

External fragmentation
Total memory space is enough to satisfy a request or to reside a process in it, but it is not contiguous so it can not be used.

External fragmentation

Internal fragmentation
Memory block assigned to process is bigger. Some portion of memory is left unused as it can not be used by another process.

Internal fragmentation

Android: android.content.res.Resources$NotFoundException: String resource ID #0x5

Another scenario that can cause this exception is with DataBinding, that is when you use something like this in your layout

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="model"
            type="point.to.your.model"/>
    </data>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@{model.someIntegerVariable}"/>

</layout>

Notice that the variable I'm using is an Integer and I'm assigning it to the text field of the TextView. Since the TextView already has a method with signature of setText(int) it will use this method instead of using the setText(String) and cast the value. Thus the TextView thinks of your input number as a resource value which obviously is not valid.

Solution is to cast your int value to string like this

android:text="@{String.valueOf(model.someIntegerVariable)}"

Proper use of mutexes in Python

You have to unlock your Mutex at sometime...