Programs & Examples On #Al.exe

Hibernate Error executing DDL via JDBC Statement

I guess you are using an old version of hibernate. You can download the latest version, 5.2, from here.

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

Solution for me (Android Studio) :

1) Use shortcut Ctrl+Shift+Alt+S or File -> Project Structure

2) and increase the level of SDK "Compile SDK Version".

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

you just change import android.support.v7.app.ActionBarActivity; to import android.support.v7.app.AppCompatActivity;

and extends AppCompatActivity

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

Please Add this into your gradle file

android {
...
defaultConfig {
    ...
    multiDexEnabled true
    }
}

AND also add the below dependency in your gradle

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}

OR another option would be: In your manifest file add the MultiDexApplication package from the multidex support library in the application tag.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

I was getting this error even when all the relevant dependencies were in place because I hadn't created the schema in MySQL.

I thought it would be created automatically but it wasn't. Although the table itself will be created, you have to create the schema.

Execution failed for task ':app:processDebugResources' even with latest build tools

Issue SOLVED by making library and app build.gradle same ... compileSdkVersion and buildToolsVersion.

library build.gradle and

android {

    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    .....
    .....
}

app build.gradle

android {

    compileSdkVersion 25
    buildToolsVersion "25.0.0"
    .....
    .....
}

Android- Error:Execution failed for task ':app:transformClassesWithDexForRelease'

So, mine didn't get resolved by adding the multiDexEnabled flag. It actually was there before getting the error message.

What resolved the error for me was making sure I was using the same version of all play-services libraries. In one library I had 11.8.0 but in the app that consumes the library I was using 11.6.0 and that difference was what caused the error message.

So, instead of changing your libraries to a specific version like previous answers, maybe you wanna check you're using the same version all across since mixing versions is explicitly discouraged by Android Studio by warnings.

android : Error converting byte to dex

My project used an external library with heterogeneous Java compatibility versions in my build.gradle files (1.7 and 1.8). I fixed it by using the same version for the lib and for the app project. In my case for both :

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
    }

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

  1. Execute: cordova plugin rm cordova-plugin-compat --force
  2. Execute: cordova plugin add [email protected]
  3. Change : config.xml in your project folder use "6.2.3" not "^6.2.3", then delete the platforms/android folder, re-run cordova prepare android, and cordova build android

com.android.build.transform.api.TransformException

If you need add this reference for cordova plugin add next line in your plugin.xml file.

<framework src="com.android.support:support-v4:+" />

Java finished with non-zero exit value 2 - Android Gradle

For me the problem was, i had put a unnecessary complie library code in build.gradle

dependencies {
    compile 'com.google.android.gms:play-services:7.5.0'
}

which was causing over 65k methods, so removed it,gradle sync, cleaned project, and then ran again and then this error stopped. I needed just maps and gcm so i put these lines and synced project

compile 'com.google.android.gms:play-services-gcm:7.5.0'
compile 'com.google.android.gms:play-services-location:7.5.0'

Hi people i again encountered this problem and this time it was because of changing build tools version and it really required me to enable multidex..so i added these my app's build.gradle file..

defaultConfig {
    applicationId "com.am.android"
    minSdkVersion 13
    targetSdkVersion 23
    // Enabling multidex support.
    multiDexEnabled true
}

dexOptions {
    incremental true
    javaMaxHeapSize "2048M"
    jumboMode = true
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:multidex:1.0.1'
}

And create a class that extends Application class and include this method inside the class..

@Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}

also include in OnCreate method too

@Override
public void onCreate() {
    MultiDex.install(this);
    super.onCreate();
}

finished with non zero exit value

I ran to same problem today and try to clean and rebuild project.

I did not solve my problem. I got it solved with change the compileSdkVersion, buildToolsVersion, targetSdkVersion and com.android.support:appcompat-v7:23.0.1 values instead on my Gradle app file. Then I ran clean and rebuild the project afterwards.

Android java.exe finished with non-zero exit value 1

I had the same issue, after trying each of the answers here, I noticed that a package which I had renamed had not been renamed in a class which imported it. I fixed the name and immediately solved the problem.

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

I recently migrated one of our corporate projects from Eclipse to Android Studio.

We too got the below error during the migration:

Error:Execution failed for task ':appName:transformClassesWithDexForDebug'. com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/bin/java'' finished with non-zero exit value 2

To resolve it, we had to do a few things:

  1. Remove/Update duplicate jars/files from libs

compile 'com.android.support:support-v4:23' compile 'com.google.android.gms:play-services:9.0.0'

to compile 'com.google.android.gms:play-services:9.0.0'

  1. Set multiDexEnabled to True

defaultConfig { multiDexEnabled true }

  1. Increase the heap size:

dexOptions { incremental true javaMaxHeapSize "4g" }

Cannot find firefox binary in PATH. Make sure firefox is installed

I've just had this issue without changing PATH.

My PC is Win7, 64-bit system, If you are also using 64-bit system, you may want to try:

  1. uninstall your current Firefox.
  2. install new Firefox under "C:\Program Files (x86)\Mozilla Firefox\" path.

It must be under "Program Files (x86)" NOT "Program Files"

Hope it can help.

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

you have to add vm argument while running the program. This should be like

-Dwebdriver.firefox.bin=/custom/path/of/firefox/exe

In IntelliJ IDE much simpler Goto Run ? Edit Configurations... In VM options add the above.

IntelliJ Run Configurations

Eclipse also have the options to give vm argument while running. This way I am using portable Firefox with selenium.

How to Update/Drop a Hive Partition?

You can update a Hive partition by, for example:

ALTER TABLE logs PARTITION(year = 2012, month = 12, day = 18) 
SET LOCATION 'hdfs://user/darcy/logs/2012/12/18';

This command does not move the old data, nor does it delete the old data. It simply sets the partition to the new location.

To drop a partition, you can do

ALTER TABLE logs DROP IF EXISTS PARTITION(year = 2012, month = 12, day = 18);

Hope it helps!

Connecting to Microsoft SQL server using Python

Minor addition to what has been said before. You likely want to return a dataframe. This would be done as

import pypyodbc 
import pandas as pd

cnxn = pypyodbc.connect("Driver={SQL Server Native Client 11.0};"
                        "Server=server_name;"
                        "Database=db_name;"
                        "uid=User;pwd=password")
df = pd.read_sql_query('select * from table', cnxn)

Multi-dimensional associative arrays in JavaScript

Don't use an array, use an object.

var foo = new Object();

How to read if a checkbox is checked in PHP?

in BS3 you can put

  <?php
                  $checked="hola";
                  $exenta = $datosOrdenCompra[0]['exenta'];
                  var_dump($datosOrdenCompra[0]['exenta']);
                  if(isset($datosOrdenCompra[0]['exenta']) and $datosOrdenCompra[0]['exenta'] == 1){

                      $checked="on";

                  }else{
                    $checked="off";
                  }

              ?>
              <input type="checkbox" id="exenta" name="exenta" <?php echo $checked;?> > <span class="label-text"> Exenta</span>

Please Note the usage of isset($datosOrdenCompra[0]['exenta'])

How to host material icons offline?

2019 Update here:

To self host your material icons, the Regular ones, Rounded, Sharp, all the variants. Go get them from this repo: https://github.com/petergng/material-icon-font

For some reason I dont know why these fonts are not easily accessible from Google repositories.

But here you go.

After downloading the package, go to bin folder and you'll see the four variants. Of course, it is up to you to use whichever.

To use them, create a css file and

  1. Generate a font face for each variant you need:
@font-face {
    font-family: 'Material Icons';
    font-style: normal;
    font-weight: 400;
    src: url(./icons/regular/Material-Icons-Regular.eot); /* For IE6-8 */
    src: local('Material-Icons-Regular'),
    url(./icons/regular/Material-Icons-Regular.woff2) format('woff2'),
    url(./icons/regular/Material-Icons-Regular.woff) format('woff'),
    url(./icons/regular/Material-Icons-Regular.ttf) format('truetype');
}

@font-face {
    font-family: 'Material Icons Round';
    font-style: normal;
    font-weight: 400;
    src: url(./icons/round/Material-Icons-Round.eot); /* For IE6-8 */
    src: local('Material-Icons-Round'),
    url(./icons/round/Material-Icons-Round.woff2) format('woff2'),
    url(./icons/round/Material-Icons-Round.woff) format('woff'),
    url(./icons/round/Material-Icons-Round.svg) format('svg'),
    url(./icons/round/Material-Icons-Round.ttf) format('truetype');
}

@font-face {
    font-family: 'Material Icons Sharp';
    font-style: normal;
    font-weight: 400;
    src: url(./icons/sharp/Material-Icons-Sharp.eot); /* For IE6-8 */
    src: local('Material-Icons-Sharp'),
    url(./icons/sharp/Material-Icons-Sharp.woff2) format('woff2'),
    url(./icons/sharp/Material-Icons-Sharp.woff) format('woff'),
    url(./icons/sharp/Material-Icons-Sharp.svg) format('svg'),
    url(./icons/sharp/Material-Icons-Sharp.ttf) format('truetype');
}

The url will link to where the icons are located in your project.

  1. Now lets register the icon classes:
.material-icons-outlined, .material-icons {
    font-weight: normal;
    font-style: normal;
    font-size: 24px;  /* Preferred icon size */
    display: inline-block;
    line-height: 1;
    text-transform: none;
    letter-spacing: normal;
    word-wrap: normal;
    white-space: nowrap;
    direction: ltr;
}

This will make both .material-icons-outlined, and .material-icons classes use the same defaults. If you want to to use .material-icons-sharp, just append it to the two class names.

  1. Finally, let us plug-in the font face you pulled in from step 1.
.material-icons {
    font-family: 'Material Icons';
}
.material-icons-outlined {
    font-family: 'Material Icons Outline';
}

Again, to use more variant, like Sharp, just add its block like the two above.

Once done...go to your html and use your newly minted icons.

<i class="material-icons-outlined">hourglass_empty</i>
<i class="material-icons">phone</i>

How to Decrease Image Brightness in CSS

-webkit-filter: brightness(0.50);

I've got this cool solution: https://jsfiddle.net/yLcd5z0h/

Is there a limit to the length of a GET request?

setFixedLengthStreamingMode(int) with contentLength parameters could set the fixed length of a HTTP request body.

How to get last key in an array?

Dont know if this is going to be faster or not, but it seems easier to do it this way, and you avoid the error by not passing in a function to end()...

it just needed a variable... not a big deal to write one more line of code, then unset it if you needed to.

$array = array(
    'first' => 123,
    'second' => 456,
    'last' => 789, 
);

$keys = array_keys($array);
$last = end($keys);

PHP: date function to get month of the current date

See http://php.net/date

date('m') or date('n') or date('F') ...

Update

m Numeric representation of a month, with leading zeros 01 through 12

n Numeric representation of a month, without leading zeros 1 through 12

F Alphabetic representation of a month January through December

....see the docs link for even more options.

Combine two (or more) PDF's

I combined the two above, because I needed to merge 3 pdfbytes and return a byte

internal static byte[] mergePdfs(byte[] pdf1, byte[] pdf2,byte[] pdf3)
        {
            MemoryStream outStream = new MemoryStream();
            using (Document document = new Document())
            using (PdfCopy copy = new PdfCopy(document, outStream))
            {
                document.Open();
                copy.AddDocument(new PdfReader(pdf1));
                copy.AddDocument(new PdfReader(pdf2));
                copy.AddDocument(new PdfReader(pdf3));
            }
            return outStream.ToArray();
        } 

MVC 3: How to render a view without its layout page when loaded via ajax?

You don't have to create an empty view for this.

In the controller:

if (Request.IsAjaxRequest())
  return PartialView();
else
  return View();

returning a PartialViewResult will override the layout definition when rendering the respons.

How can I remove the extension of a filename in a shell script?

This one covers all possibilities! (dot in the path or not; with extension or no extension):

tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*});echo $filename_noextension

Notes:

  • It gives you the filename without any extension. So there is no path in the $filename_noextension variable.
  • You end up with two unwanted variables $tmp1 and $tmp2. Make sure you are not using them in your script.

examples to test:

filename=.bashrc; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=.bashrc.txt; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=.bashrc.txt.tar; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=~/.bashrc; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=~/.bashrc.txt.tar; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=bashrc; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=bashrc.txt; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=bashrc.txt.tar; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=~/bashrc; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

filename=~/bashrc.txt.tar; echo "filename: $filename"; tmp1=${filename##*/};tmp2=${tmp1:1};filename_noextension=$(echo -n ${tmp1:0:1};echo ${tmp2%.*}); echo "filename without extension: $filename_noextension"

HTTP Error 404 when running Tomcat from Eclipse

I had this or a similar problem after installing Tomcat.

The other answers didn't quite work, but got me on the right path. I answered this at https://stackoverflow.com/a/20762179/3128838 after discovering a YouTube video showing the exact problem I was having.

How to convert a boolean array to an int array

Numpy arrays have an astype method. Just do y.astype(int).

Note that it might not even be necessary to do this, depending on what you're using the array for. Bool will be autopromoted to int in many cases, so you can add it to int arrays without having to explicitly convert it:

>>> x
array([ True, False,  True], dtype=bool)
>>> x + [1, 2, 3]
array([2, 2, 4])

How to check db2 version

For DB2:

"SELECT * FROM SYSIBMADM.ENV_INST_INFO" - SERVICE_LEVEL

Convert decimal to binary in python

all numbers are stored in binary. if you want a textual representation of a given number in binary, use bin(i)

>>> bin(10)
'0b1010'
>>> 0b1010
10

Rails - controller action name to string

mikej's answer was very precise and helpful, but the the thing i also wanted to know was how to get current method name in rails.

found out it's possible with self.current_method

easily found at http://www.ruby-forum.com/topic/75258

Could not find module FindOpenCV.cmake ( Error in configuration process)

On my Fedora machine, when I typed "make" I got an error saying it could not find "cv.h". I fixed this by modifying my "OpenCVConfig.cmake" file.

Before:

SET(OpenCV_INCLUDE_DIRS "${OpenCV_INSTALL_PATH}/include/opencv;${OpenCV_INSTALL_PATH}/include")

SET(OpenCV_LIB_DIR "${OpenCV_INSTALL_PATH}/lib64")

After:

SET(OpenCV_INCLUDE_DIRS "/usr/include/opencv;/usr/include/opencv2")

SET(OpenCV_LIB_DIR "/usr/lib64")

Listing only directories using ls in Bash?

In case you're wondering why output from 'ls -d */' gives you two trailing slashes, like:

[prompt]$ ls -d */
app//  cgi-bin//  lib//        pub//

it's probably because somewhere your shell or session configuration files alias the ls command to a version of ls that includes the -F flag. That flag appends a character to each output name (that's not a plain file) indicating the kind of thing it is. So one slash is from matching the pattern '*/', and the other slash is the appended type indicator.

To get rid of this issue, you could of course define a different alias for ls. However, to temporarily not invoke the alias, you can prepend the command with backslash:

\ls -d */

