Programs & Examples On #Replication

The use of redundant resources to improve reliability, fault-tolerance, or performance.

I get a "An attempt was made to load a program with an incorrect format" error on a SQL Server replication project

in windows form application I do this, Right-click on Project->Properties->Build->Check Prefer 32-bit checkbox. Thanks all

Could not obtain information about Windows NT group user

We encountered similar errors in a testing environment on a virtual machine. If the machine name changes due to VM cloning from a template, you can get this error.

If the computer name changed from OLD to NEW.

A job uses this stored procedure:

msdb.dbo.sp_sqlagent_has_server_access @login_name = 'OLD\Administrator'

Which uses this one:

EXECUTE master.dbo.xp_logininfo 'OLD\Administrator'

Which gives this SQL error 15404

select text from sys.messages where message_id = 15404;
Could not obtain information about Windows NT group/user '%ls', error code %#lx.

Which I guess is correct, under the circumstances. We added a script to the VM cloning/deployment process that re-creates the SQL login.

Fatal Error :1:1: Content is not allowed in prolog

Looks like you forgot adding correct headers to your get request (ask the REST API developer or you specific API description):

HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.header("Accept", "application/xml")
connection.setRequestMethod("GET");
connection.connect();

or

connection.header("Accept", "application/xml;version=1")

error: unknown type name ‘bool’

Just add the following:

#define __USE_C99_MATH

#include <stdbool.h>

What are the main differences between JWT and OAuth authentication?

find the main differences between JWT & OAuth

  1. OAuth 2.0 defines a protocol & JWT defines a token format.

  2. OAuth can use either JWT as a token format or access token which is a bearer token.

  3. OpenID connect mostly use JWT as a token format.

Error: "setFile(null,false) call failed" when using log4j

Have a look at the error - 'log4j:ERROR setFile(null,false) call failed. java.io.FileNotFoundException: logs (Access is denied)'

It seems there's a log file named as 'logs' to which access is denied i.e it is not having sufficient permissions to write logs. Try by giving write permissions to the 'logs' log file. Hope it helps.

Tower of Hanoi: Recursive Algorithm

void TOH(int n, int a, int b){
        /*Assuming a as source stack numbered as 1, b as spare stack numbered as 2 and  c as target stack numbered as 3. So once we know values of a and b, we can determine c as there sum is a constant number (3+2+1=)6.
       */
int c = 6-a-b;
if(n==1){
    cout<<"Move from "<<a<<" to "<<b<<"\n";
}
else{
    // Move n-1 disks from 1st to 2nd stack. As we are not allowed to move more than one disks at a time, we do it by recursion. Breaking the problem into a simpler problem.
    TOH(n-1, a, c);
    // Move the last alone disk from 1st to 3rd stack.
    TOH(1, a, b);
    // Put n-1 disks from 2nd to 3rd stack. As we are not allowed to move more than one disks at a time, we do it by recursion. Breaking the problem into a simpler problem.        
    TOH(n-1, c, b);
}
}
int main() {

TOH(2, 1, 3);
cout<<"FINISHED                        \n";
TOH(3, 1, 3);
cout<<"FINISHED                        \n";
TOH(4, 1, 3);
return 0;
}

How to check if user input is not an int value

Maybe you can try this:

int function(){
Scanner input = new Scanner(System.in);   
System.out.print("Enter an integer between 1-100: ");   
int range;
while(true){   
    if(input.hasNextInt()){   
    range = input.nextInt();
    if(0<=range && range <= 100)
        break;
    else
        continue;
    }
    input.nextLine();  //Comsume the garbage value
    System.out.println("Enter an integer between 1-100:");
}
return range;
}

Convert Difference between 2 times into Milliseconds?

If you are only dealing with Times and no dates you will want to only deal with TimeSpan and handle crossing over midnight.

TimeSpan time1 = ...;  // assume TimeOfDay
TimeSpan time2 = ...;  // assume TimeOfDay
TimeSpan diffTime = time2 - time1;
if (time2 < time1)  // crosses over midnight
    diffTime += TimeSpan.FromTicks(TimeSpan.TicksPerDay);
int totalMilliSeconds = (int)diffTime.TotalMilliseconds;

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

In order to set the color of highlighted item you need to set the color of cell.SelectionStyle in iOS.

This example is to set the color of tapped item to transparent.

If you want you can change it with other colors from UITableViewCellSelectionStyle. This is to be written in the platform project of iOS by creating a new Custom ListView renderer in your Forms project.

public class CustomListViewRenderer : ListViewRenderer
    {
        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            if (Control == null)
            {
                return;
            }

            if (e.PropertyName == "ItemsSource")
            {
                foreach (var cell in Control.VisibleCells)
                {
                    cell.SelectionStyle = UITableViewCellSelectionStyle.None;
                }
            }
        }
    }

For android you can add this style in your values/styles.xml

<style name="ListViewStyle.Light" parent="android:style/Widget.ListView">
    <item name="android:listSelector">@android:color/transparent</item>
    <item name="android:cacheColorHint">@android:color/transparent</item>
  </style>

How to put text over images in html?

You can try this...

<div class="image">

      <img src="" alt="" />

      <h2>Text you want to display over the image</h2>

</div>

CSS

.image { 
   position: relative; 
   width: 100%; /* for IE 6 */
}

h2 { 
   position: absolute; 
   top: 200px; 
   left: 0; 
   width: 100%; 
}

How can I remove the top and right axis in matplotlib?

(This is more of an extension comment, in addition to the comprehensive answers here.)


Note that we can hide each of these three elements independently of each other:

  • To hide the border (aka "spine"): ax.set_frame_on(False) or ax.spines['top'].set_visible(False)

  • To hide the ticks: ax.tick_params(top=False)

  • To hide the labels: ax.tick_params(labeltop=False)

PHP: date function to get month of the current date

What does your "data variable" look like? If it's like this:

$mydate = "2010-05-12 13:57:01";

You can simply do:

$month = date("m",strtotime($mydate));

For more information, take a look at date and strtotime.

EDIT:

To compare with an int, just do a date_format($date,"n"); which will give you the month without leading zero.

Alternatively, try one of these:

if((int)$month == 1)...
if(abs($month) == 1)...

Or something weird using ltrim, round, floor... but date_format() with "n" would be the best.

DataFrame constructor not properly called! error

You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.

So if you want to use your code, you could do:

df = DataFrame(eval(data))

But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:

data = []
for row in result_set:
    data.append({'value': row["tag_expression"], 'key': row["tag_name"]})

But probably even this is not needed, as depending on what is exactly in your result_set you could probably:

  • provide this directly to a DataFrame: DataFrame(result_set)
  • or use the pandas read_sql_query function to do this for you (see docs on this)

Pass array to mvc Action via AJAX

You should be able to do this just fine:

$.ajax({
   url: 'controller/myaction',
   data: JSON.stringify({
      myKey: myArray
   }),
   success: function(data) { /* Whatever */ }
});

Then your action method would be like so:

public ActionResult(List<int> myKey)
{
    // Do Stuff
}

For you, it looks like you just need to stringify your values. The JSONValueProvider in MVC will convert that back into an IEnumerable for you.

When should I use a struct rather than a class in C#?

Structure types in C# or other .net languages are generally used to hold things that should behave like fixed-sized groups of values. A useful aspect of structure types is that the fields of a structure-type instance can be modified by modifying the storage location in which it is held, and in no other way. It's possible to code a structure in such a way that the only way to mutate any field is to construct a whole new instance and then use a struct assignment to mutate all the fields of the target by overwriting them with values from the new instance, but unless a struct provides no means of creating an instance where its fields have non-default values, all of its fields will be mutable if and if the struct itself is stored in a mutable location.

Note that it's possible to design a structure type so that it will essentially behave like a class type, if the structure contains a private class-type field, and redirects its own members to that of the wrapped class object. For example, a PersonCollection might offer properties SortedByName and SortedById, both of which hold an "immutable" reference to a PersonCollection (set in their constructor) and implement GetEnumerator by calling either creator.GetNameSortedEnumerator or creator.GetIdSortedEnumerator. Such structs would behave much like a reference to a PersonCollection, except that their GetEnumerator methods would be bound to different methods in the PersonCollection. One could also have a structure wrap a portion of an array (e.g. one could define an ArrayRange<T> structure which would hold a T[] called Arr, an int Offset, and an int Length, with an indexed property which, for an index idx in the range 0 to Length-1, would access Arr[idx+Offset]). Unfortunately, if foo is a read-only instance of such a structure, current compiler versions won't allow operations like foo[3]+=4; because they have no way to determine whether such operations would attempt to write to fields of foo.

It's also possible to design a structure to behave a like a value type which holds a variable-sized collection (which will appear to be copied whenever the struct is) but the only way to make that work is to ensure that no object to which the struct holds a reference will ever be exposed to anything which might mutate it. For example, one could have an array-like struct which holds a private array, and whose indexed "put" method creates a new array whose content is like that of the original except for one changed element. Unfortunately, it can be somewhat difficult to make such structs perform efficiently. While there are times that struct semantics can be convenient (e.g. being able to pass an array-like collection to a routine, with the caller and callee both knowing that outside code won't modify the collection, may be better than requiring both caller and callee to defensively copy any data they're given), the requirement that class references point to objects that will never be mutated is often a pretty severe constraint.

How to save all files from source code of a web site?

Try Winhttrack

...offline browser utility.

It allows you to download a World Wide Web site from the Internet to a local directory, building recursively all directories, getting HTML, images, and other files from the server to your computer. HTTrack arranges the original site's relative link-structure. Simply open a page of the "mirrored" website in your browser, and you can browse the site from link to link, as if you were viewing it online. HTTrack can also update an existing mirrored site, and resume interrupted downloads. HTTrack is fully configurable, and has an integrated help system.

WinHTTrack is the Windows 2000/XP/Vista/Seven release of HTTrack, and WebHTTrack the Linux/Unix/BSD release...

How to get number of rows inserted by a transaction

@@ROWCOUNT will give the number of rows affected by the last SQL statement, it is best to capture it into a local variable following the command in question, as its value will change the next time you look at it:

DECLARE @Rows int
DECLARE @TestTable table (col1 int, col2 int)
INSERT INTO @TestTable (col1, col2) select 1,2 union select 3,4
SELECT @Rows=@@ROWCOUNT
SELECT @Rows AS Rows,@@ROWCOUNT AS [ROWCOUNT]

OUTPUT:

(2 row(s) affected)
Rows        ROWCOUNT
----------- -----------
2           1

(1 row(s) affected)

you get Rows value of 2, the number of inserted rows, but ROWCOUNT is 1 because the SELECT @Rows=@@ROWCOUNT command affected 1 row

if you have multiple INSERTs or UPDATEs, etc. in your transaction, you need to determine how you would like to "count" what is going on. You could have a separate total for each table, a single grand total value, or something completely different. You'll need to DECLARE a variable for each total you want to track and add to it following each operation that applies to it:

--note there is no error handling here, as this is a simple example
DECLARE @AppleTotal  int
DECLARE @PeachTotal  int

SELECT @AppleTotal=0,@PeachTotal=0

BEGIN TRANSACTION

INSERT INTO Apple (col1, col2) Select col1,col2 from xyz where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT

INSERT INTO Apple (col1, col2) Select col1,col2 from abc where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT

INSERT INTO Peach (col1, col2) Select col1,col2 from xyz where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT

INSERT INTO Peach (col1, col2) Select col1,col2 from abc where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT

COMMIT

SELECT @AppleTotal AS AppleTotal, @PeachTotal AS PeachTotal

Add a row number to result set of a SQL query

The typical pattern would be as follows, but you need to actually define how the ordering should be applied (since a table is, by definition, an unordered bag of rows):

SELECT t.A, t.B, t.C, number = ROW_NUMBER() OVER (ORDER BY t.A)
  FROM dbo.tableZ AS t
  ORDER BY t.A;

