Programs & Examples On #Session per request

How to call an element in a numpy array?

TL;DR:

Using slicing:

>>> import numpy as np
>>> 
>>> arr = np.array([[1,2,3,4,5],[6,7,8,9,10]])
>>> 
>>> arr[0,0]
1
>>> arr[1,1]
7
>>> arr[1,0]
6
>>> arr[1,-1]
10
>>> arr[1,-2]
9

In Long:

Hopefully this helps in your understanding:

>>> import numpy as np
>>> np.array([ [1,2,3], [4,5,6] ])
array([[1, 2, 3],
       [4, 5, 6]])
>>> x = np.array([ [1,2,3], [4,5,6] ])
>>> x[1][2] # 2nd row, 3rd column 
6
>>> x[1,2] # Similarly
6

But to appreciate why slicing is useful, in more dimensions:

>>> np.array([ [[1,2,3], [4,5,6]], [[7,8,9],[10,11,12]] ])
array([[[ 1,  2,  3],
        [ 4,  5,  6]],

       [[ 7,  8,  9],
        [10, 11, 12]]])
>>> x = np.array([ [[1,2,3], [4,5,6]], [[7,8,9],[10,11,12]] ])

>>> x[1][0][2] # 2nd matrix, 1st row, 3rd column
9
>>> x[1,0,2] # Similarly
9

>>> x[1][0:2][2] # 2nd matrix, 1st row, 3rd column
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: index 2 is out of bounds for axis 0 with size 2

>>> x[1, 0:2, 2] # 2nd matrix, 1st and 2nd row, 3rd column
array([ 9, 12])

>>> x[1, 0:2, 1:3] # 2nd matrix, 1st and 2nd row, 2nd and 3rd column
array([[ 8,  9],
       [11, 12]])

Retrieve a single file from a repository

If there is web interface deployed (like gitweb, cgit, Gitorious, ginatra), you can use it to download single file ('raw' or 'plain' view).

If other side enabled it, you can use git archive's '--remote=<URL>' option (and possibly limit it to a directory given file resides in), for example:

$ git archive [email protected]:foo/bar.git --prefix=path/to/ HEAD:path/to/ |  tar xvf -

How to restore the dump into your running mongodb

mongodump: To dump all the records:

mongodump --db databasename

To limit the amount of data included in the database dump, you can specify --db and --collection as options to mongodump. For example:

mongodump --collection myCollection --db test

This operation creates a dump of the collection named myCollection from the database 'test' in a dump/ subdirectory of the current working directory. NOTE: mongodump overwrites output files if they exist in the backup data folder.


mongorestore: To restore all data to the original database:

1) mongorestore --verbose \path\dump

or restore to a new database:

2) mongorestore --db databasename --verbose \path\dump\<dumpfolder>

Note: Both requires mongod instances.

How do I 'git diff' on a certain directory?

Add Beyond Compare as your difftool in Git and add an alias for diffdir as:

git config --global alias.diffdir = "difftool --dir-diff --tool=bc3 --no-prompt"

Get the gitdiff as:

git diffdir 4bc7ba80edf6  7f566710c7

Reference: Compare entire directories w git difftool + Beyond Compare

How do I implement a callback in PHP?

well... with 5.3 on the horizon, all will be better, because with 5.3, we'll get closures and with them anonymous functions

http://wiki.php.net/rfc/closures

importing jar libraries into android-studio

I see so many complicated answer.

All this confused me while I was adding my Aquery jar file in the new version of Android Studio.

This is what I did :

Copy pasted the jar file in the libs folder which is visible under Project view.

And in the build.gradle file just added this line : compile files('libs/android-query.jar')

PS : Once downloading the jar file please change its name. I changed the name to android-query.jar

How to pass a value from Vue data to href?

You need to use v-bind: or its alias :. For example,

<a v-bind:href="'/job/'+ r.id">

or

<a :href="'/job/' + r.id">

How do I set up a private Git repository on GitHub? Is it even possible?

Bitbucket - Their plans seem to be the best. They give you way more than GitHub do for free accounts - in fact, I'm still only using the free plan - no need to sign up to the paid ones; plus the interface is almost identical to GitHub.

A repository on Bitbucket can have up to five private users with unlimited public or private repositories - the only thing you seem to be paying for with the paid accounts are more users to access your private repositories.

How to SELECT the last 10 rows of an SQL table which has no ID field?

SQL tables have no implicit ordering, the order has to come from the data. Perhaps you should add a field to your table (e.g. an int counter) and re-import the data.

However that will only give the order of the import and not the data. If your data has no ordering you have to find out how to add it.

EDIT: you say

...to make sure it imported everything.

What's wrong with using row count?

How to center horizontally div inside parent div

.parent-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.child-canvas {
  flex-shrink: 0;
}

How do I unload (reload) a Python module?

The following code allows you Python 2/3 compatibility:

try:
    reload
except NameError:
    # Python 3
    from imp import reload

The you can use it as reload() in both versions which makes things simpler.

is it possible to add colors to python output?

If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.

Here an example:

print ('This is \x1b[31mred\x1b[0m.') 

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

IntelliJ IDEA "The selected directory is not a valid home for JDK"

It got this error because I had managed to clobber jdk1.8.0_60 with the jre!

How to attach source or JavaDoc in eclipse for any jar file e.g. JavaFX?

This trick worked for me in Eclipse Luna (4.4.2): For a jar file I am using (htsjdk), I packed the source in a separate jar file (named htsjdk-2.0.1-src.jar; I could do this since htsjdk is open source) and stored it in the lib-src folder of my project. In my own Java source I selected an element I was using from the jar and hit F3 (Open declaration). Eclipse opened the class file and showed the button "Attach source". I clicked the button and pointed to the src jar file I had just put into the lib-src folder. Now I get the Javadoc when hovering over anything I’m using from the jar.

What is the LD_PRELOAD trick?

Using LD_PRELOAD path, you can force the application loader to load provided shared object, over the default provided.

Developers uses this to debug their applications by providing different versions of the shared objects.

We've used it to hack certain applications, by overriding existing functions using prepared shared objects.

How do I setup the InternetExplorerDriver so it works

Another way to resolve this problem is:

Let's assume:

path_to_driver_directory = C:\Work\drivers\

driver = IEDriverServer.exe

When getting messsage about path you can always add path_to_driver_directory containing driver to the PATH environment variable. Check: http://java.com/en/download/help/path.xml

Then simply check in cmd window if driver is available - just run cmd in any location and type name of driver.

If everything works fine then you get:

C:\Users\A>IEDriverServer.exe
Started InternetExplorerDriver server (32-bit)
2.28.0.0
Listening on port 5555

Thats it.

How does java do modulus calculations with negative numbers?

To overcome this, you could add 64 (or whatever your modulus base is) to the negative value until it is positive

int k = -13;
int modbase = 64;

while (k < 0) {
    k += modbase;
}

int result = k % modbase;

The result will still be in the same equivalence class.

How do you create a static class in C++?

Consider Matt Price's solution.

  1. In C++, a "static class" has no meaning. The nearest thing is a class with only static methods and members.
  2. Using static methods will only limit you.

What you want is, expressed in C++ semantics, to put your function (for it is a function) in a namespace.

Edit 2011-11-11

There is no "static class" in C++. The nearest concept would be a class with only static methods. For example:

// header
class MyClass
{
   public :
      static void myMethod() ;
} ;

// source
void MyClass::myMethod()
{
   // etc.
}

But you must remember that "static classes" are hacks in the Java-like kind of languages (e.g. C#) that are unable to have non-member functions, so they have instead to move them inside classes as static methods.

In C++, what you really want is a non-member function that you'll declare in a namespace:

// header
namespace MyNamespace
{
   void myMethod() ;
}

// source
namespace MyNamespace
{
   void myMethod()
   {
      // etc.
   }
}

Why is that?

In C++, the namespace is more powerful than classes for the "Java static method" pattern, because:

  • static methods have access to the classes private symbols
  • private static methods are still visible (if inaccessible) to everyone, which breaches somewhat the encapsulation
  • static methods cannot be forward-declared
  • static methods cannot be overloaded by the class user without modifying the library header
  • there is nothing that can be done by a static method that can't be done better than a (possibly friend) non-member function in the same namespace
  • namespaces have their own semantics (they can be combined, they can be anonymous, etc.)
  • etc.

Conclusion: Do not copy/paste that Java/C#'s pattern in C++. In Java/C#, the pattern is mandatory. But in C++, it is bad style.

Edit 2010-06-10

There was an argument in favor to the static method because sometimes, one needs to use a static private member variable.

I disagree somewhat, as show below:

The "Static private member" solution

// HPP

class Foo
{
   public :
      void barA() ;
   private :
      void barB() ;
      static std::string myGlobal ;
} ;

First, myGlobal is called myGlobal because it is still a global private variable. A look at the CPP source will clarify that:

// CPP
std::string Foo::myGlobal ; // You MUST declare it in a CPP

void Foo::barA()
{
   // I can access Foo::myGlobal
}

void Foo::barB()
{
   // I can access Foo::myGlobal, too
}

void barC()
{
   // I CAN'T access Foo::myGlobal !!!
}

At first sight, the fact the free function barC can't access Foo::myGlobal seems a good thing from an encapsulation viewpoint... It's cool because someone looking at the HPP won't be able (unless resorting to sabotage) to access Foo::myGlobal.

But if you look at it closely, you'll find that it is a colossal mistake: Not only your private variable must still be declared in the HPP (and so, visible to all the world, despite being private), but you must declare in the same HPP all (as in ALL) functions that will be authorized to access it !!!

So using a private static member is like walking outside in the nude with the list of your lovers tattooed on your skin : No one is authorized to touch, but everyone is able to peek at. And the bonus: Everyone can have the names of those authorized to play with your privies.

private indeed... :-D

The "Anonymous namespaces" solution

Anonymous namespaces will have the advantage of making things private really private.

First, the HPP header

// HPP

namespace Foo
{
   void barA() ;
}

Just to be sure you remarked: There is no useless declaration of barB nor myGlobal. Which means that no one reading the header knows what's hidden behind barA.

Then, the CPP:

// CPP
namespace Foo
{
   namespace
   {
      std::string myGlobal ;

      void Foo::barB()
      {
         // I can access Foo::myGlobal
      }
   }

   void barA()
   {
      // I can access myGlobal, too
   }
}

void barC()
{
   // I STILL CAN'T access myGlobal !!!
}

As you can see, like the so-called "static class" declaration, fooA and fooB are still able to access myGlobal. But no one else can. And no one else outside this CPP knows fooB and myGlobal even exist!

Unlike the "static class" walking on the nude with her address book tattooed on her skin the "anonymous" namespace is fully clothed, which seems quite better encapsulated AFAIK.

Does it really matter?

Unless the users of your code are saboteurs (I'll let you, as an exercise, find how one can access to the private part of a public class using a dirty behaviour-undefined hack...), what's private is private, even if it is visible in the private section of a class declared in a header.

Still, if you need to add another "private function" with access to the private member, you still must declare it to all the world by modifying the header, which is a paradox as far as I am concerned: If I change the implementation of my code (the CPP part), then the interface (the HPP part) should NOT change. Quoting Leonidas : "This is ENCAPSULATION!"

Edit 2014-09-20

When are classes static methods are actually better than namespaces with non-member functions?

When you need to group together functions and feed that group to a template:

namespace alpha
{
   void foo() ;
   void bar() ;
}

struct Beta
{
   static void foo() ;
   static void bar() ;
};

template <typename T>
struct Gamma
{
   void foobar()
   {
      T::foo() ;
      T::bar() ;
   }
};

Gamma<alpha> ga ; // compilation error
Gamma<Beta> gb ;  // ok
gb.foobar() ;     // ok !!!

Because, if a class can be a template parameter, a namespaces cannot.

Convert a list to a data frame

A short (but perhaps not the fastest) way to do this would be to use base r, since a data frame is just a list of equal length vectors. Thus the conversion between your input list and a 30 x 132 data.frame would be:

df <- data.frame(l)

From there we can transpose it to a 132 x 30 matrix, and convert it back to a dataframe:

new_df <- data.frame(t(df))

As a one-liner:

new_df <- data.frame(t(data.frame(l)))

The rownames will be pretty annoying to look at, but you could always rename those with

rownames(new_df) <- 1:nrow(new_df)

How to set the text color of TextView in code?

Try using the following code :

holder.text.setTextColor(Color.parseColor("F00"));

Regarding C++ Include another class

C++ (and C for that matter) split the "declaration" and the "implementation" of types, functions and classes. You should "declare" the classes you need in a header-file (.h or .hpp), and put the corresponding implementation in a .cpp-file. Then, when you wish to use (access) a class somewhere, you #include the corresponding headerfile.

Example

ClassOne.hpp:

class ClassOne
{
public:
  ClassOne(); // note, no function body        
  int method(); // no body here either
private:
  int member;
};

ClassOne.cpp:

#include "ClassOne.hpp"

// implementation of constructor
ClassOne::ClassOne()
 :member(0)
{}

// implementation of "method"
int ClassOne::method()
{
  return member++;
}

main.cpp:

#include "ClassOne.hpp" // Bring the ClassOne declaration into "view" of the compiler

int main(int argc, char* argv[])
{
  ClassOne c1;
  c1.method();

  return 0;
}

notifyDataSetChange not working from custom adapter

If by any chance you landed on this thread and wondering why adapter.invaidate() or adapter.clear() methods are not present in your case then maybe because you might be using RecyclerView.Adapter instead of BaseAdapter which is used by the asker of this question. If clearing the list or arraylist not resolving your problem then it may happen that you are making two or more instances of the adapter for ex.:

MainActivity

...

adapter = new CustomAdapter(list);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);

...

and
SomeFragment

...

adapter = new CustomAdapter(newList);
adapter.notifyDataSetChanged();

...

If in the second case you are expecting a change in the list of inflated views in recycler view then it is not gonna happen as in the second time a new instance of the adapter is created which is not attached to the recycler view. Setting notifyDataSetChanged in the second adapter is not gonna change the content of recycer view. For that make a new instance of the recycler view in SomeFragment and attach it to the new instance of the adapter.

SomeFragment

...

recyclerView = new RecyclerView();
adapter = new CustomAdapter();
recyclerView.setAdapter(adapter);

...

Although, I don't recommend making multiple instances of the same adapter and recycler view.

Is there a way to iterate over a range of integers?

You can, and should, just write a for loop. Simple, obvious code is the Go way.

for i := 1; i <= 10; i++ {
    fmt.Println(i)
}

Wait 5 seconds before executing next line

This solution comes from React Native's documentation for a refresh control:

function wait(timeout) {
    return new Promise(resolve => {
        setTimeout(resolve, timeout);
    });
}

To apply this to the OP's question, you could use this function in coordination with await:

await wait(5000);
if (newState == -1) {
    alert('Done');
}

Cocoa Autolayout: content hugging vs content compression resistance priority

Content Hugging and Content Compression Resistence Priorities work for elements which can calculate their size intrinsically depending upon the contents which are coming in.

From Apple docs:

enter image description here

Get page title with Selenium WebDriver using Java

You can do it easily by using JUnit or TestNG framework. Do the assertion as below:

String actualTitle = driver.getTitle();
String expectedTitle = "Title of Page";
assertEquals(expectedTitle,actualTitle);

OR,

assertTrue(driver.getTitle().contains("Title of Page"));

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

Similar error messages will pop up when transitioning from version 5 to 6. Here is an answer for the change to rxjs-6.

Import the individual operators, then use pipe instead of chaining.

import { map, delay, catchError } from 'rxjs/operators'; 

source.pipe(
  map(x => x + x),
  delay(4000),
  catchError(err => of('error found')),
).subscribe(printResult);

Can I change the Android startActivity() transition animation?

 // CREATE anim 

 // CREATE animation,animation2  xml // animation like fade out 

  Intent myIntent1 = new Intent(getApplicationContext(), Attend.class);
  Bundle bndlanimation1 =  ActivityOptions.makeCustomAnimation(getApplicationContext(), 
  R.anim.animation, R.anim.animation2).toBundle();
  tartActivity(myIntent1, bndlanimation1);

Django ManyToMany filter()

another way to do this is by going through the intermediate table. I'd express this within the Django ORM like this:

UserZone = User.zones.through

# for a single zone
users_in_zone = User.objects.filter(
  id__in=UserZone.objects.filter(zone=zone1).values('user'))

# for multiple zones
users_in_zones = User.objects.filter(
  id__in=UserZone.objects.filter(zone__in=[zone1, zone2, zone3]).values('user'))

it would be nice if it didn't need the .values('user') specified, but Django (version 3.0.7) seems to need it.

the above code will end up generating SQL that looks something like:

SELECT * FROM users WHERE id IN (SELECT user_id FROM userzones WHERE zone_id IN (1,2,3))

which is nice because it doesn't have any intermediate joins that could cause duplicate users to be returned

MySQL - select data from database between two dates

You need to use '2011-12-07' as the end point as a date without a time default to time 00:00:00.

So what you have actually written is interpreted as:

 SELECT users.* 
 FROM   users
 WHERE  created_at >= '2011-12-01 00:00:00' 
   AND  created_at <= '2011-12-06 00:00:00'

And your time stamp is: 2011-12-06 10:45:36 which is not between those points.
Change this too:

 SELECT users.* 
 FROM   users
 WHERE  created_at >= '2011-12-01'  -- Implied 00:00:00
   AND  created_at <  '2011-12-07'  -- Implied 00:00:00 and smaller than 
                                   --                  thus any time on 06

Adding blank spaces to layout

This can by be achieved by using space or view.

Space is lightweight but not much flexible.

View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is more customizable, you can add background, draw shapes like space.

Implementing Space :

(Eg: Space For 20 vertical and 10 horizontal density pixels)

<Space
  android:layout_width="10dp"
  android:layout_height="20dp"/>

Implementing View :

(Eg: View For 20 vertical and 10 horizontal density pixels including a background color)

  <View
       android:layout_width="10dp"
       android:layout_height="20dp"
       android:background="@color/bg_color"/>

Space for string formatting using HTML entity:

&#160; for non-breakable whitespace. &#032; for regular space.

How does Python manage int and long?

Python 2.7.9 auto promotes numbers. For a case where one is unsure to use int() or long().

>>> a = int("123")
>>> type(a)
<type 'int'>
>>> a = int("111111111111111111111111111111111111111111111111111")
>>> type(a)
<type 'long'>

How to change the color of text in javafx TextField?

The CSS styles for text input controls such as TextField for JavaFX 8 are defined in the modena.css stylesheet as below. Create a custom CSS stylesheet and modify the colors as you wish. Use the CSS reference guide if you need help understanding the syntax and available attributes and values.

.text-input {
    -fx-text-fill: -fx-text-inner-color;
    -fx-highlight-fill: derive(-fx-control-inner-background,-20%);
    -fx-highlight-text-fill: -fx-text-inner-color;
    -fx-prompt-text-fill: derive(-fx-control-inner-background,-30%);
    -fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border),
        linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
    -fx-background-insets: 0, 1;
    -fx-background-radius: 3, 2;
    -fx-cursor: text;
    -fx-padding: 0.333333em 0.583em 0.333333em 0.583em; /* 4 7 4 7 */
}
.text-input:focused {
    -fx-highlight-fill: -fx-accent;
    -fx-highlight-text-fill: white;
    -fx-background-color: 
        -fx-focus-color,
        -fx-control-inner-background,
        -fx-faint-focus-color,
        linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
    -fx-background-insets: -0.2, 1, -1.4, 3;
    -fx-background-radius: 3, 2, 4, 0;
    -fx-prompt-text-fill: transparent;
}