Can I use library that used android support with Androidx projects.

I had a problem like this before, it was the gradle.properties file doesn't exist, only the gradle.properties.txt , so i went to my project folder and i copied & pasted the gradle.properties.txt file but without .txt extension then it finally worked.

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

If you want to deploy an MVC application without installing MVC, you can deploy the MVC DLL's with your application. This gets around installing MVC 3. You can use features in some .Net 4.0 namespaces without installing .Net using a similar approach.

github: server certificate verification failed

To me a simple

sudo apt-get update

solved the issue. It was a clock issue and with this command it resets to the current date/time and everything worked

How can I declare a Boolean parameter in SQL statement?

SQL Server recognizes 'TRUE' and 'FALSE' as bit values. So, use a bit data type!

declare @var bit
set @var = 'true'
print @var

That returns 1.

Configure Flask dev server to be visible across the network

If your cool app has it's configuration loaded from an external file, like in the following example, then don't forget to update the corresponding config file with HOST="0.0.0.0"

cool.app.run(
    host=cool.app.config.get("HOST", "localhost"),
    port=cool.app.config.get("PORT", 9000)
)            

Assign a synthesizable initial value to a reg in Verilog

You should use what your FPGA documentation recommends. There is no portable way to initialize register values other than using a reset net. This has a hardware cost associated with it on most synthesis targets.

R: numeric 'envir' arg not of length one in predict()

There are several problems here:

  1. The newdata argument of predict() needs a predictor variable. You should thus pass it values for Coupon, instead of Total, which is the response variable in your model.

  2. The predictor variable needs to be passed in as a named column in a data frame, so that predict() knows what the numbers its been handed represent. (The need for this becomes clear when you consider more complicated models, having more than one predictor variable).

  3. For this to work, your original call should pass df in through the data argument, rather than using it directly in your formula. (This way, the name of the column in newdata will be able to match the name on the RHS of the formula).

With those changes incorporated, this will work:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

What's the difference between SoftReference and WeakReference in Java?

The six types of object reachability states in Java:

  1. Strongly reachable objects - GC will not collect (reclaim the memory occupied by) this kind of object. These are reachable via a root node or another strongly reachable object (i.e. via local variables, class variables, instance variables, etc.)
  2. Softly reachable objects - GC may attempt to collect this kind of object depending on memory contention. These are reachable from the root via one or more soft reference objects
  3. Weakly reachable objects - GC must collect this kind of object. These are reachable from the root via one or more weak reference objects
  4. Resurrect-able objects - GC is already in the process of collecting these objects. But they may go back to one of the states - Strong/Soft/Weak by the execution of some finalizer
  5. Phantomly reachable object - GC is already in the process of collecting these objects and has determined to not be resurrect-able by any finalizer (if it declares a finalize() method itself, then its finalizer will have been run). These are reachable from the root via one or more phantom reference objects
  6. Unreachable object - An object is neither strongly, softly, weakly, nor phantom reachable, and is not resurrectable. These objects are ready for reclamation

For more details: https://www.artima.com/insidejvm/ed2/gc16.html « collapse

Is it correct to use DIV inside FORM?

It is completely acceptable to use a DIV inside a <form> tag.

If you look at the default CSS 2.1 stylesheet, div and p are both in the display: block category. Then looking at the HTML 4.01 specification for the form element, they include not only <p> tags, but <table> tags, so of course <div> would meet the same criteria. There is also a <legend> tag inside the form in the documentation.

For instance, the following passes HTML4 validation in strict mode:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> 
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Test</title>
</head>
<body>
<form id="test" action="test.php">
<div>
  Test: <input name="blah" value="test" type="text">
</div>
</form>
</body>
</html>

Appending to an existing string

Yet an other way:

s.insert(-1, ' world')

Given final block not properly padded

depending on the cryptography algorithm you are using, you may have to add some padding bytes at the end before encrypting a byte array so that the length of the byte array is multiple of the block size:

Specifically in your case the padding schema you chose is PKCS5 which is described here: http://www.rsa.com/products/bsafe/documentation/cryptoj35html/doc/dev_guide/group_CJ_SYM__PAD.html

(I assume you have the issue when you try to encrypt)

You can choose your padding schema when you instantiate the Cipher object. Supported values depend on the security provider you are using.

By the way are you sure you want to use a symmetric encryption mechanism to encrypt passwords? Wouldn't be a one way hash better? If you really need to be able to decrypt passwords, DES is quite a weak solution, you may be interested in using something stronger like AES if you need to stay with a symmetric algorithm.

Disable same origin policy in Chrome

If you are using Google Chrome on Linux, following command works.

google-chrome  --disable-web-security

What are the time complexities of various data structures?

Arrays

  • Set, Check element at a particular index: O(1)
  • Searching: O(n) if array is unsorted and O(log n) if array is sorted and something like a binary search is used,
  • As pointed out by Aivean, there is no Delete operation available on Arrays. We can symbolically delete an element by setting it to some specific value, e.g. -1, 0, etc. depending on our requirements
  • Similarly, Insert for arrays is basically Set as mentioned in the beginning

ArrayList:

  • Add: Amortized O(1)
  • Remove: O(n)
  • Contains: O(n)
  • Size: O(1)

Linked List:

  • Inserting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Doubly-Linked List:

  • Inserting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Deleting: O(1), if done at the head or tail, O(n) if anywhere else since we have to reach that position by traveseing the linkedlist linearly.
  • Searching: O(n)

Stack:

  • Push: O(1)
  • Pop: O(1)
  • Top: O(1)
  • Search (Something like lookup, as a special operation): O(n) (I guess so)

Queue/Deque/Circular Queue:

  • Insert: O(1)
  • Remove: O(1)
  • Size: O(1)

Binary Search Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(n)

Red-Black Tree:

  • Insert, delete and search: Average case: O(log n), Worst Case: O(log n)

Heap/PriorityQueue (min/max):

  • Find Min/Find Max: O(1)
  • Insert: O(log n)
  • Delete Min/Delete Max: O(log n)
  • Extract Min/Extract Max: O(log n)
  • Lookup, Delete (if at all provided): O(n), we will have to scan all the elements as they are not ordered like BST

HashMap/Hashtable/HashSet:

  • Insert/Delete: O(1) amortized
  • Re-size/hash: O(n)
  • Contains: O(1)

Jquery bind double click and single click separately

Same as the above answer but allows for triple click. (Delay 500) http://jsfiddle.net/luenwarneke/rV78Y/1/

    var DELAY = 500,
    clicks = 0,
    timer = null;

$(document).ready(function() {
    $("a")
    .on("click", function(e){
        clicks++;  //count clicks
        timer = setTimeout(function() {
        if(clicks === 1) {
           alert('Single Click'); //perform single-click action
        } else if(clicks === 2) {
           alert('Double Click'); //perform single-click action
        } else if(clicks >= 3) {
           alert('Triple Click'); //perform Triple-click action
        }
         clearTimeout(timer);
         clicks = 0;  //after action performed, reset counter
       }, DELAY);
    })
    .on("dblclick", function(e){
        e.preventDefault();  //cancel system double-click event
    });
});

What's the default password of mariadb on fedora?

I hit the same issue and none of the solutions worked. I then bumped an answer in stackexchange dba which lead to this link. So here is what I did:

  1. ran sudo mysqld_safe --skip-grant-tables --skip-networking &
  2. ran sudo mysql -uroot and got into mysql console
  3. run ALTER USER root@localhost identified via unix_socket; and flush privileges; consecutively to allow for password-less login

If you want to set the password then you need to do one more step, that is running ALTER USER root@localhost IDENTIFIED VIA mysql_native_password; and SET PASSWORD = PASSWORD('YourPasswordHere'); consecutively.

UPDATE

Faced this issue recently and here is how I resolved it with recent version, but before that some background. Mariadb does not require a password when is run as root. So first run it as a root. Then once in the Mariadb console, change password there. If you are content with running it as admin, you can just keep doing it but I find that cumbersome especially because I cannot use that with DB Admin Tools. TL;DR here is how I did it on Mac (should be similar for *nix systems)

sudo mariadb-secure-installation

then follow instructions on the screen!

Hope this will help someone and serve me a reference for future problems

Submitting a form by pressing enter without a submit button

I think you should go the Javascript route, or at least I would:

<script type="text/javascript">
// Using jQuery.

$(function() {
    $('form').each(function() {
        $(this).find('input').keypress(function(e) {
            // Enter pressed?
            if(e.which == 10 || e.which == 13) {
                this.form.submit();
            }
        });

        $(this).find('input[type=submit]').hide();
    });
});
</script>


<form name="loginBox" target="#here" method="post">
    <input name="username" type="text" /><br />
    <input name="password" type="password" />
    <input type="submit" />
</form>

What is the JavaScript equivalent of var_dump or print_r in PHP?

I wrote this JS function dump() to work like PHP's var_dump(). To show the contents of the variable in an alert window: dump(variable) To show the contents of the variable in the web page: dump(variable, 'body') To just get a string of the variable: dump(variable, 'none')

/* repeatString() returns a string which has been repeated a set number of times */
function repeatString(str, num) {
    out = '';
    for (var i = 0; i < num; i++) {
        out += str;
    }
    return out;
}

/*
dump() displays the contents of a variable like var_dump() does in PHP. dump() is
better than typeof, because it can distinguish between array, null and object.
Parameters:
    v:              The variable
    howDisplay:     "none", "body", "alert" (default)
    recursionLevel: Number of times the function has recursed when entering nested
                    objects or arrays. Each level of recursion adds extra space to the
                    output to indicate level. Set to 0 by default.
Return Value:
    A string of the variable's contents
Limitations:
    Can't pass an undefined variable to dump(). 
    dump() can't distinguish between int and float.
    dump() can't tell the original variable type of a member variable of an object.
    These limitations can't be fixed because these are *features* of JS. However, dump()
*/
function dump(v, howDisplay, recursionLevel) {
    howDisplay = (typeof howDisplay === 'undefined') ? "alert" : howDisplay;
    recursionLevel = (typeof recursionLevel !== 'number') ? 0 : recursionLevel;

    var vType = typeof v;
    var out = vType;

    switch (vType) {
        case "number":
        /* there is absolutely no way in JS to distinguish 2 from 2.0
           so 'number' is the best that you can do. The following doesn't work:
           var er = /^[0-9]+$/;
           if (!isNaN(v) && v % 1 === 0 && er.test(3.0)) {
               out = 'int';
           }
        */
        break;
    case "boolean":
        out += ": " + v;
        break;
    case "string":
        out += "(" + v.length + '): "' + v + '"';
        break;
    case "object":
        //check if null
        if (v === null) {
            out = "null";
        }
        //If using jQuery: if ($.isArray(v))
        //If using IE: if (isArray(v))
        //this should work for all browsers according to the ECMAScript standard:
        else if (Object.prototype.toString.call(v) === '[object Array]') {
            out = 'array(' + v.length + '): {\n';
            for (var i = 0; i < v.length; i++) {
                out += repeatString('   ', recursionLevel) + "   [" + i + "]:  " +
                    dump(v[i], "none", recursionLevel + 1) + "\n";
            }
            out += repeatString('   ', recursionLevel) + "}";
        }
        else {
            //if object
            let sContents = "{\n";
            let cnt = 0;
            for (var member in v) {
                //No way to know the original data type of member, since JS
                //always converts it to a string and no other way to parse objects.
                sContents += repeatString('   ', recursionLevel) + "   " + member +
                    ":  " + dump(v[member], "none", recursionLevel + 1) + "\n";
                cnt++;
            }
            sContents += repeatString('   ', recursionLevel) + "}";
            out += "(" + cnt + "): " + sContents;
        }
        break;
    default:
        out = v;
        break;
    }

    if (howDisplay == 'body') {
        var pre = document.createElement('pre');
        pre.innerHTML = out;
        document.body.appendChild(pre);
    }
    else if (howDisplay == 'alert') {
        alert(out);
    }

    return out;
}

Remove trailing spaces automatically or with a shortcut

Have a look at the EditorConfig plugin.

By using the plugin you can have settings specific for various projects. Visual Studio Code also has IntelliSense built-in for .editorconfig files.

remove / reset inherited css from an element

Only set the relevant / important CSS properties.

Example (only change the attributes which may cause your div to look completely different):

background: #FFF;
border: none;
color: #000;
display: block;
font: initial;
height: auto;
letter-spacing: normal;
line-height: normal;
margin: 0;
padding: 0;
text-transform: none;
visibility: visible;
width: auto;
word-spacing: normal;
z-index: auto;

Choose a very specific selector, such as div#donttouchme, <div id="donttouchme"></div>. Additionally, you can add `!important before every semicolon in the declaration. Your customers are deliberately trying to mess up your lay-out when this option fails.

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

All the above not working for me.. Because I am using Facebook Ad dependency..

Incase If anybody using this dependency compile 'com.facebook.android:audience-network-sdk:4.16.0'

Try this code instead of above

compile ('com.facebook.android:audience-network-sdk:4.16.0'){
exclude group: 'com.google.android.gms'
}

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

it's well documented here:

https://cwiki.apache.org/confluence/display/TOMCAT/Connectors#Connectors-Q6

How do I bind to a specific ip address? - "Each Connector element allows an address property. See the HTTP Connector docs or the AJP Connector docs". And HTTP Connectors docs:

http://tomcat.apache.org/tomcat-7.0-doc/config/http.html

Standard Implementation -> address

"For servers with more than one IP address, this attribute specifies which address will be used for listening on the specified port. By default, this port will be used on all IP addresses associated with the server."

How to create .pfx file from certificate and private key?

When you say the certificate is available in MMC, is it available under "Current User" or "Local Computer"? I've found that I can only export the private key if it is under Local Computer.

You can add the snap in for Certificates to MMC and choose which account it should manage certificates for. Choose Local Computer. If your certificate is not there, import it by right clicking the store and choosing All Tasks > Import.