Not sure what the variables in your question are supposed to represent (they don't match).

How to strip a specific word from a string?

If want to remove the word from only the start of the string, then you could do:

  string[string.startswith(prefix) and len(prefix):]  

Where string is your string variable and prefix is the prefix you want to remove from your string variable.

For example:

  >>> papa = "papa is a good man. papa is the best."  
  >>> prefix = 'papa'
  >>> papa[papa.startswith(prefix) and len(prefix):]
  ' is a good man. papa is the best.'

Java - No enclosing instance of type Foo is accessible

You've declared the class Thing as a non-static inner class. That means it must be associated with an instance of the Hello class.

In your code, you're trying to create an instance of Thing from a static context. That is what the compiler is complaining about.

There are a few possible solutions. Which solution to use depends on what you want to achieve.

  • Move Thing out of the Hello class.

  • Change Thing to be a static nested class.

    static class Thing
    
  • Create an instance of Hello before creating an instance of Thing.

    public static void main(String[] args)
    {
        Hello h = new Hello();
        Thing thing1 = h.new Thing(); // hope this syntax is right, typing on the fly :P
    }
    

The last solution (a non-static nested class) would be mandatory if any instance of Thing depended on an instance of Hello to be meaningful. For example, if we had:

public class Hello {
    public int enormous;

    public Hello(int n) {
        enormous = n;
    }

    public class Thing {
        public int size;

        public Thing(int m) {
            if (m > enormous)
                size = enormous;
            else
                size = m;
        }
    }
    ...
}

any raw attempt to create an object of class Thing, as in:

Thing t = new Thing(31);

would be problematic, since there wouldn't be an obvious enormous value to test 31 against it. An instance h of the Hello outer class is necessary to provide this h.enormous value:

...
Hello h = new Hello(30);
...
Thing t = h.new Thing(31);
...

Because it doesn't mean a Thing if it doesn't have a Hello.

For more information on nested/inner classes: Nested Classes (The Java Tutorials)

insert vertical divider line between two nested divs, not full height

Use a div for your divider. It will always be centered vertically regardless to whether left and right divs are equal in height. You can reuse it anywhere on your site.

.divider{
    position:absolute;
    left:50%;
    top:10%;
    bottom:10%;
    border-left:1px solid white;
}

Check working example at http://jsfiddle.net/gtKBs/

How to work with progress indicator in flutter?

This is my solution with stack

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';

final themeColor = new Color(0xfff5a623);
final primaryColor = new Color(0xff203152);
final greyColor = new Color(0xffaeaeae);
final greyColor2 = new Color(0xffE8E8E8);

class LoadindScreen extends StatefulWidget {
  LoadindScreen({Key key, this.title}) : super(key: key);
  final String title;
  @override
  LoginScreenState createState() => new LoginScreenState();
}

class LoginScreenState extends State<LoadindScreen> {
  SharedPreferences prefs;

  bool isLoading = false;

  Future<Null> handleSignIn() async {
    setState(() {
      isLoading = true;
    });
    prefs = await SharedPreferences.getInstance();
    var isLoadingFuture = Future.delayed(const Duration(seconds: 3), () {
      return false;
    });
    isLoadingFuture.then((response) {
      setState(() {
        isLoading = response;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(
            widget.title,
            style: TextStyle(color: primaryColor, fontWeight: FontWeight.bold),
          ),
          centerTitle: true,
        ),
        body: Stack(
          children: <Widget>[
            Center(
              child: FlatButton(
                  onPressed: handleSignIn,
                  child: Text(
                    'SIGN IN WITH GOOGLE',
                    style: TextStyle(fontSize: 16.0),
                  ),
                  color: Color(0xffdd4b39),
                  highlightColor: Color(0xffff7f7f),
                  splashColor: Colors.transparent,
                  textColor: Colors.white,
                  padding: EdgeInsets.fromLTRB(30.0, 15.0, 30.0, 15.0)),
            ),

            // Loading
            Positioned(
              child: isLoading
                  ? Container(
                      child: Center(
                        child: CircularProgressIndicator(
                          valueColor: AlwaysStoppedAnimation<Color>(themeColor),
                        ),
                      ),
                      color: Colors.white.withOpacity(0.8),
                    )
                  : Container(),
            ),
          ],
        ));
  }
}

SQL RANK() versus ROW_NUMBER()

Look this example.

CREATE TABLE [dbo].#TestTable(
    [id] [int] NOT NULL,
    [create_date] [date] NOT NULL,
    [info1] [varchar](50) NOT NULL,
    [info2] [varchar](50) NOT NULL,
)

Insert some data

INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (1, '1/1/09', 'Blue', 'Green')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (1, '1/2/09', 'Red', 'Yellow')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (1, '1/3/09', 'Orange', 'Purple')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (2, '1/1/09', 'Yellow', 'Blue')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (2, '1/5/09', 'Blue', 'Orange')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (3, '1/2/09', 'Green', 'Purple')
INSERT INTO dbo.#TestTable (id, create_date, info1, info2)
VALUES (3, '1/8/09', 'Red', 'Blue')

Repeat same Values for 1

INSERT INTO dbo.#TestTable (id, create_date, info1, info2) VALUES (1, '1/1/09', 'Blue', 'Green')

Look All

SELECT * FROM #TestTable

Look your results

SELECT Id,
    create_date,
    info1,
    info2,
    ROW_NUMBER() OVER (PARTITION BY Id ORDER BY create_date DESC) AS RowId,
    RANK() OVER(PARTITION BY Id ORDER BY create_date DESC)    AS [RANK]
FROM #TestTable

Need to understand the different

failed to push some refs to [email protected]

In Heroku,you may have problems with pushing to master branch. I just had to start a new branch using

git checkout -b masterbranch

and then push using

git push heroku masterbranch

please try as above!

Excel - extracting data based on another list

Have you tried Advanced Filter? Using your short list as the 'Criteria' and long list as the 'List Range'. Use the options: 'Filter in Place' and 'Unique Values'.

You should be presented with the list of unique values that only appear in your short list.

Alternatively, you can paste your Unique list to another location (on the same sheet), if you prefer. Choose the option 'Copy to another Location' and in the 'Copy to' box enter the cell reference (say F1) where you want the Unique list.

Note: this will work with the two columns (name/ID) too, if you select the two columns as both 'Criteria' and 'List Range'.

Regular Expression usage with ls

You are confusing regular expression with shell globbing. If you want to use regular expression to match file names you could do:

$ ls | egrep '.+\..+'

jQuery & CSS - Remove/Add display:none

If you have a lot of elements you would like to .hide() or .show(), you are going to waste a lot of resources to do what you want - even if use .hide(0) or .show(0) - the 0 parameter is the duration of the animation.

As opposed to Prototype.js .hide() and .show() methods which only used to manipulate the display attribute of the element, jQuery's implementation is more complex and not recommended for a large number of elements.

In this cases you should probably try .css('display','none') to hide and .css('display','') to show

.css('display','block') should be avoided, especially if you're working with inline elements, table rows (actually any table elements) etc.

List of Java processes

The following commands will return only Java ProcessIDs. These commands are very useful especially whenever you want to feed another process by these return values (java PIDs).

sudo netstat -nlpt | awk '/java/ {print $7}' | tr '/java' ' '

sudo netstat -nlpt | awk '/java/ {print $7}' | sed 's/\/java/ /g'

But if you remove the latest pipe, you will be noticed these are java process

sudo netstat -nlpt | awk '/java/ {print $7}'

sudo netstat -nlpt | awk '/java/ {print $7}'

Reading an image file into bitmap from sdcard, why am I getting a NullPointerException?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

What is a good regular expression to match a URL?

Regex if you want to ensure URL starts with HTTP/HTTPS:

https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)

If you do not require HTTP protocol:

[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)

To try this out see http://regexr.com?37i6s, or for a version which is less restrictive http://regexr.com/3e6m0.

Example JavaScript implementation:

_x000D_
_x000D_
var expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;_x000D_
var regex = new RegExp(expression);_x000D_
var t = 'www.google.com';_x000D_
_x000D_
if (t.match(regex)) {_x000D_
  alert("Successful match");_x000D_
} else {_x000D_
  alert("No match");_x000D_
}
_x000D_
_x000D_
_x000D_

import an array in python

Have a look at SciPy cookbook. It should give you an idea of some basic methods to import /export data.

If you save/load the files from your own Python programs, you may also want to consider the Pickle module, or cPickle.

How to make graphics with transparent background in R using ggplot2?

As for someone don't like gray background like academic editor, try this:

p <- p + theme_bw()
p

How can I prevent java.lang.NumberFormatException: For input string: "N/A"?

"N/A" is a string and cannot be converted to a number. Catch the exception and handle it. For example:

    String text = "N/A";
    int intVal = 0;
    try {
        intVal = Integer.parseInt(text);
    } catch (NumberFormatException e) {
        //Log it if needed
        intVal = //default fallback value;
    }

Simple Deadlock Examples

Simple example from https://docs.oracle.com/javase/tutorial/essential/concurrency/deadlock.html

public class Deadlock {

public static void printMessage(String message) {

    System.out.println(String.format("%s %s ", Thread.currentThread().getName(), message));

}

private static class Friend {

    private String name;

    public Friend(String name) {
        this.name = name;
    }

    public void bow(Friend friend) {

        printMessage("Acquiring lock on " + this.name);

        synchronized(this) {
            printMessage("Acquired lock on " + this.name);
            printMessage(name + " bows " + friend.name);
            friend.bowBack(this);
        }

    }

    public void bowBack(Friend friend) {

        printMessage("Acquiring lock on " + this.name);

        synchronized (this) {
            printMessage("Acquired lock on " + this.name);
            printMessage(friend.name + " bows back");
        }

    }

}

public static void main(String[] args) throws InterruptedException {

    Friend one = new Friend("one");
    Friend two = new Friend("two");

    new Thread(new Runnable() {
        @Override
        public void run() {
            one.bow(two);
        }
    }).start();

    new Thread(new Runnable() {
        @Override
        public void run() {
            two.bow(one);
        }
    }).start();
}

}

Output:

Thread-0 Acquiring lock on one 
Thread-1 Acquiring lock on two 
Thread-0 Acquired lock on one 
Thread-1 Acquired lock on two 
Thread-1 two bows one 
Thread-0 one bows two 
Thread-1 Acquiring lock on one 
Thread-0 Acquiring lock on two 

Thread Dump:

2016-03-14 12:20:09
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.74-b02 mixed mode):

"DestroyJavaVM" #13 prio=5 os_prio=0 tid=0x00007f472400a000 nid=0x3783 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Thread-1" #12 prio=5 os_prio=0 tid=0x00007f472420d800 nid=0x37a3 waiting for monitor entry [0x00007f46e89a5000]
   java.lang.Thread.State: BLOCKED (on object monitor)
    at com.anantha.algorithms.ThreadJoin$Friend.bowBack(ThreadJoin.java:102)
    - waiting to lock <0x000000076d0583a0> (a com.anantha.algorithms.ThreadJoin$Friend)
    at com.anantha.algorithms.ThreadJoin$Friend.bow(ThreadJoin.java:92)
    - locked <0x000000076d0583e0> (a com.anantha.algorithms.ThreadJoin$Friend)
    at com.anantha.algorithms.ThreadJoin$2.run(ThreadJoin.java:141)
    at java.lang.Thread.run(Thread.java:745)

"Thread-0" #11 prio=5 os_prio=0 tid=0x00007f472420b800 nid=0x37a2 waiting for monitor entry [0x00007f46e8aa6000]
   java.lang.Thread.State: BLOCKED (on object monitor)
    at com.anantha.algorithms.ThreadJoin$Friend.bowBack(ThreadJoin.java:102)
    - waiting to lock <0x000000076d0583e0> (a com.anantha.algorithms.ThreadJoin$Friend)
    at com.anantha.algorithms.ThreadJoin$Friend.bow(ThreadJoin.java:92)
    - locked <0x000000076d0583a0> (a com.anantha.algorithms.ThreadJoin$Friend)
    at com.anantha.algorithms.ThreadJoin$1.run(ThreadJoin.java:134)
    at java.lang.Thread.run(Thread.java:745)

"Monitor Ctrl-Break" #10 daemon prio=5 os_prio=0 tid=0x00007f4724211000 nid=0x37a1 runnable [0x00007f46e8def000]
   java.lang.Thread.State: RUNNABLE
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
    at java.net.SocketInputStream.read(SocketInputStream.java:170)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
    at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
    at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
    - locked <0x000000076d20afb8> (a java.io.InputStreamReader)
    at java.io.InputStreamReader.read(InputStreamReader.java:184)
    at java.io.BufferedReader.fill(BufferedReader.java:161)
    at java.io.BufferedReader.readLine(BufferedReader.java:324)
    - locked <0x000000076d20afb8> (a java.io.InputStreamReader)
    at java.io.BufferedReader.readLine(BufferedReader.java:389)
    at com.intellij.rt.execution.application.AppMain$1.run(AppMain.java:93)
    at java.lang.Thread.run(Thread.java:745)

"Service Thread" #9 daemon prio=9 os_prio=0 tid=0x00007f47240c9800 nid=0x3794 runnable [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C1 CompilerThread3" #8 daemon prio=9 os_prio=0 tid=0x00007f47240c6800 nid=0x3793 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread2" #7 daemon prio=9 os_prio=0 tid=0x00007f47240c4000 nid=0x3792 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread1" #6 daemon prio=9 os_prio=0 tid=0x00007f47240c2800 nid=0x3791 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"C2 CompilerThread0" #5 daemon prio=9 os_prio=0 tid=0x00007f47240bf800 nid=0x3790 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Signal Dispatcher" #4 daemon prio=9 os_prio=0 tid=0x00007f47240be000 nid=0x378f waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

"Finalizer" #3 daemon prio=8 os_prio=0 tid=0x00007f472408c000 nid=0x378e in Object.wait() [0x00007f46e98c5000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x000000076cf88ee0> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:143)
    - locked <0x000000076cf88ee0> (a java.lang.ref.ReferenceQueue$Lock)
    at java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:164)
    at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:209)

"Reference Handler" #2 daemon prio=10 os_prio=0 tid=0x00007f4724087800 nid=0x378d in Object.wait() [0x00007f46e99c6000]
   java.lang.Thread.State: WAITING (on object monitor)
    at java.lang.Object.wait(Native Method)
    - waiting on <0x000000076cf86b50> (a java.lang.ref.Reference$Lock)
    at java.lang.Object.wait(Object.java:502)
    at java.lang.ref.Reference.tryHandlePending(Reference.java:191)
    - locked <0x000000076cf86b50> (a java.lang.ref.Reference$Lock)
    at java.lang.ref.Reference$ReferenceHandler.run(Reference.java:153)

"VM Thread" os_prio=0 tid=0x00007f4724080000 nid=0x378c runnable 

"GC task thread#0 (ParallelGC)" os_prio=0 tid=0x00007f472401f000 nid=0x3784 runnable 

"GC task thread#1 (ParallelGC)" os_prio=0 tid=0x00007f4724021000 nid=0x3785 runnable 

"GC task thread#2 (ParallelGC)" os_prio=0 tid=0x00007f4724022800 nid=0x3786 runnable 

"GC task thread#3 (ParallelGC)" os_prio=0 tid=0x00007f4724024800 nid=0x3787 runnable 

"GC task thread#4 (ParallelGC)" os_prio=0 tid=0x00007f4724026000 nid=0x3788 runnable 

"GC task thread#5 (ParallelGC)" os_prio=0 tid=0x00007f4724028000 nid=0x3789 runnable 

"GC task thread#6 (ParallelGC)" os_prio=0 tid=0x00007f4724029800 nid=0x378a runnable 

"GC task thread#7 (ParallelGC)" os_prio=0 tid=0x00007f472402b800 nid=0x378b runnable 

"VM Periodic Task Thread" os_prio=0 tid=0x00007f47240cc800 nid=0x3795 waiting on condition 

JNI global references: 16


Found one Java-level deadlock:
=============================
"Thread-1":
  waiting to lock monitor 0x00007f46dc003f08 (object 0x000000076d0583a0, a com.anantha.algorithms.ThreadJoin$Friend),
  which is held by "Thread-0"
"Thread-0":
  waiting to lock monitor 0x00007f46dc006008 (object 0x000000076d0583e0, a com.anantha.algorithms.ThreadJoin$Friend),
  which is held by "Thread-1"

Java stack information for the threads listed above:
===================================================
"Thread-1":
    at com.anantha.algorithms.ThreadJoin$Friend.bowBack(ThreadJoin.java:102)
    - waiting to lock <0x000000076d0583a0> (a com.anantha.algorithms.ThreadJoin$Friend)
    at com.anantha.algorithms.ThreadJoin$Friend.bow(ThreadJoin.java:92)
    - locked <0x000000076d0583e0> (a com.anantha.algorithms.ThreadJoin$Friend)
    at com.anantha.algorithms.ThreadJoin$2.run(ThreadJoin.java:141)
    at java.lang.Thread.run(Thread.java:745)
"Thread-0":
    at com.anantha.algorithms.ThreadJoin$Friend.bowBack(ThreadJoin.java:102)
    - waiting to lock <0x000000076d0583e0> (a com.anantha.algorithms.ThreadJoin$Friend)
    at com.anantha.algorithms.ThreadJoin$Friend.bow(ThreadJoin.java:92)
    - locked <0x000000076d0583a0> (a com.anantha.algorithms.ThreadJoin$Friend)
    at com.anantha.algorithms.ThreadJoin$1.run(ThreadJoin.java:134)
    at java.lang.Thread.run(Thread.java:745)

Found 1 deadlock.

Heap
 PSYoungGen      total 74752K, used 9032K [0x000000076cf80000, 0x0000000772280000, 0x00000007c0000000)
  eden space 64512K, 14% used [0x000000076cf80000,0x000000076d8520e8,0x0000000770e80000)
  from space 10240K, 0% used [0x0000000771880000,0x0000000771880000,0x0000000772280000)
  to   space 10240K, 0% used [0x0000000770e80000,0x0000000770e80000,0x0000000771880000)
 ParOldGen       total 171008K, used 0K [0x00000006c6e00000, 0x00000006d1500000, 0x000000076cf80000)
  object space 171008K, 0% used [0x00000006c6e00000,0x00000006c6e00000,0x00000006d1500000)
 Metaspace       used 3183K, capacity 4500K, committed 4864K, reserved 1056768K
  class space    used 352K, capacity 388K, committed 512K, reserved 1048576K

Create code first, many to many, with additional fields in association table

It's not possible to create a many-to-many relationship with a customized join table. In a many-to-many relationship EF manages the join table internally and hidden. It's a table without an Entity class in your model. To work with such a join table with additional properties you will have to create actually two one-to-many relationships. It could look like this:

public class Member
{
    public int MemberID { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<MemberComment> MemberComments { get; set; }
}

public class Comment
{
    public int CommentID { get; set; }
    public string Message { get; set; }