Although using an external stylesheet is a preferred way to do the styling, you can style inline, using something like below:

textField.setStyle("-fx-text-inner-color: red;");

Allow user to select camera or gallery for image

This should take care of Tina's null outputFileUri issue:

private static final String STORED_INSTANCE_KEY_FILE_URI = "output_file_uri";

@Override
public void onSaveInstanceState( Bundle outState ) {
    super.onSaveInstanceState( outState );

    if ( outputFileUri != null ) {
        outState.putString( STORED_INSTANCE_KEY_FILE_URI, outputFileUri.toString() );
    }
}

@Override
public void onViewStateRestored( Bundle savedInstanceState ) {
    super.onViewStateRestored( savedInstanceState );

    if ( savedInstanceState != null ) {
      final String outputFileUriStr = savedInstanceState.getString( STORED_INSTANCE_KEY_FILE_URI );
      if ( outputFileUriStr != null && !outputFileUriStr.isEmpty() ) {
          outputFileUri = Uri.parse( outputFileUriStr );
      }
    }
}

Note: I'm using this code inside android.support.v4.app.Fragment your overridden methods might change depending on what Fragment/Activity version you're using.

Do fragments really need an empty constructor?

Here is my simple solution:

1 - Define your fragment

public class MyFragment extends Fragment {

    private String parameter;

    public MyFragment() {
    }

    public void setParameter(String parameter) {
        this.parameter = parameter;
    } 
}

2 - Create your new fragment and populate the parameter

    myfragment = new MyFragment();
    myfragment.setParameter("here the value of my parameter");

3 - Enjoy it!

Obviously you can change the type and the number of parameters. Quick and easy.

Find duplicate entries in a column

Using:

  SELECT t.ctn_no
    FROM YOUR_TABLE t
GROUP BY t.ctn_no
  HAVING COUNT(t.ctn_no) > 1

...will show you the ctn_no value(s) that have duplicates in your table. Adding criteria to the WHERE will allow you to further tune what duplicates there are:

  SELECT t.ctn_no
    FROM YOUR_TABLE t
   WHERE t.s_ind = 'Y'
GROUP BY t.ctn_no
  HAVING COUNT(t.ctn_no) > 1

If you want to see the other column values associated with the duplicate, you'll want to use a self join:

SELECT x.*
  FROM YOUR_TABLE x
  JOIN (SELECT t.ctn_no
          FROM YOUR_TABLE t
      GROUP BY t.ctn_no
        HAVING COUNT(t.ctn_no) > 1) y ON y.ctn_no = x.ctn_no

Is there a way to detect if a browser window is not currently active?

For a solution without jQuery check out Visibility.js which provides information about three page states

visible    ... page is visible
hidden     ... page is not visible
prerender  ... page is being prerendered by the browser

and also convenience-wrappers for setInterval

/* Perform action every second if visible */
Visibility.every(1000, function () {
    action();
});

/* Perform action every second if visible, every 60 sec if not visible */
Visibility.every(1000, 60*1000, function () {
    action();
});

A fallback for older browsers (IE < 10; iOS < 7) is also available

How can I reverse a list in Python?

Strictly speaking, the question is not how to return a list in reverse but rather how to reverse a list with an example list name array.

To reverse a list named "array" use array.reverse().

The incredibly useful slice method as described can also be used to reverse a list in place by defining the list as a sliced modification of itself using array = array[::-1].

Converting milliseconds to minutes and seconds with Javascript

this code will do a better job if you want to show hours, and centiseconds or miliseconds after seconds like 1:02:32.21 and if used in a cell phone the timer will show correct timing even after screen lock.

_x000D_
_x000D_
<div id="timer" style="font-family:monospace;">00:00<small>.00</small></div>_x000D_
_x000D_
<script>_x000D_
var d = new Date();_x000D_
var n = d.getTime();_x000D_
var startTime = n;_x000D_
_x000D_
var tm=0;_x000D_
function updateTimer(){_x000D_
  d = new Date();_x000D_
  n = d.getTime();_x000D_
  var currentTime = n;  _x000D_
  tm = (currentTime-startTime);_x000D_
  _x000D_
  //tm +=1; _x000D_
  // si el timer cuenta en centesimas de segundo_x000D_
  //tm = tm*10;_x000D_
  _x000D_
  var hours = Math.floor(tm / 1000 / 60 / 60);_x000D_
  var minutes = Math.floor(tm / 60000) % 60;_x000D_
  var seconds =  ((tm / 1000) % 60);_x000D_
  // saca los decimales ej 2 d{0,2}_x000D_
  var seconds = seconds.toString().match(/^-?\d+(?:\.\d{0,-1})?/)[0];_x000D_
  var miliseconds = ("00" + tm).slice(-3);_x000D_
  var centiseconds;_x000D_
_x000D_
  _x000D_
  // si el timer cuenta en centesimas de segundo_x000D_
  //tm = tm/10;_x000D_
_x000D_
_x000D_
  centiseconds = miliseconds/10;_x000D_
  centiseconds = (centiseconds).toString().match(/^-?\d+(?:\.\d{0,-1})?/)[0];_x000D_
_x000D_
  minutes = (minutes < 10 ? '0' : '') + minutes;_x000D_
  seconds = (seconds < 10 ? '0' : '') + seconds;_x000D_
  centiseconds = (centiseconds < 10 ? '0' : '') + centiseconds;_x000D_
  hours = hours + (hours > 0 ? ':' : '');_x000D_
  if (hours==0){_x000D_
    hours='';_x000D_
  }_x000D_
_x000D_
  document.getElementById("timer").innerHTML = hours + minutes + ':' + seconds + '<small>.' + centiseconds + '</small>';_x000D_
}_x000D_
_x000D_
var timerInterval = setInterval(updateTimer, 10);_x000D_
// clearInterval(timerInterval);_x000D_
</script>
_x000D_
_x000D_
_x000D_

Start redis-server with config file

Okay, redis is pretty user friendly but there are some gotchas.

Here are just some easy commands for working with redis on Ubuntu:

install:

sudo apt-get install redis-server

start with conf:

sudo redis-server <path to conf>
sudo redis-server config/redis.conf

stop with conf:

redis-ctl shutdown

(not sure how this shuts down the pid specified in the conf. Redis must save the path to the pid somewhere on boot)

log:

tail -f /var/log/redis/redis-server.log

Also, various example confs floating around online and on this site were beyond useless. The best, sure fire way to get a compatible conf is to copy-paste the one your installation is already using. You should be able to find it here:

/etc/redis/redis.conf

Then paste it at <path to conf>, tweak as needed and you're good to go.

Pythonic way to create a long multi-line string

You can also include variables when using """ notation:

foo = '1234'

long_string = """fosdl a sdlfklaskdf as
as df ajsdfj asdfa sld
a sdf alsdfl alsdfl """ +  foo + """ aks
asdkfkasdk fak"""

A better way is, with named parameters and .format():

body = """
<html>
<head>
</head>
<body>
    <p>Lorem ipsum.</p>
    <dl>
        <dt>Asdf:</dt>     <dd><a href="{link}">{name}</a></dd>
    </dl>
    </body>