Now navigate to your imported certificate under the Local Computer version of the certificate snap in. Right click the certificate and choose All Tasks > Export. The second page of the export wizard should ask if you want to export the private key. Select Yes. The PFX option will now be the only one available (it is grayed out if you select no and the option to export the private key isn't available under the Current User account).

You'll be asked to set a password for the PFX file and then to set the certificate name.

How to delete an element from a Slice in Golang

Remove one element from the Slice (this is called 're-slicing'):

package main

import (
    "fmt"
)

func RemoveIndex(s []int, index int) []int {
    return append(s[:index], s[index+1:]...)
}

func main() {
    all := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
    fmt.Println(all) //[0 1 2 3 4 5 6 7 8 9]
    all = RemoveIndex(all, 5)
    fmt.Println(all) //[0 1 2 3 4 6 7 8 9]
}

Bootstrap NavBar with left, center or right aligned items

2021 Update

Bootstrap 5 (beta)

Bootstrap 5 also has a flexbox Navbar, and introduces new RTL support. For this reason the concept of "left" and "right" has been replaced with "start" and "end". Therefore the margin utilities changed for Bootstrap 5 beta:

  • ml-auto => ms-auto
  • mr-auto => me-auto

Bootstrap 4

Now that Bootstrap 4 has flexbox, Navbar alignment is much easier. Here are updated examples for left, right and center in the Bootstrap 4 Navbar, and many other alignment scenarios demonstrated here.

The flexbox, auto-margins, and ordering utility classes can be used to align Navbar content as needed. There are many things to consider including the order and alignment of Navbar items (brand, links, toggler) on both large screens and the mobile/collapsed views. Don't use the grid classes (row,col) for the Navbar.

Here are various examples...

Left, center(brand) and right links:

enter image description here

<nav class="navbar navbar-expand-md navbar-dark bg-dark">
    <div class="navbar-collapse collapse w-100 order-1 order-md-0 dual-collapse2">
        <ul class="navbar-nav mr-auto">
            <li class="nav-item active">
                <a class="nav-link" href="#">Left</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="//codeply.com">Codeply</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
            </li>
        </ul>
    </div>
    <div class="mx-auto order-0">
        <a class="navbar-brand mx-auto" href="#">Navbar 2</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".dual-collapse2">
            <span class="navbar-toggler-icon"></span>
        </button>
    </div>
    <div class="navbar-collapse collapse w-100 order-3 dual-collapse2">
        <ul class="navbar-nav ml-auto">
            <li class="nav-item">
                <a class="nav-link" href="#">Right</a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
            </li>
        </ul>
    </div>
</nav>

http://codeply.com/go/qhaBrcWp3v


Another BS4 Navbar option with center links and overlay logo image:

center links and overlay logo image

<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
    <div class="navbar-collapse collapse w-100 dual-collapse2 order-1 order-md-0">
        <ul class="navbar-nav ml-auto text-center">
            <li class="nav-item active">
                <a class="nav-link" href="#">Link</a>
            </li>
        </ul>
    </div>
    <div class="mx-auto my-2 order-0 order-md-1 position-relative">
        <a class="mx-auto" href="#">
            <img src="//placehold.it/120/ccff00" class="rounded-circle">
        </a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target=".dual-collapse2">
            <span class="navbar-toggler-icon"></span>
        </button>
    </div>
    <div class="navbar-collapse collapse w-100 dual-collapse2 order-2 order-md-2">
        <ul class="navbar-nav mr-auto text-center">
            <li class="nav-item">
                <a class="nav-link" href="#">Link</a>
            </li>
        </ul>
    </div>
</nav>

Or, these other Bootstrap 4 alignment scenarios:

brand left, dead center links, (empty right)

Navbar brand left, dead center links


brand and links center, icons left and right

enter image description here


More Bootstrap 4 examples:

toggler left on mobile, brand right
center brand and links on mobile
right align links on desktop, center links on mobile
left links & toggler, center brand, search right


Also see: Bootstrap 4 align navbar items to the right
Bootstrap 4 navbar right align with button that doesn't collapse on mobile
Center an element in Bootstrap 4 Navbar


Bootstrap 3

Option 1 - Brand center, with left/right nav links:

enter image description here

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>    
  </div>
  <a class="navbar-brand" href="#">Brand</a>
  <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav navbar-left">
        <li><a href="#">Left</a></li>
        <li><a href="#about">Left</a></li>
    </ul>
    <ul class="nav navbar-nav navbar-right">
      <li><a href="#about">Right</a></li>
      <li><a href="#contact">Right</a></li>
    </ul>
  </div>
</nav>

.navbar-brand
{
    position: absolute;
    width: 100%;
    left: 0;
    text-align: center;
    margin:0 auto;
}
.navbar-toggle {
    z-index:3;
}

http://bootply.com/98314 (3.x)


Option 2 - Left, center and right nav links:

enter image description here

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>    
  </div>
  <div class="navbar-collapse collapse">
    <ul class="nav navbar-nav">
        <li><a href="#">Left</a></li>
    </ul>
    <ul class="nav navbar-nav navbar-center">
        <li><a href="#">Center</a></li>
        <li><a href="#">Center</a></li>
      <li><a href="#">Center</a></li>
    </ul>
    <ul class="nav navbar-nav navbar-right">
        <li><a href="#">Right</a></li>
    </ul>
  </div>
</nav>

@media (min-width: 768px) {
  .navbar-nav.navbar-center {
    position: absolute;
    left: 50%;
    transform: translatex(-50%);
  }
}

http://bootply.com/SGYC6BWeBK

Option 3 - Center both brand and links

enter image description here

.navbar .navbar-header,
.navbar-collapse {
    float:none;
    display:inline-block;
    vertical-align: top;
}

@media (max-width: 768px) {
    .navbar-collapse  {
        display: block;
    }
}

http://codeply.com/go/1lrdvNH9GI

More examples:

Left brand, center links
Left toggler, center brand

For 3.x also see nav-justified: Bootstrap center navbar


Center Navbar in Bootstrap
Bootstrap 4 align navbar items to the right

What does "select 1 from" do?

SELECT COUNT(*) in EXISTS/NOT EXISTS

EXISTS(SELECT CCOUNT(*) FROM TABLE_NAME WHERE CONDITIONS) - the EXISTS condition will always return true irrespective of CONDITIONS are met or not.

NOT EXISTS(SELECT CCOUNT(*) FROM TABLE_NAME WHERE CONDITIONS) - the NOT EXISTS condition will always return false irrespective of CONDITIONS are met or not.

SELECT COUNT 1 in EXISTS/NOT EXISTS

EXISTS(SELECT CCOUNT 1 FROM TABLE_NAME WHERE CONDITIONS) - the EXISTS condition will return true if CONDITIONS are met. Else false.

NOT EXISTS(SELECT CCOUNT 1 FROM TABLE_NAME WHERE CONDITIONS) - the NOT EXISTS condition will return false if CONDITIONS are met. Else true.

How to check if an element is off-screen

Well... I've found some issues in every proposed solution here.

  • You should be able to choose if you want entire element to be on screen or just any part of it
  • Proposed solutions fails if element is higher/wider than window and kinda covers browser window.

Here is my solution that include jQuery .fn instance function and expression. I've created more variables inside my function than I could, but for complex logical problem I like to divide it into smaller, clearly named pieces.

I'm using getBoundingClientRect method that returns element position relatively to the viewport so I don't need to care about scroll position

Useage:

$(".some-element").filter(":onscreen").doSomething();
$(".some-element").filter(":entireonscreen").doSomething();
$(".some-element").isOnScreen(); // true / false
$(".some-element").isOnScreen(true); // true / false (partially on screen)
$(".some-element").is(":onscreen"); // true / false (partially on screen)
$(".some-element").is(":entireonscreen"); // true / false 

Source:

$.fn.isOnScreen = function(partial){

    //let's be sure we're checking only one element (in case function is called on set)
    var t = $(this).first();

    //we're using getBoundingClientRect to get position of element relative to viewport
    //so we dont need to care about scroll position
    var box = t[0].getBoundingClientRect();

    //let's save window size
    var win = {
        h : $(window).height(),
        w : $(window).width()
    };

    //now we check against edges of element

    //firstly we check one axis
    //for example we check if left edge of element is between left and right edge of scree (still might be above/below)
    var topEdgeInRange = box.top >= 0 && box.top <= win.h;
    var bottomEdgeInRange = box.bottom >= 0 && box.bottom <= win.h;

    var leftEdgeInRange = box.left >= 0 && box.left <= win.w;
    var rightEdgeInRange = box.right >= 0 && box.right <= win.w;


    //here we check if element is bigger then window and 'covers' the screen in given axis
    var coverScreenHorizontally = box.left <= 0 && box.right >= win.w;
    var coverScreenVertically = box.top <= 0 && box.bottom >= win.h;

    //now we check 2nd axis
    var topEdgeInScreen = topEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );
    var bottomEdgeInScreen = bottomEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );

    var leftEdgeInScreen = leftEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );
    var rightEdgeInScreen = rightEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );

    //now knowing presence of each edge on screen, we check if element is partially or entirely present on screen
    var isPartiallyOnScreen = topEdgeInScreen || bottomEdgeInScreen || leftEdgeInScreen || rightEdgeInScreen;
    var isEntirelyOnScreen = topEdgeInScreen && bottomEdgeInScreen && leftEdgeInScreen && rightEdgeInScreen;

    return partial ? isPartiallyOnScreen : isEntirelyOnScreen;

};

$.expr.filters.onscreen = function(elem) {
  return $(elem).isOnScreen(true);
};

$.expr.filters.entireonscreen = function(elem) {
  return $(elem).isOnScreen(true);
};

Tomcat: How to find out running tomcat version

I have this challenge when working on an Ubuntu 18.04 Linux server.

Here's how I fixed it:

Run the command below to determine the location of your version.sh file:

sudo find / -name "version.sh"

For me the output was:

/opt/tomcat/bin/version.sh

Then, using the output, run the file (version.sh) as a shell script (sh):

sh /opt/tomcat/bin/version.sh

That's all.

I hope this helps

How to sort an associative array by its values in Javascript?

Just so it's out there and someone is looking for tuple based sorts. This will compare the first element of the object in array, than the second element and so on. i.e in the example below, it will compare first by "a", then by "b" and so on.

let arr = [
    {a:1, b:2, c:3},
    {a:3, b:5, c:1},
    {a:2, b:3, c:9},
    {a:2, b:5, c:9},
    {a:2, b:3, c:10}    
]

function getSortedScore(obj) {
    var keys = []; 
    for(var key in obj[0]) keys.push(key);
    return obj.sort(function(a,b){
        for (var i in keys) {
            let k = keys[i];
            if (a[k]-b[k] > 0) return -1;
            else if (a[k]-b[k] < 0) return 1;
            else continue;
        };
    });
}

console.log(getSortedScore(arr))

OUPUTS

 [ { a: 3, b: 5, c: 1 },
  { a: 2, b: 5, c: 9 },
  { a: 2, b: 3, c: 10 },
  { a: 2, b: 3, c: 9 },
  { a: 1, b: 2, c: 3 } ]

Java array reflection: isArray vs. instanceof

If you ever have a choice between a reflective solution and a non-reflective solution, never pick the reflective one (involving Class objects). It's not that it's "Wrong" or anything, but anything involving reflection is generally less obvious and less clear.

Converting json results to a date

If you use jQuery

In case you use jQuery on the client side, you may be interested in this blog post that provides code how to globally extend jQuery's $.parseJSON() function to automatically convert dates for you.

You don't have to change existing code in case of adding this code. It doesn't affect existing calls to $.parseJSON(), but if you start using $.parseJSON(data, true), dates in data string will be automatically converted to Javascript dates.

It supports Asp.net date strings: /Date(2934612301)/ as well as ISO strings 2010-01-01T12_34_56-789Z. The first one is most common for most used back-end web platform, the second one is used by native browser JSON support (as well as other JSON client side libraries like json2.js).

Anyway. Head over to blog post to get the code. http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html

google maps v3 marker info window on mouseover

var icon1 = "imageA.png";
var icon2 = "imageB.png";

var marker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    icon: icon1,
    title: "some marker"
});

google.maps.event.addListener(marker, 'mouseover', function() {
    marker.setIcon(icon2);
});
google.maps.event.addListener(marker, 'mouseout', function() {
    marker.setIcon(icon1);
});

What Language is Used To Develop Using Unity

It uses c#, and unityscript(javascript), which is supported by the source code in c++, and c++ plugin support(source code, and plugins require pro).

The unity3d script reference is really easy to understand/use if needed, probably the easiest out of engines like cryengine, udk, etc.

Hope this helps.

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

I solved the Access-Control-Allow-Origin error modifying the dataType parameter to dataType:'jsonp' and adding a crossDomain:true

$.ajax({

    url: 'https://www.googleapis.com/moderator/v1/series?key='+key,
    data: myData,
    type: 'GET',
    crossDomain: true,
    dataType: 'jsonp',
    success: function() { alert("Success"); },
    error: function() { alert('Failed!'); },
    beforeSend: setHeader
});

Comment shortcut Android Studio

Comment method like pro developers:

Windows/linux:

Line Comment : Ctrl + /

Block Comment : Ctrl + Shift

Method Commenting:

Type `/**` and press `Enter Key`

it will add the comment snippet like we see in standard documentation, give it a try this once.

/**
 * 
 * @param addOpacity
 */
public void setOpacityOnUserImage(boolean addOpacity) {
// Your business logic. 
}

How do you build a Singleton in Dart?

After reading all the alternatives I came up with this, which reminds me a "classic singleton":

class AccountService {
  static final _instance = AccountService._internal();

  AccountService._internal();

  static AccountService getInstance() {
    return _instance;
  }
}

Validate IPv4 address in Java

the lib of apache-httpcomponents

// ipv4 is true
assertTrue(InetAddressUtils.isIPv4Address("127.0.0.1"));
// not detect the ipv6
assertFalse(InetAddressUtils.isIPv4Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334"));

maven lib (update Sep, 2019)

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.10</version>
</dependency>

Twig for loop for arrays with keys

There's this example in the SensioLab page on the for tag:

<h1>Members</h1>
<ul>
    {% for key, user in users %}
        <li>{{ key }}: {{ user.username|e }}</li>
    {% endfor %}
</ul>

http://twig.sensiolabs.org/doc/tags/for.html#iterating-over-keys

Grant execute permission for a user on all stored procedures in database?

Without over-complicating the problem, to grant the EXECUTE on chosen database:

USE [DB]
GRANT EXEC TO [User_Name];

How to make div appear in front of another?

Use the CSS z-index property. Elements with a greater z-index value are positioned in front of elements with smaller z-index values.

Note that for this to work, you also need to set a position style (position:absolute, position:relative, or position:fixed) on both/all of the elements you want to order.

Install gitk on Mac

Correct, the 1.7.12.4 (Apple Git-37) does not come with gitk. You can install a more recent version of git + git-ui as a separate formula by using brew. More thorough instructions located here: http://www.moncefbelyamani.com/how-to-install-xcode-homebrew-git-rvm-ruby-on-mac/ (see this commit extracting git-gui/gitk into its own formula: https://github.com/Homebrew/homebrew-core/commit/dfa3ccf1e7d3901e371b5140b935839ba9d8b706)

Run the following commands at the terminal:

brew update
brew install git
brew install git-gui

If you get an error indicating it could not link git, then you may need to change permissions/owners of the files it mentions.

Once completed, run:

type -a git

And make sure it shows:

/usr/local/bin/git

If it does not, run:

brew doctor

And make the path change to put /usr/local/bin earlier in the path. Now, gitk should be on your path (along with an updated version of git).

java.net.SocketException: Software caused connection abort: recv failed

If you are using Netbeans to manage Tomcat, try to disable HTTP monitor in Tools - Servers

How to query values from xml nodes?

SELECT  b.BatchID,
        x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
        x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM    Batches b
CROSS APPLY b.RawXml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol);

Demo: SQLFiddle

Copy Notepad++ text with formatting?

As the chosen answer is pretty old, and things changed, here is the new procedure, if you use 64 bits Notepad++. 64 bits version does not come with Plugin Manager nor NppExport. All details provided here.