    public virtual ICollection<MemberComment> MemberComments { get; set; }
}

public class MemberComment
{
    [Key, Column(Order = 0)]
    public int MemberID { get; set; }
    [Key, Column(Order = 1)]
    public int CommentID { get; set; }

    public virtual Member Member { get; set; }
    public virtual Comment Comment { get; set; }

    public int Something { get; set; }
    public string SomethingElse { get; set; }
}

If you now want to find all comments of members with LastName = "Smith" for example you can write a query like this:

var commentsOfMembers = context.Members
    .Where(m => m.LastName == "Smith")
    .SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
    .ToList();

... or ...

var commentsOfMembers = context.MemberComments
    .Where(mc => mc.Member.LastName == "Smith")
    .Select(mc => mc.Comment)
    .ToList();

Or to create a list of members with name "Smith" (we assume there is more than one) along with their comments you can use a projection:

var membersWithComments = context.Members
    .Where(m => m.LastName == "Smith")
    .Select(m => new
    {
        Member = m,
        Comments = m.MemberComments.Select(mc => mc.Comment)
    })
    .ToList();

If you want to find all comments of a member with MemberId = 1:

var commentsOfMember = context.MemberComments
    .Where(mc => mc.MemberId == 1)
    .Select(mc => mc.Comment)
    .ToList();

Now you can also filter by the properties in your join table (which would not be possible in a many-to-many relationship), for example: Filter all comments of member 1 which have a 99 in property Something:

var filteredCommentsOfMember = context.MemberComments
    .Where(mc => mc.MemberId == 1 && mc.Something == 99)
    .Select(mc => mc.Comment)
    .ToList();

Because of lazy loading things might become easier. If you have a loaded Member you should be able to get the comments without an explicit query:

var commentsOfMember = member.MemberComments.Select(mc => mc.Comment);

I guess that lazy loading will fetch the comments automatically behind the scenes.

Edit

Just for fun a few examples more how to add entities and relationships and how to delete them in this model:

1) Create one member and two comments of this member:

var member1 = new Member { FirstName = "Pete" };
var comment1 = new Comment { Message = "Good morning!" };
var comment2 = new Comment { Message = "Good evening!" };
var memberComment1 = new MemberComment { Member = member1, Comment = comment1,
                                         Something = 101 };
var memberComment2 = new MemberComment { Member = member1, Comment = comment2,
                                         Something = 102 };

context.MemberComments.Add(memberComment1); // will also add member1 and comment1
context.MemberComments.Add(memberComment2); // will also add comment2

context.SaveChanges();

2) Add a third comment of member1:

var member1 = context.Members.Where(m => m.FirstName == "Pete")
    .SingleOrDefault();
if (member1 != null)
{
    var comment3 = new Comment { Message = "Good night!" };
    var memberComment3 = new MemberComment { Member = member1,
                                             Comment = comment3,
                                             Something = 103 };

    context.MemberComments.Add(memberComment3); // will also add comment3
    context.SaveChanges();
}

3) Create new member and relate it to the existing comment2:

var comment2 = context.Comments.Where(c => c.Message == "Good evening!")
    .SingleOrDefault();
if (comment2 != null)
{
    var member2 = new Member { FirstName = "Paul" };
    var memberComment4 = new MemberComment { Member = member2,
                                             Comment = comment2,
                                             Something = 201 };

    context.MemberComments.Add(memberComment4);
    context.SaveChanges();
}

4) Create relationship between existing member2 and comment3:

var member2 = context.Members.Where(m => m.FirstName == "Paul")
    .SingleOrDefault();
var comment3 = context.Comments.Where(c => c.Message == "Good night!")
    .SingleOrDefault();
if (member2 != null && comment3 != null)
{
    var memberComment5 = new MemberComment { Member = member2,
                                             Comment = comment3,
                                             Something = 202 };

    context.MemberComments.Add(memberComment5);
    context.SaveChanges();
}

5) Delete this relationship again:

var memberComment5 = context.MemberComments
    .Where(mc => mc.Member.FirstName == "Paul"
        && mc.Comment.Message == "Good night!")
    .SingleOrDefault();
if (memberComment5 != null)
{
    context.MemberComments.Remove(memberComment5);
    context.SaveChanges();
}

6) Delete member1 and all its relationships to the comments:

var member1 = context.Members.Where(m => m.FirstName == "Pete")
    .SingleOrDefault();
if (member1 != null)
{
    context.Members.Remove(member1);
    context.SaveChanges();
}

This deletes the relationships in MemberComments too because the one-to-many relationships between Member and MemberComments and between Comment and MemberComments are setup with cascading delete by convention. And this is the case because MemberId and CommentId in MemberComment are detected as foreign key properties for the Member and Comment navigation properties and since the FK properties are of type non-nullable int the relationship is required which finally causes the cascading-delete-setup. Makes sense in this model, I think.

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

check your image cmd using the command docker inspect image_name . The output might be like this:

"Cmd": [
    "/bin/bash",
    "-c",
    "#(nop) ",
    "CMD [\"/bin/bash\"]"
],

So use the command docker exec -it container_id /bin/bash. If your cmd output is different like this:

"Cmd": [
    "/bin/sh",
    "-c",
    "#(nop) ",
    "CMD [\"/bin/sh\"]"
],

Use /bin/sh instead of /bin/bash in the command above.

java.io.StreamCorruptedException: invalid stream header: 54657374

Clearly you aren't sending the data with ObjectOutputStream: you are just writing the bytes.

  • If you read with readObject() you must write with writeObject().
  • If you read with readUTF() you must write with writeUTF().
  • If you read with readXXX() you must write with writeXXX(), for most values of XXX.

android get real path by Uri.getPath()

This is what I do:

Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));

and:

private String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        result = contentURI.getPath();
    } else { 
        cursor.moveToFirst(); 
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}

NOTE: managedQuery() method is deprecated, so I am not using it.

Last edit: Improvement. We should close cursor!!

Groovy / grails how to determine a data type?

Simple groovy way to check object type:

somObject in Date

Can be applied also to interfaces.

How to return value from an asynchronous callback function?

If you happen to be using jQuery, you might want to give this a shot: http://api.jquery.com/category/deferred-object/

It allows you to defer the execution of your callback function until the ajax request (or any async operation) is completed. This can also be used to call a callback once several ajax requests have all completed.

Run .jar from batch-file

If double-clicking the .jar file in Windows Explorer works, then you should be able to use this:

start myapp.jar

in your batch file.

The Windows start command does exactly the same thing behind the scenes as double-clicking a file.

Regular expression: find spaces (tabs/space) but not newlines

If you want to replace space below code worked for me in C#

Regex.Replace(Line,"\\\s","");

For Tab

Regex.Replace(Line,"\\\s\\\s","");

OPENSSL file_get_contents(): Failed to enable crypto

Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.

<?php
function getSSLPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSLVERSION,3); 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>

When you set the SSL Version with curl to v3 then it works.

Edit:

Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.

http://curl.haxx.se/docs/caextract.html

here you can download the root certificates.

curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

Then you can use the CURLOPT_SSL_VERIFYPEER option with true otherwise you get an error.

Get only part of an Array in Java?

If you are using Java 1.6 or greater, you can use Arrays.copyOfRange to copy a portion of the array. From the javadoc:

Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case false is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from.

Here is a simple example:

/**
 * @Program that Copies the specified range of the specified array into a new 
 * array.
 * CopyofRange8Array.java 
 * Author:-RoseIndia Team
 * Date:-15-May-2008
 */
import java.util.*;
public class CopyofRange8Array {
    public static void main(String[] args) {
       //creating a short array
       Object T[]={"Rose","India","Net","Limited","Rohini"};
        // //Copies the specified  short array upto specified range,
        Object T1[] = Arrays.copyOfRange(T, 1,5);
        for (int i = 0; i < T1.length; i++) 
            //Displaying the Copied short array upto specified range
            System.out.println(T1[i]);
    }

}

How do we check if a pointer is NULL pointer?

I always think simply if(p != NULL){..} will do the job.

It will.

How to check if pytorch is using the GPU?

This is going to work :

In [1]: import torch

In [2]: torch.cuda.current_device()
Out[2]: 0

In [3]: torch.cuda.device(0)
Out[3]: <torch.cuda.device at 0x7efce0b03be0>

In [4]: torch.cuda.device_count()
Out[4]: 1

In [5]: torch.cuda.get_device_name(0)
Out[5]: 'GeForce GTX 950M'

In [6]: torch.cuda.is_available()
Out[6]: True

This tells me the GPU GeForce GTX 950M is being used by PyTorch.

HTTP Error 404.3-Not Found in IIS 7.5

In my case, along with Mekanik's suggestions, I was receiving this error in Windows Server 2012 and I had to tick "HTTP Activation" in "Add Role Services".

When would you use the different git merge strategies?

"Resolve" vs "Recursive" merge strategy

Recursive is the current default two-head strategy, but after some searching I finally found some info about the "resolve" merge strategy.

Taken from O'Reilly book Version Control with Git (Amazon) (paraphrased):

Originally, "resolve" was the default strategy for Git merges.

In criss-cross merge situations, where there is more than one possible merge basis, the resolve strategy works like this: pick one of the possible merge bases, and hope for the best. This is actually not as bad as it sounds. It often turns out that the users have been working on different parts of the code. In that case, Git detects that it's remerging some changes that are already in place and skips the duplicate changes, avoiding the conflict. Or, if these are slight changes that do cause conflict, at least the conflict should be easy for the developer to handle..

I have successfully merged trees using "resolve" that failed with the default recursive strategy. I was getting fatal: git write-tree failed to write a tree errors, and thanks to this blog post (mirror) I tried "-s resolve", which worked. I'm still not exactly sure why... but I think it was because I had duplicate changes in both trees, and resolve "skipped" them properly.

Oracle find a constraint

To get a more detailed description (which table/column references which table/column) you can run the following query:

SELECT   uc.constraint_name||CHR(10)
   ||      '('||ucc1.TABLE_NAME||'.'||ucc1.column_name||')' constraint_source
   ,       'REFERENCES'||CHR(10)
   ||      '('||ucc2.TABLE_NAME||'.'||ucc2.column_name||')' references_column
FROM user_constraints uc ,
  user_cons_columns ucc1 ,
  user_cons_columns ucc2
WHERE uc.constraint_name = ucc1.constraint_name
AND uc.r_constraint_name = ucc2.constraint_name
AND ucc1.POSITION        = ucc2.POSITION -- Correction for multiple column primary keys.
AND uc.constraint_type   = 'R'
AND uc.constraint_name   = 'SYS_C00381400'
ORDER BY ucc1.TABLE_NAME ,
  uc.constraint_name;

From here.

Getting value of HTML text input

See my jsFiddle here: http://jsfiddle.net/fuDBL/

Whenever you change the email field, the link is updated automatically. This requires a small amount of jQuery. So now your form will work as needed, but your link will be updated dynamically so that when someone clicks on it, it contains what they entered in the email field. You should validate the input on the receiving page.

$('input[name="email"]').change(function(){
  $('#regLink').attr('href')+$('input[name="email"]').val();
});

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

I tried various approach described above but none of them worked since I have ejected my css. Finally applying following steps helped:

  1. Upgradereact-scripts from "react-scripts": "3.x.x" to "react-scripts": "^3.4.0"
  2. Downgrading react-dev-utils form "react-dev-utils": "^10.x.x" to "react-dev-utils": "10.0.0"
  3. Delete node-modules folder and package-lock.json/yarn.lock
  4. Reinstall packages npm install/yarn install

Uploading multiple files using formData()

I found this work for me!

var fd = new FormData();
$.each($('.modal-banner [type=file]'), function(index, file) {
  fd.append('item[]', $('input[type=file]')[index].files[0]);
});

$.ajax({
  type: 'POST',
  url: 'your/path/', 
  data: fd,
  dataType: 'json',
  contentType: false,
  processData: false,
  cache: false,
  success: function (response) {
    console.log(response);
  },
  error: function(err){
    console.log(err);
  }
}).done(function() {
  // do something....
});
return false;

Event system in Python

You may have a look at pymitter (pypi). Its a small single-file (~250 loc) approach "providing namespaces, wildcards and TTL".

Here's a basic example:

from pymitter import EventEmitter

ee = EventEmitter()

# decorator usage
@ee.on("myevent")
def handler1(arg):
   print "handler1 called with", arg

# callback usage
def handler2(arg):
    print "handler2 called with", arg
ee.on("myotherevent", handler2)

# emit
ee.emit("myevent", "foo")
# -> "handler1 called with foo"

ee.emit("myotherevent", "bar")
# -> "handler2 called with bar"

CSS How to set div height 100% minus nPx

div {
    height: 100%;
    height: -webkit-calc(100% - 60px);
    height: -moz-calc(100% - 60px);
    height: calc(100% - 60px);
}

Make sure while using less

height: ~calc(100% - 60px);

Otherwise less is no going to compile it correctly

Cross-reference (named anchor) in markdown

On bitbucket.org the voted solution wouldn't work. Instead, when using headers (with ##), it is possible to reference them as anchors by prefixing them as #markdown-header-my-header-name, where #markdown-header- is an implicit prefix generated by the renderer, and the rest is the lower-cased header title with dashes replacing spaces.

Example

## My paragraph title

will produce an implicit anchor like this

#markdown-header-my-paragraph-title

The whole URL before each anchor reference is optional, i.e.

