Programs & Examples On #Miglayout

MiG Layout is a free and open-source layout manager for Java Swing, SWT, JavaFX2, Fantom, Qt and other GUI toolkits.

Eclipse Bug: Unhandled event loop exception No more handles

As suggested by Nineroad Installing WindowBuilder as the default editor for files with a *.java extention fixed this issue for me.

In Eclipse, navigate to Help > Install New Software

Add http://archive.eclipse.org/windowbuilder/WB/release/R201309271200/4.3 to the "Work with" path, select all components suggested, and install WindowBuilder.

Once complete, Eclipse will request restart. Once restarted, within Eclipse navigate to Window > Preferences. In The Preferences dialogue-box navigate to General > Editor > File Associations. Under "File Associations" list, be sure to select *.java file types. The bottom window (labeled "Associated Editors") should have WindowBuilder as an option. Select WindowBuilder and click "Default" to the right, to set WindowBuilder as your default *.java file editor.

This fixed the SWT error for me.

Note: Eclipse Version: Kepler Service Release 2 Windows 7 64-bit

How to resize JLabel ImageIcon?

This will keep the right aspect ratio.

    public ImageIcon scaleImage(ImageIcon icon, int w, int h)
    {
        int nw = icon.getIconWidth();
        int nh = icon.getIconHeight();

        if(icon.getIconWidth() > w)
        {
          nw = w;
          nh = (nw * icon.getIconHeight()) / icon.getIconWidth();
        }

        if(nh > h)
        {
          nh = h;
          nw = (icon.getIconWidth() * nh) / icon.getIconHeight();
        }

        return new ImageIcon(icon.getImage().getScaledInstance(nw, nh, Image.SCALE_DEFAULT));
    }

When is it appropriate to use UDP instead of TCP?

Comparing TCP with UDP, connection-less protocols like UDP assure speed, but not reliability of packet transmission. For example in video games typically don't need a reliable network but the speed is the most important and using UDP for games has the advantage of reducing network delay.

enter image description here

How can I apply a function to every row/column of a matrix in MATLAB?

Many built-in operations like sum and prod are already able to operate across rows or columns, so you may be able to refactor the function you are applying to take advantage of this.

If that's not a viable option, one way to do it is to collect the rows or columns into cells using mat2cell or num2cell, then use cellfun to operate on the resulting cell array.

As an example, let's say you want to sum the columns of a matrix M. You can do this simply using sum:

M = magic(10);           %# A 10-by-10 matrix
columnSums = sum(M, 1);  %# A 1-by-10 vector of sums for each column

And here is how you would do this using the more complicated num2cell/cellfun option:

M = magic(10);                  %# A 10-by-10 matrix
C = num2cell(M, 1);             %# Collect the columns into cells
columnSums = cellfun(@sum, C);  %# A 1-by-10 vector of sums for each cell

Is it possible to style html5 audio tag?

Missing the most important one IMO the container for the controls ::-webkit-media-controls-enclosure:

&::-webkit-media-controls-enclosure {
    border-radius: 5px;
    background-color: green;
}

Failed to build gem native extension (installing Compass)

Try brew install coreutils.

I've hit this problem while rebuilding an aging sass/compass project that was recently updated to ruby 2.2.5 by a colleague. The project uses rvm and bundler. These were my commands

$ rvm install ruby-2.2.5
$ rvm use ruby-2.2.5
$ gem install bundler
$ bundle install

This caused me to hit the famed ffi installation errors, that are reported around the StackOverflow environment:

An error occurred while installing ffi (1.9.14), and Bundler cannot continue.

Most of the suggestions to solve this problem are to install Xcode command line tools. However this was already installed in my environment:

$ xcode-select -p
/Library/Developer/CommandLineTools

Other suggestions said to install gcc... so I tried:

$ brew install gcc46

But this also failed due to a segmentation fault... ¯\_(?)_/¯.

So, I then tried installing compass by hand, just to see if it would give the same ffi error:

$ gem install compass

But to my surprise, I got a totally different error:

make: /usr/local/bin/gmkdir: No such file or directory

So I searched for that issue, and found this ancient blog post that said to install coreutils:

$ brew install coreutils

After installing coreutils with Homebrew, bundler was able to finish and installed compass and dependencies successfully.

The End.

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

Here's one which i just wrote this morning based on pretty much the same math as above:

/* math adapted from: http://www.rapidtables.com/convert/color/rgb-to-hsl.htm
 * reasonably optimized for speed, without going crazy */
void rgb_to_hsv (int r, int g, int b, float *r_h, float *r_s, float *r_v) {
  float rp, gp, bp, cmax, cmin, delta, l;
  int cmaxwhich, cminwhich;

  rp = ((float) r) / 255;
  gp = ((float) g) / 255;
  bp = ((float) b) / 255;

  //debug ("rgb=%d,%d,%d rgbprime=%f,%f,%f", r, g, b, rp, gp, bp);

  cmax = rp;
  cmaxwhich = 0; /* faster comparison afterwards */
  if (gp > cmax) { cmax = gp; cmaxwhich = 1; }
  if (bp > cmax) { cmax = bp; cmaxwhich = 2; }
  cmin = rp;
  cminwhich = 0;
  if (gp < cmin) { cmin = gp; cminwhich = 1; }
  if (bp < cmin) { cmin = bp; cminwhich = 2; }

  //debug ("cmin=%f,cmax=%f", cmin, cmax);
  delta = cmax - cmin;

  /* HUE */
  if (delta == 0) {
    *r_h = 0;
  } else {
    switch (cmaxwhich) {
      case 0: /* cmax == rp */
        *r_h = HUE_ANGLE * (fmod ((gp - bp) / delta, 6));
      break;

      case 1: /* cmax == gp */
        *r_h = HUE_ANGLE * (((bp - rp) / delta) + 2);
      break;

      case 2: /* cmax == bp */
        *r_h = HUE_ANGLE * (((rp - gp) / delta) + 4);
      break;
    }
    if (*r_h < 0)
      *r_h += 360;
  }

  /* LIGHTNESS/VALUE */
  //l = (cmax + cmin) / 2;
  *r_v = cmax;

  /* SATURATION */
  /*if (delta == 0) {
    *r_s = 0;
  } else {
    *r_s = delta / (1 - fabs (1 - (2 * (l - 1))));
  }*/
  if (cmax == 0) {
    *r_s = 0;
  } else {
    *r_s = delta / cmax;
  }
  //debug ("rgb=%d,%d,%d ---> hsv=%f,%f,%f", r, g, b, *r_h, *r_s, *r_v);
}


void hsv_to_rgb (float h, float s, float v, int *r_r, int *r_g, int *r_b) {
  if (h > 360)
    h -= 360;
  if (h < 0)
    h += 360;
  h = CLAMP (h, 0, 360);
  s = CLAMP (s, 0, 1);
  v = CLAMP (v, 0, 1);
  float c = v * s;
  float x = c * (1 - fabsf (fmod ((h / HUE_ANGLE), 2) - 1));
  float m = v - c;
  float rp, gp, bp;
  int a = h / 60;

  //debug ("h=%f, a=%d", h, a);

  switch (a) {
    case 0:
      rp = c;
      gp = x;
      bp = 0;
    break;

    case 1:
      rp = x;
      gp = c;
      bp = 0;
    break;

    case 2:
      rp = 0;
      gp = c;
      bp = x;
    break;

    case 3:
      rp = 0;
      gp = x;
      bp = c;
    break;

    case 4:
      rp = x;
      gp = 0;
      bp = c;
    break;

    default: // case 5:
      rp = c;
      gp = 0;
      bp = x;
    break;
  }

  *r_r = (rp + m) * 255;
  *r_g = (gp + m) * 255;
  *r_b = (bp + m) * 255;

  //debug ("hsv=%f,%f,%f, ---> rgb=%d,%d,%d", h, s, v, *r_r, *r_g, *r_b);
}

WPF MVVM ComboBox SelectedItem or SelectedValue not working

You need to put the ItemsSource property BEFORE the SelectedItem property. I came across a blog a few days ago mentioning the issue.

Using reflection in Java to create a new instance with the reference variable type set to the new instance class name?

As an addendum to akf's answer you could use instanceof checks instead of String equals() calls:

String cname="com.some.vendor.Impl";
try {
  Class c=this.getClass().getClassLoader().loadClass(cname);
  Object o= c.newInstance();
  if(o instanceof Spam) {
    Spam spam=(Spam) o;
    process(spam);
  }
  else if(o instanceof Ham) {
    Ham ham = (Ham) o;
    process(ham);
  }
  /* etcetera */
}
catch(SecurityException se) {
  System.err.printf("Someone trying to game the system?%nOr a rename is in order because this JVM doesn't feel comfortable with: “%s”", cname);
  se.printStackTrace();
}
catch(LinkageError le) {
  System.err.printf("Seems like a bad class to this JVM: “%s”.", cname);
  le.printStackTrace();
}
catch(RuntimeException re) { 
  // runtime exceptions I might have forgotten. Classloaders are wont to produce those.
  re.printStackTrace();
}
catch(Exception e) { 
  e.printStackTrace();
}

Note the liberal hardcoding of some values. Anyways the main points are:

  1. Use instanceof rather than equals(). If anything, it will co-operate better when refactoring.
  2. Be sure to catch these runtime errors and security ones too.

Picking a random element from a set

Javascript solution ;)

function choose (set) {
    return set[Math.floor(Math.random() * set.length)];
}

var set  = [1, 2, 3, 4], rand = choose (set);

Or alternatively:

Array.prototype.choose = function () {
    return this[Math.floor(Math.random() * this.length)];
};

[1, 2, 3, 4].choose();

Repeat a string in JavaScript a number of times

I'm going to expand on @bonbon's answer. His method is an easy way to "append N chars to an existing string", just in case anyone needs to do that. For example since "a google" is a 1 followed by 100 zeros.

_x000D_
_x000D_
for(var google = '1'; google.length < 1 + 100; google += '0'){}_x000D_
document.getElementById('el').innerText = google;
_x000D_
<div>This is "a google":</div>_x000D_
<div id="el"></div>
_x000D_
_x000D_
_x000D_

NOTE: You do have to add the length of the original string to the conditional.

Can't update: no tracked branch

So after reading a bit on how git sets up the repo. I realized that I ran the command

git push origin master

but instead for the first time I should have ran

git push -u origin master

which sets up the upstream initially. Way to go!

Visual Studio Expand/Collapse keyboard shortcuts

Visual Studio 2015:

Tools > Options > Settings > Environment > Keyboard

Defaults:

Edit.CollapsetoDefinitions: CTRL + M + O

Edit.CollapseCurrentRegion: CTRL + M +CTRL + S

Edit.ExpandAllOutlining: CTRL + M + CTRL + X

Edit.ExpandCurrentRegion: CTRL + M + CTRL + E

I like to set and use IntelliJ's shortcuts:

Edit.CollapsetoDefinitions: CTRL + SHIFT + NUM-

Edit.CollapseCurrentRegion: CTRL + NUM-

Edit.ExpandAllOutlining: CTRL + SHIFT + NUM+

Edit.ExpandCurrentRegion: CTRL + NUM+

CSS getting text in one line rather than two

Add white-space: nowrap;:

.garage-title {
    clear: both;
    display: inline-block;
    overflow: hidden;
    white-space: nowrap;
}

jsFiddle

Concat all strings inside a List<string> using LINQ

Good question. I've been using

List<string> myStrings = new List<string>{ "ours", "mine", "yours"};
string joinedString = string.Join(", ", myStrings.ToArray());

It's not LINQ, but it works.

Cannot open Windows.h in Microsoft Visual Studio

If you are targeting Windows XP (v140_xp), try installing Windows XP Support for C++.

Starting with Visual Studio 2012, the default toolset (v110) dropped support for Windows XP. As a result, a Windows.h error can occur if your project is targeting Windows XP with the default C++ packages.

Check which Windows SDK version is specified in your project's Platform Toolset. (Project ? Properties ? Configuration Properties ? General). If your Toolset ends in _xp, you'll need to install XP support.

Visual Studio: Project toolset

Open the Visual Studio Installer and click Modify for your version of Visual Studio. Open the Individual Components tab and scroll down to Compilers, build tools, and runtimes. Near the bottom, check Windows XP support for C++ and click Modify to begin installing.

Visual Studio Installer: XP Support for C++

See Also:

error while loading shared libraries: libncurses.so.5:

Mixaz's above answer worked for me. However I had issues installing the package because of PGP check failures. Installing it by skipping the signature worked, you could try this :

yaourt --m-arg "--skipchecksums --skippgpcheck" -Sb <your-package>

How do I iterate through children elements of a div using jQuery?

It is also possible to iterate through all elements within a specific context, no mattter how deeply nested they are:

$('input', $('#mydiv')).each(function () {
    console.log($(this)); //log every element found to console output
});

The second parameter $('#mydiv') which is passed to the jQuery 'input' Selector is the context. In this case the each() clause will iterate through all input elements within the #mydiv container, even if they are not direct children of #mydiv.

SVN Error - Not a working copy

Could it be a working copy format mismatch? It changed between svn 1.4 and 1.5 and newer tools automatically convert the format, but then the older ones no longer work with the converted copy.

Android Debug Bridge (adb) device - no permissions

The cause of that problem has to do with system permissions (thanks @ IsaacCisneros for this suggestion). Somehow HTC Wildfire (and maybe the others) need something more from the system than Samsung devices. Simple solution is to run Eclipse as a root, but this is not very comfortable with non-sudo Linux systems like Fedora.

I've found another way of achieving the same goal, which seems to be more user friendly and is lesser security hole then running entire IDE with super user privileges. Mind this is still only a workaround of the problem. System root usage should be minimalized only to administrative tasks, and “adb” was designed to work with normal user account without SUID. Despite of the fact that the proper setting of SUID is quite secure, every single permission increase is a potential system security hole.

1.Setting ownership of the adb binary (owner – root, owner group - user_group):

chown root:user_group adb

2.Setting permissions with SUID:

chmod 4550 adb

This should result something similar to this (ls -llh):

-r-sr-x---. 1 root user_name 1.2M Jan 8 11:42 adb

After that you will be able to run adb as a root, event though you'll be using your normal user account. You can run Eclipse as a normal user and your HTC should be discovered properly.

./adb devices 
List of devices attached 
HT0BPPY15230    device 

Chrome net::ERR_INCOMPLETE_CHUNKED_ENCODING error

This seems like a common problem with multiple causes and solutions, so I'm going to put my answer here for anyone who may require it.

I was getting net::ERR_INCOMPLETE_CHUNKED_ENCODING on Chrome, osx, php70, httpd24 combination, but the same code ran fine on the production server.

I initially tailed the regular logs but nothing really showed up. A quick ls -later showed system.log was the latest touched file in /var/log, and tailing that gave me

Saved crash report for httpd[99969] version 2.4.16 (805) 
to /Library/Logs/DiagnosticReports/httpd.crash

Contained within:

Process:               httpd [99974]
Path:                  /usr/sbin/httpd
Identifier:            httpd
Version:               2.4.16 (805)
Code Type:             X86-64 (Native)
Parent Process:        httpd [99245]
Responsible:           httpd [99974]
User ID:               70

PlugIn Path:             /usr/local/opt/php70-mongodb/mongodb.so
PlugIn Identifier:       mongodb.so

A brew uninstall php70-mongodb and a httpd -k restart later and everything was smooth sailing.

Python: Remove division decimal

When a number as a decimal it is usually a float in Python.

If you want to remove the decimal and keep it an integer (int). You can call the int() method on it like so...

>>> int(2.0)
2

However, int rounds down so...

>>> int(2.9)
2

If you want to round to the nearest integer you can use round:

>>> round(2.9)
3.0
>>> round(2.4)
2.0

And then call int() on that:

>>> int(round(2.9))
3
>>> int(round(2.4))
2

Display special characters when using print statement

Use repr:

a = "Hello\tWorld\nHello World"
print(repr(a))
# 'Hello\tWorld\nHello World'

Note you do not get \s for a space. I hope that was a typo...?

But if you really do want \s for spaces, you could do this:

print(repr(a).replace(' ',r'\s'))

Fill formula down till last row in column

Alternatively, you may use FillDown

Range("M3") = "=G3&"",""&L3": Range("M3:M" & LastRow).FillDown

Converting a double to an int in Javascript without rounding

There is no such thing as an int in Javascript. All Numbers are actually doubles behind the scenes* so you can't rely on the type system to issue a rounding order for you as you can in C or C#.

You don't need to worry about precision issues (since doubles correctly represent any integer up to 2^53) but you really are stuck with using Math.floor (or other equivalent tricks) if you want to round to the nearest integer.