To resume quickly, Plugin Manager is no longer develloped and NppExport can be found just here.

How can I get Git to follow symlinks?

Hmmm, mount --bind doesn't seem to work on Darwin.

Does anyone have a trick that does?

[edited]

OK, I found the answer on Mac OS X is to make a hardlink. Except that that API is not exposed via ln, so you have to use your own tiny program to do this. Here is a link to that program:

Creating directory hard links in Mac OS X

Enjoy!

Python dictionary : TypeError: unhashable type: 'list'

It works fine : http://codepad.org/5KgO0b1G, your aSourceDictionary variable may have other datatype than dict

aSourceDictionary = { 'abc' : [1,2,3] , 'ccd' : [4,5] }
aTargetDictionary = {}
for aKey in aSourceDictionary:
        aTargetDictionary[aKey] = []
        aTargetDictionary[aKey].extend(aSourceDictionary[aKey])
print aTargetDictionary

Java Process with Input/Output Stream

I think you can use thread like demon-thread for reading your input and your output reader will already be in while loop in main thread so you can read and write at same time.You can modify your program like this:

Thread T=new Thread(new Runnable() {

    @Override
    public void run() {
        while(true)
        {
            String input = scan.nextLine();
            input += "\n";
            try {
                writer.write(input);
                writer.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }
} );
T.start();

and you can reader will be same as above i.e.

while ((line = reader.readLine ()) != null) {
    System.out.println ("Stdout: " + line);
}

make your writer as final otherwise it wont be able to accessible by inner class.

How can I mark a foreign key constraint using Hibernate annotations?

There are many answers and all are correct as well. But unfortunately none of them have a clear explanation.

The following works for a non-primary key mapping as well.

Let's say we have parent table A with column 1 and another table, B, with column 2 which references column 1:

@ManyToOne
@JoinColumn(name = "TableBColumn", referencedColumnName = "TableAColumn")
private TableA session_UserName;

Enter image description here

@ManyToOne
@JoinColumn(name = "bok_aut_id", referencedColumnName = "aut_id")
private Author bok_aut_id;

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

Typically you see this error after you have already done a redirect and then try to output some more data to the output stream. In the cases where I have seen this in the past, it is often one of the filters that is trying to redirect the page, and then still forwards through to the servlet. I cannot see anything immediately wrong with the servlet, so you might want to try having a look at any filters that you have in place as well.

Edit: Some more help in diagnosing the problem…

The first step to diagnosing this problem is to ascertain exactly where the exception is being thrown. We are assuming that it is being thrown by the line

getServletConfig().getServletContext()
                  .getRequestDispatcher("/GroupCopiedUpdt.jsp")
                  .forward(request, response);

But you might find that it is being thrown later in the code, where you are trying to output to the output stream after you have tried to do the forward. If it is coming from the above line, then it means that somewhere before this line you have either:

  1. output data to the output stream, or
  2. done another redirect beforehand.

Good luck!

How to finish current activity in Android

If you are doing a loading screen, just set the parameter to not keep it in activity stack. In your manifest.xml, where you define your activity do:

<activity android:name=".LoadingScreen" android:noHistory="true" ... />

And in your code there is no need to call .finish() anymore. Just do startActivity(i);

There is also no need to keep a instance of your current activity in a separate field. You can always access it like LoadingScreen.this.doSomething() instead of private LoadingScreen loadingScreen;

Why is C so fast, and why aren't other languages as fast or faster?

Actually, in certain applications (numerics) even C can be beaten, and I don't mean assembly language, but the old, oft-ridiculed Fortran. The reason is, Fortran guarantees no pointer aliasing.

How to get an absolute file path in Python

>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

Also works if it is already an absolute path:

>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

Asynchronous method call in Python?

You can implement a decorator to make your functions asynchronous, though that's a bit tricky. The multiprocessing module is full of little quirks and seemingly arbitrary restrictions – all the more reason to encapsulate it behind a friendly interface, though.

from inspect import getmodule
from multiprocessing import Pool


def async(decorated):
    r'''Wraps a top-level function around an asynchronous dispatcher.

        when the decorated function is called, a task is submitted to a
        process pool, and a future object is returned, providing access to an
        eventual return value.

        The future object has a blocking get() method to access the task
        result: it will return immediately if the job is already done, or block
        until it completes.

        This decorator won't work on methods, due to limitations in Python's
        pickling machinery (in principle methods could be made pickleable, but
        good luck on that).
    '''
    # Keeps the original function visible from the module global namespace,
    # under a name consistent to its __name__ attribute. This is necessary for
    # the multiprocessing pickling machinery to work properly.
    module = getmodule(decorated)
    decorated.__name__ += '_original'
    setattr(module, decorated.__name__, decorated)

    def send(*args, **opts):
        return async.pool.apply_async(decorated, args, opts)

    return send

The code below illustrates usage of the decorator:

@async
def printsum(uid, values):
    summed = 0
    for value in values:
        summed += value

    print("Worker %i: sum value is %i" % (uid, summed))

    return (uid, summed)


if __name__ == '__main__':
    from random import sample

    # The process pool must be created inside __main__.
    async.pool = Pool(4)

    p = range(0, 1000)
    results = []
    for i in range(4):
        result = printsum(i, sample(p, 100))
        results.append(result)

    for result in results:
        print("Worker %i: sum value is %i" % result.get())

In a real-world case I would ellaborate a bit more on the decorator, providing some way to turn it off for debugging (while keeping the future interface in place), or maybe a facility for dealing with exceptions; but I think this demonstrates the principle well enough.

How to read HDF5 files in Python

Read HDF5

import h5py
filename = "file.hdf5"

with h5py.File(filename, "r") as f:
    # List all groups
    print("Keys: %s" % f.keys())
    a_group_key = list(f.keys())[0]

    # Get the data
    data = list(f[a_group_key])

Write HDF5

import h5py

# Create random data
import numpy as np
data_matrix = np.random.uniform(-1, 1, size=(10, 3))

# Write data to HDF5
with h5py.File("file.hdf5", "w") as data_file:
    data_file.create_dataset("group_name", data=data_matrix)

See h5py docs for more information.

Alternatives

For your application, the following might be important:

  • Support by other programming languages
  • Reading / writing performance
  • Compactness (file size)

See also: Comparison of data serialization formats

In case you are rather looking for a way to make configuration files, you might want to read my short article Configuration files in Python

Default passwords of Oracle 11g?

Login into the machine as oracle login user id( where oracle is installed)..

  1. Add ORACLE_HOME = <Oracle installation Directory> in Environment variable

  2. Open a command prompt

  3. Change the directory to %ORACLE_HOME%\bin

  4. type the command sqlplus /nolog

  5. SQL> connect /as sysdba

  6. SQL> alter user SYS identified by "newpassword";

One more check, while oracle installation and database confiuration assistant setup, if you configure any database then you might have given password and checked the same password for all other accounts.. If so, then you try with the password which you have given in your database configuration assistant setup.

Hope this will work for you..

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

Basically your query returns more than one result set. In API Docs uniqueResult() method says that Convenience method to return a single instance that matches the query, or null if the query returns no results

uniqueResult() method yield only single resultset

Is there a "null coalescing" operator in JavaScript?

Logical nullish assignment, 2020+ solution

A new operator is currently being added to the browsers, ??=. This combines the null coalescing operator ?? with the assignment operator =.

NOTE: This is not common in public browser versions yet. Will update as availability changes.

??= checks if the variable is undefined or null, short-circuiting if already defined. If not, the right-side value is assigned to the variable.

Basic Examples

let a          // undefined
let b = null
let c = false

a ??= true  // true
b ??= true  // true
c ??= true  // false

Object/Array Examples

let x = ["foo"]
let y = { foo: "fizz" }

x[0] ??= "bar"  // "foo"
x[1] ??= "bar"  // "bar"

y.foo ??= "buzz"  // "fizz"
y.bar ??= "buzz"  // "buzz"

x  // Array [ "foo", "bar" ]
y  // Object { foo: "fizz", bar: "buzz" }

Browser Support Sept 2020 - 3.7%

Mozilla Documentation

Git push won't do anything (everything up-to-date)

Right now, it appears as you are on the develop branch. Do you have a develop branch on your origin? If not, try git push origin develop. git push will work once it knows about a develop branch on your origin.

As further reading, I'd have a look at the git-push man pages, in particular, the examples section.

Escape dot in a regex range

If you using JavaScript to test your Regex, try \\. instead of \..

It acts on the same way because JS remove first backslash.

Unable to compile class for JSP

<pluginManagement>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>       
                <version>2.2</version>
            </plugin>
        </plugins>

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

I want to alert('test'); in an input type text but it should not execute the alert(alert prompt).

<input type="text" value="<script>alert('test');</script>" />

Produces:

enter image description here

You can do this programatically via JavaScript. First obtain a reference to the input element, then set the value attribute.

var inputElement = document.querySelector("input");
inputElement.value = "<script>alert('test');<\/script>";

How to downgrade Node version

In case of windows, one of the options you have is to uninstall current version of Node. Then, go to the node website and download the desired version and install this last one instead.

Callback functions in Java

public class HelloWorldAnonymousClasses {

    //this is an interface with only one method
    interface HelloWorld {
        public void printSomething(String something);
    }

    //this is a simple function called from main()
    public void sayHello() {

    //this is an object with interface reference followed by the definition of the interface itself

        new HelloWorld() {
            public void printSomething(String something) {
                System.out.println("Hello " + something);
            }
        }.printSomething("Abhi");

     //imagine this as an object which is calling the function'printSomething()"
    }

    public static void main(String... args) {
        HelloWorldAnonymousClasses myApp =
                new HelloWorldAnonymousClasses();
        myApp.sayHello();
    }
}
//Output is "Hello Abhi"

Basically if you want to make the object of an interface it is not possible, because interface cannot have objects.

The option is to let some class implement the interface and then call that function using the object of that class. But this approach is really verbose.

Alternatively, write new HelloWorld() (*oberserve this is an interface not a class) and then follow it up with the defination of the interface methods itself. (*This defination is in reality the anonymous class). Then you get the object reference through which you can call the method itself.

Move layouts up when soft keyboard is shown?

In your manifest file add the below line. It will work

<activity name="MainActivity"
    android:windowSoftInputMode="stateVisible|adjustResize">
    ...
</activity>

How to correctly get image from 'Resources' folder in NetBeans

For me it worked like I had images in icons folder under src and I wrote below code.

new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

Git: add vs push vs commit

Very nice pdf about many GIT secrets.

Add is same as svn's add (how ever sometimes it is used to mark file resolved).

Commit also is same as svn's , but it commit change into your local repository.

No tests found with test runner 'JUnit 4'

In context menu of your 'test' directory choose 'Build path' -> 'Use as a source folder'. Eclipse should see your unitTests.java files as a source files. Warning 'No JUnit tests found' occures because there is no unitTests.class files in your 'build' directory

How can I convert radians to degrees with Python?

I like this method,use sind(x) or cosd(x)

import math

def sind(x):
    return math.sin(math.radians(x))

def cosd(x):
    return math.cos(math.radians(x))

How can I increase the size of a bootstrap button?

Default Bootstrap size classes

You can use btn-lg, btn-sm and btn-xs classes for manipulating with its size.

btn-block

Also, there is a class btn-block which will extend your button to the whole block. It is very convenient in combination with Bootstrap grid.
For example, this code will show a button with the width equal to half of screen for medium and large screens; and will show a full-width button for small screens:

<div class="container">
    <div class="col-xs-12 col-xs-offset-0 col-sm-offset-3 col-sm-6">
        <button class="btn btn-group">Click me!</button>
    </div>
</div>

Check this JSFiddle out. Try to resize frame.

If it is not enough, you can easily create your custom class.

Failed to resolve: com.android.support:appcompat-v7:28.0

implementation 'com.android.support:appcompat-v7:28.0' implementation 'com.android.support:support-media-compat:28.0.0' implementation 'com.android.support:support-v4:28.0.0' All to add

Pythonic way of checking if a condition holds for any element of a list

any():

if any(t < 0 for t in x):
    # do something

Also, if you're going to use "True in ...", make it a generator expression so it doesn't take O(n) memory:

if True in (t < 0 for t in x):

Context.startForegroundService() did not then call Service.startForeground()

I am facing same issue and after spending time found a solutons you can try below code. If your using Service then put this code in onCreate else your using Intent Service then put this code in onHandleIntent.

if (Build.VERSION.SDK_INT >= 26) {
        String CHANNEL_ID = "my_app";
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                "MyApp", NotificationManager.IMPORTANCE_DEFAULT);
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("")
                .setContentText("").build();
        startForeground(1, notification);
    }

How to change content on hover

The CSS content property along with ::after and ::before pseudo-elements have been introduced for this.

.item:hover a p.new-label:after{
    content: 'ADD';
}

JSFiddle Demo

A Windows equivalent of the Unix tail command

Another option would be to install MSYS (which is more leightweight than Cygwin).

Delete topic in Kafka 0.8.1.1

As mentioned in doc here

Topic deletion option is disabled by default. To enable it set the server config delete.topic.enable=true Kafka does not currently support reducing the number of partitions for a topic or changing the replication factor.

Make sure delete.topic.enable=true

Using Image control in WPF to display System.Drawing.Bitmap

It's easy for disk file, but harder for Bitmap in memory.

System.Drawing.Bitmap bmp;
Image image;
...
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
ms.Position = 0;
BitmapImage bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();

image.Source = bi;

Stealed here

ipad safari: disable scrolling, and bounce effect?

For those who are using MyScript the Web App and are struggling with the body scrolling/dragging (on iPad and Tablets) instead of actually writing:

<body touch-action="none" unresolved>

That fixed it for me.

How using try catch for exception handling is best practice

Best practice is to throw an Exception when the error occurs. Because an error has occurred and it should not be hidden.

But in real life you can have several situations when you want to hide this

  1. You rely on third party component and you want to continue the program in case of error.
  2. You have a business case that you need to continue in case of error

PHP remove special character from string

Your dot is matching all characters. Escape it (and the other special characters), like this:

preg_replace('/[^a-zA-Z0-9_ %\[\]\.\(\)%&-]/s', '', $String);

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

Pandas How to filter a Series

From pandas version 0.18+ filtering a series can also be done as below

test = {
383:    3.000000,
663:    1.000000,
726:    1.000000,
737:    9.000000,
833:    8.166667
}

pd.Series(test).where(lambda x : x!=1).dropna()

Checkout: http://pandas.pydata.org/pandas-docs/version/0.18.1/whatsnew.html#method-chaininng-improvements

Docker Error bind: address already in use

`$` sudo service redis-server stop

Does the trick.

How SID is different from Service name in Oracle tnsnames.ora

As per Oracle Glossary :

SID is a unique name for an Oracle database instance. ---> To switch between Oracle databases, users must specify the desired SID <---. The SID is included in the CONNECT DATA parts of the connect descriptors in a TNSNAMES.ORA file, and in the definition of the network listener in the LISTENER.ORA file. Also known as System ID. Oracle Service Name may be anything descriptive like "MyOracleServiceORCL". In Windows, You can your Service Name running as a service under Windows Services.

You should use SID in TNSNAMES.ORA as a better approach.

CSS disable hover effect

I have really simple solution for this.

just create a new class

.noHover{
    pointer-events: none;
}

and use this to disable any event on it. use it like:

<a href='' class='btn noHover'>You cant touch ME :P</a>

Spring data JPA query with parameter properties

You can try something like this:

public interface PersonRepository extends CrudRepository<Person, Long> {
       @Query("select p from Person AS p"
       + " ,Name AS n"  
       + " where p.forename = n.forename "
       + " and p.surname = n.surname"
       + " and n = :name")
       Set<Person>findByName(@Param("name") Name name);
    }

Change the "No file chosen":

I would use "button" instead of "label", hope this help someone.

This will just display a button, user clicked will popup file chooser, after file chose, automatically upload.

<button onclick='<%= "$(\"#" + FileUpload1.ClientID + "\").click(); return false;" %>'>The Text You Want</button>

<asp:FileUpload onchange="$('#btnUpload').click();" ID="FileUpload1" runat="server" style="display: none;" />

<asp:Button ID="btnUpload" ClientIDMode="Static" runat="server" OnClick="btnUpload_Click" style="display: none;" />

Ansible - read inventory hosts and variables to group_vars/all file

Yes the example by nixlike works very well.

Inventory:

[docker-host]
myhost1 user=barbara
myhost2 user=heather

playbook:

---

- hosts: localhost
  connection: local         

     tasks:    
        - name: loop debug inventory hostnames
          debug: 
            msg: "the docker host is {{ item }}"
          with_inventory_hostnames: docker-host
        - name: loop debug items
          debug: 
            msg: "the docker host is {{ hostvars[item]['user'] }}"
          with_items: "{{ groups['docker-host'] }}"

output:

ansible-playbook ansible/tests/vars-test-local.yml

PLAY [localhost]


TASK [setup] ******************************************************************* ok: [localhost]

TASK [loop debug inventory hostnames] ****************************************** ok: [localhost] => (item=myhost2) => { "item": "myhost2", "msg": "the docker host is myhost2" } ok: [localhost] => (item=myhost1) => { "item": "myhost1", "msg": "the docker host is myhost1" }

TASK [loop debug items] ******************************************************** ok: [localhost] => (item=myhost1) => { "item": "myhost1", "msg": "the docker host is barbara" } ok: [localhost] => (item=myhost2) => { "item": "myhost2", "msg": "the docker host is heather" }

PLAY RECAP ********************************************************************* localhost : ok=3 changed=0 unreachable=0
failed=0

thanks!

Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

Lately I created a chrome extension "eXtract Snippet" for copying the inspected element, html and only the relevant css and media queries from a page. Note that this would give you the actual relevant CSS

https://chrome.google.com/webstore/detail/extract-snippet/bfcjfegkgdoomgmofhcidoiampnpbdao?hl=en

What is a LAMP stack?

That simply means using Linux, Apache, MySQL and PHP as your operating system, web server, database, and programming language, respectively.

NameError: global name is not defined

Importing the namespace is somewhat cleaner. Imagine you have two different modules you import, both of them with the same method/class. Some bad stuff might happen. I'd dare say it is usually good practice to use:

import module

over

from module import function/class

How do I properly clean up Excel interop objects?

My answer is late and its only purpose is to support the solution proposed by Govert, Porkbutts, and Dave Cousineau with a complete example. Automating Excel or other COM objects from the COM-agnostic .NET world is a “tough nut,” as we say in German, and you can easily go nuts. I rely on the following steps:

  1. For each interaction with Excel, get one and only one local instance ExcelApp of the Application interface and create a scope within which ExcelApp lives. This is necessary, because the CLR won’t free the resources of Excel before any reference to Excel goes out of scope. A new Excel process is started in the background.

  2. Implement functions that do the tasks by using ExcelApp to generate via Collection properties new objects like Workbook(s), Worksheet(s), and Cell(s). In these functions don’t care for the voodoo one-dot-good, two-dot-bad rule, don’t try to get a reference for each implicitly created object and don’t Marshall.ReleaseComObject anything. That is the job of the Garbage Collection.

  3. Within the scope of ExcelApp, call these functions and pass the reference ExcelApp.

  4. While your Excel instance is loaded, don’t allow any user actions that would bypass the Quit function that unloads this instance again.

  5. When you are done with Excel, call the separate Quit function within the scope made for Excel handling. This should be the last statement within this scope.

Before you run my app, open the task manager and watch in the Processes tab the entries in background processes. When you start the program, a new Excel process entry appears in the list and stays there until the thread wakes up again after 5 seconds. After that the Quit function will be called, stopping the Excel process that gracefully vanishes from the list of background processes.

using System;
using System.Threading;
using Excel = Microsoft.Office.Interop.Excel;

namespace GCTestOnOffice
{
  class Program
  {
    //Don't: private  static Excel.Application ExcelApp = new Excel.Application();

    private static void DoSomething(Excel.Application ExcelApp)
    {
        Excel.Workbook Wb = ExcelApp.Workbooks.Open(@"D:\Aktuell\SampleWorkbook.xlsx");
        Excel.Worksheet NewWs = Wb.Worksheets.Add();

        for (int i = 1; i < 10; i++)
        {
            NewWs.Cells[i, 1] = i;
        }
        Wb.Save();
    }

    public static void Quit(Excel.Application ExcelApp)
    {
        if (ExcelApp != null)
        {
            ExcelApp.Quit(); //Don't forget!!!!!
            ExcelApp = null;
        }
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }

    static void Main(string[] args)
    {
      {
        Excel.Application ExcelApp = new Excel.Application();
        Thread.Sleep(5000);
        DoSomething(ExcelApp);
        Quit(ExcelApp);
        //ExcelApp goes out of scope, the CLR can and will(!) release Excel
      }

      Console.WriteLine("Input a digit: ");
      int k = Console.Read(); 
    }
  }
}

If I changed the Main function to

static void Main(string[] args)
{
  Excel.Application ExcelApp = new Excel.Application();
  DoSomething(ExcelApp);

  Console.WriteLine("Input a digit: ");
  int k = Console.Read(); 
  Quit(ExcelApp);
}

the user could instead of inputting a number, hit the Close button of the console and my Excel instance lived happily ever after. So, in cases where your Excel instance remains stubbornly loaded, your cleanup feature might not be wrong, but is bypassed by unforeseen user actions.

If the Program class would have a member for the Excel instance, the CLR would not unload the Excel instance before the app terminates. That's why I prefer local references that go out of scope when they are no longer needed.

$http.get(...).success is not a function

The .success syntax was correct up to Angular v1.4.3.

For versions up to Angular v.1.6, you have to use then method. The then() method takes two arguments: a success and an error callback which will be called with a response object.

Using the then() method, attach a callback function to the returned promise.

Something like this:

app.controller('MainCtrl', function ($scope, $http){
   $http({
      method: 'GET',
      url: 'api/url-api'
   }).then(function (response){

   },function (error){

   });
}

See reference here.

Shortcut methods are also available.

$http.get('api/url-api').then(successCallback, errorCallback);

function successCallback(response){
    //success code
}
function errorCallback(error){
    //error code
}

The data you get from the response is expected to be in JSON format. JSON is a great way of transporting data, and it is easy to use within AngularJS

The major difference between the 2 is that .then() call returns a promise (resolved with a value returned from a callback) while .success() is more traditional way of registering callbacks and doesn't return a promise.

How to develop a soft keyboard for Android?

Create Custom Key Board for Own EditText

Download Entire Code

In this post i Created Simple Keyboard which contains Some special keys like ( France keys ) and it's supported Capital letters and small letters and Number keys and some Symbols .

package sra.keyboard;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;

public class Main extends Activity implements OnTouchListener, OnClickListener,
  OnFocusChangeListener {
 private EditText mEt, mEt1; // Edit Text boxes
 private Button mBSpace, mBdone, mBack, mBChange, mNum;
 private RelativeLayout mLayout, mKLayout;
 private boolean isEdit = false, isEdit1 = false;
 private String mUpper = "upper", mLower = "lower";
 private int w, mWindowWidth;
 private String sL[] = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
   "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w",
   "x", "y", "z", "ç", "à", "é", "è", "û", "î" };
 private String cL[] = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
   "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W",
   "X", "Y", "Z", "ç", "à", "é", "è", "û", "î" };
 private String nS[] = { "!", ")", "'", "#", "3", "$", "%", "&", "8", "*",
   "?", "/", "+", "-", "9", "0", "1", "4", "@", "5", "7", "(", "2",
   "\"", "6", "_", "=", "]", "[", "<", ">", "|" };
 private Button mB[] = new Button[32];

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  try {
   setContentView(R.layout.main);
   // adjusting key regarding window sizes
   setKeys();
   setFrow();
   setSrow();
   setTrow();
   setForow();
   mEt = (EditText) findViewById(R.id.xEt);
   mEt.setOnTouchListener(this);
   mEt.setOnFocusChangeListener(this);
   mEt1 = (EditText) findViewById(R.id.et1);

   mEt1.setOnTouchListener(this);
   mEt1.setOnFocusChangeListener(this);
   mEt.setOnClickListener(this);
   mEt1.setOnClickListener(this);
   mLayout = (RelativeLayout) findViewById(R.id.xK1);
   mKLayout = (RelativeLayout) findViewById(R.id.xKeyBoard);

  } catch (Exception e) {
   Log.w(getClass().getName(), e.toString());
  }

 }

 @Override
 public boolean onTouch(View v, MotionEvent event) {
  if (v == mEt) {
   hideDefaultKeyboard();
   enableKeyboard();

  }
  if (v == mEt1) {
   hideDefaultKeyboard();
   enableKeyboard();

  }
  return true;
 }

 @Override
 public void onClick(View v) {

  if (v == mBChange) {

   if (mBChange.getTag().equals(mUpper)) {
    changeSmallLetters();
    changeSmallTags();
   } else if (mBChange.getTag().equals(mLower)) {
    changeCapitalLetters();
    changeCapitalTags();
   }

  } else if (v != mBdone && v != mBack && v != mBChange && v != mNum) {
   addText(v);

  } else if (v == mBdone) {

   disableKeyboard();

  } else if (v == mBack) {
   isBack(v);
  } else if (v == mNum) {
   String nTag = (String) mNum.getTag();
   if (nTag.equals("num")) {
    changeSyNuLetters();
    changeSyNuTags();
    mBChange.setVisibility(Button.INVISIBLE);

   }
   if (nTag.equals("ABC")) {
    changeCapitalLetters();
    changeCapitalTags();
   }

  }

 }

 @Override
 public void onFocusChange(View v, boolean hasFocus) {
  if (v == mEt && hasFocus == true) {
   isEdit = true;
   isEdit1 = false;

  } else if (v == mEt1 && hasFocus == true) {
   isEdit = false;
   isEdit1 = true;

  }

 }

 private void addText(View v) {
  if (isEdit == true) {
   String b = "";
   b = (String) v.getTag();
   if (b != null) {
    // adding text in Edittext
    mEt.append(b);

   }
  }

  if (isEdit1 == true) {
   String b = "";
   b = (String) v.getTag();
   if (b != null) {
    // adding text in Edittext
    mEt1.append(b);

   }

  }

 }

 private void isBack(View v) {
  if (isEdit == true) {
   CharSequence cc = mEt.getText();
   if (cc != null && cc.length() > 0) {
    {
     mEt.setText("");
     mEt.append(cc.subSequence(0, cc.length() - 1));
    }

   }
  }

  if (isEdit1 == true) {
   CharSequence cc = mEt1.getText();
   if (cc != null && cc.length() > 0) {
    {
     mEt1.setText("");
     mEt1.append(cc.subSequence(0, cc.length() - 1));
    }
   }
  }
 }
 private void changeSmallLetters() {
  mBChange.setVisibility(Button.VISIBLE);
  for (int i = 0; i < sL.length; i++)
   mB[i].setText(sL[i]);
  mNum.setTag("12#");
 }
 private void changeSmallTags() {
  for (int i = 0; i < sL.length; i++)
   mB[i].setTag(sL[i]);
  mBChange.setTag("lower");
  mNum.setTag("num");
 }
 private void changeCapitalLetters() {
  mBChange.setVisibility(Button.VISIBLE);
  for (int i = 0; i < cL.length; i++)
   mB[i].setText(cL[i]);
  mBChange.setTag("upper");
  mNum.setText("12#");

 }

 private void changeCapitalTags() {
  for (int i = 0; i < cL.length; i++)
   mB[i].setTag(cL[i]);
  mNum.setTag("num");

 }

 private void changeSyNuLetters() {

  for (int i = 0; i < nS.length; i++)
   mB[i].setText(nS[i]);
  mNum.setText("ABC");
 }

 private void changeSyNuTags() {
  for (int i = 0; i < nS.length; i++)
   mB[i].setTag(nS[i]);
  mNum.setTag("ABC");
 }

 // enabling customized keyboard
 private void enableKeyboard() {

  mLayout.setVisibility(RelativeLayout.VISIBLE);
  mKLayout.setVisibility(RelativeLayout.VISIBLE);

 }

 // Disable customized keyboard
 private void disableKeyboard() {
  mLayout.setVisibility(RelativeLayout.INVISIBLE);
  mKLayout.setVisibility(RelativeLayout.INVISIBLE);

 }

 private void hideDefaultKeyboard() {
  getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

 }

 private void setFrow() {
  w = (mWindowWidth / 13);
  w = w - 15;
  mB[16].setWidth(w);
  mB[22].setWidth(w + 3);
  mB[4].setWidth(w);
  mB[17].setWidth(w);
  mB[19].setWidth(w);
  mB[24].setWidth(w);
  mB[20].setWidth(w);
  mB[8].setWidth(w);
  mB[14].setWidth(w);
  mB[15].setWidth(w);
  mB[16].setHeight(50);
  mB[22].setHeight(50);
  mB[4].setHeight(50);
  mB[17].setHeight(50);
  mB[19].setHeight(50);
  mB[24].setHeight(50);
  mB[20].setHeight(50);
  mB[8].setHeight(50);
  mB[14].setHeight(50);
  mB[15].setHeight(50);

 }

 private void setSrow() {
  w = (mWindowWidth / 10);
  mB[0].setWidth(w);
  mB[18].setWidth(w);
  mB[3].setWidth(w);
  mB[5].setWidth(w);
  mB[6].setWidth(w);
  mB[7].setWidth(w);
  mB[26].setWidth(w);
  mB[9].setWidth(w);
  mB[10].setWidth(w);
  mB[11].setWidth(w);
  mB[26].setWidth(w);

  mB[0].setHeight(50);
  mB[18].setHeight(50);
  mB[3].setHeight(50);
  mB[5].setHeight(50);
  mB[6].setHeight(50);
  mB[7].setHeight(50);
  mB[9].setHeight(50);
  mB[10].setHeight(50);
  mB[11].setHeight(50);
  mB[26].setHeight(50);
 }

 private void setTrow() {
  w = (mWindowWidth / 12);
  mB[25].setWidth(w);
  mB[23].setWidth(w);
  mB[2].setWidth(w);
  mB[21].setWidth(w);
  mB[1].setWidth(w);
  mB[13].setWidth(w);
  mB[12].setWidth(w);
  mB[27].setWidth(w);
  mB[28].setWidth(w);
  mBack.setWidth(w);

  mB[25].setHeight(50);
  mB[23].setHeight(50);
  mB[2].setHeight(50);
  mB[21].setHeight(50);
  mB[1].setHeight(50);
  mB[13].setHeight(50);
  mB[12].setHeight(50);
  mB[27].setHeight(50);
  mB[28].setHeight(50);
  mBack.setHeight(50);

 }

 private void setForow() {
  w = (mWindowWidth / 10);
  mBSpace.setWidth(w * 4);
  mBSpace.setHeight(50);
  mB[29].setWidth(w);
  mB[29].setHeight(50);

  mB[30].setWidth(w);
  mB[30].setHeight(50);

  mB[31].setHeight(50);
  mB[31].setWidth(w);
  mBdone.setWidth(w + (w / 1));
  mBdone.setHeight(50);

 }

 private void setKeys() {
  mWindowWidth = getWindowManager().getDefaultDisplay().getWidth(); // getting
  // window
  // height
  // getting ids from xml files
  mB[0] = (Button) findViewById(R.id.xA);
  mB[1] = (Button) findViewById(R.id.xB);
  mB[2] = (Button) findViewById(R.id.xC);
  mB[3] = (Button) findViewById(R.id.xD);
  mB[4] = (Button) findViewById(R.id.xE);
  mB[5] = (Button) findViewById(R.id.xF);
  mB[6] = (Button) findViewById(R.id.xG);
  mB[7] = (Button) findViewById(R.id.xH);
  mB[8] = (Button) findViewById(R.id.xI);
  mB[9] = (Button) findViewById(R.id.xJ);
  mB[10] = (Button) findViewById(R.id.xK);
  mB[11] = (Button) findViewById(R.id.xL);
  mB[12] = (Button) findViewById(R.id.xM);
  mB[13] = (Button) findViewById(R.id.xN);
  mB[14] = (Button) findViewById(R.id.xO);
  mB[15] = (Button) findViewById(R.id.xP);
  mB[16] = (Button) findViewById(R.id.xQ);
  mB[17] = (Button) findViewById(R.id.xR);
  mB[18] = (Button) findViewById(R.id.xS);
  mB[19] = (Button) findViewById(R.id.xT);
  mB[20] = (Button) findViewById(R.id.xU);
  mB[21] = (Button) findViewById(R.id.xV);
  mB[22] = (Button) findViewById(R.id.xW);
  mB[23] = (Button) findViewById(R.id.xX);
  mB[24] = (Button) findViewById(R.id.xY);
  mB[25] = (Button) findViewById(R.id.xZ);
  mB[26] = (Button) findViewById(R.id.xS1);
  mB[27] = (Button) findViewById(R.id.xS2);
  mB[28] = (Button) findViewById(R.id.xS3);
  mB[29] = (Button) findViewById(R.id.xS4);
  mB[30] = (Button) findViewById(R.id.xS5);
  mB[31] = (Button) findViewById(R.id.xS6);
  mBSpace = (Button) findViewById(R.id.xSpace);
  mBdone = (Button) findViewById(R.id.xDone);
  mBChange = (Button) findViewById(R.id.xChange);
  mBack = (Button) findViewById(R.id.xBack);
  mNum = (Button) findViewById(R.id.xNum);
  for (int i = 0; i < mB.length; i++)
   mB[i].setOnClickListener(this);
  mBSpace.setOnClickListener(this);
  mBdone.setOnClickListener(this);
  mBack.setOnClickListener(this);
  mBChange.setOnClickListener(this);
  mNum.setOnClickListener(this);

 }

}