[Some text](#markdown-header-my-paragraph-title)

is equivalent of

[Some text](https://bitbucket.org/some_project/some_page#markdown-header-my-paragraph-title) 

provided that they are in the same page.

Source: https://bitbucket.org/tutorials/markdowndemo/overview (edit source of this .md file and look at how anchors are made).

Replace one character with another in Bash

Use inline shell string replacement. Example:

foo="  "

# replace first blank only
bar=${foo/ /.}

# replace all blanks
bar=${foo// /.}

See http://tldp.org/LDP/abs/html/string-manipulation.html for more details.

How to automatically allow blocked content in IE?

Alternatively, as long as permissions are not given, the good old <noscript> tags works. You can cover the page in css and tell them what's wrong, ... without using javascript ofcourse.

Convert Promise to Observable

import { from } from 'rxjs';

from(firebase.auth().createUserWithEmailAndPassword(email, password))
.subscribe((user: any) => {
      console.log('test');
});

Here is a shorter version using a combination of some of the answers above to convert your code from a promise to an observable.

How to declare a variable in SQL Server and use it in the same Stored Procedure

CREATE PROCEDURE AddBrand
@BrandName nvarchar(50) = null,
@CategoryID int = null
AS    
BEGIN

DECLARE @BrandID int = null
SELECT @BrandID = BrandID FROM tblBrand 
WHERE BrandName = @BrandName

INSERT INTO tblBrandinCategory (CategoryID, BrandID) 
       VALUES (@CategoryID, @BrandID)

END

EXEC AddBrand @BrandName = 'BMW', @CategoryId = 1

Is unsigned integer subtraction defined behavior?

When you work with unsigned types, modular arithmetic (also known as "wrap around" behavior) is taking place. To understand this modular arithmetic, just have a look at these clocks:

enter image description here

9 + 4 = 1 (13 mod 12), so to the other direction it is: 1 - 4 = 9 (-3 mod 12). The same principle is applied while working with unsigned types. If the result type is unsigned, then modular arithmetic takes place.


Now look at the following operations storing the result as an unsigned int:

unsigned int five = 5, seven = 7;
unsigned int a = five - seven;      // a = (-2 % 2^32) = 4294967294 

int one = 1, six = 6;
unsigned int b = one - six;         // b = (-5 % 2^32) = 4294967291

When you want to make sure that the result is signed, then stored it into signed variable or cast it to signed. When you want to get the difference between numbers and make sure that the modular arithmetic will not be applied, then you should consider using abs() function defined in stdlib.h:

int c = five - seven;       // c = -2
int d = abs(five - seven);  // d =  2

Be very careful, especially while writing conditions, because:

if (abs(five - seven) < seven)  // = if (2 < 7)
    // ...

if (five - seven < -1)          // = if (-2 < -1)
    // ...

if (one - six < 1)              // = if (-5 < 1)
    // ...

if ((int)(five - seven) < 1)    // = if (-2 < 1)
    // ...

but

if (five - seven < 1)   // = if ((unsigned int)-2 < 1) = if (4294967294 < 1)
    // ...

if (one - six < five)   // = if ((unsigned int)-5 < 5) = if (4294967291 < 5)
    // ...

Excel: Use a cell value as a parameter for a SQL query

If you are using microsoft query, you can add "?" to your query...

select name from user where id= ?

that will popup a small window asking for the cell/data/etc when you go back to excel.

In the popup window, you can also select "always use this cell as a parameter" eliminating the need to define that cell every time you refresh your data. This is the easiest option.

PDF Parsing Using Python - extracting formatted and plain texts

That's a difficult problem to solve since visually similar PDFs may have a wildly differing structure depending on how they were produced. In the worst case the library would need to basically act like an OCR. On the other hand, the PDF may contain sufficient structure and metadata for easy removal of tables and figures, which the library can be tailored to take advantage of.

I'm pretty sure there are no open source tools which solve your problem for a wide variety of PDFs, but I remember having heard of commercial software claiming to do exactly what you ask for. I'm sure you'll run into them while googling.

Does it matter what extension is used for SQLite database files?

In distributable software, I dont want my customers mucking about in the database by themselves. The program reads and writes it all by itself. The only reason for a user to touch the DB file is to take a backup copy. Therefore I have named it whatever_records.db

The simple .db extension tells the user that it is a binary data file and that's all they have to know. Calling it .sqlite invites the interested user to open it up and mess something up!

Totally depends on your usage scenario I suppose.

Using Git with Visual Studio

Git Source Control Provider is new plug-in that integrates Git with Visual Studio.

How do you show animated GIFs on a Windows Form (c#)

If you put it in a PictureBox control, it should just work

Play infinitely looping video on-load in HTML5

You can do this the following two ways:

1) Using loop attribute in video element (mentioned in the first answer):

2) and you can use the ended media event:

window.addEventListener('load', function(){
    var newVideo = document.getElementById('videoElementId');
    newVideo.addEventListener('ended', function() {
        this.currentTime = 0;
        this.play();
    }, false);

    newVideo.play();

});

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

I think the reason that this is happening could be because TextBox1 is scoping to the VBA module and its associated sheet, while Range is scoping to the "Active Sheet".

EDIT

It looks like you may be able to use the GetObject function to pull the textbox from the workbook.

What's the difference between "app.render" and "res.render" in express.js?

use app.render in scenarios where you need to render a view but not send it to a client via http. html emails springs to mind.

Lightweight XML Viewer that can handle large files

I have tried dozens of XML editors hoping to find one which would be able to do some kind of visualization. The best lightweight viewer for windows I have found was XMLMarker - too bad the project has been dead for some years now. It is not so useful as an editor, but it does a good job of displaying flat XML data as tables.

There are tons of free editors that do XML syntax highlighting, including vim, emacs, scite, eclipse (J2EE edition), jedit, notepad++.

For heavyweight XML features, like XPath support, XSLT editing and debugging, SOAP/WSDL there are some good commercial tools like, XMLSpy, Oxygen, StylusStudio.

JEdit is open-source and also has plugins for XML, XPath and XSLT.

Word-2003 is fairly good for visualizing (but don't use it for editing). Excel-2003 and up also does a good job at visualizing flat XML data and can apply XSL transformations (again, no good as an editor).

Splitting string with pipe character ("|")

| is a metacharacter in regex. You'd need to escape it:

String[] value_split = rat_values.split("\\|");

Multiple arguments to function called by pthread_create()?

Since asking the same question but for C++ is considered a duplicate I might as well supply C++ code as an answer.

//  hello-2args.cpp
// https://stackoverflow.com/questions/1352749
#include <iostream>
#include <omp.h>
#include <pthread.h>
using namespace std;

typedef struct thread_arguments {
  int thrnr;
  char *msg;
} thargs_t;

void *print_hello(void *thrgs) {
  cout << ((thargs_t*)thrgs)->msg << ((thargs_t*)thrgs)->thrnr << "\n";
  pthread_exit(NULL);
}

int main(int argc, char *argv[]) {
  cout << " Hello C++!\n";
  const int NR_THRDS = omp_get_max_threads();
  pthread_t threads[NR_THRDS];
  thargs_t thrgs[NR_THRDS];
  for(int t=0;t<NR_THRDS;t++) {
    thrgs[t].thrnr = t;
    thrgs[t].msg = (char*)"Hello World. - It's me! ... thread #";
    cout << "In main: creating thread " << t << "\n";
    pthread_create(&threads[t], NULL, print_hello, &thrgs[t]);
  }
  for(int t=0;t<NR_THRDS;t++) {
    pthread_join(threads[t], NULL);
  }
  cout << "After join: I am always last. Byebye!\n";
  return EXIT_SUCCESS;
}

Compile and run by using one of the following:

g++ -fopenmp -pthread hello-2args.cpp && ./a.out # Linux
g++ -fopenmp -pthread hello-2args.cpp && ./a.exe # MSYS2, Windows

How do I increase memory on Tomcat 7 when running as a Windows Service?

According to catalina.sh customizations should always go into your own setenv.sh (or setenv.bat respectively) eg:

CATALINA_OPTS='-Xms512m -Xmx1024m'

My guess is that setenv.bat will also be called when starting a service.I might be wrong, though, since I'm not a windows user.

How to stop a looping thread in Python?

I had a different approach. I've sub-classed a Thread class and in the constructor I've created an Event object. Then I've written custom join() method, which first sets this event and then calls a parent's version of itself.

Here is my class, I'm using for serial port communication in wxPython app:

import wx, threading, serial, Events, Queue

class PumpThread(threading.Thread):

    def __init__ (self, port, queue, parent):
        super(PumpThread, self).__init__()
        self.port = port
        self.queue = queue
        self.parent = parent

        self.serial = serial.Serial()
        self.serial.port = self.port
        self.serial.timeout = 0.5
        self.serial.baudrate = 9600
        self.serial.parity = 'N'

        self.stopRequest = threading.Event()

    def run (self):
        try:
            self.serial.open()
        except Exception, ex:
            print ("[ERROR]\tUnable to open port {}".format(self.port))
            print ("[ERROR]\t{}\n\n{}".format(ex.message, ex.traceback))
            self.stopRequest.set()
        else:
            print ("[INFO]\tListening port {}".format(self.port))
            self.serial.write("FLOW?\r")

        while not self.stopRequest.isSet():
            msg = ''
            if not self.queue.empty():
                try:
                    command = self.queue.get()
                    self.serial.write(command)
                except Queue.Empty:
                    continue

            while self.serial.inWaiting():
                char = self.serial.read(1)
                if '\r' in char and len(msg) > 1:
                    char = ''
                    #~ print('[DATA]\t{}'.format(msg))
                    event = Events.PumpDataEvent(Events.SERIALRX, wx.ID_ANY, msg)
                    wx.PostEvent(self.parent, event)
                    msg = ''
                    break
                msg += char
        self.serial.close()

    def join (self, timeout=None):
        self.stopRequest.set()
        super(PumpThread, self).join(timeout)

    def SetPort (self, serial):
        self.serial = serial

    def Write (self, msg):
        if self.serial.is_open:
            self.queue.put(msg)
        else:
            print("[ERROR]\tPort {} is not open!".format(self.port))

    def Stop(self):
        if self.isAlive():
            self.join()

The Queue is used for sending messages to the port and main loop takes responses back. I've used no serial.readline() method, because of different end-line char, and I have found the usage of io classes to be too much fuss.

Laravel, sync() - how to sync an array and also pass additional pivot fields?

$data = array();
foreach ($request->planes as $plan) {
 $data_plan = array($plan => array('dia' => $request->dia[$plan] ) );                
 array_push($data,$data_plan);    
}
$user->planes()->sync($data);

How can I hide an HTML table row <tr> so that it takes up no space?

I was having the same issue, I even added style="display: none" to each cell.

In the end I used HTML comments <!-- [HTML] -->

How to check whether a string is Base64 encoded or not

If you are using Java, you can actually use commons-codec library

import org.apache.commons.codec.binary.Base64;

String stringToBeChecked = "...";
boolean isBase64 = Base64.isArrayByteBase64(stringToBeChecked.getBytes());

[UPDATE 1] Deprecation Notice Use instead

Base64.isBase64(value);

   /**
     * Tests a given byte array to see if it contains only valid characters within the Base64 alphabet. Currently the
     * method treats whitespace as valid.
     *
     * @param arrayOctet
     *            byte array to test
     * @return {@code true} if all bytes are valid characters in the Base64 alphabet or if the byte array is empty;
     *         {@code false}, otherwise
     * @deprecated 1.5 Use {@link #isBase64(byte[])}, will be removed in 2.0.
     */
    @Deprecated
    public static boolean isArrayByteBase64(final byte[] arrayOctet) {
        return isBase64(arrayOctet);
    }

make: Nothing to be done for `all'

Remove the hello file from your folder and try again.

The all target depends on the hello target. The hello target first tries to find the corresponding file in the filesystem. If it finds it and it is up to date with the dependent files—there is nothing to do.

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

I solved this by referring properties of login user under the security, logins. then go to User Mapping and select the database then check db_datareader and db_dataweriter options.

Changing default shell in Linux

Try linux command chsh.

The detailed command is chsh -s /bin/bash. It will prompt you to enter your password. Your default login shell is /bin/bash now. You must log out and log back in to see this change.

The following is quoted from man page:

The chsh command changes the user login shell. This determines the name of the users initial login command. A normal user may only change the login shell for her own account, the superuser may change the login shell for any account

This command will change the default login shell permanently.

Note: If your user account is remote such as on Kerberos authentication (e.g. Enterprise RHEL) then you will not be able to use chsh.

How to use python numpy.savetxt to write strings and float number to an ASCII file?

The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.

import numpy as np

names  = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 ,  0.5678 ,  0.9123 ])

ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats

np.savetxt('test.txt', ab, fmt="%10s %10.3f")

Update: This example also works properly in Python 3 by using the 'U6' Unicode string dtype, when creating the ab structured array, instead of the 'S6' byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1' in Python 3.

How to create multiple output paths in Webpack config

Please don't use any workaround because it will impact build performance.

Webpack File Manager Plugin

Easy to install copy this tag on top of the webpack.config.js

const FileManagerPlugin = require('filemanager-webpack-plugin');

Install

npm install filemanager-webpack-plugin --save-dev

Add the plugin

module.exports = {
    plugins: [
        new FileManagerPlugin({
            onEnd: {
                copy: [
                    {source: 'www', destination: './vinod test 1/'},
                    {source: 'www', destination: './vinod testing 2/'},
                    {source: 'www', destination: './vinod testing 3/'},
                ],
            },
        }),
    ],
};

Screenshot

enter image description here

After installing SQL Server 2014 Express can't find local db

Just download and install LocalDB 64BIT\SqlLocalDB.msi can also solve this problem. You don't really need to uninstall and reinstall SQL Server 2014 Express with Advanced Services.

Javascript onclick hide div

Simple & Best way:

onclick="parentNode.remove()"

Deletes the complete parent from html

NoClassDefFoundError on Maven dependency

This is due to Morphia jar not being part of your output war/jar. Eclipse or local build includes them as part of classpath, but remote builds or auto/scheduled build don't consider them part of classpath.

You can include dependent jars using plugin.

Add below snippet into your pom's plugins section

    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.0.0</version>
        <configuration>
            <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
    </plugin>

Google Play Services Missing in Emulator (Android 4.4.2)

If you happen to not have the image, download it via the SDK manager:

enter image description here

Jquery split function

Javascript String objects have a split function, doesn't really need to be jQuery specific

 var str = "nice.test"
 var strs = str.split(".")

strs would be

 ["nice", "test"]

I'd be tempted to use JSON in your example though. The php could return the JSON which could easily be parsed

 success: function(data) {
   var items = JSON.parse(data)
 }

How do I copy a folder from remote to local using scp?

scp -r [email protected]:/path/to/foo /home/user/Desktop/

By not including the trailing '/' at the end of foo, you will copy the directory itself (including contents), rather than only the contents of the directory.

From man scp (See online manual)

-r Recursively copy entire directories

Warning: #1265 Data truncated for column 'pdd' at row 1

You are most likely pushing a string 'NULL' to the table, rather then an actual NULL, but other things may be going on as well, an illustration:

mysql> CREATE TABLE date_test (pdd DATE NOT NULL);
Query OK, 0 rows affected (0.11 sec)

mysql> INSERT INTO date_test VALUES (NULL);
ERROR 1048 (23000): Column 'pdd' cannot be null
mysql> INSERT INTO date_test VALUES ('NULL');
Query OK, 1 row affected, 1 warning (0.05 sec)

mysql> show warnings;
+---------+------+------------------------------------------+
| Level   | Code | Message                                  |
+---------+------+------------------------------------------+
| Warning | 1265 | Data truncated for column 'pdd' at row 1 |
+---------+------+------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM date_test;
+------------+
| pdd        |
+------------+
| 0000-00-00 |
+------------+
1 row in set (0.00 sec)

mysql> ALTER TABLE date_test MODIFY COLUMN pdd DATE NULL;
Query OK, 1 row affected (0.15 sec)
Records: 1  Duplicates: 0  Warnings: 0

mysql> INSERT INTO date_test VALUES (NULL);
Query OK, 1 row affected (0.06 sec)

mysql> SELECT * FROM date_test;
+------------+
| pdd        |
+------------+
| 0000-00-00 |
| NULL       |
+------------+
2 rows in set (0.00 sec)

How to download a file over HTTP?

In 2012, use the python requests library

>>> import requests
>>> 
>>> url = "http://download.thinkbroadband.com/10MB.zip"
>>> r = requests.get(url)
>>> print len(r.content)
10485760

You can run pip install requests to get it.

Requests has many advantages over the alternatives because the API is much simpler. This is especially true if you have to do authentication. urllib and urllib2 are pretty unintuitive and painful in this case.


2015-12-30

People have expressed admiration for the progress bar. It's cool, sure. There are several off-the-shelf solutions now, including tqdm:

from tqdm import tqdm
import requests

url = "http://download.thinkbroadband.com/10MB.zip"
response = requests.get(url, stream=True)

with open("10MB", "wb") as handle:
    for data in tqdm(response.iter_content()):
        handle.write(data)

This is essentially the implementation @kvance described 30 months ago.

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

for powerpoint and pdf files:

<html>
<input type="file" placeholder="Do you have a .ppt?" name="pptfile" id="pptfile" accept="application/pdf,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.slideshow,application/vnd.openxmlformats-officedocument.presentationml.presentation"/>
</html>

application/x-www-form-urlencoded or multipart/form-data?

TL;DR

Summary; if you have binary (non-alphanumeric) data (or a significantly sized payload) to transmit, use multipart/form-data. Otherwise, use application/x-www-form-urlencoded.


The MIME types you mention are the two Content-Type headers for HTTP POST requests that user-agents (browsers) must support. The purpose of both of those types of requests is to send a list of name/value pairs to the server. Depending on the type and amount of data being transmitted, one of the methods will be more efficient than the other. To understand why, you have to look at what each is doing under the covers.

For application/x-www-form-urlencoded, the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be: 

MyVariableOne=ValueOne&MyVariableTwo=ValueTwo

According to the specification:

[Reserved and] non-alphanumeric characters are replaced by `%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character

That means that for each non-alphanumeric byte that exists in one of our values, it's going to take three bytes to represent it. For large binary files, tripling the payload is going to be highly inefficient.

That's where multipart/form-data comes in. With this method of transmitting name/value pairs, each pair is represented as a "part" in a MIME message (as described by other answers). Parts are separated by a particular string boundary (chosen specifically so that this boundary string does not occur in any of the "value" payloads). Each part has its own set of MIME headers like Content-Type, and particularly Content-Disposition, which can give each part its "name." The value piece of each name/value pair is the payload of each part of the MIME message. The MIME spec gives us more options when representing the value payload -- we can choose a more efficient encoding of binary data to save bandwidth (e.g. base 64 or even raw binary).

Why not use multipart/form-data all the time? For short alphanumeric values (like most web forms), the overhead of adding all of the MIME headers is going to significantly outweigh any savings from more efficient binary encoding.

Numpy Resize/Rescale Image

If anyone came here looking for a simple method to scale/resize an image in Python, without using additional libraries, here's a very simple image resize function:

#simple image scaling to (nR x nC) size
def scale(im, nR, nC):
  nR0 = len(im)     # source number of rows 
  nC0 = len(im[0])  # source number of columns 
  return [[ im[int(nR0 * r / nR)][int(nC0 * c / nC)]  
             for c in range(nC)] for r in range(nR)]

Example usage: resizing a (30 x 30) image to (100 x 200):

import matplotlib.pyplot as plt

def sqr(x):
  return x*x

def f(r, c, nR, nC):
  return 1.0 if sqr(c - nC/2) + sqr(r - nR/2) < sqr(nC/4) else 0.0

# a red circle on a canvas of size (nR x nC)
def circ(nR, nC):
  return [[ [f(r, c, nR, nC), 0, 0] 
             for c in range(nC)] for r in range(nR)]

plt.imshow(scale(circ(30, 30), 100, 200))

Output: scaled image

This works to shrink/scale images, and works fine with numpy arrays.

Styling the last td in a table with css

Javascript is the only viable way to do this client side (that is, CSS won't help you). In jQuery:

$("table td:last").css("border", "none");

fatal: does not appear to be a git repository

I was facing same issue with my one of my feature branch. I tried above mentioned solution nothing worked. I resolved this issue by doing following things.

  • git pull origin feature-branch-name
  • git push

Removing a non empty directory programmatically in C or C++

How to delete a non empty folder using unlinkat() in c?

Here is my work on it:

    /*
     * Program to erase the files/subfolders in a directory given as an input
     */

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <dirent.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    void remove_dir_content(const char *path)
    {
        struct dirent *de;
        char fname[300];
        DIR *dr = opendir(path);
        if(dr == NULL)
        {
            printf("No file or directory found\n");
            return;
        }
        while((de = readdir(dr)) != NULL)
        {
            int ret = -1;
            struct stat statbuf;
            sprintf(fname,"%s/%s",path,de->d_name);
            if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
                        continue;
            if(!stat(fname, &statbuf))
            {
                if(S_ISDIR(statbuf.st_mode))
                {
                    printf("Is dir: %s\n",fname);
                    printf("Err: %d\n",ret = unlinkat(dirfd(dr),fname,AT_REMOVEDIR));
                    if(ret != 0)
                    {
                        remove_dir_content(fname);
                        printf("Err: %d\n",ret = unlinkat(dirfd(dr),fname,AT_REMOVEDIR));
                    }
                }
                else
                {
                    printf("Is file: %s\n",fname);
                    printf("Err: %d\n",unlink(fname));
                }
            }
        }
        closedir(dr);
    }
    void main()
    {
        char str[10],str1[20] = "../",fname[300]; // Use str,str1 as your directory path where it's files & subfolders will be deleted.
        printf("Enter the dirctory name: ");
        scanf("%s",str);
        strcat(str1,str);
        printf("str1: %s\n",str1);
        remove_dir_content(str1); //str1 indicates the directory path
    }

No connection could be made because the target machine actively refused it?

I just faced this right now...

enter image description here

Here on my end, I have 2 separated Visual Studio solutions (.sln)... opened each one in their own Visual Studio instance.

Solution 2 calls Solution 1 code. The problem was related to the port assigned to Solution 1. I had to change the port on solution 1 to another one and then Solution 2 started working again. So make sure you check the port assigned to your project.

How do I match any character across multiple lines in a regular expression?

If you're using Eclipse search, you can enable the "DOTALL" option to make '.' match any character including line delimiters: just add "(?s)" at the beginning of your search string. Example:

(?s).*<FooBar>

How to change app default theme to a different app theme?

Actually you should define your styles in res/values/styles.xml. I guess now you've got the following configuration:

<style name="AppBaseTheme" parent="android:Theme.Holo.Light"/>
<style name="AppTheme" parent="AppBaseTheme"/>

so if you want to use Theme.Black then change AppBaseTheme parent to android:Theme.Black or you could change app style directly in manifest file like this - android:theme="@android:style/Theme.Black". You must be lacking android namespace before style tag.

You can read more about styles and themes here.

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

What are the differences between type() and isinstance()?

To summarize the contents of other (already good!) answers, isinstance caters for inheritance (an instance of a derived class is an instance of a base class, too), while checking for equality of type does not (it demands identity of types and rejects instances of subtypes, AKA subclasses).

Normally, in Python, you want your code to support inheritance, of course (since inheritance is so handy, it would be bad to stop code using yours from using it!), so isinstance is less bad than checking identity of types because it seamlessly supports inheritance.

It's not that isinstance is good, mind you—it's just less bad than checking equality of types. The normal, Pythonic, preferred solution is almost invariably "duck typing": try using the argument as if it was of a certain desired type, do it in a try/except statement catching all exceptions that could arise if the argument was not in fact of that type (or any other type nicely duck-mimicking it;-), and in the except clause, try something else (using the argument "as if" it was of some other type).

basestring is, however, quite a special case—a builtin type that exists only to let you use isinstance (both str and unicode subclass basestring). Strings are sequences (you could loop over them, index them, slice them, ...), but you generally want to treat them as "scalar" types—it's somewhat incovenient (but a reasonably frequent use case) to treat all kinds of strings (and maybe other scalar types, i.e., ones you can't loop on) one way, all containers (lists, sets, dicts, ...) in another way, and basestring plus isinstance helps you do that—the overall structure of this idiom is something like:

if isinstance(x, basestring)
  return treatasscalar(x)
try:
  return treatasiter(iter(x))
except TypeError:
  return treatasscalar(x)

You could say that basestring is an Abstract Base Class ("ABC")—it offers no concrete functionality to subclasses, but rather exists as a "marker", mainly for use with isinstance. The concept is obviously a growing one in Python, since PEP 3119, which introduces a generalization of it, was accepted and has been implemented starting with Python 2.6 and 3.0.

The PEP makes it clear that, while ABCs can often substitute for duck typing, there is generally no big pressure to do that (see here). ABCs as implemented in recent Python versions do however offer extra goodies: isinstance (and issubclass) can now mean more than just "[an instance of] a derived class" (in particular, any class can be "registered" with an ABC so that it will show as a subclass, and its instances as instances of the ABC); and ABCs can also offer extra convenience to actual subclasses in a very natural way via Template Method design pattern applications (see here and here [[part II]] for more on the TM DP, in general and specifically in Python, independent of ABCs).

For the underlying mechanics of ABC support as offered in Python 2.6, see here; for their 3.1 version, very similar, see here. In both versions, standard library module collections (that's the 3.1 version—for the very similar 2.6 version, see here) offers several useful ABCs.

For the purpose of this answer, the key thing to retain about ABCs (beyond an arguably more natural placement for TM DP functionality, compared to the classic Python alternative of mixin classes such as UserDict.DictMixin) is that they make isinstance (and issubclass) much more attractive and pervasive (in Python 2.6 and going forward) than they used to be (in 2.5 and before), and therefore, by contrast, make checking type equality an even worse practice in recent Python versions than it already used to be.

how to convert a string to date in mysql?

STR_TO_DATE('12/31/2011', '%m/%d/%Y')

Get file version in PowerShell

Here an alternative method. It uses Get-WmiObject CIM_DATAFILE to select the version.

(Get-WmiObject -Class CIM_DataFile -Filter "Name='C:\\Windows\\explorer.exe'" | Select-Object Version).Version

How to get memory available or used in C#

For the complete system you can add the Microsoft.VisualBasic Framework as a reference;

 Console.WriteLine("You have {0} bytes of RAM",
        new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory);
        Console.ReadLine();

Using LINQ to group a list of objects

var groupedCustomerList = CustomerList
                         .GroupBy(u => u.GroupID, u=>{
                                                        u.Name = "User" + u.Name;
                                                        return u;
                                                     }, (key,g)=>g.ToList())
                         .ToList();

If you don't want to change the original data, you should add some method (kind of clone and modify) to your class like this:

public class Customer {
  public int ID { get; set; }
  public string Name { get; set; }
  public int GroupID { get; set; }
  public Customer CloneWithNamePrepend(string prepend){
    return new Customer(){
          ID = this.ID,
          Name = prepend + this.Name,
          GroupID = this.GroupID
     };
  }
}    
//Then
var groupedCustomerList = CustomerList
                         .GroupBy(u => u.GroupID, u=>u.CloneWithNamePrepend("User"), (key,g)=>g.ToList())
                         .ToList();

I think you may want to display the Customer differently without modifying the original data. If so you should design your class Customer differently, like this:

public class Customer {
  public int ID { get; set; }
  public string Name { get; set; }
  public int GroupID { get; set; }
  public string Prefix {get;set;}
  public string FullName {
    get { return Prefix + Name;}
  }            
}
//then to display the fullname, just get the customer.FullName; 
//You can also try adding some override of ToString() to your class

var groupedCustomerList = CustomerList
                         .GroupBy(u => {u.Prefix="User", return u.GroupID;} , (key,g)=>g.ToList())
                         .ToList();

How do you get the Git repository's name in some Git repository?

In general, you cannot do this. Git does not care how your git repository is named. For example, you can rename directory containing your repository (one with .git subdirectory), and git will not even notice it - everything will continue to work.

However, if you cloned it, you can use command:

git remote show origin

to display a lot of information about original remote that you cloned your repository from, and it will contain original clone URL.

If, however, you removed link to original remote using git remote rm origin, or if you created that repository using git init, such information is simply impossible to obtain - it does not exist anywhere.

Open multiple Eclipse workspaces on the Mac

One another way is just to duplicate only the "Eclipse.app" file instead of making multiple copies of entire eclipse directory. Right-Click on the "Eclipse.app" file and click the duplicate option to create a duplicate.

How can I serve static html from spring boot?

You can quickly serve static content in JAVA Spring-boot App via thymeleaf (ref: source)

I assume you have already added Spring Boot plugin apply plugin: 'org.springframework.boot' and the necessary buildscript

Then go ahead and ADD thymeleaf to your build.gradle ==>

dependencies {
    compile('org.springframework.boot:spring-boot-starter-web')
    compile("org.springframework.boot:spring-boot-starter-thymeleaf")
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

Lets assume you have added home.html at src/main/resources To serve this file, you will need to create a controller.

package com.ajinkya.th.controller;

  import org.springframework.stereotype.Controller;
  import org.springframework.web.bind.annotation.RequestMapping;

  @Controller
  public class HomePageController {

      @RequestMapping("/")
      public String homePage() {
        return "home";
      }

  }

Thats it ! Now restart your gradle server. ./gradlew bootRun

python dictionary sorting in descending order based on values

you can make use of the below code for sorting in descending order and storing to a dictionary:

        listname = []  
        for key, value in sorted(dictionaryName.iteritems(), key=lambda (k,v): (v,k),reverse=True):  
            diction= {"value":value, "key":key}  
            listname.append(diction)

Abstraction VS Information Hiding VS Encapsulation

Abstraction allows you to treat a complex process as a simple process. For example, the standard "file" abstraction treats files as a contiguous array of bytes. The user/developer does not even have to think about issues of clusters and fragmentation. (Abstraction normally appears as classes or subroutines.)

Information hiding is about protecting your abstractions from malicious/incompetent users. By restricting control of some state (hard drive allocations, for example) to the original developer, huge amounts of error handling becomes redundant. If nobody else besides the file system driver can write to the hard drive, then the file system driver knows exactly what has been written to the hard drive and where. (The usual manifestation of this concept is private and protected keywords in OO languages.)

Visual Studio - How to change a project's folder name and solution name without breaking the solution

This is what I did:

  1. Change project and solution name in Visual Studio
  2. Close the project and open the folder containing the project (The Visual studio solution name is already changed).
  3. Change the old project folder names to the new project name
  4. Open the .sln file and the change the project folder names manually from old to new folder names.
  5. Save the .sln file in the text editor
  6. Open the project again with Visual Studio and the solution is ready to modify

Select folder dialog WPF

Based on Oyun's answer, it's better to use a dependency property for the FolderName. This allows (for example) binding to sub-properties, which doesn't work in the original. Also, in my adjusted version, the dialog shows selects the initial folder.

Usage in XAML:

<Button Content="...">
   <i:Interaction.Behaviors>
      <Behavior:FolderDialogBehavior FolderName="{Binding FolderPathPropertyName, Mode=TwoWay}"/>
    </i:Interaction.Behaviors>
</Button>

Code:

using System.Windows;
using System.Windows.Forms;
using System.Windows.Interactivity;
using Button = System.Windows.Controls.Button;

public class FolderDialogBehavior : Behavior<Button>
{
    #region Attached Behavior wiring
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.Click += OnClick;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.Click -= OnClick;
        base.OnDetaching();
    }
    #endregion

    #region FolderName Dependency Property
    public static readonly DependencyProperty FolderName =
            DependencyProperty.RegisterAttached("FolderName",
            typeof(string), typeof(FolderDialogBehavior));

    public static string GetFolderName(DependencyObject obj)
    {
        return (string)obj.GetValue(FolderName);
    }

    public static void SetFolderName(DependencyObject obj, string value)
    {
        obj.SetValue(FolderName, value);
    }
    #endregion

    private void OnClick(object sender, RoutedEventArgs e)
    {
        var dialog = new FolderBrowserDialog();
        var currentPath = GetValue(FolderName) as string;
        dialog.SelectedPath = currentPath;
        var result = dialog.ShowDialog();
        if (result == DialogResult.OK)
        {
            SetValue(FolderName, dialog.SelectedPath);
        }
    }
}

How to use MySQL dump from a remote machine

No one mentions anything about the --single-transaction option. People should use it by default for InnoDB tables to ensure data consistency. In this case:

mysqldump --single-transaction -h [remoteserver.com] -u [username] -p [password] [yourdatabase] > [dump_file.sql]

This makes sure the dump is run in a single transaction that's isolated from the others, preventing backup of a partial transaction.

For instance, consider you have a game server where people can purchase gears with their account credits. There are essentially 2 operations against the database:

  1. Deduct the amount from their credits
  2. Add the gear to their arsenal

Now if the dump happens in between these operations, the next time you restore the backup would result in the user losing the purchased item, because the second operation isn't dumped in the SQL dump file.

While it's just an option, there are basically not much of a reason why you don't use this option with mysqldump.

React - How to force a function component to render?

The accepted answer is good. Just to make it easier to understand.

Example component:

export default function MyComponent(props) {

    const [updateView, setUpdateView] = useState(0);

    return (
        <>
            <span style={{ display: "none" }}>{updateView}</span>
        </>
    );
}

To force re-rendering call the code below:

setUpdateView((updateView) => ++updateView);

Create Windows service from executable

Many existing answers include human intervention at install time. This can be an error-prone process. If you have many executables wanted to be installed as services, the last thing you want to do is to do them manually at install time.

Towards the above described scenario, I created serman, a command line tool to install an executable as a service. All you need to write (and only write once) is a simple service configuration file along with your executable. Run

serman install <path_to_config_file>

will install the service. stdout and stderr are all logged. For more info, take a look at the project website.

A working configuration file is very simple, as demonstrated below. But it also has many useful features such as <env> and <persistent_env> below.

<service>
  <id>hello</id>
  <name>hello</name>
  <description>This service runs the hello application</description>

  <executable>node.exe</executable>

  <!-- 
       {{dir}} will be expanded to the containing directory of your 
       config file, which is normally where your executable locates 
   -->
  <arguments>"{{dir}}\hello.js"</arguments>

  <logmode>rotate</logmode>

  <!-- OPTIONAL FEATURE:
       NODE_ENV=production will be an environment variable 
       available to your application, but not visible outside 
       of your application
   -->
  <env name="NODE_ENV" value="production"/>

  <!-- OPTIONAL FEATURE:
       FOO_SERVICE_PORT=8989 will be persisted as an environment
       variable to the system.
   -->
  <persistent_env name="FOO_SERVICE_PORT" value="8989" />
</service>

Excel: How to check if a cell is empty with VBA?

IsEmpty() would be the quickest way to check for that.

IsNull() would seem like a similar solution, but keep in mind Null has to be assigned to the cell; it's not inherently created in the cell.

Also, you can check the cell by:

count()

counta()

Len(range("BCell").Value) = 0

How to set the Android progressbar's height?

From this tutorial:

<style name="CustomProgressBarHorizontal" parent="android:Widget.ProgressBar.Horizontal">
      <item name="android:progressDrawable">@drawable/custom_progress_bar_horizontal</item>
      <item name="android:minHeight">10dip</item>
      <item name="android:maxHeight">20dip</item>
</style>

Then simply apply the style to your progress bars or better, override the default style in your theme to style all of your app's progress bars automatically.

The difference you are seeing in the screenshots is because the phones/emulators are using a difference Android version (latest is the theme from ICS (Holo), top is the original theme).

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

I faced this issue with Eclipse (Version: 2019-12 (4.14.0)) too. The solution seems either to use IntelliJ or to use the Maven test to run such tests in Eclipse.

SQL Server PRINT SELECT (Print a select query result)?

If you're OK with viewing it as XML:

DECLARE @xmltmp xml = (SELECT * FROM table FOR XML AUTO)
PRINT CONVERT(NVARCHAR(MAX), @xmltmp)

While the OP's question as asked doesn't necessarily require this, it's useful if you got here looking to print multiple rows/columns (within reason).

Change Bootstrap input focus blue glow

Actually, in Bootstrap 4.0.0-Beta (as of October 2017) the input element isn't referenced by input[type="text"], all Bootstrap 4 properties for the input element are actually form based.

So it's using the .form-control:focus styles. The appropriate code for the "on focus" highlighting of an input element is the following:

.form-control:focus {
  color: #495057;
  background-color: #fff;
  border-color: #80bdff;
  outline: none;
}

Pretty easy to implement, just change the border-color property.

ALTER DATABASE failed because a lock could not be placed on database

Killing the process ID worked nicely for me. When running "EXEC sp_who2" Command over a new query window... and filter the results for the "busy" database , Killing the processes with "KILL " command managed to do the trick. After that all worked again.

How to Convert UTC Date To Local time Zone in MySql Select Query

In my case, where the timezones are not available on the server, this works great:

SELECT CONVERT_TZ(`date_field`,'+00:00',@@global.time_zone) FROM `table`

Note: global.time_zone uses the server timezone. You have to make sure, that it has the desired timezone!

relative path to CSS file

if the file containing that link tag is in the root dir of the project, then the correct path would be "css/styles.css"

jQuery scroll() detect when user stops scrolling

This should work:

var Timer;
$('.Scroll_Table_Div').on("scroll",function() 
{
    // do somethings

    clearTimeout(Timer);
    Timer = setTimeout(function()
    {
        console.log('scrolling is stop');
    },50);
});

Could not load file or assembly for Oracle.DataAccess in .NET

In my case the error states that the assemly

Oracle.DataAccess, Version=2.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342

is missing.

When I run gacutil.exe /l 'Oracle.DataAccess' the result was:

The Global Assembly Cache contains the following assemblies:
Oracle.DataAccess, Version=2.112.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86

Number of items = 1

At this moment I have just installed the oracle client: win32_11gR2_client

Then I installed oracle developer tools ODTwithODAC112030_deleloper_tool

Now gacutil is saying:

The Global Assembly Cache contains the following assemblies:
Oracle.DataAccess, Version=2.112.1.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86
Oracle.DataAccess, Version=2.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86

Number of items = 2

Fixed, one totally missing assembly case

How do I mock a REST template exchange?

This work on my side.

ResourceBean resourceBean = initResourceBean();
ResponseEntity<ResourceBean> responseEntity  
    = new ResponseEntity<ResourceBean>(resourceBean, HttpStatus.ACCEPTED);
when(restTemplate.exchange(
    Matchers.anyObject(), 
    Matchers.any(HttpMethod.class),
    Matchers.<HttpEntity> any(), 
    Matchers.<Class<ResourceBean>> any())
 ).thenReturn(responseEntity);

The required anti-forgery form field "__RequestVerificationToken" is not present Error in user Registration

All the other answers in here are also valid, but if none of them solve the issue it is also worth checking that the actual headers are being passed to the server.

For example, in a load balanced environment behind nginx, the default configuration is to strip out the __RequestVerificationToken header before passing the request on to the server, see: simple nginx reverse proxy seems to strip some headers

How to disable Google Chrome auto update?

For Windows users, you may follow the steps in Google Chrome Enterprise Help - Manage Chrome updates (Windows).

Just follow step 1: Install Google Update > Get the Google Update policy template & step 2: Configure auto-updates > Turn off Chrome Browser auto-updates.

If everything is configured correctly, you will see "Updates are disabled by your administrator." in Google Chrome settings About Chrome section after you reboot the pc. configured successful screenshot

Downloading folders from aws s3, cp or sync?

In case you need to use another profile, especially cross account. you need to add the profile in the config file

[profile profileName]
region = us-east-1
role_arn = arn:aws:iam::XXX:role/XXXX
source_profile = default

and then if you are accessing only a single file

aws s3 cp s3://crossAccountBucket/dir localdir --profile profileName

Get the first item from an iterable that matches a condition

In Python 3:

a = (None, False, 0, 1)
assert next(filter(None, a)) == 1

In Python 2.6:

a = (None, False, 0, 1)
assert next(iter(filter(None, a))) == 1

EDIT: I thought it was obvious, but apparently not: instead of None you can pass a function (or a lambda) with a check for the condition:

a = [2,3,4,5,6,7,8]
assert next(filter(lambda x: x%2, a)) == 3

What's the right way to decode a string that has special HTML entities in it?

If you don't want to use html/dom, you could use regex. I haven't tested this; but something along the lines of:

function parseHtmlEntities(str) {
    return str.replace(/&#([0-9]{1,3});/gi, function(match, numStr) {
        var num = parseInt(numStr, 10); // read num as normal number
        return String.fromCharCode(num);
    });
}

[Edit]

Note: this would only work for numeric html-entities, and not stuff like &oring;.

[Edit 2]

Fixed the function (some typos), test here: http://jsfiddle.net/Be2Bd/1/

Why am I getting "void value not ignored as it ought to be"?

  int a = srand(time(NULL));

The prototype for srand is void srand(unsigned int) (provided you included <stdlib.h>).
This means it returns nothing ... but you're using the value it returns (???) to assign, by initialization, to a.


Edit: this is what you need to do:

#include <stdlib.h> /* srand(), rand() */
#include <time.h>   /* time() */

#define ARRAY_SIZE 1024

void getdata(int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
        arr[i] = rand();
    }
}

int main(void)
{
    int arr[ARRAY_SIZE];
    srand(time(0));
    getdata(arr, ARRAY_SIZE);
    /* ... */
}

How can I specify system properties in Tomcat configuration on startup?

(Update: If I could delete this answer I would, although since it's accepted, I can't. I'm updating the description to provide better guidance and discourage folks from using the poor practice I outlined in the original answer).

You can specify these parameters via context or environment parameters, such as in context.xml. See the sections titled "Context Parameters" and "Environment Entries" on this page:

http://tomcat.apache.org/tomcat-5.5-doc/config/context.html

As @netjeff points out, these values will be available via the Context.lookup(String) method and not as System parameters.

Another way to do specify these values is to define variables inside of the web.xml file of the web application you're deploying (see below). As @Roberto Lo Giacco points out, this is generally considered a poor practice since a deployed artifact should not be environment specific. However, below is the configuration snippet if you really want to do this:

<env-entry>
    <env-entry-name>SMTP_PASSWORD</env-entry-name>
    <env-entry-type>java.lang.String</env-entry-type>
    <env-entry-value>abc123ftw</env-entry-value>
</env-entry>

ITSAppUsesNonExemptEncryption export compliance while internal testing?

Apple has simplified our building process, so you don't need to click on the same checkbox every time. You can streamline your iTC flow by compiling this flag into the app.

This is still the case as of 2019.

Changing capitalization of filenames in Git

File names under OS X are not case sensitive (by default). This is more of an OS problem than a Git problem. If you remove and readd the file, you should get what you want, or rename it to something else and then rename it back.

How to convert CLOB to VARCHAR2 inside oracle pl/sql

ALTER TABLE TABLE_NAME ADD (COLUMN_NAME_NEW varchar2(4000 char));
update TABLE_NAME set COLUMN_NAME_NEW = COLUMN_NAME;

ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME;
ALTER TABLE TABLE_NAME rename column COLUMN_NAME_NEW to COLUMN_NAME;

Bootstrap 3 Navbar Collapse

I had the same problem today.

Bootstrap 4

It's a native functionality: https://getbootstrap.com/docs/4.0/components/navbar/#responsive-behaviors

You have to use .navbar-expand{-sm|-md|-lg|-xl} classes:

<nav class="navbar navbar-expand-md navbar-light bg-light">

Bootstrap 3

@media (max-width: 991px) {
    .navbar-header {
        float: none;
    }
    .navbar-toggle {
        display: block;
    }
    .navbar-collapse {
        border-top: 1px solid transparent;
        box-shadow: inset 0 1px 0 rgba(255,255,255,0.1);
    }
    .navbar-collapse.collapse {
        display: none!important;
    }
    .navbar-nav {
        float: none!important;
        margin: 7.5px -15px;
    }
    .navbar-nav>li {
        float: none;
    }
    .navbar-nav>li>a {
        padding-top: 10px;
        padding-bottom: 10px;
    }
    .navbar-text {
        float: none;
        margin: 15px 0;
    }
    /* since 3.1.0 */
    .navbar-collapse.collapse.in { 
        display: block!important;
    }
    .collapsing {
        overflow: hidden!important;
    }
}

Just change 991px by 1199px for md sizes.

Demo

How to keep two folders automatically synchronized?

You need something like this: https://github.com/axkibe/lsyncd It is a tool which combines rsync and inotify - the former is a tool that mirrors, with the correct options set, a directory to the last bit. The latter tells the kernel to notify a program of changes to a directory ot file. It says:

It aggregates and combines events for a few seconds and then spawns one (or more) process(es) to synchronize the changes.

But - according to Digital Ocean at https://www.digitalocean.com/community/tutorials/how-to-mirror-local-and-remote-directories-on-a-vps-with-lsyncd - it ought to be in the Ubuntu repository!

I have similar requirements, and this tool, which I have yet to try, seems suitable for the task.

Converting a double to an int in Javascript without rounding

Similar to C# casting to (int) with just using standard lib:

Math.trunc(1.6) // 1
Math.trunc(-1.6) // -1

How to start a Process as administrator mode in C#

var pass = new SecureString();
pass.AppendChar('s');
pass.AppendChar('e');
pass.AppendChar('c');
pass.AppendChar('r');
pass.AppendChar('e');
pass.AppendChar('t');
Process.Start("notepad", "admin", pass, "");

Works also with ProcessStartInfo:

var psi = new ProcessStartInfo
{
    FileName = "notepad",
    UserName = "admin",
    Domain = "",
    Password = pass,
    UseShellExecute = false,
    RedirectStandardOutput = true,
    RedirectStandardError = true
};
Process.Start(psi);

When do I need to do "git pull", before or after "git add, git commit"?

pull = fetch + merge.

You need to commit what you have done before merging.

So pull after commit.

Terminating idle mysql connections

Manual cleanup:

You can KILL the processid.

mysql> show full processlist;
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| Id      | User       | Host              | db   | Command | Time  | State | Info                  |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+
| 1193777 | TestUser12 | 192.168.1.11:3775 | www  | Sleep   | 25946 |       | NULL                  |
+---------+------------+-------------------+------+---------+-------+-------+-----------------------+

mysql> kill 1193777;

But:

  • the php application might report errors (or the webserver, check the error logs)
  • don't fix what is not broken - if you're not short on connections, just leave them be.

Automatic cleaner service ;)

Or you configure your mysql-server by setting a shorter timeout on wait_timeout and interactive_timeout

mysql> show variables like "%timeout%";
+--------------------------+-------+
| Variable_name            | Value |
+--------------------------+-------+
| connect_timeout          | 5     |
| delayed_insert_timeout   | 300   |
| innodb_lock_wait_timeout | 50    |
| interactive_timeout      | 28800 |
| net_read_timeout         | 30    |
| net_write_timeout        | 60    |
| slave_net_timeout        | 3600  |
| table_lock_wait_timeout  | 50    |
| wait_timeout             | 28800 |
+--------------------------+-------+
9 rows in set (0.00 sec)

Set with:

set global wait_timeout=3;
set global interactive_timeout=3;

(and also set in your configuration file, for when your server restarts)

But you're treating the symptoms instead of the underlying cause - why are the connections open? If the PHP script finished, shouldn't they close? Make sure your webserver is not using connection pooling...

Understanding passport serialize deserialize

For anyone using Koa and koa-passport:

Know that the key for the user set in the serializeUser method (often a unique id for that user) will be stored in:

this.session.passport.user

When you set in done(null, user) in deserializeUser where 'user' is some user object from your database:

this.req.user OR this.passport.user

for some reason this.user Koa context never gets set when you call done(null, user) in your deserializeUser method.

So you can write your own middleware after the call to app.use(passport.session()) to put it in this.user like so:

app.use(function * setUserInContext (next) {
  this.user = this.req.user
  yield next
})

If you're unclear on how serializeUser and deserializeUser work, just hit me up on twitter. @yvanscher

Change url query string value using jQuery

If you only need to modify the page num you can replace it:

var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum);

VBA Macro On Timer style to run code every set number of seconds, i.e. 120 seconds

My solution:

Option Explicit
Public datHora As Date

Function Cronometro(action As Integer) As Integer 
'This return the seconds between two >calls
Cronometro = 0
  If action = 1 Then 'Start
    datHora = Now
  End If
  If action = 2 Then 'Time until that moment
    Cronometro = DateDiff("s", datHora, Now)
  End If
End Function

How to use? Easy...

dummy= Cronometro(1) ' This starts the timer

seconds= Cronometro(2) ' This returns the seconds between the first call and this one

Excel Define a range based on a cell value

You can also use OFFSET:

OFFSET($A$10,-$B$1+1,0,$B$1)

It moves the range $A$10 up by $B$1-1 (becomes $A$6 ($A$5)) and then resizes the range to $B$1 rows (becomes $A$6:$A$10 ($A$5:$A$10))

Distinct by property of class with LINQ

You can use grouping, and get the first car from each group:

List<Car> distinct =
  cars
  .GroupBy(car => car.CarCode)
  .Select(g => g.First())
  .ToList();

Length of the String without using length() method

Here's another way:

int length = 0;
while (!str.equals("")) {
    str = str.substring(1);
    ++length;
}

In the same spirit (although much less efficient):

String regex = "(?s)";
int length = 0;
while (!str.matches(regex)) {
    regex += ".";
    ++length;
}

Or even:

int length = 0;
while (!str.matches("(?s).{" + length + "}")) {
    ++length;
}

How to set value to form control in Reactive Forms in Angular

Setting or Updating of Reactive Forms Form Control values can be done using both patchValue and setValue. However, it might be better to use patchValue in some instances.

patchValue does not require all controls to be specified within the parameters in order to update/set the value of your Form Controls. On the other hand, setValue requires all Form Control values to be filled in, and it will return an error if any of your controls are not specified within the parameter.

In this scenario, we will want to use patchValue, since we are only updating user and questioning:

this.qService.editQue([params["id"]]).subscribe(res => {
  this.question = res;
  this.editqueForm.patchValue({
    user: this.question.user,
    questioning: this.question.questioning
  });
});

EDIT: If you feel like doing some of ES6's Object Destructuring, you may be interested to do this instead

const { user, questioning } = this.question;

this.editqueForm.patchValue({
  user,
  questioning
});

Ta-dah!

Bash script to check running process

Despite some success with the /dev/null approach in bash. When I pushed the solution to cron it failed. Checking the size of a returned command worked perfectly though. The ampersrand allows bash to exit.

#!/bin/bash
SERVICE=/path/to/my/service
result=$(ps ax|grep -v grep|grep $SERVICE)
echo ${#result}
if  ${#result}> 0 
then
        echo " Working!"
else
        echo "Not Working.....Restarting"
        /usr/bin/xvfb-run -a /opt/python27/bin/python2.7 SERVICE &
fi

Module not found: Error: Can't resolve 'core-js/es6'

Ended up to have a file named polyfill.js in projectpath\src\polyfill.js That file only contains this line: import 'core-js'; this polyfills not only es-6, but is the correct way to use core-js since version 3.0.0.

I added the polyfill.js to my webpack-file entry attribute like this:

entry: ['./src/main.scss', './src/polyfill.js', './src/main.jsx']

Works perfectly.

I also found some more information here : https://github.com/zloirock/core-js/issues/184

The library author (zloirock) claims:

ES6 changes behaviour almost all features added in ES5, so core-js/es6 entry point includes almost all of them. Also, as you wrote, it's required for fixing broken browser implementations.

(Quotation https://github.com/zloirock/core-js/issues/184 from zloirock)

So I think import 'core-js'; is just fine.

How to delete a line from a text file in C#?

Remove a block of code from multiple files

To expand on @Markus Olsson's answer, I needed to remove a block of code from multiple files. I had problems with Swedish characters in a core project, so I needed to install System.Text.CodePagesEncodingProvider nuget package and use System.Text.Encoding.GetEncoding(1252) instead of System.Text.Encoding.UTF8.

    public static void Main(string[] args)
    {
        try
        {
            var dir = @"C:\Test";
            //Get all html and htm files
            var files = DirSearch(dir);
            foreach (var file in files)
            {
                RmCode(file);
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            throw;
        }

    }

    private static void RmCode(string file)
    {
        string tempFile = Path.GetTempFileName();

        using (var sr = new StreamReader(file, Encoding.UTF8))
        using (var sw = new StreamWriter(new FileStream(tempFile, FileMode.Open, FileAccess.ReadWrite), Encoding.UTF8))
        {
            string line;

            var startOfBadCode = "<div>";
            var endOfBadCode = "</div>";
            var deleteLine = false;

            while ((line = sr.ReadLine()) != null)
            {
                if (line.Contains(startOfBadCode))
                {
                    deleteLine = true;
                }
                if (!deleteLine)
                {
                    sw.WriteLine(line);
                }

                if (line.Contains(endOfBadCode))
                {
                    deleteLine = false;
                }
            }
        }

        File.Delete(file);
        File.Move(tempFile, file);
    }

    private static List<String> DirSearch(string sDir)
    {
        List<String> files = new List<String>();
        try
        {
            foreach (string f in Directory.GetFiles(sDir))
            {
                files.Add(f);
            }
            foreach (string d in Directory.GetDirectories(sDir))
            {
                files.AddRange(DirSearch(d));
            }
        }
        catch (System.Exception excpt)
        {
            Console.WriteLine(excpt.Message);
        }

        return files.Where(s => s.EndsWith(".htm") || s.EndsWith(".html")).ToList();
    }

How to write JUnit test with Spring Autowire?

You should make another XML-spring configuration file in your test resource folder or just copy the old one, it looks fine, but if you're trying to start a web context for testing a micro service, just put the following code as your master test class and inherits from that:

@WebAppConfiguration
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath*:spring-test-config.xml")
public abstract class AbstractRestTest {
    @Autowired
    private WebApplicationContext wac;
}

Landscape printing from HTML

My solution:

<style type="text/css" media="print">
    @page { 
        size: landscape;
    }
    body { 
        writing-mode: tb-rl;
    }
</style>

This works in IE, Firefox and Chrome

What is the difference between Jupyter Notebook and JupyterLab?

This answer shows the python perspective. Jupyter supports various languages besides python.

Both Jupyter Notebook and Jupyterlab are browser compatible interactive python (i.e. python ".ipynb" files) environments, where you can divide the various portions of the code into various individually executable cells for the sake of better readability. Both of these are popular in Data Science/Scientific Computing domain.

I'd suggest you to go with Jupyterlab for the advantages over Jupyter notebooks:

  1. In Jupyterlab, you can create ".py" files, ".ipynb" files, open terminal etc. Jupyter Notebook allows ".ipynb" files while providing you the choice to choose "python 2" or "python 3".
  2. Jupyterlab can open multiple ".ipynb" files inside a single browser tab. Whereas, Jupyter Notebook will create new tab to open new ".ipynb" files every time. Hovering between various tabs of browser is tedious, thus Jupyterlab is more helpful here.

I'd recommend using PIP to install Jupyterlab.

If you can't open a ".ipynb" file using Jupyterlab on Windows system, here are the steps:

  1. Go to the file --> Right click --> Open With --> Choose another app --> More Apps --> Look for another apps on this PC --> Click.
  2. This will open a file explorer window. Now go inside your Python installation folder. You should see Scripts folder. Go inside it.
  3. Once you find jupyter-lab.exe, select that and now it will open the .ipynb files by default on your PC.

get the value of DisplayName attribute

If instead

[DisplayName("Something To Name")]

you use

[Display(Name = "Something To Name")]

Just do this:

private string GetDisplayName(Class1 class1)
{
    string displayName = string.Empty;

    string propertyName = class1.Name.GetType().Name;

    CustomAttributeData displayAttribute = class1.GetType().GetProperty(propertyName).CustomAttributes.FirstOrDefault(x => x.AttributeType.Name == "DisplayAttribute");

    if (displayAttribute != null)
    {
        displayName = displayAttribute.NamedArguments.FirstOrDefault().TypedValue.Value;
    }

    return displayName;
}

Detect and exclude outliers in Pandas data frame

This answer is similar to that provided by @tanemaki, but uses a lambda expression instead of scipy stats.

df = pd.DataFrame(np.random.randn(100, 3), columns=list('ABC'))

df[df.apply(lambda x: np.abs(x - x.mean()) / x.std() < 3).all(axis=1)]

To filter the DataFrame where only ONE column (e.g. 'B') is within three standard deviations:

df[((df.B - df.B.mean()) / df.B.std()).abs() < 3]

See here for how to apply this z-score on a rolling basis: Rolling Z-score applied to pandas dataframe

"Parameter not valid" exception loading System.Drawing.Image

all the solutions given doesnt work.. dont concentrate only on the retrieving part. luk at the inserting of the image. i did the same mistake. I tuk an image from hard disk and saved it to database. The problem lies in the insert command. luk at my fault code..:

 public bool convertImage()
    {
        try
        {
            MemoryStream ms = new MemoryStream();
            pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
            photo = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(photo, 0, photo.Length);
            return true;
        }
        catch
        {
            MessageBox.Show("image can not be converted");
            return false;
        }
    }
    public void insertImage()
    {
       // SqlConnection con = new SqlConnection();
        try
        {
            cs.Close();
            cs.Open();
            da.UpdateCommand = new SqlCommand("UPDATE All_students SET disco = " +photo+" WHERE Reg_no = '" + Convert.ToString(textBox1.Text)+ "'", cs);
            da.UpdateCommand.ExecuteNonQuery();
            cs.Close();
            cs.Open();
            int i = da.UpdateCommand.ExecuteNonQuery();
            if (i > 0)
            {
                MessageBox.Show("Successfully Inserted...");
            }

        }
        catch
        {
            MessageBox.Show("Error in Connection");
        }
        cs.Close();
    }

The above code shows succesfully inserted... but actualy its saving the image in the form of wrong datatype.. whereas the datatype must bt "image".. so i improved the code..

  public bool convertImage()
    {
        try
        {
            MemoryStream ms = new MemoryStream();
            pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
            photo = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(photo, 0, photo.Length);
            return true;
        }
        catch
        {
            MessageBox.Show("image can not be converted");
            return false;
        }
    }
    public void insertImage()
    {
       // SqlConnection con = new SqlConnection();
        try
        {
            cs.Close();
            cs.Open();
            //THIS WHERE THE CODE MUST BE CHANGED>>>>>>>>>>>>>>

            da.UpdateCommand = new SqlCommand("UPDATE All_students SET disco = @img WHERE Reg_no = '" + Convert.ToString(textBox1.Text)+ "'", cs);
            da.UpdateCommand.Parameters.Add("@img", SqlDbType.Image);//CHANGED TO IMAGE DATATYPE...
            da.UpdateCommand.Parameters["@img"].Value = photo;
            da.UpdateCommand.ExecuteNonQuery();
            cs.Close();
            cs.Open();
            int i = da.UpdateCommand.ExecuteNonQuery();
            if (i > 0)
            {
                MessageBox.Show("Successfully Inserted...");
            }

        }
        catch
        {
            MessageBox.Show("Error in Connection");
        }
        cs.Close();
    }

100% gurantee that there will be no PARAMETER NOT VALID error in retrieving....SOLVED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

What port is used by Java RMI connection?

RMI generally won't work over a firewall, since it uses unpredictable ports (it starts off on 1099, and then runs off with a random port after that).

In these situations, you generally need to resort to tunnelling RMI over HTTP, which is described well here.

What is the difference between __str__ and __repr__?

Apart from all the answers given, I would like to add few points :-

1) __repr__() is invoked when you simply write object's name on interactive python console and press enter.

2) __str__() is invoked when you use object with print statement.

3) In case, if __str__ is missing, then print and any function using str() invokes __repr__() of object.

4) __str__() of containers, when invoked will execute __repr__() method of its contained elements.

5) str() called within __str__() could potentially recurse without a base case, and error on maximum recursion depth.