*Most JS engines use native ints when they can but all in all JS numbers must still have double semantics.

Where can I find the .apk file on my device, when I download any app and install?

You can do that I believe. It needs root permission. If you want to know where your apk files are stored, open a emulator and then go to

DDMS>File Explorer-> you can see a directory by name "data" -> Click on it and you will see a "app" folder.

Your apks are stored there. In fact just copying a apk directly to the folder works for me with emulators.

How to respond to clicks on a checkbox in an AngularJS directive?

I prefer to use the ngModel and ngChange directives when dealing with checkboxes. ngModel allows you to bind the checked/unchecked state of the checkbox to a property on the entity:

<input type="checkbox" ng-model="entity.isChecked">

Whenever the user checks or unchecks the checkbox the entity.isChecked value will change too.

If this is all you need then you don't even need the ngClick or ngChange directives. Since you have the "Check All" checkbox, you obviously need to do more than just set the value of the property when someone checks a checkbox.

When using ngModel with a checkbox, it's best to use ngChange rather than ngClick for handling checked and unchecked events. ngChange is made for just this kind of scenario. It makes use of the ngModelController for data-binding (it adds a listener to the ngModelController's $viewChangeListeners array. The listeners in this array get called after the model value has been set, avoiding this problem).

<input type="checkbox" ng-model="entity.isChecked" ng-change="selectEntity()">

... and in the controller ...

var model = {};
$scope.model = model;

// This property is bound to the checkbox in the table header
model.allItemsSelected = false;

// Fired when an entity in the table is checked
$scope.selectEntity = function () {
    // If any entity is not checked, then uncheck the "allItemsSelected" checkbox
    for (var i = 0; i < model.entities.length; i++) {
        if (!model.entities[i].isChecked) {
            model.allItemsSelected = false;
            return;
        }
    }

    // ... otherwise ensure that the "allItemsSelected" checkbox is checked
    model.allItemsSelected = true;
};

Similarly, the "Check All" checkbox in the header:

<th>
    <input type="checkbox" ng-model="model.allItemsSelected" ng-change="selectAll()">
</th>

... and ...

// Fired when the checkbox in the table header is checked
$scope.selectAll = function () {
    // Loop through all the entities and set their isChecked property
    for (var i = 0; i < model.entities.length; i++) {
        model.entities[i].isChecked = model.allItemsSelected;
    }
};

CSS

What is the best way to... add a CSS class to the <tr> containing the entity to reflect its selected state?

If you use the ngModel approach for the data-binding, all you need to do is add the ngClass directive to the <tr> element to dynamically add or remove the class whenever the entity property changes:

<tr ng-repeat="entity in model.entities" ng-class="{selected: entity.isChecked}">

See the full Plunker here.

What is the native keyword in Java for?

NATIVE is Non access modifier.it can be applied only to METHOD. It indicates the PLATFORM-DEPENDENT implementation of method or code.

Eclipse shows errors but I can't find them

I came across the same issue while working on a selenium project(maven). The Project folder and pom.xml were showing red cross symbol. This was coming as i had the test datasheet open. I could remove the error by just closing the datasheet and the never faced the issue again

How do I copy items from list to list without foreach?

You could try this:

List<Int32> copy = new List<Int32>(original);

or if you're using C# 3 and .NET 3.5, with Linq, you can do this:

List<Int32> copy = original.ToList();

How do I change Eclipse to use spaces instead of tabs?

For the default text editor:

  • General » Editors » Text Editors » Insert spaces for tabs (check it)

For PHP:

  • PHP » Code Style » Formatter » Tab policy (choose "spaces")
  • PHP » Code Style » Formatter » Indentation size (set to 4)

For CSS:

  • Web » CSS » Editor » Indent using spaces (select it)
  • Web » CSS » Editor » Indentation size (set to 4)

For HTML:

  • Web » HTML » Editor » Indent using spaces (select it)
  • Web » HTML » Editor » Indentation size (set to 4)

For XML:

  • XML » XML Files » Editor » Indent using spaces (select it)
  • XML » XML Files » Editor » Indentation size (set to 4)

For Javascript:

  • Javascript » Preferences » Code Style » Formatter » Edit » Indentation (choose "spaces only")
  • Rename the formatter settings profile to save it

For Java:

  • Java » Preferences » Code Style » Formatter » Edit » Indentation (choose "spaces only")
  • Rename the formatter settings profile to save it

Access non-numeric Object properties by index?

Get the array of keys, reverse it, then run your loop

  var keys = Object.keys( obj ).reverse();
  for(var i = 0; i < keys.length; i++){
    var key = keys[i];
    var value = obj[key];
    //do stuff backwards
  }

IF... OR IF... in a windows batch file

It's possible to use a function, which evaluates the OR logic and returns a single value.

@echo off
set var1=3
set var2=5
call :logic_or orResult "'%var1%'=='4'" "'%var2%'=='5'"
if %orResult%==1 ( 
    echo At least one expression is true
) ELSE echo All expressions are false
exit /b

:logic_or <resultVar> expression1 [[expr2] ... expr-n] 
SETLOCAL
set "logic_or.result=0"
set "logic_or.resultVar=%~1"

:logic_or_loop 
if "%~2"=="" goto :logic_or_end 
if %~2 set "logic_or.result=1"
SHIFT 
goto :logic_or_loop 

:logic_or_end 
( 
  ENDLOCAL 
  set "%logic_or.resultVar%=%logic_or.result%"
  exit /b
) 

How to call a method in MainActivity from another class?

You can make this method static.

public static void startChronometer(){
        mChronometer.start();
        showElapsedTime();
    } 

you can call this function in other class as below:

MainActivity.startChronometer();

OR

You can make an object of the main class in second class like,

MainActivity mActivity = new MainActivity();
mActivity.startChronometer();

Is there an easy way to convert jquery code to javascript?

I can see a reason, unrelated to the original post, to automatically compile jQuery code into standard JavaScript:

16k -- or whatever the gzipped, minified jQuery library is -- might be too much for your website that is intended for a mobile browser. The w3c is recommending that all HTTP requests for mobile websites should be a maximum of 20k.

w3c specs for mobile

So I enjoy coding in my nice, terse, chained jQuery. But now I need to optimize for mobile. Should I really go back and do the difficult, tedious work of rewriting all the helper functions I used in the jQuery library? Or is there some kind of convenient app that will help me recompile?

That would be very sweet. Sadly, I don't think such a thing exists.

SeekBar and media player in android

I've used this tutorial with success, it's really simple to understand: www.androidhive.info/2012/03/android-building-audio-player-tutorial/

This is the interesting part:

/**
 * Update timer on seekbar
 * */
public void updateProgressBar() {
    mHandler.postDelayed(mUpdateTimeTask, 100);
}  

/**
 * Background Runnable thread
 * */
private Runnable mUpdateTimeTask = new Runnable() {
       public void run() {
           long totalDuration = mp.getDuration();
           long currentDuration = mp.getCurrentPosition();

           // Displaying Total Duration time
           songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
           // Displaying time completed playing
           songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

           // Updating progress bar
           int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
           //Log.d("Progress", ""+progress);
           songProgressBar.setProgress(progress);

           // Running this thread after 100 milliseconds
           mHandler.postDelayed(this, 100);
       }
    };

/**
 *
 * */
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {

}

/**
 * When user starts moving the progress handler
 * */
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    // remove message Handler from updating progress bar
    mHandler.removeCallbacks(mUpdateTimeTask);
}

/**
 * When user stops moving the progress hanlder
 * */
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    mHandler.removeCallbacks(mUpdateTimeTask);
    int totalDuration = mp.getDuration();
    int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

    // forward or backward to certain seconds
    mp.seekTo(currentPosition);

    // update timer progress again
    updateProgressBar();
}

How can I print literal curly-brace characters in a string and also use .format on it?

If you want to only print one curly brace (for example {) you can use {{, and you can add more braces later in the string if you want. For example:

>>> f'{{ there is a curly brace on the left. Oh, and 1 + 1 is {1 + 1}'
'{ there is a curly brace on the left. Oh, and 1 + 1 is 2'

PHP string "contains"

PHP 8 or newer:

Use the str_contains function.

if (str_contains($str, "."))
{
    echo 'Found it';
}

else
{
    echo 'Not found.';
}

PHP 7 or older:

if (strpos($str, '.') !== FALSE)
{
    echo 'Found it';
}

else
{
    echo 'Not found.';
}

Note that you need to use the !== operator. If you use != or <> and the '.' is found at position 0, the comparison will evaluate to true because 0 is loosely equal to false.

OperationalError, no such column. Django

I simple made a careless mistake of forgetting to actually apply the migration (migrate) after making migrations. Writing this just in case anyone might make the same mistake.

XAMPP PORT 80 is Busy / EasyPHP error in Apache configuration file:

Port 80 might be busy with other application like IIS. If you don't want to stop it, you can change the apache port. Here is the way..

  1. go to the C:\xampp\apache\conf (directory where you installed xampp). Now, locate the httpd.conf.
  2. Open it with any text editor (like notepad) and go the line that says Listen 80
  3. Change this with any other port (like Listen 1234)
  4. Save the file. Restart the server and go ahead.

How to delete multiple rows in SQL where id = (x to y)

Delete Id from table where Id in (select id from table)

Multiple try codes in one block

You'll have to make this separate try blocks:

try:
    code a
except ExplicitException:
    pass

try:
    code b
except ExplicitException:
    try:
        code c
    except ExplicitException:
        try:
            code d
        except ExplicitException:
            pass

This assumes you want to run code c only if code b failed.

If you need to run code c regardless, you need to put the try blocks one after the other:

try:
    code a
except ExplicitException:
    pass

try:
    code b
except ExplicitException:
    pass

try:
    code c
except ExplicitException:
    pass

try:
    code d
except ExplicitException:
    pass

I'm using except ExplicitException here because it is never a good practice to blindly ignore all exceptions. You'll be ignoring MemoryError, KeyboardInterrupt and SystemExit as well otherwise, which you normally do not want to ignore or intercept without some kind of re-raise or conscious reason for handling those.

What's the best visual merge tool for Git?

Diffuse is my favourite but of course I am biased. :-) It is very easy to use:

$ diffuse "mine" "output" "theirs"

Diffuse is a small and simple text merge tool written in Python. With Diffuse, you can easily merge, edit, and review changes to your code. Diffuse is free software.

How to show particular image as thumbnail while implementing share on Facebook?

I was having the same problems and believe I have solved it. I used the link meta tag as mentioned here to point to the image I wanted, but the key is that if you do that FB won't pull any other images as choices. Also if your image is too big, you won't have any choices at all.

Here's how I fixed my site http://gnorml.com/blog/facebook-link-thumbnails/

Load image from url

public class MainActivity extends Activity {

    Bitmap b;
    ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        img = (ImageView)findViewById(R.id.imageView1);
        information info = new information();
        info.execute("");
    }

    public class information extends AsyncTask<String, String, String>
    {
        @Override
        protected String doInBackground(String... arg0) {

            try
            {
                URL url = new URL("http://10.119.120.10:80/img.jpg");
                InputStream is = new BufferedInputStream(url.openStream());
                b = BitmapFactory.decodeStream(is);

            } catch(Exception e){}
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            img.setImageBitmap(b);
        }
    }
}

OSError [Errno 22] invalid argument when use open() in Python

you should add one more "/" in the last "/" of path, that is: open('C:\Python34\book.csv') to open('C:\Python34\\book.csv'). For example:

import csv
with open('C:\Python34\\book.csv', newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter='', quotechar='|')
    for row in spamreader:
        print(row)

git push vs git push origin <branchname>

The first push should be a:

git push -u origin branchname

That would make sure:

Any future git push will, with that default policy, only push the current branch, and only if that branch has an upstream branch with the same name.
that avoid pushing all matching branches (previous default policy), where tons of test branches were pushed even though they aren't ready to be visible on the upstream repo.

Downloading a file from spring controllers

You should be able to write the file on the response directly. Something like

response.setContentType("application/pdf");      
response.setHeader("Content-Disposition", "attachment; filename=\"somefile.pdf\""); 

and then write the file as a binary stream on response.getOutputStream(). Remember to do response.flush() at the end and that should do it.

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

Please remove call to trustSrc function and try again like this . {{trustSrc(currentProject.url)}} to {{currentProject.url}}. Check this link http://plnkr.co/edit/caqS1jE9fpmMn5NofUve?p=preview


But according to the Angular Js 1.2 Documentation, you should write a function for getting src url. Have a look on the following code.

Before:

Javascript

scope.baseUrl = 'page';
scope.a = 1;
scope.b = 2;

Html

<!-- Are a and b properly escaped here? Is baseUrl controlled by user? -->
<iframe src="{{baseUrl}}?a={{a}&b={{b}}"

But for security reason they are recommending following method

Javascript

var baseUrl = "page";
scope.getIframeSrc = function() {

  // One should think about their particular case and sanitize accordingly
  var qs = ["a", "b"].map(function(value, name) {
      return encodeURIComponent(name) + "=" +
             encodeURIComponent(value);
    }).join("&");

  // `baseUrl` isn't exposed to a user's control, so we don't have to worry about escaping it.
  return baseUrl + "?" + qs;
};

Html

<iframe src="{{getIframeSrc()}}">

How do I bind to list of checkbox values with AngularJS?

You don't have to write all that code. AngularJS will keep the model and the checkboxes in sync simply by using ngTrueValue and ngFalseValue

Codepen here: http://codepen.io/paulbhartzog/pen/kBhzn

Code snippet:

<p ng-repeat="item in list1" class="item" id="{{item.id}}">
  <strong>{{item.id}}</strong> <input name='obj1_data' type="checkbox" ng-model="list1[$index].data" ng-true-value="1" ng-false-value="0"> Click this to change data value below
</p>
<pre>{{list1 | json}}</pre>

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

Applying a CORS restriction is a security feature defined by a server and implemented by a browser.

The browser looks at the CORS policy of the server and respects it.

However, the Postman tool does not bother about the CORS policy of the server.

That is why the CORS error appears in the browser, but not in Postman.

django: TypeError: 'tuple' object is not callable

You're missing comma (,) inbetween:

>>> ((1,2) (2,3))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable

Put comma:

>>> ((1,2), (2,3))
((1, 2), (2, 3))

how to add <script>alert('test');</script> inside a text box?

JQuery version:

$('yourInputSelectorHere').val("<script>alert('test');<\/script>")

XPath OR operator for different nodes

All title nodes with zipcode or book node as parent:

Version 1:

//title[parent::zipcode|parent::book]

Version 2:

//bookstore/book/title|//bookstore/city/zipcode/title

Version 3: (results are sorted based on source data rather than the order of book then zipcode)

//title[../../../*[book or magazine] or ../../../../*[city/zipcode]]

or - used within true/false - a Boolean operator in xpath

| - a Union operator in xpath that appends the query to the right of the operator to the result set from the left query.

Random integer in VB.NET

Dim rnd As Random = New Random
rnd.Next(n)

Can I escape a double quote in a verbatim string literal?

Use double quotation marks.

string foo = @"this ""word"" is escaped";

Splitting a table cell into two columns in HTML

You have two options.

  1. Use an extra column in the header, and use <colspan> in your header to stretch a cell for two or more columns.
  2. Insert a <table> with 2 columns inside the td you want extra columns in.

How do I put text on ProgressBar?

You will have to override the OnPaint method, call the base implementation and the paint your own text.

You will need to create your own CustomProgressBar and then override OnPaint to draw what ever text you want.

Custom Progress Bar Class

namespace ProgressBarSample
{

public enum ProgressBarDisplayText
{
    Percentage,
    CustomText
}

class CustomProgressBar: ProgressBar
{
    //Property to set to decide whether to print a % or Text
    public ProgressBarDisplayText DisplayStyle { get; set; }

    //Property to hold the custom text
    public String CustomText { get; set; }

    public CustomProgressBar()
    {
        // Modify the ControlStyles flags
        //http://msdn.microsoft.com/en-us/library/system.windows.forms.controlstyles.aspx
        SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint, true);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        Rectangle rect = ClientRectangle;
        Graphics g = e.Graphics;

        ProgressBarRenderer.DrawHorizontalBar(g, rect);
        rect.Inflate(-3, -3);
        if (Value > 0)
        {
            // As we doing this ourselves we need to draw the chunks on the progress bar
            Rectangle clip = new Rectangle(rect.X, rect.Y, (int)Math.Round(((float)Value / Maximum) * rect.Width), rect.Height);
            ProgressBarRenderer.DrawHorizontalChunks(g, clip);
        }

        // Set the Display text (Either a % amount or our custom text
        string text = DisplayStyle == ProgressBarDisplayText.Percentage ? Value.ToString() + '%' : CustomText;


        using (Font f = new Font(FontFamily.GenericSerif, 10))
        {

            SizeF len = g.MeasureString(text, f);
            // Calculate the location of the text (the middle of progress bar)
            // Point location = new Point(Convert.ToInt32((rect.Width / 2) - (len.Width / 2)), Convert.ToInt32((rect.Height / 2) - (len.Height / 2)));
            Point location = new Point(Convert.ToInt32((Width / 2) - len.Width / 2), Convert.ToInt32((Height / 2) - len.Height / 2)); 
            // The commented-out code will centre the text into the highlighted area only. This will centre the text regardless of the highlighted area.
            // Draw the custom text
            g.DrawString(text, f, Brushes.Red, location);
        }
    }
}
}