C# Validating input for textbox on winforms

Description

There are many ways to validate your TextBox. You can do this on every keystroke, at a later time, or on the Validating event.

The Validating event gets fired if your TextBox looses focus. When the user clicks on a other Control, for example. If your set e.Cancel = true the TextBox doesn't lose the focus.

MSDN - Control.Validating Event When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order

Enter

GotFocus

Leave

Validating

Validated

LostFocus

When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:

Enter

GotFocus

LostFocus

Leave

Validating

Validated

Sample Validating Event

private void textBox1_Validating(object sender, CancelEventArgs e)
{
    if (textBox1.Text != "something")
        e.Cancel = true;
}

Update

You can use the ErrorProvider to visualize that your TextBox is not valid. Check out Using Error Provider Control in Windows Forms and C#

More Information

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

import os
os.environ["PATH"] += os.pathsep + "/Macintosh HD?/anaconda3?/lib?/?python3.7?/site-packages?/sphinx?/templates?/graphviz"

This solved the PATH issue on MAC for me!

Moment.js with ReactJS (ES6)

I'm using moment in my react project

import moment from 'moment'

state = {
    startDate: moment()
};
render() {
    const selectedDate = this.state.startDate.format("Do MMMM YYYY");
    return(
     <Fragment>
       {selectedDate)
     </Fragment>
   );
}