6) __repr__() can call repr() which will attempt to avoid infinite recursion automatically, replacing an already represented object with ....

Textfield with only bottom border

See this JSFiddle

_x000D_
_x000D_
 input[type="text"]_x000D_
    {_x000D_
        border: 0;_x000D_
        border-bottom: 1px solid red;_x000D_
        outline: 0;_x000D_
    }
_x000D_
<form>_x000D_
        <input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
    </form>
_x000D_
_x000D_
_x000D_

Securing a password in a properties file

The poor mans compromise solution is to use a simplistic multi signature approach.

For Example the DBA sets the applications database password to a 50 character random string. TAKqWskc4ncvKaJTyDcgAHq82X7tX6GfK2fc386bmNw3muknjU

He or she give half the password to the application developer who then hard codes it into the java binary.

private String pass1 = "TAKqWskc4ncvKaJTyDcgAHq82"

The other half of the password is passed as a command line argument. the DBA gives pass2 to the system support or admin person who either enters it a application start time or puts it into the automated application start up script.

java -jar /myapplication.jar -pass2 X7tX6GfK2fc386bmNw3muknjU

When the application starts it uses pass1 + pass2 and connects to the database.

This solution has many advantages with out the downfalls mentioned.

You can safely put half the password in a command line arguments as reading it wont help you much unless you are the developer who has the other half of the password.

