SyntaxFix.com - Programming Questions & Answers Hub For Beginners


Some Of The Best Answers From Latest Asked Questions

Groovy built-in REST/HTTP client?

import groovyx.net.http.HTTPBuilder;

public class HttpclassgetrRoles {
     static void main(String[] args){
         def baseUrl = new URL('http://test.city.com/api/Cirtxyz/GetUser')

         HttpURLConnection connection = (HttpURLConnection) baseUrl.openConnection();
         connection.addRequestProperty("Accept", "application/json")
         connection.with {
           doOutput = true
           requestMethod = 'GET'
           println content.text
         }

     }
}

Setting up a JavaScript variable from Spring model by using Thymeleaf

If you use Thymeleaf 3:

<script th:inline="javascript">
    var username = [[${session.user.name}]];
</script>

How to return rows from left table not found in right table?

I also like to use NOT EXISTS. When it comes to performance if index correctly it should perform the same as a LEFT JOIN or better. Plus its easier to read.

SELECT Column1
FROM TableA a
WHERE NOT EXISTS ( SELECT Column1
                   FROM Tableb b
                   WHERE a.Column1 = b.Column1
                 )

Connect to SQL Server Database from PowerShell

# database Intraction

$SQLServer = "YourServerName" #use Server\Instance for named SQL instances!
$SQLDBName = "YourDBName"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; 
User ID= YourUserID; Password= YourPassword" 
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = 'StoredProcName'
$SqlCmd.Connection = $SqlConnection 
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd 
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet) 
$SqlConnection.Close() 

#End :database Intraction
clear

Images can't contain alpha channels or transparencies

If you have imagemagick installed, then you can put the following alias into your .bash_profile. It will convert every png in a directory to a jpg, which automatically removes the alpha. You can use the resulting jpg files as your screen shots.

alias pngToJpg='for i in *.png; do convert $i ${i/.png/}.jpg; done'

How to localise a string inside the iOS info.plist file?

Tips

  1. Remember that the iOS Simulator exploits by default your system language. Please change the language (and region) in the iOS Simulator Setting too in order to test your translations.

  2. The localisation string (see Apple docs here) should be

    NSLocationWhenInUseUsageDescription = "Description of this";
    

    and not (with quote "...")

    "NSLocationWhenInUseUsageDescription" = "Description of this";
    

Replace Div Content onclick

A simple addClass and removeClass will do the trick on what you need..

$('#change').on('click', function() { 
  $('div').each(function() { 
    if($(this).hasClass('active')) { 
        $(this).removeClass('active');
    } else { 
        $(this).addClass('active');
    }
});

});

Seee fiddle

I recommend you to learn jquery first before using.

Plotting a fast Fourier transform in Python

The important thing about fft is that it can only be applied to data in which the timestamp is uniform (i.e. uniform sampling in time, like what you have shown above).

In case of non-uniform sampling, please use a function for fitting the data. There are several tutorials and functions to choose from:

https://github.com/tiagopereira/python_tips/wiki/Scipy%3A-curve-fitting http://docs.scipy.org/doc/numpy/reference/generated/numpy.polyfit.html

If fitting is not an option, you can directly use some form of interpolation to interpolate data to a uniform sampling:

https://docs.scipy.org/doc/scipy-0.14.0/reference/tutorial/interpolate.html

When you have uniform samples, you will only have to wory about the time delta (t[1] - t[0]) of your samples. In this case, you can directly use the fft functions

Y    = numpy.fft.fft(y)
freq = numpy.fft.fftfreq(len(y), t[1] - t[0])

pylab.figure()
pylab.plot( freq, numpy.abs(Y) )
pylab.figure()
pylab.plot(freq, numpy.angle(Y) )
pylab.show()

This should solve your problem.

How to return the current timestamp with Moment.js?

Still, no answer. Moment.js - Can do anything but such a simple task.

I'm using this:

moment().toDate().getTime()

Bootstrap Columns Not Working

Try this:

DEMO

<div class="container-fluid"> <!-- If Needed Left and Right Padding in 'md' and 'lg' screen means use container class -->
            <div class="row">
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#">About</a>
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <img src="image.png" />
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#myModal1" data-toggle="modal">SHARE</a>
                </div>
            </div>
        </div>

Request header field Access-Control-Allow-Headers is not allowed by Access-Control-Allow-Headers

I had the same problem. In the jQuery documentation I found:

For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server.

So though the server allows cross origin request but does not allow Access-Control-Allow-Headers , it will throw errors. By default angular content type is application/json, which is trying to send a OPTION request. Try to overwrite angular default header or allow Access-Control-Allow-Headers in server end. Here is an angular sample:

$http.post(url, data, {
    headers : {
        'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
    }
});

NuGet: 'X' already has a dependency defined for 'Y'

In my case I had to delete the file NuGet.exe in the Project folder/.nuget and rebuild the project.

I also have in NuGet.targets the DownloadNuGetExe marked as true:

<DownloadNuGetExe Condition=" '$(DownloadNuGetExe)' == '' ">true</DownloadNuGetExe>

Hope it's helps.

Write to Windows Application Event Log

Yes, there is a way to write to the event log you are looking for. You don't need to create a new source, just simply use the existent one, which often has the same name as the EventLog's name and also, in some cases like the event log Application, can be accessible without administrative privileges*.

*Other cases, where you cannot access it directly, are the Security EventLog, for example, which is only accessed by the operating system.

I used this code to write directly to the event log Application:

using (EventLog eventLog = new EventLog("Application")) 
{
    eventLog.Source = "Application"; 
    eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1); 
}

As you can see, the EventLog source is the same as the EventLog's name. The reason of this can be found in Event Sources @ Windows Dev Center (I bolded the part which refers to source name):

Each log in the Eventlog key contains subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application or the name of a subcomponent of the application if the application is large. You can add a maximum of 16,384 event sources to the registry.

How do I format a date as ISO 8601 in moment.js?

Use format with no parameters:

var date = moment();
date.format(); // "2014-09-08T08:02:17-05:00"