How can I pad an integer with zeros on the left?

Try this one:

import java.text.DecimalFormat; 

DecimalFormat df = new DecimalFormat("0000");

String c = df.format(9);   // Output: 0009

String a = df.format(99);  // Output: 0099

String b = df.format(999); // Output: 0999

MySQL SELECT DISTINCT multiple columns

can this help?

select 
(SELECT group_concat(DISTINCT a) FROM my_table) as a,
(SELECT group_concat(DISTINCT b) FROM my_table) as b,
(SELECT group_concat(DISTINCT c) FROM my_table) as c,
(SELECT group_concat(DISTINCT d) FROM my_table) as d

Bootstrap 3 breakpoints and media queries

@media screen and (max-width: 767px) {

}

@media screen and (min-width: 768px) and (max-width: 991px){


}

@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape){


}

@media screen and (min-width: 992px) {



}

Scrolling to an Anchor using Transition/CSS3

I guess it might be possible to set some kind of hardcore transition to the top style of a #container div to move your entire page in the desired direction when clicking your anchor. Something like adding a class that has top:-2000px.

I did use JQuery because I'm to lazy too use native JS, but it is not necessary for what I did.

This is probably not the best possible solution because the top content just moves towards the top and you can't get it back easily, you should definitely use JQuery if you really need that scroll animation.

DEMO

How to call a MySQL stored procedure from within PHP code?

This is my solution with prepared statements and stored procedure is returning several rows not only one value.

<?php

require 'config.php';
header('Content-type:application/json');
$connection->set_charset('utf8');

$mIds = $_GET['ids'];

$stmt = $connection->prepare("CALL sp_takes_string_returns_table(?)");
$stmt->bind_param("s", $mIds);

$stmt->execute();

$result = $stmt->get_result();
$response = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($response);

$stmt->close();
$connection->close();

How to override and extend basic Django admin templates?

As for Django 1.8 being the current release, there is no need to symlink, copy the admin/templates to your project folder, or install middlewares as suggested by the answers above. Here is what to do:

  1. create the following tree structure(recommended by the official documentation)

    your_project
         |-- your_project/
         |-- myapp/
         |-- templates/
              |-- admin/
                  |-- myapp/
                      |-- change_form.html  <- do not misspell this
    

Note: The location of this file is not important. You can put it inside your app and it will still work. As long as its location can be discovered by django. What's more important is the name of the HTML file has to be the same as the original HTML file name provided by django.

  1. Add this template path to your settings.py:

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')], # <- add this line
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    
  2. Identify the name and block you want to override. This is done by looking into django's admin/templates directory. I am using virtualenv, so for me, the path is here:

    ~/.virtualenvs/edge/lib/python2.7/site-packages/django/contrib/admin/templates/admin
    