The DBA can also still change the second half of the password and the developer need not have to re-deploy the application.

The source code can also be semi public as reading it and the password will not give you application access.

You can further improve the situation by adding restrictions on the IP address ranges the database will accept connections from.

Properties private set;

Maybe I'm misunderstanding, but if you want truly readonly Ids why not use an actual readonly field?

public class Person
{
   public Person(int id)
   {
      m_id = id;
   }

   readonly int m_id;
   public int Id { get { return m_id; } }
}

Automated Python to Java translation

Actually, this may or may not be much help but you could write a script which created a Java class for each Python class, including method stubs, placing the Python implementation of the method inside the Javadoc

In fact, this is probably pretty easy to knock up in Python.

I worked for a company which undertook a port to Java of a huge Smalltalk (similar-ish to Python) system and this is exactly what they did. Filling in the methods was manual but invaluable, because it got you to really think about what was going on. I doubt that a brute-force method would result in nice code.

Here's another possibility: can you convert your Python to Jython more easily? Jython is just Python for the JVM. It may be possible to use a Java decompiler (e.g. JAD) to then convert the bytecode back into Java code (or you may just wish to run on a JVM). I'm not sure about this however, perhaps someone else would have a better idea.

how to get param in method post spring mvc?

You should use @RequestParam on those resources with method = RequestMethod.GET

