Programs & Examples On #Dbms metadata

An Oracle package that enables the retrieval of an objects metadata.

JavaScript: How to find out if the user browser is Chrome?

You can use:

navigator.userAgent.indexOf("Chrome") != -1

It is working on v.71

How do I programmatically set device orientation in iOS 7?

Use this. Perfect solution to orientation problem..ios7 and earlier

[[UIDevice currentDevice] setValue:
    [NSNumber numberWithInteger: UIInterfaceOrientationPortrait]
        forKey:@"orientation"];

How to detect tableView cell touched or clicked in swift

To get an elements from Array in tableView cell touched or clicked in swift

func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell
    cell.textLabel?.text= arr_AsianCountries[indexPath.row]
    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let indexpath = arr_AsianCountries[indexPath.row]
print("indexpath:\(indexpath)")
}

Can you get the column names from a SqlDataReader?

Use an extension method:

    public static List<string> ColumnList(this IDataReader dataReader)
    {
        var columns = new List<string>();
        for (int i = 0; i < dataReader.FieldCount; i++)
        {
            columns.Add(dataReader.GetName(i));
        }
        return columns;
    }

ImportError: No module named PytQt5

If you are on ubuntu, just install pyqt5 with apt-get command:

    sudo apt-get install python3-pyqt5   # for python3

or

    sudo apt-get install python-pyqt5    # for python2

However, on Ubuntu 14.04 the python-pyqt5 package is left out [source] and need to be installed manually [source]

How do I iterate through lines in an external file with shell?

I know the purists will hate this method, but you can cat the file.

NAMES=`cat scripts/names.txt` #names from names.txt file
for NAME in $NAMES; do
   echo "$NAME"
done

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

I had the same error yesterday: I had two classes, cProgress and cProgressEx, in my project, one of which was no longer used, and when I removed cProgress class I was given this same compilation error.

I managed to fix the error as follows:

  • Exported all modules, forms and classes to the hard drive
  • Removed everything from the project
  • Saved the project
  • Reimported all modules, forms and classes, removed cProgress class, and compiled.
  • The error disappeared.

What are the differences between the different saving methods in Hibernate?

This link explains in good manner :

http://www.stevideter.com/2008/12/07/saveorupdate-versus-merge-in-hibernate/

We all have those problems that we encounter just infrequently enough that when we see them again, we know we’ve solved this, but can’t remember how.

The NonUniqueObjectException thrown when using Session.saveOrUpdate() in Hibernate is one of mine. I’ll be adding new functionality to a complex application. All my unit tests work fine. Then in testing the UI, trying to save an object, I start getting an exception with the message “a different object with the same identifier value was already associated with the session.” Here’s some example code from Java Persistence with Hibernate.

            Session session = sessionFactory1.openSession();
            Transaction tx = session.beginTransaction();
            Item item = (Item) session.get(Item.class, new Long(1234));
            tx.commit();
            session.close(); // end of first session, item is detached

            item.getId(); // The database identity is "1234"
            item.setDescription("my new description");
            Session session2 = sessionFactory.openSession();
            Transaction tx2 = session2.beginTransaction();
            Item item2 = (Item) session2.get(Item.class, new Long(1234));
            session2.update(item); // Throws NonUniqueObjectException
            tx2.commit();
            session2.close();

To understand the cause of this exception, it’s important to understand detached objects and what happens when you call saveOrUpdate() (or just update()) on a detached object.

When we close an individual Hibernate Session, the persistent objects we are working with are detached. This means the data is still in the application’s memory, but Hibernate is no longer responsible for tracking changes to the objects.

If we then modify our detached object and want to update it, we have to reattach the object. During that reattachment process, Hibernate will check to see if there are any other copies of the same object. If it finds any, it has to tell us it doesn’t know what the “real” copy is any more. Perhaps other changes were made to those other copies that we expect to be saved, but Hibernate doesn’t know about them, because it wasn’t managing them at the time.

Rather than save possibly bad data, Hibernate tells us about the problem via the NonUniqueObjectException.

So what are we to do? In Hibernate 3, we have merge() (in Hibernate 2, use saveOrUpdateCopy()). This method will force Hibernate to copy any changes from other detached instances onto the instance you want to save, and thus merges all the changes in memory before the save.

        Session session = sessionFactory1.openSession();
        Transaction tx = session.beginTransaction();
        Item item = (Item) session.get(Item.class, new Long(1234));
        tx.commit();
        session.close(); // end of first session, item is detached

        item.getId(); // The database identity is "1234"
        item.setDescription("my new description");
        Session session2 = sessionFactory.openSession();
        Transaction tx2 = session2.beginTransaction();
        Item item2 = (Item) session2.get(Item.class, new Long(1234));
        Item item3 = session2.merge(item); // Success!
        tx2.commit();
        session2.close();

It’s important to note that merge returns a reference to the newly updated version of the instance. It isn’t reattaching item to the Session. If you test for instance equality (item == item3), you’ll find it returns false in this case. You will probably want to work with item3 from this point forward.

It’s also important to note that the Java Persistence API (JPA) doesn’t have a concept of detached and reattached objects, and uses EntityManager.persist() and EntityManager.merge().

I’ve found in general that when using Hibernate, saveOrUpdate() is usually sufficient for my needs. I usually only need to use merge when I have objects that can have references to objects of the same type. Most recently, the cause of the exception was in the code validating that the reference wasn’t recursive. I was loading the same object into my session as part of the validation, causing the error.

Where have you encountered this problem? Did merge work for you or did you need another solution? Do you prefer to always use merge, or prefer to use it only as needed for specific cases

Getting only Month and Year from SQL DATE

This can be helpful as well.

SELECT YEAR(0), MONTH(0), DAY(0);

or

SELECT YEAR(getdate()), MONTH(getdate()), DAY(getdate());

or

SELECT YEAR(yourDateField), MONTH(yourDateField), DAY(yourDateField);

What does OpenCV's cvWaitKey( ) function do?

The cvWaitKey simply provides something of a delay. For example:

char c = cvWaitKey(33);
if( c == 27 ) break;

Tis was apart of my code in which a video was loaded into openCV and the frames outputted. The 33 number in the code means that after 33ms, a new frame would be shown. Hence, the was a dely or time interval of 33ms between each frame being shown on the screen. Hope this helps.

Can't connect to Postgresql on port 5432

I had the same problem after a MacOS system upgrade. Solved it by upgrading the postgres with brew. Details: it looks like the system was trying to access Postgres 11 using older Postgres 10 settings. I'm sure it was my mistake somewhere in the past, but luckily it all got sorted out with the upgrade above.

How to convert file to base64 in JavaScript?

Here are a couple functions I wrote to get a file in a json format which can be passed around easily:

    //takes an array of JavaScript File objects
    function getFiles(files) {
        return Promise.all(files.map(file => getFile(file)));
    }

    //take a single JavaScript File object
    function getFile(file) {
        var reader = new FileReader();
        return new Promise((resolve, reject) => {
            reader.onerror = () => { reader.abort(); reject(new Error("Error parsing file"));}
            reader.onload = function () {

                //This will result in an array that will be recognized by C#.NET WebApi as a byte[]
                let bytes = Array.from(new Uint8Array(this.result));

                //if you want the base64encoded file you would use the below line:
                let base64StringFile = btoa(bytes.map((item) => String.fromCharCode(item)).join(""));

                //Resolve the promise with your custom file structure
                resolve({ 
                    bytes: bytes,
                    base64StringFile: base64StringFile,
                    fileName: file.name, 
                    fileType: file.type
                });
            }
            reader.readAsArrayBuffer(file);
        });
    }

    //using the functions with your file:

    file = document.querySelector('#files > input[type="file"]').files[0]
    getFile(file).then((customJsonFile) => {
         //customJsonFile is your newly constructed file.
         console.log(customJsonFile);
    });

    //if you are in an environment where async/await is supported

    files = document.querySelector('#files > input[type="file"]').files
    let customJsonFiles = await getFiles(files);
    //customJsonFiles is an array of your custom files
    console.log(customJsonFiles);

What's wrong with using == to compare floats in Java?

As mentioned in other answers, doubles can have small deviations. And you could write your own method to compare them using an "acceptable" deviation. However ...

There is an apache class for comparing doubles: org.apache.commons.math3.util.Precision

It contains some interesting constants: SAFE_MIN and EPSILON, which are the maximum possible deviations of simple arithmetic operations.

It also provides the necessary methods to compare, equal or round doubles. (using ulps or absolute deviation)

Referencing another schema in Mongoose

Addendum: No one mentioned "Populate" --- it is very much worth your time and money looking at Mongooses Populate Method : Also explains cross documents referencing

http://mongoosejs.com/docs/populate.html

Input button target="_blank" isn't causing the link to load in a new window/tab

Please try this it's working for me

onClick="window.open('http://www.facebook.com/','facebook')"

<button type="button" class="btn btn-default btn-social" onClick="window.open('http://www.facebook.com/','facebook')">
          <i class="fa fa-facebook" aria-hidden="true"></i>
</button>

How do you find out which version of GTK+ is installed on Ubuntu?

Try,

apt-cache policy libgtk2.0-0 libgtk-3-0 

or,

dpkg -l libgtk2.0-0 libgtk-3-0

How to return an array from an AJAX call?

Use JSON to transfer data types (arrays and objects) between client and server.

In PHP:

In JavaScript:

PHP:

echo json_encode($id_numbers);

JavaScript:

id_numbers = JSON.parse(msg);

As Wolfgang mentioned, you can give a fourth parameter to jQuery to automatically decode JSON for you.

id_numbers = new Array();
$.ajax({
    url:"Example.php",
    type:"POST",
    success:function(msg){
        id_numbers = msg;
    },
    dataType:"json"
});

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

To use in Eloquent. Add on top of your model

protected $table = 'table_name as alias'

//table_name should be exact as in your database

..then use in your query like

ModelName::query()->select(alias.id, alias.name)

fatal: could not read Username for 'https://github.com': No such file or directory

Short Answer:

git init
git add README.md
git commit -m "first commit"


git remote add origin https://github.com/{USER_NAME}/{REPOSITORY_NAME}.git
git push --set-upstream origin master

Ignore first three lines if it's not a new repository.

Longer description:

Just had the same problem, as non of the above answers helped me, I have decided to post this solution that worked for me.

Few Notes:

  • The SSH key was generated
  • SSH key was added to github, still had this error.
  • I've made a new repository on GitHub for this project and followed the steps described

As the command line tool I used GitShell (for Windows, I use Terminal.app on Mac).
GitShell is official GitHub tool, can be downloaded from https://windows.github.com/

Hope this helps to anyone who has the same problem.

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

You have quite a few options for this:

1 - If you can find an SVG file for the map you want, you can use something like RaphaelJS or SnapSVG to add click listeners for your states/regions, this solution is the most customizable...

2 - You can use dedicated tools such as clickablemapbuilder (free) or makeaclickablemap (i think free also).

[disclaimer] Im the author of clickablemapbuilder.com :)

What is the purpose of the var keyword and when should I use it (or omit it)?

I see people are confused when declaring variables with or without var and inside or outside the function. Here is a deep example that will walk you through these steps:

See the script below in action here at jsfiddle

a = 1;// Defined outside the function without var
var b = 1;// Defined outside the function with var
alert("Starting outside of all functions... \n \n a, b defined but c, d not defined yet: \n a:" + a + "\n b:" + b + "\n \n (If I try to show the value of the undefined c or d, console.log would throw 'Uncaught ReferenceError: c is not defined' error and script would stop running!)");