</html>
""".format(
    link='http://www.asdf.com',
    name='Asdf',
)

print(body)

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

jQuery Ajax calls and the Html.AntiForgeryToken()

found this very clever idea from https://gist.github.com/scottrippey/3428114 for every $.ajax calls it modifies the request and add the token.

// Setup CSRF safety for AJAX:
$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    if (options.type.toUpperCase() === "POST") {
        // We need to add the verificationToken to all POSTs
        var token = $("input[name^=__RequestVerificationToken]").first();
        if (!token.length) return;

        var tokenName = token.attr("name");

        // If the data is JSON, then we need to put the token in the QueryString:
        if (options.contentType.indexOf('application/json') === 0) {
            // Add the token to the URL, because we can't add it to the JSON data:
            options.url += ((options.url.indexOf("?") === -1) ? "?" : "&") + token.serialize();
        } else if (typeof options.data === 'string' && options.data.indexOf(tokenName) === -1) {
            // Append to the data string:
            options.data += (options.data ? "&" : "") + token.serialize();
        }
    }
});

Delete last char of string

string strgroupids = string.Empty;

groupIds.ForEach(g =>
{
    strgroupids = strgroupids + g.ToString() + ",";
});

strgroupids = strgroupids.Substring(0, strgroupids.Length - 1);

Note that the use of ForEach here is normally considered "wrong" (read for example http://blogs.msdn.com/b/ericlippert/archive/2009/05/18/foreach-vs-foreach.aspx)

Using some LINQ:

string strgroupids = groupIds.Aggregate(string.Empty, (p, q) => p + q + ',');
strgroupids = strgroupids.Substring(0, str1.Length - 1);

Without end-substringing:

string strgroupids = groupIds.Aggregate(string.Empty, (p, q) => (p != string.Empty ? p + "," + q : q.ToString()));

How do I "un-revert" a reverted Git commit?

If you haven't pushed that change yet, git reset --hard HEAD^

Otherwise, reverting the revert is perfectly fine.

Another way is to git checkout HEAD^^ -- . and then git add -A && git commit.

Flexbox not working in Internet Explorer 11

See "Can I Use" for the full list of IE11 Flexbox bugs and more

There are numerous Flexbox bugs in IE11 and other browsers - see flexbox on Can I Use -> Known Issues, where the following are listed under IE11:

  • IE 11 requires a unit to be added to the third argument, the flex-basis property
  • In IE10 and IE11, containers with display: flex and flex-direction: column will not properly calculate their flexed childrens' sizes if the container has min-height but no explicit height property
  • IE 11 does not vertically align items correctly when min-height is used

Also see Philip Walton's Flexbugs list of issues and workarounds.

Indent multiple lines quickly in vi

A big selection would be:

gg=G

It is really fast, and everything gets indented ;-)

Set keyboard caret position in html textbox

Since I actually really needed this solution, and the typical baseline solution (focus the input - then set the value equal to itself) doesn't work cross-browser, I spent some time tweaking and editing everything to get it working. Building upon @kd7's code here's what I've come up with.

Enjoy! Works in IE6+, Firefox, Chrome, Safari, Opera

Cross-browser caret positioning technique (example: moving the cursor to the END)

// ** USEAGE ** (returns a boolean true/false if it worked or not)
// Parameters ( Id_of_element, caretPosition_you_want)

setCaretPosition('IDHERE', 10); // example

The meat and potatoes is basically @kd7's setCaretPosition, with the biggest tweak being if (el.selectionStart || el.selectionStart === 0), in firefox the selectionStart is starting at 0, which in boolean of course is turning to False, so it was breaking there.

In chrome the biggest issue was that just giving it .focus() wasn't enough (it kept selecting ALL of the text!) Hence, we set the value of itself, to itself el.value = el.value; before calling our function, and now it has a grasp & position with the input to use selectionStart.

function setCaretPosition(elemId, caretPos) {
    var el = document.getElementById(elemId);

    el.value = el.value;
    // ^ this is used to not only get "focus", but
    // to make sure we don't have it everything -selected-
    // (it causes an issue in chrome, and having it doesn't hurt any other browser)

    if (el !== null) {

        if (el.createTextRange) {
            var range = el.createTextRange();
            range.move('character', caretPos);
            range.select();
            return true;
        }

        else {
            // (el.selectionStart === 0 added for Firefox bug)
            if (el.selectionStart || el.selectionStart === 0) {
                el.focus();
                el.setSelectionRange(caretPos, caretPos);
                return true;
            }

            else  { // fail city, fortunately this never happens (as far as I've tested) :)
                el.focus();
                return false;
            }
        }
    }
}

"CASE" statement within "WHERE" clause in SQL Server 2008

CASE LEN('TestPerson')
    WHEN 0 THEN co.personentered  = co.personentered ELSE co.personentered LIKE '%TestPerson'

Try the following:

... and ( 
    (LEN('TestPerson') = 0 and co.personentered  = co.personentered) or
    (LEN('TestPerson') <> 0 and co.personentered LIKE '%TestPerson') ) and ...

How do you add a timer to a C# console application

Here is the code to create a simple one second timer tick:

  using System;
  using System.Threading;

  class TimerExample
  {
      static public void Tick(Object stateInfo)
      {
          Console.WriteLine("Tick: {0}", DateTime.Now.ToString("h:mm:ss"));
      }

      static void Main()
      {
          TimerCallback callback = new TimerCallback(Tick);

          Console.WriteLine("Creating timer: {0}\n", 
                             DateTime.Now.ToString("h:mm:ss"));

          // create a one second timer tick
          Timer stateTimer = new Timer(callback, null, 0, 1000);

          // loop here forever
          for (; ; )
          {
              // add a sleep for 100 mSec to reduce CPU usage
              Thread.Sleep(100);
          }
      }
  }

And here is the resulting output:

    c:\temp>timer.exe
    Creating timer: 5:22:40

    Tick: 5:22:40
    Tick: 5:22:41
    Tick: 5:22:42
    Tick: 5:22:43
    Tick: 5:22:44
    Tick: 5:22:45
    Tick: 5:22:46
    Tick: 5:22:47

EDIT: It is never a good idea to add hard spin loops into code as they consume CPU cycles for no gain. In this case that loop was added just to stop the application from closing, allowing the actions of the thread to be observed. But for the sake of correctness and to reduce the CPU usage a simple Sleep call was added to that loop.

Facebook database design?

TL;DR:

They use a stack architecture with cached graphs for everything above the MySQL bottom of their stack.

Long Answer:

I did some research on this myself because I was curious how they handle their huge amount of data and search it in a quick way. I've seen people complaining about custom made social network scripts becoming slow when the user base grows. After I did some benchmarking myself with just 10k users and 2.5 million friend connections - not even trying to bother about group permissions and likes and wall posts - it quickly turned out that this approach is flawed. So I've spent some time searching the web on how to do it better and came across this official Facebook article:

I really recommend you to watch the presentation of the first link above before continue reading. It's probably the best explanation of how FB works behind the scenes you can find.

The video and article tells you a few things:

  • They're using MySQL at the very bottom of their stack
  • Above the SQL DB there is the TAO layer which contains at least two levels of caching and is using graphs to describe the connections.
  • I could not find anything on what software / DB they actually use for their cached graphs

Let's take a look at this, friend connections are top left:

enter image description here

Well, this is a graph. :) It doesn't tell you how to build it in SQL, there are several ways to do it but this site has a good amount of different approaches. Attention: Consider that a relational DB is what it is: It's thought to store normalised data, not a graph structure. So it won't perform as good as a specialised graph database.

Also consider that you have to do more complex queries than just friends of friends, for example when you want to filter all locations around a given coordinate that you and your friends of friends like. A graph is the perfect solution here.

I can't tell you how to build it so that it will perform well but it clearly requires some trial and error and benchmarking.

Here is my disappointing test for just findings friends of friends:

DB Schema:

CREATE TABLE IF NOT EXISTS `friends` (
`id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `friend_id` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

Friends of Friends Query:

(
        select friend_id
        from friends
        where user_id = 1
    ) union (
        select distinct ff.friend_id
        from
            friends f
            join friends ff on ff.user_id = f.friend_id
        where f.user_id = 1
    )

I really recommend you to create you some sample data with at least 10k user records and each of them having at least 250 friend connections and then run this query. On my machine (i7 4770k, SSD, 16gb RAM) the result was ~0.18 seconds for that query. Maybe it can be optimized, I'm not a DB genius (suggestions are welcome). However, if this scales linear you're already at 1.8 seconds for just 100k users, 18 seconds for 1 million users.

This might still sound OKish for ~100k users but consider that you just fetched friends of friends and didn't do any more complex query like "display me only posts from friends of friends + do the permission check if I'm allowed or NOT allowed to see some of them + do a sub query to check if I liked any of them". You want to let the DB do the check on if you liked a post already or not or you'll have to do in code. Also consider that this is not the only query you run and that your have more than active user at the same time on a more or less popular site.

I think my answer answers the question how Facebook designed their friends relationship very well but I'm sorry that I can't tell you how to implement it in a way it will work fast. Implementing a social network is easy but making sure it performs well is clearly not - IMHO.

I've started experimenting with OrientDB to do the graph-queries and mapping my edges to the underlying SQL DB. If I ever get it done I'll write an article about it.

Can you autoplay HTML5 videos on the iPad?

Just set

webView.mediaPlaybackRequiresUserAction = NO;

The autoplay works for me on iOS.

Chrome extension: accessing localStorage in content script

Sometimes it may be better to use chrome.storage API. It's better then localStorage because you can:

  • store information from your content script without the need for message passing between content script and extension;
  • store your data as JavaScript objects without serializing them to JSON (localStorage only stores strings).

Here's a simple code demonstrating the use of chrome.storage. Content script gets the url of visited page and timestamp and stores it, popup.js gets it from storage area.

content_script.js

(function () {
    var visited = window.location.href;
    var time = +new Date();
    chrome.storage.sync.set({'visitedPages':{pageUrl:visited,time:time}}, function () {
        console.log("Just visited",visited)
    });
})();

popup.js

(function () {
    chrome.storage.onChanged.addListener(function (changes,areaName) {
        console.log("New item in storage",changes.visitedPages.newValue);
    })
})();

"Changes" here is an object that contains old and new value for a given key. "AreaName" argument refers to name of storage area, either 'local', 'sync' or 'managed'.

Remember to declare storage permission in manifest.json.

manifest.json

...
"permissions": [
    "storage"
 ],
...

How to put scroll bar only for modal-body?

Adding on to Carlos Calla's great answer.

The height of .modal-body must be set, BUT you can use media queries to make sure it's appropriate for the screen size.

.modal-body{
    height: 250px;
    overflow-y: auto;
}

@media (min-height: 500px) {
    .modal-body { height: 400px; }
}

@media (min-height: 800px) {
    .modal-body { height: 600px; }
}

Insert data into a view (SQL Server)

You just need to specify which columns you're inserting directly into:

INSERT INTO [dbo].[rLicenses] ([Name]) VALUES ('test')

Views can be picky like that.

Creating a batch file, for simple javac and java command execution

I've also faced a similar situation where I needed a script which can take care of javac and then java(ing) my java program. So, I came up with this BATCH script.

::  @author Rudhin Menon
::  Created on 09/06/2015
::
::  Auto-Concrete is a build tool, which monitor the file under
::  scrutiny for any changes, and compiles or runs the same once
::  it got changed.
::  
::  ========================================
::  md5sum and gawk programs are prerequisites for this script.
::  Please download them before running auto-concrete.
::  ========================================
::  
::  Happy coding ...

@echo off

:: if filename is missing
if [%1] EQU [] goto usage_message

:: Set cmd window name
title Auto-Concrete v0.2

cd versions

if %errorlevel% NEQ 0 (
    echo creating versions directory
    mkdir versions
    cd versions
)

cd ..

javac "%1"

:loop
    :: Get OLD HASH of file
    md5sum "%1" | gawk '{print $1}' > old
    set /p oldHash=<old
    copy "%1" "versions\%oldHash%.java"

    :inner_loop
    :: Get NEW HASH of the same file
    md5sum "%1" | gawk '{print $1}' > new
    set /p newHash=<new

    :: While OLD HASH and NEW HASH are the same
    :: keep comparing OLD HASH and NEW HASH
    if "%newHash%" EQU "%oldHash%" (
        :: Take rest before proceeding
        ping -w 200 0.0.0.0 >nul
        goto inner_loop
    )

    :: Once they differ, compile the source file
    :: and repeat everything again
    echo.
    echo ========= %1 changed on %DATE% at %TIME% ===========
    echo.       
    javac "%1"
goto loop

:usage_message
echo Usage : auto-concrete FILENAME.java

Above batch script will check the file for any changes and compile if any changes are done, you can tweak it for compiling whenever you want. Happy coding :)

Batch file include external file for variables

Batch uses the less than and greater than brackets as input and output pipes.

>file.ext

Using only one output bracket like above will overwrite all the information in that file.

>>file.ext

Using the double right bracket will add the next line to the file.

(
echo
echo
)<file.ext

This will execute the parameters based on the lines of the file. In this case, we are using two lines that will be typed using "echo". The left bracket touching the right parenthesis bracket means that the information from that file will be piped into those lines.

I have compiled an example-only read/write file. Below is the file broken down into sections to explain what each part does.

@echo off
echo TEST R/W
set SRU=0

SRU can be anything in this example. We're actually setting it to prevent a crash if you press Enter too fast.

set /p SRU=Skip Save? (y): 
if %SRU%==y goto read
set input=1
set input2=2
set /p input=INPUT: 
set /p input2=INPUT2: 

Now, we need to write the variables to a file.

(echo %input%)> settings.cdb
(echo %input2%)>> settings.cdb
pause

I use .cdb as a short form for "Command Database". You can use any extension. The next section is to test the code from scratch. We don't want to use the set variables that were run at the beginning of the file, we actually want them to load FROM the settings.cdb we just wrote.

:read
(
set /p input=
set /p input2=
)<settings.cdb

So, we just piped the first two lines of information that you wrote at the beginning of the file (which you have the option to skip setting the lines to check to make sure it's working) to set the variables of input and input2.

echo %input%
echo %input2%
pause
if %input%==1 goto newecho
pause
exit

:newecho
echo If you can see this, good job!
pause
exit

This displays the information that was set while settings.cdb was piped into the parenthesis. As an extra good-job motivator, pressing enter and setting the default values which we set earlier as "1" will return a good job message. Using the bracket pipes goes both ways, and is much easier than setting the "FOR" stuff. :)

Dump a NumPy array into a csv file

You can use pandas. It does take some extra memory so it's not always possible, but it's very fast and easy to use.

import pandas as pd 
pd.DataFrame(np_array).to_csv("path/to/file.csv")

if you don't want a header or index, use to_csv("/path/to/file.csv", header=None, index=None)

Show a number to two decimal places

$number = sprintf('%0.2f', $numbers); // 520.89898989 -> 520.89

This will give you 2 number after decimal.

How do you do a ‘Pause’ with PowerShell 2.0?

The solutions like cmd /c pause cause a new command interpreter to start and run in the background. Although acceptable in some cases, this isn't really ideal.

The solutions using Read-Host force the user to press Enter and are not really "any key".

This solution will give you a true "press any key to continue" interface and will not start a new interpreter, which will essentially mimic the original pause command.

Write-Host "Press any key to continue..."
[void][System.Console]::ReadKey($true)

Disable/Enable Submit Button until all forms have been filled

Here is the code

<html>
   <body>
      <input type="text" name="name" id="name" required="required"                                    aria-required="true" pattern="[a-z]{1,5}" onchange="func()">
      <script>
       function func()
       {
        var namdata=document.form1.name.value;
         if(namdata.match("[a-z]{1,5}"))
        {
         document.getElementById("but1").disabled=false;
        }
        }
        </script>
  </body>
</html>

Using Javascript

What's the fastest algorithm for sorting a linked list?

Here's an implementation that traverses the list just once, collecting runs, then schedules the merges in the same way that mergesort does.

Complexity is O(n log m) where n is the number of items and m is the number of runs. Best case is O(n) (if the data is already sorted) and worst case is O(n log n) as expected.

It requires O(log m) temporary memory; the sort is done in-place on the lists.

(updated below. commenter one makes a good point that I should describe it here)

The gist of the algorithm is:

    while list not empty
        accumulate a run from the start of the list
        merge the run with a stack of merges that simulate mergesort's recursion
    merge all remaining items on the stack

Accumulating runs doesn't require much explanation, but it's good to take the opportunity to accumulate both ascending runs and descending runs (reversed). Here it prepends items smaller than the head of the run and appends items greater than or equal to the end of the run. (Note that prepending should use strict less-than to preserve sort stability.)

It's easiest to just paste the merging code here:

    int i = 0;
    for ( ; i < stack.size(); ++i) {
        if (!stack[i])
            break;
        run = merge(run, stack[i], comp);
        stack[i] = nullptr;
    }
    if (i < stack.size()) {
        stack[i] = run;
    } else {
        stack.push_back(run);
    }

Consider sorting the list (d a g i b e c f j h) (ignoring runs). The stack states proceed as follows:

    [ ]
    [ (d) ]
    [ () (a d) ]
    [ (g), (a d) ]
    [ () () (a d g i) ]
    [ (b) () (a d g i) ]
    [ () (b e) (a d g i) ]
    [ (c) (b e) (a d g i ) ]
    [ () () () (a b c d e f g i) ]
    [ (j) () () (a b c d e f g i) ]
    [ () (h j) () (a b c d e f g i) ]

Then, finally, merge all these lists.

Note that the number of items (runs) at stack[i] is either zero or 2^i and the stack size is bounded by 1+log2(nruns). Each element is merged once per stack level, hence O(n log m) comparisons. There's a passing similarity to Timsort here, though Timsort maintains its stack using something like a Fibonacci sequence where this uses powers of two.

Accumulating runs takes advantage of any already sorted data so that best case complexity is O(n) for an already sorted list (one run). Since we're accumulating both ascending and descending runs, runs will always be at least length 2. (This reduces the maximum stack depth by at least one, paying for the cost of finding the runs in the first place.) Worst case complexity is O(n log n), as expected, for data that is highly randomized.

(Um... Second update.)

Or just see wikipedia on bottom-up mergesort.

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

These instructions are for windows machine with a single user profile for AWS. Make sure your ~/.aws/credentials file looks like this

[profile_name]
aws_access_key_id = yourAccessId
aws_secret_access_key = yourSecretKey

I had to set the AWS_DEFAULT_PROFILEenvironment variable to profile_name found in your credentials.
Then my python was able to connect. eg from here

import boto3

# Let's use Amazon S3
s3 = boto3.resource('s3')

# Print out bucket names
for bucket in s3.buckets.all():
    print(bucket.name)

Rename Files and Directories (Add Prefix)

On my system, I don't have the rename command. Here is a simple one liner. It finds all the HTML files recursively and adds prefix_ in front of their names:

for f in $(find . -name '*.html'); do mv "$f" "$(dirname "$f")/prefix_$(basename "$f")"; done

Print second last column/field in awk

It's simplest:

 awk '{print $--NF}' 

The reason the original $NF-- didn't work is because the expression is evaluated before the decrement, whereas my prefix decrement is performed before evaluation.

Safely casting long to int in Java

DONT: This is not a solution!

My first approach was:

public int longToInt(long theLongOne) {
  return Long.valueOf(theLongOne).intValue();
}

But that merely just casts the long to an int, potentially creating new Long instances or retrieving them from the Long pool.


The drawbacks

  1. Long.valueOf creates a new Long instance if the number is not within Long's pool range [-128, 127].

  2. The intValue implementation does nothing more than:

    return (int)value;
    

So this can be considered even worse than just casting the long to int.

"webxml attribute is required" error in Maven

Was your folder structure altered so the file is no-longer at /src/main/webapp/WEB-INF/web.xml ?

To resolve this issue, I gave my web folder the name webapp and placed it inside the src/main. Maven seems to look for web.xml by default at /src/main/webapp/WEB-INF/web.xml. If you do this then you don't need to explicitly tell maven where web.xml is. And if you've altered your folder structure and your build recently stopped working, this could be why.

Note: This is an old post but the posted solutions don't point out why a working build would suddenly stop working.

Working with select using AngularJS's ng-options

I hope the following will work for you.

<select class="form-control"
        ng-model="selectedOption"
        ng-options="option.name + ' (' + (option.price | currency:'USD$') + ')' for option in options">
</select>

Best way to split string into lines

  • If it looks ugly, just remove the unnecessary ToCharArray call.

  • If you want to split by either \n or \r, you've got two options:

    • Use an array literal – but this will give you empty lines for Windows-style line endings \r\n:

      var result = text.Split(new [] { '\r', '\n' });
      
    • Use a regular expression, as indicated by Bart:

      var result = Regex.Split(text, "\r\n|\r|\n");
      
  • If you want to preserve empty lines, why do you explicitly tell C# to throw them away? (StringSplitOptions parameter) – use StringSplitOptions.None instead.

How to use a variable from a cursor in the select statement of another cursor in pl/sql

Use alter session set current_schema = <username>, in your case as an execute immediate.

See Oracle's documentation for further information.

In your case, that would probably boil down to (untested)

DECLARE

   CURSOR client_cur IS
     SELECT  distinct username 
       from all_users 
      where length(username) = 3;

   -- client cursor 
   CURSOR emails_cur IS
   SELECT id, name 
     FROM org;

BEGIN

   FOR client IN client_cur LOOP

   -- ****
      execute immediate 
     'alter session set current_schema = ' || client.username;
   -- ****

      FOR email_rec in client_cur LOOP

         dbms_output.put_line(
             'Org id is ' || email_rec.id || 
             ' org nam '  || email_rec.name);

      END LOOP;

  END LOOP;
END;
/

How to convert a .eps file to a high quality 1024x1024 .jpg?

For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.

Try something like

convert -density 300 image.eps -resize 1024x1024 image.jpg

Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.

The order of the arguments matters! The -density X argument needs to go before image.eps because you want to affect the resolution that the input file is rendered at.

This is not super obvious in the manpage for convert, but is hinted at:

SYNOPSIS

convert [input-option] input-file [output-option] output-file

Iterating through populated rows

It looks like you just hard-coded the row and column; otherwise, a couple of small tweaks, and I think you're there:

Dim sh As Worksheet
Dim rw As Range
Dim RowCount As Integer

RowCount = 0

Set sh = ActiveSheet
For Each rw In sh.Rows

  If sh.Cells(rw.Row, 1).Value = "" Then
    Exit For
  End If

  RowCount = RowCount + 1

Next rw

MsgBox (RowCount)

Multiple submit buttons in the same form calling different Servlets

    function gotofirst(){
        window.location = "firstServelet.java";
}
    function gotosecond(){
        window.location = "secondServelet.java";
}
<form action="FirstServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" onclick="gotofirst()" value="FirstServlet">
    <input type="submit" onclick="gotosecond()" value="SecondServlet">
</form>

insert password into database in md5 format?

Darren Davies is partially correct in saying that you should use a salt - there are several issues with his claim that MD5 is insecure.

You've said that you have to insert the password using an Md5 hash, but that doesn't really tell us why. Is it because that's the format used when validatinb the password? Do you have control over the code which validates the password?

The thing about using a salt is that it avoids the problem where 2 users have the same password - they'll also have the same hash - not a desirable outcome. By using a diferent salt for each password then this does not arise (with very large volumes of data there is still a risk of collisions arising from 2 different passwords - but we'll ignore that for now).

So you can aither generate a random value for the salt and store that in the record too, or you could use some of the data you already hold - such as the username:

$query="INSERT INTO ptb_users (id,
        user_id,
        first_name,
        last_name,
        email )
        VALUES('NULL',
        'NULL',
        '".$firstname."',
        '".$lastname."',
        '".$email."',
        MD5('"$user_id.$password."')
        )";

(I am assuming that you've properly escaped all those strings earlier in your code)

Link entire table row?

Example: http://xxjjnn.com/linktablerow.html

Link entire row:

<table>
  <tr onclick="location.href='SomeWherrrreOverTheWebsiiiite.html'">**
    <td> ...content... </td>
    <td> ...content... </td>
    ...
  </tr>
</table>

Iff you'd like to do highlight on mouseover for the entire row, then:

<table class="nogap">
  <tr class="lovelyrow" onclick="location.href='SomeWherrrreOverTheWebsiiiite.html'">**
     ...
  </tr>
</table>

with something like the following for css, which will remove the gap between the table cells and change the background on hover:

tr.lovelyrow{
  background-color: hsl(0,0%,90%);
}

tr.lovelyrow:hover{
  background-color: hsl(0,0%,40%);
  cursor: pointer;
}

table.nogap{
  border-collapse: collapse;
}

Iff you are using Rails 3.0.9 then you might find this example code useful:

Sea has many Fish, Fish has many Scales, here is snippet of app/view/fish/index.erb

<table>
<% @fishies.each do |fish| %>
  <tr onclick="location.href='<%= sea_fish_scales_path(@sea, fish) %>'"> 
    <td><%= fish.title %></td>
  </tr>
<% end %>
</table>

with @fishies and @sea are defined in app/controllers/seas_controller.rb

How to add a fragment to a programmatically generated layout?

Below is a working code to add a fragment e.g 3 times to a vertical LinearLayout (xNumberLinear). You can change number 3 with any other number or take a number from a spinner!

for (int i = 0; i < 3; i++) {
            LinearLayout linearDummy = new LinearLayout(getActivity());
            linearDummy.setOrientation(LinearLayout.VERTICAL);
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {

                Toast.makeText(getActivity(), "This function works on newer versions of android", Toast.LENGTH_LONG).show();

            } else {
                linearDummy.setId(View.generateViewId());
            }
            fragmentManager.beginTransaction().add(linearDummy.getId(), new SomeFragment(),"someTag1").commit();

            xNumberLinear.addView(linearDummy);
        }

Where is the documentation for the values() method of Enum?

Run this

    for (Method m : sex.class.getDeclaredMethods()) {
        System.out.println(m);
    }

you will see

public static test.Sex test.Sex.valueOf(java.lang.String)
public static test.Sex[] test.Sex.values()

These are all public methods that "sex" class has. They are not in the source code, javac.exe added them

Notes:

  1. never use sex as a class name, it's difficult to read your code, we use Sex in Java

  2. when facing a Java puzzle like this one, I recommend to use a bytecode decompiler tool (I use Andrey Loskutov's bytecode outline Eclispe plugin). This will show all what's inside a class

Handlebars/Mustache - Is there a built in way to loop through the properties of an object?

It's actually quite easy to implement as a helper:

Handlebars.registerHelper('eachProperty', function(context, options) {
    var ret = "";
    for(var prop in context)
    {
        ret = ret + options.fn({property:prop,value:context[prop]});
    }
    return ret;
});

Then using it like so:

{{#eachProperty object}}
    {{property}}: {{value}}<br/>
{{/eachProperty }}

Get the string representation of a DOM node

You can create a temporary parent node, and get the innerHTML content of it:

var el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));

var tmp = document.createElement("div");
tmp.appendChild(el);
console.log(tmp.innerHTML); // <p>Test</p>

EDIT: Please see answer below about outerHTML. el.outerHTML should be all that is needed.

HTML-Tooltip position relative to mouse pointer

We can achieve the same using "Directive" in Angularjs.

            //Bind mousemove event to the element which will show tooltip
            $("#tooltip").mousemove(function(e) {
                //find X & Y coodrinates
                x = e.clientX,
                y = e.clientY;

                //Set tooltip position according to mouse position
                tooltipSpan.style.top = (y + 20) + 'px';
                tooltipSpan.style.left = (x + 20) + 'px';
            });

You can check this post for further details. http://www.ufthelp.com/2014/12/Tooltip-Directive-AngularJS.html

mysql error 1364 Field doesn't have a default values

Set a default value for Created_By (eg: empty VARCHAR) and the trigger will update the value anyways.

create table try ( 
     name varchar(8), 
     CREATED_BY varchar(40) DEFAULT '' not null
);

How to deal with INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES without uninstall?

Nothing from above worked for me. The problem for me was that I had wrong source in my Java Build Path for android-support-v7-appcompat. When you go to Project> Build Path> Configure Build Path>. Under the Source tab make sure you have android-support-v7-appcompat/gen , android-support-v7-appcompat/libs and android-support-v7-appcompat/src and nothing else. Click OK and it should work.

How to represent a DateTime in Excel

If, like me, you can't find a datetime under date or time in the format dialog, you should be able to find it in 'Custom'.

I just selected 'dd/mm/yyyy hh:mm' from 'Custom' and am happy with the results.

What is the best way to test for an empty string in Go?

It would be cleaner and less error-prone to use a function like the one below:

func empty(s string) bool {
    return len(strings.TrimSpace(s)) == 0
}

git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054

All these tips did not work for me, what worked was cloning over ssh rather that http

Reference alias (calculated in SELECT) in WHERE clause

You can do this using cross apply

SELECT c.BalanceDue AS BalanceDue
FROM Invoices
cross apply (select (InvoiceTotal - PaymentTotal - CreditTotal) as BalanceDue) as c
WHERE  c.BalanceDue  > 0;

How to make a GridLayout fit screen size

Just a quick follow up and note that it is possible now to use the support library with weighted spacing in GridLayout to achieve what you want, see:

As of API 21, GridLayout's distribution of excess space accomodates the principle of weight. In the event that no weights are specified, the previous conventions are respected and columns and rows are taken as flexible if their views specify some form of alignment within their groups. The flexibility of a view is therefore influenced by its alignment which is, in turn, typically defined by setting the gravity property of the child's layout parameters. If either a weight or alignment were defined along a given axis then the component is taken as flexible in that direction. If no weight or alignment was set, the component is instead assumed to be inflexible.

How to change a string into uppercase

>>> s = 'sdsd'
>>> s.upper()
'SDSD'

See String Methods.

JSHint and jQuery: '$' is not defined

To fix this error when using the online JSHint implementation:

  • Click "CONFIGURE" (top of the middle column on the page)
  • Enable "jQuery" (under the "ASSUME" section at the bottom)

This page didn't load Google Maps correctly. See the JavaScript console for technical details

The fix is really simple: just replace YOUR_API_KEY on the last line of your code with your actual API key!

If you don't have one, you can get it for free on the Google Developers Website.

Center image horizontally within a div

This also would do it

#imagewrapper {
    text-align:center;
}

#imagewrapper img {
    display:inline-block;
    margin:0 5px;
}

ActionBar text color

Here Style.xml is like

 <resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="actionBarTheme">@style/MyTheme</item>
</style>


 <style name="MyTheme" parent="@android:style/Theme.Holo.Light">
    <item name="android:actionBarStyle">@style/AppTheme.ActionBarStyle</item>
</style>

<style name="AppTheme.ActionBarStyle" parent="@android:style/Widget.Holo.Light.ActionBar">
    <item name="android:titleTextStyle">@style/AppTheme.ActionBar.TitleTextStyle</item>
</style>

<style name="AppTheme.ActionBar.TitleTextStyle" parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title">
    <item name="android:textColor">@color/colorBlack</item>
</style>

You should add

<item name="actionBarTheme">@style/MyTheme</item> 

in AppTheme

Using setDate in PreparedStatement

The problem you're having is that you're passing incompatible formats from a formatted java.util.Date to construct an instance of java.sql.Date, which don't behave in the same way when using valueOf() since they use different formats.

I also can see that you're aiming to persist hours and minutes, and I think that you'd better change the data type to java.sql.Timestamp, which supports hours and minutes, along with changing your database field to DATETIME or similar (depending on your database vendor).

Anyways, if you want to change from java.util.Date to java.sql.Date, I suggest to use

java.util.Date date = Calendar.getInstance().getTime();
java.sql.Date sqlDate = new java.sql.Date(date.getTime()); 
// ... more code here
prs.setDate(sqlDate);

How do I represent a time only value in .NET?

As others have said, you can use a DateTime and ignore the date, or use a TimeSpan. Personally I'm not keen on either of these solutions, as neither type really reflects the concept you're trying to represent - I regard the date/time types in .NET as somewhat on the sparse side which is one of the reasons I started Noda Time. In Noda Time, you can use the LocalTime type to represent a time of day.

One thing to consider: the time of day is not necessarily the length of time since midnight on the same day...

(As another aside, if you're also wanting to represent a closing time of a shop, you may find that you want to represent 24:00, i.e. the time at the end of the day. Most date/time APIs - including Noda Time - don't allow that to be represented as a time-of-day value.)

How can I align text directly beneath an image?

In order to be able to justify the text, you need to know the width of the image. You can just use the normal width of the image, or use a different width, but IE 6 might get cranky at you and not scale.

Here's what you need:

<style type="text/css">
#container { width: 100px; //whatever width you want }

#image {width: 100%; //fill up whole div }

#text { text-align: justify; }    
</style>

 <div id="container"> 
     <img src="" id="image" /> 
     <p id="text">oooh look! text!</p> 
 </div>

CSS: How can I set image size relative to parent height?

you can use flex box for it.. this will solve your problem

.image-parent 
{
     height:33px; 
     display:flex; 
}

Validate email address textbox using JavaScript

You should use below regex which have tested all possible email combination

     function validate(email) {
            var reg = "^[a-zA-Z0-9]+(\.[_a-zA-Z0-9]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,15})$";
            //var address = document.getElementById[email].value;
            if (reg.test(email) == false) 
            {
                alert('Invalid Email Address');
                return (false);
            }  
     }

Bonus tip if you're using this in Input tag than you can directly add the regex in that tag example

<input type="text"  
       name="email" 
       class="form-control"
       placeholder="Email" 
       required 
       pattern="^[a-zA-Z0-9]+(\.[_a-zA-Z0-9]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,15})$"/>

Above you can see two attribute required & pattern in

required make sure it input block have data @time of submit &
pattern make sure it input tag validate based in pattern(regex) @time of submit

For more info you can go throw doc

Normalize numpy array columns in python

If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.

Starting with your example array:

import numpy as np

x = np.array([[1000,  10,   0.5],
              [ 765,   5,  0.35],
              [ 800,   7,  0.09]])

x_normed = x / x.max(axis=0)

print(x_normed)
# [[ 1.     1.     1.   ]
#  [ 0.765  0.5    0.7  ]
#  [ 0.8    0.7    0.18 ]]

x.max(0) takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size (ncols,) containing the maximum value in each column. You can then divide x by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.


If x contains negative values you would need to subtract the minimum first:

x_normed = (x - x.min(0)) / x.ptp(0)

Here, x.ptp(0) returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.

Disable XML validation in Eclipse

Window > Preferences > Validation > uncheck XML Validator Manual and Build enter image description here

Proper use of const for defining functions in JavaScript

There are some very important benefits to the use of const and some would say it should be used wherever possible because of how deliberate and indicative it is.

It is, as far as I can tell, the most indicative and predictable declaration of variables in JavaScript, and one of the most useful, BECAUSE of how constrained it is. Why? Because it eliminates some possibilities available to var and let declarations.

What can you infer when you read a const? You know all of the following just by reading the const declaration statement, AND without scanning for other references to that variable:

  • the value is bound to that variable (although its underlying object is not deeply immutable)
  • it can’t be accessed outside of its immediately containing block
  • the binding is never accessed before declaration, because of Temporal Dead Zone (TDZ) rules.

The following quote is from an article arguing the benefits of let and const. It also more directly answers your question about the keyword's constraints/limits:

Constraints such as those offered by let and const are a powerful way of making code easier to understand. Try to accrue as many of these constraints as possible in the code you write. The more declarative constraints that limit what a piece of code could mean, the easier and faster it is for humans to read, parse, and understand a piece of code in the future.

Granted, there’s more rules to a const declaration than to a var declaration: block-scoped, TDZ, assign at declaration, no reassignment. Whereas var statements only signal function scoping. Rule-counting, however, doesn’t offer a lot of insight. It is better to weigh these rules in terms of complexity: does the rule add or subtract complexity? In the case of const, block scoping means a narrower scope than function scoping, TDZ means that we don’t need to scan the scope backwards from the declaration in order to spot usage before declaration, and assignment rules mean that the binding will always preserve the same reference.

The more constrained statements are, the simpler a piece of code becomes. As we add constraints to what a statement might mean, code becomes less unpredictable. This is one of the biggest reasons why statically typed programs are generally easier to read than dynamically typed ones. Static typing places a big constraint on the program writer, but it also places a big constraint on how the program can be interpreted, making its code easier to understand.

With these arguments in mind, it is recommended that you use const where possible, as it’s the statement that gives us the least possibilities to think about.

Source: https://ponyfoo.com/articles/var-let-const

Change column type in pandas

this below code will change datatype of column.

df[['col.name1', 'col.name2'...]] = df[['col.name1', 'col.name2'..]].astype('data_type')

in place of data type you can give your datatype .what do you want like str,float,int etc.

MySQL - ERROR 1045 - Access denied

use this command to check the possible output

mysql> select user,host,password from mysql.user;

output

mysql> select user,host,password from mysql.user;
+-------+-----------------------+-------------------------------------------+
| user  | host                  | password                                  |
+-------+-----------------------+-------------------------------------------+
| root  | localhost             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | 127.0.0.1             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| admin | localhost             | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| admin | %                     |                                           |
+-------+-----------------------+-------------------------------------------+
5 rows in set (0.00 sec)
  1. In this user admin will not be allowed to login from another host though you have granted permission. the reason is that user admin is not identified by any password.
  2. Grant the user admin with password using GRANT command once again

    mysql> GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED by 'password'
    

then check the GRANT LIST the out put will be like his

mysql> select user,host,password from mysql.user;

+-------+-----------------------+-------------------------------------------+
| user  | host                  | password                                  |
+-------+-----------------------+-------------------------------------------+
| root  | localhost             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | localhost.localdomain | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| root  | 127.0.0.1             | *8232A1298A49F710DBEE0B330C42EEC825D4190A |
| admin | localhost             | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| admin | %                     | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
+-------+-----------------------+-------------------------------------------+
5 rows in set (0.00 sec)

if the desired user for example user 'admin' is need to be allowed login then use once GRANT command and execute the command.

Now the user should be allowed to login.

How to fill Matrix with zeros in OpenCV?

You can use this to fill zeroes in a Mat object already containing data:

image1 = Scalar::all(0);

For eg, if you use it this way:

Mat image,image1;
image = imread("IMG_20160107_185956.jpg", CV_LOAD_IMAGE_COLOR);   // Read the file

if(! image.data )                              // Check for invalid input
{
    cout <<  "Could not open or find the image" << std::endl ;
    return -1;
}
cvtColor(image,image1,CV_BGR2GRAY);
image1 = Scalar::all(0);

It will work fine. But you cannot use this for uninitialised Mat. For that you can go for other options mentioned in above answers, like

Mat drawing = Mat::zeros( image.size(), CV_8UC3 );

Java error: Implicit super constructor is undefined for default constructor

You get this error because a class which has no constructor has a default constructor, which is argument-less and is equivalent to the following code:

public ACSubClass() {
    super();
}

However since your BaseClass declares a constructor (and therefore doesn't have the default, no-arg constructor that the compiler would otherwise provide) this is illegal - a class that extends BaseClass can't call super(); because there is not a no-argument constructor in BaseClass.

This is probably a little counter-intuitive because you might think that a subclass automatically has any constructor that the base class has.

The simplest way around this is for the base class to not declare a constructor (and thus have the default, no-arg constructor) or have a declared no-arg constructor (either by itself or alongside any other constructors). But often this approach can't be applied - because you need whatever arguments are being passed into the constructor to construct a legit instance of the class.

How to copy and edit files in Android shell?

If you just want to append to a file, e.g. to add some lines to a configuration file, inbuilt shell commands are enough:

adb shell
cat >> /path/to/file <<EOF
some text to append
a second line of text to append
EOF
exit

In the above, replace /path/to/file with the file you want to edit. You'll need to have write permission on the file, which implies root access if you're editing a system file. Secondly, replace some text to append and a second line of text to append with the lines you want to add.

How do I tell a Python script to use a particular version

You can add a shebang line the to the top of the script:

#!/usr/bin/env python2.7

But that will only work when executing as ./my_program.py.

If you execute as python my_program.py, then the whatever Python version that which python returns will be used.

In re: to virtualenv use: virtualenv -p /usr/bin/python3.2 or whatever to set it up to use that Python executable.

Run a Java Application as a Service on Linux

You can use Thrift server or JMX to communicate with your Java service.

How to pass data between fragments

Why don't you use a Bundle. From your first fragment, here's how to set it up:

Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putInt(key, value);
fragment.setArguments(bundle);

Then in your second Fragment, retrieve the data using:

Bundle bundle = this.getArguments();
int myInt = bundle.getInt(key, defaultValue);

Bundle has put methods for lots of data types. Please see http://developer.android.com/reference/android/os/Bundle.html

What is the default stack size, can it grow, how does it work with garbage collection?

How much a stack can grow?

You can use a VM option named ss to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M to set the maximum of stack size to 1M.

Each thread has at least one stack. Some Java Virtual Machines(JVM) put Java stack(Java method calls) and native stack(Native method calls in VM) into one stack, and perform stack unwinding using a Managed to Native Frame, known as M2NFrame. Some JVMs keep two stacks separately. The Xss set the size of the Java Stack in most cases.

For many JVMs, they put different default values for stack size on different platforms.

Can we limit this growth?

When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on java stack affects the performance some time(cache miss).

Does stack has some default minimum value or default maximum value?

As I said before, different VMs are different, and may change over versions. See here.

how does garbage collection work on stack?

Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.

This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .net. The GC on oracle jvm is quite similar so I think that might also help you.

How to run a single RSpec test?

For single example of spec file you need to add line number at the last , For Example

rspec spec/controllers/api/v1/card_list_controller_spec.rb:35

For single file you can specify your file path, For Example

rspec spec/controllers/api/v1/card_list_controller_spec.rb

For Whole Rspec Example in spec folder, you can try with this command

bundle exec rspec spec

How can I loop through a List<T> and grab each item?

The low level iterator manipulate code:

List<Money> myMoney = new List<Money>
{
    new Money{amount = 10, type = "US"},
    new Money{amount = 20, type = "US"}
};
using (var enumerator = myMoney.GetEnumerator())
{
    while (enumerator.MoveNext())
    {
        var element = enumerator.Current;
        Console.WriteLine(element.amount);
    }
}

Storing and retrieving datatable from session

To store DataTable in Session:

DataTable dtTest = new DataTable();
Session["dtTest"] = dtTest; 

To retrieve DataTable from Session:

DataTable dt = (DataTable) Session["dtTest"];

How to create a popup windows in javafx

Have you looked into ControlsFx Popover control.


import org.controlsfx.control.PopOver;
import org.controlsfx.control.PopOver.ArrowLocation;

private PopOver item;

final Scene scene = addItemButton.getScene();

final Point2D windowCoord = new Point2D(scene.getWindow()
        .getX(), scene.getWindow().getY());

final Point2D sceneCoord = new Point2D(scene.getX(), scene.
                getY());

final Point2D nodeCoord = addItemButton.localToScene(0.0,
                        0.0);
final double clickX = Math.round(windowCoord.getX()
    + sceneCoord.getY() + nodeCoord.getX());

final double clickY = Math.round(windowCoord.getY()
        + sceneCoord.getY() + nodeCoord.getY());
item.setContentNode(addItemScreen);
item.setArrowLocation(ArrowLocation.BOTTOM_LEFT);
item.setCornerRadius(4);                            
item.setDetachedTitle("Add New Item");
item.show(addItemButton.getParent(), clickX, clickY);

This is only an example but a PopOver sounds like it could accomplish what you want. Check out the documentation for more info.

Important note: ControlsFX will only work on JavaFX 8.0 b118 or later.

Convert Java object to XML string

Using ByteArrayOutputStream

public static String printObjectToXML(final Object object) throws TransformerFactoryConfigurationError,
        TransformerConfigurationException, SOAPException, TransformerException
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLEncoder xmlEncoder = new XMLEncoder(baos);
    xmlEncoder.writeObject(object);
    xmlEncoder.close();

    String xml = baos.toString();
    System.out.println(xml);

    return xml.toString();
}

Sending JWT token in the headers with Postman

In Postman latest version(7++) may be there is no Bearer field in Authorization So go to Header tab

select key as Authorization and in value write JWT

Bootstrap control with multiple "data-toggle"

Since tooltip is not initialized automatically, you can make changes in your initialization of the tooltip. I did mine like this:

$(document).ready(function() {
    $('body').tooltip({
        selector: "[data-tooltip=tooltip]",
        container: "body"
    });
});

with this markup:

<button type="button" data-target="#myModal" data-toggle="modal" data-tooltip="tooltip" class="btn btn-info" title="Your tooltip">Text here</button>

Notice the data-tooltip.

Update

Or simply,

$('[data-tooltip="tooltip"]').tooltip();

ASP.NET MVC: No parameterless constructor defined for this object

All of the answers say to create a parameters less constructor which isn't ideal if you don't want any other devs using it and only the model binder.

The attribute [Obsolete("For model binding only", true)] above a public constructor will throw a compiler error if another dev tries to use this. Took me ages to find this, hope it helps someone.

Datatype for storing ip address in SQL Server

The technically correct way to store IPv4 is binary(4), since that is what it actually is (no, not even an INT32/INT(4), the numeric textual form that we all know and love (255.255.255.255) being just the display conversion of its binary content).

If you do it this way, you will want functions to convert to and from the textual-display format:

Here's how to convert the textual display form to binary:

CREATE FUNCTION dbo.fnBinaryIPv4(@ip AS VARCHAR(15)) RETURNS BINARY(4)
AS
BEGIN
    DECLARE @bin AS BINARY(4)

    SELECT @bin = CAST( CAST( PARSENAME( @ip, 4 ) AS INTEGER) AS BINARY(1))
                + CAST( CAST( PARSENAME( @ip, 3 ) AS INTEGER) AS BINARY(1))
                + CAST( CAST( PARSENAME( @ip, 2 ) AS INTEGER) AS BINARY(1))
                + CAST( CAST( PARSENAME( @ip, 1 ) AS INTEGER) AS BINARY(1))

    RETURN @bin
END
go

And here's how to convert the binary back to the textual display form:

CREATE FUNCTION dbo.fnDisplayIPv4(@ip AS BINARY(4)) RETURNS VARCHAR(15)
AS
BEGIN
    DECLARE @str AS VARCHAR(15) 

    SELECT @str = CAST( CAST( SUBSTRING( @ip, 1, 1) AS INTEGER) AS VARCHAR(3) ) + '.'
                + CAST( CAST( SUBSTRING( @ip, 2, 1) AS INTEGER) AS VARCHAR(3) ) + '.'
                + CAST( CAST( SUBSTRING( @ip, 3, 1) AS INTEGER) AS VARCHAR(3) ) + '.'
                + CAST( CAST( SUBSTRING( @ip, 4, 1) AS INTEGER) AS VARCHAR(3) );

    RETURN @str
END;
go

Here's a demo of how to use them:

SELECT dbo.fnBinaryIPv4('192.65.68.201')
--should return 0xC04144C9
go

SELECT dbo.fnDisplayIPv4( 0xC04144C9 )
-- should return '192.65.68.201'
go

Finally, when doing lookups and compares, always use the binary form if you want to be able to leverage your indexes.


UPDATE:

I wanted to add that one way to address the inherent performance problems of scalar UDFs in SQL Server, but still retain the code-reuse of a function is to use an iTVF (inline table-valued function) instead. Here's how the first function above (string to binary) can be re-written as an iTVF:

CREATE FUNCTION dbo.itvfBinaryIPv4(@ip AS VARCHAR(15)) RETURNS TABLE
AS RETURN (
    SELECT CAST(
               CAST( CAST( PARSENAME( @ip, 4 ) AS INTEGER) AS BINARY(1))
            +  CAST( CAST( PARSENAME( @ip, 3 ) AS INTEGER) AS BINARY(1))
            +  CAST( CAST( PARSENAME( @ip, 2 ) AS INTEGER) AS BINARY(1))
            +  CAST( CAST( PARSENAME( @ip, 1 ) AS INTEGER) AS BINARY(1))
                AS BINARY(4)) As bin
        )
go

Here's it in the example:

SELECT bin FROM dbo.fnBinaryIPv4('192.65.68.201')
--should return 0xC04144C9
go

And here's how you would use it in an INSERT

INSERT INTo myIpTable
SELECT {other_column_values,...},
       (SELECT bin FROM dbo.itvfBinaryIPv4('192.65.68.201'))

How to write loop in a Makefile?

For cross-platform support, make the command separator (for executing multiple commands on the same line) configurable.

If you're using MinGW on a Windows platform for example, the command separator is &:

NUMBERS = 1 2 3 4
CMDSEP = &
doit:
    $(foreach number,$(NUMBERS),./a.out $(number) $(CMDSEP))

This executes the concatenated commands in one line:

./a.out 1 & ./a.out 2 & ./a.out 3 & ./a.out 4 &

As mentioned elsewhere, on a *nix platform use CMDSEP = ;.

Install python 2.6 in CentOS

Late to the party, but the OP should have gone with Buildout or Virtualenv, and sidestepped the problem completely.

I am currently working on a Centos server, well, toiling away would be the proper term and I can assure everyone that the only way I am able to blink back the tears whilst using the software equivalents of fire hardened spears, is buildout.

Java: Why is the Date constructor deprecated, and what do I use instead?

One reason that the constructor is deprecated is that the meaning of the year parameter is not what you would expect. The javadoc says:

As of JDK version 1.1, replaced by Calendar.set(year + 1900, month, date).

Notice that the year field is the number of years since 1900, so your sample code most likely won't do what you expect it to do. And that's the point.

In general, the Date API only supports the modern western calendar, has idiosyncratically specified components, and behaves inconsistently if you set fields.

The Calendar and GregorianCalendar APIs are better than Date, and the 3rd-party Joda-time APIs were generally thought to be the best. In Java 8, they introduced the java.time packages, and these are now the recommended alternative.

How to change default Anaconda python environment

The correct answer (as of Dec 2018) is... you can't. Upgrading conda install python=3.6 may work, but it might not if you have packages that are necessary, but cannot be uninstalled.

Anaconda uses a default environment named base and you cannot create a new (e.g. python 3.6) environment with the same name. This is intentional. If you want your base Anaconda to be python 3.6, the right way to do this is to install Anaconda for python 3.6. As a package manager, the goal of Anaconda is to make different environments encapsulated, hence why you must source activate into them and why you can't just quietly switch the base package at will as this could lead to many issues on production systems.

Fitting a density curve to a histogram in R

Dirk has explained how to plot the density function over the histogram. But sometimes you might want to go with the stronger assumption of a skewed normal distribution and plot that instead of density. You can estimate the parameters of the distribution and plot it using the sn package:

> sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
$call
sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35, 
    times = 10), rep(45, times = 4)))

$cp
    mean     s.d. skewness 
41.46228 12.47892  0.99527 

Skew-normal distributed data plot

This probably works better on data that is more skew-normal:

Another skew-normal plot

Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

Like @itsneo said, I personally find ? + [ and ] the most convenient ones on a mac. But I can understand if you come from Linux side of things. Then you can use ? + alt + ? or ?.

Is it possible to read the value of a annotation in java?

Yes, if your Column annotation has the runtime retention

@Retention(RetentionPolicy.RUNTIME)
@interface Column {
    ....
}

you can do something like this

for (Field f: MyClass.class.getFields()) {
   Column column = f.getAnnotation(Column.class);
   if (column != null)
       System.out.println(column.columnName());
}

UPDATE : To get private fields use

Myclass.class.getDeclaredFields()

Is there a way to specify a max height or width for an image?

You can try this one

img{
    max-height:500px;
    max-width:500px;
    height:auto;
    width:auto;
}

This keeps the aspect ratio of the image and prevents either the two dimensions exceed 500px

You can check this post

Convert number to varchar in SQL with formatting

What is the value range? Is it 0 through 10? If so, then try:

SELECT REPLICATE('0',2-LEN(@t)) + CAST(@t AS VARCHAR)

That handles 0 through 9 as well as 10 through 99.

Now, tinyint can go up to the value of 255. If you want to handle > 99 through 255, then try this solution:

declare @t  TINYINT
set @t =233
SELECT ISNULL(REPLICATE('0',2-LEN(@t)),'') + CAST(@t AS VARCHAR)

To understand the solution, the expression to the left of the + calculates the number of zeros to prefix to the string.

In case of the value 3, the length is 1. 2 - 1 is 1. REPLICATE Adds one zero. In case of the value 10, the length is 2. 2 - 2 is 0. REPLICATE Adds nothing. In the case of the value 100, the length is -1 which produces a NULL. However, the null value is handled and set to an empty string.

Now if you decide that because tinyint can contain up to 255 and you want your formatting as three characters, just change the 2-LEN to 3-LEN in the left expression and you're set.

How to get a barplot with several variables side by side grouped by a factor

You can plot the means without resorting to external calculations and additional tables using stat_summary(...). In fact, stat_summary(...) was designed for exactly what you are doing.

library(ggplot2)
library(reshape2)            # for melt(...)
gg <- melt(df,id="gender")   # df is your original table
ggplot(gg, aes(x=variable, y=value, fill=factor(gender))) + 
  stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) + 
  scale_color_discrete("Gender")
  stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
               color="grey80",position=position_dodge(1), width=.2)

To add "error bars" you cna also use stat_summary(...) (here, I'm using the min and max value rather than sd because you have so little data).

ggplot(gg, aes(x=variable, y=value, fill=factor(gender))) + 
  stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) + 
  stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
               color="grey40",position=position_dodge(1), width=.2) +
  scale_fill_discrete("Gender")

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

It is possible to get a web application running in full screen in both iOS and Android, it is called a PWA and after mucha hard work, it was the only way around this issue.

PWAs open a number of interesting options for development that should not be missed. I've made a couple already, check out this Public and Private Tender Manual For Designers (Spanish). And here is an English explanation from the CosmicJS site

Python: create dictionary using dict() with integer keys?

Yes, but not with that version of the constructor. You can do this:

>>> dict([(1, 2), (3, 4)])
{1: 2, 3: 4}

There are several different ways to make a dict. As documented, "providing keyword arguments [...] only works for keys that are valid Python identifiers."

set initial viewcontroller in appdelegate - swift

I had done in Xcode 8 and swift 3.0 hope it will be useful for u, and its working perfectly. Use following code :

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {       
    self.window = UIWindow(frame: UIScreen.main.bounds)
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let initialViewController = storyboard.instantiateViewController(withIdentifier: "ViewController")
    self.window?.rootViewController = initialViewController
    self.window?.makeKeyAndVisible()
    return true
}

And If you are using the navigation controller, then use following code for that:

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    self.window = UIWindow(frame: UIScreen.main.bounds)
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let navigationController:UINavigationController = storyboard.instantiateInitialViewController() as! UINavigationController
    let initialViewController = storyboard.instantiateViewControllerWithIdentifier("ViewController")
    navigationController.viewControllers = [initialViewController]
    self.window?.rootViewController = navigationController
    self.window?.makeKeyAndVisible()      
    return true
}

hibernate - get id after save object

By default, hibernate framework will immediately return id , when you are trying to save the entity using Save(entity) method. There is no need to do it explicitly.

In case your primary key is int you can use below code:

int id=(Integer) session.save(entity);

In case of string use below code:

String str=(String)session.save(entity);

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

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

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

Capturing window.onbeforeunload

you just cant do alert() in onbeforeunload, anything else works

HTML SELECT - Change selected option by VALUE using JavaScript

try out this....

JSFIDDEL DEMO

using javascript

?document.getElementById('sel').value = 'car';??????????

using jQuery

$('#sel').val('car');

Print Html template in Angular 2 (ng-print in Angular 2)

you can do like this in angular 2

in ts file

 export class Component{          
      constructor(){
      }
       printToCart(printSectionId: string){
        let popupWinindow
        let innerContents = document.getElementById(printSectionId).innerHTML;
        popupWinindow = window.open('', '_blank', 'width=600,height=700,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
        popupWinindow.document.open();
        popupWinindow.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + innerContents + '</html>');
        popupWinindow.document.close();
  }

 }

in html

<div id="printSectionId" >
  <div>
    <h1>AngularJS Print html templates</h1>
    <form novalidate>
      First Name:
      <input type="text"  class="tb8">
      <br>
      <br> Last Name:
      <input type="text"  class="tb8">
      <br>
      <br>
      <button  class="button">Submit</button>
      <button (click)="printToCart('printSectionId')" class="button">Print</button>
    </form>
  </div>
  <div>
    <br/>
   </div>
</div>

env: node: No such file or directory in mac

I solved it this way:

$ brew uninstall --force node
$ brew uninstall --force npm

after it

$ brew install node

which suggested me to overwrite simlinks

Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink share/doc/node/gdbinit
Target /usr/local/share/doc/node/gdbinit
already exists. You may want to remove it:
  rm '/usr/local/share/doc/node/gdbinit'

To force the link and overwrite all conflicting files:
  brew link --overwrite node

after executing

$ brew link --overwrite node

everything worked again.

DataTables: Cannot read property style of undefined

In my case, I was updating the server-sided datatable twice and it gives me this error. Hope it helps someone.

An attempt was made to access a socket in a way forbidden by its access permissions

My situation and solution: I had created and enabled a HyperV ethernet adapter. For some reason, my main windows machine was using the "virtual" ethernet adapter instead of the 'hardware' adapter.

I disabled the virtual ethernet and my network settings to change the network public/privacy settings were revealed.

Show/hide div if checkbox selected

change the input boxes like

<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox
<input type="checkbox" name="c1" onclick="showMe('div1')">Show Hide Checkbox

and js code as

function showMe (box) {

    var chboxs = document.getElementsByName("c1");
    var vis = "none";
    for(var i=0;i<chboxs.length;i++) { 
        if(chboxs[i].checked){
         vis = "block";
            break;
        }
    }
    document.getElementById(box).style.display = vis;


}

here is a demo fiddle

Difference between string and StringBuilder in C#

System.String is a mutable object, meaning it cannot be modified after it’s been created. Please refer to Difference between string and StringBuilder in C#? for better understanding.

Superscript in Python plots

Alternatively, in python 3.6+, you can generate Unicode superscript and copy paste that in your code:

ax1.set_ylabel('Rate (min?¹)')

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

In TorpedoQuery it look like this

Entity from = from(Entity.class);
where(from.getCode()).in("Joe", "Bob");
Query<Entity> select = select(from);

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

I faced a similar issue during work with Ubuntu 16.04 by using Docker. In my case that was a problem with Composer, but error message (and thus the problem) was the same.

Because of minimalist Docker-oriented base image I had missing ca-certificates package and simple apt-get install ca-certificates helped me.

Create a tar.xz in one command

Use the -J compression option for xz. And remember to man tar :)

tar cfJ <archive.tar.xz> <files>

Edit 2015-08-10:

If you're passing the arguments to tar with dashes (ex: tar -cf as opposed to tar cf), then the -f option must come last, since it specifies the filename (thanks to @A-B-B for pointing that out!). In that case, the command looks like:

tar -cJf <archive.tar.xz> <files>

SQL Server Management Studio, how to get execution time down to milliseconds

I was after the same thing and stumbled across the following link which was brilliant:

http://www.sqlserver.info/management-studio/show-query-execution-time/

It shows three different ways of measuring the performance. All good for their own strengths. The one I opted for was as follows:


DECLARE @Time1 DATETIME

DECLARE @Time2 DATETIME

SET @Time1 = GETDATE()

-- Insert query here

SET @Time2 = GETDATE()

SELECT DATEDIFF(MILLISECOND,@Time1,@Time2) AS Elapsed_MS


This will show the results from your query followed by the amount of time it took to complete.

Hope this helps.

Difference between EXISTS and IN in SQL?

IN:

  • Works on List result set
  • Doesn’t work on subqueries resulting in Virtual tables with multiple columns
  • Compares every value in the result list
  • Performance is comparatively SLOW for larger result set of subquery

EXISTS:

  • Works on Virtual tables
  • Is used with co-related queries
  • Exits comparison when match is found
  • Performance is comparatively FAST for larger result set of subquery

Node.js server that accepts POST requests

Receive POST and GET request in nodejs :

1).Server

    var http = require('http');
    var server = http.createServer ( function(request,response){

    response.writeHead(200,{"Content-Type":"text\plain"});
    if(request.method == "GET")
        {
            response.end("received GET request.")
        }
    else if(request.method == "POST")
        {
            response.end("received POST request.");
        }
    else
        {
            response.end("Undefined request .");
        }
});

server.listen(8000);
console.log("Server running on port 8000");

2). Client :

var http = require('http');

var option = {
    hostname : "localhost" ,
    port : 8000 ,
    method : "POST",
    path : "/"
} 

    var request = http.request(option , function(resp){
       resp.on("data",function(chunck){
           console.log(chunck.toString());
       }) 
    })
    request.end();

Expanding a parent <div> to the height of its children

_x000D_
_x000D_
#parent{_x000D_
  background-color:green;_x000D_
  height:auto;_x000D_
  width:300px;_x000D_
  overflow:hidden;_x000D_
}_x000D_
_x000D_
#childRightCol{_x000D_
  color:gray;_x000D_
  background-color:yellow;_x000D_
  margin:10px;_x000D_
  padding:10px;_x000D_
}
_x000D_
<div id="parent">_x000D_
    <div id="childRightCol">_x000D_
        <p>_x000D_
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vulputate sit amet neque ac consequat._x000D_
        </p>_x000D_
    </div>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

you are manage by using overflow:hidden; property in css

Cursor inside cursor

You could also sidestep nested cursor issues, general cursor issues, and global variable issues by avoiding the cursors entirely.

declare @rowid int
declare @rowid2 int
declare @id int
declare @type varchar(10)
declare @rows int
declare @rows2 int
declare @outer table (rowid int identity(1,1), id int, type varchar(100))
declare @inner table (rowid int  identity(1,1), clientid int, whatever int)

insert into @outer (id, type) 
Select id, type from sometable

select @rows = count(1) from @outer
while (@rows > 0)
Begin
    select top 1 @rowid = rowid, @id  = id, @type = type
    from @outer
    insert into @innner (clientid, whatever ) 
    select clientid whatever from contacts where contactid = @id
    select @rows2 = count(1) from @inner
    while (@rows2 > 0)
    Begin
        select top 1 /* stuff you want into some variables */
        /* Other statements you want to execute */
        delete from @inner where rowid = @rowid2
        select @rows2 = count(1) from @inner
    End  
    delete from @outer where rowid = @rowid
    select @rows = count(1) from @outer
End

Trigger event when user scroll to specific element - with jQuery

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

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

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

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

"’" showing on page instead of " ' "

If someone gets this error on WordPress website, you need to change wp-config db charset:

define('DB_CHARSET', 'utf8mb4_unicode_ci');

instead of:

define('DB_CHARSET', 'utf8mb4');

Merge two rows in SQL

There might be neater methods, but the following could be one approach:

SELECT    t.fk,
          (
             SELECT t1.Field1 
             FROM   `table` t1 
             WHERE  t1.fk = t.fk AND t1.Field1 IS NOT NULL
             LIMIT  1
          ) Field1,
          (
             SELECT t2.Field2
             FROM   `table` t2 
             WHERE  t2.fk = t.fk AND t2.Field2 IS NOT NULL
             LIMIT  1
          ) Field2
FROM      `table` t
WHERE     t.fk = 3
GROUP BY  t.fk;

Test Case:

CREATE TABLE `table` (fk int, Field1 varchar(10), Field2 varchar(10));

INSERT INTO `table` VALUES (3, 'ABC', NULL);
INSERT INTO `table` VALUES (3, NULL, 'DEF');
INSERT INTO `table` VALUES (4, 'GHI', NULL);
INSERT INTO `table` VALUES (4, NULL, 'JKL');
INSERT INTO `table` VALUES (5, NULL, 'MNO');

Result:

+------+--------+--------+
| fk   | Field1 | Field2 |
+------+--------+--------+
|    3 | ABC    | DEF    |
+------+--------+--------+
1 row in set (0.01 sec)

Running the same query without the WHERE t.fk = 3 clause, it would return the following result-set:

+------+--------+--------+
| fk   | Field1 | Field2 |
+------+--------+--------+
|    3 | ABC    | DEF    |
|    4 | GHI    | JKL    |
|    5 | NULL   | MNO    |
+------+--------+--------+
3 rows in set (0.01 sec)

Multiple contexts with the same path error running web service in Eclipse using Tomcat

Try to delete the existing tomcat server in the server console. If you don't have the console then you can go to "Show view ->server", delete the server by right clicking on it, then add a new server.

Why is lock(this) {...} bad?

Please refer to the following link which explains why lock (this) is not a good idea.

https://docs.microsoft.com/en-us/dotnet/standard/threading/managed-threading-best-practices

So the solution is to add a private object, for example, lockObject to the class and place the code region inside the lock statement as shown below:

lock (lockObject)
{
...
}

How can a web application send push notifications to iOS devices?

Google Chrome now supports the W3C standard for push notifications.

http://www.w3.org/TR/push-api/

How to make div same height as parent (displayed as table-cell)

Another option is to set your child div to display: inline-block;

.content {
    display: inline-block;
    height: 100%;
    width: 100%;
    background-color: blue;
}

_x000D_
_x000D_
.container {_x000D_
  display: table;_x000D_
}_x000D_
.child {_x000D_
  width: 30px;_x000D_
  background-color: red;_x000D_
  display: table-cell;_x000D_
  vertical-align: top;_x000D_
}_x000D_
.content {_x000D_
  display: inline-block;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="child">_x000D_
    a_x000D_
    <br />a_x000D_
    <br />a_x000D_
  </div>_x000D_
  <div class="child">_x000D_
    a_x000D_
    <br />a_x000D_
    <br />a_x000D_
    <br />a_x000D_
    <br />a_x000D_
    <br />a_x000D_
    <br />a_x000D_
  </div>_x000D_
  <div class="child">_x000D_
    <div class="content">_x000D_
      a_x000D_
      <br />a_x000D_
      <br />a_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


JSFiddle Demo

How to change the remote a branch is tracking?

the easiest way is to simply push to the new branch:

git push -u origin branch/name

Bootstrap: add margin/padding space between columns

A solution for someone like me when cells got background color

HTML

<div class="row">
        <div class="col-6 cssBox">
            a<br />ba<br />ba<br />b
        </div>
        <div class="col-6 cssBox">
            a<br />b
        </div>
</div>

CSS

.cssBox {
  background-color: red;
  margin: 0 10px;
  flex-basis: calc(50% - 20px);
}

Matrix multiplication in OpenCV

You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.

Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple * operator:

C = A * B

Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul() function:

output = A.mul(B);

Write HTML to string

The most straight forward way is to use an XmlWriter object. This can be used to produce valid HTML and will take care of all of the nasty escape sequences for you.

How to get selected value from Dropdown list in JavaScript

Here is a simple example to get the selected value of dropdown in javascript

First we design the UI for dropdown

<div class="col-xs-12">
<select class="form-control" id="language">
    <option>---SELECT---</option>
    <option>JAVA</option>
    <option>C</option>
    <option>C++</option>
    <option>PERL</option>
</select>

Next we need to write script to get the selected item

<script type="text/javascript">
$(document).ready(function () {
    $('#language').change(function () {
        var doc = document.getElementById("language");
        alert("You selected " + doc.options[doc.selectedIndex].value);
    });
});

Now When change the dropdown the selected item will be alert.

What's the best way to select the minimum value from several columns?

This is brute force but works

 select case when col1 <= col2 and col1 <= col3 then col1
           case when col2 <= col1 and col2 <= col3 then col2
           case when col3 <= col1 and col3 <= col2 then col3
    as 'TheMin'
           end

from Table T

... because min() works only on one column and not across columns.

CURL to access a page that requires a login from a different page

The web site likely uses cookies to store your session information. When you run

curl --user user:pass https://xyz.com/a  #works ok
curl https://xyz.com/b #doesn't work

curl is run twice, in two separate sessions. Thus when the second command runs, the cookies set by the 1st command are not available; it's just as if you logged in to page a in one browser session, and tried to access page b in a different one.

What you need to do is save the cookies created by the first command:

curl --user user:pass --cookie-jar ./somefile https://xyz.com/a

and then read them back in when running the second:

curl --cookie ./somefile https://xyz.com/b

Alternatively you can try downloading both files in the same command, which I think will use the same cookies.

How to add hours to current date in SQL Server?

The DATEADD() function adds or subtracts a specified time interval from a date.

DATEADD(datepart,number,date)

datepart(interval) can be hour, second, day, year, quarter, week etc; number (increment int); date(expression smalldatetime)

For example if you want to add 30 days to current date you can use something like this

 select dateadd(dd, 30, getdate())

To Substract 30 days from current date

select dateadd(dd, -30, getdate())

Read pdf files with php

There is a php library (pdfparser) that does exactly what you want.

project website

http://www.pdfparser.org/

github

https://github.com/smalot/pdfparser

Demo page/api

http://www.pdfparser.org/demo

After including pdfparser in your project you can get all text from mypdf.pdf like so:

<?php
$parser = new \installpath\PdfParser\Parser();
$pdf    = $parser->parseFile('mypdf.pdf');  
$text = $pdf->getText();
echo $text;//all text from mypdf.pdf

?>

Simular you can get the metadata from the pdf as wel as getting the pdf objects (for example images).

Can I set an unlimited length for maxJsonLength in web.config?

 JsonResult result = Json(r);
 result.MaxJsonLength = Int32.MaxValue;
 result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
 return result;

The most accurate way to check JS object's type?

I'd argue that most of the solutions shown here suffer from being over-engineerd. Probably the most simple way to check if a value is of type [object Object] is to check against the .constructor property of it:

function isObject (a) { return a != null && a.constructor === Object; }

or even shorter with arrow-functions:

const isObject = a => a != null && a.constructor === Object;

The a != null part is necessary because one might pass in null or undefined and you cannot extract a constructor property from either of these.

It works with any object created via:

  • the Object constructor
  • literals {}

Another neat feature of it, is it's ability to give correct reports for custom classes which make use of Symbol.toStringTag. For example:

class MimicObject {
  get [Symbol.toStringTag]() {
    return 'Object';
  }
}

The problem here is that when calling Object.prototype.toString on an instance of it, the false report [object Object] will be returned:

let fakeObj = new MimicObject();
Object.prototype.toString.call(fakeObj); // -> [object Object]

But checking against the constructor gives a correct result:

let fakeObj = new MimicObject();
fakeObj.constructor === Object; // -> false

Remove duplicates from an array of objects in JavaScript

Make Something simple. Fancy is good but unreadable code is useless. Enjoy :-)

_x000D_
_x000D_
var a = [_x000D_
 {_x000D_
  executiveId: 6873702,_x000D_
  largePhotoCircle: null,_x000D_
  name: "John A. Cuomo",_x000D_
  photoURL: null,_x000D_
  primaryCompany: "VSE CORP",_x000D_
  primaryTitle: "Chief Executive Officer, President and Director"_x000D_
 },_x000D_
 {_x000D_
  executiveId: 6873702,_x000D_
  largePhotoCircle: null,_x000D_
  name: "John A. Cuomo",_x000D_
  photoURL: null,_x000D_
  primaryCompany: "VSE CORP",_x000D_
  primaryTitle: "Chief Executive Officer, President and Director"_x000D_
 },_x000D_
 {_x000D_
  executiveId: 6873703,_x000D_
  largePhotoCircle: null,_x000D_
  name: "John A. Cuomo",_x000D_
  photoURL: null,_x000D_
  primaryCompany: "VSE CORP",_x000D_
  primaryTitle: "Chief Executive Officer, President and Director",_x000D_
 }_x000D_
];_x000D_
_x000D_
function filterDuplicate(myArr, prop) {_x000D_
      // Format - (1)_x000D_
_x000D_
      // return myArr.filter((obj, pos, arr) => {_x000D_
      //     return arr.map(mapObj => mapObj[prop]).indexOf(obj[prop]) === pos;_x000D_
      // });_x000D_
_x000D_
      // Format - (2)_x000D_
      var res = {};_x000D_
      var resArr = [];_x000D_
      for (var elem of myArr) {_x000D_
        res[elem.executiveId] = elem;_x000D_
      }_x000D_
      for (let [index, elem] of Object.entries(res)) {_x000D_
        resArr.push(elem);_x000D_
      }_x000D_
      return resArr;_x000D_
  }_x000D_
  _x000D_
let finalRes = filterDuplicate(a,"executiveId");_x000D_
console.log("finalResults : ",finalRes);
_x000D_
_x000D_
_x000D_

How do I block or restrict special characters from input fields with jquery?

Your textbox:

<input type="text" id="name">

Your javascript:

$("#name").keypress(function(event) {
    var character = String.fromCharCode(event.keyCode);
    return isValid(character);     
});

function isValid(str) {
    return !/[~`!@#$%\^&*()+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}

How to stop an app on Heroku?

Go to your dashboard on heroku. Select the app. There is a dynos section. Just pull the sliders for the dynos down, (a decrease in dynos is to the left), to the number of dynos you want to be running. The slider goes to 0. Then save your changes. Boom.

According to the comment below: there is a pencil icon that needs to be clicked to accomplish this. I have not checked - but am putting it here in case it helps.

How to see data from .RData file?

This may fit better as a comment but I don't have enough reputation, so I put it here.
It worth mentioning that the load() function will retain the object name that was originally saved no matter how you name the .Rdata file.

Please check the name of the data.frame object used in the save() function. If you were using RStudio, you could check the upper right panel, Global Environment-Data, to find the name of the data you load.

Getting Google+ profile picture url with user_id

You can get the URL for the profile image using the people.get method of the Google+ API. That does require an extra round trip, but is the most reliable way to get the image.

You technically can also use the URL https://s2.googleusercontent.com/s2/photos/profile/{id}?sz={size} which will then redirect to the final URL. {id} is the Google user ID or one of the old Google Profiles usernames (they still exist for users who had them, but I don't think you can create new ones anymore). {size} is the desired size of the photo in pixels. I'm almost certain this is not a documented, supported feature, so I wouldn't rely on it for anything important as it may go away at anytime without notice. But for quick prototypes or small one-off applications, it may be sufficient.

Text overwrite in visual studio 2010

Visual Studio : Right Bottom : Look for OVR label. Double Click on it.

Bingo...

Change <select>'s option and trigger events with JavaScript

The whole creating and dispatching events works, but since you are using the onchange attribute, your life can be a little simpler:

http://jsfiddle.net/xwywvd1a/3/

var selEl = document.getElementById("sel");
selEl.options[1].selected = true;
selEl.onchange();

If you use the browser's event API (addEventListener, IE's AttachEvent, etc), then you will need to create and dispatch events as others have pointed out already.

How to execute Python code from within Visual Studio Code

There is a Run Python File in Terminal command available in the Python for Visual Studio Code extension.

Run Python File in Terminal

How to close existing connections to a DB

In more recent versions of SQL Server Management studio, you can now right click on a database and 'Take Database Offline'. This gives you the option to Drop All Active Connections to the database.

How can I check if mysql is installed on ubuntu?

# mysqladmin -u root -p status

Output:

Enter password:
Uptime: 4  Threads: 1  Questions: 62  Slow queries: 0  Opens: 51  Flush tables: 1  Open tables: 45  Queries per second avg: 15.500

It means MySQL serer is running

If server is not running then it will dump error as follows

# mysqladmin -u root -p status

Output :

mysqladmin: connect to server at 'localhost' failed
error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists!

So Under Debian Linux you can type following command

# /etc/init.d/mysql status

How to assign text size in sp value using java code

From Api level 1, you can use the public void setTextSize (float size) method.

From the documentation:

Set the default text size to the given value, interpreted as "scaled pixel" units. This size is adjusted based on the current density and user font size preference.

Parameters: size -> float: The scaled pixel size.

So you can simple do:

textView.setTextSize(12); // your size in sp

Excel function to get first word from sentence in other cell

How about something like

=LEFT(A1,SEARCH(" ",A1)-1)

or

=LEFT(A1,SEARCH("<b>",A1)-1)

Have a look at MS Excel: Search Function and Excel 2007 LEFT Function

Is there a way to represent a directory tree in a Github README.md?

Insert command tree in bash.

Also, there is a DOS comnand "tree". You can displays directory paths and files in each subdirectory with command:

tree /F

https://web.csulb.edu/~murdock/tree.html

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

How to call a asp:Button OnClick event using JavaScript?

If you're open to using jQuery:

<script type="text/javascript">
 function fncsave()
 {
    $('#<%= savebtn.ClientID %>').click();
 }
</script>

Also, if you are using .NET 4 or better you can make the ClientIDMode == static and simplify the code:

<script type="text/javascript">
 function fncsave()
 {
    $("#savebtn").click();
 }
</script>

Reference: MSDN Article for Control.ClientIDMode

Move a view up only when the keyboard covers an input field

for swift 4.2.

This will apply to any form. No need of scrollview. do not forget to set delegate.

Make a var of uitextfield

var clickedTextField = UITextField()

In your viewdid load

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name:NSNotification.Name.UIKeyboardWillShow, object: nil);
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name:NSNotification.Name.UIKeyboardWillHide, object: nil);

Know the clicked text field. probably you are having textfields on the entire screen.

func textFieldDidBeginEditing(_ textField: UITextField) {
    clickedTextField = textField
}

Check if the keyboard is covering textfield or not.

@objc func keyboardWillShow(sender: NSNotification,_ textField : UITextField) {
    if let keyboardSize = (sender.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {

        if clickedTextField.frame.origin.y > keyboardSize.origin.y {
            self.view.frame.origin.y = keyboardSize.origin.y - clickedTextField.center.y - 20
        }
    }
}

@objc func keyboardWillHide(sender: NSNotification) {
    self.view.frame.origin.y = 0
}

Return to close keyboard

func textFieldShouldReturn(_ textField: UITextField) -> Bool {   //delegate method
    textField.resignFirstResponder()
    return true
}

UPDATE : NSNotification.Name.UIKeyboardWillShow & NSNotification.Name.UIKeyboardWillHide are renamed to UIResponder.keyboardWillShowNotification & UIResponder.keyboardWillHideNotification respectively.

Better way to get type of a Javascript variable?

function getType(obj) {
    if(obj && obj.constructor && obj.constructor.name) {
        return obj.constructor.name;
    }
    return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
}

In my preliminary tests, this is working pretty well. The first case will print the name of any object created with "new", and the 2nd case should catch everything else.

I'm using (8, -1) because I'm assuming that the result is always going to start with [object and end with ] but I'm not certain that's true in every scenario.

What is the best way to dump entire objects to a log in C#?

What I like doing is overriding ToString() so that I get more useful output beyond the type name. This is handy in the debugger, you can see the information you want about an object without needing to expand it.

When using SASS how can I import a file from a different directory?

Looks like some changes to SASS have made possible what you've initially tried doing:

@import "../subdir/common";

We even got this to work for some totally unrelated folder located in c:\projects\sass:

@import "../../../../../../../../../../projects/sass/common";

Just add enough ../ to be sure you'll end up at the drive root and you're good to go.

Of course, this solution is far from pretty, but I couldn't get an import from a totally different folder to work, neither using I c:\projects\sass nor setting the environment variable SASS_PATH (from: :load_paths reference) to that same value.

How to test that a registered variable is not empty?

- name: set pkg copy dir name
  set_fact:
    PKG_DIR: >-
      {% if ansible_os_family == "RedHat" %}centos/*.rpm
      {%- elif ansible_distribution == "Ubuntu" %}ubuntu/*.deb
      {%- elif ansible_distribution == "Kylin Linux Advanced Server" %}kylin/*.deb
      {%- else %}{%- endif %}

How to Consume WCF Service with Android

If I were doing this I would probably use WCF REST on the server and a REST library on the Java/Android client.

Check a radio button with javascript

By using document.getElementById() function you don't have to pass # before element's id.

Code:

document.getElementById('_1234').checked = true;

Demo: JSFiddle

Renaming column names of a DataFrame in Spark Scala

For those of you interested in PySpark version (actually it's same in Scala - see comment below) :

    merchants_df_renamed = merchants_df.toDF(
        'merchant_id', 'category', 'subcategory', 'merchant')

    merchants_df_renamed.printSchema()

Result:

root
|-- merchant_id: integer (nullable = true)
|-- category: string (nullable = true)
|-- subcategory: string (nullable = true)
|-- merchant: string (nullable = true)

Regex expressions in Java, \\s vs. \\s+

The first one matches a single whitespace, whereas the second one matches one or many whitespaces. They're the so-called regular expression quantifiers, and they perform matches like this (taken from the documentation):

Greedy quantifiers
X?  X, once or not at all
X*  X, zero or more times
X+  X, one or more times
X{n}    X, exactly n times
X{n,}   X, at least n times
X{n,m}  X, at least n but not more than m times

Reluctant quantifiers
X?? X, once or not at all
X*? X, zero or more times
X+? X, one or more times
X{n}?   X, exactly n times
X{n,}?  X, at least n times
X{n,m}? X, at least n but not more than m times

Possessive quantifiers
X?+ X, once or not at all
X*+ X, zero or more times
X++ X, one or more times
X{n}+   X, exactly n times
X{n,}+  X, at least n times
X{n,m}+ X, at least n but not more than m times