In this example, I want to modify the add new user form. The template responsiblve for this view is change_form.html. Open up the change_form.html and find the {% block %} that you want to extend.

  1. In your change_form.html, write somethings like this:

    {% extends "admin/change_form.html" %}
    {% block field_sets %}
         {# your modification here #}
    {% endblock %}
    
  2. Load up your page and you should see the changes

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

Use the directions API.

Make an ajax call i.e.

https://maps.googleapis.com/maps/api/directions/json?parameters

and then parse the responce

What algorithms compute directions from point A to point B on a map?

Probably similar to the answer on pre-computed routes between major locations and layered maps, but my understanding is that in games, to speed up A*, you have a map that is very coarse for macro navigation, and a fine-grained map for navigation to the boundary of macro directions. So you have 2 small paths to calculate, and hence your search space is much much smaller than simply doing a single path to the destination. And if you're in the business of doing this a lot, you'd have a lot of that data pre-computed so at least part of the search is a search for pre-computed data, rather than a search for a path.

crop text too long inside div

Below code will hide your text with fixed width you decide. but not quite right for responsive designs.

.CropLongTexts {
  width: 170px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

Update

I have noticed in (mobile) device(s) that the text (mixed) with each other due to (fixed width)... so i have edited the code above to become hidden responsively as follow:

.CropLongTexts {
  max-width: 170px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

The (max-width) ensure the text will be hidden responsively whatever the (screen size) and will not mixed with each other.

How do I debug a stand-alone VBScript script?

Run cscript.exe for full command args, I think

cscript //X scriptfile.vbs MyArg1 MyArg2

will run the script in a debugger.

How can I display an RTSP video stream in a web page?

For purposes like this one I use VLC as a redistribution server. You said you get to catch the video with VLC? Right-click on the media in VLC, select "stream" and choose your options. You can also do it with command line, which gives you potential benefits of various option (transcoding, scaling, compressing, desinterlacing). Here is a batch that starts VLC distribution from source to its own 555 port (so you will have to type rstp://myvlcserveripaddress:555 in your src option on the webpage to get the stream)

cd \
cd C:\Program Files (x86)\VideoLAN\VLC\

vlc --logo-file C:\logo.png --logo-position 5 --logo-opacity 200 --logo-x 900 --logo-y -2 "mmsh://typeyoursourceIPhere:554" :sout=#transcode{vcodec=div3,vb=800,scale=0,acodec=mpga,ab=128,channels=2,samplerate=44100}:duplicate{dst=rtp{mux=ts,sdp=rtsp://:555/stream}} :sout-all :sout-keep

Here, you have a sample of a webpage that embeds player (based on VLC plugin).

Search all the occurrences of a string in the entire project in Android Studio

Android Studio Version 4.0.1 on Mac combination is for me:

Shift + Control + F

Is there an addHeaderView equivalent for RecyclerView?

Maybe wrap header and recyclerview into a coordinatorlayout:

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:elevation="0dp">

    <View
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_scrollFlags="scroll" />

</android.support.design.widget.AppBarLayout>

<android.support.v7.widget.RecyclerView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

Trigger event when user scroll to specific element - with jQuery

I use the same code doing that all the time, so added a simple jquery plugin doing it. 480 bytes long, and fast. Only bound elements analyzed in runtime.

https://www.npmjs.com/package/jquery-on-scrolled-to

It will be $('#scroll-to').onScrolledTo(0, function() { alert('you have scrolled to the h1!'); });

or use 0.5 instead of 0 if need to alert when half of the h1 shown.

Open Facebook Page in Facebook App (if installed) on Android

Here's a solution that mixes the code by Jared Rummler and AndroidMechanic.

Note: fb://facewebmodal/f?href= redirects to a weird facebook page that doesn't have the like and other important buttons, which is why I try fb://page/. It works fine with the current Facebook version (126.0.0.21.77, June 1st 2017). The catch might be useless, I left it just in case.

public static String getFacebookPageURL(Context context)
{
    final String FACEBOOK_PAGE_ID = "123456789";
    final String FACEBOOK_URL = "MyFacebookPage";

    if(appInstalledOrNot(context, "com.facebook.katana"))
    {
        try
        {
            return "fb://page/" + FACEBOOK_PAGE_ID;
            // previous version, maybe relevant for old android APIs ?
            // return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
        }
        catch(Exception e) {}
    }
    else
    {
        return FACEBOOK_URL;
    }

}

Here's the appInstalledOrNot function which I took (and modified) from Aerrow's answer to this post

private static boolean appInstalledOrNot(Context context, String uri)
{
    PackageManager pm = context.getPackageManager();
    try
    {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    }
    catch(PackageManager.NameNotFoundException e)
    {
    }

    return false;
}

How to get the Facebook ID of a page:

  1. Go to your page
  2. Right-click and View Page Source
  3. Find in page: fb://page/?id=
  4. Here you go!

Java, How to specify absolute value and square roots

Use the static methods in the Math class for both - there are no operators for this in the language:

double root = Math.sqrt(value);
double absolute = Math.abs(value);

(Likewise there's no operator for raising a value to a particular power - use Math.pow for that.)

If you use these a lot, you might want to use static imports to make your code more readable:

import static java.lang.Math.sqrt;
import static java.lang.Math.abs;

...

double x = sqrt(abs(x) + abs(y));

instead of

double x = Math.sqrt(Math.abs(x) + Math.abs(y));

jquery: get id from class selector

Doh.. If I get you right, it should be as simple as:

_x000D_
_x000D_
$('.test').click(function() {_x000D_
  console.log(this.id);_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<a href="#" class="test" id="test_1">Some text</a>_x000D_
<a href="#" class="test" id="test_2">Some text</a>_x000D_
<a href="#" class="test" id="test_3">Some text</a>
_x000D_
_x000D_
_x000D_

You can just access the id property over the underlaying dom node, within the event handler.

Can't bind to 'formGroup' since it isn't a known property of 'form'

If you have to import two modules then add like this below

import {ReactiveFormsModule,FormsModule} from '@angular/forms';
@NgModule({
  declarations: [
    AppComponent,
    HomeComponentComponent,
    BlogComponentComponent,
    ContactComponentComponent,
    HeaderComponentComponent,
    FooterComponentComponent,
    RegisterComponent,
    LoginComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    routes,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

How to encrypt and decrypt file in Android?

Use a CipherOutputStream or CipherInputStream with a Cipher and your FileInputStream / FileOutputStream.

I would suggest something like Cipher.getInstance("AES/CBC/PKCS5Padding") for creating the Cipher class. CBC mode is secure and does not have the vulnerabilities of ECB mode for non-random plaintexts. It should be present in any generic cryptographic library, ensuring high compatibility.

Don't forget to use a Initialization Vector (IV) generated by a secure random generator if you want to encrypt multiple files with the same key. You can prefix the plain IV at the start of the ciphertext. It is always exactly one block (16 bytes) in size.

If you want to use a password, please make sure you do use a good key derivation mechanism (look up password based encryption or password based key derivation). PBKDF2 is the most commonly used Password Based Key Derivation scheme and it is present in most Java runtimes, including Android. Note that SHA-1 is a bit outdated hash function, but it should be fine in PBKDF2, and does currently present the most compatible option.

Always specify the character encoding when encoding/decoding strings, or you'll be in trouble when the platform encoding differs from the previous one. In other words, don't use String.getBytes() but use String.getBytes(StandardCharsets.UTF_8).

To make it more secure, please add cryptographic integrity and authenticity by adding a secure checksum (MAC or HMAC) over the ciphertext and IV, preferably using a different key. Without an authentication tag the ciphertext may be changed in such a way that the change cannot be detected.

Be warned that CipherInputStream may not report BadPaddingException, this includes BadPaddingException generated for authenticated ciphers such as GCM. This would make the streams incompatible and insecure for these kind of authenticated ciphers.

error: could not create '/usr/local/lib/python2.7/dist-packages/virtualenv_support': Permission denied

You don't have permission to the Python folder.

sudo chown -R $USER /usr/local/lib/python2.7

How to increment a datetime by one day?

Here is another method to add days on date using dateutil's relativedelta.

from datetime import datetime
from dateutil.relativedelta import relativedelta

print 'Today: ',datetime.now().strftime('%d/%m/%Y %H:%M:%S') 
date_after_month = datetime.now()+ relativedelta(day=1)
print 'After a Days:', date_after_month.strftime('%d/%m/%Y %H:%M:%S')

Output:

Today: 25/06/2015 20:41:44

After a Days: 01/06/2015 20:41:44

Delete default value of an input text on click

Just use a placeholder tag in your input instead of value

The view or its master was not found or no view engine supports the searched locations

Check whether the View (.ASPX File) that you have created is having the same name as mentioned in the Controller. For e.g:

 public ActionResult GetView()
 {
    return View("MyView");
 }

In this case, the aspx file should be having the name MyView.aspx instead of GetView.aspx

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

How do I get the current year using SQL on Oracle?

Using to_char:

select to_char(sysdate, 'YYYY') from dual;

In your example you can use something like:

BETWEEN trunc(sysdate, 'YEAR') 
    AND add_months(trunc(sysdate, 'YEAR'), 12)-1/24/60/60;

The comparison values are exactly what you request:

select trunc(sysdate, 'YEAR') begin_year
     , add_months(trunc(sysdate, 'YEAR'), 12)-1/24/60/60 last_second_year
from dual;

BEGIN_YEAR  LAST_SECOND_YEAR
----------- ----------------
01/01/2009  31/12/2009

Python xml ElementTree from a string source?

You need the xml.etree.ElementTree.fromstring(text)

from xml.etree.ElementTree import XML, fromstring
myxml = fromstring(text)

text box input height

You can define a class or id for input fields.

Or

input {
    line-height: 20px;
}

Hope this helps you.

AngularJS routing without the hash '#'

Lets write answer that looks simple and short

In Router at end add html5Mode(true);

app.config(function($routeProvider,$locationProvider) {

    $routeProvider.when('/home', {
        templateUrl:'/html/home.html'
    });

    $locationProvider.html5Mode(true);
})

In html head add base tag

<html>
<head>
    <meta charset="utf-8">    
    <base href="/">
</head>

thanks To @plus- for detailing the above answer

android:drawableLeft margin and/or padding

You can use android:drawableLeft="@drawable/your_icon" to set the drawable to be shown on the left side. In order to set a padding for the drawable you should use the android:paddingLeft or android:paddingRight to set the left/right padding respectively.

android:paddingRight="10dp"
android:paddingLeft="20dp"
android:drawableRight="@drawable/ic_app_manager"

How to connect to local instance of SQL Server 2008 Express

Under Configuration Manager and Network Configuration and Protocols for your instance is TCP/IP Enabled? That could be the problem.

How to upload file to server with HTTP POST multipart/form-data?

Here is what worked for me while sending the file as mult-form data:

    public T HttpPostMultiPartFileStream<T>(string requestURL, string filePath, string fileName)
    {
        string content = null;

        using (MultipartFormDataContent form = new MultipartFormDataContent())
        {
            StreamContent streamContent;
            using (var fileStream = new FileStream(filePath, FileMode.Open))
            {
                streamContent = new StreamContent(fileStream);

                streamContent.Headers.Add("Content-Type", "application/octet-stream");
                streamContent.Headers.Add("Content-Disposition", string.Format("form-data; name=\"file\"; filename=\"{0}\"", fileName));
                form.Add(streamContent, "file", fileName);

                using (HttpClient client = GetAuthenticatedHttpClient())
                {
                    HttpResponseMessage response = client.PostAsync(requestURL, form).GetAwaiter().GetResult();
                    content = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();



                    try
                    {
                        return JsonConvert.DeserializeObject<T>(content);
                    }
                    catch (Exception ex)
                    {
                        // Log the exception
                    }

                    return default(T);
                }
            }
        }
    }

GetAuthenticatedHttpClient used above can be:

private HttpClient GetAuthenticatedHttpClient()
{
    HttpClient httpClient = new HttpClient();
    httpClient.BaseAddress = new Uri(<yourBaseURL>));
    httpClient.DefaultRequestHeaders.Add("Token, <yourToken>);
    return httpClient;
}

Dynamic SELECT TOP @var In SQL Server

The syntax "select top (@var) ..." only works in SQL SERVER 2005+. For SQL 2000, you can do:

set rowcount @top

select * from sometable

set rowcount 0 

Hope this helps

Oisin.

(edited to replace @@rowcount with rowcount - thanks augustlights)

unix sort descending order

If you only want to sort only on the 5th field then use -k5,5.

Also, use the -t command line switch to specify the delimiter to tab. Try this:

sort  -k5,5 -r -n -t \t filename

or if the above doesn't work (with the tab) this:

sort  -k5,5 -r -n -t $'\t' filename

The man page for sort states:

-t, --field-separator=SEP use SEP instead of non-blank to blank transition

Finally, this SO question Unix Sort with Tab Delimiter might be helpful.

The type or namespace name 'System' could not be found

For the folks that like me got here because they're trying to host aspnet.core mvc in a console application: The ONLY way I was able to solve this was by converting the .csproj to the new format and add the Sdk property to the Project tag on the very first line.

<Project Sdk="Microsoft.NET.Sdk.Razor">

Escape regex special characters in a Python string

If you only want to replace some characters you could use this:

import re

print re.sub(r'([\.\\\+\*\?\[\^\]\$\(\)\{\}\!\<\>\|\:\-])', r'\\\1', "example string.")

Get only the date in timestamp in mysql

You can convert that time in Unix timestamp by using

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

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

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

For in detail you can visit link

Java logical operator short-circuiting

boolean a = (x < z) && (x == x);

This kind will short-circuit, meaning if (x < z) evaluates to false then the latter is not evaluated, a will be false, otherwise && will also evaluate (x == x).

& is a bitwise operator, but also a boolean AND operator which does not short-circuit.

You can test them by something as follows (see how many times the method is called in each case):

public static boolean getFalse() {
    System.out.println("Method");
    return false;
}

public static void main(String[] args) {
    if(getFalse() && getFalse()) { }        
    System.out.println("=============================");        
    if(getFalse() & getFalse()) { }
}

How do I create a link to add an entry to a calendar?

The links in Dave's post are great. Just to put a few technical details about the google links into an answer here on SO:

Google Calendar Link

<a href="http://www.google.com/calendar/event?action=TEMPLATE&text=Example%20Event&dates=20131124T010000Z/20131124T020000Z&details=Event%20Details%20Here&location=123%20Main%20St%2C%20Example%2C%20NY">Add to gCal</a>

the parameters being:

  • action=TEMPLATE (required)
  • text (url encoded name of the event)
  • dates (ISO date format, startdate/enddate - must have both start and end time - the button generator will let you leave the endtime blank, but you must have one or it won't work.)
    • to use the user's timezone: 20131208T160000/20131208T180000
    • to use global time, convert to UTC, then use 20131208T160000Z/20131208T180000Z
    • all day events, you can use 20131208/20131209 - note that the button generator gets it wrong. You must use the following date as the end date for a one day all day event, or +1 day to whatever you want the end date to be.
  • details (url encoded event description/details)
  • location (url encoded location of the event - make sure it's an address google maps can read easily)

Update Feb 2018:

Here's a new link structure that seems to support the new google version of google calendar w/o requiring API interaction:

https://calendar.google.com/calendar/r/eventedit?text=My+Custom+Event&dates=20180512T230000Z/20180513T030000Z&details=For+details,+link+here:+https://example.com/tickets-43251101208&location=Garage+Boston+-+20+Linden+Street+-+Allston,+MA+02134

New base url: https://calendar.google.com/calendar/r/eventedit

New parameters:

  • text (name of the event)
  • dates (ISO date format, startdate/enddate - must have both start and end time)
    • an event w/ start/end times: 20131208T160000/20131208T180000
    • all day events, you can use 20131208/20131209 - end date must be +1 day to whatever you want the end date to be.
  • ctz (timezone such as America/New_York - leave blank to use the user's default timezone. Highly recommended to include this in almost all situations. For example, a reminder for a video conference: if three people in different timezones clicked this link and set a reminder for their "own" Tuesday at 10:00am, this would not work out well.)
  • details (url encoded event description/details)
  • location (url encoded location of the event - make sure it's an address google maps can read easily)
  • add (comma separated list of emails - adds guests to your new event)

Notes:

  • the old url structure above now redirects here
  • supports https
  • deals w/ timezones better
  • accepts + for space in addition to %20 (urlencode vs rawurlencode in php - both work)

How to pad a string to a fixed length with spaces in Python?

I know this is a bit of an old question, but I've ended up making my own little class for it.

Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:

class consolePrinter():
'''
Class to write to the console

Objective is to make it easy to write to console, with user able to 
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------    
#Class variables
stringLen = 0    
# -------------------------------------------------------------------------    
    
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteFlag=False):
    import sys
    #Get length of stringIn and update stringLen if needed
    if len(stringIn) > consolePrinter.stringLen:
        consolePrinter.stringLen = len(stringIn)+1
    
    ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"
    if overwriteFlag:
        sys.stdout.write("\r" + ctrlString.format(stringIn))
    else:
        sys.stdout.write("\n" + stringIn)
    sys.stdout.flush()
    
    return

Which then is called via:

consolePrinter.writeline("text here", True) 

If you want to overwrite the previous line, or

consolePrinter.writeline("text here",False)

if you don't.

Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.

JQuery: detect change in input field

Same functionality i recently achieved using below function.

I wanted to enable SAVE button on edit.

  1. Change event is NOT advisable as it will ONLY be fired if after editing, mouse is clicked somewhere else on the page before clicking SAVE button.
  2. Key Press doesnt handle Backspace, Delete and Paste options.
  3. Key Up handles everything including tab, Shift key.

Hence i wrote below function combining keypress, keyup (for backspace, delete) and paste event for text fields.

Hope it helps you.

function checkAnyFormFieldEdited() {
    /*
     * If any field is edited,then only it will enable Save button
     */
    $(':text').keypress(function(e) { // text written
        enableSaveBtn();
    });

    $(':text').keyup(function(e) {
        if (e.keyCode == 8 || e.keyCode == 46) { //backspace and delete key
            enableSaveBtn();
        } else { // rest ignore
            e.preventDefault();
        }
    });
    $(':text').bind('paste', function(e) { // text pasted
        enableSaveBtn();
    });

    $('select').change(function(e) { // select element changed
        enableSaveBtn();
    });

    $(':radio').change(function(e) { // radio changed
        enableSaveBtn();
    });

    $(':password').keypress(function(e) { // password written
        enableSaveBtn();
    });
    $(':password').bind('paste', function(e) { // password pasted
        enableSaveBtn();
    });


}

CORS with spring-boot and angularjs not working

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class SimpleCORSFilter implements Filter {

private final Logger log = LoggerFactory.getLogger(SimpleCORSFilter.class);

public SimpleCORSFilter() {
    log.info("SimpleCORSFilter init");
}

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
    response.setHeader("Access-Control-Allow-Credentials", "true");
    response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With, remember-me");

    chain.doFilter(req, res);
}

@Override
public void init(FilterConfig filterConfig) {
}

@Override
public void destroy() {
}

}

No need extra define this filter just add this class. Spring will be scan and add it for you. SimpleCORSFilter. Here is the example: spring-enable-cors

Python constructors and __init__

There is no notion of method overloading in Python. But you can achieve a similar effect by specifying optional and keyword arguments

SQL Query to add a new column after an existing column in SQL Server 2005

It's possible.

First, just add each column the usual way (as the last column).

Secondly, in SQL Server Management Studio Get into Tools => Options.

Under 'Designers' Tab => 'Table and Database Designers' menu, uncheck the option 'Prevent saving changes that require table re-creation'.

Afterwards, right click on your table and choose 'Design'. In 'Design' mode just drag the columns to order them.

Don't forget to save.

XPath:: Get following Sibling

You can go for identifying a list of elements with xPath:

//td[text() = ' Color Digest ']/following-sibling::td[1]

This will give you a list of two elements, than you can use the 2nd element as your intended one. For example:

List<WebElement> elements = driver.findElements(By.xpath("//td[text() = ' Color Digest ']/following-sibling::td[1]"))

Now, you can use the 2nd element as your intended element, which is elements.get(1)

List of zeros in python

#add code here to figure out the number of 0's you need, naming the variable n.
listofzeros = [0] * n

if you prefer to put it in the function, just drop in that code and add return listofzeros

Which would look like this:

def zerolistmaker(n):
    listofzeros = [0] * n
    return listofzeros

sample output:

>>> zerolistmaker(4)
[0, 0, 0, 0]
>>> zerolistmaker(5)
[0, 0, 0, 0, 0]
>>> zerolistmaker(15)
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
>>> 

How to pass Multiple Parameters from ajax call to MVC Controller

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "ChnagePassword.aspx/AutocompleteSuggestions",
  data: "{'searchstring':'" + request.term + "','st':'Arb'}",
  dataType: "json",
  success: function (data) {
     response($.map(data.d, function (item) {
         return { value: item }
     }))
  },
  error: function (result) {
      alert("Error");
  }
});

Java: How To Call Non Static Method From Main Method?

You cannot call a non-static method from the main without instance creation, whereas you can simply call a static method. The main logic behind this is that, whenever you execute a .class file all the static data gets stored in the RAM and however, JVM(java virtual machine) would be creating context of the mentioned class which contains all the static data of the class. Therefore, it is easy to access the static data from the class without instance creation.The object contains the non-static data Context is created only once, whereas object can be created any number of times. context contains methods, variables etc. Whereas, object contains only data. thus, the an object can access both static and non-static data from the context of the class

Python: Importing urllib.quote

This is how I handle this, without using exceptions.

import sys
if sys.version_info.major > 2:  # Python 3 or later
    from urllib.parse import quote
else:  # Python 2
    from urllib import quote

Difference between Return and Break statements

break:- These transfer statement bypass the correct flow of execution to outside of the current loop by skipping on the remaining iteration

class test
{
    public static void main(String []args)
    {
        for(int i=0;i<10;i++)
        {
            if(i==5)
            break;
        }
        System.out.println(i);
    }
} 

output will be 
0
1
2
3
4

Continue :-These transfer Statement will bypass the flow of execution to starting point of the loop inorder to continue with next iteration by skipping all the remaining instructions .

class test
{
    public static void main(String []args)
    {
        for(int i=0;i<10;i++)
        {
            if(i==5)
            continue;
        }
        System.out.println(i);
    }
} 

output will be:
0
1
2
3
4
6
7
8
9 

return :- At any time in a method the return statement can be used to cause execution to branch back to the caller of the method. Thus, the return statement immediately terminates the method in which it is executed. The following example illustrates this point. Here, return causes execution to return to the Java run-time system, since it is the run-time system that calls main( ).

class test
{
    public static void main(String []args)
    {
        for(int i=0;i<10;i++)
        {
            if(i==5)
            return;
        }
        System.out.println(i)
    }
} 


output will be :
0
1
2
3
4

Setting the target version of Java in ant javac

You may also set {{ant.build.javac.target=1.5}} ant property to update default target version of task. See http://ant.apache.org/manual/javacprops.html#target

How to get item's position in a list?

If your list got large enough and you only expected to find the value in a sparse number of indices, consider that this code could execute much faster because you don't have to iterate every value in the list.

lookingFor = 1
i = 0
index = 0
try:
  while i < len(testlist):
    index = testlist.index(lookingFor,i)
    i = index + 1
    print index
except ValueError: #testlist.index() cannot find lookingFor
  pass

If you expect to find the value a lot you should probably just append "index" to a list and print the list at the end to save time per iteration.

What is the most efficient way of finding all the factors of a number in Python?

Here is an example if you want to use the primes number to go a lot faster. These lists are easy to find on the internet. I added comments in the code.

# http://primes.utm.edu/lists/small/10000.txt
# First 10000 primes

_PRIMES = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 
        31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 
        73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 
        127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 
        179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 
        233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 
        283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 
        353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 
        419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 
        467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 
        547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 
        607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 
        661, 673, 677, 683, 691, 701, 709, 719, 727, 733, 
        739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 
        811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 
        877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 
        947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013, 
# Mising a lot of primes for the purpose of the example
)


from bisect import bisect_left as _bisect_left
from math import sqrt as _sqrt


def get_factors(n):
    assert isinstance(n, int), "n must be an integer."
    assert n > 0, "n must be greather than zero."
    limit = pow(_PRIMES[-1], 2)
    assert n <= limit, "n is greather then the limit of {0}".format(limit)
    result = set((1, n))
    root = int(_sqrt(n))
    primes = [t for t in get_primes_smaller_than(root + 1) if not n % t]
    result.update(primes)  # Add all the primes factors less or equal to root square
    for t in primes:
        result.update(get_factors(n/t))  # Add all the factors associted for the primes by using the same process
    return sorted(result)


def get_primes_smaller_than(n):
    return _PRIMES[:_bisect_left(_PRIMES, n)]

How do I force a DIV block to extend to the bottom of a page even if it has no content?

I think the issue would be fixed just making the html fill 100% also, might be body fills the 100% of the html but html doesn't fill 100% of the screen.

Try with:

html, body {
      height: 100%;
}

java.sql.SQLException: Incorrect string value: '\xF0\x9F\x91\xBD\xF0\x9F...'

I faced the same issue and solved it by setting the Collation to utf8_general_ci for each column.

SVN Repository on Google Drive or DropBox

I made my own subversion repository on my Ubuntu One folder. Then, I imported the files to the repository using svn+ssh and my user account password.

When I want to do a checkout, I just checkout from my Ubuntu One folder. The commit process its analogue.

You must setup Ubutnu One on the devices that you want to grant access, then checkout the project from this folder to a temporary folder to edit it.

In my case, I use a folder in the Ubuntu One file-system, so I have the repository and my develop-folder in Ubuntu One.

What is the difference between \r and \n?

In addition to @Jon Skeet's answer:

Traditionally Windows has used \r\n, Unix \n and Mac \r, however newer Macs use \n as they're unix based.

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

LOL, I was doing all the steps here - I ended up doing the unpairing/repairing steps from the "given by Surjeet" answer. It didn't work, and then I noticed that when I clicked the "connect via network" button, the same yellow box would pop up that pops up when you repair, saying "busy" - I got frustrated and just started hammering the "connect via network" button, clicking it quickly for probably like 15 - 20 clicks - it started spazzing out, but eventually landed on being able to connect to the network. Before that worked, I also shut my wifi off and turned it on again, as suggested by one of these answers, but clicking the "connect via network" button really fast did the trick...LOL

Also, before I hammered the button, I linked the device support folders, although I'm not sure if it did anything:

open the terminal

cd /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport

ln -s 13.3 13.4

ls -l 13.4

restart Xcode and retry run on device

Said to do it here - https://forums.developer.apple.com/thread/126940 - I edited the folder version in my comment to adjust to the latest version of iOS 13.4.

EDIT I believe I figured out what my problem was, I had to stop my Little Snitch network filter. Also, after I was able to connect by hammering the button, the "connect via IP address" option appeared in the dropdown when you right click on the device in the devices manager in xcode, it wasn't there before I was able to connect ultra-hacky style the first time. If I connect, and then turn my network filter on, it disconnects my phone.

How to serve static files in Flask

A simplest working example based on the other answers is the following:

from flask import Flask, request
app = Flask(__name__, static_url_path='')

@app.route('/index/')
def root():
    return app.send_static_file('index.html')

if __name__ == '__main__':
  app.run(debug=True)

With the HTML called index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Hello World!</title>
</head>
<body>
    <div>
         <p>
            This is a test.
         </p>
    </div>
</body>
</html>

IMPORTANT: And index.html is in a folder called static, meaning <projectpath> has the .py file, and <projectpath>\static has the html file.

If you want the server to be visible on the network, use app.run(debug=True, host='0.0.0.0')

EDIT: For showing all files in the folder if requested, use this

@app.route('/<path:path>')
def static_file(path):
    return app.send_static_file(path)

Which is essentially BlackMamba's answer, so give them an upvote.

Twitter Bootstrap date picker

add

z-index:1151;

to the style sheet in

.datepicker

jquery - Click event not working for dynamically created button

the simple and easy way to do that is use on event:

$('body').on('click','#element',function(){
    //somthing
});

but we can say this is not the best way to do this. I suggest a another way to do this is use clone() method instead of using dynamic html. Write some html in you file for example:

<div id='div1'></div>

Now in the script tag make a clone of this div then all the properties of this div would follow with new element too. For Example:

var dynamicDiv = jQuery('#div1').clone(true);

Now use the element dynamicDiv wherever you want to add it or change its properties as you like. Now all jQuery functions will work with this element

How can I detect when an Android application is running in the emulator?

if ("sdk".equals( Build.PRODUCT )) {
 // Then you are running the app on the emulator.
        Log.w("MyAPP", "\n\n  Emulator \n\n"); 
}

What is the format for the PostgreSQL connection string / URL?

server.address=10.20.20.10
server.port=8080
database.user=username
database.password=password
spring.datasource.url=jdbc:postgresql://${server.address}/${server.port}?user=${database.user}&password=${database.password}

Convert laravel object to array

$foo = Bar::getBeers(); $foo = $foo->toArray();

Find unused npm packages in package.json

There is also a package called npm-check:

npm-check

Check for outdated, incorrect, and unused dependencies.

enter image description here

It is quite powerful and actively developed. One of it's features it checking for unused dependencies - for this part it uses the depcheck module mentioned in the other answer.

What is the meaning of ImagePullBackOff status on a Kubernetes pod?

You can specify also imagePullPolicy: Never in the container's spec:

containers:
- name: nginx
  imagePullPolicy: Never
  image: custom-nginx
  ports:
  - containerPort: 80

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

I have the same problem and the solution was uncheck the "use ports 80 and 443" on skype advanced configuration!

Using moment.js to convert date to string "MM/dd/yyyy"

I think you just have incorrect casing in the format string. According to the documentation this should work for you: MM/DD/YYYY

moment.js documentation

When increasing the size of VARCHAR column on a large table could there be any problems?

This is a metadata change only: it is quick.

An observation: specify NULL or NOT NULL explicitly to avoid "accidents" if one of the SET ANSI_xx settings are different eg run in osql not SSMS for some reason

Declaring a variable and setting its value from a SELECT query in Oracle

One Additional point:

When you are converting from tsql to plsql you have to worry about no_data_found exception

DECLARE
   v_var NUMBER;
BEGIN
   SELECT clmn INTO v_var FROM tbl;
Exception when no_data_found then v_var := null; --what ever handle the exception.
END;

In tsql if no data found then the variable will be null but no exception

Django Reverse with arguments '()' and keyword arguments '{}' not found

This problems gave me great headache when i tried to use reverse for generating activation link and send it via email of course. So i think from tests.py it will be same. The correct way to do this is following:

from django.test import Client
from django.core.urlresolvers import reverse

#app name - name of the app where the url is defined
client= Client()
response = client.get(reverse('app_name:edit_project', project_id=4)) 

How to get a cross-origin resource sharing (CORS) post request working

I finally stumbled upon this link "A CORS POST request works from plain javascript, but why not with jQuery?" that notes that jQuery 1.5.1 adds the

 Access-Control-Request-Headers: x-requested-with

header to all CORS requests. jQuery 1.5.2 does not do this. Also, according to the same question, setting a server response header of

Access-Control-Allow-Headers: *

does not allow the response to continue. You need to ensure the response header specifically includes the required headers. ie:

Access-Control-Allow-Headers: x-requested-with 

How to rename array keys in PHP?

Recursive php rename keys function:

function replaceKeys($oldKey, $newKey, array $input){
    $return = array(); 
    foreach ($input as $key => $value) {
        if ($key===$oldKey)
            $key = $newKey;

        if (is_array($value))
            $value = replaceKeys( $oldKey, $newKey, $value);

        $return[$key] = $value;
    }
    return $return; 
}

What is the difference between == and equals() in Java?

== is an operator and equals() is a method.

Operators are generally used for primitive type comparisons and thus == is used for memory address comparison and equals() method is used for comparing objects.

When to use self over $this?

When self is used with the :: operator it refers to the current class, which can be done both in static and non-static contexts. $this refers to the object itself. In addition, it is perfectly legal to use $this to call static methods (but not to refer to fields).

how to get GET and POST variables with JQuery?

Just for the record, I wanted to know the answer to this question, so I used a PHP method:

<script>
var jGets = new Array ();
<?
if(isset($_GET)) {
    foreach($_GET as $key => $val)
        echo "jGets[\"$key\"]=\"$val\";\n";
}
?>
</script>

That way all my javascript/jquery that runs after this can access everything in the jGets. Its an nice elegant solution I feel.

Rails: How can I set default values in ActiveRecord?

Here's a solution I've used that I was a little surprised hasn't been added yet.

There are two parts to it. First part is setting the default in the actual migration, and the second part is adding a validation in the model ensuring that the presence is true.

add_column :teams, :new_team_signature, :string, default: 'Welcome to the Team'

So you'll see here that the default is already set. Now in the validation you want to ensure that there is always a value for the string, so just do

 validates :new_team_signature, presence: true

What this will do is set the default value for you. (for me I have "Welcome to the Team"), and then it will go one step further an ensure that there always is a value present for that object.

Hope that helps!

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

Although a bit late, I've come across this question while searching the solution for the same problem, so I hope it can be of any help...

Found myself in the same darkness than you. Just found this article, which explains some new hints introduced in NetBeans 7.4, including this one:

https://blogs.oracle.com/netbeansphp/entry/improve_your_code_with_new

The reason why it has been added is because superglobals usually are filled with user input, which shouldn't ever be blindly trusted. Instead, some kind of filtering should be done, and that's what the hint suggests. Filter the superglobal value in case it has some poisoned content.

For instance, where I had:

$_SERVER['SERVER_NAME']

I've put instead:

filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_STRING)

You have the filter_input and filters doc here:

http://www.php.net/manual/en/function.filter-input.php

http://www.php.net/manual/en/filter.filters.php

How to use protractor to check if an element is visible?

If there are multiple elements in DOM with same class name. But only one of element is visible.

element.all(by.css('.text-input-input')).filter(function(ele){
        return ele.isDisplayed();
    }).then(function(filteredElement){
        filteredElement[0].click();
    });

In this example filter takes a collection of elements and returns a single visible element using isDisplayed().

Xcode 5 and iOS 7: Architecture and Valid architectures

My understanding from Apple Docs.

  • What is Architectures (ARCHS) into Xcode build-settings?
    • Specifies architecture/s to which the binary is TARGETED. When specified more that one architecture, the generated binary may contain object code for each of the specified architecture.
  • What is Valid Architectures (VALID_ARCHS) into Xcode build-settings?

    • Specifies architecture/s for which the binary may be BUILT.
    • During build process, this list is intersected with ARCHS and the resulting list specifies the architectures the binary can run on.
  • Example :- One iOS project has following build-settings into Xcode.

    • ARCHS = armv7 armv7s
    • VALID_ARCHS = armv7 armv7s arm64
    • In this case, binary will be built for armv7 armv7s arm64 architectures. But the same binary will run on ONLY ARCHS = armv7 armv7s.

Regex Letters, Numbers, Dashes, and Underscores

Depending on your regex variant, you might be able to do simply this:

([\w-]+)

Also, you probably don't need the parentheses unless this is part of a larger expression.

How to implement a binary search tree in Python?

Just something to help you to start on.

A (simple idea of) binary tree search would be quite likely be implement in python according the lines:

def search(node, key):
    if node is None: return None  # key not found
    if key< node.key: return search(node.left, key)
    elif key> node.key: return search(node.right, key)
    else: return node.value  # found key

Now you just need to implement the scaffolding (tree creation and value inserts) and you are done.

how to set default method argument values?

If your arguments are the same type you could use varargs:

public int something(int... args) {
    int a = 0;
    int b = 0;
    if (args.length > 0) {
      a = args[0];
    }
    if (args.length > 1) {
      b = args[1];
    }
    return a + b
}

but this way you lose the semantics of the individual arguments, or

have a method overloaded which relays the call to the parametered version

public int something() {
  return something(1, 2);
}

or if the method is part of some kind of initialization procedure, you could use the builder pattern instead:

class FoodBuilder {
   int saltAmount;
   int meatAmount;
   FoodBuilder setSaltAmount(int saltAmount) {
       this.saltAmount = saltAmount;
       return this;
   }
   FoodBuilder setMeatAmount(int meatAmount) {
       this.meatAmount = meatAmount;
       return this;
   }
   Food build() {
       return new Food(saltAmount, meatAmount);
   }
}

Food f = new FoodBuilder().setSaltAmount(10).build();
Food f2 = new FoodBuilder().setSaltAmount(10).setMeatAmount(5).build();

Then work with the Food object

int doSomething(Food f) {
    return f.getSaltAmount() + f.getMeatAmount();
}

The builder pattern allows you to add/remove parameters later on and you don't need to create new overloaded methods for them.