Sample WinForms Application

using System;
using System.Linq;
using System.Windows.Forms;
using System.Collections.Generic;

namespace ProgressBarSample
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            // Set our custom Style (% or text)
            customProgressBar1.DisplayStyle = ProgressBarDisplayText.CustomText;
            customProgressBar1.CustomText = "Initialising";
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            customProgressBar1.Value = 0;
            btnStart.Enabled = true;
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            btnReset.Enabled = false;
            btnStart.Enabled = false;

            for (int i = 0; i < 101; i++)
            {

                customProgressBar1.Value = i;
                // Demo purposes only
                System.Threading.Thread.Sleep(100);

                // Set the custom text at different intervals for demo purposes
                if (i > 30 && i < 50)
                {
                    customProgressBar1.CustomText = "Registering Account";
                }

                if (i > 80)
                {
                    customProgressBar1.CustomText = "Processing almost complete!";
                }

                if (i >= 99)
                {
                    customProgressBar1.CustomText = "Complete";
                }
            }

            btnReset.Enabled = true;


        }


    }
}

What's the best way to add a drop shadow to my UIView

You can create an extension for UIView to access these values in the design editor

Shadow options in design editor

extension UIView{

    @IBInspectable var shadowOffset: CGSize{
        get{
            return self.layer.shadowOffset
        }
        set{
            self.layer.shadowOffset = newValue
        }
    }

    @IBInspectable var shadowColor: UIColor{
        get{
            return UIColor(cgColor: self.layer.shadowColor!)
        }
        set{
            self.layer.shadowColor = newValue.cgColor
        }
    }

    @IBInspectable var shadowRadius: CGFloat{
        get{
            return self.layer.shadowRadius
        }
        set{
            self.layer.shadowRadius = newValue
        }
    }

    @IBInspectable var shadowOpacity: Float{
        get{
            return self.layer.shadowOpacity
        }
        set{
            self.layer.shadowOpacity = newValue
        }
    }
}

PHP error: Notice: Undefined index:

Try this:

$month = ( isset($_POST['month']) ) ? $_POST['month'] : '';

$op = ( isset($_POST['op']) ) ? $_POST['op'] : '';

How to get the fields in an Object via reflection?

You can use Class#getDeclaredFields() to get all declared fields of the class. You can use Field#get() to get the value.

In short:

Object someObject = getItSomehow();
for (Field field : someObject.getClass().getDeclaredFields()) {
    field.setAccessible(true); // You might want to set modifier to public first.
    Object value = field.get(someObject); 
    if (value != null) {
        System.out.println(field.getName() + "=" + value);
    }
}

To learn more about reflection, check the Sun tutorial on the subject.


That said, the fields does not necessarily all represent properties of a VO. You would rather like to determine the public methods starting with get or is and then invoke it to grab the real property values.

for (Method method : someObject.getClass().getDeclaredMethods()) {
    if (Modifier.isPublic(method.getModifiers())
        && method.getParameterTypes().length == 0
        && method.getReturnType() != void.class
        && (method.getName().startsWith("get") || method.getName().startsWith("is"))
    ) {
        Object value = method.invoke(someObject);
        if (value != null) {
            System.out.println(method.getName() + "=" + value);
        }
    }
}

That in turn said, there may be more elegant ways to solve your actual problem. If you elaborate a bit more about the functional requirement for which you think that this is the right solution, then we may be able to suggest the right solution. There are many, many tools available to massage javabeans.

Abstract Class:-Real Time Example

You should be able to cite at least one from the JDK itself. Look in the java.util.collections package. There are several abstract classes. You should fully understand interface, abstract, and concrete for Map and why Joshua Bloch wrote it that way.

Merge Cell values with PHPExcel - PHP

$this->excel->setActiveSheetIndex(0)->mergeCells("A".($p).":B".($p)); for dynamic merging of cells

String replacement in java, similar to a velocity template

Here's an outline of how you could go about doing this. It should be relatively straightforward to implement it as actual code.

  1. Create a map of all the objects that will be referenced in the template.
  2. Use a regular expression to find variable references in the template and replace them with their values (see step 3). The Matcher class will come in handy for find-and-replace.
  3. Split the variable name at the dot. user.name would become user and name. Look up user in your map to get the object and use reflection to obtain the value of name from the object. Assuming your objects have standard getters, you will look for a method getName and invoke it.

QED symbol in latex

The question specifically mentions a full box and not an empty box and not using proof environment from amsthm package. Hence, an option may be to use the command \QED from the package stix. It reproduces the character U+220E (end of proof, ?).

SSIS Convert Between Unicode and Non-Unicode Error

Below Steps worked for me:

1). right click on source task.

2). click on "Show Advanced editor". advanced edit option for source task in ssis

3). Go to "Input and Output Properties" tab.

4). select the output column for which you are getting the error.

5). Its data type will be "String[DT_STR]".

6). Change that data type to "Unicode String[DT_WSTR]". Changing the data type to unicode string

7). save and close. Hope this helps!

How to run a PowerShell script

Using cmd (BAT) file:

@echo off
color 1F
echo.

C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "PrepareEnvironment.ps1"

:EOF
echo Waiting seconds
timeout /t 10 /nobreak > NUL

If you need run as administrator:

  1. Make a shortcut pointed to the command prompt (I named it Administrative Command Prompt)
  2. Open the shortcut's properties and go to the Compatibility tab
  3. Under the Privilege Level section, make sure the checkbox next to "Run this program as an administrator" is checked

php refresh current page?

$_SERVER['REQUEST_URI'] should work.

Creating a select box with a search option

Use a data list instead.

<form action="/action_page.php" method="get">
      <input list="browsers" name="browser">
      <datalist id="browsers">
        <option value="Internet Explorer">
        <option value="Firefox">
        <option value="Chrome">
        <option value="Opera">
        <option value="Safari">
      </datalist>
      <input type="submit">
    </form>

Not supported I.E. 9 and back. https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_datalist

How to set HttpResponse timeout for Android in Java

If you're using the default http client, here's how to do it using the default http params:

HttpClient client = new DefaultHttpClient();
HttpParams params = client.getParams();
HttpConnectionParams.setConnectionTimeout(params, 3000);
HttpConnectionParams.setSoTimeout(params, 3000);

Original credit goes to http://www.jayway.com/2009/03/17/configuring-timeout-with-apache-httpclient-40/

How to inject JPA EntityManager using spring

Yes, although it's full of gotchas, since JPA is a bit peculiar. It's very much worth reading the documentation on injecting JPA EntityManager and EntityManagerFactory, without explicit Spring dependencies in your code:

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/orm.html#orm-jpa

This allows you to either inject the EntityManagerFactory, or else inject a thread-safe, transactional proxy of an EntityManager directly. The latter makes for simpler code, but means more Spring plumbing is required.

How do I convert a number to a letter in Java?

public static String abcBase36(int i) {
    char[] ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    int quot = i / 36;
    int rem = i % 36;

    char letter = ALPHABET[rem];
    if (quot == 0) {
        return "" + letter;
    } else {
        return abcBase36(quot - 1) + letter;
    }
}

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

gem update --system

will update the rubygems and will fix the problem.

Setting a max height on a table

In Tables, For minimum table cells height or rows height use css height: in place of min-height:

AND

For Limiting max-height of all cells or rows in table with Javascript:

This script is good for horizontal overflow tables.

This script increase the table width 300px each time (maximum 4000px) until rows shrinks to max-height(160px) , and you can also edit numbers as your need.

var i = 0, row, table = document.getElementsByTagName('table')[0], j = table.offsetWidth;
while (row = table.rows[i++]) {
    while (row.offsetHeight > 160 && j < 4000) {
        j += 300;
        table.style.width = j + 'px';
    }
}

Source: HTML Table Solution Max Height Limit For Rows Or Cells By Increasing Table Width, Javascript

Keeping session alive with Curl and PHP

You have correctly used "CURLOPT_COOKIEJAR" (writing) but you also need to set "CURLOPT_COOKIEFILE" (reading)

curl_setopt ($ch, CURLOPT_COOKIEJAR, COOKIE_FILE); 
curl_setopt ($ch, CURLOPT_COOKIEFILE, COOKIE_FILE); 

How to get EditText value and display it on screen through TextView?

yesButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        eiteText=(EditText)findViewById(R.id.nameET);
        String result=eiteText.getText().toString();
        Log.d("TAG",result);
    }
});

How to compile C programming in Windows 7?

Microsoft Visual Studio Express

It's a full IDE, with powerful debugging tools, syntax highlighting, etc.

How to iterate over a TreeMap?

Just to point out the generic way to iterate over any map:

 private <K, V> void iterateOverMap(Map<K, V> map) {
    for (Map.Entry<K, V> entry : map.entrySet()) {
        System.out.println("key ->" + entry.getKey() + ", value->" + entry.getValue());
    }
    }

What's the best way to override a user agent CSS stylesheet rule that gives unordered-lists a 1em margin?

I had the same issues but nothing worked. What I did was I added this to the selector:

-webkit-appearance: none;
-moz-appearance: none;
appearance: none;

Get scroll position using jquery

Use scrollTop() to get or set the scroll position.

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

How to lock specific cells but allow filtering and sorting