function testVar1(){
    c = 1;// Defined inside the function without var
    var d = 1;// Defined inside the function with var
    alert("Now inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);

    a = a + 5;
    b = b + 5;
    c = c + 5;
    d = d + 5;

    alert("After added values inside the 1. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};


testVar1();
alert("Run the 1. function again...");
testVar1();

function testVar2(){
    var d = 1;// Defined inside the function with var
    alert("Now inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);

    a = a + 5;
    b = b + 5;
    c = c + 5;
    d = d + 5;

    alert("After added values inside the 2. function: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n d:" + d);
};

testVar2();

alert("Now outside of all functions... \n \n Final Values: \n a:" + a + "\n b:" + b + "\n c:" + c + "\n You will not be able to see d here because then the value is requested, console.log would throw error 'Uncaught ReferenceError: d is not defined' and script would stop. \n ");
alert("**************\n Conclusion \n ************** \n \n 1. No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.\n 2. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2() \n 3. If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.");
alert("Now check console.log for the error when value d is requested next:");
alert(d);

Conclusion

  1. No matter declared with or without var (like a, b) if they get their value outside the function, they will preserve their value and also any other values that are added inside various functions through the script are preserved.
  2. If the variable is declared without var inside a function (like c), it will act like the previous rule, it will preserve its value across all functions from now on. Either it got its first value in function testVar1() it still preserves the value and get additional value in function testVar2()
  3. If the variable is declared with var inside a function only (like d in testVar1 or testVar2) it will will be undefined whenever the function ends. So it will be temporary variable in a function.

Convert all data frame character columns to factors

DF <- data.frame(x=letters[1:5], y=1:5, stringsAsFactors=FALSE)

str(DF)
#'data.frame':  5 obs. of  2 variables:
# $ x: chr  "a" "b" "c" "d" ...
# $ y: int  1 2 3 4 5

The (annoying) default of as.data.frame is to turn all character columns into factor columns. You can use that here:

DF <- as.data.frame(unclass(DF))
str(DF)
#'data.frame':  5 obs. of  2 variables:
# $ x: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
# $ y: int  1 2 3 4 5

Why is synchronized block better than synchronized method?

One classic difference between Synchronized block and Synchronized method is that Synchronized method locks the entire object. Synchronized block just locks the code within the block.

Synchronized method: Basically these 2 sync methods disable multithreading. So one thread completes the method1() and the another thread waits for the Thread1 completion.

class SyncExerciseWithSyncMethod {

public synchronized void method1() {
    try {
        System.out.println("In Method 1");
        Thread.sleep(5000);
    } catch (Exception e) {
        System.out.println("Catch of method 1");
    } finally {
        System.out.println("Finally of method 1");
    }

}

public synchronized void method2() {
    try {
        for (int i = 1; i < 10; i++) {
            System.out.println("Method 2 " + i);
            Thread.sleep(1000);
        }
    } catch (Exception e) {
        System.out.println("Catch of method 2");
    } finally {
        System.out.println("Finally of method 2");
    }
}

}

Output

In Method 1

Finally of method 1

Method 2 1

Method 2 2

Method 2 3

Method 2 4

Method 2 5

Method 2 6

Method 2 7

Method 2 8

Method 2 9

Finally of method 2


Synchronized block: Enables multiple threads to access the same object at same time [Enables multi-threading].

class SyncExerciseWithSyncBlock {

public Object lock1 = new Object();
public Object lock2 = new Object();

public void method1() {
    synchronized (lock1) {
        try {
            System.out.println("In Method 1");
            Thread.sleep(5000);
        } catch (Exception e) {
            System.out.println("Catch of method 1");
        } finally {
            System.out.println("Finally of method 1");
        }
    }

}

public void method2() {

    synchronized (lock2) {
        try {
            for (int i = 1; i < 10; i++) {
                System.out.println("Method 2 " + i);
                Thread.sleep(1000);
            }
        } catch (Exception e) {
            System.out.println("Catch of method 2");
        } finally {
            System.out.println("Finally of method 2");
        }
    }
}

}

Output

In Method 1

Method 2 1

Method 2 2

Method 2 3

Method 2 4

Method 2 5

Finally of method 1

Method 2 6

Method 2 7

Method 2 8

Method 2 9

Finally of method 2

Reset local repository branch to be just like remote repository HEAD

The only solution that works in all cases that I've seen is to delete and reclone. Maybe there's another way, but obviously this way leaves no chance of old state being left there, so I prefer it. Bash one-liner you can set as a macro if you often mess things up in git:

REPO_PATH=$(pwd) && GIT_URL=$(git config --get remote.origin.url) && cd .. && rm -rf $REPO_PATH && git clone --recursive $GIT_URL $REPO_PATH && cd $REPO_PATH

* assumes your .git files aren't corrupt

How to make a custom LinkedIn share button

The API is updated now and the previous API will be deprecated on 1st March, 2019.

To create a custom Share button for LinkedIn, you need to make POST calls now. You can read the updated documentation here for doing so.

Difference between 'struct' and 'typedef struct' in C++?

In C++, there is only a subtle difference. It's a holdover from C, in which it makes a difference.

The C language standard (C89 §3.1.2.3, C99 §6.2.3, and C11 §6.2.3) mandates separate namespaces for different categories of identifiers, including tag identifiers (for struct/union/enum) and ordinary identifiers (for typedef and other identifiers).

If you just said:

struct Foo { ... };
Foo x;

you would get a compiler error, because Foo is only defined in the tag namespace.

You'd have to declare it as:

struct Foo x;

Any time you want to refer to a Foo, you'd always have to call it a struct Foo. This gets annoying fast, so you can add a typedef:

struct Foo { ... };
typedef struct Foo Foo;

Now struct Foo (in the tag namespace) and just plain Foo (in the ordinary identifier namespace) both refer to the same thing, and you can freely declare objects of type Foo without the struct keyword.


The construct:

typedef struct Foo { ... } Foo;

is just an abbreviation for the declaration and typedef.


Finally,

typedef struct { ... } Foo;

declares an anonymous structure and creates a typedef for it. Thus, with this construct, it doesn't have a name in the tag namespace, only a name in the typedef namespace. This means it also cannot be forward-declared. If you want to make a forward declaration, you have to give it a name in the tag namespace.


In C++, all struct/union/enum/class declarations act like they are implicitly typedef'ed, as long as the name is not hidden by another declaration with the same name. See Michael Burr's answer for the full details.

How to get commit history for just one branch?

You can use a range to do that.

git log master..

If you've checked out your my_experiment branch. This will compare where master is at to HEAD (the tip of my_experiment).

The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

This error comes because compile does not know where to find the class..so it occurs mainly when u copy or import item ..to solve this .. 1.change the namespace in the formname.cs and formname.designer.cs to the name of your project .

Spring,Request method 'POST' not supported

For information i removed the action attribute and i got this error when i call an ajax post..Even though my action attribute in the form looks like this action="javascript://;"

I thought I had it from the ajax call and serializing the form but I added the dummy action attribute to the form back again and it worked.

How can one see content of stack with GDB?

Use:

  • bt - backtrace: show stack functions and args
  • info frame - show stack start/end/args/locals pointers
  • x/100x $sp - show stack memory
(gdb) bt
#0  zzz () at zzz.c:96
#1  0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2  0xf7d3a4f6 in yyyinit () at yyy.c:590
#3  0x0804ac0c in gnninit () at gnn.c:374
#4  main (argc=1, argv=0xffffd5e4) at gnn.c:389

(gdb) info frame
Stack level 0, frame at 0xffeac770:
 eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
 source language c.
 Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
 Locals at 0xffeac768, Previous frame's sp is 0xffeac770
 Saved registers:
  ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c

(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba  0xf7d3c0d8  0xf7d3c21b  0x00000001
0xffeac64c: 0xf78d133f  0xffeac6f4  0xf7a14450  0xffeac678
0xffeac65c: 0x00000000  0xf7d3790e

Plotting multiple time series on the same plot using ggplot()

If both data frames have the same column names then you should add one data frame inside ggplot() call and also name x and y values inside aes() of ggplot() call. Then add first geom_line() for the first line and add second geom_line() call with data=df2 (where df2 is your second data frame). If you need to have lines in different colors then add color= and name for eahc line inside aes() of each geom_line().

df1<-data.frame(x=1:10,y=rnorm(10))
df2<-data.frame(x=1:10,y=rnorm(10))

ggplot(df1,aes(x,y))+geom_line(aes(color="First line"))+
  geom_line(data=df2,aes(color="Second line"))+
  labs(color="Legend text")

enter image description here

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

Shorter in Swift 4/5:

var string = "123456"
string = String(string.prefix(3)) //"123"
string = String(string.suffix(3)) //"456"

Best way to store data locally in .NET (C#)

Depending on the compelexity of your Account object, I would recomend either XML or Flat file.

If there are just a couple of values to store for each account, you could store them on a properties file, like this:

account.1.somekey=Some value
account.1.someotherkey=Some other value
account.1.somedate=2009-12-21
account.2.somekey=Some value 2
account.2.someotherkey=Some other value 2

... and so forth. Reading from a properties file should be easy, as it maps directly to a string dictionary.

As to where to store this file, the best choise would be to store into AppData folder, inside a subfolder for your program. This is a location where current users will always have access to write, and it's kept safe from other users by the OS itself.

Xcode 'CodeSign error: code signing is required'

  • I love Stack Overflow:

  • I realized that some time being too specific is not enough that is because we may have different Xcode version, I have 2 xcode version on the same Mac Pro myself. So here I would like to provide a general instruction that i hope it will work for all Xcode version:

  • My 2 versions are xcode 3.2.6 and 4.0. You need to find (even google for the settings) your xcode BUILD SETTINGS and its CODE SIGNING under CODE SIGNING you have CODE SIGN IDENTITY this provide you a list of IDENTIFIERS (if you do not have IDENTIFIERS go here to get one and registration is required https://developer.apple.com/ios/manage/overview/index.action - follow this instruction of Apple "Get your application on an iOS with the Development Provisioning Assistant") If you have a list of identifiers just select a valid one and run your Xcode again. It will work!

  • 3.2.6 specific: On your scode window - click on Project -> Project settings -> Build (tab) -> there is a scroll down because the list is long MAKING SURE you scroll down to find your CODE SIGNING section

  • 4.0 specific: On your xcode window - click on your project file left most colum -> then next colum click on your target app -> find CODE SIGNING and assign an IDENTIFIER. It should work for you.

Done!

turn typescript object into json string

You can use the standard JSON object, available in Javascript:

var a: any = {};
a.x = 10;
a.y='hello';
var jsonString = JSON.stringify(a);

How to exclude particular class name in CSS selector?

Method 1

The problem with your code is that you are selecting the .remode_hover that is a descendant of .remode_selected. So the first part of getting your code to work correctly is by removing that space

.reMode_selected.reMode_hover:hover

Then, in order to get the style to not work, you have to override the style set by the :hover. In other words, you need to counter the background-color property. So the final code will be

.reMode_selected.reMode_hover:hover {
  background-color:inherit;
}
.reMode_hover:hover {
  background-color: #f0ac00;
}

Fiddle

Method 2

An alternative method would be to use :not(), as stated by others. This will return any element that doesn't have the class or property stated inside the parenthesis. In this case, you would put .remode_selected in there. This will target all elements that don't have a class of .remode_selected

Fiddle

However, I would not recommend this method, because of the fact that it was introduced in CSS3, so browser support is not ideal.

Method 3

A third method would be to use jQuery. You can target the .not() selector, which would be similar to using :not() in CSS, but with much better browser support

Fiddle

How to read the Stock CPU Usage data

This should be the Unix load average. Wikipedia has a nice article about this.

The numbers show the average load of the CPU in different time intervals. From left to right: last minute/last five minutes/last fifteen minutes

Can not find the tag library descriptor of springframework

I had the same issue with weblogic 12c and maven I initially while deploying from eclipse (kepler) (deploying from the console gave no errors).

The other solutions given on this page didn't help.

I extracted the spring.tld spring-form.tld files of the spring-webmvc jar (which I found in my repository) in the web\WEB-INF folder of my war module;

I did a fresh build; deployed (from eclipse) into weblogic 12c, tested the application and the error was gone;

I removed the spring.tld spring-form.tld files again and after deleting; rebuilding and redeploying the application the error didn't show up again.

I double checked whether the files were gone in the war and they were indeed not present.

hope this helps others with a similar issue...

Java - How to convert type collection into ArrayList?

The following code will fail:

List<String> will_fail =  (List<String>)Collections.unmodifiableCollection(new ArrayList<String>());

This instead will work:

List<String> will_work = new ArrayList<String>(Collections.unmodifiableCollection(new ArrayList<String>()));

How to allow only numeric (0-9) in HTML inputbox using jQuery?

Need to make sure you have the numeric keypad and the tab key working too

 // Allow only backspace and delete
            if (event.keyCode == 46 || event.keyCode == 8  || event.keyCode == 9) {
                // let it happen, don't do anything
            }
            else {
                // Ensure that it is a number and stop the keypress
                if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) {

                }
                else {
                    event.preventDefault();
                }
            }

Get cart item name, quantity all details woocommerce

This will show only Cart Items Count.

 global $woocommerce; 
    echo $woocommerce->cart->cart_contents_count;

System.BadImageFormatException: Could not load file or assembly

I found a different solution to this issue. Apparently my IIS 7 did not have 32bit mode enabled in my Application Pool by default.

To enable 32bit mode, open IIS and select your Application Pool. Mine was named "ASP.NET v4.0".
Right click, go to "Advanced Settings" and change the section named: "Enabled 32-bit Applications" to true.

Restart your web server and try again.

I found the fix from this blog reference: http://darrell.mozingo.net/2009/01/17/running-iis-7-in-32-bit-mode/

Additionally, you can change the settings on Visual Studio. In my case, I went to Tools > Options > Projects and Solutions > Web Projects and checked Use the 64 bit version of IIS Express for web sites and projects - This was on VS Pro 2015. Nothing else fixed it but this.

How to comment and uncomment blocks of code in the Office VBA Editor

An easy way to add buttons to Comment or Un-Comment a code block is:

  • Go to View-Toolbars-Customise
  • Select the Command tab
  • Select the Edit Category on the left
  • Drag the “Comment Block” and “Uncomment Block” icons onto your toolbar.

How to send 100,000 emails weekly?

Short answer: While it's technically possible to send 100k e-mails each week yourself, the simplest, easiest and cheapest solution is to outsource this to one of the companies that specialize in it (I did say "cheapest": there's no limit to the amount of development time (and therefore money) that you can sink into this when trying to DIY).

Long answer: If you decide that you absolutely want to do this yourself, prepare for a world of hurt (after all, this is e-mail/e-fail we're talking about). You'll need:

  • e-mail content that is not spam (otherwise you'll run into additional major roadblocks on every step, even legal repercussions)
  • in addition, your content should be easy to distinguish from spam - that may be a bit hard to do in some cases (I heard that a certain pharmaceutical company had to all but abandon e-mail, as their brand names are quite common in spams)
  • a configurable SMTP server of your own, one which won't buckle when you dump 100k e-mails onto it (your ISP's upstream server won't be sufficient here and you'll make the ISP violently unhappy; we used two dedicated boxes)
  • some mail wrapper (e.g. PhpMailer if PHP's your poison of choice; using PHP's mail() is horrible enough by itself)
  • your own sender function to run in a loop, create the mails and pass them to the wrapper (note that you may run into PHP's memory limits if your app has a memory leak; you may need to recycle the sending process periodically, or even better, decouple the "creating e-mails" and "sending e-mails" altogether)

Surprisingly, that was the easy part. The hard part is actually sending it:

  • some servers will ban you when you send too many mails close together, so you need to shuffle and watch your queue (e.g. send one mail to [email protected], then three to other domains, only then another to [email protected])
  • you need to have correct PTR, SPF, DKIM records
  • handling remote server timeouts, misconfigured DNS records and other network pleasantries
  • handling invalid e-mails (and no, regex is the wrong tool for that)
  • handling unsubscriptions (many legitimate newsletters have been reclassified as spam due to many frustrated users who couldn't unsubscribe in one step and instead chose to "mark as spam" - the spam filters do learn, esp. with large e-mail providers)
  • handling bounces and rejects ("no such mailbox [email protected]","mailbox [email protected] full")
  • handling blacklisting and removal from blacklists (Sure, you're not sending spam. Some recipients won't be so sure - with such large list, it will happen sometimes, no matter what precautions you take. Some people (e.g. your not-so-scrupulous competitors) might even go as far to falsely report your mailings as spam - it does happen. On average, it takes weeks to get yourself removed from a blacklist.)

And to top it off, you'll have to manage the legal part of it (various federal, state, and local laws; and even different tangles of laws once you send outside the U.S. (note: you have no way of finding if [email protected] lives in Southwest Elbonia, the country with world's most draconian antispam laws)).

I'm pretty sure I missed a few heads of this hydra - are you still sure you want to do this yourself? If so, there'll be another wave, this time merely the annoying problems inherent in sending an e-mail. (You see, SMTP is a store-and-forward protocol, which means that your e-mail will be shuffled across many SMTP servers around the Internet, in the hope that the next one is a bit closer to the final recipient. Basically, the e-mail is sent to an SMTP server, which puts it into its forward queue; when time comes, it will forward it further to a different SMTP server, until it reaches the SMTP server for the given domain. This forward could happen immediately, or in a few minutes, or hours, or days, or never.) Thus, you'll see the following issues - most of which could happen en route as well as at the destination:

  • the remote SMTP servers don't want to talk to your SMTP server
  • your mails are getting marked as spam (<blink> is not your friend here, nor is <font color=...>)
  • your mails are delivered days, even weeks late (contrary to popular opinion, SMTP is designed to make a best effort to deliver the message sometime in the future - not to deliver it now)
  • your mails are not delivered at all (already sent from e-mail server on hop #4, not sent yet from server on hop #5, the server that currently holds the message crashes, data is lost)
  • your mails are mangled by some braindead server en route (this one is somewhat solvable with base64 encoding, but then the size goes up and the e-mail looks more suspicious)
  • your mails are delivered and the recipients seem not to want them ("I'm sure I didn't sign up for this, I remember exactly what I did a year ago" (of course you do, sir))
  • users with various versions of Microsoft Outlook and its special handling of Internet mail
  • wizard's apprentice mode (a self-reinforcing positive feedback loop - in other words, automated e-mails as replies to automated e-mails as replies to...; you really don't want to be the one to set this off, as you'd anger half the internet at yourself)

and it'll be your job to troubleshoot and solve this (hint: you can't, mostly). The people who run a legit mass-mailing businesses know that in the end you can't solve it, and that they can't solve it either - and they have the reasons well researched, documented and outlined (maybe even as a Powerpoint presentation - complete with sounds and cool transitions - that your bosses can understand), as they've had to explain this a million times before. Plus, for the problems that are actually solvable, they know very well how to solve them.

If, after all this, you are not discouraged and still want to do this, go right ahead: it's even possible that you'll find a better way to do this. Just know that the road ahead won't be easy - sending e-mail is trivial, getting it delivered is hard.

Bootstrap 3 Navbar with Logo

Bootstrap 3 navbar logo resizing

COMPLETE DEMO WITH MANY EXAMPLES

IMPORTANT UPDATE: 12/21/15

There is currently a bug in Mozilla I discovered that breaks the navbar on certain browser widths with MANY DEMOS ON THIS PAGE. Basically the mozilla bug is including the left and right padding on the navbar brand link as part of the image width. However, this can be fixed easily and I've tested this out and I fairly sure it's the most stable working example on this page. It will resize automatically and works on all browsers.

Just add this to your css and use navbar-brand the same way you would .img-responsive. Your logo will automatically fit

.navbar-brand {
  padding: 0px; /* firefox bug fix */
}
.navbar-brand>img {
  height: 100%;
  padding: 15px; /* firefox bug fix */
  width: auto;
}

Another option is to use a background image. Use an image of any size and then just set the desired width:

.navbar-brand {
  background: url(http://disputebills.com/site/uploads/2015/10/dispute.png) center / contain no-repeat;
  width: 200px;
}


ORIGINAL ANSWER BELOW (for reference only)

People seem to forget about object-fit a lot. Personally I think it's the easiest one to work with because the image automatically adjusts to the menu size. If you just use object fit on the image it will auto resize to the menus height.

    .navbar-brand > img {
      max-height: 100%;
      height: 100%;
      -o-object-fit: contain;
      object-fit: contain;
    }

It was pointed out that this does not work in IE "yet". There is a polyfill, but that might be excessive if you don't plan on using it for anything else. It does look like object-fit is being planned for a future release of IE so once that happens this will work in all browsers.

However, if you notice the .img-responsive class in bootstrap the max-width is assuming you are putting these images in columns or something that has an explicit with set. This would mean that 100% specifically means 100% width of the parent element.

    .img-responsive
        max-width: 100%;
        height: auto;
    }

The reason we can't use that with the navbar is because the parent (.navbar-brand) has a fixed height of 50px, but the width is not set.

If we take that logic and reverse it to be responsive based on the height we can have a responsive image that scales to the .navbar-brand height and by adding and auto set width it will adjust to proportion.

max-height: 100%;
width: auto;

Usually we would have to add display:block; to the scenario, but since navbar-brand already has float:left; applied to it, it automatically acts as a block element.


You may run into the rare situation where your logo is too small. The img-responsive approach does not take this into account, but we will. By also adding the "height" attribute to the .navbar-brand > img you can be assured that it will scale up as well as down.

max-height: 100%;
height: 100%;
width: auto;

So to complete this I put them both together and it seems to work perfectly in all browsers.

<style type="text/css">
.navbar-brand>img {
   max-height: 100%;
   height: 100%;
   width: auto;
   margin: 0 auto;


   /* probably not needed anymore, but doesn't hurt */
   -o-object-fit: contain;
   object-fit: contain; 

}
</style>

<nav class="navbar navbar-default">
      <div class="container">
        <div class="navbar-header">
          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
          </button>
          <a class="navbar-brand" href="http://disputebills.com"><img src="http://disputebills.com/site/uploads/2015/10/dispute.png" alt="Dispute Bills"></a>
        </div>
        <div id="navbar" class="collapse navbar-collapse">
          <ul class="nav navbar-nav">
            <li class="active"><a href="#">Home</a></li>
            <li><a href="#about">About</a></li>
            <li><a href="#contact">Contact</a></li>
          </ul>
        </div>
      </div>
</nav>

DEMO http://codepen.io/bootstrapped/pen/KwYGwq

Getting unix timestamp from Date()

To get a timestamp from Date(), you'll need to divide getTime() by 1000, i.e. :

Date currentDate = new Date();
currentDate.getTime() / 1000;
// 1397132691

or simply:

long unixTime = System.currentTimeMillis() / 1000L;

How to access host port from docker container

Currently the easiest way to do this on Mac and Windows is using host host.docker.internal, that resolves to host machine's IP address. Unfortunately it does not work on linux yet (as of April 2018).

How to read barcodes with the camera on Android?

Here is sample code using camera api

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;

public class MainActivity extends AppCompatActivity {

TextView barcodeInfo;
SurfaceView cameraView;
CameraSource cameraSource;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    cameraView = (SurfaceView) findViewById(R.id.camera_view);
      barcodeInfo = (TextView) findViewById(R.id.txtContent);


    BarcodeDetector barcodeDetector =
            new BarcodeDetector.Builder(this)
                    .setBarcodeFormats(Barcode.CODE_128)//QR_CODE)
                    .build();

    cameraSource = new CameraSource
            .Builder(this, barcodeDetector)
            .setRequestedPreviewSize(640, 480)
            .build();

    cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {

            try {
                cameraSource.start(cameraView.getHolder());
            } catch (IOException ie) {
                Log.e("CAMERA SOURCE", ie.getMessage());
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            cameraSource.stop();
        }
    });


    barcodeDetector.setProcessor(new Detector.Processor<Barcode>() {
        @Override
        public void release() {
        }

        @Override
        public void receiveDetections(Detector.Detections<Barcode> detections) {

            final SparseArray<Barcode> barcodes = detections.getDetectedItems();

            if (barcodes.size() != 0) {
                barcodeInfo.post(new Runnable() {    // Use the post method of the TextView
                    public void run() {
                        barcodeInfo.setText(    // Update the TextView
                                barcodes.valueAt(0).displayValue
                        );
                    }
                });
            }
        }
    });
}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.gateway.cameraapibarcode.MainActivity">

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <SurfaceView
        android:layout_width="640px"
        android:layout_height="480px"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:id="@+id/camera_view"/>

    <TextView
        android:text=" code reader"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtContent"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Process"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true" />
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imgview"/>
</LinearLayout>
</RelativeLayout>

build.gradle(Module:app)

add compile 'com.google.android.gms:play-services:7.8.+' in dependencies

Load local images in React.js

Best approach is to import image in js file and use it. Adding images in public folder have some downside:

  • Files inside public folder not get minified or post-processed,

  • You can't use hashed name (need to set in webpack config) for images , if you do then you have to change names again and again,

  • Can't find files at runtime (compilation), result in 404 error at client side.

What does the Ellipsis object do?

As mentioned by @no?????z??? and @phoenix - You can indeed use it in stub files. e.g.

class Foo:
    bar: Any = ...
    def __init__(self, name: str=...) -> None: ...

More information and examples of how to use this ellipsis can be discovered here https://www.python.org/dev/peps/pep-0484/#stub-files

Reinitialize Slick js after successful ajax call

After calling an request, set timeout to initialize slick slider.

var options = {
    arrows: false,
    slidesToShow: 1,
    variableWidth: true,
    centerPadding: '10px'
}

$.ajax({
    type: "GET",
    url: review_url+"?page="+page,
    success: function(result){
        setTimeout(function () {
            $(".reviews-page-carousel").slick(options)
        }, 500);
    }
})

Do not initialize slick slider at start. Just initialize after an AJAX with timeout. That should work for you.

Hot deploy on JBoss - how do I make JBoss "see" the change?

Start the server in debug mode and It will track changes inside methods. Other changes It will ask to restart the module.

C# Linq Where Date Between 2 Dates

If someone interested to know how to work with 2 list and between dates

var newList = firstList.Where(s => secondList.Any(secL => s.Start > secL.RangeFrom && s.End < secL.RangeTo))

Play local (hard-drive) video file with HTML5 video tag?

It is possible to play a local video file.

<input type="file" accept="video/*"/>
<video controls autoplay></video>

When a file is selected via the input element:

  1. 'change' event is fired
  2. Get the first File object from the input.files FileList
  3. Make an object URL that points to the File object
  4. Set the object URL to the video.src property
  5. Lean back and watch :)

http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/

_x000D_
_x000D_
(function localFileVideoPlayer() {_x000D_
  'use strict'_x000D_
  var URL = window.URL || window.webkitURL_x000D_
  var displayMessage = function(message, isError) {_x000D_
    var element = document.querySelector('#message')_x000D_
    element.innerHTML = message_x000D_
    element.className = isError ? 'error' : 'info'_x000D_
  }_x000D_
  var playSelectedFile = function(event) {_x000D_
    var file = this.files[0]_x000D_
    var type = file.type_x000D_
    var videoNode = document.querySelector('video')_x000D_
    var canPlay = videoNode.canPlayType(type)_x000D_
    if (canPlay === '') canPlay = 'no'_x000D_
    var message = 'Can play type "' + type + '": ' + canPlay_x000D_
    var isError = canPlay === 'no'_x000D_
    displayMessage(message, isError)_x000D_
_x000D_
    if (isError) {_x000D_
      return_x000D_
    }_x000D_
_x000D_
    var fileURL = URL.createObjectURL(file)_x000D_
    videoNode.src = fileURL_x000D_
  }_x000D_
  var inputNode = document.querySelector('input')_x000D_
  inputNode.addEventListener('change', playSelectedFile, false)_x000D_
})()
_x000D_
video,_x000D_
input {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.info {_x000D_
  background-color: aqua;_x000D_
}_x000D_
_x000D_
.error {_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
}
_x000D_
<h1>HTML5 local video file player example</h1>_x000D_
<div id="message"></div>_x000D_
<input type="file" accept="video/*" />_x000D_
<video controls autoplay></video>
_x000D_
_x000D_
_x000D_

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

Powershell Error "The term 'Get-SPWeb' is not recognized as the name of a cmdlet, function..."

Run this script from SharePoint 2010 Management Shell as Administrator.

Skip certain tables with mysqldump

You can use the mysqlpump command with the

--exclude-tables=name

command. It specifies a comma-separated list of tables to exclude.

Syntax of mysqlpump is very similar to mysqldump, buts its way more performant. More information of how to use the exclude option you can read here: https://dev.mysql.com/doc/refman/5.7/en/mysqlpump.html#mysqlpump-filtering

Find child element in AngularJS directive

jQlite (angular's "jQuery" port) doesn't support lookup by classes.

One solution would be to include jQuery in your app.

Another is using QuerySelector or QuerySelectorAll:

link: function(scope, element, attrs) {
   console.log(element[0].querySelector('.list-scrollable'))
}

We use the first item in the element array, which is the HTML element. element.eq(0) would yield the same.

FIDDLE

Is null reference possible?

Yes:

#include <iostream>
#include <functional>

struct null_ref_t {
   template <typename T>
   operator T&() {
      union TypeSafetyBreaker {
         T *ptr;

         // see https://stackoverflow.com/questions/38691282/use-of-union-with-reference
         std::reference_wrapper<T> ref; 
      };

      TypeSafetyBreaker ptr = {.ptr = nullptr};

      // unwrap the reference
      return ptr.ref.get();
   }
};

null_ref_t nullref;


int main() {
   int &a = nullref;

   // Segmentation fault
   a = 4;
   return 0;
}

Angular2, what is the correct way to disable an anchor element?

My answer might be late for this post. It can be achieved through inline css within anchor tag only.

<a [routerLink]="['/user']" [style.pointer-events]="isDisabled ?'none':'auto'">click-label</a>

Considering isDisabled is a property in component which can be true or false.

Plunker for it: https://embed.plnkr.co/TOh8LM/

How to redirect to another page in node.js

You should return the line that redirects

return res.redirect('/UserHomePage');

How to set the component size with GridLayout? Is there a better way?

For more complex layouts I often used GridBagLayout, which is more complex, but that's the price. Today, I would probably check out MiGLayout.

How to have conditional elements and keep DRY with Facebook React's JSX?

What about this. Let's define a simple helping If component.

var If = React.createClass({
    render: function() {
        if (this.props.test) {
            return this.props.children;
        }
        else {
            return false;
        }
    }
});

And use it this way:

render: function () {
    return (
        <div id="page">
            <If test={this.state.banner}>
                <div id="banner">{this.state.banner}</div>
            </If>
            <div id="other-content">
                blah blah blah...
            </div>
        </div>
    );
}

UPDATE: As my answer is getting popular, I feel obligated to warn you about the biggest danger related to this solution. As pointed out in another answer, the code inside the <If /> component is executed always regardless of whether the condition is true or false. Therefore the following example will fail in case the banner is null (note the property access on the second line):

<If test={this.state.banner}>
    <div id="banner">{this.state.banner.url}</div>
</If>

You have to be careful when you use it. I suggest reading other answers for alternative (safer) approaches.

UPDATE 2: Looking back, this approach is not only dangerous but also desperately cumbersome. It's a typical example of when a developer (me) tries to transfer patterns and approaches he knows from one area to another but it doesn't really work (in this case other template languages).

If you need a conditional element, do it like this:

render: function () {
    return (
        <div id="page">
            {this.state.banner &&
                <div id="banner">{this.state.banner}</div>}
            <div id="other-content">
                blah blah blah...
            </div>
        </div>
    );
}

If you also need the else branch, just use a ternary operator:

{this.state.banner ?
   <div id="banner">{this.state.banner}</div> :
   <div>There is no banner!</div>
}

It's way shorter, more elegant and safe. I use it all the time. The only disadvantage is that you cannot do else if branching that easily but that is usually not that common.

Anyway, this is possible thanks to how logical operators in JavaScript work. The logical operators even allow little tricks like this:

<h3>{this.state.banner.title || 'Default banner title'}</h3>

JavaScript function in href vs. onclick

Personally, I find putting javascript calls in the HREF tag annoying. I usually don't really pay attention to whether or not something is a javascript link or not, and often times want to open things in a new window. When I try doing this with one of these types of links, I get a blank page with nothing on it and javascript in my location bar. However, this is sidestepped a bit by using an onlick.

Command Prompt Error 'C:\Program' is not recognized as an internal or external command, operable program or batch file

try put cd before the file path

example:

C:\Users\user>cd C:\Program Files\MongoDB\Server\4.4\bin

List all tables in postgresql information_schema

If you want a quick and dirty one-liner query:

select * from information_schema.tables

You can run it directly in the Query tool without having to open psql.

(Other posts suggest nice more specific information_schema queries but as a newby, I am finding this one-liner query helps me get to grips with the table)

How to enable production mode?

Go to src/enviroments/enviroments.ts and enable the production mode

export const environment = {
  production: true
};

for Angular 2

Responsive background image in div full width

I also tried this style for ionic hybrid app background. this is also having style for background blur effect.

.bg-image {
   position: absolute;
   background: url(../img/bglogin.jpg) no-repeat;
   height: 100%;
   width: 100%;
   background-size: cover;
   bottom: 0px;
   margin: 0 auto;
   background-position: 50%;


  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);

}

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

For the OP's command:

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

I get this error:

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

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

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

this now results in:

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

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

from [#tmp_CTF**]

if that is the table name.

How to append data to div using JavaScript?

Beware of innerHTML, you sort of lose something when you use it:

theDiv.innerHTML += 'content';

Is equivalent to:

theDiv.innerHTML = theDiv.innerHTML + 'content';

Which will destroy all nodes inside your div and recreate new ones. All references and listeners to elements inside it will be lost.

If you need to keep them (when you have attached a click handler, for example), you have to append the new contents with the DOM functions(appendChild,insertAfter,insertBefore):

var newNode = document.createElement('div');
newNode.innerHTML = data;
theDiv.appendChild(newNode);

Resolve build errors due to circular dependency amongst classes

In some cases it is possible to define a method or a constructor of class B in the header file of class A to resolve circular dependencies involving definitions. In this way you can avoid having to put definitions in .cc files, for example if you want to implement a header only library.

// file: a.h
#include "b.h"
struct A {
  A(const B& b) : _b(b) { }
  B get() { return _b; }
  B _b;
};

// note that the get method of class B is defined in a.h
A B::get() {
  return A(*this);
}

// file: b.h
class A;
struct B {
  // here the get method is only declared
  A get();
};

// file: main.cc
#include "a.h"
int main(...) {
  B b;
  A a = b.get();
}

Add default value of datetime field in SQL Server to a timestamp

In SQLPlus while creating a table it is be like as

SQL> create table Test

 ( Test_ID number not null,
   Test_Date date default sysdate not null );

SQL> insert into Test(id) values (1);

 Test_ID Test_Date
       1 08-MAR-19

Reflection - get attribute name and value on property

private static Dictionary<string, string> GetAuthors()
{
    return typeof(Book).GetProperties()
        .SelectMany(prop => prop.GetCustomAttributes())
        .OfType<AuthorAttribute>()
        .ToDictionary(a => a.GetType().Name.Replace("Attribute", ""), a => a.Name);
}

Example using generics (target framework 4.5)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

private static Dictionary<string, string> GetAttribute<TAttribute, TType>(
    Func<TAttribute, string> valueFunc)
    where TAttribute : Attribute
{
    return typeof(TType).GetProperties()
        .SelectMany(p => p.GetCustomAttributes())
        .OfType<TAttribute>()
        .ToDictionary(a => a.GetType().Name.Replace("Attribute", ""), valueFunc);
}

Usage

var dictionary = GetAttribute<AuthorAttribute, Book>(a => a.Name);

What is the difference between public, protected, package-private and private in Java?

My two cents :)

private:

class -> a top level class cannot be private. inner classes can be private which are accessible from same class.

instance variable -> accessible only in the class. Cannot access outside the class.

package-private:

class -> a top level class can be package-private. It can only be accessible from same package. Not from sub package, not from outside package.

instance variable -> accessible from same package. Not from sub package, not from outside package.

protected:

class -> a top level class cannot be protected.

instance variable -> Only accessible in same package or subpackage. Can only be access outside the package while extending class.

public:

class -> accessible from package/subpackage/another package

instance variable -> accessible from package/subpackage/another package

Here is detailed answer

https://github.com/junto06/java-4-beginners/blob/master/basics/access-modifier.md

How can I find the version of the Fedora I use?

These commands worked for Artik 10 :

  • cat /etc/fedora-release
  • cat /etc/issue
  • hostnamectl

and these others didn't :

  • lsb_release -a
  • uname -a

jQuery get html of container including the container itself

I like to use this;

$('#container').prop('outerHTML');

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

If you have desired permissions saved to string then do

s = '660'
os.chmod(file_path, int(s, base=8))

Change image source in code behind - Wpf

None of the methods worked for me as i needed to pull the image from a folder instead of adding it to the application. The below code worked:

TestImage.Source = GetImage("/Content/Images/test.png")

private static BitmapImage GetImage(string imageUri)
{
    var bitmapImage = new BitmapImage();
    
    bitmapImage.BeginInit();
    bitmapImage.UriSource = new Uri("pack://siteoforigin:,,,/" + imageUri,             UriKind.RelativeOrAbsolute);
    bitmapImage.EndInit();
    
    return bitmapImage;
} 

event.preventDefault() vs. return false

e.preventDefault();

It simply stops the default action of an element.

Instance Ex.:-

prevents the hyperlink from following the URL, prevents the submit button to submit the form. When you have many event handlers and you just want to prevent default event from occuring, & occuring from many times, for that we need to use in the top of the function().

Reason:-

The reason to use e.preventDefault(); is that in our code so something goes wrong in the code, then it will allow to execute the link or form to get submitted or allow to execute or allow whatever action you need to do. & link or submit button will get submitted & still allow further propagation of the event.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en" dir="ltr">_x000D_
   <head>_x000D_
      <meta charset="utf-8">_x000D_
      <title></title>_x000D_
   </head>_x000D_
   <body>_x000D_
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
      <a href="https://www.google.com" onclick="doSomethingElse()">Preventsss page from redirect</a>_x000D_
      <script type="text/javascript">_x000D_
         function doSomethingElse(){_x000D_
           console.log("This is Test...");_x000D_
         }_x000D_
         $("a").click(function(e){_x000D_
          e.preventDefault(); _x000D_
         });_x000D_
      </script>_x000D_
   </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

return False;

It simply stops the execution of the function().

"return false;" will end the whole execution of process.

Reason:-

The reason to use return false; is that you don't want to execute the function any more in strictly mode.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en" dir="ltr">_x000D_
   <head>_x000D_
      <meta charset="utf-8">_x000D_
      <title></title>_x000D_
   </head>_x000D_
   <body>_x000D_
      <a href="#" onclick="returnFalse();">Blah</a>_x000D_
      <script type="text/javascript">_x000D_
         function returnFalse(){_x000D_
         console.log("returns false without location redirection....")_x000D_
             return false;_x000D_
             location.href = "http://www.google.com/";_x000D_
         _x000D_
         }_x000D_
      </script>_x000D_
   </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

python error: no module named pylab

I solved the same problem by installing "matplotlib".

SQL Server Insert Example

To insert a single row of data:

INSERT INTO USERS
VALUES (1, 'Mike', 'Jones');

To do an insert on specific columns (as opposed to all of them) you must specify the columns you want to update.

INSERT INTO USERS (FIRST_NAME, LAST_NAME)
VALUES ('Stephen', 'Jiang');

To insert multiple rows of data in SQL Server 2008 or later:

INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');

To insert multiple rows of data in earlier versions of SQL Server, use "UNION ALL" like so:

INSERT INTO USERS (FIRST_NAME, LAST_NAME)
SELECT 'James', 'Bond' UNION ALL
SELECT 'Miss', 'Moneypenny' UNION ALL
SELECT 'Raoul', 'Silva'

Note, the "INTO" keyword is optional in INSERT queries. Source and more advanced querying can be found here.

Escape double quote character in XML

Here are the common characters which need to be escaped in XML, starting with double quotes:

  1. double quotes (") are escaped to &quot;
  2. ampersand (&) is escaped to &amp;
  3. single quotes (') are escaped to &apos;
  4. less than (<) is escaped to &lt;
  5. greater than (>) is escaped to &gt;

How do I see all foreign keys to a table or column?

For a Table:

SELECT 
  TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_SCHEMA = '<database>' AND
  REFERENCED_TABLE_NAME = '<table>';

For a Column:

SELECT 
  TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME
FROM
  INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_SCHEMA = '<database>' AND
  REFERENCED_TABLE_NAME = '<table>' AND
  REFERENCED_COLUMN_NAME = '<column>';

Basically, we changed REFERENCED_TABLE_NAME with REFERENCED_COLUMN_NAME in the where clause.

How to delete Certain Characters in a excel 2010 cell

If [John Smith] is in cell A1, then use this formula to do what you want:

=SUBSTITUTE(SUBSTITUTE(A1, "[", ""), "]", "")

The inner SUBSTITUTE replaces all instances of "[" with "" and returns a new string, then the other SUBSTITUTE replaces all instances of "]" with "" and returns the final result.

Disabling Controls in Bootstrap

Remember for jQuery 1.6+ you should use the .prop() function.

$("input").prop('disabled', true);

$("input").prop('disabled', false);

Docker remove <none> TAG images

docker image prune removes all dangling images (those with tag none). docker image prune -a would also remove any images that have no container that uses them.

The difference between dangling and unused images is explained in this stackoverflow thread.

Avoid "current URL string parser is deprecated" warning by setting useNewUrlParser to true

The connection string format must be mongodb://user:password@host:port/db

For example:

MongoClient.connect('mongodb://user:[email protected]:27017/yourDB', { useNewUrlParser: true } )

How to find if a file contains a given string using Windows command line

I've used a DOS command line to do this. Two lines, actually. The first one to make the "current directory" the folder where the file is - or the root folder of a group of folders where the file can be. The second line does the search.

CD C:\TheFolder
C:\TheFolder>FINDSTR /L /S /I /N /C:"TheString" *.PRG

You can find details about the parameters at this link.

Hope it helps!

org.apache.http.conn.HttpHostConnectException: Connection to http://localhost refused in android

for wamp server use 10.0.2.2 for local host e.g. 10.0.2.2/phpMyAdmin

and for tomcat use 10.0.2.2:8080/server

JavaScript regex for alphanumeric string with length of 3-5 chars

add {3,5} to your expression which means length between 3 to 5

/^([a-zA-Z0-9_-]){3,5}$/

Android: How do bluetooth UUIDs work?

The UUID is used for uniquely identifying information. It identifies a particular service provided by a Bluetooth device. The standard defines a basic BASE_UUID: 00000000-0000-1000-8000-00805F9B34FB.

Devices such as healthcare sensors can provide a service, substituting the first eight digits with a predefined code. For example, a device that offers an RFCOMM connection uses the short code: 0x0003

So, an Android phone can connect to a device and then use the Service Discovery Protocol (SDP) to find out what services it provides (UUID).

In many cases, you don't need to use these fixed UUIDs. In the case your are creating a chat application, for example, one Android phone interacts with another Android phone that uses the same application and hence the same UUID.

So, you can set an arbitrary UUID for your application using, for example, one of the many random UUID generators on the web (for example).

JavaScript data grid for millions of rows

Take a look at dGrid:

https://dgrid.io/

I agree that users will NEVER, EVER need to view millions of rows of data all at once, but dGrid can display them quickly (a screenful at a time).

Don't boil the ocean to make a cup of tea.

how to open a jar file in Eclipse

Try JadClipse.It will open all your .class file. Add library to your project and when you try to open any object declared in the lib file it will open just like your .java file.

In eclipse->help-> marketplace -> go to popular tab. There you can find plugins for the same.

Update: For those who are unable to find above plug-in, try downloading this: https://github.com/java-decompiler/jd-eclipse/releases/download/v1.0.0/jd-eclipse-site-1.0.0-RC2.zip

Then import it into Eclipse.

If you have issues importing above plug-in, refer: How to install plugin for Eclipse from .zip

Proper use of mutexes in Python

This is the solution I came up with:

import time
from threading import Thread
from threading import Lock

def myfunc(i, mutex):
    mutex.acquire(1)
    time.sleep(1)
    print "Thread: %d" %i
    mutex.release()


mutex = Lock()
for i in range(0,10):
    t = Thread(target=myfunc, args=(i,mutex))
    t.start()
    print "main loop %d" %i

Output:

main loop 0
main loop 1
main loop 2
main loop 3
main loop 4
main loop 5
main loop 6
main loop 7
main loop 8
main loop 9
Thread: 0
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: 5
Thread: 6
Thread: 7
Thread: 8
Thread: 9

HTML table with fixed headers and a fixed column?

<script>
   $(document).ready(function () {
   $("#GridHeader table").html($('#<%= GridView1.ClientID %>').html());
   $("#GridHeader table tbody .rows").remove();
   $('#<%= GridView1.ClientID %> tr:first th').hide();
});
</script>

<div id="GridHeader">
    <table></table>
</div>

<div style="overflow: auto; height:400px;">
    <asp:GridView ID="GridView1" runat="server" />
</div>

mysqld: Can't change dir to data. Server doesn't start

remove all files in "{path-to-mysql}\data" directory and run:

mysqld --initialize-insecure --basedir={path-to-mysql}\mysql --datadir={path-to-mysql}\data --console

Convert RGB to Black & White in OpenCV

This seemed to have worked for me!

Mat a_image = imread(argv[1]);

cvtColor(a_image, a_image, CV_BGR2GRAY);
GaussianBlur(a_image, a_image, Size(7,7), 1.5, 1.5);
threshold(a_image, a_image, 100, 255, CV_THRESH_BINARY);

How can jQuery deferred be used?

Another example using Deferreds to implement a cache for any kind of computation (typically some performance-intensive or long-running tasks):

var ResultsCache = function(computationFunction, cacheKeyGenerator) {
    this._cache = {};
    this._computationFunction = computationFunction;
    if (cacheKeyGenerator)
        this._cacheKeyGenerator = cacheKeyGenerator;
};

ResultsCache.prototype.compute = function() {
    // try to retrieve computation from cache
    var cacheKey = this._cacheKeyGenerator.apply(this, arguments);
    var promise = this._cache[cacheKey];

    // if not yet cached: start computation and store promise in cache 
    if (!promise) {
        var deferred = $.Deferred();
        promise = deferred.promise();
        this._cache[cacheKey] = promise;

        // perform the computation
        var args = Array.prototype.slice.call(arguments);
        args.push(deferred.resolve);
        this._computationFunction.apply(null, args);
    }

    return promise;
};

// Default cache key generator (works with Booleans, Strings, Numbers and Dates)
// You will need to create your own key generator if you work with Arrays etc.
ResultsCache.prototype._cacheKeyGenerator = function(args) {
    return Array.prototype.slice.call(arguments).join("|");
};

Here is an example of using this class to perform some (simulated heavy) calculation:

// The addingMachine will add two numbers
var addingMachine = new ResultsCache(function(a, b, resultHandler) {
    console.log("Performing computation: adding " + a + " and " + b);
    // simulate rather long calculation time by using a 1s timeout
    setTimeout(function() {
        var result = a + b;
        resultHandler(result);
    }, 1000);
});

addingMachine.compute(2, 4).then(function(result) {
    console.log("result: " + result);
});

addingMachine.compute(1, 1).then(function(result) {
    console.log("result: " + result);
});

// cached result will be used
addingMachine.compute(2, 4).then(function(result) {
    console.log("result: " + result);
});

The same underlying cache could be used to cache Ajax requests:

var ajaxCache = new ResultsCache(function(id, resultHandler) {
    console.log("Performing Ajax request for id '" + id + "'");
    $.getJSON('http://jsfiddle.net/echo/jsonp/?callback=?', {value: id}, function(data) {
        resultHandler(data.value);
    });
});

ajaxCache.compute("anID").then(function(result) {
    console.log("result: " + result);
});

ajaxCache.compute("anotherID").then(function(result) {
    console.log("result: " + result);
});

// cached result will be used
ajaxCache.compute("anID").then(function(result) {
    console.log("result: " + result);
});

You can play with the above code in this jsFiddle.

How to connect to LocalDB in Visual Studio Server Explorer?

Select in :

  1. Data Source: Microsoft SQL Server (SqlClient)
  2. Server name: (localdb)\MSSQLLocalDB
  3. Log on to the server: Use Windows Authentication

Press Refresh button to get the database name :)

Screenshot

Git command to show which specific files are ignored by .gitignore

It should be sufficient to use

git ls-files --others -i --exclude-standard

as that covers everything covered by

git ls-files --others -i --exclude-from=.git/info/exclude

therefore the latter is redundant.


You can make this easier by adding an alias to your ~/.gitconfig file:

git config --global alias.ignored "ls-files --others -i --exclude-standard"

Now you can just type git ignored to see the list. Much easier to remember, and faster to type.

If you prefer the more succinct display of Jason Geng's solution, you can add an alias for that like this:

git config --global alias.ignored "status --ignored -s"

However the more verbose output is more useful for troubleshooting problems with your .gitignore files, as it lists every single cotton-pickin' file that is ignored. You would normally pipe the results through grep to see if a file you expect to be ignored is in there, or if a file you don't want to be ignore is in there.

git ignored | grep some-file-that-isnt-being-ignored-properly

Then, when you just want to see a short display, it's easy enough to remember and type

git status --ignored

(The -s can normally be left off.)

How to send post request to the below post method using postman rest client

JSON:-

For POST request using json object it can be configured by selecting

Body -> raw -> application/json

POST JSON object using POSTMAN

Form Data(For Normal content POST):- multipart/form-data

For normal POST request (using multipart/form-data) it can be configured by selecting

Body -> form-data

POST multipart/form-data using POSTMAN

Why SQL Server throws Arithmetic overflow error converting int to data type numeric?

Numeric defines the TOTAL number of digits, and then the number after the decimal.

A numeric(3,2) can only hold up to 9.99.

Overloading operators in typedef structs (c++)

The breakdown of your declaration and its members is somewhat littered:

Remove the typedef

The typedef is neither required, not desired for class/struct declarations in C++. Your members have no knowledge of the declaration of pos as-written, which is core to your current compilation failure.

Change this:

typedef struct {....} pos;

To this:

struct pos { ... };

Remove extraneous inlines

You're both declaring and defining your member operators within the class definition itself. The inline keyword is not needed so long as your implementations remain in their current location (the class definition)


Return references to *this where appropriate

This is related to an abundance of copy-constructions within your implementation that should not be done without a strong reason for doing so. It is related to the expression ideology of the following:

a = b = c;

This assigns c to b, and the resulting value b is then assigned to a. This is not equivalent to the following code, contrary to what you may think:

a = c;
b = c;

Therefore, your assignment operator should be implemented as such:

pos& operator =(const pos& a)
{
    x = a.x;
    y = a.y;
    return *this;
}

Even here, this is not needed. The default copy-assignment operator will do the above for you free of charge (and code! woot!)

Note: there are times where the above should be avoided in favor of the copy/swap idiom. Though not needed for this specific case, it may look like this:

pos& operator=(pos a) // by-value param invokes class copy-ctor
{
    this->swap(a);
    return *this;
}

Then a swap method is implemented:

void pos::swap(pos& obj)
{
    // TODO: swap object guts with obj
}

You do this to utilize the class copy-ctor to make a copy, then utilize exception-safe swapping to perform the exchange. The result is the incoming copy departs (and destroys) your object's old guts, while your object assumes ownership of there's. Read more the copy/swap idiom here, along with the pros and cons therein.


Pass objects by const reference when appropriate

All of your input parameters to all of your members are currently making copies of whatever is being passed at invoke. While it may be trivial for code like this, it can be very expensive for larger object types. An exampleis given here:

Change this:

bool operator==(pos a) const{
    if(a.x==x && a.y== y)return true;
    else return false;
}

To this: (also simplified)

bool operator==(const pos& a) const
{
    return (x == a.x && y == a.y);
}

No copies of anything are made, resulting in more efficient code.


Finally, in answering your question, what is the difference between a member function or operator declared as const and one that is not?

A const member declares that invoking that member will not modifying the underlying object (mutable declarations not withstanding). Only const member functions can be invoked against const objects, or const references and pointers. For example, your operator +() does not modify your local object and thus should be declared as const. Your operator =() clearly modifies the local object, and therefore the operator should not be const.


Summary

struct pos
{
    int x;
    int y;

    // default + parameterized constructor
    pos(int x=0, int y=0) 
        : x(x), y(y)
    {
    }

    // assignment operator modifies object, therefore non-const
    pos& operator=(const pos& a)
    {
        x=a.x;
        y=a.y;
        return *this;
    }

    // addop. doesn't modify object. therefore const.
    pos operator+(const pos& a) const
    {
        return pos(a.x+x, a.y+y);
    }

    // equality comparison. doesn't modify object. therefore const.
    bool operator==(const pos& a) const
    {
        return (x == a.x && y == a.y);
    }
};

EDIT OP wanted to see how an assignment operator chain works. The following demonstrates how this:

a = b = c;

Is equivalent to this:

b = c;
a = b;

And that this does not always equate to this:

a = c;
b = c;

Sample code:

#include <iostream>
#include <string>
using namespace std;

struct obj
{
    std::string name;
    int value;

    obj(const std::string& name, int value)
        : name(name), value(value)
    {
    }

    obj& operator =(const obj& o)
    {
        cout << name << " = " << o.name << endl;
        value = (o.value+1); // note: our value is one more than the rhs.
        return *this;
    }    
};

int main(int argc, char *argv[])
{

    obj a("a", 1), b("b", 2), c("c", 3);

    a = b = c;
    cout << "a.value = " << a.value << endl;
    cout << "b.value = " << b.value << endl;
    cout << "c.value = " << c.value << endl;

    a = c;
    b = c;
    cout << "a.value = " << a.value << endl;
    cout << "b.value = " << b.value << endl;
    cout << "c.value = " << c.value << endl;

    return 0;
}

Output

b = c
a = b
a.value = 5
b.value = 4
c.value = 3
a = c
b = c
a.value = 4
b.value = 4
c.value = 3

How can I list all tags for a Docker image on a remote registry?

You can also use this scrap :

# vim /usr/sbin/docker-tags 

& Append Following (as it is):

#!/bin/bash
im="$1"
[[ -z "$im" ]] && { echo -e '\e[31m[-]\e[39m Where is the image name ??' ; exit ; }
[[ -z "$(echo "$im"| grep -o '/')" ]] && { link="https://hub.docker.com/r/library/$im/tags/" ; } || { link="https://hub.docker.com/r/$im/tags/" ; }
resp="$(curl -sL "$link")"
err="$(echo "$resp" | grep -o 'Page Not Found')"
if [[ ! -z "$err" ]] ; then
    echo -e "\e[31m[-]\e[39m No Image Found with name => [ \e[32m$im\e[39m ]"
    exit
else
    tags="$(echo "$resp"|sed  -e 's|}|\n|g' -e 's|{|\n|g'|grep '"result"'|sed -e 's|,|\n|g'|cut -d '[' -f2|cut -d ']' -f1|sed  '/"tags":/d'|sed -e 's|"||g')"
    echo -e "\e[32m$tags\e[39m"
fi

Make it Executable :

# chmod 755 /usr/sbin/docker-tags

Then Finally Try By :

$ docker-tags testexampleidontexist
   [-] No Image Found with name => [ testexampleidontexist ]

$ docker search ubuntu

$ docker-tags teamrock/ubuntu
   latest

[ Hope you are aware of $ & # before running any command ]

How do I remove documents using Node.js Mongoose?

As per Samyak Jain's Answer, i use Async Await

let isDelete = await MODEL_NAME.deleteMany({_id:'YOUR_ID', name:'YOUR_NAME'});

window.open with target "_blank" in Chrome

It's a setting in chrome. You can't control how the browser interprets the target _blank.

jQuery.ajax handling continue responses: "success:" vs ".done"?

From JQuery Documentation

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:

jqXHR.done(function( data, textStatus, jqXHR ) {});

An alternative construct to the success callback option, refer to deferred.done() for implementation details.

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); 

(added in jQuery 1.6) An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});

Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Composer: The requested PHP extension ext-intl * is missing from your system

If You have got this error while running composer install command, don't worry. Steps to be followed and requirements:

  • Step1: Go to server folder such as xampp(or) wampp etc.
  • Step2: open php folder inside that and go to ext folder.
  • Step3: If you find a file named as php_intl.dll no problem.

Just go to php.ini file and uncomment the line

From:

;extension=php_intl.dll

To:

extension=php_intl.dll
  • Step4: restart xampp, thats it

Note: If you don't find any of the file named as php_intl.dll, then you need to upgrade the PHP version.

Grid of responsive squares

You can make responsive grid of squares with verticaly and horizontaly centered content only with CSS. I will explain how in a step by step process but first here are 2 demos of what you can achieve :

Responsive 3x3 square grid Responsive square images in a 3x3 grid

Now let's see how to make these fancy responsive squares!



1. Making the responsive squares :

The trick for keeping elements square (or whatever other aspect ratio) is to use percent padding-bottom.
Side note: you can use top padding too or top/bottom margin but the background of the element won't display.

As top padding is calculated according to the width of the parent element (See MDN for reference), the height of the element will change according to its width. You can now Keep its aspect ratio according to its width.
At this point you can code :

HTML :

 <div></div>

CSS

div {
    width: 30%;
    padding-bottom: 30%; /* = width for a square aspect ratio */
}

Here is a simple layout example of 3*3 squares grid using the code above.

With this technique, you can make any other aspect ratio, here is a table giving the values of bottom padding according to the aspect ratio and a 30% width.

 Aspect ratio  |  padding-bottom  |  for 30% width
------------------------------------------------
    1:1        |  = width         |    30%
    1:2        |  width x 2       |    60%
    2:1        |  width x 0.5     |    15%
    4:3        |  width x 0.75    |    22.5%
    16:9       |  width x 0.5625  |    16.875%




2. Adding content inside the squares

As you can't add content directly inside the squares (it would expand their height and squares wouldn't be squares anymore) you need to create child elements (for this example I am using divs) inside them with position: absolute; and put the content inside them. This will take the content out of the flow and keep the size of the square.

Don't forget to add position:relative; on the parent divs so the absolute children are positioned/sized relatively to their parent.

Let's add some content to our 3x3 grid of squares :

HTML :

<div class="square">
    <div class="content">
        .. CONTENT HERE ..
    </div>
</div>
... and so on 9 times for 9 squares ...

CSS :

.square {
    float:left;
    position: relative;
    width: 30%;
    padding-bottom: 30%; /* = width for a 1:1 aspect ratio */
    margin:1.66%;
    overflow:hidden;
}

.content {
    position:absolute;
    height:80%; /* = 100% - 2*10% padding */
    width:90%; /* = 100% - 2*5% padding */
    padding: 10% 5%;
}

RESULT <-- with some formatting to make it pretty!



3.Centering the content

Horizontally :

This is pretty easy, you just need to add text-align:center to .content.
RESULT

Vertical alignment

This becomes serious! The trick is to use

display:table;
/* and */
display:table-cell;
vertical-align:middle;

but we can't use display:table; on .square or .content divs because it conflicts with position:absolute; so we need to create two children inside .content divs. Our code will be updated as follow :

HTML :

<div class="square">
    <div class="content">
        <div class="table">
            <div class="table-cell">
                ... CONTENT HERE ...
            </div>
        </div>
    </div>
</div>
... and so on 9 times for 9 squares ...

CSS :

.square {
    float:left;
    position: relative;
    width: 30%;
    padding-bottom : 30%; /* = width for a 1:1 aspect ratio */
    margin:1.66%;
    overflow:hidden;
}

.content {
    position:absolute;
    height:80%; /* = 100% - 2*10% padding */
    width:90%; /* = 100% - 2*5% padding */
    padding: 10% 5%;
}
.table{
    display:table;
    height:100%;
    width:100%;
}
.table-cell{
    display:table-cell;
    vertical-align:middle;
    height:100%;
    width:100%;
}




We have now finished and we can take a look at the result here :

LIVE FULLSCREEN RESULT

editable fiddle here


Is HTML considered a programming language?

No, HTML is not a programming language. The "M" stands for "Markup". Generally, a programming language allows you to describe some sort of process of doing something, whereas HTML is a way of adding context and structure to text.

If you're looking to add more alphabet soup to your CV, don't classify them at all. Just put them in a big pile called "Technologies" or whatever you like. Remember, however, that anything you list is fair game for a question.

HTML is so common that I'd expect almost any technology person to already know it (although not stuff like CSS and so on), so you might consider not listing every initialism you've ever come across. I tend to regard CVs listing too many things as suspicious, so I ask more questions to weed out the stuff that shouldn't be listed. :)

However, if your HTML experience includes serious web design stuff including Ajax, JavaScript, and so on, you might talk about those in your "Experience" section.

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

DateTime.strptime can handle seconds since epoch. The number must be converted to a string:

require 'date'
DateTime.strptime("1318996912",'%s')

Why doesn't wireshark detect my interface?

By Restarting NPF, I can see the interfaces with wireshark 1.6.5

Open a Command Prompt with administrative privileges.

  1. Execute the command "sc stop npf".
  2. Then start npf by command "sc start npf".
  3. Open WireShark.

That's it.

How do I test a private function or a class that has private methods, fields or inner classes?

I only test the public interface, but I have been known to make specific private methods protected so I can either mock them out entirely, or add in additional steps specific for unit testing purposes. A general case is to hook in flags I can set from the unit test to make certain methods intentionally cause an exception to be able to test fault paths; the exception triggering code is only in the test path in an overridden implementation of the protected method.

I minimize the need for this though and I always document the precise reasons to avoid confusion.

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

  1. The accepted answer is one way of fixing the issue, because it will just apply some strategy for the problematic dependency (com.google.code.findbugs:jsr305) and it will resolve the problem around the project, using some version of this dependency. Basically it will align the versions of this library inside the whole project.

  2. There is an answer from @Santhosh (and couple of other people) who suggests to exclude the same dependency for espresso, which should work by the same way, but if the project has some other dependencies who depend on the same library (com.google.code.findbugs:jsr305), again we will have the same issue. So in order to use this approach you will need to exclude the same group from all project dependencies, who depend on com.google.code.findbugs:jsr305. I personally found that Espresso Contrib and Espresso Intents also use com.google.code.findbugs:jsr305.

I hope this thoughts will help somebody to realise what exactly is happening here and how things work (not just copy paste some code) :).

Mixing C# & VB In The Same Project

Well, actually I inherited a project some years ago from a colleague who had decided to mix VB and C# webforms within the same project. That worked but is far from fun to maintain.

I decided that new code should be C# classes and to get them to work I had to add a subnode to the compilation part of web.config

        <codeSubDirectories>
            <add directoryName="VB"/>
            <add directoryName="CS"/>
        </codeSubDirectories>

The all VB code goes into a subfolder in the App_Code called VB and the C# code into the CS subfolder. This will produce two .dll files. It works, but code is compiled in the same order as listed in "codeSubDirectories" and therefore i.e Interfaces should be in the VB folder if used in both C# and VB.

I have both a reference to a VB and a C# compiler in

<system.codedom>
    <compilers>

The project is currently updated to framework 3.5 and it still works (but still no fun to maintain..)

How is length implemented in Java Arrays?

If you have an array of a known type or is a subclass of Object[] you can cast the array first.

Object array = new ????[n];
Object[] array2 = (Object[]) array;
System.out.println(array2.length);

or

Object array = new char[n];
char[] array2 = (char[]) array;
System.out.println(array2.length);

However if you have no idea what type of array it is you can use Array.getLength(Object);

System.out.println(Array.getLength(new boolean[4]);
System.out.println(Array.getLength(new int[5]);
System.out.println(Array.getLength(new String[6]);

Set font-weight using Bootstrap classes

EDIT 2 (final) : According to the bootstrap 4 documentation, class="font-weight-bold" is what you are looking for.


EDIT : You can use class="font-weight-bold" as shown here (Bootstrap 4 alpha).

I kept the original answer below for clarity purposes.


I am posting this answer because this thread seems to have a lot of visitors, yet it had no proper solution to solve this issue. But there will be soon now a way with Bootstrap 4 :

As this GitHub pull request shows, you will just have to use the text-weight-normal, text-weight-bold and text-weight-italic classes.

This can maybe change until the official stable release. At this date of writing, this pull request is not merged yet in the alpha branch.

I will update this post once Bootstrap v4 has been released.

ORA-12516, TNS:listener could not find available handler

You opened a lot of connections and that's the issue. I think in your code, you did not close the opened connection.

A database bounce could temporarily solve, but will re-appear when you do consecutive execution. Also, it should be verified the number of concurrent connections to the database. If maximum DB processes parameter has been reached this is a common symptom.

Courtesy of this thread: https://community.oracle.com/thread/362226?tstart=-1

Unnamed/anonymous namespaces vs. static functions

From experience I'll just note that while it is the C++ way to put formerly-static functions into the anonymous namespace, older compilers can sometimes have problems with this. I currently work with a few compilers for our target platforms, and the more modern Linux compiler is fine with placing functions into the anonymous namespace.

But an older compiler running on Solaris, which we are wed to until an unspecified future release, will sometimes accept it, and other times flag it as an error. The error is not what worries me, it's what it might be doing when it accepts it. So until we go modern across the board, we are still using static (usually class-scoped) functions where we'd prefer the anonymous namespace.

Difference between Math.Floor() and Math.Truncate()

Math.Floor(): Returns the largest integer less than or equal to the specified double-precision floating-point number.

Math.Round(): Rounds a value to the nearest integer or to the specified number of fractional digits.

How to detect DataGridView CheckBox event change?

I found @Killercam's solution to work but was a bit dodgy if the user double clicked too fast. Not sure if other's found that the case either. I found a another solution here.

It uses the datagrid's CellValueChanged and CellMouseUp. Changhong explains that

"The reason for that is OnCellvalueChanged event won’t fire until the DataGridView thinks you have completed editing. This makes senses for a TextBox Column, as OnCellvalueChanged wouldn’t [bother] to fire for each key strike, but it doesn’t [make sense] for a CheckBox."

Here it is in action from his example:

private void myDataGrid_OnCellValueChanged(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == myCheckBoxColumn.Index && e.RowIndex != -1)
    {
        // Handle checkbox state change here
    }
}

And the code to tell the checkbox it is done editing when it is clicked, instead of waiting till the user leaves the field:

private void myDataGrid_OnCellMouseUp(object sender,DataGridViewCellMouseEventArgs e)
{
    // End of edition on each click on column of checkbox
    if (e.ColumnIndex == myCheckBoxColumn.Index && e.RowIndex != -1)
    {
        myDataGrid.EndEdit();
    }
}

Edit: A DoubleClick event is treated separate from a MouseUp event. If a DoubleClick event is detected, the application will ignore the first MouseUp event entirely. This logic needs to be added to the CellDoubleClick event in addition to the MouseUp event:

private void myDataGrid_OnCellDoubleClick(object sender,DataGridViewCellEventArgs e)
{
    // End of edition on each click on column of checkbox
    if (e.ColumnIndex == myCheckBoxColumn.Index && e.RowIndex != -1)
    {
        myDataGrid.EndEdit();
    }
}

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

It is just letting you know that the object you are printing is not a string, rather a byte object as a byte literal. People explain this in incomplete ways, so here is my take.

Consider creating a byte object by typing a byte literal (literally defining a byte object without actually using a byte object e.g. by typing b'') and converting it into a string object encoded in utf-8. (Note that converting here means decoding)

byte_object= b"test" # byte object by literally typing characters
print(byte_object) # Prints b'test'
print(byte_object.decode('utf8')) # Prints "test" without quotations

You see that we simply apply the .decode(utf8) function.

Bytes in Python

https://docs.python.org/3.3/library/stdtypes.html#bytes

String literals are described by the following lexical definitions:

https://docs.python.org/3.3/reference/lexical_analysis.html#string-and-bytes-literals

stringliteral   ::=  [stringprefix](shortstring | longstring)
stringprefix    ::=  "r" | "u" | "R" | "U"
shortstring     ::=  "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring      ::=  "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
shortstringitem ::=  shortstringchar | stringescapeseq
longstringitem  ::=  longstringchar | stringescapeseq
shortstringchar ::=  <any source character except "\" or newline or the quote>
longstringchar  ::=  <any source character except "\">
stringescapeseq ::=  "\" <any source character>

bytesliteral   ::=  bytesprefix(shortbytes | longbytes)
bytesprefix    ::=  "b" | "B" | "br" | "Br" | "bR" | "BR" | "rb" | "rB" | "Rb" | "RB"
shortbytes     ::=  "'" shortbytesitem* "'" | '"' shortbytesitem* '"'
longbytes      ::=  "'''" longbytesitem* "'''" | '"""' longbytesitem* '"""'
shortbytesitem ::=  shortbyteschar | bytesescapeseq
longbytesitem  ::=  longbyteschar | bytesescapeseq
shortbyteschar ::=  <any ASCII character except "\" or newline or the quote>
longbyteschar  ::=  <any ASCII character except "\">
bytesescapeseq ::=  "\" <any ASCII character>

show all tags in git log

Note about tag of tag (tagging a tag), which is at the origin of your issue, as Charles Bailey correctly pointed out in the comment:

Make sure you study this thread, as overriding a signed tag is not as easy:

  • if you already pushed a tag, the git tag man page seriously advised against a simple git tag -f B to replace a tag name "A"
  • don't try to recreate a signed tag with git tag -f (see the thread extract below)

    (it is about a corner case, but quite instructive about tags in general, and it comes from another SO contributor Jakub Narebski):

Please note that the name of tag (heavyweight tag, i.e. tag object) is stored in two places:

  • in the tag object itself as a contents of 'tag' header (you can see it in output of "git show <tag>" and also in output of "git cat-file -p <tag>", where <tag> is heavyweight tag, e.g. v1.6.3 in git.git repository),
  • and also is default name of tag reference (reference in "refs/tags/*" namespace) pointing to a tag object.
    Note that the tag reference (appropriate reference in the "refs/tags/*" namespace) is purely local matter; what one repository has in 'refs/tags/v0.1.3', other can have in 'refs/tags/sub/v0.1.3' for example.

So when you create signed tag 'A', you have the following situation (assuming that it points at some commit)

  35805ce   <--- 5b7b4ead  <=== refs/tags/A
  (commit)       tag A
                 (tag)

Please also note that "git tag -f A A" (notice the absence of options forcing it to be an annotated tag) is a noop - it doesn't change the situation.

If you do "git tag -f -s A A": note that you force owerwriting a tag (so git assumes that you know what you are doing), and that one of -s / -a / -m options is used to force annotated tag (creation of tag object), you will get the following situation

  35805ce   <--- 5b7b4ea  <--- ada8ddc  <=== refs/tags/A
  (commit)       tag A         tag A
                 (tag)         (tag)

Note also that "git show A" would show the whole chain down to the non-tag object...

How to view DLL functions?

You may try the Object Browser in Visual Studio.

Select Edit Custom Component Set. From there, you can choose from a variety of .NET, COM or project libraries or just import external dlls via Browse.

How do I add a placeholder on a CharField in Django?

For a ModelForm, you can use the Meta class thus:

from django import forms

from .models import MyModel

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'name': forms.TextInput(attrs={'placeholder': 'Name'}),
            'description': forms.Textarea(
                attrs={'placeholder': 'Enter description here'}),
        }

jQuery: go to URL with target="_blank"

The .ready function is used to insert the attribute once the page has finished loading.

$(document).ready(function() {
     $("class name or id a.your class name").attr({"target" : "_blank"})
})

How do I toggle an ng-show in AngularJS based on a boolean?

Basically I solved it by NOT-ing the isReplyFormOpen value whenever it is clicked:

<a ng-click="isReplyFormOpen = !isReplyFormOpen">Reply</a>

<div ng-init="isReplyFormOpen = false" ng-show="isReplyFormOpen" id="replyForm">
    <!-- Form -->
</div>

setting global sql_mode in mysql

Setting sql mode permanently using mysql config file.

In my case i have to change file /etc/mysql/mysql.conf.d/mysqld.cnf as mysql.conf.d is included in /etc/mysql/my.cnf. i change this under [mysqld]

[mysqld]
sql_mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

just removed ONLY_FULL_GROUP_BY sql mode cause it was causing issue.

I am using ubuntu 16.04, php 7 and mysql --version give me this mysql Ver 14.14 Distrib 5.7.13, for Linux (x86_64) using EditLine wrapper

After this change run below commands

sudo service mysql stop
sudo service mysql start

Now check sql modes by this query SELECT @@sql_mode and you should get modes that you have just set.

How can I query for null values in entity framework?

If you prefer using method (lambda) syntax as I do, you could do the same thing like this:

var result = new TableName();

using(var db = new EFObjectContext)
{
    var query = db.TableName;

    query = value1 == null 
        ? query.Where(tbl => tbl.entry1 == null) 
        : query.Where(tbl => tbl.entry1 == value1);

    query = value2 == null 
        ? query.Where(tbl => tbl.entry2 == null) 
        : query.Where(tbl => tbl.entry2 == value2);

    result = query
        .Select(tbl => tbl)
        .FirstOrDefault();

   // Inspect the value of the trace variable below to see the sql generated by EF
   var trace = ((ObjectQuery<REF_EQUIPMENT>) query).ToTraceString();

}

return result;

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

While Building a Project, if in the project properties it shows that it is build under Target.NET Framework 4.5, update it to 4.6 or 4.6.1. Then the build will be able to locate Entity Framework 6.0 in the Web.config file. This approach solved my problem. Selecting Target framework from Project Properties

How to run Visual Studio post-build events for debug build only

Pre- and Post-Build Events run as a batch script. You can do a conditional statement on $(ConfigurationName).

For instance

if $(ConfigurationName) == Debug xcopy something somewhere

Internet Explorer 11- issue with security certificate error prompt

If you updated Internet Explorer and began having technical problems, you can use the Compatibility View feature to emulate a previous version of Internet Explorer.

For instructions, see the section below that corresponds with your version. To find your version number, click Help > About Internet Explorer. Internet Explorer 11

To edit the Compatibility View list:

Open the desktop, and then tap or click the Internet Explorer icon on the taskbar.
Tap or click the Tools button (Image), and then tap or click Compatibility View settings.
To remove a website:
Click the website(s) where you would like to turn off Compatibility View, clicking Remove after each one.
To add a website:
Under Add this website, enter the website(s) where you would like to turn on Compatibility View, clicking Add after each one.

What port number does SOAP use?

SOAP (Simple Object Access Protocol) is the communication protocol in the web service scenario.

One benefit of SOAP is that it allowas RPC to execute through a firewall. But to pass through a firewall, you will probably want to use 80. it uses port no.8084 To the firewall, a SOAP conversation on 80 looks like a POST to a web page. However, there are extensions in SOAP which are specifically aimed at the firewall. In the future, it may be that firewalls will be configured to filter SOAP messages. But as of today, most firewalls are SOAP ignorant.

so exclusively open SOAP Port in Firewalls

How to convert a HTMLElement to a string

The element outerHTML property (note: supported by Firefox after version 11) returns the HTML of the entire element.

Example

<div id="new-element-1">Hello world.</div>

<script type="text/javascript"><!--

var element = document.getElementById("new-element-1");
var elementHtml = element.outerHTML;
// <div id="new-element-1">Hello world.</div>

--></script>

Similarly, you can use innerHTML to get the HTML contained within a given element, or innerText to get the text inside an element (sans HTML markup).

See Also

  1. outerHTML - Javascript Property
  2. Javascript Reference - Elements

How do I add files and folders into GitHub repos?

Check my answer here : https://stackoverflow.com/a/50039345/2647919

"OR, even better just the ol' "drag and drop" the folder, onto your repository opened in git browser.

Open your repository in the web portal , you will see the listing of all your files. If you have just recently created the repo, and initiated with a README, you will only see the README listing.

Open your folder which you want to upload. drag and drop on the listing in browser. See the image here."

Render HTML string as real HTML in a React component

I use innerHTML together a ref to span:

import React, { useRef, useEffect, useState } from 'react';

export default function Sample() {
  const spanRef = useRef<HTMLSpanElement>(null);
  const [someHTML,] = useState("some <b>bold</b>");

  useEffect(() => {
    if (spanRef.current) {
      spanRef.current.innerHTML = someHTML;
    }
  }, [spanRef.current, someHTML]);

  return <div>
    my custom text follows<br />
    <span ref={spanRef} />
  </div>
}

How to unstage large number of files without deleting the content

If you have a pristine repo (or HEAD isn't set)[1] you could simply

rm .git/index

Of course, this will require you to re-add the files that you did want to be added.


[1] Note (as explained in the comments) this would usually only happen when the repo is brand-new ("pristine") or if no commits have been made. More technically, whenever there is no checkout or work-tree.

Just making it more clear :)

Jquery each - Stop loop and return object

here :

http://jsbin.com/ucuqot/3/edit

function findXX(word)
{  
  $.each(someArray, function(i,n)
  {
    $('body').append('-> '+i+'<br />');
    if(n == word)
    {
      return false;
    }   
  });  
}

What's the difference between "git reset" and "git checkout"?

The two commands (reset and checkout) are completely different.

checkout X IS NOT reset --hard X

If X is a branch name, checkout X will change the current branch while reset --hard X will not.

How to get text and a variable in a messagebox

MsgBox("Variable {0} " , variable)

How can I get column names from a table in Oracle?

describe YOUR_TABLE;

In your case :

describe EVENT_LOG;

WAITING at sun.misc.Unsafe.park(Native Method)

unsafe.park is pretty much the same as thread.wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits. It's used a lot for thread pooling.

So, to answer your question, all the thread is doing is waiting for something, it's not really using any CPU. Considering that your original stack trace shows that you're using a lock I would assume a deadlock is going on in your case.

Yes I know you have almost certainly already solved this issue by now. However, you're one of the top results if someone googles sun.misc.unsafe.park. I figure answering the question may help others trying to understand what this method that seems to be using all their CPU is.

How to determine if a number is positive or negative?

I think there is a very simple solution:

public boolean isPositive(int|float|double|long i){
    return (((i-i)==0)? true : false);
}

tell me if I'm wrong!

How to use DbContext.Database.SqlQuery<TElement>(sql, params) with stored procedure? EF Code First CTP5

Also, you can use the "sql" parameter as a format specifier:

context.Database.SqlQuery<MyEntityType>("mySpName @param1 = {0}", param1)

Sum values from an array of key-value pairs in JavaScript

Try the following

_x000D_
_x000D_
var myData = [['2013-01-22', 0], ['2013-01-29', 1], ['2013-02-05', 21]];_x000D_
_x000D_
var myTotal = 0;  // Variable to hold your total_x000D_
_x000D_
for(var i = 0, len = myData.length; i < len; i++) {_x000D_
    myTotal += myData[i][1];  // Iterate over your first array and then grab the second element add the values up_x000D_
}_x000D_
_x000D_
document.write(myTotal); // 22 in this instance
_x000D_
_x000D_
_x000D_

Disable vertical sync for glxgears

Putting the other answers all together, here's a command line that will work:

env vblank_mode=0 __GL_SYNC_TO_VBLANK=0 glxgears

This has the advantages of working for both Mesa and NVidia drivers, and not requiring any changes to configuration files.

How do you test running time of VBA code?

We've used a solution based on timeGetTime in winmm.dll for millisecond accuracy for many years. See http://www.aboutvb.de/kom/artikel/komstopwatch.htm

The article is in German, but the code in the download (a VBA class wrapping the dll function call) is simple enough to use and understand without being able to read the article.

How to replace all strings to numbers contained in each string in Notepad++?

psxls gave a great answer but I think my Notepad++ version is slightly different so the $ (dollar sign) capturing did not work.

I have Notepad++ v.5.9.3 and here's how you can accomplish your task:

Search for the pattern: value=\"([0-9]*)\" And replace with: \1 (whatever you want to do around that capturing group)

Ex. Surround with square brackets

[\1] --> will produce value="[4]"

How to add and remove classes in Javascript without jQuery

Updated JS Class Method

The add methods do not add duplicate classes and the remove method only removes class with exact string match.

const addClass = (selector, classList) => {
  const element = document.querySelector(selector);
  const classes = classList.split(' ')
  classes.forEach((item, id) => {
    element.classList.add(item)
  })
}

const removeClass = (selector, classList) => {
  const element = document.querySelector(selector);
  const classes = classList.split(' ')
  classes.forEach((item, id) => {
    element.classList.remove(item)
  })
}

addClass('button.submit', 'text-white color-blue') // add text-white and color-blue classes
removeClass('#home .paragraph', 'text-red bold') // removes text-red and bold classes

SVN check out linux

You can use checkout or co

$ svn co http://example.com/svn/app-name directory-name

Some short codes:-

  1. checkout (co)
  2. commit (ci)
  3. copy (cp)
  4. delete (del, remove,rm)
  5. diff (di)

SQL statement to select all rows from previous day

It's seems the obvious answer was missing. To get all data from a table (Ttable) where the column (DatetimeColumn) is a datetime with a timestamp the following query can be used:

SELECT * FROM Ttable
WHERE DATEDIFF(day,Ttable.DatetimeColumn ,GETDATE()) = 1 -- yesterday

This can easily be changed to today, last month, last year, etc.

How do I compute the intersection point of two lines?

Can't stand aside,

So we have linear system:

A1 * x + B1 * y = C1
A2 * x + B2 * y = C2

let's do it with Cramer's rule, so solution can be found in determinants:

x = Dx/D
y = Dy/D

where D is main determinant of the system:

A1 B1
A2 B2

and Dx and Dy can be found from matricies:

C1 B1
C2 B2

and

A1 C1
A2 C2

(notice, as C column consequently substitues the coef. columns of x and y)

So now the python, for clarity for us, to not mess things up let's do mapping between math and python. We will use array L for storing our coefs A, B, C of the line equations and intestead of pretty x, y we'll have [0], [1], but anyway. Thus, what I wrote above will have the following form further in the code:

for D

L1[0] L1[1]
L2[0] L2[1]

for Dx

L1[2] L1[1]
L2[2] L2[1]

for Dy

L1[0] L1[2]
L2[0] L2[2]

Now go for coding:

line - produces coefs A, B, C of line equation by two points provided,
intersection - finds intersection point (if any) of two lines provided by coefs.

from __future__ import division 

def line(p1, p2):
    A = (p1[1] - p2[1])
    B = (p2[0] - p1[0])
    C = (p1[0]*p2[1] - p2[0]*p1[1])
    return A, B, -C

def intersection(L1, L2):
    D  = L1[0] * L2[1] - L1[1] * L2[0]
    Dx = L1[2] * L2[1] - L1[1] * L2[2]
    Dy = L1[0] * L2[2] - L1[2] * L2[0]
    if D != 0:
        x = Dx / D
        y = Dy / D
        return x,y
    else:
        return False

Usage example:

L1 = line([0,1], [2,3])
L2 = line([2,3], [0,4])

R = intersection(L1, L2)
if R:
    print "Intersection detected:", R
else:
    print "No single intersection point detected"

Sequence contains more than one element

FYI you can also get this error if EF Migrations tries to run with no Db configured, for example in a Test Project.

Chased this for hours before I figured out that it was erroring on a query, but, not because of the query but because it was when Migrations kicked in to try to create the Db.

Link a photo with the cell in excel

Select both the column you are sorting, and the column that the picture is in (I am assuming the picture is small compared to the cell, i.e. it is "in" the cell). Make sure that the object positioning property is set as "move but don't size with cells". Now if you do a sort, the pictures will move with the list being sorted.

Note - you must include the column with the picture in your range when you sort, and the picture must fit inside the cell.

The following VBA snippet will make sure all pictures in your spreadsheet have their "move and size" property set:

Sub moveAndSize()
Dim s As Shape
For Each s In ActiveSheet.Shapes
  If s.Type = msoPicture Or s.Type = msoLinkedPicture Or s.Type = msoPlaceholder Then
    s.Placement = xlMove
  End If
Next
End Sub

If you want to make sure the picture continues to fit after you move it, you can use xlMoveAndSize instead of xlMove.

Collision resolution in Java HashMap

It could have formed a linked list, indeed. It's just that Map contract requires it to replace the entry:

V put(K key, V value)

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)

http://docs.oracle.com/javase/6/docs/api/java/util/Map.html

For a map to store lists of values, it'd need to be a Multimap. Here's Google's: http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html

A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.

Edit: Collision resolution

That's a bit different. A collision happens when two different keys happen to have the same hash code, or two keys with different hash codes happen to map into the same bucket in the underlying array.

Consider HashMap's source (bits and pieces removed):

public V put(K key, V value) {
    int hash = hash(key.hashCode());
    int i = indexFor(hash, table.length);
    // i is the index where we want to insert the new element
    addEntry(hash, key, value, i);
    return null;
}

void addEntry(int hash, K key, V value, int bucketIndex) {
    // take the entry that's already in that bucket
    Entry<K,V> e = table[bucketIndex];
    // and create a new one that points to the old one = linked list
    table[bucketIndex] = new Entry<>(hash, key, value, e);
}

For those who are curious how the Entry class in HashMap comes to behave like a list, it turns out that HashMap defines its own static Entry class which implements Map.Entry. You can see for yourself by viewing the source code:

GrepCode for HashMap

Cursor adapter and sqlite example

In Android, How to use a Cursor with a raw query in sqlite:

Cursor c = sampleDB.rawQuery("SELECT FirstName, Age FROM mytable " +
           "where Age > 10 LIMIT 5", null);

if (c != null ) {
    if  (c.moveToFirst()) {
        do {
            String firstName = c.getString(c.getColumnIndex("FirstName"));
            int age = c.getInt(c.getColumnIndex("Age"));
            results.add("" + firstName + ",Age: " + age);
        }while (c.moveToNext());
    }
}
c.close();

Show compose SMS view in Android

You can use this to send sms to any number:

 public void sendsms(View view) {
        String phoneNumber = "+880xxxxxxxxxx";
        String message = "Welcome to sms";
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("sms:" + phoneNumber));
        intent.putExtra("sms_body", message);
        startActivity(intent);
    }

Load dimension value from res/values/dimension.xml from source code

The Resource class also has a method getDimensionPixelSize() which I think will fit your needs.

Java Best Practices to Prevent Cross Site Scripting

My preference is to encode all non-alphaumeric characters as HTML numeric character entities. Since almost, if not all attacks require non-alphuneric characters (like <, ", etc) this should eliminate a large chunk of dangerous output.

Format is &#N;, where N is the numeric value of the character (you can just cast the character to an int and concatenate with a string to get a decimal value). For example:

// java-ish pseudocode
StringBuffer safestrbuf = new StringBuffer(string.length()*4);
foreach(char c : string.split() ){  
  if( Character.isAlphaNumeric(c) ) safestrbuf.append(c);
  else safestrbuf.append(""+(int)symbol);

You will also need to be sure that you are encoding immediately before outputting to the browser, to avoid double-encoding, or encoding for HTML but sending to a different location.

Java - Find shortest path between 2 points in a distance weighted map

Estimated sanjan:

The idea behind Dijkstra's Algorithm is to explore all the nodes of the graph in an ordered way. The algorithm stores a priority queue where the nodes are ordered according to the cost from the start, and in each iteration of the algorithm the following operations are performed:

  1. Extract from the queue the node with the lowest cost from the start, N
  2. Obtain its neighbors (N') and their associated cost, which is cost(N) + cost(N, N')
  3. Insert in queue the neighbor nodes N', with the priority given by their cost

It's true that the algorithm calculates the cost of the path between the start (A in your case) and all the rest of the nodes, but you can stop the exploration of the algorithm when it reaches the goal (Z in your example). At this point you know the cost between A and Z, and the path connecting them.

I recommend you to use a library which implements this algorithm instead of coding your own. In Java, you might take a look to the Hipster library, which has a very friendly way to generate the graph and start using the search algorithms.

Here you have an example of how to define the graph and start using Dijstra with Hipster.

// Create a simple weighted directed graph with Hipster where
// vertices are Strings and edge values are just doubles
HipsterDirectedGraph<String,Double> graph = GraphBuilder.create()
  .connect("A").to("B").withEdge(4d)
  .connect("A").to("C").withEdge(2d)
  .connect("B").to("C").withEdge(5d)
  .connect("B").to("D").withEdge(10d)
  .connect("C").to("E").withEdge(3d)
  .connect("D").to("F").withEdge(11d)
  .connect("E").to("D").withEdge(4d)
  .buildDirectedGraph();

// Create the search problem. For graph problems, just use
// the GraphSearchProblem util class to generate the problem with ease.
SearchProblem p = GraphSearchProblem
  .startingFrom("A")
  .in(graph)
  .takeCostsFromEdges()
  .build();

// Search the shortest path from "A" to "F"
System.out.println(Hipster.createDijkstra(p).search("F"));

You only have to substitute the definition of the graph for your own, and then instantiate the algorithm as in the example.

I hope this helps!

Understanding Bootstrap's clearfix class

The :before pseudo element isn't needed for the clearfix hack itself.

It's just an additional nice feature helping to prevent margin-collapsing of the first child element. Thus the top margin of an child block element of the "clearfixed" element is guaranteed to be positioned below the top border of the clearfixed element.

display:table is being used because display:block doesn't do the trick. Using display:block margins will collapse even with a :before element.

There is one caveat: if vertical-align:baseline is used in table cells with clearfixed <div> elements, Firefox won't align well. Then you might prefer using display:block despite loosing the anti-collapsing feature. In case of further interest read this article: Clearfix interfering with vertical-align.

How can I deploy an iPhone application from Xcode to a real iPhone device?

No, its easy to do this. In Xcode, set the Active Configuration to Release. Change the device from Simulator to Device - whatever SDK. If you want to directly export to your iPhone, connect it to your computer. Press Build and Go. If your iPhone is not connected to your computer, a message will come up saying that your iPhone is not connected.

If this applies to you: (iPhone was not connected)

Go to your projects folder and then to the build folder inside. Go to the Release-iphoneos folder and take the app inside, drag and drop on iTunes icon. When you sync your iTouch device, it will copy it to your device. It will also show up in iTunes as a application for the iPhone.

Hope this helps!

P.S.: If it says something about a certificate not being valid, just click on the project in Xcode, the little project icon in the file stack to the left, and press Apple+I, or do Get Info from the menu bar. Click on Build at the top. Under Code Signing, change Code Signing Identity - Any iPhone OS Device to be Don't Sign.

How do I convert hh:mm:ss.000 to milliseconds in Excel?

try this:

=(RIGHT(E9;3))+(MID(E9;7;2)*1000)+(MID(E9;5;2)*3600000)+(LEFT(E9;2)*216000000)

Maybe you need to change semi-colon by coma...

How to output git log with the first line only?

You can define a global alias so you can invoke a short log in a more comfortable way:

git config --global alias.slog "log --pretty=oneline --abbrev-commit"

Then you can call it using git slog (it even works with autocompletion if you have it enabled).

How to continue the code on the next line in VBA

(i, j, n + 1) = k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
(k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

From ms support

To continue a statement from one line to the next, type a space followed by the line-continuation character [the underscore character on your keyboard (_)].

You can break a line at an operator, list separator, or period.

Java reverse an int value without using array

If the idea is not to use arrays or string, reversing an integer has to be done by reading the digits of a number from the end one at a time. Below explanation is provided in detail to help the novice.

pseudocode :

  1. lets start with reversed_number = 0 and some value for original_number which needs to be reversed.
  2. the_last_digit = original_number % 10 (i.e, the reminder after dividing by 10)
  3. original_number = original_number/10 (since we already have the last digit, remove the last digit from the original_number)
  4. reversed_number = reversed_number * 10 + last_digit (multiply the reversed_number with 10, so as to add the last_digit to it)
  5. repeat steps 2 to 4, till the original_number becomes 0. When original_number = 0, reversed_number would have the reverse of the original_number.

More info on step 4: If you are provided with a digit at a time, and asked to append it at the end of a number, how would you do it - by moving the original number one place to the left so as to accommodate the new digit. If number 23 has to become 234, you multiply 23 with 10 and then add 4.

234 = 23x10 + 4;

Code:

public static int reverseInt(int original_number) {
        int reversed_number = 0;
        while (original_number > 0) {
            int last_digit = original_number % 10;
            original_number = original_number / 10;
            reversed_number = reversed_number * 10 + last_digit;    
        }
        return reversed_number;
    }

Using for loop inside of a JSP

You concrete problem is caused because you're mixing discouraged and old school scriptlets <% %> with its successor EL ${}. They do not share the same variable scope. The allFestivals is not available in scriptlet scope and the i is not available in EL scope.

You should install JSTL (<-- click the link for instructions) and declare it in top of JSP as follows:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

and then iterate over the list as follows:

<c:forEach items="${allFestivals}" var="festival">
    <tr>      
        <td>${festival.festivalName}</td>
        <td>${festival.location}</td>
        <td>${festival.startDate}</td>
        <td>${festival.endDate}</td>
        <td>${festival.URL}</td>  
    </tr>
</c:forEach>

(beware of possible XSS attack holes, use <c:out> accordingly)

Don't forget to remove the <jsp:useBean> as it has no utter value here when you're using a servlet as model-and-view controller. It would only lead to confusion. See also our servlets wiki page. Further you would do yourself a favour to disable scriptlets by the following entry in web.xml so that you won't accidently use them:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
</jsp-config>

Execute Shell Script after post build in Jenkins

You can also run arbitrary commands using the Groovy Post Build - and that will give you a lot of control over when they run and so forth. We use that to run a 'finger of blame' shell script in the case of failed or unstable builds.

if (manager.build.result.isWorseThan(hudson.model.Result.SUCCESS)) {
  item = hudson.model.Hudson.instance.getItem("PROJECTNAMEHERE")
  lastStableBuild = item.getLastStableBuild()
  lastStableDate = lastStableBuild.getTime()
  formattedLastStableDate = lastStableDate.format("MM/dd/yyyy h:mm:ss a")
  now = new Date()
  formattedNow = now.format("MM/dd/yyyy h:mm:ss a")
  command = ['/appframe/jenkins/appframework/fob.ksh', "${formattedLastStableDate}", "${formattedNow}"]
  manager.listener.logger.println "FOB Command: ${command}"
  manager.listener.logger.println command.execute().text
}

(Our command takes the last stable build date and the current time as parameters so it can go investigate who might have broken the build, but you could run whatever commands you like in a similar fashion)

How to center a window on the screen in Tkinter?

Use:

import tkinter as tk

if __name__ == '__main__':
    root = tk.Tk()
    root.title('Centered!')

    w = 800
    h = 650

    ws = root.winfo_screenwidth()
    hs = root.winfo_screenheight()
    x = (ws/2) - (w/2)
    y = (hs/2) - (h/2)

    root.geometry('%dx%d+%d+%d' % (w, h, x, y))

    root.mainloop()

Set default value of javascript object attributes

Since I asked the question several years ago things have progressed nicely.

Proxies are part of ES6. The following example works in Chrome, Firefox, Safari and Edge:

var handler = {
  get: function(target, name) {
    return target.hasOwnProperty(name) ? target[name] : 42;
  }
};

var p = new Proxy({}, handler);

p.answerToTheUltimateQuestionOfLife; //=> 42

Read more in Mozilla's documentation on Proxies.

How to find out which processes are using swap space in Linux?

I did notice this thread is rather old, but if you happen to stumble upon it, as I just did, another answer is: use smem.

Here is a link which tells you both how to install it and how to use it:

http://www.cyberciti.biz/faq/linux-which-process-is-using-swap/

Making a WinForms TextBox behave like your browser's address bar

This is working for me in .NET 2005 -

    ' * if the mouse button is down, do not run the select all.
    If MouseButtons = Windows.Forms.MouseButtons.Left Then
        Exit Sub
    End If

 ' * OTHERWISE INVOKE THE SELECT ALL AS DISCUSSED.

What is object slicing?

OK, I'll give it a try after reading many posts explaining object slicing but not how it becomes problematic.

The vicious scenario that can result in memory corruption is the following:

  • Class provides (accidentally, possibly compiler-generated) assignment on a polymorphic base class.
  • Client copies and slices an instance of a derived class.
  • Client calls a virtual member function that accesses the sliced-off state.

Regex remove all special characters except numbers?

This should work as well

text = 'the car? was big and* red!'

newtext = re.sub( '[^a-z0-9]', ' ', text)

print(newtext)

the car was big and red

Run a controller function whenever a view is opened/shown

I faced at the same problem, and here i leave the reason of this behavior for everyone else with the same issue.

View LifeCycle

In order to improve performance, we've improved Ionic's ability to cache view elements and scope data. Once a controller is initialized, it may persist throughout the app’s life; it’s just hidden and removed from the watch cycle. Since we aren’t rebuilding scope, we’ve added events for which we should listen when entering the watch cycle again.

To see full description and $ionicView events go to: http://ionicframework.com/blog/navigating-the-changes/

Difference between h:button and h:commandButton

h:commandButton must be enclosed in a h:form and has the two ways of navigation i.e. static by setting the action attribute and dynamic by setting the actionListener attribute hence it is more advanced as follows:

<h:form>
    <h:commandButton action="page.xhtml" value="cmdButton"/>
</h:form>

this code generates the follwing html:

<form id="j_idt7" name="j_idt7" method="post" action="/jsf/faces/index.xhtml" enctype="application/x-www-form-urlencoded">

whereas the h:button is simpler and just used for static or rule based navigation as follows

<h:button outcome="page.xhtml" value="button"/>

the generated html is

 <title>Facelet Title</title></head><body><input type="button" onclick="window.location.href='/jsf/faces/page.xhtml'; return false;" value="button" />

Changing text of UIButton programmatically swift

Swift 3

let button: UIButton = UIButton()
button.frame = CGRect.init(x: view.frame.width/2, y: view.frame.height/2, width: 100, height: 100)
button.setTitle(“Title Button”, for: .normal)

Javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: Failure in SSL library, usually a protocol error

Also you should know that you can force TLS v1.2 for Android 4.0 devices that don't have it enabled by default:

Put this code in onCreate() of your Application file:

try {
        ProviderInstaller.installIfNeeded(getApplicationContext());
        SSLContext sslContext;
        sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(null, null, null);
        sslContext.createSSLEngine();
    } catch (GooglePlayServicesRepairableException | GooglePlayServicesNotAvailableException
            | NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }

Check if a value exists in ArrayList

Please refer to my answer on this post.

There is no need to iterate over the List just overwrite the equals method.

Use equals instead of ==

@Override
public boolean equals (Object object) {
    boolean result = false;
    if (object == null || object.getClass() != getClass()) {
        result = false;
    } else {
        EmployeeModel employee = (EmployeeModel) object;
        if (this.name.equals(employee.getName()) && this.designation.equals(employee.getDesignation())   && this.age == employee.getAge()) {
            result = true;
        }
    }
    return result;
}

Call it like this:

public static void main(String args[]) {

    EmployeeModel first = new EmployeeModel("Sameer", "Developer", 25);
    EmployeeModel second = new EmployeeModel("Jon", "Manager", 30);
    EmployeeModel third = new EmployeeModel("Priyanka", "Tester", 24);

    List<EmployeeModel> employeeList = new ArrayList<EmployeeModel>();
    employeeList.add(first);
    employeeList.add(second);
    employeeList.add(third);

    EmployeeModel checkUserOne = new EmployeeModel("Sameer", "Developer", 25);
    System.out.println("Check checkUserOne is in list or not");
    System.out.println("Is checkUserOne Preasent = ? " + employeeList.contains(checkUserOne));

    EmployeeModel checkUserTwo = new EmployeeModel("Tim", "Tester", 24);
    System.out.println("Check checkUserTwo is in list or not");
    System.out.println("Is checkUserTwo Preasent = ? " + employeeList.contains(checkUserTwo));

}

Detecting when a div's height changes using jQuery

You can make a simple setInterval.

_x000D_
_x000D_
function someJsClass()_x000D_
{_x000D_
  var _resizeInterval = null;_x000D_
  var _lastHeight = 0;_x000D_
  var _lastWidth = 0;_x000D_
  _x000D_
  this.Initialize = function(){_x000D_
    var _resizeInterval = setInterval(_resizeIntervalTick, 200);_x000D_
  };_x000D_
  _x000D_
  this.Stop = function(){_x000D_
    if(_resizeInterval != null)_x000D_
      clearInterval(_resizeInterval);_x000D_
  };_x000D_
  _x000D_
  var _resizeIntervalTick = function () {_x000D_
    if ($(yourDiv).width() != _lastWidth || $(yourDiv).height() != _lastHeight) {_x000D_
      _lastWidth = $(contentBox).width();_x000D_
      _lastHeight = $(contentBox).height();_x000D_
      DoWhatYouWantWhenTheSizeChange();_x000D_
    }_x000D_
  };_x000D_
}_x000D_
_x000D_
var class = new someJsClass();_x000D_
class.Initialize();
_x000D_
_x000D_
_x000D_

EDIT:

This is a example with a class. But you can do something easiest.

Adobe Reader Command Line Reference

Call this after the print job has returned:

oShell.AppActivate "Adobe Reader"
oShell.SendKeys "%FX"

Most efficient way to map function over numpy array

TL;DR

As noted by @user2357112, a "direct" method of applying the function is always the fastest and simplest way to map a function over Numpy arrays:

import numpy as np
x = np.array([1, 2, 3, 4, 5])
f = lambda x: x ** 2
squares = f(x)

Generally avoid np.vectorize, as it does not perform well, and has (or had) a number of issues. If you are handling other data types, you may want to investigate the other methods shown below.

Comparison of methods

Here are some simple tests to compare three methods to map a function, this example using with Python 3.6 and NumPy 1.15.4. First, the set-up functions for testing:

import timeit
import numpy as np

f = lambda x: x ** 2
vf = np.vectorize(f)

def test_array(x, n):
    t = timeit.timeit(
        'np.array([f(xi) for xi in x])',
        'from __main__ import np, x, f', number=n)
    print('array: {0:.3f}'.format(t))

def test_fromiter(x, n):
    t = timeit.timeit(
        'np.fromiter((f(xi) for xi in x), x.dtype, count=len(x))',
        'from __main__ import np, x, f', number=n)
    print('fromiter: {0:.3f}'.format(t))

def test_direct(x, n):
    t = timeit.timeit(
        'f(x)',
        'from __main__ import x, f', number=n)
    print('direct: {0:.3f}'.format(t))

def test_vectorized(x, n):
    t = timeit.timeit(
        'vf(x)',
        'from __main__ import x, vf', number=n)
    print('vectorized: {0:.3f}'.format(t))

Testing with five elements (sorted from fastest to slowest):

x = np.array([1, 2, 3, 4, 5])
n = 100000
test_direct(x, n)      # 0.265
test_fromiter(x, n)    # 0.479
test_array(x, n)       # 0.865
test_vectorized(x, n)  # 2.906

With 100s of elements:

x = np.arange(100)
n = 10000
test_direct(x, n)      # 0.030
test_array(x, n)       # 0.501
test_vectorized(x, n)  # 0.670
test_fromiter(x, n)    # 0.883

And with 1000s of array elements or more:

x = np.arange(1000)
n = 1000
test_direct(x, n)      # 0.007
test_fromiter(x, n)    # 0.479
test_array(x, n)       # 0.516
test_vectorized(x, n)  # 0.945

Different versions of Python/NumPy and compiler optimization will have different results, so do a similar test for your environment.

Check if a string is null or empty in XSLT

What about?

test="not(normalize-space(categoryName)='')"

How can you find the height of text on an HTML canvas?

Here is a simple function. No library needed.

I wrote this function to get the top and bottom bounds relative to baseline. If textBaseline is set to alphabetic. What it does is it creates another canvas, and then draws there, and then finds the top most and bottom most non blank pixel. And that is the top and bottom bounds. It returns it as relative, so if height is 20px, and there is nothing below the baseline, then the top bound is -20.

You must supply characters to it. Otherwise it will give you 0 height and 0 width, obviously.

Usage:

alert(measureHeight('40px serif', 40, 'rg').height)

Here is the function:

function measureHeight(aFont, aSize, aChars, aOptions={}) {
    // if you do pass aOptions.ctx, keep in mind that the ctx properties will be changed and not set back. so you should have a devoted canvas for this
    // if you dont pass in a width to aOptions, it will return it to you in the return object
    // the returned width is Math.ceil'ed
    console.error('aChars: "' + aChars + '"');
    var defaultOptions = {
        width: undefined, // if you specify a width then i wont have to use measureText to get the width
        canAndCtx: undefined, // set it to object {can:,ctx:} // if not provided, i will make one
        range: 3
    };

    aOptions.range = aOptions.range || 3; // multiples the aSize by this much

    if (aChars === '') {
        // no characters, so obviously everything is 0
        return {
            relativeBot: 0,
            relativeTop: 0,
            height: 0,
            width: 0
        };
        // otherwise i will get IndexSizeError: Index or size is negative or greater than the allowed amount error somewhere below
    }

    // validateOptionsObj(aOptions, defaultOptions); // not needed because all defaults are undefined

    var can;
    var ctx; 
    if (!aOptions.canAndCtx) {
        can = document.createElement('canvas');;
        can.mozOpaque = 'true'; // improved performanceo on firefox i guess
        ctx = can.getContext('2d');

        // can.style.position = 'absolute';
        // can.style.zIndex = 10000;
        // can.style.left = 0;
        // can.style.top = 0;
        // document.body.appendChild(can);
    } else {
        can = aOptions.canAndCtx.can;
        ctx = aOptions.canAndCtx.ctx;
    }

    var w = aOptions.width;
    if (!w) {
        ctx.textBaseline = 'alphabetic';
        ctx.textAlign = 'left'; 
        ctx.font = aFont;
        w = ctx.measureText(aChars).width;
    }

    w = Math.ceil(w); // needed as i use w in the calc for the loop, it needs to be a whole number

    // must set width/height, as it wont paint outside of the bounds
    can.width = w;
    can.height = aSize * aOptions.range;

    ctx.font = aFont; // need to set the .font again, because after changing width/height it makes it forget for some reason
    ctx.textBaseline = 'alphabetic';
    ctx.textAlign = 'left'; 

    ctx.fillStyle = 'white';

    console.log('w:', w);

    var avgOfRange = (aOptions.range + 1) / 2;
    var yBaseline = Math.ceil(aSize * avgOfRange);
    console.log('yBaseline:', yBaseline);

    ctx.fillText(aChars, 0, yBaseline);

    var yEnd = aSize * aOptions.range;

    var data = ctx.getImageData(0, 0, w, yEnd).data;
    // console.log('data:', data)

    var botBound = -1;
    var topBound = -1;

    // measureHeightY:
    for (y=0; y<=yEnd; y++) {
        for (var x = 0; x < w; x += 1) {
            var n = 4 * (w * y + x);
            var r = data[n];
            var g = data[n + 1];
            var b = data[n + 2];
            // var a = data[n + 3];

            if (r+g+b > 0) { // non black px found
                if (topBound == -1) { 
                    topBound = y;
                }
                botBound = y; // break measureHeightY; // dont break measureHeightY ever, keep going, we till yEnd. so we get proper height for strings like "`." or ":" or "!"
                break;
            }
        }
    }

    return {
        relativeBot: botBound - yBaseline, // relative to baseline of 0 // bottom most row having non-black
        relativeTop: topBound - yBaseline, // relative to baseline of 0 // top most row having non-black
        height: (botBound - topBound) + 1,
        width: w// EDIT: comma has been added to fix old broken code.
    };
}

relativeBot, relativeTop, and height are the useful things in the return object.

Here is example usage:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Page Title</title>_x000D_
<script>_x000D_
function measureHeight(aFont, aSize, aChars, aOptions={}) {_x000D_
 // if you do pass aOptions.ctx, keep in mind that the ctx properties will be changed and not set back. so you should have a devoted canvas for this_x000D_
 // if you dont pass in a width to aOptions, it will return it to you in the return object_x000D_
 // the returned width is Math.ceil'ed_x000D_
 console.error('aChars: "' + aChars + '"');_x000D_
 var defaultOptions = {_x000D_
  width: undefined, // if you specify a width then i wont have to use measureText to get the width_x000D_
  canAndCtx: undefined, // set it to object {can:,ctx:} // if not provided, i will make one_x000D_
  range: 3_x000D_
 };_x000D_
 _x000D_
 aOptions.range = aOptions.range || 3; // multiples the aSize by this much_x000D_
 _x000D_
 if (aChars === '') {_x000D_
  // no characters, so obviously everything is 0_x000D_
  return {_x000D_
   relativeBot: 0,_x000D_
   relativeTop: 0,_x000D_
   height: 0,_x000D_
   width: 0_x000D_
  };_x000D_
  // otherwise i will get IndexSizeError: Index or size is negative or greater than the allowed amount error somewhere below_x000D_
 }_x000D_
 _x000D_
 // validateOptionsObj(aOptions, defaultOptions); // not needed because all defaults are undefined_x000D_
 _x000D_
 var can;_x000D_
 var ctx; _x000D_
 if (!aOptions.canAndCtx) {_x000D_
  can = document.createElement('canvas');;_x000D_
  can.mozOpaque = 'true'; // improved performanceo on firefox i guess_x000D_
  ctx = can.getContext('2d');_x000D_
  _x000D_
  // can.style.position = 'absolute';_x000D_
  // can.style.zIndex = 10000;_x000D_
  // can.style.left = 0;_x000D_
  // can.style.top = 0;_x000D_
  // document.body.appendChild(can);_x000D_
 } else {_x000D_
  can = aOptions.canAndCtx.can;_x000D_
  ctx = aOptions.canAndCtx.ctx;_x000D_
 }_x000D_
 _x000D_
 var w = aOptions.width;_x000D_
 if (!w) {_x000D_
  ctx.textBaseline = 'alphabetic';_x000D_
  ctx.textAlign = 'left'; _x000D_
  ctx.font = aFont;_x000D_
  w = ctx.measureText(aChars).width;_x000D_
 }_x000D_
 _x000D_
 w = Math.ceil(w); // needed as i use w in the calc for the loop, it needs to be a whole number_x000D_
 _x000D_
 // must set width/height, as it wont paint outside of the bounds_x000D_
 can.width = w;_x000D_
 can.height = aSize * aOptions.range;_x000D_
 _x000D_
 ctx.font = aFont; // need to set the .font again, because after changing width/height it makes it forget for some reason_x000D_
 ctx.textBaseline = 'alphabetic';_x000D_
 ctx.textAlign = 'left'; _x000D_
 _x000D_
 ctx.fillStyle = 'white';_x000D_
 _x000D_
 console.log('w:', w);_x000D_
 _x000D_
 var avgOfRange = (aOptions.range + 1) / 2;_x000D_
 var yBaseline = Math.ceil(aSize * avgOfRange);_x000D_
 console.log('yBaseline:', yBaseline);_x000D_
 _x000D_
 ctx.fillText(aChars, 0, yBaseline);_x000D_
 _x000D_
 var yEnd = aSize * aOptions.range;_x000D_
 _x000D_
 var data = ctx.getImageData(0, 0, w, yEnd).data;_x000D_
 // console.log('data:', data)_x000D_
 _x000D_
 var botBound = -1;_x000D_
 var topBound = -1;_x000D_
 _x000D_
 // measureHeightY:_x000D_
 for (y=0; y<=yEnd; y++) {_x000D_
  for (var x = 0; x < w; x += 1) {_x000D_
   var n = 4 * (w * y + x);_x000D_
   var r = data[n];_x000D_
   var g = data[n + 1];_x000D_
   var b = data[n + 2];_x000D_
   // var a = data[n + 3];_x000D_
   _x000D_
   if (r+g+b > 0) { // non black px found_x000D_
    if (topBound == -1) { _x000D_
     topBound = y;_x000D_
    }_x000D_
    botBound = y; // break measureHeightY; // dont break measureHeightY ever, keep going, we till yEnd. so we get proper height for strings like "`." or ":" or "!"_x000D_
    break;_x000D_
   }_x000D_
  }_x000D_
 }_x000D_
 _x000D_
 return {_x000D_
  relativeBot: botBound - yBaseline, // relative to baseline of 0 // bottom most row having non-black_x000D_
  relativeTop: topBound - yBaseline, // relative to baseline of 0 // top most row having non-black_x000D_
  height: (botBound - topBound) + 1,_x000D_
  width: w_x000D_
 };_x000D_
}_x000D_
_x000D_
</script>_x000D_
</head>_x000D_
<body style="background-color:steelblue;">_x000D_
<input type="button" value="reuse can" onClick="alert(measureHeight('40px serif', 40, 'rg', {canAndCtx:{can:document.getElementById('can'), ctx:document.getElementById('can').getContext('2d')}}).height)">_x000D_
<input type="button" value="dont reuse can" onClick="alert(measureHeight('40px serif', 40, 'rg').height)">_x000D_
<canvas id="can"></canvas>_x000D_
<h1>This is a Heading</h1>_x000D_
<p>This is a paragraph.</p>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The relativeBot and relativeTop are what you see in this image here:

https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial/Drawing_text

Git merge without auto commit

When there is one commit only in the branch, I usually do

git merge branch_name --ff

Error in plot.new() : figure margins too large, Scatter plot

Just a side-note. Sometimes this "margin" error occurs because you want to save a high-resolution figure (eg. dpi = 300 or res = 300) in R.
In this case, what you need to do is to specify the width and height. (Btw, ggsave() doesn't require this.)

This causes the margin error:

# eg. for tiff()
par(mar=c(1,1,1,1))
tiff(filename =  "qq.tiff",
     res = 300,                                                 # the margin error.
     compression = c( "lzw") )
# qq plot for genome wide association study (just an example)
qqman::qq(df$rawp, main = "Q-Q plot of GWAS p-values", cex = .3)
dev.off()

This will fix the margin error:

# eg. for tiff()
par(mar=c(1,1,1,1))
tiff(filename =  "qq.tiff",
     res = 300,                                                 # the margin error.
     width = 5, height = 4, units = 'in',                       # fixed
     compression = c( "lzw") )
# qq plot for genome wide association study (just an example)
qqman::qq(df$rawp, main = "Q-Q plot of GWAS p-values", cex = .3)
dev.off()

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

Try this:

<div id="wrapper">
    <div class="float left">left</div>
    <div class="float right">right</div>
</div>

#wrapper {
   width:500px; 
   height:300px; 
   position:relative;
}

.float {
   background-color:black; 
   height:300px; 
   margin:0; 
   padding:0; 
   color:white;
}

.left {
   background-color:blue; 
   position:fixed; 
   width:400px;
}

.right {
   float:right; 
   width:100px;
}

jsFiddle: http://jsfiddle.net/khA4m

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

mysqldump -uusername -ppassword -c -e --default-character-set=utf8 --single-transaction --skip-set-charset --add-drop-database -B dbname > dump.sql
cp dump.sql dump-fixed.sql
vim dump-fixed.sql


:%s/DEFAULT CHARACTER SET latin1/DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci/
:%s/DEFAULT CHARSET=latin1/DEFAULT CHARSET=utf8/
:wq

mysql -uusername -ppassword < dump-fixed.sql

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

This Works for me.

  1. Go to SQL Server >> Security >> Logins and right click on NT AUTHORITY\NETWORK SERVICE and select Properties
  2. In newly opened screen of Login Properties, go to the “User Mapping” tab.
  3. Then, on the “User Mapping” tab, select the desired database – especially the database for which this error message is displayed.
  4. Click OK.

Read this blog.

http://blog.sqlauthority.com/2009/08/20/sql-server-fix-error-cannot-open-database-requested-by-the-login-the-login-failed-login-failed-for-user-nt-authoritynetwork-service/

Check if a string isn't nil or empty in Lua

One simple thing you could do is abstract the test inside a function.

local function isempty(s)
  return s == nil or s == ''
end

if isempty(foo) then
  foo = "default value"
end

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

Try this ...

 StringRequest sr = new StringRequest(type,url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            // valid response
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            // error
        }
    }){

@Override
    protected Map<String,String> getParams(){
        Map<String,String> params = new HashMap<String, String>();
            params.put("username", username);
            params.put("password", password);
            params.put("grant_type", "password");
        return params;
    }

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String,String> params = new HashMap<String, String>();
        // Removed this line if you dont need it or Use application/json
        // params.put("Content-Type", "application/x-www-form-urlencoded");
        return params;
    }

How to generate a simple popup using jQuery

ONLY CSS POPUP LOGIC! TRY DO IT . EASY! I think this mybe be hack popular in future

            <a href="#openModal">OPEN</a>

            <div id="openModal" class="modalDialog">
                <div>
                    <a href="#close"  class="close">X</a>
                    <h2>MODAL</h2>

                </div>
            </div>


.modalDialog {
    position: fixed;
    font-family: Arial, Helvetica, sans-serif;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: rgba(0,0,0,0.8);
    z-index: 99999;
    -webkit-transition: opacity 400ms ease-in;
    -moz-transition: opacity 400ms ease-in;
    transition: opacity 400ms ease-in;
    display: none;
    pointer-events: none;
}

.modalDialog:target {
    display: block;
    pointer-events: auto;
}

.modalDialog > div {
    width: 400px;
    position: relative;
    margin: 10% auto;
    padding: 5px 20px 13px 20px;
    border-radius: 10px;
    background: #fff;
    background: -moz-linear-gradient(#fff, #999);
    background: -webkit-linear-gradient(#fff, #999);
    background: -o-linear-gradient(#fff, #999);
}

Move an array element from one array position to another

This version isn't ideal for all purposes, and not everyone likes comma expressions, but here's a one-liner that's a pure expression, creating a fresh copy:

const move = (from, to, ...a) => (a.splice(to, 0, ...a.splice(from, 1)), a)

A slightly performance-improved version returns the input array if no move is needed, it's still OK for immutable use, as the array won't change, and it's still a pure expression:

const move = (from, to, ...a) => 
    from === to 
    ? a 
    : (a.splice(to, 0, ...a.splice(from, 1)), a)

The invocation of either is

const shuffled = move(fromIndex, toIndex, ...list)

i.e. it relies on spreading to generate a fresh copy. Using a fixed arity 3 move would jeopardize either the single expression property, or the non-destructive nature, or the performance benefit of splice. Again, it's more of an example that meets some criteria than a suggestion for production use.

Using the "start" command with parameters passed to the started program

Change The "Virtual PC.exe" to a name without space like "VirtualPC.exe" in the folder. When you write start "path" with "" the CMD starts a new cmd window with the path as the title. Change the name to a name without space,write this on Notepad and after this save like Name.cmd or Name.bat:

CD\
CD Program Files
CD Microsoft Virtual PC
start VirtualPC.exe
timeout 2
exit

This command will redirect the CMD to the folder,start the VirualPC.exe,wait 2 seconds and exit.

What are .iml files in Android Studio?

What are iml files in Android Studio project?

A Google search on iml file turns up:

IML is a module file created by IntelliJ IDEA, an IDE used to develop Java applications. It stores information about a development module, which may be a Java, Plugin, Android, or Maven component; saves the module paths, dependencies, and other settings.

(from this page)

why not to use gradle scripts to integrate with external modules that you add to your project.

You do "use gradle scripts to integrate with external modules", or your own modules.

However, Gradle is not IntelliJ IDEA's native project model — that is separate, held in .iml files and the metadata in .idea/ directories. In Android Studio, that stuff is largely generated out of the Gradle build scripts, which is why you are sometimes prompted to "sync project with Gradle files" when you change files like build.gradle. This is also why you don't bother putting .iml files or .idea/ in version control, as their contents will be regenerated.

If I have a team that work in different IDE's like Eclipse and AS how to make project IDE agnostic?

To a large extent, you can't.

You are welcome to have an Android project that uses the Eclipse-style directory structure (e.g., resources and manifest in the project root directory). You can teach Gradle, via build.gradle, how to find files in that structure. However, other metadata (compileSdkVersion, dependencies, etc.) will not be nearly as easily replicated.

Other alternatives include:

  • Move everybody over to another build system, like Maven, that is equally integrated (or not, depending upon your perspective) to both Eclipse and Android Studio

  • Hope that Andmore takes off soon, so that perhaps you can have an Eclipse IDE that can build Android projects from Gradle build scripts

  • Have everyone use one IDE

regex match any whitespace

Your regex should work 'as-is'. Assuming that it is doing what you want it to.

wordA(\s*)wordB(?! wordc)

This means match wordA followed by 0 or more spaces followed by wordB, but do not match if followed by wordc. Note the single space between ?! and wordc which means that wordA wordB wordc will not match, but wordA wordB wordc will.

Here are some example matches and the associated replacement output:

enter image description here

Note that all matches are replaced no matter how many spaces. There are a couple of other points: -

  • (?! wordc) is a negative lookahead, so you wont match lines wordA wordB wordc which is assume is intended (and is why the last line is not matched). Currently you are relying on the space after ?! to match the whitespace. You may want to be more precise and use (?!\swordc). If you want to match against more than one space before wordc you can use (?!\s*wordc) for 0 or more spaces or (?!\s*+wordc) for 1 or more spaces depending on what your intention is. Of course, if you do want to match lines with wordc after wordB then you shouldn't use a negative lookahead.

  • * will match 0 or more spaces so it will match wordAwordB. You may want to consider + if you want at least one space.

  • (\s*) - the brackets indicate a capturing group. Are you capturing the whitespace to a group for a reason? If not you could just remove the brackets, i.e. just use \s.

Update based on comment

Hello the problem is not the expression but the HTML out put   that are not considered as whitespace. it's a Joomla website.

Preserving your original regex you can use:

wordA((?:\s|&nbsp;)*)wordB(?!(?:\s|&nbsp;)wordc)

The only difference is that not the regex matches whitespace OR &nbsp;. I replaced wordc with \swordc since that is more explicit. Note as I have already pointed out that the negative lookahead ?! will not match when wordB is followed by a single whitespace and wordc. If you want to match multiple whitespaces then see my comments above. I also preserved the capture group around the whitespace, if you don't want this then remove the brackets as already described above.

Example matches:

enter image description here

What is a vertical tab?

It was used during the typewriter era to move down a page to the next vertical stop, typically spaced 6 lines apart (much the same way horizontal tabs move along a line by 8 characters).

In modern day settings, the vt is of very little, if any, significance.