In order to post parameters, you must send them as the request body. A body like JSON or another data representation would depending on your implementation (I mean, consume and produce MediaType).

Typically, multipart/form-data is used to upload files.

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

For chat applications or any other application that is in constant conversation with the server, WebSockets are the best option. However, you can only use WebSockets with a server that supports them, so that may limit your ability to use them if you cannot install the required libraries. In which case, you would need to use Long Polling to obtain similar functionality.

Android open camera from button

To call the camera you can use:

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivity(intent);

The image will be automatically saved in a default directory.

And you need to set the permission for the camera in your AndroidManifest.xml:

<uses-permission android:name="android.permission.CAMERA"> </uses-permission>

How to break out of a loop from inside a switch?

You could potentially use goto, but I would prefer to set a flag that stops the loop. Then break out of the switch.

How can I check if mysql is installed on ubuntu?

"mysql" may be found even if mysql and mariadb is uninstalled, but not "mysqld".

Faster than rpm -qa | grep mysqld is:

which mysqld

Failed to build gem native extension (installing Compass)

sudo gem update --system
sudo gem install compass 

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

javascript functions to show and hide divs

I usually do this with classes, that seems to force the browsers to reassess all the styling.

.hiddendiv {display:none;}
.visiblediv {display:block;}

then use;