(http://jsfiddle.net/8gvhL1dz/)

How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning?

One thing that happened for me is that the version of R provided by my linux distribution (R version 3.0.2 provided by Ubuntu 14.04) was too old for the latest version of the package available on CRAN (in my case, plyr version 1.8.3 as of today). The solution was to use the packaging system of my distribution instead of trying to install from R (apt-get install r-cran-plyr got me version 1.8.1 of plyr). Maybe I could have tried to update R using updateR(), but I'm afraid that doing so would interfere with my distribution's package manager.


Edit (04/08/2020): I recently had an issue with a package (XML) reportedly not available for my R version (3.6.3, latest supported on Debian stretch), after an update of the package in CRAN. It was very unexpected because I already had installed it with success before (on the same version of R and same OS).

For some reason, the package was still there, but install.packages was only looking at the updated (and incompatible) version. The solution was to find the URL of the compatible version and force install.packages to use it, as follows:

install.packages("https://cran.r-project.org/src/contrib/Archive/XML/XML_3.99-0.3.tar.gz", repos=NULL, type="source", ask=FALSE)

Bootstrap-select - how to fire event on change

When Bootstrap Select initializes, it'll build a set of custom divs that run alongside the original <select> element and will typically synchronize state between the two input mechanisms.

BS Select Elements

Which is to say that one way to handle events on bootstrap select is to listen for events on the original select that it modifies, regardless of who updated it.

Solution 1 - Native Events

Just listen for a change event and get the selected value using javascript or jQuery like this:

$('select').on('change', function(e){
  console.log(this.value,
              this.options[this.selectedIndex].value,
              $(this).find("option:selected").val(),);
});

*NOTE: As with any script reliant on the DOM, make sure you wait for the DOM ready event before executing

Demo in Stack Snippets:

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  $('select').on('change', function(e){_x000D_
    console.log(this.value,_x000D_
                this.options[this.selectedIndex].value,_x000D_
                $(this).find("option:selected").val(),);_x000D_
  });_x000D_
  _x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.css" rel="stylesheet"/>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.js"></script>_x000D_
_x000D_
<select class="selectpicker">_x000D_
  <option val="Must"> Mustard </option>_x000D_
  <option val="Cat" > Ketchup </option>_x000D_
  <option val="Rel" > Relish  </option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Solution 2 - Bootstrap Select Custom Events

As this answer alludes, Bootstrap Select has their own set of custom events, including changed.bs.select which:

fires after the select's value has been changed. It passes through event, clickedIndex, newValue, oldValue.

And you can use that like this:

$("select").on("changed.bs.select", 
      function(e, clickedIndex, newValue, oldValue) {
    console.log(this.value, clickedIndex, newValue, oldValue)
});

Demo in Stack Snippets:

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  $("select").on("changed.bs.select", _x000D_
        function(e, clickedIndex, newValue, oldValue) {_x000D_
      console.log(this.value, clickedIndex, newValue, oldValue)_x000D_
  });_x000D_
_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.css" rel="stylesheet"/>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.js"></script>_x000D_
_x000D_
<select class="selectpicker">_x000D_
  <option val="Must"> Mustard </option>_x000D_
  <option val="Cat" > Ketchup </option>_x000D_
  <option val="Rel" > Relish  </option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Return list from async/await method

You need to correct your code to wait for the list to be downloaded:

List<Item> list = await GetListAsync();

Also, make sure that the method, where this code is located, has async modifier.

The reason why you get this error is that GetListAsync method returns a Task<T> which is not a completed result. As your list is downloaded asynchronously (because of Task.Run()) you need to "extract" the value from the task using the await keyword.

If you remove Task.Run(), you list will be downloaded synchronously and you don't need to use Task, async or await.

One more suggestion: you don't need to await in GetListAsync method if the only thing you do is just delegating the operation to a different thread, so you can shorten your code to the following:

private Task<List<Item>> GetListAsync(){
    return Task.Run(() => manager.GetList());
}

"Untrusted App Developer" message when installing enterprise iOS Application

This issue comes when trust verification of app fails.

Screenshot 1

You can trust app from Settings shown in below images.

Screenshot 2

Screenshot 3

Screenshot 4

If this dosen't work then delete app and re-install it.

How to solve java.lang.OutOfMemoryError trouble in Android

You can't increase the heap size dynamically but you can request to use more by using.

android:largeHeap="true"

in the manifest.xml,you can add in your manifest these lines it is working for some situations.

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">

Whether your application's processes should be created with a large Dalvik heap. This applies to all processes created for the application. It only applies to the first application loaded into a process; if you're using a shared user ID to allow multiple applications to use a process, they all must use this option consistently or they will have unpredictable results. Most apps should not need this and should instead focus on reducing their overall memory usage for improved performance. Enabling this also does not guarantee a fixed increase in available memory, because some devices are constrained by their total available memory.


To query the available memory size at runtime, use the methods getMemoryClass() or getLargeMemoryClass().

If still facing problem then this should also work

 BitmapFactory.Options options = new BitmapFactory.Options();
 options.inSampleSize = 8;
 mBitmapInsurance = BitmapFactory.decodeFile(mCurrentPhotoPath,options);

If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory.

This is the optimal use of BitmapFactory.Options.inSampleSize with regards to speed of displaying the image. The documentation mentions using values that are a power of 2, so I am working with 2, 4, 8, 16 etc.

Lets get more deeper to Image Sampling:

For example, it’s not worth loading a 1024x768 pixel image into memory if it will eventually be displayed in a 128x128 pixel thumbnail in an ImageView.

To tell the decoder to subsample the image, loading a smaller version into memory, set inSampleSize to true in your BitmapFactory.Options object. For example, an image with resolution 2100 x 1500 pixels that is decoded with an inSampleSize of 4 produces a bitmap of approximately 512x384. Loading this into memory uses 0.75MB rather than 12MB for the full image (assuming a bitmap configuration of ARGB_8888). Here’s a method to calculate a sample size value that is a power of two based on a target width and height:

public static int calculateInSampleSize(
        BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

Note: A power of two value is calculated because the decoder uses a final value by rounding down to the nearest power of two, as per the inSampleSize documentation.

To use this method, first decode with inJustDecodeBounds set to true, pass the options through and then decode again using the new inSampleSize value and inJustDecodeBounds set to false:

public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
    int reqWidth, int reqHeight) {

    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(res, resId, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(res, resId, options);
}

This method makes it easy to load a bitmap of arbitrarily large size into an ImageView that displays a 100x100 pixel thumbnail, as shown in the following example code:

mImageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(), R.id.myimage, 100, 100));

You can follow a similar process to decode bitmaps from other sources, by substituting the appropriate BitmapFactory.decode* method as needed.


I found this code also interesting:

private Bitmap getBitmap(String path) {

Uri uri = getImageUri(path);
InputStream in = null;
try {
    final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
    in = mContentResolver.openInputStream(uri);

    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(in, null, o);
    in.close();

    int scale = 1;
    while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) > 
          IMAGE_MAX_SIZE) {
       scale++;
    }
    Log.d(TAG, "scale = " + scale + ", orig-width: " + o.outWidth + ", 
       orig-height: " + o.outHeight);

    Bitmap bitmap = null;
    in = mContentResolver.openInputStream(uri);
    if (scale > 1) {
        scale--;
        // scale to max possible inSampleSize that still yields an image
        // larger than target
        o = new BitmapFactory.Options();
        o.inSampleSize = scale;
        bitmap = BitmapFactory.decodeStream(in, null, o);

        // resize to desired dimensions
        int height = bitmap.getHeight();
        int width = bitmap.getWidth();
        Log.d(TAG, "1th scale operation dimenions - width: " + width + ",
           height: " + height);

        double y = Math.sqrt(IMAGE_MAX_SIZE
                / (((double) width) / height));
        double x = (y / height) * width;

        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, (int) x, 
           (int) y, true);
        bitmap.recycle();
        bitmap = scaledBitmap;

        System.gc();
    } else {
        bitmap = BitmapFactory.decodeStream(in);
    }
    in.close();

    Log.d(TAG, "bitmap size - width: " +bitmap.getWidth() + ", height: " + 
       bitmap.getHeight());
    return bitmap;
} catch (IOException e) {
    Log.e(TAG, e.getMessage(),e);
    return null;
}

How to Manage Your App's Memory: link


It's not a good idea to use android:largeHeap="true" here's the extract from google that explains it,

However, the ability to request a large heap is intended only for a small set of apps that can justify the need to consume more RAM (such as a large photo editing app). Never request a large heap simply because you've run out of memory and you need a quick fix—you should use it only when you know exactly where all your memory is being allocated and why it must be retained. Yet, even when you're confident your app can justify the large heap, you should avoid requesting it to whatever extent possible. Using the extra memory will increasingly be to the detriment of the overall user experience because garbage collection will take longer and system performance may be slower when task switching or performing other common operations.

After working excrutiatingly with out of memory errors i would say adding this to the manifest to avoid the oom issue is not a sin


Verifying App Behavior on the Android Runtime (ART)

The Android runtime (ART) is the default runtime for devices running Android 5.0 (API level 21) and higher. This runtime offers a number of features that improve performance and smoothness of the Android platform and apps. You can find more information about ART's new features in Introducing ART.

However, some techniques that work on Dalvik do not work on ART. This document lets you know about things to watch for when migrating an existing app to be compatible with ART. Most apps should just work when running with ART.


Addressing Garbage Collection (GC) Issues

Under Dalvik, apps frequently find it useful to explicitly call System.gc() to prompt garbage collection (GC). This should be far less necessary with ART, particularly if you're invoking garbage collection to prevent GC_FOR_ALLOC-type occurrences or to reduce fragmentation. You can verify which runtime is in use by calling System.getProperty("java.vm.version"). If ART is in use, the property's value is "2.0.0" or higher.

Furthermore, a compacting garbage collector is under development in the Android Open-Source Project (AOSP) to improve memory management. Because of this, you should avoid using techniques that are incompatible with compacting GC (such as saving pointers to object instance data). This is particularly important for apps that make use of the Java Native Interface (JNI). For more information, see Preventing JNI Issues.


Preventing JNI Issues

ART's JNI is somewhat stricter than Dalvik's. It is an especially good idea to use CheckJNI mode to catch common problems. If your app makes use of C/C++ code, you should review the following article:


Also, you can use native memory (NDK & JNI), so you actually bypass the heap size limitation.

Here are some posts made about it:

and here's a library made for it:

Is it possible to make Font Awesome icons larger than 'fa-5x'?

You can also define a scale transformation, with CSS like so:

.larger-icon {
 transform:scale(2);
}

Arduino Nano - "avrdude: ser_open():system can't open device "\\.\COM1": the system cannot find the file specified"

Changing the port in Device Manager works for me. I was also able to fix it by finding the port that Arduino was using and then select it from the Adruion IDE from tools menu Tools>Port>Com Port

Adruino IDE

Change the bullet color of list

Example JS Fiddle

Bullets take the color property of the list:

.listStyle {
    color: red;
}

Note if you want your list text to be a different colour, you have to wrap it in say, a p, for example:

.listStyle p {
    color: black;
}

Example HTML:

<ul class="listStyle">
    <li>
        <p><strong>View :</strong> blah blah.</p>
    </li>
    <li>
        <p><strong>View :</strong> blah blah.</p>
    </li>
</ul>

JSON ValueError: Expecting property name: line 1 column 2 (char 1)

  1. replace all single quotes with double quotes
  2. replace 'u"' from your strings to '"' ... so basically convert internal unicodes to strings before loading the string into json
>> strs = "{u'key':u'val'}"
>> strs = strs.replace("'",'"')
>> json.loads(strs.replace('u"','"'))

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

0. Is there any difference between the two errors?

Not really. "Cannot find symbol", "Cannot resolve symbol" and "Symbol not found" all mean the same thing. Different Java compilers use different phraseology.

1. What does a "Cannot find symbol" error mean?

Firstly, it is a compilation error1. It means that either there is a problem in your Java source code, or there is a problem in the way that you are compiling it.

Your Java source code consists of the following things:

  • Keywords: like true, false, class, while, and so on.
  • Literals: like 42 and 'X' and "Hi mum!".
  • Operators and other non-alphanumeric tokens: like +, =, {, and so on.
  • Identifiers: like Reader, i, toString, processEquibalancedElephants, and so on.
  • Comments and whitespace.

A "Cannot find symbol" error is about the identifiers. When your code is compiled, the compiler needs to work out what each and every identifier in your code means.

A "Cannot find symbol" error means that the compiler cannot do this. Your code appears to be referring to something that the compiler doesn't understand.

2. What can cause a "Cannot find symbol" error?

As a first order, there is only one cause. The compiler looked in all of the places where the identifier should be defined, and it couldn't find the definition. This could be caused by a number of things. The common ones are as follows:

  • For identifiers in general:

    • Perhaps you spelled the name incorrectly; i.e. StringBiulder instead of StringBuilder. Java cannot and will not attempt to compensate for bad spelling or typing errors.
    • Perhaps you got the case wrong; i.e. stringBuilder instead of StringBuilder. All Java identifiers are case sensitive.
    • Perhaps you used underscores inappropriately; i.e. mystring and my_string are different. (If you stick to the Java style rules, you will be largely protected from this mistake ...)
    • Perhaps you are trying to use something that was declared "somewhere else"; i.e. in a different context to where you have implicitly told the compiler to look. (A different class? A different scope? A different package? A different code-base?)
  • For identifiers that should refer to variables:

    • Perhaps you forgot to declare the variable.
    • Perhaps the variable declaration is out of scope at the point you tried to use it. (See example below)
  • For identifiers that should be method or field names:

    • Perhaps you are trying to refer to an inherited method or field that wasn't declared in the parent / ancestor classes or interfaces.

    • Perhaps you are trying to refer to a method or field that does not exist (i.e. has not been declared) in the type you are using; e.g. "someString".push()2.

    • Perhaps you are trying to use a method as a field, or vice versa; e.g. "someString".length or someArray.length().

    • Perhaps you are mistakenly operating on an array rather than array element; e.g.

          String strings[] = ...
          if (strings.charAt(3)) { ... }
          // maybe that should be 'strings[0].charAt(3)'
      
  • For identifiers that should be class names:

    • Perhaps you forgot to import the class.

    • Perhaps you used "star" imports, but the class isn't defined in any of the packages that you imported.

    • Perhaps you forgot a new as in:

          String s = String();  // should be 'new String()'
      
  • For cases where type or instance doesn't appear to have the member you were expecting it to have:

    • Perhaps you have declared a nested class or a generic parameter that shadows the type you were meaning to use.
    • Perhaps you are shadowing a static or instance variable.
    • Perhaps you imported the wrong type; e.g. due to IDE completion or auto-correction.
    • Perhaps you are using (compiling against) the wrong version of an API.
    • Perhaps you forgot to cast your object to an appropriate subclass.

The problem is often a combination of the above. For example, maybe you "star" imported java.io.* and then tried to use the Files class ... which is in java.nio not java.io. Or maybe you meant to write File ... which is a class in java.io.


Here is an example of how incorrect variable scoping can lead to a "Cannot find symbol" error:

List<String> strings = ...

for (int i = 0; i < strings.size(); i++) {
    if (strings.get(i).equalsIgnoreCase("fnord")) {
        break;
    }
}
if (i < strings.size()) {
    ...
}

This will give a "Cannot find symbol" error for i in the if statement. Though we previously declared i, that declaration is only in scope for the for statement and its body. The reference to i in the if statement cannot see that declaration of i. It is out of scope.

(An appropriate correction here might be to move the if statement inside the loop, or to declare i before the start of the loop.)


Here is an example that causes puzzlement where a typo leads to a seemingly inexplicable "Cannot find symbol" error:

for (int i = 0; i < 100; i++); {
    System.out.println("i is " + i);
}

This will give you a compilation error in the println call saying that i cannot be found. But (I hear you say) I did declare it!

The problem is the sneaky semicolon ( ; ) before the {. The Java language syntax defines a semicolon in that context to be an empty statement. The empty statement then becomes the body of the for loop. So that code actually means this:

for (int i = 0; i < 100; i++); 

// The previous and following are separate statements!!

{
    System.out.println("i is " + i);
}

The { ... } block is NOT the body of the for loop, and therefore the previous declaration of i in the for statement is out of scope in the block.


Here is another example of "Cannot find symbol" error that is caused by a typo.

int tmp = ...
int res = tmp(a + b);

Despite the previous declaration, the tmp in the tmp(...) expression is erroneous. The compiler will look for a method called tmp, and won't find one. The previously declared tmp is in the namespace for variables, not the namespace for methods.

In the example I came across, the programmer had actually left out an operator. What he meant to write was this:

int res = tmp * (a + b);

There is another reason why the compiler might not find a symbol if you are compiling from the command line. You might simply have forgotten to compile or recompile some other class. For example, if you have classes Foo and Bar where Foo uses Bar. If you have never compiled Bar and you run javac Foo.java, you are liable to find that the compiler can't find the symbol Bar. The simple answer is to compile Foo and Bar together; e.g. javac Foo.java Bar.java or javac *.java. Or better still use a Java build tool; e.g. Ant, Maven, Gradle and so on.

There are some other more obscure causes too ... which I will deal with below.

3. How do I fix these errors ?

Generally speaking, you start out by figuring out what caused the compilation error.

  • Look at the line in the file indicated by the compilation error message.
  • Identify which symbol that the error message is talking about.
  • Figure out why the compiler is saying that it cannot find the symbol; see above!

Then you think about what your code is supposed to be saying. Then finally you work out what correction you need to make to your source code to do what you want.

Note that not every "correction" is correct. Consider this:

for (int i = 1; i < 10; i++) {
    for (j = 1; j < 10; j++) {
        ...
    }
}

Suppose that the compiler says "Cannot find symbol" for j. There are many ways I could "fix" that:

  • I could change the inner for to for (int j = 1; j < 10; j++) - probably correct.
  • I could add a declaration for j before the inner for loop, or the outer for loop - possibly correct.
  • I could change j to i in the inner for loop - probably wrong!
  • and so on.

The point is that you need to understand what your code is trying to do in order to find the right fix.

4. Obscure causes

Here are a couple of cases where the "Cannot find symbol" is seemingly inexplicable ... until you look closer.

  1. Incorrect dependencies: If you are using an IDE or a build tool that manages the build path and project dependencies, you may have made a mistake with the dependencies; e.g. left out a dependency, or selected the wrong version. If you are using a build tool (Ant, Maven, Gradle, etc), check the project's build file. If you are using an IDE, check the project's build path configuration.

  2. You are not recompiling: It sometimes happens that new Java programmers don't understand how the Java tool chain works, or haven't implemented a repeatable "build process"; e.g. using an IDE, Ant, Maven, Gradle and so on. In such a situation, the programmer can end up chasing his tail looking for an illusory error that is actually caused by not recompiling the code properly, and the like ...

  3. An earlier build problem: It is possible that an earlier build failed in a way that gave a JAR file with missing classes. Such a failure would typically be noticed if you were using a build tool. However if you are getting JAR files from someone else, you are dependent on them building properly, and noticing errors. If you suspect this, use tar -tvf to list the contents of the suspect JAR file.

  4. IDE issues: People have reported cases where their IDE gets confused and the compiler in the IDE cannot find a class that exists ... or the reverse situation.

    • This could happen if the IDE has been configured with the wrong JDK version.

    • This could happen if the IDE's caches get out of sync with the file system. There are IDE specific ways to fix that.

    • This could be an IDE bug. For instance @Joel Costigliola describes a scenario where Eclipse does not handle a Maven "test" tree correctly: see this answer.

  5. Android issues: When you are programming for Android, and you have "Cannot find symbol" errors related to R, be aware that the R symbols are defined by the context.xml file. Check that your context.xml file is correct and in the correct place, and that the corresponding R class file has been generated / compiled. Note that the Java symbols are case sensitive, so the corresponding XML ids are be case sensitive too.

    Other symbol errors on Android are likely to be due to previously mention reasons; e.g. missing or incorrect dependencies, incorrect package names, method or fields that don't exist in a particular API version, spelling / typing errors, and so on.

  6. Redefining system classes: I've seen cases where the compiler complains that substring is an unknown symbol in something like the following

    String s = ...
    String s1 = s.substring(1);
    

    It turned out that the programmer had created their own version of String and that his version of the class didn't define a substring methods.

    Lesson: Don't define your own classes with the same names as common library classes!

  7. Homoglyphs: If you use UTF-8 encoding for your source files, it is possible to have identifiers that look the same, but are in fact different because they contain homoglyphs. See this page for more information.

    You can avoid this by restricting yourself to ASCII or Latin-1 as the source file encoding, and using Java \uxxxx escapes for other characters.


1 - If, perchance, you do see this in a runtime exception or error message, then either you have configured your IDE to run code with compilation errors, or your application is generating and compiling code .. at runtime.

2 - The three basic principles of Civil Engineering: water doesn't flow uphill, a plank is stronger on its side, and you can't push on a string.

PowerShell To Set Folder Permissions

Specifying inheritance in the FileSystemAccessRule() constructor fixes this, as demonstrated by the modified code below (notice the two new constuctor parameters inserted between "FullControl" and "Allow").

$Acl = Get-Acl "\\R9N2WRN\Share"

$Ar = New-Object System.Security.AccessControl.FileSystemAccessRule("user", "FullControl", "ContainerInherit,ObjectInherit", "None", "Allow")

$Acl.SetAccessRule($Ar)
Set-Acl "\\R9N2WRN\Share" $Acl

According to this topic

"when you create a FileSystemAccessRule the way you have, the InheritanceFlags property is set to None. In the GUI, this corresponds to an ACE with the Apply To box set to "This Folder Only", and that type of entry has to be viewed through the Advanced settings."

I have tested the modification and it works, but of course credit is due to the MVP posting the answer in that topic.

Failed to connect to mysql at 127.0.0.1:3306 with user root access denied for user 'root'@'localhost'(using password:YES)

Solution for me on Windows10:

  1. Go to Services and find the MYSQL service, than STOP it.
  2. Open Notepad and enter the following line:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPassword';

than save the file to the root of your hard drive (C:\ ). Choose a filename that makes sense, such as mysql-init.txt.

  1. Navigate to the MySQL directory using the command prompt (run as administrator):

cd "C:\Program Files\MySQL\MySQL Server 8.0\bin"

  1. Enter the following:

mysqld --init-file=C:\mysql-init.txt

  1. Now, you can log into your MySQL server as root using the new password and you can delete the C:\mysql-init.txt file.

  2. Go to Services and START your MYSQL service.

How to keep Docker container running after starting services?

you can run plain cat without any arguments as mentioned by bro @Sa'ad to simply keep the container working [actually doing nothing but waiting for user input] (Jenkins' Docker plugin does the same thing)

Nginx: stat() failed (13: permission denied)

I found a work around: Moved the folder to nginx configuration folder, in my case "/etc/nginx/my-web-app". And then changed the permissions to root user "sudo chown -R root:root "my-web-app".

Django: OperationalError No Such Table

I'm using Django CMS 3.4 with Django 1.8. I stepped through the root cause in the Django CMS code. Root cause is the Django CMS is not changing directory to the directory with file containing the SQLite3 database before making database calls. The error message is spurious. The underlying problem is that a SQLite database call is made in the wrong directory.

The workaround is to ensure all your Django applications change directory back to the Django Project root directory when changing to working directories.

Change color when hover a font awesome icon?

if you want to change only the colour of the flag on hover use this:

http://jsfiddle.net/uvamhedx/

_x000D_
_x000D_
.fa-flag:hover {_x000D_
    color: red;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<i class="fa fa-flag fa-3x"></i>
_x000D_
_x000D_
_x000D_

iOS 8 UITableView separator inset 0 not working

For iOS 9 you need to add:

if([myTableView respondsToSelector:@selector(setCellLayoutMarginsFollowReadableWidth:)])
{
    myTableView.cellLayoutMarginsFollowReadableWidth = NO;
} 

For more details please refer to question.

How/when to generate Gradle wrapper files?

If you want to download gradle with source and docs, the default distribution url configured in gradle-wrapper.properites will not satisfy your need.It is https://services.gradle.org/distributions/gradle-2.10-bin.zip, not https://services.gradle.org/distributions/gradle-2.10-all.zip.This full url is suggested by IDE such as Android Studio.If you want to download the full gradle,You can configure the wrapper task like this:

task wrapper(type: Wrapper) {
    gradleVersion = '2.13'
    distributionUrl = distributionUrl.replace("bin", "all")
}

How to remove a build from itunes connect?

I had this problem. I'll share my ride on the learning curve.

First, I couldn't find how to reject the binary but remembered seeing it earlier today in the iTunesConnect App. So using the App I rejected the binary.

If you "mouse over" the rejected binary under the "Build" section you'll notice that a red circle icon with a - (i.e. a delete button) appears. Tap on this and then hit the save button at the top of the screen. Submitted binary is now gone.

You should now get all the notifications for the app being in state "Prepare for Upload" (email, App notification etc).

Xcode organiser was still giving me "Redundant Binary". After a bit of research I now understand the difference between "Version" & "Build". Version is what iTunes displays and the user sees. Build is just the internal tracking number. I had both at 2.3.0, I changed build to 2.3.0.1 and re-Archive. Now it validates and I can upload the new binary and re-submit. Hope that helps others!

Spring Boot application.properties value not populating

If you're working in a large multi-module project, with several different application.properties files, then try adding your value to the parent project's property file.

If you are unsure which is your parent project, check your project's pom.xml file, for a <parent> tag.

This solved the issue for me.

Cannot create Maven Project in eclipse

It worked for = I just removed "archetypes" folder from below location

C:\Users\Lenovo.m2\repository\org\apache\maven

But you may change following for experiment - download latest binary zip of Maven, add to you C:\ drive and change following....

enter image description here

enter image description here

enter image description here

Change Proxy

 <proxy>
          <id>optional</id>
          <active>true</active>
          <protocol>http</protocol>
          <username></username>
          <password></password>
          <host>10.23.73.253</host>
          <port>8080</port>
          <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
        </proxy>

iOS8 Beta Ad-Hoc App Download (itms-services)

Specify a 'display-image' and 'full-size-image' as described here: http://www.informit.com/articles/article.aspx?p=1829415&seqNum=16

iOS8 requires these images

iPhone 6 and 6 Plus Media Queries

iPhone X

/* Portrait and Landscape */
@media only screen 
  and (min-device-width: 375px) 
  and (max-device-width: 812px) 
  and (-webkit-min-device-pixel-ratio: 3)
  /* uncomment for only portrait: */
  /* and (orientation: portrait) */
  /* uncomment for only landscape: */
  /* and (orientation: landscape) */ { 

}

iPhone 6+, 7+ and 8+

/* Portrait and Landscape */
@media only screen 
  and (min-device-width: 414px) 
  and (max-device-width: 736px) 
  and (-webkit-min-device-pixel-ratio: 3)
  /* uncomment for only portrait: */
  /* and (orientation: portrait) */
  /* uncomment for only landscape: */
  /* and (orientation: landscape) */ { 

}

iPhone 6, 6S, 7 and 8

/* Portrait and Landscape */
@media only screen 
  and (min-device-width: 375px) 
  and (max-device-width: 667px) 
  and (-webkit-min-device-pixel-ratio: 2)
  /* uncomment for only portrait: */
  /* and (orientation: portrait) */
  /* uncomment for only landscape: */
  /* and (orientation: landscape) */ { 

}

Source: Media Queries for Standard Devices

vagrant login as root by default

Solution:
Add the following to your Vagrantfile:

config.ssh.username = 'root'
config.ssh.password = 'vagrant'
config.ssh.insert_key = 'true'

When you vagrant ssh henceforth, you will login as root and should expect the following:

==> mybox: Waiting for machine to boot. This may take a few minutes...
    mybox: SSH address: 127.0.0.1:2222
    mybox: SSH username: root
    mybox: SSH auth method: password
    mybox: Warning: Connection timeout. Retrying...
    mybox: Warning: Remote connection disconnect. Retrying...
==> mybox: Inserting Vagrant public key within guest...
==> mybox: Key inserted! Disconnecting and reconnecting using new SSH key...
==> mybox: Machine booted and ready!

Update 23-Jun-2015: This works for version 1.7.2 as well. Keying security has improved since 1.7.0; this technique overrides back to the previous method which uses a known private key. This solution is not intended to be used for a box that is accessible publicly without proper security measures done prior to publishing.

Reference:

Bootstrap modal: is not a function

The problem happened to me just in production just because I imported jquery with HTTP and not HTTPS (and production is HTTPS)

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

(Cross-posting my answer from here: https://stackoverflow.com/a/25775147/798533)

For anybody looking for the resolution of the image to upload (if you want to create some fancy photoshop screenshots), they are:

  • iPhone 6: 750 × 1334
  • iPhone 6 Plus: 1242 × 2208

Good reference guide here: http://www.paintcodeapp.com/news/iphone-6-screens-demystified (talks about resolutions and downsampling of the iPhone 6+).

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

The answer is that older apps run in 2208 x 1242 Zoomed Mode. But when an app is built for the new phones the resolutions available are: Super Retina HD 5.8 (iPhone X) 1125 x 2436 (458ppi), Retina HD 5.5 (iPhone 6, 7, 8 Plus) 1242 x 2208 and Retina HD 4.7 (iPhone 6) 750 x 1334. This is causing the confusion mentioned in the question. To build apps that use the full screen size of the new phones add LaunchImages in the sizes: 1125 x 2436, 1242 x 2208, 2208 x 1242 and 750 x 1334.


Updated for the new iPhones 12, 12 mini, 12 Pro, 12 Pro Max

Size for iPhone 12 Pro Max with @3x scaling, coordinate space: 428 x 926 points and 1284 x 2778 pixels, 458 ppi, device physical size is 3.07 x 6.33 in or 78.1 x 160.8 mm. 6.7" Super Retina XDR display.

Size for iPhone 12 Pro with @3x scaling, coordinate space: 390 x 844 points and 1170 x 2532 pixels, 460 ppi, device physical size is 2.82 x 5.78 in or 71.5 x 146.7 mm. 6.1" Super Retina XDR display.

Size for iPhone 12 with @2x scaling, coordinate space: 585 x 1266 points and 1170 x 2532 pixels, 460 ppi, device physical size is 2.82 x 5.78 in or 71.5 x 146.7 mm. 6.1" Super Retina XDR display.

Size for iPhone 12 mini with @2x scaling, coordinate space: 540 x 1170 points and 1080 x 2340 pixels, 476 ppi, device physical size is 2.53 x 5.18 in or 64.2 x 131.5 mm. 5.4" Super Retina XDR display.


Size for iPhone 11 Pro Max with @3x scaling, coordinate space: 414 x 896 points and 1242 x 2688 pixels, 458 ppi, device physical size is 3.06 x 6.22 in or 77.8 x 158.0 mm. 6.5" Super Retina XDR display.

Size for iPhone 11 Pro with @3x scaling, coordinate space: 375 x 812 points and 1125 x 2436 pixels, 458 ppi, device physical size is 2.81 x 5.67 in or 71.4 x 144.0 mm. 5.8" Super Retina XDR display.

Size for iPhone 11 with @2x scaling, coordinate space: 414 x 896 points and 828 x 1792 pixels, 326 ppi, device physical size is 2.98 x 5.94 in or 75.7 x 150.9 mm. 6.1" Liquid Retina HD display.

Size for iPhone X Max with @3x scaling (Apple name: Super Retina HD 6.5 display"), coordinate space: 414 x 896 points and 1242 x 2688 pixels, 458 ppi, device physical size is 3.05 x 6.20 in or 77.4 x 157.5 mm.

let screen = UIScreen.main
print("Screen bounds: \(screen.bounds), Screen resolution: \(screen.nativeBounds), scale: \(screen.scale)")
//iPhone X Max Screen bounds: (0.0, 0.0, 414.0, 896.0), Screen resolution: (0.0, 0.0, 1242.0, 2688.0), scale: 3.0

Size for iPhone X with @2x scaling (Apple name: Super Retina HD 6.1" display), coordinate space: 414 x 896 points and 828 x 1792 pixels, 326 ppi, device physical size is 2.98 x 5.94 in or 75.7 x 150.9 mm.

let screen = UIScreen.main
print("Screen bounds: \(screen.bounds), Screen resolution: \(screen.nativeBounds), scale: \(screen.scale)")
//iPhone X Screen bounds: (0.0, 0.0, 414.0, 896.0), Screen resolution: (0.0, 0.0, 828.0, 1792.0), scale: 2.0

Size for iPhone X and iPhone X with @3x scaling (Apple name: Super Retina HD 5.8" display), coordinate space: 375 x 812 points and 1125 x 2436 pixels, 458 ppi, device physical size is 2.79 x 5.65 in or 70.9 x 143.6 mm.

let screen = UIScreen.main
print("Screen bounds: \(screen.bounds), Screen resolution: \(screen.nativeBounds), scale: \(screen.scale)")
//iPhone X and X Screen bounds: (0.0, 0.0, 375.0, 812.0), Screen resolution: (0.0, 0.0, 1125.0, 2436.0), scale: 3.0

enter image description here

Size for iPhone 6, 6S, 7 and 8 with @3x scaling (Apple name: Retina HD 5.5), coordinate space: 414 x 736 points and 1242 x 2208 pixels, 401 ppi, screen physical size is 2.7 x 4.8 in or 68 x 122 mm. When running in Zoomed Mode, i.e. without the new LaunchImages or choosen in Setup on iPhone 6 Plus, the native scale is 2.88 and the screen is 320 x 568 points, which is the iPhone 5 native size:

Screen bounds: {{0, 0}, {414, 736}}, Screen resolution: <UIScreen: 0x7f97fad330b0; bounds = {{0, 0}, {414, 736}};
mode = <UIScreenMode: 0x7f97fae1ce00; size = 1242.000000 x 2208.000000>>, scale: 3.000000, nativeScale: 3.000000

Size for iPhone 6 and iPhone 6S with @2x scaling (Apple name: Retina HD 4.7), coordinate space: 375 x 667 points and 750 x 1334 pixels, 326 ppi, screen physical size is 2.3 x 4.1 in or 58 x 104 mm. When running in Zoomed Mode, i.e. without the new LaunchImages, the screen is 320 x 568 points, which is the iPhone 5 native size:

Screen bounds: {{0, 0}, {375, 667}}, Screen resolution: <UIScreen: 0x7fa01b5182d0; bounds = {{0, 0}, {375, 667}};
mode = <UIScreenMode: 0x7fa01b711760; size = 750.000000 x 1334.000000>>, scale: 2.000000, nativeScale: 2.000000

And iPhone 5 for comparison is 640 x 1136, iPhone 4 640 x 960.


Here is the code I used to check this out (note that nativeScale only runs on iOS 8):

UIScreen *mainScreen = [UIScreen mainScreen];
NSLog(@"Screen bounds: %@, Screen resolution: %@, scale: %f, nativeScale: %f",
          NSStringFromCGRect(mainScreen.bounds), mainScreen.coordinateSpace, mainScreen.scale, mainScreen.nativeScale);

Note: Upload LaunchImages otherwise the app will run in Zoomed Mode and not show the correct scaling, or screen sizes. In Zoomed Mode the nativeScale and scale will not be the same. On an actual device the scale can be 2.608 on the iPhone 6 Plus, even when it is not running in Zoomed Mode, but it will show scale of 3.0 when running on the simulator.

Comparing iPhone 6 and 6 Plus

How to enable native resolution for apps on iPhone 6 and 6 Plus?

I didn't want to introduce an asset catalog.

Per the answer from seahorseseaeo here, adding the following to info.plist worked for me. (I edited it as a "source code".) I then named the images [email protected] and [email protected]

<key>UILaunchImages</key>
<array>
    <dict>
        <key>UILaunchImageMinimumOSVersion</key>
        <string>8.0</string>
        <key>UILaunchImageName</key>
        <string>Default-667h</string>
        <key>UILaunchImageOrientation</key>
        <string>Portrait</string>
        <key>UILaunchImageSize</key>
        <string>{375, 667}</string>
    </dict>
    <dict>
        <key>UILaunchImageMinimumOSVersion</key>
        <string>8.0</string>
        <key>UILaunchImageName</key>
        <string>Default-736h</string>
        <key>UILaunchImageOrientation</key>
        <string>Portrait</string>
        <key>UILaunchImageSize</key>
        <string>{414, 736}</string>
    </dict>
</array>

How to extract hours and minutes from a datetime.datetime object?

It's easier to use the timestamp for this things since Tweepy gets both

import datetime
print(datetime.datetime.fromtimestamp(int(t1)).strftime('%H:%M'))

tkinter: how to use after method

I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.

Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None))

Reading NFC Tags with iPhone 6 / iOS 8

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

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

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

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

Pandas: sum DataFrame rows for given columns

You can just sum and set param axis=1 to sum the rows, this will ignore none numeric columns:

In [91]:

df = pd.DataFrame({'a': [1,2,3], 'b': [2,3,4], 'c':['dd','ee','ff'], 'd':[5,9,1]})
df['e'] = df.sum(axis=1)
df
Out[91]:
   a  b   c  d   e
0  1  2  dd  5   8
1  2  3  ee  9  14
2  3  4  ff  1   8

If you want to just sum specific columns then you can create a list of the columns and remove the ones you are not interested in:

In [98]:

col_list= list(df)
col_list.remove('d')
col_list
Out[98]:
['a', 'b', 'c']
In [99]:

df['e'] = df[col_list].sum(axis=1)
df
Out[99]:
   a  b   c  d  e
0  1  2  dd  5  3
1  2  3  ee  9  5
2  3  4  ff  1  7

Partial Dependency (Databases)

  • consider a table={cid,sid,location}
  • candidate key: cidsid (uniquely identify the row)
  • prime attributes: cid and sid (attributes which are used in making of candidate key)
  • non-prime attribute: location(attribute other than candidate key)

if candidate key determine non-prime attribute:

i.e cidsid--->location (---->=determining) 
   then, it is fully functional dependent

if proper subset of candidate key determining non-prime attribute:

 i.e sid--->location (proper subset are sid and cid)
         then it is term as partial dependency

to remove partial dependency we divide the table accordingly .

Java 8: Difference between two LocalDateTime in multiple units

Joda-Time

Since many of the answers required API 26 support and my min API was 23, I solved it by below code :

import org.joda.time.Days

LocalDate startDate = Something
LocalDate endDate = Something
// The difference would be exclusive of both dates, 
// so in most of use cases we may need to increment it by 1
Days.daysBetween(startDate, endDate).days

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Changing the data type to text helped dataType: 'text'

I have check with JSONlint and my json format was proper. Still it was throwing error when I set dataType: 'json'

JSON Data: {"eventinvite":1,"groupcount":8,"totalMessagesUnread":0,"unreadmessages":{"378":0,"379":0,"380":0,"385":0,"390":0,"393":0,"413":0,"418":0}} 

java.net.BindException: Address already in use: JVM_Bind <null>:80

PID 0 is the System Idle Process, which is surely not listening to port 80. How did you check which process was using the port?

You can use

netstat /nao | findstr "80"

to find the PID and check what process it is.

How can I get key's value from dictionary in Swift?

From Apple Docs

You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:

https://developer.apple.com/documentation/swift/dictionary

if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."

How to run a cronjob every X minutes?

In a crontab file, the fields are:

  • minute of the hour.
  • hour of the day.
  • day of the month.
  • month of the year.
  • day of the week.

So:

10 * * * * blah

means execute blah at 10 minutes past every hour.

If you want every five minutes, use either:

*/5 * * * * blah

meaning every minute but only every fifth one, or:

0,5,10,15,20,25,30,35,40,45,50,55 * * * * blah

for older cron executables that don't understand the */x notation.

If it still seems to be not working after that, change the command to something like:

date >>/tmp/debug_cron_pax.txt

and monitor that file to ensure something's being written every five minutes. If so, there's something wrong with your PHP scripts. If not, there's something wrong with your cron daemon.

Select query to get data from SQL Server

That is by design.

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

Removing duplicate elements from an array in Swift

Swift 4.x:

extension Sequence where Iterator.Element: Hashable {
  func unique() -> [Iterator.Element] {
    return Array(Set<Iterator.Element>(self))
  }

  func uniqueOrdered() -> [Iterator.Element] {
    return reduce([Iterator.Element]()) { $0.contains($1) ? $0 : $0 + [$1] }
  }
}

usage:

["Ljubljana", "London", "Los Angeles", "Ljubljana"].unique()

or

["Ljubljana", "London", "Los Angeles", "Ljubljana"].uniqueOrdered()

Redirect echo output in shell script to logfile

You can add this line on top of your script:

#!/bin/bash
# redirect stdout/stderr to a file
exec &> logfile.txt

OR else to redirect only stdout use:

exec > logfile.txt

Python safe method to get value of nested dictionary

By combining all of these answer here and small changes that I made, I think this function would be useful. its safe, quick, easily maintainable.

def deep_get(dictionary, keys, default=None):
    return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("."), dictionary)

Example :

>>> from functools import reduce
>>> def deep_get(dictionary, keys, default=None):
...     return reduce(lambda d, key: d.get(key, default) if isinstance(d, dict) else default, keys.split("."), dictionary)
...
>>> person = {'person':{'name':{'first':'John'}}}
>>> print (deep_get(person, "person.name.first"))
John
>>> print (deep_get(person, "person.name.lastname"))
None
>>> print (deep_get(person, "person.name.lastname", default="No lastname"))
No lastname
>>>

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

<div style="display: flex;">
<div style="display: flex;">
 <img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>

If you're using a single element (e.g. dead-centered text in a single flex element) use the following:

align-items: center;
display: flex;
justify-content: center;

Trim whitespace from a String

Using a regex

#include <regex>
#include <string>

string trim(string s) {
    regex e("^\\s+|\\s+$");   // remove leading and trailing spaces
    return regex_replace(s, e, "");
}

Credit to: https://www.regular-expressions.info/examples.html for the regex

How do I convert a Swift Array to a String?

If you question is something like this: tobeFormattedString = ["a", "b", "c"] Output = "abc"

String(tobeFormattedString)

Using tr to replace newline with space

Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

or use:

tr '\r\n' ' '

Calling one method from another within same class in Python

To call the method, you need to qualify function with self.. In addition to that, if you want to pass a filename, add a filename parameter (or other name you want).

class MyHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        srcpath = event.src_path
        print (srcpath, 'has been ',event.event_type)
        print (datetime.datetime.now())
        filename = srcpath[12:]
        self.dropbox_fn(filename) # <----

    def dropbox_fn(self, filename):  # <-----
        print('In dropbox_fn:', filename)

Xcode process launch failed: Security

I had this issue before on Xcode 7 cause then i realized it's all about my internet connection it was down and the security check using the internet to make sure your developer account is correct. and when it see no internet it give this error … after i have fixed my internet it works good.

TransactionRequiredException Executing an update/delete query

After integrating Spring 4 with Hibernate 5 in my project and experiencing this problem, I found that I could prevent the error from appearing by changing the way of getting the session from sessionFactory.openSession() to sessionFactory.getCurrentSession(). the proper way to work out this bug may be keep using the same session for the binding transaction.opensession will always create a new session which doesnt like the former one holding a transaction configed.using getCurrentSession and adding additional property <property name="current_session_context_class">org.springframework.orm.hibernate5.SpringSessionContext</property> works fine for me.

pip is not able to install packages correctly: Permission denied error

It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied.

One thing you can try is doing a user install of the package with pip install lxml --user. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)

You can also run pip install as a superuser with sudo pip install lxml but it is not generally a good idea because it can cause issues with your system-level packages.

How to _really_ programmatically change primary and accent color in Android Lollipop?

from an activity you can do:

getWindow().setStatusBarColor(i color);

cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome

To stop seeing those cast_sender.js errors, edit the youtube link in the iframe src and change embed to v

Class 'ViewController' has no initializers in swift

The Swift Programming Language states:

Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.

You can set an initial value for a stored property within an initializer, or by assigning a default property value as part of the property’s definition.

Therefore, you can write:

class myClass {

    var delegate: AppDelegate //non-optional variable

    init() {
        delegate = UIApplication.sharedApplication().delegate as AppDelegate
    }

}

Or:

class myClass {

    var delegate = UIApplication.sharedApplication().delegate as AppDelegate //non-optional variable

    init() {
        println("Hello")
    }

}

Or:

class myClass {

    var delegate : AppDelegate! //implicitly unwrapped optional variable set to nil when class is initialized

    init() {
        println("Hello")
    }

    func myMethod() {
        delegate = UIApplication.sharedApplication().delegate as AppDelegate
    }

}

But you can't write the following:

class myClass {

    var delegate : AppDelegate //non-optional variable

    init() {
        println("Hello")
    }

    func myMethod() {
        //too late to assign delegate as an non-optional variable
        delegate = UIApplication.sharedApplication().delegate as AppDelegate
    }

}

Check if my SSL Certificate is SHA1 or SHA2

You can check by visiting the site in your browser and viewing the certificate that the browser received. The details of how to do that can vary from browser to browser, but generally if you click or right-click on the lock icon, there should be an option to view the certificate details.

In the list of certificate fields, look for one called "Certificate Signature Algorithm". (For StackOverflow's certificate, its value is "PKCS #1 SHA-1 With RSA Encryption".)

how to open .mat file without using MATLAB?

I didn't use it myself but heard of a simple tool (not a text editor) for this so it is definitely possible without setting up a programming environment (by installing octave or python).

A quick search hints that it was possible with total commander. (A lightweight tool with an easy point and click interface)

I would not be surprised if this still works, but I can't guarantee it.

How to Detect Browser Back Button event - Cross Browser

if (window.performance && window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
  alert('hello world');
}

This is the only one solution that worked for me (it's not a onepage website). It's working with Chrome, Firefox and Safari.

Android setOnClickListener method - How does it work?

its an implementation of anonymouse class object creation to give ease of writing less code and to save time

Converting Swagger specification JSON to HTML documentation

Everything was too difficult or badly documented so I solved this with a simple script swagger-yaml-to-html.py, which works like this

python swagger-yaml-to-html.py < /path/to/api.yaml > doc.html

This is for YAML but modifying it to work with JSON is also trivial.

Returning string from C function

word is on the stack and goes out of scope as soon as getStr() returns. You are invoking undefined behavior.

Iterate through 2 dimensional array

Simple idea: get the lenght of the longest row, iterate over each column printing the content of a row if it has elements. The below code might have some off-by-one errors as it was coded in a simple text editor.

  int longestRow = 0;
  for (int i = 0; i < array.length; i++) {
    if (array[i].length > longestRow) {
      longestRow = array[i].length;
    }
  }

  for (int j = 0; j < longestRow; j++) {
    for (int i = 0; i < array.length; i++) {
      if(array[i].length > j) {
        System.out.println(array[i][j]);
      }
    }
  }

Capture iOS Simulator video for App Preview

For Xcode 8.2 or later

You can take videos and screenshots of Simulator using the xcrun simctl, a command-line utility to control the Simulator

  1. Run your app on the simulator

  2. Open a terminal

  3. Run the command

    • To take a screenshot

      xcrun simctl io booted screenshot <filename>.<file extension>

      For example:

      xcrun simctl io booted screenshot myScreenshot.png

    • To take a video

      xcrun simctl io booted recordVideo <filename>.<file extension>

      For example:

      xcrun simctl io booted recordVideo appVideo.mov

  4. Press ctrl + C to stop recording the video.

The default location for the created file is the current directory.

Xcode 11.2 and later gives extra options.

From Xcode 11.2 Beta Release Notes

simctl video recording now produces smaller video files, supports HEIC compression, and takes advantage of hardware encoding support where available. In addition, the ability to record video on iOS 13, tvOS 13, and watchOS 6 devices has been restored.

You could use additional flags:

xcrun simctl io --help
Set up a device IO operation.
Usage: simctl io <device> <operation> <arguments>

...

    recordVideo [--codec=<codec>] [--display=<display>] [--mask=<policy>] [--force] <file or url>
        Records the display to a QuickTime movie at the specified file or url.
        --codec      Specifies the codec type: "h264" or "hevc". Default is "hevc".

        --display    iOS: supports "internal" or "external". Default is "internal".
                     tvOS: supports only "external"
                     watchOS: supports only "internal"

        --mask       For non-rectangular displays, handle the mask by policy:
                     ignored: The mask is ignored and the unmasked framebuffer is saved.
                     alpha: Not supported, but retained for compatibility; the mask is rendered black.
                     black: The mask is rendered black.

        --force      Force the output file to be written to, even if the file already exists.

    screenshot [--type=<type>] [--display=<display>] [--mask=<policy>] <file or url>
        Saves a screenshot as a PNG to the specified file or url(use "-" for stdout).
        --type       Can be "png", "tiff", "bmp", "gif", "jpeg". Default is png.

        --display    iOS: supports "internal" or "external". Default is "internal".
                     tvOS: supports only "external"
                     watchOS: supports only "internal"

                     You may also specify a port by UUID
        --mask       For non-rectangular displays, handle the mask by policy:
                     ignored: The mask is ignored and the unmasked framebuffer is saved.
                     alpha: The mask is used as premultiplied alpha.
                     black: The mask is rendered black.

Now you can take a screenshot in jpeg, with mask (for non-rectangular displays) and some other flags:

xcrun simctl io booted screenshot --type=jpeg --mask=black screenshot.jpeg

How to pass in a react component into another react component to transclude the first component's content?

You can use this.props.children to render whatever children the component contains:

const Wrap = ({ children }) => <div>{children}</div>

export default () => <Wrap><h1>Hello word</h1></Wrap>

How to check if input file is empty in jQuery

  $("#customFile").change(function() { 
    var fileName = $("#customFile").val();  

    if(fileName) { // returns true if the string is not empty   
        $('.picture-selected').addClass('disable-inputs'); 
        $('#btn').removeClass('disabled');   
    } else { // no file was selected 
      $('.picture-selected').removeClass('disable-inputs'); 
      $('#btn').addClass('disabled');
    }  
  });

Difference between using Makefile and CMake to compile the code

Make (or rather a Makefile) is a buildsystem - it drives the compiler and other build tools to build your code.

CMake is a generator of buildsystems. It can produce Makefiles, it can produce Ninja build files, it can produce KDEvelop or Xcode projects, it can produce Visual Studio solutions. From the same starting point, the same CMakeLists.txt file. So if you have a platform-independent project, CMake is a way to make it buildsystem-independent as well.

If you have Windows developers used to Visual Studio and Unix developers who swear by GNU Make, CMake is (one of) the way(s) to go.

I would always recommend using CMake (or another buildsystem generator, but CMake is my personal preference) if you intend your project to be multi-platform or widely usable. CMake itself also provides some nice features like dependency detection, library interface management, or integration with CTest, CDash and CPack.

Using a buildsystem generator makes your project more future-proof. Even if you're GNU-Make-only now, what if you later decide to expand to other platforms (be it Windows or something embedded), or just want to use an IDE?

Fill formula down till last row in column

For people with a similar question and find this post (like I did); you can do this even without lastrow if your dataset is formatted as a table.

Range("tablename[columnname]").Formula = "=G3&"",""&L3"

Making it a true one liner. Hope it helps someone!

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

Build not visible in itunes connect

This worked for me

If build are missing from Itunes 'Activity' tab. Then check your info.plist keys. If all keys are there, then check all keys description. if their length is short then increase your keys description length.

Image resolution for new iPhone 6 and 6+, @3x support added?

I've tried in a sample project to use standard, @2x and @3x images, and the iPhone 6+ simulator uses the @3x image. So it would seem that there are @3x images to be done (if the simulator actually replicates the device's behavior). But the strange thing is that all devices (simulators) seem to use this @3x image when it's on the project structure, iPhone 4S/iPhone 5 too.
The lack of communication from Apple on a potential @3x structure, while they ask developers to publish their iOS8 apps is quite confusing, especially when seeing those results on simulator.

**Edit from Apple's Website **: Also found this on the "What's new on iOS 8" section on Apple's developer space :

Support for a New Screen Scale The iPhone 6 Plus uses a new Retina HD display with a screen scale of 3.0. To provide the best possible experience on these devices, include new artwork designed for this screen scale. In Xcode 6, asset catalogs can include images at 1x, 2x, and 3x sizes; simply add the new image assets and iOS will choose the correct assets when running on an iPhone 6 Plus. The image loading behavior in iOS also recognizes an @3x suffix.

Still not understanding why all devices seem to load the @3x. Maybe it's because I'm using regular files and not xcassets ? Will try soon.

Edit after further testing : Ok it seems that iOS8 has a talk in this. When testing on an iOS 7.1 iPhone 5 simulator, it uses correctly the @2x image. But when launching the same on iOS 8 it uses the @3x on iPhone 5. Not sure if that's a wanted behavior or a mistake/bug in iOS8 GM or simulators in Xcode 6 though.

Xamarin.Forms ListView: Set the highlight color of a tapped item

Found this lovely option using effects here.

iOS:

[assembly: ResolutionGroupName("MyEffects")]
[assembly: ExportEffect(typeof(ListViewHighlightEffect), nameof(ListViewHighlightEffect))]
namespace Effects.iOS.Effects
{
    public class ListViewHighlightEffect : PlatformEffect
    {
        protected override void OnAttached()
        {
            var listView = (UIKit.UITableView)Control;

            listView.AllowsSelection = false;
        }

        protected override void OnDetached()
        {
        }
    }
}

Android:

[assembly: ResolutionGroupName("MyEffects")]
[assembly: ExportEffect(typeof(ListViewHighlightEffect), nameof(ListViewHighlightEffect))]
namespace Effects.Droid.Effects
{
    public class ListViewHighlightEffect : PlatformEffect
    {
        protected override void OnAttached()
        {
            var listView = (Android.Widget.ListView)Control;

            listView.ChoiceMode = ChoiceMode.None;
        }

        protected override void OnDetached()
        {
        }
    }
}

Forms:

ListView_Demo.Effects.Add(Effect.Resolve($"MyEffects.ListViewHighlightEffect"));

iOS 8 Snapshotting a view that has not been rendered results in an empty snapshot

I found the same issue and tried everything. I have two different apps, one in objective-C and one in swift - both have the same problem. The error message comes in the debugger and the screen goes black after the first photo. This only happens in iOS >= 8.0, obviously it is a bug.

I found a difficult workaround. Shut off the camera controls with imagePicker.showsCameraControls = false and create your own overlayView that has the missing buttons. There are various tutorials around how to do this. The strange error message stays, but at least the screen doesn't go black and you have a working app.

How to use jquery $.post() method to submit form values

You have to select and send the form data as well:

$("#post-btn").click(function(){        
    $.post("process.php", $("#reg-form").serialize(), function(data) {
        alert(data);
    });
});

Take a look at the documentation for the jQuery serialize method, which encodes the data from the form fields into a data-string to be sent to the server.

How do I use Join-Path to combine more than two strings into a file path?

Or you could write your own function for it (which is what I ended up doing).

function Join-Path-Recursively($PathParts) {
    $NumberOfPathParts = $PathParts.Length;

    if ($NumberOfPathParts -eq 0) {
        return $null
    } elseif ($NumberOfPathParts -eq 1) {
        return $PathParts[0]
    } else {
        return Join-Path -Path $PathParts[0] -ChildPath $(Join-Path-Recursively -PathParts $PathParts[1..($NumberOfPathParts-1)])
    }
}

You could then call the function like this:

Join-Path-Recursively -PathParts  @("C:", "Program Files", "Microsoft Office")
Join-Path-Recursively  @("C:", "Program Files", "Microsoft Office")

This has the advantage of having the exact same behaviour as the normal Join-Path function and not depending on the .NET Framework.

Error:java: invalid source release: 8 in Intellij. What does it mean?

For Gradle users having this issues, if nothing above helps this is what solved my problem - apply this declarations in your build.gradle files:

targetCompatibility = 1.6 //or 1.7;1.8 and so on
sourceCompatibility = 1.6 //or 1.7;1.8 and so on

Problem solved!

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

Comparing the contents of two files in Sublime Text

You can actually compare files natively right in Sublime Text.

  1. Navigate to the folder containing them through Open Folder... or in a project
  2. Select the two files (ie, by holding Ctrl on Windows or ? on macOS) you want to compare in the sidebar
  3. Right click and select the Diff files... option.

How to put scroll bar only for modal-body?

In your modal body you have to set a height, it can be % vh or calc:

modal-body {
    height: 80vh;
    overflow-x: auto;
}

or

modal-body {
    height: calc(100vh - 5em);
    overflow-x: auto;
}

In my case look like: enter image description here

How to square or raise to a power (elementwise) a 2D numpy array?

The fastest way is to do a*a or a**2 or np.square(a) whereas np.power(a, 2) showed to be considerably slower.

np.power() allows you to use different exponents for each element if instead of 2 you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2 or a*a, which become important in cases where you have small tolerances.

I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:

In [29]: a = np.random.random((1000, 1000))

In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop

In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop

In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop

Classpath resource not found when running as jar

I was facing same error

InputStream inputStream = new ClassPathResource("filename.ext").inputStream();

this should solve FileNotFoundException while running

Field 'id' doesn't have a default value?

I landed this question in 2019. MY problem was updating table1 with table2 ignoring the variables with different name in both tables. I was getting the same error as mentioned in question: Error Code: 1364. Field 'id' doesn't have a default value in mysql. Here is how solved it:

Table 1 Schema : id ( unique & auto increment)| name | profile | Age Table 2 Schema: motherage| father| name| profile

This solved my error: INSERT IGNORE INTO table2 (name,profile) SELECT name, profile FROM table1

Android Activity without ActionBar

If you're using AppCompat, declare your activity in AndroidManifest.xml as follows:

<activity
    android:name=".SomeActivity"
    ...
    android:theme="@style/Theme.AppCompat.Light.NoActionBar" />

Turn off axes in subplots

You can turn the axes off by following the advice in Veedrac's comment (linking to here) with one small modification.

Rather than using plt.axis('off') you should use ax.axis('off') where ax is a matplotlib.axes object. To do this for your code you simple need to add axarr[0,0].axis('off') and so on for each of your subplots.

The code below shows the result (I've removed the prune_matrix part because I don't have access to that function, in the future please submit fully working code.)

import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.cm as cm

img = mpimg.imread("stewie.jpg")

f, axarr = plt.subplots(2, 2)
axarr[0,0].imshow(img, cmap = cm.Greys_r)
axarr[0,0].set_title("Rank = 512")
axarr[0,0].axis('off')

axarr[0,1].imshow(img, cmap = cm.Greys_r)
axarr[0,1].set_title("Rank = %s" % 128)
axarr[0,1].axis('off')

axarr[1,0].imshow(img, cmap = cm.Greys_r)
axarr[1,0].set_title("Rank = %s" % 32)
axarr[1,0].axis('off')

axarr[1,1].imshow(img, cmap = cm.Greys_r)
axarr[1,1].set_title("Rank = %s" % 16)
axarr[1,1].axis('off')

plt.show()

Stewie example

Note: To turn off only the x or y axis you can use set_visible() e.g.:

axarr[0,0].xaxis.set_visible(False) # Hide only x axis

How can I align button in Center or right using IONIC framework?

center tag aligns the buttons within it as expected:  

<ion-footer>
    <ion-toolbar>
        <center>
            <button royal>
                Contacts
                <ion-icon name="contact"></ion-icon>
            </button>
            <button secondary>
                Receive
                <ion-icon name="arrow-round-back"></ion-icon>
            </button>
            <button danger>
                Wallet
                <ion-icon name="home"></ion-icon>
            </button>
            <button secondary>
                Send
                <ion-icon name="send"></ion-icon>
            </button>
            <button danger>
                Transactions
                <ion-icon name="archive"></ion-icon>
            </button>
            <button danger>
                About
                <ion-icon name="information-circle"></ion-icon>
            </button>
        </center>
    </ion-toolbar>
</ion-footer>

How do I set response headers in Flask?

You can do this pretty easily:

@app.route("/")
def home():
    resp = flask.Response("Foo bar baz")
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

Look at flask.Response and flask.make_response()

But something tells me you have another problem, because the after_request should have handled it correctly too.

EDIT
I just noticed you are already using make_response which is one of the ways to do it. Like I said before, after_request should have worked as well. Try hitting the endpoint via curl and see what the headers are:

curl -i http://127.0.0.1:5000/your/endpoint

You should see

> curl -i 'http://127.0.0.1:5000/'
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 11
Access-Control-Allow-Origin: *
Server: Werkzeug/0.8.3 Python/2.7.5
Date: Tue, 16 Sep 2014 03:47:13 GMT

Noting the Access-Control-Allow-Origin header.

EDIT 2
As I suspected, you are getting a 500 so you are not setting the header like you thought. Try adding app.debug = True before you start the app and try again. You should get some output showing you the root cause of the problem.

For example:

@app.route("/")
def home():
    resp = flask.Response("Foo bar baz")
    user.weapon = boomerang
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

Gives a nicely formatted html error page, with this at the bottom (helpful for curl command)

Traceback (most recent call last):
...
  File "/private/tmp/min.py", line 8, in home
    user.weapon = boomerang
NameError: global name 'boomerang' is not defined

Trying to make bootstrap modal wider

You could try:

.modal.modal-wide .modal-dialog {
  width: 90%;
}

.modal-wide .modal-body {
  overflow-y: auto;
}

Just add .modal-wide to your classes

Eclipse Java error: This selection cannot be launched and there are no recent launches

When you create a new class file, try to mark the check box near

public static void main(String[] args) {

this will help you to fix the problem.