This is a very old, but still very useful thread. I came here recently with the same issue. I suggest protecting the sheet when appropriate and unprotecting it when the filter row (eg Row 1) is selected. My solution doesn't use password protection - I don't need it (its a safeguard, not a security feature). I can't find an event handler that recognizes selection of a filter button - so I gave the instruction to my users to first select the filter cell then click the filter button. Here's what I advocate, (I only change protection if it needs to be changed, that may or may not save time - I don't know, but it "feels" right):

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Const FilterRow = 1
  Dim c As Range
  Dim NotFilterRow As Boolean
  Dim oldstate As Boolean
  Dim ws As Worksheet
  Set ws = ActiveSheet
  oldstate = ws.ProtectContents
  NotFilterRow = False
  For Each c In Target.Cells
     NotFilterRow = c.Row <> FilterRow
     If NotFilterRow Then Exit For
  Next c
  If NotFilterRow <> oldstate Then
     If NotFilterRow Then
        ws.Protect
     Else
        ws.Unprotect
     End If
  End If
  Set ws = Nothing
End Sub

What's the difference between eval, exec, and compile?

The short answer, or TL;DR

Basically, eval is used to evaluate a single dynamically generated Python expression, and exec is used to execute dynamically generated Python code only for its side effects.

eval and exec have these two differences:

  1. eval accepts only a single expression, exec can take a code block that has Python statements: loops, try: except:, class and function/method definitions and so on.

    An expression in Python is whatever you can have as the value in a variable assignment:

    a_variable = (anything you can put within these parentheses is an expression)
    
  2. eval returns the value of the given expression, whereas exec ignores the return value from its code, and always returns None (in Python 2 it is a statement and cannot be used as an expression, so it really does not return anything).

In versions 1.0 - 2.7, exec was a statement, because CPython needed to produce a different kind of code object for functions that used exec for its side effects inside the function.

In Python 3, exec is a function; its use has no effect on the compiled bytecode of the function where it is used.


Thus basically:

>>> a = 5
>>> eval('37 + a')   # it is an expression
42
>>> exec('37 + a')   # it is an expression statement; value is ignored (None is returned)
>>> exec('a = 47')   # modify a global variable as a side effect
>>> a
47
>>> eval('a = 47')  # you cannot evaluate a statement
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    a = 47
      ^
SyntaxError: invalid syntax

The compile in 'exec' mode compiles any number of statements into a bytecode that implicitly always returns None, whereas in 'eval' mode it compiles a single expression into bytecode that returns the value of that expression.

>>> eval(compile('42', '<string>', 'exec'))  # code returns None
>>> eval(compile('42', '<string>', 'eval'))  # code returns 42
42
>>> exec(compile('42', '<string>', 'eval'))  # code returns 42,
>>>                                          # but ignored by exec

In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression:

>>> compile('for i in range(3): print(i)', '<string>', 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

Actually the statement "eval accepts only a single expression" applies only when a string (which contains Python source code) is passed to eval. Then it is internally compiled to bytecode using compile(source, '<string>', 'eval') This is where the difference really comes from.

If a code object (which contains Python bytecode) is passed to exec or eval, they behave identically, excepting for the fact that exec ignores the return value, still returning None always. So it is possible use eval to execute something that has statements, if you just compiled it into bytecode before instead of passing it as a string:

>>> eval(compile('if 1: print("Hello")', '<string>', 'exec'))
Hello
>>>

works without problems, even though the compiled code contains statements. It still returns None, because that is the return value of the code object returned from compile.

In the 'eval' mode (and thus with the eval function if a string is passed in), the compile raises an exception if the source code contains statements or anything else beyond a single expression:

>>> compile('for i in range(3): print(i)', '<string>'. 'eval')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

The longer answer, a.k.a the gory details

exec and eval

The exec function (which was a statement in Python 2) is used for executing a dynamically created statement or program:

>>> program = '''
for i in range(3):
    print("Python is cool")
'''
>>> exec(program)
Python is cool
Python is cool
Python is cool
>>> 

The eval function does the same for a single expression, and returns the value of the expression:

>>> a = 2
>>> my_calculation = '42 * a'
>>> result = eval(my_calculation)
>>> result
84

exec and eval both accept the program/expression to be run either as a str, unicode or bytes object containing source code, or as a code object which contains Python bytecode.

If a str/unicode/bytes containing source code was passed to exec, it behaves equivalently to:

exec(compile(source, '<string>', 'exec'))

and eval similarly behaves equivalent to:

eval(compile(source, '<string>', 'eval'))

Since all expressions can be used as statements in Python (these are called the Expr nodes in the Python abstract grammar; the opposite is not true), you can always use exec if you do not need the return value. That is to say, you can use either eval('my_func(42)') or exec('my_func(42)'), the difference being that eval returns the value returned by my_func, and exec discards it:

>>> def my_func(arg):
...     print("Called with %d" % arg)
...     return arg * 2
... 
>>> exec('my_func(42)')
Called with 42
>>> eval('my_func(42)')
Called with 42
84
>>> 

Of the 2, only exec accepts source code that contains statements, like def, for, while, import, or class, the assignment statement (a.k.a a = 42), or entire programs:

>>> exec('for i in range(3): print(i)')
0
1
2
>>> eval('for i in range(3): print(i)')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print(i)
      ^
SyntaxError: invalid syntax

Both exec and eval accept 2 additional positional arguments - globals and locals - which are the global and local variable scopes that the code sees. These default to the globals() and locals() within the scope that called exec or eval, but any dictionary can be used for globals and any mapping for locals (including dict of course). These can be used not only to restrict/modify the variables that the code sees, but are often also used for capturing the variables that the executed code creates:

>>> g = dict()
>>> l = dict()
>>> exec('global a; a, b = 123, 42', g, l)
>>> g['a']
123
>>> l
{'b': 42}

(If you display the value of the entire g, it would be much longer, because exec and eval add the built-ins module as __builtins__ to the globals automatically if it is missing).

In Python 2, the official syntax for the exec statement is actually exec code in globals, locals, as in

>>> exec 'global a; a, b = 123, 42' in g, l

However the alternate syntax exec(code, globals, locals) has always been accepted too (see below).

compile

The compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1) built-in can be used to speed up repeated invocations of the same code with exec or eval by compiling the source into a code object beforehand. The mode parameter controls the kind of code fragment the compile function accepts and the kind of bytecode it produces. The choices are 'eval', 'exec' and 'single':

  • 'eval' mode expects a single expression, and will produce bytecode that when run will return the value of that expression:

    >>> dis.dis(compile('a + b', '<string>', 'eval'))
      1           0 LOAD_NAME                0 (a)
                  3 LOAD_NAME                1 (b)
                  6 BINARY_ADD
                  7 RETURN_VALUE
    
  • 'exec' accepts any kinds of python constructs from single expressions to whole modules of code, and executes them as if they were module top-level statements. The code object returns None:

    >>> dis.dis(compile('a + b', '<string>', 'exec'))
      1           0 LOAD_NAME                0 (a)
                  3 LOAD_NAME                1 (b)
                  6 BINARY_ADD
                  7 POP_TOP                             <- discard result
                  8 LOAD_CONST               0 (None)   <- load None on stack
                 11 RETURN_VALUE                        <- return top of stack
    
  • 'single' is a limited form of 'exec' which accepts a source code containing a single statement (or multiple statements separated by ;) if the last statement is an expression statement, the resulting bytecode also prints the repr of the value of that expression to the standard output(!).

    An if-elif-else chain, a loop with else, and try with its except, else and finally blocks is considered a single statement.

    A source fragment containing 2 top-level statements is an error for the 'single', except in Python 2 there is a bug that sometimes allows multiple toplevel statements in the code; only the first is compiled; the rest are ignored:

    In Python 2.7.8:

    >>> exec(compile('a = 5\na = 6', '<string>', 'single'))
    >>> a
    5
    

    And in Python 3.4.2:

    >>> exec(compile('a = 5\na = 6', '<string>', 'single'))
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<string>", line 1
        a = 5
            ^
    SyntaxError: multiple statements found while compiling a single statement
    

    This is very useful for making interactive Python shells. However, the value of the expression is not returned, even if you eval the resulting code.

Thus greatest distinction of exec and eval actually comes from the compile function and its modes.


In addition to compiling source code to bytecode, compile supports compiling abstract syntax trees (parse trees of Python code) into code objects; and source code into abstract syntax trees (the ast.parse is written in Python and just calls compile(source, filename, mode, PyCF_ONLY_AST)); these are used for example for modifying source code on the fly, and also for dynamic code creation, as it is often easier to handle the code as a tree of nodes instead of lines of text in complex cases.


While eval only allows you to evaluate a string that contains a single expression, you can eval a whole statement, or even a whole module that has been compiled into bytecode; that is, with Python 2, print is a statement, and cannot be evalled directly:

>>> eval('for i in range(3): print("Python is cool")')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    for i in range(3): print("Python is cool")
      ^
SyntaxError: invalid syntax

compile it with 'exec' mode into a code object and you can eval it; the eval function will return None.

>>> code = compile('for i in range(3): print("Python is cool")',
                   'foo.py', 'exec')
>>> eval(code)
Python is cool
Python is cool
Python is cool

If one looks into eval and exec source code in CPython 3, this is very evident; they both call PyEval_EvalCode with same arguments, the only difference being that exec explicitly returns None.

Syntax differences of exec between Python 2 and Python 3

One of the major differences in Python 2 is that exec is a statement and eval is a built-in function (both are built-in functions in Python 3). It is a well-known fact that the official syntax of exec in Python 2 is exec code [in globals[, locals]].

Unlike majority of the Python 2-to-3 porting guides seem to suggest, the exec statement in CPython 2 can be also used with syntax that looks exactly like the exec function invocation in Python 3. The reason is that Python 0.9.9 had the exec(code, globals, locals) built-in function! And that built-in function was replaced with exec statement somewhere before Python 1.0 release.

Since it was desirable to not break backwards compatibility with Python 0.9.9, Guido van Rossum added a compatibility hack in 1993: if the code was a tuple of length 2 or 3, and globals and locals were not passed into the exec statement otherwise, the code would be interpreted as if the 2nd and 3rd element of the tuple were the globals and locals respectively. The compatibility hack was not mentioned even in Python 1.4 documentation (the earliest available version online); and thus was not known to many writers of the porting guides and tools, until it was documented again in November 2012:

The first expression may also be a tuple of length 2 or 3. In this case, the optional parts must be omitted. The form exec(expr, globals) is equivalent to exec expr in globals, while the form exec(expr, globals, locals) is equivalent to exec expr in globals, locals. The tuple form of exec provides compatibility with Python 3, where exec is a function rather than a statement.

Yes, in CPython 2.7 that it is handily referred to as being a forward-compatibility option (why confuse people over that there is a backward compatibility option at all), when it actually had been there for backward-compatibility for two decades.

Thus while exec is a statement in Python 1 and Python 2, and a built-in function in Python 3 and Python 0.9.9,

>>> exec("print(a)", globals(), {'a': 42})
42

has had identical behaviour in possibly every widely released Python version ever; and works in Jython 2.5.2, PyPy 2.3.1 (Python 2.7.6) and IronPython 2.6.1 too (kudos to them following the undocumented behaviour of CPython closely).

What you cannot do in Pythons 1.0 - 2.7 with its compatibility hack, is to store the return value of exec into a variable:

Python 2.7.11+ (default, Apr 17 2016, 14:00:29) 
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = exec('print(42)')
  File "<stdin>", line 1
    a = exec('print(42)')
           ^
SyntaxError: invalid syntax

(which wouldn't be useful in Python 3 either, as exec always returns None), or pass a reference to exec:

>>> call_later(exec, 'print(42)', delay=1000)
  File "<stdin>", line 1
    call_later(exec, 'print(42)', delay=1000)
                  ^
SyntaxError: invalid syntax

Which a pattern that someone might actually have used, though unlikely;

Or use it in a list comprehension:

>>> [exec(i) for i in ['print(42)', 'print(foo)']
  File "<stdin>", line 1
    [exec(i) for i in ['print(42)', 'print(foo)']
        ^
SyntaxError: invalid syntax

which is abuse of list comprehensions (use a for loop instead!).

How to put scroll bar only for modal-body?

Problem solved with combine solution @carlos calla and @jonathan marston.

    /* Important part */
.modal-dialog{
    overflow-y: initial !important
}
.modal-body{
    max-height: calc(100vh - 200px);
    overflow-y: auto;
}

How to reference a method in javadoc?

You will find much information about JavaDoc at the Documentation Comment Specification for the Standard Doclet, including the information on the

{@link package.class#member label}

tag (that you are looking for). The corresponding example from the documentation is as follows

For example, here is a comment that refers to the getComponentAt(int, int) method:

Use the {@link #getComponentAt(int, int) getComponentAt} method.

The package.class part can be ommited if the referred method is in the current class.


Other useful links about JavaDoc are:

Disable copy constructor

You can make the copy constructor private and provide no implementation:

private:
    SymbolIndexer(const SymbolIndexer&);

Or in C++11, explicitly forbid it:

SymbolIndexer(const SymbolIndexer&) = delete;

Get Mouse Position

If you're using SWT, you might want to look at adding a MouseMoveListener as explained here.

How do I make a file:// hyperlink that works in both IE and Firefox?

At least with Chrome, (I don't know about Firefox) You can drag the icon to the left of the URL in the browser to a folder location on your desktop and it will create a file that behaves as an internet shortcut.

I don't know if the file format is universal yet, however Chrome seems to know what to do with it.

The file produced is a .url file and contains the following:

[InternetShortcut] URL=http://www.accordingtothescriptures.org/prophecy/353prophecies.html

You can replace the URL with anything you'd like.

Python: Find in list

Definition and Usage

the count() method returns the number of elements with the specified value.

Syntax

list.count(value)

example:

fruits = ['apple', 'banana', 'cherry']

x = fruits.count("cherry")

Question's example:

item = someSortOfSelection()

if myList.count(item) >= 1 :

    doMySpecialFunction(item)

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

Click on Deployment Assembly ( right above Java Build Path that you show as active ) and make sure that you see json-lib-2.4-jdk15.jar there.

Usually, you should add it to your build path and export it from your project. Once it's exported you will see the WTP warning that it's not a part of the deployment. Choose the Quick Fix option and add it to your deployment path.

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ' '

For the OP's command:

select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0,  Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from  #tmp_CTF** 

I get this error:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.

when debugging something like this split the long line up so you'll get a better row number:

select compid
,2
, convert(datetime
, '01/01/' 
+ CONVERT(char(4)
,cal_yr) 
,101) 
,0
,  Update_dt
, th1
, th2
, th3_pc 
, Update_id
, Update_dt
,1
from  #tmp_CTF** 

this now results in:

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.

which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:

from [#tmp_CTF**]

if that is the table name.

How to add/update an attribute to an HTML element using JavaScript?

What seems easy is actually tricky if you want to be completely compatible.

var e = document.createElement('div');

Let's say you have an id of 'div1' to add.

e['id'] = 'div1';
e.id = 'div1';
e.attributes['id'] = 'div1';
e.createAttribute('id','div1')
These will all work except the last in IE 5.5 (which is ancient history at this point but still is XP's default with no updates).

But there are contingencies, of course. Will not work in IE prior to 8:e.attributes['style'] Will not error but won't actually set the class, it must be className:e['class'] .
However, if you're using attributes then this WILL work:e.attributes['class']

In summary, think of attributes as literal and object-oriented.

In literal, you just want it to spit out x='y' and not think about it. This is what attributes, setAttribute, createAttribute is for (except for IE's style exception). But because these are really objects things can get confused.

Since you are going to the trouble of properly creating a DOM element instead of jQuery innerHTML slop, I would treat it like one and stick with the e.className = 'fooClass' and e.id = 'fooID'. This is a design preference, but in this instance trying to treat is as anything other than an object works against you.

It will never backfire on you like the other methods might, just be aware of class being className and style being an object so it's style.width not style="width:50px". Also remember tagName but this is already set by createElement so you shouldn't need to worry about it.

This was longer than I wanted, but CSS manipulation in JS is tricky business.

PHP fopen() Error: failed to open stream: Permission denied

You may need to change the permissions as an administrator. Open up terminal on your Mac and then open the directory that markers.xml is located in. Then type:

sudo chmod 777 markers.xml

You may be prompted for a password. Also, it could be the directories that don't allow full access. I'm not familiar with WordPress, so you may have to change the permission of each directory moving upward to the mysite directory.

Space between two rows in a table?

The correct way to give spacing for tables is to use cellpadding and cellspacing e.g.

<table cellpadding="4">

Does Java have something like C#'s ref and out keywords?

No, Java doesn't have something like C#'s ref and out keywords for passing by reference.

You can only pass by value in Java. Even references are passed by value. See Jon Skeet's page about parameter passing in Java for more details.

To do something similar to ref or out you would have to wrap your parameters inside another object and pass that object reference in as a parameter.

Export query result to .csv file in SQL Server 2008

You could use QueryToDoc (http://www.querytodoc.com). It lets you write a query against a SQL database and export the results - after you pick the delimiter - to Excel, Word, HTML, or CSV

How to set the value of a hidden field from a controller in mvc

Please find code for respected region.

Controller

ViewBag.hdnFlag= Session["hdnFlag"];

View

<input type="hidden" value="@ViewBag.hdnFlag" id="hdnFlag" />

JavaScript

var hdnFlagVal = $("#hdnFlag").val();

adding line break

C# 6+

In addition, since c#6 you can also use a static using statement for System.Environment.

So instead of Environment.NewLine, you can just write NewLine.

Concise and much easier on the eye, particularly when there are multiple instances ...

using static System.Environment;
   
FirmNames = "";
foreach (var item in FirmNameList)
{
    if (FirmNames != "")
    {
       FirmNames += ", " + NewLine;
    }
    FirmNames += item;
}

Twitter bootstrap scrollable table

All above solutions make table header scroll too... If you want to scroll tbody only then apply this:

tbody {
    height: 100px !important;
    overflow: scroll;
    display:block;
}

How do I check whether a file exists without exceptions?

Testing for files and folders with os.path.isfile(), os.path.isdir() and os.path.exists()

Assuming that the "path" is a valid path, this table shows what is returned by each function for files and folders:

enter image description here

You can also test if a file is a certain type of file using os.path.splitext() to get the extension (if you don't already know it)

>>> import os
>>> path = "path to a word document"
>>> os.path.isfile(path)
True
>>> os.path.splitext(path)[1] == ".docx" # test if the extension is .docx
True

How to break lines in PowerShell?

If you are using just code like this below, you must put just a grave accent at the end of line `.

docker run -d --name rabbitmq `
           -p 5672:5672 `
           -p 15672:15672 `
           --restart=always `
           --hostname rabbitmq-master `
           -v c:\docker\rabbitmq\data:/var/lib/rabbitmq `
           rabbitmq:latest

How to draw vectors (physical 2D/3D vectors) in MATLAB?

I agree with Aamir that the submission arrow.m from Erik Johnson on the MathWorks File Exchange is a very nice option. You can use it to illustrate the different methods of vector addition like so:

  • Tip-to-tail method:

    o = [0 0 0];  %# Origin
    a = [2 3 5];  %# Vector 1
    b = [1 1 0];  %# Vector 2
    c = a+b;      %# Resultant
    arrowStarts = [o; a; o];        %# Starting points for arrows
    arrowEnds = [a; c; c];          %# Ending points for arrows
    arrow(arrowStarts,arrowEnds);   %# Plot arrows
    
  • Parallelogram method:

    o = [0 0 0];  %# Origin
    a = [2 3 5];  %# Vector 1
    b = [1 1 0];  %# Vector 2
    c = a+b;      %# Resultant
    arrowStarts = [o; o; o];        %# Starting points for arrows
    arrowEnds = [a; b; c];          %# Ending points for arrows
    arrow(arrowStarts,arrowEnds);   %# Plot arrows
    hold on;
    lineX = [a(1) b(1); c(1) c(1)];  %# X data for lines
    lineY = [a(2) b(2); c(2) c(2)];  %# Y data for lines
    lineZ = [a(3) b(3); c(3) c(3)];  %# Z data for lines
    line(lineX,lineY,lineZ,'Color','k','LineStyle',':');  %# Plot lines
    

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

I haven't seen the official steps recommended by the MySQL 8.0 guide, which were the only ones that worked for me. Here's a summary of those steps.

  1. Stop the MySQL server if it is running. Look in /var/lib/mysql/, /var/run/mysqld/, or /usr/local/mysql/data/ to find the pid file with the server's process ID. Generally the file begins with either mysqld or your system's host name and ends with .pid. Replace mysql-data-directory and host_name that you just found, in the following command:

    $ sudo kill `sudo cat /mysql-data-directory/host_name.pid`
    
  2. This command will create a text file in /tmp/mysql-init with the SQL statement and makes the mysql user the owner. Replace in the command MyNewPass with your own password.

    $ echo "ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';" > /tmp/mysql-init && sudo chown mysql /tmp/mysql-init
    
  3. Start the MySQL server by running the following command on the command line. After this the password is updated and you can close the server again with CTRL+C.

    $ sudo mysqld --user=mysql --init-file=/tmp/mysql-init &
    
  4. Remove the temporary file with your password:

    $ sudo rm /tmp/mysql-init
    

Create SQLite database in android

this is the full source code to direct use,

    public class CardDBDAO {

        protected SQLiteDatabase database;
        private DataBaseHelper dbHelper;
        private Context mContext;

        public CardDBDAO(Context context) {
            this.mContext = context;
            dbHelper = DataBaseHelper.getHelper(mContext);
            open();

        }

        public void open() throws SQLException {
            if(dbHelper == null)
                dbHelper = DataBaseHelper.getHelper(mContext);
            database = dbHelper.getWritableDatabase();
        }

    }



    public class DataBaseHelper extends SQLiteOpenHelper {

        private static final String DATABASE_NAME = "mydbnamedb";
        private static final int DATABASE_VERSION = 1;

        public static final String CARDS_TABLE = "tbl_cards";
        public static final String POICATEGORIES_TABLE = "tbl_poicategories";
        public static final String POILANGS_TABLE = "tbl_poilangs";

        public static final String ID_COLUMN = "id";

        public static final String POI_ID = "poi_id";
        public static final String POICATEGORIES_COLUMN = "poi_categories";

        public static final String POILANGS_COLUMN = "poi_langs";

        public static final String CARDS = "cards";
        public static final String CARD_ID = "card_id";
        public static final String CARDS_PCAT_ID = "pcat_id";

        public static final String CREATE_PLANG_TABLE = "CREATE TABLE "
                + POILANGS_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY,"
                + POILANGS_COLUMN + " TEXT, " + POI_ID + " TEXT)";

        public static final String CREATE_PCAT_TABLE = "CREATE TABLE "
                + POICATEGORIES_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY,"
                + POICATEGORIES_COLUMN + " TEXT, " + POI_ID + " TEXT)";

        public static final String CREATE_CARDS_TABLE = "CREATE TABLE "
                + CARDS_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY," + CARD_ID
                + " TEXT, " + CARDS_PCAT_ID + " TEXT, " + CARDS + " TEXT)";

        private static DataBaseHelper instance;

        public static synchronized DataBaseHelper getHelper(Context context) {
            if (instance == null)
                instance = new DataBaseHelper(context);
            return instance;
        }

        private DataBaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onOpen(SQLiteDatabase db) {
            super.onOpen(db);
            if (!db.isReadOnly()) {
                // Enable foreign key constraints
                // db.execSQL("PRAGMA foreign_keys=ON;");
            }
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL(CREATE_PCAT_TABLE);
            db.execSQL(CREATE_PLANG_TABLE);
            db.execSQL(CREATE_CARDS_TABLE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        }
    }




    public class PoiLangDAO extends CardDBDAO {

            private static final String WHERE_ID_EQUALS = DataBaseHelper.ID_COLUMN
                    + " =?";

            public PoiLangDAO(Context context) {
                super(context);
            }

            public long save(PLang plang_data) {

                ContentValues values = new ContentValues();
                values.put(DataBaseHelper.POI_ID, plang_data.getPoi_id());
                values.put(DataBaseHelper.POILANGS_COLUMN, plang_data.getLangarr());

                return database
                        .insert(DataBaseHelper.POILANGS_TABLE, null, values);
            }

            public long update(PLang plang_data) {
                ContentValues values = new ContentValues();
                values.put(DataBaseHelper.POI_ID, plang_data.getPoi_id());
                values.put(DataBaseHelper.POILANGS_COLUMN, plang_data.getLangarr());

                long result = database.update(DataBaseHelper.POILANGS_TABLE,
                        values, WHERE_ID_EQUALS,
                        new String[] { String.valueOf(plang_data.getId()) });
                Log.d("Update Result:", "=" + result);
                return result;

            }

            public int deleteDept(PLang plang_data) {
                return database.delete(DataBaseHelper.POILANGS_TABLE,
                        WHERE_ID_EQUALS, new String[] { plang_data.getId() + "" });
            }

            public List<PLang> getPLangs1() {
                List<PLang> plang_list = new ArrayList<PLang>();
                Cursor cursor = database.query(DataBaseHelper.POILANGS_TABLE,
                        new String[] { DataBaseHelper.ID_COLUMN, DataBaseHelper.POI_ID,
                                DataBaseHelper.POILANGS_COLUMN }, null, null, null,
                        null, null);

                while (cursor.moveToNext()) {
                    PLang plang_bin = new PLang();
                    plang_bin.setId(cursor.getInt(0));
                    plang_bin.setPoi_id(cursor.getString(1));
                    plang_bin.setLangarr(cursor.getString(2));
                    plang_list.add(plang_bin);
                }
                return plang_list;
            }

            public List<PLang> getPLangs(String pid) {
                List<PLang> plang_list = new ArrayList<PLang>();

                String selection = DataBaseHelper.POI_ID + "=?";
                String[] selectionArgs = { pid };

                Cursor cursor = database.query(DataBaseHelper.POILANGS_TABLE,
                        new String[] { DataBaseHelper.ID_COLUMN, DataBaseHelper.POI_ID,
                                DataBaseHelper.POILANGS_COLUMN }, selection,
                        selectionArgs, null, null, null);

                while (cursor.moveToNext()) {
                    PLang plang_bin = new PLang();
                    plang_bin.setId(cursor.getInt(0));
                    plang_bin.setPoi_id(cursor.getString(1));
                    plang_bin.setLangarr(cursor.getString(2));
                    plang_list.add(plang_bin);
                }
                return plang_list;
            }

            public void loadPLangs(String poi_id, String langarrs) {
                PLang plangbin = new PLang(poi_id, langarrs);

                List<PLang> plang_arr = new ArrayList<PLang>();
                plang_arr.add(plangbin);

                for (PLang dept : plang_arr) {
                    ContentValues values = new ContentValues();
                    values.put(DataBaseHelper.POI_ID, dept.getPoi_id());
                    values.put(DataBaseHelper.POILANGS_COLUMN, dept.getLangarr());
                    database.insert(DataBaseHelper.POILANGS_TABLE, null, values);
                }
            }

        }




        public class PLang {

            public PLang() {
                super();
            }

            public PLang(String poi_id, String langarrs) {
                // TODO Auto-generated constructor stub

                this.poi_id = poi_id;
                this.langarr = langarrs;
            }

            public int getId() {
                return id;
            }

            public void setId(int id) {
                this.id = id;
            }

            public String getPoi_id() {
                return poi_id;
            }

            public void setPoi_id(String poi_id) {
                this.poi_id = poi_id;
            }

            public String getLangarr() {
                return langarr;
            }

            public void setLangarr(String langarr) {
                this.langarr = langarr;
            }

            private int id;
            private String poi_id;
            private String langarr;

    }

Iterate a list with indexes in Python

Yep, that would be the enumerate function! Or more to the point, you need to do:

list(enumerate([3,7,19]))

[(0, 3), (1, 7), (2, 19)]

React Native: Possible unhandled promise rejection

In My case, I am running a local Django backend in IP 127.0.0.1:8000 with Expo start. Just make sure you have the server in public domain not hosted lcoally on your machine

Finding absolute value of a number without using Math.abs()

Here is a one-line solution that will return the absolute value of a number:

abs_number = (num < 0) ? -num : num;

Add/remove class with jquery based on vertical scroll?

Is this value intended? if (scroll <= 500) { ... This means it's happening from 0 to 500, and not 500 and greater. In the original post you said "after the user scrolls down a little"

Regular vs Context Free Grammars

The difference between regular and context free grammar: (N, S, P, S) : terminals, nonterminals, productions, starting state Terminal symbols

? elementary symbols of the language defined by a formal grammar

? abc

Nonterminal symbols (or syntactic variables)

? replaced by groups of terminal symbols according to the production rules

? ABC

regular grammar: right or left regular grammar right regular grammar, all rules obey the forms

  1. B ? a where B is a nonterminal in N and a is a terminal in S
  2. B ? aC where B and C are in N and a is in S
  3. B ? e where B is in N and e denotes the empty string, i.e. the string of length 0

left regular grammar, all rules obey the forms

  1. A ? a where A is a nonterminal in N and a is a terminal in S
  2. A ? Ba where A and B are in N and a is in S
  3. A ? e where A is in N and e is the empty string

context free grammar (CFG)

? formal grammar in which every production rule is of the form V ? w

? V is a single nonterminal symbol

? w is a string of terminals and/or nonterminals (w can be empty)

how to stop a loop arduino

just use this line to exit function:

return;

sqlite copy data from one table to another

If you're copying data like that, that probably means your datamodel isn't fully normalized, right? Is it possible to make one list of countries and do a JOIN more?

Instead of a JOIN you could also use virtual tables so you don't have to change the queries in your system.

How to force remounting on React components?

Use setState in your view to change employed property of state. This is example of React render engine.

 someFunctionWhichChangeParamEmployed(isEmployed) {
      this.setState({
          employed: isEmployed
      });
 }

 getInitialState() {
      return {
          employed: true
      }
 },

 render(){
    if (this.state.employed) {
        return (
            <div>
                <MyInput ref="job-title" name="job-title" />
            </div>
        );
    } else {
        return (
            <div>
                <span>Diff me!</span>
                <MyInput ref="unemployment-reason" name="unemployment-reason" />
                <MyInput ref="unemployment-duration" name="unemployment-duration" />
            </div>
        );
    }
}

How to uninstall / completely remove Oracle 11g (client)?

There are some more actions you should consider:

  • Remove Registry Entries for MS Distributed Transaction Coordinator (MSDTC)

    Note: on the Internet I found this step only at a single (private) page. I don't know if it is required/working or if it breaks anything on your PC.

    • Open Regedit
    • Navigate to HKEY_LOCAL_MACHINE\Software\Microsoft\MSDTC\MTxOCI
    • Add an x before each string for OracleOciLib, OracleSqlLib, and OracleXaLib
    • Navigate to HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\MSDTC\MTxOCI
    • Add an x before each string for OracleOciLib, OracleSqlLib, and OracleXaLib

    Otherwise these files, if they exist, will still be in use next time you reboot, and unable to be deleted.

  • Remove environment variable ORACLE_HOME, ORACLE_BASE, TNS_ADMIN, NLS_LANG if exist

    Check also Oracle doc to find all Oracle related environment variables, however apart from variables listed above they are very rarely used on Windows Client: Oracle Environment Variables

  • Unregister oci.dll

    • Open a command line window (Start Menu -> Run... -> cmd)
    • Enter regsvr32 /u oci.dll, resp. %windir%\SysWOW64\regsvr32 /u oci.dll

    • In some cases the file %ORACLE_HOME%\bin\oci.dll is locked and you cannot delete it. In such case rename the file (e.g. to oci.dll.x) and reboot the PC, afterwards you can delete it.

  • Remove Oracle .NET assemblies from Global Assembly Cache (GAC). You do this typically with the gacutil utility, if available on your system. Would be like this:

    gacutil /u Policy.10.1.Oracle.DataAccess
    gacutil /u Policy.10.2.Oracle.DataAccess
    gacutil /u Policy.1.102.Oracle.DataAccess
    gacutil /u Policy.1.111.Oracle.DataAccess
    
    gacutil /u Policy.2.102.Oracle.DataAccess
    gacutil /u Policy.2.111.Oracle.DataAccess
    gacutil /u Policy.2.112.Oracle.DataAccess
    gacutil /u Policy.2.121.Oracle.DataAccess
    gacutil /u Policy.2.122.Oracle.DataAccess
    
    gacutil /u Policy.4.112.Oracle.DataAccess
    gacutil /u Policy.4.121.Oracle.DataAccess
    gacutil /u Policy.4.122.Oracle.DataAccess
    
    gacutil /u Oracle.DataAccess
    gacutil /u Oracle.DataAccess.resources
    
    gacutil /u Policy.4.121.Oracle.ManagedDataAccess
    gacutil /u Policy.4.122.Oracle.ManagedDataAccess
    gacutil /u Oracle.ManagedDataAccess
    gacutil /u Oracle.ManagedDataAccess.resources
    gacutil /u Oracle.ManagedDataAccessDTC
    gacutil /u Oracle.ManagedDataAccessIOP
    gacutil /u Oracle.ManagedDataAccess.EntityFramework
    
    • Entry System.Data.OracleClient should not be removed, this one is installed by Microsoft - not an Oracle component!

    • Instead of gacutil /u ... you can also use OraProvCfg /action:ungac /providerpath:... if OraProvCfg is still available on your system. You may find it at %ORACLE_HOME%\odp.net\managed\x64\OraProvCfg.exe.

  • With a text editor, open XML Config file %SYSTEMROOT%\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config and delete branch <oracle.manageddataaccess.client>, if existing.

    • Do the same with:

      %SYSTEMROOT%\Microsoft.NET\Framework64\v4.0.30319\Config\machine.config
      %SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319\Config\machine.config
      %SYSTEMROOT%\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
      %SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319\Config\web.config
      

    Instead of editing the XML Config file manually you can also run (if OraProvCfg.exe is still available on your system):

    %ORACLE_HOME%\odp.net\managed\x64\OraProvCfg.exe /action:unconfig /product:odpm /frameworkversion:v4.0.30319 
    %ORACLE_HOME%\odp.net\managed\x86\OraProvCfg.exe /action:unconfig /product:odpm /frameworkversion:v4.0.30319
    %ORACLE_HOME%\odp.net\managed\x64\OraProvCfg.exe /action:unconfig /product:odp /frameworkversion:v4.0.30319 
    %ORACLE_HOME%\odp.net\managed\x86\OraProvCfg.exe /action:unconfig /product:odp /frameworkversion:v4.0.30319
    
  • Check following Registry Keys and delete them if existing

    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v2.0.50727\AssemblyFoldersEx\ODP.Net
    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\ODP.Net
    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.ManagedDataAccess
    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.ManagedDataAccess.EntityFramework6
    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\odp.net.managed
    HKLM\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.DataAccess.EntityFramework6\
    
    HKLM\SOFTWARE\Microsoft\.NETFramework\v2.0.50727\AssemblyFoldersEx\ODP.Net
    HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\ODP.Net
    HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.ManagedDataAccess
    HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.ManagedDataAccess.EntityFramework6
    HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\odp.net.managed
    HKLM\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx\Oracle.DataAccess.EntityFramework6\
    
    HKLM\SYSTEM\CurrentControlSet\Services\EventLog\Application\Oracle Data Provider for .NET, Managed Driver
    HKLM\SYSTEM\CurrentControlSet\Services\EventLog\Application\Oracle Data Provider for .NET, Unmanaged Driver
    HKLM\SYSTEM\CurrentControlSet\Services\EventLog\Application\Oracle Provider for OLE DB
    
  • Delete the Inventory folder, typically C:\Program Files\Oracle\Inventory and C:\Program Files (x86)\Oracle\Inventory

  • Delete temp folders %TEMP%\deinstall\, %TEMP%\OraInstall\ and %TEMP%\CVU* (e.g %TEMP%\CVU_11.1.0.2.0_domscheit) if existing.

How to setup virtual environment for Python in VS Code?

There is a VSCode extension called "Python Auto Venv" that automatically detects and uses your virtual environment if there is one.

Jenkins - how to build a specific branch

This is extension of answer provided by Ranjith

I would suggest, you to choose a choice-parameter build, and specify the branches that you would like to build. Active Choice Parameter

And after that, you can specify branches to build. Branch to Build

Now, when you would build your project, you would be provided with "Build with Parameters, where you can choose the branch to build"

You can also write a groovy script to fetch all your branches to in active choice parameter.

jQuery .each() with input elements

Assume if all the input elements are inside a form u can refer the below code.

 // get all the inputs into an array.

    var $inputs = $('#myForm :input');

    // not sure if you wanted this, but I thought I'd add it.
    // get an associative array of just the values.
    var values = {};
    $inputs.each(function() {
        values[this.name] = $(this).val();
    });

What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

For my project's setup, "${pageContext.request.contextPath}"= refers to "src/main/webapp". Another way to tell is by right clicking on your project in Eclipse and then going to Properties:

enter image description here

How can I make a countdown with NSTimer?

XCode 10 with Swift 4.2

import UIKit

class ViewController: UIViewController {

   var timer = Timer()
   var totalSecond = 10

   override func viewDidLoad() {
       super.viewDidLoad()
       startTimer()
   }


   func startTimer() {
       timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
   }

   @objc func updateTime() {

        print(timeFormatted(totalSecond))

        if totalSecond != 0 {
           totalSecond -= 1
        } else {
           endTimer()
        }
    }

    func endTimer() {
        timer.invalidate()
    }

    func timeFormatted(_ totalSeconds: Int) -> String {
        let seconds: Int = totalSeconds % 60
        return String(format: "0:%02d", seconds)
    }

}

Difference between single and double quotes in Bash

The accepted answer is great. I am making a table that helps in quick comprehension of the topic. The explanation involves a simple variable a as well as an indexed array arr.

If we set

a=apple      # a simple variable
arr=(apple)  # an indexed array with a single element

and then echo the expression in the second column, we would get the result / behavior shown in the third column. The fourth column explains the behavior.

# Expression Result Comments
1 "$a" apple variables are expanded inside ""
2 '$a' $a variables are not expanded inside ''
3 "'$a'" 'apple' '' has no special meaning inside ""
4 '"$a"' "$a" "" is treated literally inside ''
5 '\'' invalid can not escape a ' within ''; use "'" or $'\'' (ANSI-C quoting)
6 "red$arocks" red $arocks does not expand $a; use ${a}rocks to preserve $a
7 "redapple$" redapple$ $ followed by no variable name evaluates to $
8 '\"' \" \ has no special meaning inside ''
9 "\'" \' \' is interpreted inside "" but has no significance for '
10 "\"" " \" is interpreted inside ""
11 "*" * glob does not work inside "" or ''
12 "\t\n" \t\n \t and \n have no special meaning inside "" or ''; use ANSI-C quoting
13 "`echo hi`" hi `` and $() are evaluated inside "" (backquotes are retained in actual output)
14 '`echo hi`' echo hi `` and $() are not evaluated inside '' (backquotes are retained in actual output)
15 '${arr[0]}' ${arr[0]} array access not possible inside ''
16 "${arr[0]}" apple array access works inside ""
17 $'$a\'' $a' single quotes can be escaped inside ANSI-C quoting
18 "$'\t'" $'\t' ANSI-C quoting is not interpreted inside ""
19 '!cmd' !cmd history expansion character '!' is ignored inside ''
20 "!cmd" cmd args expands to the most recent command matching "cmd"
21 $'!cmd' !cmd history expansion character '!' is ignored inside ANSI-C quotes

See also:

Python: fastest way to create a list of n lists

So I did some speed comparisons to get the fastest way. List comprehensions are indeed very fast. The only way to get close is to avoid bytecode getting exectuded during construction of the list. My first attempt was the following method, which would appear to be faster in principle:

l = [[]]
for _ in range(n): l.extend(map(list,l))

(produces a list of length 2**n, of course) This construction is twice as slow as the list comprehension, according to timeit, for both short and long (a million) lists.

My second attempt was to use starmap to call the list constructor for me, There is one construction, which appears to run the list constructor at top speed, but still is slower, but only by a tiny amount:

from itertools import starmap
l = list(starmap(list,[()]*(1<<n)))

Interesting enough the execution time suggests that it is the final list call that is makes the starmap solution slow, since its execution time is almost exactly equal to the speed of:

l = list([] for _ in range(1<<n))

My third attempt came when I realized that list(()) also produces a list, so I tried the apperently simple:

l = list(map(list, [()]*(1<<n)))

but this was slower than the starmap call.

Conclusion: for the speed maniacs: Do use the list comprehension. Only call functions, if you have to. Use builtins.

Easier way to create circle div than using an image?

You can try the radial-gradient CSS function:

.circle {
    width: 500px;
    height: 500px;
    border-radius: 50%;
    background: #ffffff; /* Old browsers */
    background: -moz-radial-gradient(center, ellipse cover, #ffffff 17%, #ff0a0a 19%, #ff2828 40%, #000000 41%); /* FF3.6-15 */
    background: -webkit-radial-gradient(center, ellipse cover, #ffffff 17%,#ff0a0a 19%,#ff2828 40%,#000000 41%); /* Chrome10-25,Safari5.1-6 */
    background: radial-gradient(ellipse at center, #ffffff 17%,#ff0a0a 19%,#ff2828 40%,#000000 41%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
}

Apply it to a div layer:

<div class="circle"></div>

How to get the difference between two arrays of objects in JavaScript

I found this solution using filter and some.

_x000D_
_x000D_
resultFilter = (firstArray, secondArray) => {_x000D_
  return firstArray.filter(firstArrayItem =>_x000D_
    !secondArray.some(_x000D_
      secondArrayItem => firstArrayItem._user === secondArrayItem._user_x000D_
    )_x000D_
  );_x000D_
};
_x000D_
_x000D_
_x000D_

How to read from a file or STDIN in Bash?

Perl's behavior, with the code given in the OP can take none or several arguments, and if an argument is a single hyphen - this is understood as stdin. Moreover, it's always possible to have the filename with $ARGV. None of the answers given so far really mimic Perl's behavior in these respects. Here's a pure Bash possibility. The trick is to use exec appropriately.

#!/bin/bash

(($#)) || set -- -
while (($#)); do
   { [[ $1 = - ]] || exec < "$1"; } &&
   while read -r; do
      printf '%s\n' "$REPLY"
   done
   shift
done

Filename's available in $1.

If no arguments are given, we artificially set - as the first positional parameter. We then loop on the parameters. If a parameter is not -, we redirect standard input from filename with exec. If this redirection succeeds we loop with a while loop. I'm using the standard REPLY variable, and in this case you don't need to reset IFS. If you want another name, you must reset IFS like so (unless, of course, you don't want that and know what you're doing):

while IFS= read -r line; do
    printf '%s\n' "$line"
done

Export P7b file with all the certificate chain into CER file

If you add -chain to your command line, it will export any chained certificates.

http://www.openssl.org/docs/apps/pkcs12.html

How read Doc or Docx file in java?

Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.

import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ReadDocFile
{
    public static void main(String[] args)
    {
        File file = null;
        WordExtractor extractor = null;
        try
        {

            file = new File("c:\\New.doc");
            FileInputStream fis = new FileInputStream(file.getAbsolutePath());
            HWPFDocument document = new HWPFDocument(fis);
            extractor = new WordExtractor(document);
            String[] fileData = extractor.getParagraphText();
            for (int i = 0; i < fileData.length; i++)
            {
                if (fileData[i] != null)
                    System.out.println(fileData[i]);
            }
        }
        catch (Exception exep)
        {
            exep.printStackTrace();
        }
    }
}

How to see which flags -march=native will activate?

To see command-line flags, use:

gcc -march=native -E -v - </dev/null 2>&1 | grep cc1

If you want to see the compiler/precompiler defines set by certain parameters, do this:

echo | gcc -dM -E - -march=native

docker unauthorized: authentication required - upon push with successful login

What worked for me was to create a new repository and rename the image with

$ docker tag image_id myname/server:latest

What is "406-Not Acceptable Response" in HTTP?

In my case, I added:

Content-Type: application/x-www-form-urlencoded

solved my problem completely.

How to determine when Fragment becomes visible in ViewPager

Only this worked for me!! and setUserVisibleHint(...) is now deprecated (I attached docs at end), which means any other answer is deprecated ;-)

public class FragmentFirewall extends Fragment {
    /**
     * Required cause "setMenuVisibility(...)" is not guaranteed to be
     * called after "onResume()" and/or "onCreateView(...)" method.
     */
    protected void didVisibilityChange() {
        Activity activity = getActivity();
        if (isResumed() && isMenuVisible()) {
            // Once resumed and menu is visible, at last
            // our Fragment is really visible to user.
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        didVisibilityChange();
    }

    @Override
    public void setMenuVisibility(boolean visible) {
        super.setMenuVisibility(visible);
        didVisibilityChange();
    }
}

Tested and works with NaviagationDrawer as well, there isMenuVisible() will always return true (and onResume() seems enough, but we want to support ViewPager too).

setUserVisibleHint is deprecated. If overriding this method, behavior implemented when passing in true should be moved to Fragment.onResume(), and behavior implemented when passing in false should be moved to Fragment.onPause().

Clear and reset form input fields

/* See newState and use of it in eventSubmit() for resetting all the state. I have tested it is working for me. Please let me know for mistakes */

import React from 'react';
    
    const newState = {
        fullname: '',
        email: ''
    }
    
    class Form extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                fullname: ' ',
                email: ' '
            }
    
            this.eventChange = this
                .eventChange
                .bind(this);
            this.eventSubmit = this
                .eventSubmit
                .bind(this);
        }
        eventChange(event) {
            const target = event.target;
            const value = target.type === 'checkbox'
                ? target.type
                : target.value;
            const name = target.name;
    
            this.setState({[name]: value})
        }
    
        eventSubmit(event) {
            alert(JSON.stringify(this.state))
            event.preventDefault();
            this.setState({...newState});
        }
    
        render() {
            return (
                <div className="container">
                    <form className="row mt-5" onSubmit={this.eventSubmit}>
                        <label className="col-md-12">
                            Full Name
                            <input
                                type="text"
                                name="fullname"
                                id="fullname"
                                value={this.state.fullname}
                                onChange={this.eventChange}/>
                        </label>
                        <label className="col-md-12">
                            email
                            <input
                                type="text"
                                name="email"
                                id="email"
                                value={this.state.value}
                                onChange={this.eventChange}/>
                        </label>
                        <input type="submit" value="Submit"/>
                    </form>
                </div>
            )
        }
    }
    
    export default Form;
    

How to make Git "forget" about a file that was tracked but is now in .gitignore?

This is no longer an issue in the latest git (v2.17.1 at the time of writing).

The .gitignore finally ignores tracked-but-deleted files. You can test this for yourself by running the following script. The final git status statement should report "nothing to commit".

# Create empty repo
mkdir gitignore-test
cd gitignore-test
git init

# Create a file and commit it
echo "hello" > file
git add file
git commit -m initial

# Add the file to gitignore and commit
echo "file" > .gitignore
git add .gitignore
git commit -m gitignore

# Remove the file and commit
git rm file
git commit -m "removed file"

# Reintroduce the file and check status.
# .gitignore is now respected - status reports "nothing to commit".
echo "hello" > file
git status

How do I run a PowerShell script when the computer starts?

enter image description hereA relatively short path to specifying a Powershell script to execute at startup in Windows could be:

  1. Click the Windows-button (Windows-button + r)
  2. Enter this:

shell:startup

  1. Create a new shortcut by rightclick and in context menu choose menu item: New=>Shortcut

  2. Create a shortcut to your script, e.g:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "C:\Users\someuser\Documents\WindowsPowerShell\Scripts\somesscript.ps1"

Note the use of -NoProfile In case you put a lot of initializing in your $profile file, it is inefficient to load this up to just run a Powershell script. The -NoProfile will skip loading your profile file and is smart to specify, if it is not necessary to run it before the Powershell script is to be executed.

Here you see such a shortcut created (.lnk file with a Powershell icon with shortcut glyph):

Enforcing the type of the indexed members of a Typescript object?

var stuff: { [key: string]: string; } = {};
stuff['a'] = ''; // ok
stuff['a'] = 4;  // error

// ... or, if you're using this a lot and don't want to type so much ...
interface StringMap { [key: string]: string; }
var stuff2: StringMap = { };
// same as above

Check if pull needed in Git

Here's my version of a Bash script that checks all repositories in a predefined folder:

https://gist.github.com/henryiii/5841984

It can differentiate between common situations, like pull needed and push needed, and it is multithreaded, so the fetch happens all at once. It has several commands, like pull and status.

Put a symlink (or the script) in a folder in your path, then it works as git all status (, etc.). It only supports origin/master, but it can be edited or combined with another method.

Upload Progress Bar in PHP

Implementation of the upload progress bar is easy and doesn't require any additional PHP extension, JavaScript or Flash. But you need PHP 5.4 and newer.

You have to enable collecting of the upload progress information by setting the directive session.upload_progress.enabled to On in php.ini.

Then add a hidden input to the HTML upload form just before any other file inputs. HTML attribute name of that hidden input should be the same as the value of the directive session.upload_progress.name from php.ini (eventually preceded by session.upload_progress.prefix). The value attribute is up to you, it will be used as part of the session key.

HTML form could looks like this:

<form action="upload.php" method="POST" enctype="multipart/form-data">
   <input type="hidden" name="<?php echo ini_get('session.upload_progress.prefix').ini_get('session.upload_progress.name'); ?>" value="myupload" />
   <input type="file" name="file1" />
   <input type="submit" />
</form>

When you send this form, PHP should create a new key in the $_SESSION superglobal structure which will be populated with the upload status information. The key is concatenated name and value of the hidden input.

In PHP you can take a look at populated upload information:

var_dump($_SESSION[
    ini_get('session.upload_progress.prefix')
   .ini_get('session.upload_progress.name')
   .'_myupload'
]);

The output will look similarly to the following:

$_SESSION["upload_progress_myupload"] = array(
  "start_time" => 1234567890,   // The request time
  "content_length" => 57343257, // POST content length
  "bytes_processed" => 54321,   // Amount of bytes received and processed
  "done" => false,              // true when the POST handler has finished, successfully or not
  "files" => array(
    0 => array(
      "field_name" => "file1",    // Name of the <input /> field
      // The following 3 elements equals those in $_FILES
      "name" => "filename.ext",
      "tmp_name" => "/tmp/phpxxxxxx",
      "error" => 0,
      "done" => false,            // True when the POST handler has finished handling this file
      "start_time" => 1234567890, // When this file has started to be processed
      "bytes_processed" => 54321, // Number of bytes received and processed for this file
    )
  )
);

There is all the information needed to create a progress bar — you have the information if the upload is still in progress, the information how many bytes is going to be transferred in total and how many bytes has been transferred already.

To present the upload progress to the user, write an another PHP script than the uploading one, which will only look at the upload information in the session and return it in the JSON format, for example. This script can be called periodically, for example every second, using AJAX and information presented to the user.

You are even able to cancel the upload by setting the $_SESSION[$key]['cancel_upload'] to true.

For detailed information, additional settings and user's comments see PHP manual.

How to get number of rows inserted by a transaction

In case you need further info for your log/audit you can OUTPUT clause: This way, not only you keep the number of rows affected, but also what records.

As an example of the Output Clause during inserts: SQL Server list of insert identities

DECLARE @InsertedIDs table(ID int);

INSERT INTO YourTable
    OUTPUT INSERTED.ID
        INTO @InsertedIDs 
    SELECT ...

HTH

jQuery send string as POST parameters

Not sure whether this is still actual.. just for future readers. If what you really want is to pass your parameters as part of the URL, you should probably use jQuery.param().

How to check if an excel cell is empty using Apache POI?

Try below code:

String empty = "-";
if (row.getCell(3) == null || row.getCell(3).getCellType() == Cell.CELL_TYPE_BLANK) {
    upld.setValue(empty);
} else {
    upld.setValue(row.getCell(3).getStringCellValue());
}

How do I syntax check a Bash script without running it?

sh  -n   script-name 

Run this. If there are any syntax errors in the script, then it returns the same error message. If there are no errors, then it comes out without giving any message. You can check immediately by using echo $?, which will return 0 confirming successful without any mistake.

It worked for me well. I ran on Linux OS, Bash Shell.

Pure CSS checkbox image replacement

Using javascript seems to be unnecessary if you choose CSS3.

By using :before selector, you can do this in two lines of CSS. (no script involved).

Another advantage of this approach is that it does not rely on <label> tag and works even it is missing.

Note: in browsers without CSS3 support, checkboxes will look normal. (backward compatible).

input[type=checkbox]:before { content:""; display:inline-block; width:12px; height:12px; background:red; }
input[type=checkbox]:checked:before { background:green; }?

You can see a demo here: http://jsfiddle.net/hqZt6/1/

and this one with images:

http://jsfiddle.net/hqZt6/6/

How do I run a node.js app as a background service?

If you are running nodejs in linux server, I think this is the best way.

Create a service script and copy to /etc/init/nodejs.conf

start service: sudo service nodejs start

stop service: sudo service nodejs stop

Sevice script

description "DManager node.js server - Last Update: 2012-08-06"
author      "Pedro Muniz - [email protected]"

env USER="nodejs" #you have to create this user 
env APPNAME="nodejs" #you can change the service name
env WORKDIR="/home/<project-home-dir>" #set your project home folder here
env COMMAND="/usr/bin/node <server name>" #app.js ?

# used to be: start on startup
# until we found some mounts weren't ready yet while booting:
start on started mountall
stop on shutdown

# Automatically Respawn:
respawn
respawn limit 99 5

pre-start script
    sudo -u $USER echo "[`date -u +%Y-%m-%dT%T.%3NZ`] (sys) Starting" >> /var/log/$APPNAME.log
end script

script
    # Not sure why $HOME is needed, but we found that it is:
    export HOME="<project-home-dir>"  #set your project home folder here
    export NODE_PATH="<project node_path>"

    #log file, grant permission to nodejs user
    exec start-stop-daemon --start --make-pidfile --pidfile /var/run/$APPNAME.pid --chuid $USER --chdir $WORKDIR --exec $COMMAND >> /var/log/$APPNAME.log 2>&1
end script

post-start script
   # Optionally put a script here that will notifiy you node has (re)started
   # /root/bin/hoptoad.sh "node.js has started!"
end script

pre-stop script
    sudo -u $USER echo "[`date -u +%Y-%m-%dT%T.%3NZ`] (sys) Stopping" >> /var/log/$APPNAME.log
end script

How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

Wrote my own test. tested the code on stackoverflow, works fine tells me that chrome/FF can do 6

var change = 0;
var simultanius = 0;
var que = 20; // number of tests

Array(que).join(0).split(0).forEach(function(a,i){
    var xhr = new XMLHttpRequest;
    xhr.open("GET", "/?"+i); // cacheBust
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 2){
            change++;
            simultanius = Math.max(simultanius, change);
        }
        if(xhr.readyState == 4){
            change--;
            que--;
            if(!que){
                console.log(simultanius);
            }
        }
    };
    xhr.send();
});

it works for most websites that can trigger readystate change event at different times. (aka: flushing)

I notice on my node.js server that i had to output at least 1025 bytes to trigger the event/flush. otherwise the events would just trigger all three state at once when the request is complete so here is my backend:

var app = require('express')();

app.get("/", function(req,res) {
    res.write(Array(1025).join("a"));
    setTimeout(function() {
        res.end("a");
    },500);
});

app.listen(80);

Update

I notice that You can now have up to 2x request if you are using both xhr and fetch api at the same time

_x000D_
_x000D_
var change = 0;_x000D_
var simultanius = 0;_x000D_
var que = 30; // number of tests_x000D_
_x000D_
Array(que).join(0).split(0).forEach(function(a,i){_x000D_
    fetch("/?b"+i).then(r => {_x000D_
        change++;_x000D_
        simultanius = Math.max(simultanius, change);_x000D_
        return r.text()_x000D_
    }).then(r => {_x000D_
        change--;_x000D_
        que--;_x000D_
        if(!que){_x000D_
            console.log(simultanius);_x000D_
        }_x000D_
    });_x000D_
});_x000D_
_x000D_
Array(que).join(0).split(0).forEach(function(a,i){_x000D_
    var xhr = new XMLHttpRequest;_x000D_
    xhr.open("GET", "/?a"+i); // cacheBust_x000D_
    xhr.onreadystatechange = function() {_x000D_
        if(xhr.readyState == 2){_x000D_
            change++;_x000D_
            simultanius = Math.max(simultanius, change);_x000D_
        }_x000D_
        if(xhr.readyState == 4){_x000D_
            change--;_x000D_
            que--;_x000D_
            if(!que){_x000D_
                document.body.innerHTML = simultanius;_x000D_
            }_x000D_
        }_x000D_
    };_x000D_
    xhr.send();_x000D_
});
_x000D_
_x000D_
_x000D_

Python script to convert from UTF-8 to ASCII

data="UTF-8 DATA"
udata=data.decode("utf-8")
asciidata=udata.encode("ascii","ignore")

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

Use :

$(PROJECT_DIR)/Project name/PrefixHeader.pch

Getting full URL of action in ASP.NET MVC

This question is specific to ASP .NET however I am sure some of you will benefit of system agnostic javascript which is beneficial in many situations.

UPDATE: The way to get url formed outside of the page itself is well described in answers above.

Or you could do a oneliner like following:

new UrlHelper(actionExecutingContext.RequestContext).Action(
    "SessionTimeout", "Home", 
    new {area = string.Empty}, 
    actionExecutingContext.Request.Url!= null? 
    actionExecutingContext.Request.Url.Scheme : "http"
);

from filter or:

new UrlHelper(this.Request.RequestContext).Action(
    "Details", 
    "Journey", 
    new { area = productType }, 
    this.Request.Url!= null? this.Request.Url.Scheme : "http"
);

However quite often one needs to get the url of current page, for those cases using Html.Action and putting he name and controller of page you are in to me feels awkward. My preference in such cases is to use JavaScript instead. This is especially good in systems that are half re-written MVT half web-forms half vb-script half God knows what - and to get URL of current page one needs to use different method every time.

One way is to use JavaScript to get URL is window.location.href another - document.URL

Using setImageDrawable dynamically to set image in an ImageView

This works, at least in Android API 15

ImageView = imgv;
Resources res = getResources(); // need this to fetch the drawable
Drawable draw = res.getDrawable( R.drawable.image_name_in_drawable );
imgv.setImageDrawable(draw);

You could use setImageResource(), but the documentation specifies that "does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup ... consider using setImageDrawable() or setImageBitmap()." as stated by chetto

Casting an int to a string in Python

Either:

"ME" + str(i)

Or:

"ME%d" % i

The second one is usually preferred, especially if you want to build a string from several tokens.

Getting the source of a specific image element with jQuery

To select and element where you know only the attribute value you can use the below jQuery script

var src = $('.conversation_img[alt="example"]').attr('src');

Please refer the jQuery Documentation for attribute equals selectors

Please also refer to the example in Demo

Following is the code incase you are not able to access the demo..

HTML

<div>
    <img alt="example" src="\images\show.jpg" />
    <img  alt="exampleAll" src="\images\showAll.jpg" />  

</div>

SCRIPT JQUERY

var src = $('img[alt="example"]').attr('src');
alert("source of image with alternate text = example - " + src);


var srcAll = $('img[alt="exampleAll"]').attr('src');
alert("source of image with alternate text = exampleAll - " + srcAll );

Output will be

Two Alert messages each having values

  1. source of image with alternate text = example - \images\show.jpg
  2. source of image with alternate text = exampleAll - \images\showAll.jpg

Force GUI update from UI Thread

I've just stumbled over the same problem and found some interesting information and I wanted to put in my two cents and add it here.

First of all, as others have already mentioned, long-running operations should be done by a thread, which can be a background worker, an explicit thread, a thread from the threadpool or (since .Net 4.0) a task: Stackoverflow 570537: update-label-while-processing-in-windows-forms, so that the UI keeps responsive.

But for short tasks there is no real need for threading although it doesn't hurt of course.

I have created a winform with one button and one label to analyze this problem:

System::Void button1_Click(System::Object^  sender, System::EventArgs^  e)
{
  label1->Text = "Start 1";
  label1->Update();
  System::Threading::Thread::Sleep(5000); // do other work
}

My analysis was stepping over the code (using F10) and seeing what happened. And after reading this article Multithreading in WinForms I have found something interesting. The article says at the bottom of the first page, that the UI thread can not repaint the UI until the currently executed function finishes and the window is marked by Windows as "not responding" instead after a while. I have also noticed that on my test application from above while stepping through it, but only in certain cases.

(For the following test it is important to not have Visual Studio set to fullscreen, you must be able to see your little application window at the same time next to it, You must not have to switch between the Visual Studio window for debugging and your application window to see what happens. Start the application, set a breakpoint at label1->Text ..., put the application window beside the VS window and place the mouse cursor over the VS window.)

  1. When I click once on VS after app start (to put the focues there and enable stepping) and step through it WITHOUT moving the mouse, the new text is set and the label is updated in the update() function. This means, the UI is repainted obviously.

  2. When I step over the first line, then move the mouse around a lot and click somewhere, then step further, the new text is likely set and the update() function is called, but the UI is not updated/repainted and the old text remains there until the button1_click() function finishes. Instead of repainting, the window is marked as "not responsive"! It also doesn't help to add this->Update(); to update the whole form.

  3. Adding Application::DoEvents(); gives the UI a chance to update/repaint. Anyway you have to take care that the user can not press buttons or perform other operations on the UI that are not permitted!! Therefore: Try to avoid DoEvents()!, better use threading (which I think is quite simple in .Net).
    But (@Jagd, Apr 2 '10 at 19:25) you can omit .refresh() and .invalidate().

My explanations is as following: AFAIK winform still uses the WINAPI function. Also MSDN article about System.Windows.Forms Control.Update method refers to WINAPI function WM_PAINT. The MSDN article about WM_PAINT states in its first sentence that the WM_PAINT command is only sent by the system when the message queue is empty. But as the message queue is already filled in the 2nd case, it is not send and thus the label and the application form are not repainted.

<>joke> Conclusion: so you just have to keep the user from using the mouse ;-) <>/joke>

C#: Looping through lines of multiline string

from MSDN for StringReader

    string textReaderText = "TextReader is the abstract base " +
        "class of StreamReader and StringReader, which read " +
        "characters from streams and strings, respectively.\n\n" +

        "Create an instance of TextReader to open a text file " +
        "for reading a specified range of characters, or to " +
        "create a reader based on an existing stream.\n\n" +

        "You can also use an instance of TextReader to read " +
        "text from a custom backing store using the same " +
        "APIs you would use for a string or a stream.\n\n";

    Console.WriteLine("Original text:\n\n{0}", textReaderText);

    // From textReaderText, create a continuous paragraph 
    // with two spaces between each sentence.
    string aLine, aParagraph = null;
    StringReader strReader = new StringReader(textReaderText);
    while(true)
    {
        aLine = strReader.ReadLine();
        if(aLine != null)
        {
            aParagraph = aParagraph + aLine + " ";
        }
        else
        {
            aParagraph = aParagraph + "\n";
            break;
        }
    }
    Console.WriteLine("Modified text:\n\n{0}", aParagraph);

TypeError: You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable

This error happened to me @angular 7

You provided an invalid object where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.

The error is actually self-explanatory, it says somewhere in the observable I pass the invalid object. In my case, there was lots of API call but all the calls were failing because of wrong server configuration. I tried to use map, switchMap, or other rxjs operator but the operators are getting undefined objects.

So double-check your rxjs operator inputs.

Does functional programming replace GoF design patterns?

I think only two GoF Design Patterns are designed to introduce the functional programming logic into natural OO language. I think about Strategy and Command. Some of the other GoF design patterns can be modified by functional programming to simplify the design and keep the purpose.

Is there a way to reduce the size of the git folder?

git clean -d -f -i is the best way to do it.

This will help to clean in a more controlled manner.

-i stands for interactive.

Regex - Should hyphens be escaped?

Outside of character classes, it is conventional not to escape hyphens. If I saw an escaped hyphen outside of a character class, that would suggest to me that it was written by someone who was not very comfortable with regexes.

Inside character classes, I don't think one way is conventional over the other; in my experience, it usually seems to be to put either first or last, as in [-._:] or [._:-], to avoid the backslash; but I've also often seen it escaped instead, as in [._\-:], and I wouldn't call that unconventional.

How to get JQuery.trigger('click'); to initiate a mouse click

Just use this:

$(function() {
 $('#watchButton').trigger('click');
});

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

Firstly just try to do that:

  • go to Gradle script ? bulid.gradle(module:app) ? then you have to change (minSdkVersion) value. As an example, if you used 26 you can try to decrease the value, like (minSdkVersion 20 )
  • then try (sync now ).

Enabling refreshing for specific html elements only

Try creating a javascript function which runs this:

document.getElementById("youriframeid").contentWindow.location.reload(true);

Or maybe use an HTML workaround:

<html>
<body>
<center>
      <a href="pagename.htm" target="middle">Refresh iframe</a>
      <p>
        <iframe src="pagename.htm" name="middle">
      </p>
</center>
</body>
</html>

Both might be what you're looking for...

What is the default username and password in Tomcat?

Look in your conf/tomcat-users.xml. If there is nothing there, you'd have to configure it.

Rails find_or_create_by more than one attribute?

In Rails 4 you could do:

GroupMember.find_or_create_by(member_id: 4, group_id: 7)

And use where is different:

GroupMember.where(member_id: 4, group_id: 7).first_or_create

This will call create on GroupMember.where(member_id: 4, group_id: 7):

GroupMember.where(member_id: 4, group_id: 7).create

On the contrary, the find_or_create_by(member_id: 4, group_id: 7) will call create on GroupMember:

GroupMember.create(member_id: 4, group_id: 7)

Please see this relevant commit on rails/rails.

Get a list of resources from classpath directory

Using Reflections

Get everything on the classpath:

Reflections reflections = new Reflections(null, new ResourcesScanner());
Set<String> resourceList = reflections.getResources(x -> true);

Another example - get all files with extension .csv from some.package:

Reflections reflections = new Reflections("some.package", new ResourcesScanner());
Set<String> fileNames = reflections.getResources(Pattern.compile(".*\\.csv"));

apache redirect from non www to www

To 301 redirect all requests made directly to the domain to www you can use:

RewriteEngine On

RewriteCond %{HTTP_HOST} !^([^.]+\.[^.]+){2,}$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

The benefit of this is that this will work if you have any valid subdomains, e.g.

example.com REDIRECTED TO www.example.com

foo.example.com NO REDIRECT

bar.example.com NO REDIRECT

Display current time in 12 hour format with AM/PM

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm a");

This will display the date and time

When should I use a trailing slash in my URL?

When you make your URL /about-us/ (with the trailing slash), it's easy to start with a single file index.html and then later expand it and add more files (e.g. our-CEO-john-doe.jpg) or even build a hierarchy under it (e.g. /about-us/company/, /about-us/products/, etc.) as needed, without changing the published URL. This gives you a great flexibility.

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Hardware

If a GPU device has, for example, 4 multiprocessing units, and they can run 768 threads each: then at a given moment no more than 4*768 threads will be really running in parallel (if you planned more threads, they will be waiting their turn).

Software

threads are organized in blocks. A block is executed by a multiprocessing unit. The threads of a block can be indentified (indexed) using 1Dimension(x), 2Dimensions (x,y) or 3Dim indexes (x,y,z) but in any case xyz <= 768 for our example (other restrictions apply to x,y,z, see the guide and your device capability).

Obviously, if you need more than those 4*768 threads you need more than 4 blocks. Blocks may be also indexed 1D, 2D or 3D. There is a queue of blocks waiting to enter the GPU (because, in our example, the GPU has 4 multiprocessors and only 4 blocks are being executed simultaneously).

Now a simple case: processing a 512x512 image

Suppose we want one thread to process one pixel (i,j).

We can use blocks of 64 threads each. Then we need 512*512/64 = 4096 blocks (so to have 512x512 threads = 4096*64)

It's common to organize (to make indexing the image easier) the threads in 2D blocks having blockDim = 8 x 8 (the 64 threads per block). I prefer to call it threadsPerBlock.

dim3 threadsPerBlock(8, 8);  // 64 threads

and 2D gridDim = 64 x 64 blocks (the 4096 blocks needed). I prefer to call it numBlocks.

dim3 numBlocks(imageWidth/threadsPerBlock.x,  /* for instance 512/8 = 64*/
              imageHeight/threadsPerBlock.y); 

The kernel is launched like this:

myKernel <<<numBlocks,threadsPerBlock>>>( /* params for the kernel function */ );       

Finally: there will be something like "a queue of 4096 blocks", where a block is waiting to be assigned one of the multiprocessors of the GPU to get its 64 threads executed.

In the kernel the pixel (i,j) to be processed by a thread is calculated this way:

uint i = (blockIdx.x * blockDim.x) + threadIdx.x;
uint j = (blockIdx.y * blockDim.y) + threadIdx.y;

What is Android keystore file, and what is it used for?

The whole idea of a keytool is to sign your apk with a unique identifier indicating the source of that apk. A keystore file (from what I understand) is used for debuging so your apk has the functionality of a keytool without signing your apk for production. So yes, for debugging purposes you should be able to sign multiple apk's with a single keystore. But understand that, upon pushing to production you'll need unique keytools as identifiers for each apk you create.

HTML-encoding lost when attribute read from input field

For those who prefer plain javascript, here is the method I have used successfully:

function escapeHTML (str)
{
    var div = document.createElement('div');
    var text = document.createTextNode(str);
    div.appendChild(text);
    return div.innerHTML;
}

How to find the Number of CPU Cores via .NET/C#?

There are several different pieces of information relating to processors that you could get:

  1. Number of physical processors
  2. Number of cores
  3. Number of logical processors.

These can all be different; in the case of a machine with 2 dual-core hyper-threading-enabled processors, there are 2 physical processors, 4 cores, and 8 logical processors.

The number of logical processors is available through the Environment class, but the other information is only available through WMI (and you may have to install some hotfixes or service packs to get it on some systems):

Make sure to add a reference in your project to System.Management.dll In .NET Core, this is available (for Windows only) as a NuGet package.

Physical Processors:

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Physical Processors: {0} ", item["NumberOfProcessors"]);
}

Cores:

int coreCount = 0;
foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
{
    coreCount += int.Parse(item["NumberOfCores"].ToString());
}
Console.WriteLine("Number Of Cores: {0}", coreCount);

Logical Processors:

Console.WriteLine("Number Of Logical Processors: {0}", Environment.ProcessorCount);

OR

foreach (var item in new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem").Get())
{
    Console.WriteLine("Number Of Logical Processors: {0}", item["NumberOfLogicalProcessors"]);
}

Processors excluded from Windows:

You can also use Windows API calls in setupapi.dll to discover processors that have been excluded from Windows (e.g. through boot settings) and aren't detectable using the above means. The code below gives the total number of logical processors (I haven't been able to figure out how to differentiate physical from logical processors) that exist, including those that have been excluded from Windows:

static void Main(string[] args)
{
    int deviceCount = 0;
    IntPtr deviceList = IntPtr.Zero;
    // GUID for processor classid
    Guid processorGuid = new Guid("{50127dc3-0f36-415e-a6cc-4cb3be910b65}");

    try
    {
        // get a list of all processor devices
        deviceList = SetupDiGetClassDevs(ref processorGuid, "ACPI", IntPtr.Zero, (int)DIGCF.PRESENT);
        // attempt to process each item in the list
        for (int deviceNumber = 0; ; deviceNumber++)
        {
            SP_DEVINFO_DATA deviceInfo = new SP_DEVINFO_DATA();
            deviceInfo.cbSize = Marshal.SizeOf(deviceInfo);

            // attempt to read the device info from the list, if this fails, we're at the end of the list
            if (!SetupDiEnumDeviceInfo(deviceList, deviceNumber, ref deviceInfo))
            {
                deviceCount = deviceNumber;
                break;
            }
        }
    }
    finally
    {
        if (deviceList != IntPtr.Zero) { SetupDiDestroyDeviceInfoList(deviceList); }
    }
    Console.WriteLine("Number of cores: {0}", deviceCount);
}

[DllImport("setupapi.dll", SetLastError = true)]
private static extern IntPtr SetupDiGetClassDevs(ref Guid ClassGuid,
    [MarshalAs(UnmanagedType.LPStr)]String enumerator,
    IntPtr hwndParent,
    Int32 Flags);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern Int32 SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);

[DllImport("setupapi.dll", SetLastError = true)]
private static extern bool SetupDiEnumDeviceInfo(IntPtr DeviceInfoSet,
    Int32 MemberIndex,
    ref SP_DEVINFO_DATA DeviceInterfaceData);

[StructLayout(LayoutKind.Sequential)]
private struct SP_DEVINFO_DATA
{
    public int cbSize;
    public Guid ClassGuid;
    public uint DevInst;
    public IntPtr Reserved;
}

private enum DIGCF
{
    DEFAULT = 0x1,
    PRESENT = 0x2,
    ALLCLASSES = 0x4,
    PROFILE = 0x8,
    DEVICEINTERFACE = 0x10,
}

What are the sizes used for the iOS application splash screen?

For Adobe AIR iOS Developers, take note that if your iPad Splash images "shift" or display and scale a second later, it's because there are different dimensions depending on what version of AIR you're using.

Default-Portrait.png:
768 x 1004 (AIR 3.3 and earlier)
768 x 1024 (AIR 3.4 and higher)

[email protected]:
1536 x 2008 (AIR 3.3 and earlier)
1536 x 2048 (AIR 3.4 and higher)

Reference:
http://help.adobe.com/en_US/air/build/WS901d38e593cd1bac1e63e3d129907d2886-8000.html#WS901d38e593cd1bac58d08f9112e26606ea8-8000

Could not find a version that satisfies the requirement tensorflow

For installing Tensorflow in Windows using Command Prompt or Terminal, write the following command:

pip install tensorflow

Is there a CSS parent selector?

Try this...

This solution uses plain CSS1 with no Javascript and works in all browsers, old and new. When clicked, the child anchor tag activates its active pseudo-class event. It then simply hides itself, allowing the active event to bubble up to the parent li tag who then restyles himself and reveals his anchor child again with a new style. The child has styled the parent.

Using your example:

<ul>
    <li class="listitem">
        <a class="link" href="#">This is a Link</a>
    </li>
</ul>

Now apply these styles with the active pseudo-class on a to restyle the parent li tag when the link is clicked:

a.link {
    display: inline-block;
    color: white;
    background-color: green;
    text-decoration: none;
    padding: 5px;
}

li.listitem {
    display: inline-block;
    margin: 0;
    padding: 0;
    background-color: transparent;
}

/* When this 'active' pseudo-class event below fires on click, it hides itself,
triggering the active event again on its parent which applies new styles to itself and its child. */

a.link:active {
    display: none;
}

.listitem:active {
    background-color: blue;
}

.listitem:active a.link {
    display: inline-block;
    background-color: transparent;
}

You should see the link with a green background now change to the list item's blue background on click.

enter image description here

turns to

enter image description here

on click.

Listing available com ports with Python

This is the code I use.

Successfully tested on Windows 8.1 x64, Windows 10 x64, Mac OS X 10.9.x / 10.10.x / 10.11.x and Ubuntu 14.04 / 14.10 / 15.04 / 15.10 with both Python 2 and Python 3.

import sys
import glob
import serial


def serial_ports():
    """ Lists serial port names

        :raises EnvironmentError:
            On unsupported or unknown platforms
        :returns:
            A list of the serial ports available on the system
    """
    if sys.platform.startswith('win'):
        ports = ['COM%s' % (i + 1) for i in range(256)]
    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        # this excludes your current terminal "/dev/tty"
        ports = glob.glob('/dev/tty[A-Za-z]*')
    elif sys.platform.startswith('darwin'):
        ports = glob.glob('/dev/tty.*')
    else:
        raise EnvironmentError('Unsupported platform')

    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
        except (OSError, serial.SerialException):
            pass
    return result


if __name__ == '__main__':
    print(serial_ports())

What are carriage return, linefeed, and form feed?

As a supplement,

1, Carriage return: It's a printer terminology meaning changing the print location to the beginning of current line. In computer world, it means return to the beginning of current line in most cases but stands for new line rarely.

2, Line feed: It's a printer terminology meaning advancing the paper one line. So Carriage return and Line feed are used together to start to print at the beginning of a new line. In computer world, it generally has the same meaning as newline.

3, Form feed: It's a printer terminology, I like the explanation in this thread.

If you were programming for a 1980s-style printer, it would eject the paper and start a new page. You are virtually certain to never need it.

http://en.wikipedia.org/wiki/Form_feed

It's almost obsolete and you can refer to Escape sequence \f - form feed - what exactly is it? for detailed explanation.

Note, we can use CR or LF or CRLF to stand for newline in some platforms but newline can't be stood by them in some other platforms. Refer to wiki Newline for details.

LF: Multics, Unix and Unix-like systems (Linux, OS X, FreeBSD, AIX, Xenix, etc.), BeOS, Amiga, RISC OS, and others

CR: Commodore 8-bit machines, Acorn BBC, ZX Spectrum, TRS-80, Apple II family, Oberon, the classic Mac OS up to version 9, MIT Lisp Machine and OS-9

RS: QNX pre-POSIX implementation

0x9B: Atari 8-bit machines using ATASCII variant of ASCII (155 in decimal)

CR+LF: Microsoft Windows, DOS (MS-DOS, PC DOS, etc.), DEC TOPS-10, RT-11, CP/M, MP/M, Atari TOS, OS/2, Symbian OS, Palm OS, Amstrad CPC, and most other early non-Unix and non-IBM OSes

LF+CR: Acorn BBC and RISC OS spooled text output.

java.math.BigInteger cannot be cast to java.lang.Integer

java.lang.Integer is not a super class of BigInteger. Both BigInteger and Integer do inherit from java.lang.Number, so you could cast to a java.lang.Number.

See the java docs http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Number.html

What HTTP traffic monitor would you recommend for Windows?

Wireshark if you want to see everything going on in the network.

Fiddler if you want to just monitor HTTP/s traffic.

Live HTTP Headers if you're in Firefox and want a quick plugin just to see the headers.

Also FireBug can get you that information too and provides a nice interface when your working on a single page during development. I've used it to monitor AJAX transactions.

Getting request payload from POST request in Java servlet

With Apache Commons IO you can do this in one line.

IOUtils.toString(request.getReader())

Why does Git treat this text file as a binary file?

If git check-attr --all -- src/my_file.txt indicates that your file is flagged as binary, and you haven't set it as binary in .gitattributes, check for it in /.git/info/attributes.

How to install JQ on Mac by command-line?

For CentOS, RHEL, Amazon Linux: sudo yum install jq

What are the Ruby File.open modes and options?

In Ruby IO module documentation, I suppose.

Mode |  Meaning
-----+--------------------------------------------------------
"r"  |  Read-only, starts at beginning of file  (default mode).
-----+--------------------------------------------------------
"r+" |  Read-write, starts at beginning of file.
-----+--------------------------------------------------------
"w"  |  Write-only, truncates existing file
     |  to zero length or creates a new file for writing.
-----+--------------------------------------------------------
"w+" |  Read-write, truncates existing file to zero length
     |  or creates a new file for reading and writing.
-----+--------------------------------------------------------
"a"  |  Write-only, starts at end of file if file exists,
     |  otherwise creates a new file for writing.
-----+--------------------------------------------------------
"a+" |  Read-write, starts at end of file if file exists,
     |  otherwise creates a new file for reading and
     |  writing.
-----+--------------------------------------------------------
"b"  |  Binary file mode (may appear with
     |  any of the key letters listed above).
     |  Suppresses EOL <-> CRLF conversion on Windows. And
     |  sets external encoding to ASCII-8BIT unless explicitly
     |  specified.
-----+--------------------------------------------------------
"t"  |  Text file mode (may appear with
     |  any of the key letters listed above except "b").

use a javascript array to fill up a drop down select box

This is a part from a REST-Service I´ve written recently.

var select = $("#productSelect")
for (var prop in data) {
    var option = document.createElement('option');
    option.innerHTML = data[prop].ProduktName
    option.value = data[prop].ProduktName;
    select.append(option)
}

The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.

jQuery: Performing synchronous AJAX requests

You're using the ajax function incorrectly. Since it's synchronous it'll return the data inline like so:

var remote = $.ajax({
    type: "GET",
    url: remote_url,
    async: false
}).responseText;

Clear terminal in Python

If you wish to clear your terminal when you are using a python shell. Then, you can do the following to clear the screen

import os
os.system('clear')

Using setattr() in python

You are setting self.name to the string "get_thing", not the function get_thing.

If you want self.name to be a function, then you should set it to one:

setattr(self, 'name', self.get_thing)

However, that's completely unnecessary for your other code, because you could just call it directly:

value_returned = self.get_thing()

How to use bluetooth to connect two iPhone?

You can connect two iPhones and transfer data via Bluetooth using either the high-level GameKit framework or the lower-level (but still easy to work with) Bonjour discovery mechanisms. Bonjour also works transparently between Bluetooth and WiFi on the iPhone under 3.0, so it's a good choice if you would like to support iPhone-to-iPhone data transfers on those two types of networks.

For more information, you can also look at the responses to these questions:

Options for HTML scraping?

Python has several options for HTML scraping in addition to Beatiful Soup. Here are some others:

  • mechanize: similar to perl WWW:Mechanize. Gives you a browser like object to ineract with web pages
  • lxml: Python binding to libwww. Supports various options to traverse and select elements (e.g. XPath and CSS selection)
  • scrapemark: high level library using templates to extract informations from HTML.
  • pyquery: allows you to make jQuery like queries on XML documents.
  • scrapy: an high level scraping and web crawling framework. It can be used to write spiders, for data mining and for monitoring and automated testing

Stop setInterval

we can easily stop the set interval by calling clear interval

var count = 0 , i = 5;
var vary = function intervalFunc() {
  count++;
      console.log(count);
    console.log('hello boy');  
    if (count == 10) {
      clearInterval(this);
    }
}

  setInterval(vary, 1500);

Setting Java heap space under Maven 2 on Windows

If you are running out of heap space during the surefire (or failsafe) JUnit testing run, changing MAVEN_OPTS may not help you. I kept trying different configurations in MAVEN_OPTS with no luck until I found this post that fixed the problem.

Basically the JUnits fork off into their own environment and ignore the settings in MAVEN_OPTS. You need to configure surefire in your pom to add more memory for the JUnits.

Hopefully this can save someone else some time!


Edit: Copying solution from Keith Chapman's blog just in case the link breaks some day:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <forkMode>pertest</forkMode> 
    <argLine>-Xms256m -Xmx512m</argLine>
    <testFailureIgnore>false</testFailureIgnore> 
    <skip>false</skip> 
    <includes> 
      <include>**/*IntegrationTestSuite.java</include>
    </includes>
  </configuration>
</plugin>

Update (5/31/2017): Thanks to @johnstosh for pointing this out - surefire has evolved a bit since I put this answer out there. Here is a link to their documentation and an updated code sample (arg line is still the important part for this question):

  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.20</version>
    <configuration>
        <forkCount>3</forkCount>
        <reuseForks>true</reuseForks>
        <argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
        <systemPropertyVariables>
            <databaseSchema>MY_TEST_SCHEMA_${surefire.forkNumber}</databaseSchema>
        </systemPropertyVariables>
        <workingDirectory>FORK_DIRECTORY_${surefire.forkNumber}</workingDirectory>
    </configuration>
  </plugin>

Disable arrow key scrolling in users browser

I've tried different ways of blocking scrolling when the arrow keys are pressed, both jQuery and native Javascript - they all work fine in Firefox, but don't work in recent versions of Chrome.
Even the explicit {passive: false} property for window.addEventListener, which is recommended as the only working solution, for example here.

In the end, after many tries, I found a way that works for me in both Firefox and Chrome:

window.addEventListener('keydown', (e) => {
    if (e.target.localName != 'input') {   // if you need to filter <input> elements
        switch (e.keyCode) {
            case 37: // left
            case 39: // right
                e.preventDefault();
                break;
            case 38: // up
            case 40: // down
                e.preventDefault();
                break;
            default:
                break;
        }
    }
}, {
    capture: true,   // this disables arrow key scrolling in modern Chrome
    passive: false   // this is optional, my code works without it
});

Quote for EventTarget.addEventListener() from MDN

options Optional
   An options object specifies characteristics about the event listener. The available options are:

capture
   A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.
once
   ...
passive
   A Boolean that, if true, indicates that the function specified by listener will never call preventDefault(). If a passive listener does call preventDefault(), the user agent will do nothing other than generate a console warning. ...

Property 'value' does not exist on type EventTarget in TypeScript

Here's another fix that works for me:

(event.target as HTMLInputElement).value

That should get rid of the error by letting TS know that event.target is an HTMLInputElement, which inherently has a value. Before specifying, TS likely only knew that event alone was an HTMLInputElement, thus according to TS the keyed-in target was some randomly mapped value that could be anything.

Play audio with Python

Mac OS I tried a lot of codes but just this works on me

import pygame
import time
pygame.mixer.init()
pygame.init()
pygame.mixer.music.load('fire alarm sound.mp3') *On my project folder*
i = 0
while i<10:
    pygame.mixer.music.play(loops=10, start=0.0)
    time.sleep(10)*to protect from closing*
    pygame.mixer.music.set_volume(10)
    i = i + 1

how to get param in method post spring mvc?

It also works if you change the content type

    <form method="POST"
    action="http://localhost:8080/cms/customer/create_customer"
    id="frmRegister" name="frmRegister"
    enctype="application/x-www-form-urlencoded">

In the controller also add the header value as follows:

    @RequestMapping(value = "/create_customer", method = RequestMethod.POST, headers = "Content-Type=application/x-www-form-urlencoded")

Remove all of x axis labels in ggplot

You have to set to element_blank() in theme() elements you need to remove

ggplot(data = diamonds, mapping = aes(x = clarity)) + geom_bar(aes(fill = cut))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

python inserting variable string as file name

f = open('{}.csv'.format(), 'wb')

Checking if a string is empty or null in Java

You can leverage Apache Commons StringUtils.isEmpty(str), which checks for empty strings and handles null gracefully.

Example:

System.out.println(StringUtils.isEmpty("")); // true
System.out.println(StringUtils.isEmpty(null)); // true

Google Guava also provides a similar, probably easier-to-read method: Strings.isNullOrEmpty(str).

Example:

System.out.println(Strings.isNullOrEmpty("")); // true
System.out.println(Strings.isNullOrEmpty(null)); // true

How to return a html page from a restful controller in spring boot?

You get only the name because you return only the name return "login";. It's @RestController and this controller returns data rather than a view; because of this, you get only content that you return from method.

If you want to show view with this name you need to use Spring MVC, see this example.

What is a non-capturing group in regular expressions?

I think I would give you the answer. Don't use capture variables without checking that the match succeeded.

The capture variables, $1, etc, are not valid unless the match succeeded, and they're not cleared, either.

#!/usr/bin/perl  
use warnings;
use strict;   
$_ = "bronto saurus burger";
if (/(?:bronto)? saurus (steak|burger)/)
{
    print "Fred wants a  $1";
}
else
{
    print "Fred dont wants a $1 $2";
}

In the above example, to avoid capturing bronto in $1, (?:) is used.

If the pattern is matched , then $1 is captured as next grouped pattern.

So, the output will be as below:

Fred wants a burger

It is Useful if you don't want the matches to be saved.

How can I create an executable JAR with dependencies using Maven?

Add to pom.xml:

  <dependency>
            <groupId>com.jolira</groupId>
            <artifactId>onejar-maven-plugin</artifactId>
            <version>1.4.4</version>
  </dependency>

and

<plugin>
       <groupId>com.jolira</groupId>
       <artifactId>onejar-maven-plugin</artifactId>
       <version>1.4.4</version>
       <executions>
              <execution>
                     <goals>
                         <goal>one-jar</goal>
                     </goals>
              </execution>
       </executions>
</plugin>

Thats it. Next mvn package will also create one fat jar additionally, including all dependency jars.

android start activity from service

From inside the Service class:

Intent dialogIntent = new Intent(this, MyActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);

Powershell send-mailmessage - email to multiple recipients

To define an array of strings it is more comfortable to use $var = @('User1 ', 'User2 ').

$servername = hostname
$smtpserver = 'localhost'
$emailTo = @('username1 <[email protected]>', 'username2<[email protected]>')
$emailFrom = 'SomeServer <[email protected]>'
Send-MailMessage -To $emailTo -Subject 'Low available memory' -Body 'Warning' -SmtpServer $smtpserver -From $emailFrom

Error 1022 - Can't write; duplicate key in table

As others have mentioned, it's possible that the name for your constraint is already in use by another table in your DB. They must be unique across the database.

A good convention for naming foreign key constraints is:

fk_TableName_ColumnName

To investigate whether there's a possible clash, you can list all constraints used by your database with this query:

SELECT * FROM information_schema.table_constraints WHERE constraint_schema = 'YOUR_DB';

When I ran this query, I discovered I had previously made a temporary copy of a table and this copy was already using the constraint name I was attempting to use.

JQuery .each() backwards

$($("li").get().reverse()).each(function() { /* ... */ });