<script>  
function show() {  
    document.getElementById('benefits').className='visiblediv';  
}  
function close() {  
    document.getElementById('benefits').className='hiddendiv';  
}    
</script>

Note the casing of "className" that trips me up a lot

LINQ query on a DataTable

Using LINQ to manipulate data in DataSet/DataTable

var results = from myRow in tblCurrentStock.AsEnumerable()
              where myRow.Field<string>("item_name").ToUpper().StartsWith(tbSearchItem.Text.ToUpper())
              select myRow;
DataView view = results.AsDataView();

The matching wildcard is strict, but no declaration can be found for element 'context:component-scan

You have not specified the schema location of the context namespace, that is the reason for this specific error:

<beans .....
  xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="
    http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">

Restricting input to textbox: allowing only numbers and decimal point

here is script that cas help you :

<script type="text/javascript">
// price text-box allow numeric and allow 2 decimal points only
function extractNumber(obj, decimalPlaces, allowNegative)
{
    var temp = obj.value;

    // avoid changing things if already formatted correctly
    var reg0Str = '[0-9]*';
    if (decimalPlaces > 0) {
        reg0Str += '\[\,\.]?[0-9]{0,' + decimalPlaces + '}';
    } else if (decimalPlaces < 0) {
        reg0Str += '\[\,\.]?[0-9]*';
    }
    reg0Str = allowNegative ? '^-?' + reg0Str : '^' + reg0Str;
    reg0Str = reg0Str + '$';
    var reg0 = new RegExp(reg0Str);
    if (reg0.test(temp)) return true;

    // first replace all non numbers
    var reg1Str = '[^0-9' + (decimalPlaces != 0 ? '.' : '') + (decimalPlaces != 0 ? ',' : '') + (allowNegative ? '-' : '') + ']';
    var reg1 = new RegExp(reg1Str, 'g');
    temp = temp.replace(reg1, '');

    if (allowNegative) {
        // replace extra negative
        var hasNegative = temp.length > 0 && temp.charAt(0) == '-';
        var reg2 = /-/g;
        temp = temp.replace(reg2, '');
        if (hasNegative) temp = '-' + temp;
    }

    if (decimalPlaces != 0) {
        var reg3 = /[\,\.]/g;
        var reg3Array = reg3.exec(temp);
        if (reg3Array != null) {
            // keep only first occurrence of .
            //  and the number of places specified by decimalPlaces or the entire string if decimalPlaces < 0
            var reg3Right = temp.substring(reg3Array.index + reg3Array[0].length);
            reg3Right = reg3Right.replace(reg3, '');
            reg3Right = decimalPlaces > 0 ? reg3Right.substring(0, decimalPlaces) : reg3Right;
            temp = temp.substring(0,reg3Array.index) + '.' + reg3Right;
        }
    }

    obj.value = temp;
}
function blockNonNumbers(obj, e, allowDecimal, allowNegative)
{
    var key;
    var isCtrl = false;
    var keychar;
    var reg;
    if(window.event) {
        key = e.keyCode;
        isCtrl = window.event.ctrlKey
    }
    else if(e.which) {
        key = e.which;
        isCtrl = e.ctrlKey;
    }

    if (isNaN(key)) return true;

    keychar = String.fromCharCode(key);

    // check for backspace or delete, or if Ctrl was pressed
    if (key == 8 || isCtrl)
    {
        return true;
    }

    reg = /\d/;
    var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
    var isFirstD = allowDecimal ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
    var isFirstC = allowDecimal ? keychar == ',' && obj.value.indexOf(',') == -1 : false;
    return isFirstN || isFirstD || isFirstC || reg.test(keychar);
}
function blockInvalid(obj)
{
    var temp=obj.value;
    if(temp=="-")
    {
        temp="";
    }

    if (temp.indexOf(".")==temp.length-1 && temp.indexOf(".")!=-1)
    {
        temp=temp+"00";
    }
    if (temp.indexOf(".")==0)
    {
        temp="0"+temp;
    }
    if (temp.indexOf(".")==1 && temp.indexOf("-")==0)
    {
        temp=temp.replace("-","-0") ;
    }
    if (temp.indexOf(",")==temp.length-1 && temp.indexOf(",")!=-1)
    {
        temp=temp+"00";
    }
    if (temp.indexOf(",")==0)
    {
        temp="0"+temp;
    }
    if (temp.indexOf(",")==1 && temp.indexOf("-")==0)
    {
        temp=temp.replace("-","-0") ;
    }
    temp=temp.replace(",",".") ;
    obj.value=temp;
}
// end of price text-box allow numeric and allow 2 decimal points only
</script>

<input type="Text" id="id" value="" onblur="extractNumber(this,2,true);blockInvalid(this);" onkeyup="extractNumber(this,2,true);" onkeypress="return blockNonNumbers(this, event, true, true);">

Have nginx access_log and error_log log to STDOUT and STDERR of master process

When running Nginx in a Docker container, be aware that a volume mounted over the log dir defeats the purpose of creating a softlink between the log files and stdout/stderr in your Dockerfile, as described in @Boeboe 's answer.

In that case you can either create the softlink in your entrypoint (executed after volumes are mounted) or not use a volume at all (e.g. when logs are already collected by a central logging system).

Usage of \b and \r in C

I have experimented many of the backslash escape characters. \n which is a new line feed can be put anywhere to bring the effect. One important thing to remember while using this character is that the operating system of the machine we are using might affect the output. As an example, I have printed a bunch of escape character and displayed the result as follow to proof that the OS will affect the output.

Code:

#include <stdio.h>
int main(void){
    printf("Hello World!");
    printf("Goodbye \a");
    printf("Hi \b");
    printf("Yo\f");
    printf("What? \t");
    printf("pewpew");
    return 0;
}

What is the color code for transparency in CSS?

Or you could just put

background-color: rgba(0,0,0,0.0);

That should solve your problem.

If a DOM Element is removed, are its listeners also removed from memory?

Just extending other answers...

Delegated events handlers will not be removed upon element removal.

$('body').on('click', '#someEl', function (event){
  console.log(event);
});

$('#someEL').remove(); // removing the element from DOM

Now check:

$._data(document.body, 'events');

Mockito: Mock private field initialization

I already found the solution to this problem which I forgot to post here.

@RunWith(PowerMockRunner.class)
@PrepareForTest({ Test.class })
public class SampleTest {

@Mock
Person person;

@Test
public void testPrintName() throws Exception {
    PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
    Test test= new Test();
    test.testMethod();
    }
}

Key points to this solution are:

  1. Running my test cases with PowerMockRunner: @RunWith(PowerMockRunner.class)

  2. Instruct Powermock to prepare Test.class for manipulation of private fields: @PrepareForTest({ Test.class })

  3. And finally mock the constructor for Person class:

    PowerMockito.mockStatic(Person.class); PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);

Batch command to move files to a new directory

Something like this might help:

SET Today=%Date:~10,4%%Date:~4,2%%Date:~7,2%
mkdir C:\Test\Backup-%Today%
move C:\Test\Log\*.* C:\Test\Backup-%Today%\
SET Today=

The important part is the first line. It takes the output of the internal DATE value and parses it into an environmental variable named Today, in the format CCYYMMDD, as in '20110407`.

The %Date:~10,4% says to extract a *substring of the Date environmental variable 'Thu 04/07/2011' (built in - type echo %Date% at a command prompt) starting at position 10 for 4 characters (2011). It then concatenates another substring of Date: starting at position 4 for 2 chars (04), and then concats two additional characters starting at position 7 (07).

*The substring value starting points are 0-based.

You may need to adjust these values depending on the date format in your locale, but this should give you a starting point.

Creating and throwing new exception

You can throw your own custom errors by extending the Exception class.

class CustomException : Exception {
    [string] $additionalData

    CustomException($Message, $additionalData) : base($Message) {
        $this.additionalData = $additionalData
    }
}

try {
    throw [CustomException]::new('Error message', 'Extra data')
} catch [CustomException] {
    # NOTE: To access your custom exception you must use $_.Exception
    Write-Output $_.Exception.additionalData

    # This will produce the error message: Didn't catch it the second time
    throw [CustomException]::new("Didn't catch it the second time", 'Extra data')
}

Debugging "Element is not clickable at point" error

Wow, a lot of answers here, and many good ones.

I hope I'll add something to this from my experience.

Well guys, in my case there was a cookie overlay hiding the element occasionally. Scrolling to the element also works; but in my humble opinion (for my case, not a panacea for everyone) the simplest solution is just to go full screen (I was running my scripts on a 3/4 of the screen window)! So here we go:

driver.manage().window().maximize();

Hope that helps!

matplotlib savefig in jpeg format

Just install pillow with pip install pillow and it will work.

Visual Studio loading symbols

For me, it seems related to breakpoints, as indicated in the accepted answer. However, I found two workarounds that did not involve deleting all the breakpoints:

  • Restarting Visual Studio seemed to fix it temporarily.
  • Clicking the "X" button to close Visual Studio while debugging causes the "Do you want to stop debugging?" message box to pop up; while this message box is up, the symbols load at ordinary speeds. Once all the symbols are loaded, you can click "No" to cancel the close.

Get selected option from select element

This worked for me:

$("#SelectedCountryId_option_selected")[0].textContent

Android ListView Text Color

  1. Create a styles file, for example: my_styles.xml and save it in res/values.
  2. Add the following code:

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
    <style name="ListFont" parent="@android:style/Widget.ListView">
        <item name="android:textColor">#FF0000</item>
        <item name="android:typeface">sans</item>
    </style>
    
    </resources>
    
  3. Add your style to your Activity definition in your AndroidManifest.xml as an android:theme attribute, and assign as value the name of the style you created. For example:

    <activity android:name="your.activityClass" android:theme="@style/ListFont">
    

NOTE: the Widget.ListView comes from here. Also check this.

Why is Android Studio reporting "URI is not registered"?

You are having this issue because you are at the wrong destination! The correct directory for the Layout resource file has to be under "res-layout" not "res-all-layout"

Convert hex string (char []) to int?

Assuming you mean it's a string, how about strtol?

With ' N ' no of nodes, how many different Binary and Binary Search Trees possible?

The correct answer should be 2nCn/(n+1) for unlabelled nodes and if the nodes are labelled then (2nCn)*n!/(n+1).

Command not found error in Bash variable assignment

Drop the spaces around the = sign:

#!/bin/bash 
STR="Hello World" 
echo $STR 

What is the difference between baud rate and bit rate?

Bit per second is what is means - rate of data transmission of ones and zeros per second are used.This is called bit per second(bit/s. However, it should not be confused with bytes per second, abbreviated as bytes/s, Bps, or B/s.

Raw throughput values are normally given in bits per second, but many software applications report transfer rates in bytes per second.

So, the standard unit for bit throughput is the bit per second, which is commonly abbreviated bit/s, bps, or b/s.

Baud is a unit of measure of changes , or transitions , that occurs in a signal in each second.

For example if the signal changes from one value to a zero value(or vice versa) one hundred times per second, that is a rate of 100 baud.

The other one measures data(the throughput of channel), and the other ones measures transitions(called signalling rates).

For example if you look at modern modems they use advanced modulation techniques that encoded more than one bit of data into each transition.

Thanks.

Reset input value in angular 2

If you want to clear the input by using the HTML ONLY, then you can do something like this:

<input type="text"
       (keyup)="0"
       #searchCollectorInput
       class="search-metrics"
       placeholder="Find">

Notice the importance of (keyup)=0 and the reference to the input of course.

Then reset it like this:

<span *ngIf="searchCollectorInput.value.length > 0"
      (click)="searchCollectorInput.value = ''"
      class="fa fa-close" ></span>

How to manually trigger validation with jQuery validate?

As written in the documentation, the way to trigger form validation programmatically is to invoke validator.form()

var validator = $( "#myform" ).validate();
validator.form();

How to define object in array in Mongoose schema correctly with 2d geo index

Thanks for the replies.

I tried the first approach, but nothing changed. Then, I tried to log the results. I just drilled down level by level, until I finally got to where the data was being displayed.

After a while I found the problem: When I was sending the response, I was converting it to a string via .toString().

I fixed that and now it works brilliantly. Sorry for the false alarm.

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

You can use native JS so you don't have to rely on external libraries.

(I will use some ES2015 syntax, a.k.a ES6, modern javascript) What is ES2015?

fetch('/api/rest/abc')
    .then(response => response.json())
    .then(data => {
        // Do what you want with your data
    });

You can also capture errors if any:

fetch('/api/rest/abc')
    .then(response => response.json())
    .then(data => {
        // Do what you want with your data
    })
    .catch(err => {
        console.error('An error ocurred', err);
    });

By default it uses GET and you don't have to specify headers, but you can do all that if you want. For further reference: Fetch API reference

jQuery: How to get to a particular child of a parent?

You could use .each() with .children() and a selector within the parenthesis:

//Grab Each Instance of Box.
$(".box").each(function(i){

    //For Each Instance, grab a child called .something1. Fade It Out.
    $(this).children(".something1").fadeOut();
});

Android Studio : unmappable character for encoding UTF-8

If above answeres did not work, then you can try my answer because it worked for me.
Here's what worked for me.

  1. Close Android Studio
  2. Go to C:\Usersyour username
  3. Locate the Android Studio settings directory named .AndroidStudioX.X (X.X being the version)
  4. C:\Users\my_user_name.AndroidStudio4.0\system\caches
  5. Delete the caches folder and open android studio

This should fix the issue.

Can I have multiple primary keys in a single table?

Some people use the term "primary key" to mean exactly an integer column that gets its values generated by some automatic mechanism. For example AUTO_INCREMENT in MySQL or IDENTITY in Microsoft SQL Server. Are you using primary key in this sense?

If so, the answer depends on the brand of database you're using. In MySQL, you can't do this, you get an error:

mysql> create table foo (
  id int primary key auto_increment, 
  id2 int auto_increment
);
ERROR 1075 (42000): Incorrect table definition; 
there can be only one auto column and it must be defined as a key

In some other brands of database, you are able to define more than one auto-generating column in a table.

Can I scroll a ScrollView programmatically in Android?

I was using the Runnable with sv.fullScroll(View.FOCUS_DOWN); It works perfectly for the immediate problem, but that method makes ScrollView take the Focus from the entire screen, if you make that AutoScroll to happen every time, no EditText will be able to receive information from the user, my solution was use a different code under the runnable:

sv.scrollTo(0, sv.getBottom() + sv.getScrollY());

making the same without losing focus on important views

greetings.

rails bundle clean

Just execute, to clean gems obsolete and remove print warningns after bundle.

_x000D_
_x000D_
bundle clean --force
_x000D_
_x000D_
_x000D_