Programs & Examples On #Visitor pattern

When should I use the Visitor Design Pattern?

Everyone here is correct, but I think it fails to address the "when". First, from Design Patterns:

Visitor lets you define a new operation without changing the classes of the elements on which it operates.

Now, let's think of a simple class hierarchy. I have classes 1, 2, 3 and 4 and methods A, B, C and D. Lay them out like in a spreadsheet: the classes are lines and the methods are columns.

Now, Object Oriented design presumes you are more likely to grow new classes than new methods, so adding more lines, so to speak, is easier. You just add a new class, specify what's different in that class, and inherits the rest.

Sometimes, though, the classes are relatively static, but you need to add more methods frequently -- adding columns. The standard way in an OO design would be to add such methods to all classes, which can be costly. The Visitor pattern makes this easy.

By the way, this is the problem that Scala's pattern matches intends to solve.

Where can I read the Console output in Visual Studio 2015

What may be happening is that your console is closing before you get a chance to see the output. I would add Console.ReadLine(); after your Console.WriteLine("Hello World"); so your code would look something like this:

static void Main(string[] args)
    {
        Console.WriteLine("Hello World");
        Console.ReadLine();

    }

This way, the console will display "Hello World" and a blinking cursor underneath. The Console.ReadLine(); is the key here, the program waits for the users input before closing the console window.

Redirect after Login on WordPress

This should solve your problem. Adapted from an answer found here.

Add the following snippet of code in the functions.php file of your theme:

function admin_default_page() {
  return '/new-dashboard-url';
}

add_filter('login_redirect', 'admin_default_page');

Change PictureBox's image to image from my resources?

try the following:

 myPictureBox.Image = global::mynamespace.Properties.Resources.photo1;

and replace namespace with your project namespace

nvm is not compatible with the npm config "prefix" option:

I was looking for a solution for the nvm prefix problem a found this question(before finding the solution). Here is my shell "dialog". I hope, it can be usefull for somebody. I was able to set to prefix with the help of this post: https://github.com/npm/npm/issues/6592

When I tried npm config delete prefix or nvm use --delete-prefix before using npm --prefix="" set prefix "", I got only: npm ERR! not ok code 0

Note that you will have to repeat the same procedure with every node version, the prefix is set back to (in my case) /usr/local after installation.

    $ nvm install 0.10
    ######################################################################## 100.0%
    nvm is not compatible with the npm config "prefix" option: currently set to "/usr/local"
    Run `npm config delete prefix` or `nvm use --delete-prefix v0.10.44` to unset it.
    $ npm --prefix="" set prefix ""
    $ nvm use 0.10.44
    nvm is not compatible with the npm config "prefix" option: currently set to "/home/john"
    Run `npm config delete prefix` or `nvm use --delete-prefix v0.10.44` to unset it.
    $ nvm use --delete-prefix v0.10.44
    Now using node v0.10.44 (npm v1.3.10)
    $ nvm ls
    v0.10.44
             v4.4.3
    ->       system
    default -> 4.4.3 (-> v4.4.3)
    node -> stable (-> v4.4.3) (default)
    stable -> 4.4 (-> v4.4.3) (default)
    iojs -> N/A (default)
    $ npm config get prefix
    /usr/local

How to Set a Custom Font in the ActionBar Title?

I agree that this isn't completely supported, but here's what I did. You can use a custom view for your action bar (it will display between your icon and your action items). I'm using a custom view and I have the native title disabled. All of my activities inherit from a single activity, which has this code in onCreate:

this.getActionBar().setDisplayShowCustomEnabled(true);
this.getActionBar().setDisplayShowTitleEnabled(false);

LayoutInflater inflator = LayoutInflater.from(this);
View v = inflator.inflate(R.layout.titleview, null);

//if you need to customize anything else about the text, do it here.
//I'm using a custom TextView with a custom font in my layout xml so all I need to do is set title
((TextView)v.findViewById(R.id.title)).setText(this.getTitle());

//assign the view to the actionbar
this.getActionBar().setCustomView(v);

And my layout xml (R.layout.titleview in the code above) looks like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent" >

<com.your.package.CustomTextView
        android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:textSize="20dp"
            android:maxLines="1"
            android:ellipsize="end"
            android:text="" />
</RelativeLayout>

Alter a MySQL column to be AUTO_INCREMENT

You can do it like this:

 alter table [table_name] modify column [column_name] [column_type] AUTO_INCREMENT;

How to implement a Keyword Search in MySQL?

Ideally, have a keyword table containing the fields:

Keyword
Id
Count (possibly)

with an index on Keyword. Create an insert/update/delete trigger on the other table so that, when a row is changed, every keyword is extracted and put into (or replaced in) this table.

You'll also need a table of words to not count as keywords (if, and, so, but, ...).

In this way, you'll get the best speed for queries wanting to look for the keywords and you can implement (relatively easily) more complex queries such as "contains Java and RCA1802".

"LIKE" queries will work but they won't scale as well.

'JSON' is undefined error in JavaScript in Internet Explorer

Change the content type to 'application/x-www-form-urlencoded'

git cherry-pick says "...38c74d is a merge but no -m option was given"

The way a cherry-pick works is by taking the diff a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying it to your current branch.

So, if a commit has two or more parents, it also represents two or more diffs - which one should be applied?

You're trying to cherry pick fd9f578, which was a merge with two parents. So you need to tell the cherry-pick command which one against which the diff should be calculated, by using the -m option. For example, git cherry-pick -m 1 fd9f578 to use parent 1 as the base.

I can't say for sure for your particular situation, but using git merge instead of git cherry-pick is generally advisable. When you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m into that one commit. You lose all their history, and glom together all their diffs. Your call.

What’s the best way to load a JSONObject from a json text file?

try this:

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils; 

    public class JsonParsing {

        public static void main(String[] args) throws Exception {
            InputStream is = 
                    JsonParsing.class.getResourceAsStream( "sample-json.txt");
            String jsonTxt = IOUtils.toString( is );

            JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );        
            double coolness = json.getDouble( "coolness" );
            int altitude = json.getInt( "altitude" );
            JSONObject pilot = json.getJSONObject("pilot");
            String firstName = pilot.getString("firstName");
            String lastName = pilot.getString("lastName");

            System.out.println( "Coolness: " + coolness );
            System.out.println( "Altitude: " + altitude );
            System.out.println( "Pilot: " + lastName );
        }
    }

and this is your sample-json.txt , should be in json format

{
 'foo':'bar',
 'coolness':2.0,
 'altitude':39000,
 'pilot':
     {
         'firstName':'Buzz',
         'lastName':'Aldrin'
     },
 'mission':'apollo 11'
}

setTimeout or setInterval?

The setInterval makes it easier to cancel future execution of your code. If you use setTimeout, you must keep track of the timer id in case you wish to cancel it later on.

var timerId = null;
function myTimeoutFunction()
{
    doStuff();
    timerId = setTimeout(myTimeoutFunction, 1000);
}

myTimeoutFunction();

// later on...
clearTimeout(timerId);

versus

function myTimeoutFunction()
{
    doStuff();
}

myTimeoutFunction();
var timerId = setInterval(myTimeoutFunction, 1000);

// later on...
clearInterval(timerId);

How to position a div in the middle of the screen when the page is bigger than the screen

Use transform;

<style type="text/css">
    #mydiv {
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
</style>

Javascript Solution :

var left = (screen.width / 2) - (530 / 2);
var top = (screen.height / 2) - (500 / 2);
var _url = 'PopupListRepair.aspx';
window.open(_url, self, "width=530px,height=500px,status=yes,resizable=no,toolbar=no,menubar=no,left=" + left + ",top=" + top + ",scrollbars=no");

Fatal error: Maximum execution time of 30 seconds exceeded

Follow the path /etc/php5(your php version)/apache2/php.ini.

Open it and set the value of max_execution_time to a desired one.

HTML 5 Geo Location Prompt in Chrome

if you're hosting behind a server, and still facing issues: try changing localhost to 127.0.0.1 e.g. http://localhost:8080/ to http://127.0.0.1:8080/

The issue I was facing was that I was serving a site using apache tomcat within an eclipse IDE (eclipse luna).

For my sanity check I was using Remy Sharp's demo: https://github.com/remy/html5demos/blob/eae156ca2e35efbc648c381222fac20d821df494/demos/geo.html

and was getting the error after making minor tweaks to the error function despite hosting the code on the server (was only working on firefox and failing on chrome and safari):

"User denied Geolocation"

I made the following change to get more detailed error message:

function error(msg) {
  var s = document.querySelector('#status');
  msg = msg.message ? msg.message : msg; //add this line
  s.innerHTML = typeof msg == 'string' ? msg : "failed";
  s.className = 'fail';

  // console.log(arguments);
}

failing on internet explorer behind virtualbox IE10 on http://10.0.2.2:8080 :

"The current location cannot be determined"

How to use type: "POST" in jsonp ajax call

You can't POST using JSONP...it simply doesn't work that way, it creates a <script> element to fetch data...which has to be a GET request. There's not much you can do besides posting to your own domain as a proxy which posts to the other...but user's not going to be able to do this directly and see a response though.

TypeError: cannot perform reduce with flexible type

It looks like your 'trainData' is a list of strings:

['-214' '-153' '-58' ..., '36' '191' '-37']

Change your 'trainData' to a numeric type.

 import numpy as np
 np.array(['1','2','3']).astype(np.float)

Sending Email in Android using JavaMail API without using the default/built-in app

Here are a lot solutions. However I think we must change the configuration of the GMail to allow accessing from less secure devices. Go to the link below and enable it. It works for me

https://myaccount.google.com/lesssecureapps?pli=1

How to install PHP intl extension in Ubuntu 14.04

May be universe repository is disabled, here is your package in it

Enable it

sudo add-apt-repository universe

Update

sudo apt-get update

And install

sudo apt-get install php5-intl

How to Access Hive via Python?

None of the answers demonstrate how to fetch and print the table headers. Modified the standard example from PyHive which is widely used and actively maintained.

from pyhive import hive
cursor = hive.connect(host="localhost", 
                      port=10000, 
                      username="shadan", 
                      auth="KERBEROS", 
                      kerberos_service_name="hive"
                      ).cursor()
cursor.execute("SELECT * FROM my_dummy_table LIMIT 10")
columnList = [desc[0] for desc in cursor.description]
headerStr = ",".join(columnList)
headerTuple = tuple(headerStr.split (",")
print(headerTuple)
print(cursor.fetchone())
print(cursor.fetchall())

keycode and charcode

Okay, here are the explanations.

e.keyCode - used to get the number that represents the key on the keyboard

e.charCode - a number that represents the unicode character of the key on keyboard

e.which - (jQuery specific) is a property introduced in jQuery (DO Not use in plain javascript)

Below is the code snippet to get the keyCode and charCode

<script>
// get key code
function getKey(event) {
  event = event || window.event;
  var keyCode = event.which || event.keyCode;
  alert(keyCode);
}

// get char code
function getChar(event) {
  event = event || window.event;
  var keyCode = event.which || event.keyCode;
  var typedChar = String.fromCharCode(keyCode);
  alert(typedChar);
}
</script>

Live example of Getting keyCode and charCode in JavaScript.

Search a whole table in mySQL for a string

If you're using Sublime, you can easily generate hundreds or thousands of lines using Text Pastry in conjunction with multiple line selection and Emmet.

So in my case I set the document type to html, then typed div*249, hit tab and Emmet creates 249 empty divs. Then using multiple selection I typed col_id_ in each one and triggered Text Pastry to insert an incremental id number. Then with multiple selection again you can delete the div markup and replace it with the MySQL syntax.

How to have Android Service communicate with Activity

Another way could be using observers with a fake model class through the activity and the service itself, implementing an MVC pattern variation. I don't know if it's the best way to accomplish this, but it's the way that worked for me. If you need some example ask for it and i'll post something.

Java, looping through result set

Result Set are actually contains multiple rows of data, and use a cursor to point out current position. So in your case, rs4.getString(1) only get you the data in first column of first row. In order to change to next row, you need to call next()

a quick example

while (rs.next()) {
    String sid = rs.getString(1);
    String lid = rs.getString(2);
    // Do whatever you want to do with these 2 values
}

there are many useful method in ResultSet, you should take a look :)

Possible to make labels appear when hovering over a point in matplotlib?

The other answers did not address my need for properly showing tooltips in a recent version of Jupyter inline matplotlib figure. This one works though:

import matplotlib.pyplot as plt
import numpy as np
import mplcursors
np.random.seed(42)

fig, ax = plt.subplots()
ax.scatter(*np.random.random((2, 26)))
ax.set_title("Mouse over a point")
crs = mplcursors.cursor(ax,hover=True)

crs.connect("add", lambda sel: sel.annotation.set_text(
    'Point {},{}'.format(sel.target[0], sel.target[1])))
plt.show()

Leading to something like the following picture when going over a point with mouse: enter image description here

parse html string with jquery

MarvinS.-

Try:

$.ajax({  
        url: uri+'?js',  
        success: function(data) {  
                var imgAttr = $("img", data).attr('src'); 
                var htmlCode = $(data).html();
                $('#imgSrc').html(imgAttr);
                $('#fullHtmlOutput').html(htmlCode);
        }  
    });

This should load the whole html block from data into #fullHtmlOutput and the src of the image into #imgSrc.

Put text at bottom of div

I think that's better to use flex boxes (compatibility) than the absolute position. Here's example from me in pure css.

_x000D_
_x000D_
.container{_x000D_
  background-color:green;_x000D_
  height:500px;_x000D_
  _x000D_
  /*FLEX BOX */_x000D_
  display: -ms-flexbox;_x000D_
    display: -webkit-flex;_x000D_
    display: flex;_x000D_
    -webkit-flex-direction: column;_x000D_
    -ms-flex-direction: column;_x000D_
    flex-direction: column;_x000D_
    -webkit-flex-wrap: nowrap;_x000D_
    -ms-flex-wrap: nowrap;_x000D_
    flex-wrap: nowrap;_x000D_
    -webkit-justify-content: flex-start;_x000D_
    -ms-flex-pack: start;_x000D_
    justify-content: flex-start;_x000D_
    -webkit-align-content: stretch;_x000D_
    -ms-flex-line-pack: stretch;_x000D_
    align-content: stretch;_x000D_
    -webkit-align-items: flex-start;_x000D_
    -ms-flex-align: start;_x000D_
    align-items: flex-start;_x000D_
}_x000D_
_x000D_
.elem1{_x000D_
  background-color:red;_x000D_
  padding:20px;_x000D_
  _x000D_
   /*FLEX BOX CHILD */_x000D_
 -webkit-order: 0;_x000D_
    -ms-flex-order: 0;_x000D_
    order: 0;_x000D_
    -webkit-flex: 0 1 auto;_x000D_
    -ms-flex: 0 1 auto;_x000D_
    flex: 0 1 auto;_x000D_
    -webkit-align-self: flex-end;_x000D_
    -ms-flex-item-align: end;_x000D_
    align-self: flex-end;_x000D_
 _x000D_
}
_x000D_
<div class="container">_x000D_
 TOP OF CONTAINER _x000D_
<div class="elem1">_x000D_
  Nam pretium turpis et arcu. Sed a libero. Sed mollis, eros et ultrices tempus, mauris ipsum aliquam libero, non adipiscing dolor urna a orci._x000D_
_x000D_
Mauris sollicitudin fermentum libero. Pellentesque libero tortor, tincidunt et, tincidunt eget, semper nec, quam. Quisque id mi._x000D_
_x000D_
Donec venenatis vulputate lorem. Maecenas ullamcorper, dui et placerat feugiat, eros pede varius nisi, condimentum viverra felis nunc et lorem. Curabitur vestibulum aliquam leo._x000D_
</div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

I solved this problem by adding following code into my /etc/my.cnf file -

enter image description here

[client]
default-character-set=utf8

[mysql]
default-character-set=utf8


[mysqld]
collation-server = utf8_unicode_ci
character-set-server = utf8

After saving that,I went into my system settings and stopped MYSQL server and started again, and it worked.

Change Color of Fonts in DIV (CSS)

Your first CSS selector—social.h2—is looking for the "social" element in the "h2", class, e.g.:

<social class="h2">

Class selectors are proceeded with a dot (.). Also, use a space () to indicate that one element is inside of another. To find an <h2> descendant of an element in the social class, try something like:

.social h2 {
  color: pink;
  font-size: 14px;
}

To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.

Accessing elements by type in javascript

The sizzle selector engine (what powers JQuery) is perfectly geared up for this:

var elements = $('input[type=text]');

Or

var elements = $('input:text');

403 Forbidden vs 401 Unauthorized HTTP responses

This is an older question, but one option that was never really brought up was to return a 404. From a security perspective, the highest voted answer suffers from a potential information leakage vulnerability. Say, for instance, that the secure web page in question is a system admin page, or perhaps more commonly, is a record in a system that the user doesn't have access to. Ideally you wouldn't want a malicious user to even know that there's a page / record there, let alone that they don't have access. When I'm building something like this, I'll try to record unauthenticate / unauthorized requests in an internal log, but return a 404.

OWASP has some more information about how an attacker could use this type of information as part of an attack.

Swift Error: Editor placeholder in source file

you had this

destination = Node(key: String?, neighbors: [Edge!], visited: Bool, lat: Double, long: Double)

which was place holder text above you need to insert some values

class Edge{

}

public class Node{

  var key: String?
  var neighbors: [Edge]
  var visited: Bool = false
  var lat: Double
  var long: Double

  init(key: String?, neighbors: [Edge], visited: Bool, lat: Double, long: Double) {
    self.neighbors = [Edge]()
    self.key = key
    self.visited = visited
    self.lat = lat
    self.long = long
  }

}

class Path {

  var total: Int!
  var destination: Node
  var previous: Path!

  init(){
    destination = Node(key: "", neighbors: [], visited: true, lat: 12.2, long: 22.2)
  }
}

"Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))"

I got the same error with vlc component when i changed the framework from 4.5 to 4. but it worked for me when I changed the platform from Any CPU to x86.

What are the safe characters for making URLs?

The format for an URI is defined in RFC 3986. See section 3.3 for details.

Can Console.Clear be used to only clear a line instead of whole console?

Description

You can use the Console.SetCursorPosition function to go to a specific line number. Than you can use this function to clear the line

public static void ClearCurrentConsoleLine()
{
    int currentLineCursor = Console.CursorTop;
    Console.SetCursorPosition(0, Console.CursorTop);
    Console.Write(new string(' ', Console.WindowWidth)); 
    Console.SetCursorPosition(0, currentLineCursor);
}

Sample

Console.WriteLine("Test");
Console.SetCursorPosition(0, Console.CursorTop - 1);
ClearCurrentConsoleLine();

More Information

How to move columns in a MySQL table?

If empName is a VARCHAR(50) column:

ALTER TABLE Employees MODIFY COLUMN empName VARCHAR(50) AFTER department;

EDIT

Per the comments, you can also do this:

ALTER TABLE Employees CHANGE COLUMN empName empName VARCHAR(50) AFTER department;

Note that the repetition of empName is deliberate. You have to tell MySQL that you want to keep the same column name.

You should be aware that both syntax versions are specific to MySQL. They won't work, for example, in PostgreSQL or many other DBMSs.

Another edit: As pointed out by @Luis Rossi in a comment, you need to completely specify the altered column definition just before the AFTER modifier. The above examples just have VARCHAR(50), but if you need other characteristics (such as NOT NULL or a default value) you need to include those as well. Consult the docs on ALTER TABLE for more info.

Proper Linq where clauses

EDIT: LINQ to Objects doesn't behave how I'd expected it to. You may well be interested in the blog post I've just written about this...


They're different in terms of what will be called - the first is equivalent to:

Collection.Where(x => x.Age == 10)
          .Where(x => x.Name == "Fido")
          .Where(x => x.Fat == true)

wheras the latter is equivalent to:

Collection.Where(x => x.Age == 10 && 
                      x.Name == "Fido" &&
                      x.Fat == true)

Now what difference that actually makes depends on the implementation of Where being called. If it's a SQL-based provider, I'd expect the two to end up creating the same SQL. If it's in LINQ to Objects, the second will have fewer levels of indirection (there'll be just two iterators involved instead of four). Whether those levels of indirection are significant in terms of speed is a different matter.

Typically I would use several where clauses if they feel like they're representing significantly different conditions (e.g. one is to do with one part of an object, and one is completely separate) and one where clause when various conditions are closely related (e.g. a particular value is greater than a minimum and less than a maximum). Basically it's worth considering readability before any slight performance difference.

How can I resize an image dynamically with CSS as the browser width/height changes?

2018 and later solution:

Using viewport-relative units should make your life way easier, given we have the image of a cat:

cat

Now we want this cat inside our code, while respecting aspect ratios:

_x000D_
_x000D_
img {_x000D_
  width: 100%;_x000D_
  height: auto;_x000D_
}
_x000D_
<img src="https://www.petmd.com/sites/default/files/petmd-cat-happy-10.jpg" alt="cat">
_x000D_
_x000D_
_x000D_

So far not really interesting, but what if we would like to change the cats width to be the maximum of 50% of the viewport?

_x000D_
_x000D_
img {_x000D_
  width: 100%;_x000D_
  height: auto;_x000D_
  /* Magic! */_x000D_
  max-width: 50vw;_x000D_
}
_x000D_
<img src="https://www.petmd.com/sites/default/files/petmd-cat-happy-10.jpg" alt="cat">
_x000D_
_x000D_
_x000D_

The same image, but now restricted to a maximum width of 50vw vw (=viewport width) means the image will be X width of the viewport, depending on the digit provided. This also works for height:

_x000D_
_x000D_
img {_x000D_
  width: auto;_x000D_
  height: 100%;_x000D_
  max-height: 20vh;_x000D_
}
_x000D_
<img src="https://www.petmd.com/sites/default/files/petmd-cat-happy-10.jpg" alt="cat">
_x000D_
_x000D_
_x000D_

This restricts the height of the image to a maximum of 20% of the viewport.

RuntimeWarning: invalid value encountered in divide

I think your code is trying to "divide by zero" or "divide by NaN". If you are aware of that and don't want it to bother you, then you can try:

import numpy as np
np.seterr(divide='ignore', invalid='ignore')

For more details see:

Multiple select statements in Single query

I know this is an old stack but i will post this Multi-SQL select case

    SELECT bp.bizid, bp.usrid, bp.website, 
ROUND((SELECT SUM(rating) FROM ratings WHERE bizid=bp.bizid)/(SELECT COUNT(*) FROM ratings WHERE bizid=bp.bizid), 1) AS 'ratings', 
(SELECT COUNT(*) FROM bzreviews WHERE bizid=bp.bizid) AS 'ttlreviews', 
bp.phoneno, als.bizname, 
(SELECT COUNT(*) FROM endorsment WHERE bizid=bp.bizid) AS 'endorses'
, als.imgname, bp.`location`, bp.`ownership`, 
(SELECT COUNT(*) FROM follows WHERE bizid=bp.bizid) AS 'followers', 
bp.categories, bp.openhours, bp.bizdecri FROM bizprofile AS bp 
INNER JOIN alluser AS als ON bp.usrid=als.userid 
WHERE als.usertype='Business'

Changing image sizes proportionally using CSS?

You can use object-fit css3 property, something like

_x000D_
_x000D_
<!doctype html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset='utf-8'>_x000D_
  <style>_x000D_
    .holder {_x000D_
      display: inline;_x000D_
    }_x000D_
    .holder img {_x000D_
      max-height: 200px;_x000D_
      max-width: 200px;_x000D_
      object-fit: cover;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class='holder'>_x000D_
    <img src='meld.png'>_x000D_
  </div>_x000D_
  <div class='holder'>_x000D_
    <img src='twiddla.png'>_x000D_
  </div>_x000D_
  <div class='holder'>_x000D_
    <img src='meld.png'>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

It is not exactly your answer, though, because of it doesn't stretch the container, but it behaves like the gallery and you can keep styling the img itself.

Another drawback of this solution is still a poor support of the css3 property. More details are available here: http://www.steveworkman.com/html5-2/javascript/2012/css3-object-fit-polyfill/. jQuery solution can be found there as well.

Where in memory are my variables stored in C?

You got some of these right, but whoever wrote the questions tricked you on at least one question:

  • global variables -------> data (correct)
  • static variables -------> data (correct)
  • constant data types -----> code and/or data. Consider string literals for a situation when a constant itself would be stored in the data segment, and references to it would be embedded in the code
  • local variables(declared and defined in functions) --------> stack (correct)
  • variables declared and defined in main function -----> heap also stack (the teacher was trying to trick you)
  • pointers(ex: char *arr, int *arr) -------> heap data or stack, depending on the context. C lets you declare a global or a static pointer, in which case the pointer itself would end up in the data segment.
  • dynamically allocated space(using malloc, calloc, realloc) --------> stack heap

It is worth mentioning that "stack" is officially called "automatic storage class".

‘ant’ is not recognized as an internal or external command

When Environment variables are changed log off and log in again so that it will be applied.

React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined

You have to bind your event handlers to correct context (this):

onChange={this.setAuthorState.bind(this)}

<ng-container> vs <template>

Imo use cases for ng-container are simple replacements for which a custom template/component would be overkill. In the API doc they mention the following

use a ng-container to group multiple root nodes

and I guess that's what it is all about: grouping stuff.

Be aware that the ng-container directive falls away instead of a template where its directive wraps the actual content.

IF statement: how to leave cell blank if condition is false ("" does not work)

You can do something like this to show blank space:

=IF(AND((E2-D2)>0)=TRUE,E2-D2," ")

Inside if before first comma is condition then result and return value if true and last in value as blank if condition is false

Programmatically select a row in JTable

It is an old post, but I came across this recently

Selecting a specific interval

As @aleroot already mentioned, by using

table.setRowSelectionInterval(index0, index1);

You can specify an interval, which should be selected.

Adding an interval to the existing selection

You can also keep the current selection, and simply add additional rows by using this here

table.getSelectionModel().addSelectionInterval(index0, index1);

This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.

What is the difference between connection and read timeout for sockets?

  1. What is the difference between connection and read timeout for sockets?

The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data1. If the server (or network) fails to deliver any data <timeout> seconds after the client makes a socket read call, a read timeout error will be raised.

  1. What does connection timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?

It means that the connection attempt can potentially block for ever. There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket. (A Thread.interrupt() call may also do the trick ... not sure.)

  1. What does read timeout set to "infinity" mean? In what situation can it remain in an infinite loop? What can trigger that the infinite loop to end?

It means that a call to read on the socket stream may block for ever. Once again there is no infinite loop, but the read can be unblocked by a Thread.interrupt() call, closing the socket, and (of course) the other end sending data or closing the connection.


1 - It is not ... as one commenter thought ... the timeout on how long a socket can be open, or idle.

Call a function with argument list in python

The literal answer to your question (to do exactly what you asked, changing only the wrapper, not the functions or the function calls) is simply to alter the line

func(args)

to read

func(*args)

This tells Python to take the list given (in this case, args) and pass its contents to the function as positional arguments.

This trick works on both "sides" of the function call, so a function defined like this:

def func2(*args):
    return sum(args)

would be able to accept as many positional arguments as you throw at it, and place them all into a list called args.

I hope this helps to clarify things a little. Note that this is all possible with dicts/keyword arguments as well, using ** instead of *.

How to turn off caching on Firefox?

Have you tried to use CTRL-F5 to update the page?

How to display the string html contents into webbrowser control?

Old question, but here's my go-to for this operation.

If browser.Document IsNot Nothing Then
    browser.Document.OpenNew(True)
    browser.Document.Write(My.Resources.htmlTemplate)
Else
    browser.DocumentText = My.Resources.htmlTemplate
End If

And be sure that any browser.Navigating event DOES NOT cancel "about:blank" URLs. Example event below for full control of WebBrowser navigating.

Private Sub browser_Navigating(sender As Object, e As WebBrowserNavigatingEventArgs) Handles browser.Navigating

    Try
        Me.Cursor = Cursors.WaitCursor

        Select Case e.Url.Scheme

            Case Constants.App_Url_Scheme

                Dim query As Specialized.NameValueCollection = System.Web.HttpUtility.ParseQueryString(e.Url.Query)

                Select Case e.Url.Host

                    Case Constants.Navigation.URLs.ToggleExpander.Host

                        Dim nodeID As String = query.Item(Constants.Navigation.URLs.ToggleExpander.Parameters.NodeID)

                        :
                        :
                        <other operations here>
                        :
                        :

                End Select

            Case Else
                e.Cancel = (e.Url.ToString() <> "about:blank")

        End Select

    Catch ex As Exception
        ExceptionBox.Show(ex, "Operation failed.")
    Finally
        Me.Cursor = Cursors.Default
    End Try

End Sub

JavaScript: Create and destroy class instance through class method

1- There is no way to actually destroy an object in javascript, but using delete, we could remove a reference from an object:

var obj = {};
obj.mypointer = null;
delete obj.mypointer;

2- The important point about the delete keyword is that it does not actually destroy the object BUT if only after deleting that reference to the object, there is no other reference left in the memory pointed to the same object, that object would be marked as collectible. The delete keyword deletes the reference but doesn't GC the actual object. it means if you have several references of the same object, the object will be collected just after you delete all the pointed references.

3- there are also some tricks and workarounds that could help us out, when we want to make sure we do not leave any memory leaks behind. for instance if you have an array consisting several objects, without any other pointed reference to those objects, if you recreate the array all those objects would be killed. For instance if you have var array = [{}, {}] overriding the value of the array like array = [] would remove the references to the two objects inside the array and those two objects would be marked as collectible.

4- for your solution the easiest way is just this:

var storage = {};
storage.instance = new Class();
//since 'storage.instance' is your only reference to the object, whenever you wanted to destroy do this:
storage.instance = null;
// OR
delete storage.instance;

As mentioned above, either setting storage.instance = null or delete storage.instance would suffice to remove the reference to the object and allow it to be cleaned up by the GC. The difference is that if you set it to null then the storage object still has a property called instance (with the value null). If you delete storage.instance then the storage object no longer has a property named instance.

and WHAT ABOUT destroy method ??

the paradoxical point here is if you use instance.destroy in the destroy function you have no access to the actual instance pointer, and it won't let you delete it.

The only way is to pass the reference to the destroy function and then delete it:

// Class constructor
var Class = function () {
     this.destroy = function (baseObject, refName) {
         delete baseObject[refName];
     };
};

// instanciate
var storage = {};
storage.instance = new Class();
storage.instance.destroy(object, "instance");
console.log(storage.instance); // now it is undefined

BUT if I were you I would simply stick to the first solution and delete the object like this:

storage.instance = null;
// OR
delete storage.instance;

WOW it was too much :)

Control cannot fall through from one case label

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Case_example_1
{
    class Program
    {
        static void Main(string[] args)
        {
            Char ch;
            Console.WriteLine("Enter a character");
            ch =Convert.ToChar(Console.ReadLine());
            switch (ch)
            {
                case 'a':
                case 'e':
                case 'i':
                case 'o':
                case 'u':
                case 'A':
                case 'E':
                case 'I':
                case 'O':
                case 'U':

                    Console.WriteLine("Character is alphabet");
                    break;

                default:
                    Console.WriteLine("Character is constant");
                    break;

            }

            Console.ReadLine();

        }
    }
}

Import txt file and having each line as a list

with open('path/to/file') as infile: # try open('...', 'rb') as well
    answer = [line.strip().split(',') for line in infile]

If you want the numbers as ints:

with open('path/to/file') as infile:
    answer = [[int(i) for i in line.strip().split(',')] for line in infile]

Entity Framework: There is already an open DataReader associated with this Command

If we try to group part of our conditions into a Func<> or extension method we will get this error, suppose we have a code like this:

public static Func<PriceList, bool> IsCurrent()
{
  return p => (p.ValidFrom == null || p.ValidFrom <= DateTime.Now) &&
              (p.ValidTo == null || p.ValidTo >= DateTime.Now);
}

Or

public static IEnumerable<PriceList> IsCurrent(this IEnumerable<PriceList> prices) { .... }

This will throw the exception if we try to use it in a Where(), what we should do instead is to build a Predicate like this:

public static Expression<Func<PriceList, bool>> IsCurrent()
{
    return p => (p.ValidFrom == null || p.ValidFrom <= DateTime.Now) &&
                (p.ValidTo == null || p.ValidTo >= DateTime.Now);
}

Further more can be read at : http://www.albahari.com/nutshell/predicatebuilder.aspx

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

If you are using Bootstrap 3.3.x then use this code (you need to add class name carousel-fade to your carousel).

.carousel-fade .carousel-inner .item {
  -webkit-transition-property: opacity;
          transition-property: opacity;
}
.carousel-fade .carousel-inner .item,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  opacity: 0;
}
.carousel-fade .carousel-inner .active,
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
  opacity: 1;
}
.carousel-fade .carousel-inner .next,
.carousel-fade .carousel-inner .prev,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  left: 0;
  -webkit-transform: translate3d(0, 0, 0);
          transform: translate3d(0, 0, 0);
}
.carousel-fade .carousel-control {
  z-index: 2;
}

How to count check-boxes using jQuery?

The following code worked for me.

$('input[name="chkGender[]"]:checked').length;

Regular expression to find two strings anywhere in input

This works for searching files that contain both String1 and String2

(((.|\n)*)String1((.|\n)*)String2)|(((.|\n)*)String2((.|\n)*)String1)

Match any number of characters or line fields followed by String1 followed by any number of characters or line fields followed by String2 OR Match any number of characters or line fields followed by String2 followed by any number of characters or line fields followed by String1

Make index.html default, but allow index.php to be visited if typed in

By default, the DirectoryIndex is set to:

DirectoryIndex index.html index.htm default.htm index.php index.php3 index.phtml index.php5 index.shtml mwindex.phtml

Apache will look for each of the above files, in order, and serve the first one it finds when a visitor requests just a directory. If the webserver finds no files in the current directory that match names in the DirectoryIndex directive, then a directory listing will be displayed to the browser, showing all files in the current directory.

The order should be DirectoryIndex index.html index.php // default is index.html

Reference: Here.

How to run a shell script in OS X by double-clicking?

  • First in terminal make the script executable by typing the following command:

      chmod a+x yourscriptname
    
  • Then, in Finder, right-click your file and select "Open with" and then "Other...".

  • Here you select the application you want the file to execute into, in this case it would be Terminal. To be able to select terminal you need to switch from "Recommended Applications" to "All Applications". (The Terminal.app application can be found in the Utilities folder)

  • NOTE that unless you don't want to associate all files with this extension to be run in terminal you should not have "Always Open With" checked.

  • After clicking OK you should be able to execute you script by simply double-clicking it.

How to initialize an array in Java?

Try data = new int[] {10,20,30,40,50,60,71,80,90,91 };

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

I was facing the same problem and how i resolved see below steps or Image:

  1. Clicked on Windows menu item of eclipse
  2. Clicked on preferences
  3. select Installed JREs
  4. Add your installed jdk's path(JRE home: C:\Program Files\Java\jdk1.8.0_201\jre`)
  5. Add JRE name: jdk1.8.0_201
  6. Clicked on Finish
  7. Apply changes and close

enter image description here

VBA paste range

I would try

Sheets("Sheet1").Activate
Set Ticker = Range(Cells(2, 1), Cells(65, 1))
Ticker.Copy

Worksheets("Sheet2").Range("A1").Offset(0,0).Cells.Select
Worksheets("Sheet2").paste

ImportError: No module named sklearn.cross_validation

train_test_split is part of the module sklearn.model_selection, hence, you may need to import the module from model_selection

Code:

from sklearn.model_selection import train_test_split

Why is it string.join(list) instead of list.join(string)?

I agree that it's counterintuitive at first, but there's a good reason. Join can't be a method of a list because:

  • it must work for different iterables too (tuples, generators, etc.)
  • it must have different behavior between different types of strings.

There are actually two join methods (Python 3.0):

>>> b"".join
<built-in method join of bytes object at 0x00A46800>
>>> "".join
<built-in method join of str object at 0x00A28D40>

If join was a method of a list, then it would have to inspect its arguments to decide which one of them to call. And you can't join byte and str together, so the way they have it now makes sense.

What are intent-filters in Android?

When there are multiple activities set as main and launcher with an intent filter in the manifest. Then first activity considers as Launcher activity, and android launch or open the first activity.

<category android:name="android.intent.category.LAUNCHER" />  

The above code makes an app icon available in the device menu, so if we declare 2 launcher activity in the manifest, there will be 2 app icons get created in the device app menu.

So there will be 2 app icons, on click of the first icon, first declared activity in manifest will be launch, and click of another second declared activity gets launch

Where can I download Spring Framework jars without using Maven?

Please edit to keep this list of mirrors current

I found this maven repo where you could download from directly a zip file containing all the jars you need.

Alternate solution: Maven

The solution I prefer is using Maven, it is easy and you don't have to download each jar alone. You can do it with the following steps:

  1. Create an empty folder anywhere with any name you prefer, for example spring-source

  2. Create a new file named pom.xml

  3. Copy the xml below into this file

  4. Open the spring-source folder in your console

  5. Run mvn install

  6. After download finished, you'll find spring jars in /spring-source/target/dependencies

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>spring-source-download</groupId>
      <artifactId>SpringDependencies</artifactId>
      <version>1.0</version>
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      </properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-context</artifactId>
          <version>3.2.4.RELEASE</version>
        </dependency>
      </dependencies>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.8</version>
            <executions>
              <execution>
                <id>download-dependencies</id>
                <phase>generate-resources</phase>
                <goals>
                  <goal>copy-dependencies</goal>
                </goals>
                <configuration>
                  <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </project>
    

Also, if you need to download any other spring project, just copy the dependency configuration from its corresponding web page.

For example, if you want to download Spring Web Flow jars, go to its web page, and add its dependency configuration to the pom.xml dependencies, then run mvn install again.

<dependency>
  <groupId>org.springframework.webflow</groupId>
  <artifactId>spring-webflow</artifactId>
  <version>2.3.2.RELEASE</version>
</dependency>

How can I set the aspect ratio in matplotlib?

Third times the charm. My guess is that this is a bug and Zhenya's answer suggests it's fixed in the latest version. I have version 0.99.1.1 and I've created the following solution:

import matplotlib.pyplot as plt
import numpy as np

def forceAspect(ax,aspect=1):
    im = ax.get_images()
    extent =  im[0].get_extent()
    ax.set_aspect(abs((extent[1]-extent[0])/(extent[3]-extent[2]))/aspect)

data = np.random.rand(10,20)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data)
ax.set_xlabel('xlabel')
ax.set_aspect(2)
fig.savefig('equal.png')
ax.set_aspect('auto')
fig.savefig('auto.png')
forceAspect(ax,aspect=1)
fig.savefig('force.png')

This is 'force.png': enter image description here

Below are my unsuccessful, yet hopefully informative attempts.

Second Answer:

My 'original answer' below is overkill, as it does something similar to axes.set_aspect(). I think you want to use axes.set_aspect('auto'). I don't understand why this is the case, but it produces a square image plot for me, for example this script:

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(10,20)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data)
ax.set_aspect('equal')
fig.savefig('equal.png')
ax.set_aspect('auto')
fig.savefig('auto.png')

Produces an image plot with 'equal' aspect ratio: enter image description here and one with 'auto' aspect ratio: enter image description here

The code provided below in the 'original answer' provides a starting off point for an explicitly controlled aspect ratio, but it seems to be ignored once an imshow is called.

Original Answer:

Here's an example of a routine that will adjust the subplot parameters so that you get the desired aspect ratio:

import matplotlib.pyplot as plt

def adjustFigAspect(fig,aspect=1):
    '''
    Adjust the subplot parameters so that the figure has the correct
    aspect ratio.
    '''
    xsize,ysize = fig.get_size_inches()
    minsize = min(xsize,ysize)
    xlim = .4*minsize/xsize
    ylim = .4*minsize/ysize
    if aspect < 1:
        xlim *= aspect
    else:
        ylim /= aspect
    fig.subplots_adjust(left=.5-xlim,
                        right=.5+xlim,
                        bottom=.5-ylim,
                        top=.5+ylim)

fig = plt.figure()
adjustFigAspect(fig,aspect=.5)
ax = fig.add_subplot(111)
ax.plot(range(10),range(10))

fig.savefig('axAspect.png')

This produces a figure like so: enter image description here

I can imagine if your having multiple subplots within the figure, you would want to include the number of y and x subplots as keyword parameters (defaulting to 1 each) to the routine provided. Then using those numbers and the hspace and wspace keywords, you can make all the subplots have the correct aspect ratio.

Use Expect in a Bash script to provide a password to an SSH command

Add the 'interact' Expect command just before your EOD:

#!/bin/bash

read -s PWD

/usr/bin/expect <<EOD
spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no usr@$myhost.example.com
expect "password"
send "$PWD\n"
interact
EOD
echo "you're out"

This should let you interact with the remote machine until you log out. Then you'll be back in Bash.

Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"

Put in other words, this error is telling you that SQL Server does not know which B to select from the group.

Either you want to select one specific value (e.g. the MIN, SUM, or AVG) in which case you would use the appropriate aggregate function, or you want to select every value as a new row (i.e. including B in the GROUP BY field list).


Consider the following data:

ID  A   B
1   1  13
1   1  79
1   2  13
1   2  13
1   2  42

The query

SELECT A, COUNT(B) AS T1 
FROM T2 
GROUP BY A

would return:

A  T1
1  2
2  3

which is all well and good.

However consider the following (illegal) query, which would produce this error:

SELECT A, COUNT(B) AS T1, B 
FROM T2 
GROUP BY A

And its returned data set illustrating the problem:

A  T1  B
1  2   13? 79? Both 13 and 79 as separate rows? (13+79=92)? ...?
2  3   13? 42? ...?

However, the following two queries make this clear, and will not cause the error:

  1. Using an aggregate

    SELECT A, COUNT(B) AS T1, SUM(B) AS B
    FROM T2
    GROUP BY A
    

    would return:

    A  T1  B
    1  2   92
    2  3   68
    
  2. Adding the column to the GROUP BY list

    SELECT A, COUNT(B) AS T1, B
    FROM T2
    GROUP BY A, B
    

    would return:

    A  T1  B
    1  1   13
    1  1   79
    2  2   13
    2  1   42
    

UTF-8 encoding in JSP page

i add this shell script to convert jsp files from IS

#!/bin/sh

###############################################
## this script file must be placed in the parent  
## folder of the to folders "in" and "out"
## in contain the input jsp files
## out will containt the generated jsp files
## 
###############################################

find in/ -name *.jsp | 
    while read line; do 
        outpath=`echo $line | sed -e 's/in/out/'` ;
        parentdir=`echo $outpath | sed -e 's/[^\/]*\.jsp$//'` ;
        mkdir -p $parentdir
        echo $outpath ;
        iconv -t UTF-8 -f ISO-8859-1 -o $outpath $line ;
    done 

Resize image proportionally with CSS?

<img style="width: 50%;" src="..." />

worked just fine for me ... Or am I missing something?

Edit: But see Shawn's caveat about accidentally upsizing.

Fastest way to get the first object from a queryset in django?

Use the convenience methods .first() and .last():

MyModel.objects.filter(blah=blah).first()

They both swallow the resulting exception and return None if the queryset returns no objects.

These were added in Django 1.6, which was released in Nov 2013.

Remove specific rows from a data frame

 X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
  Variable1 Variable2
1        11         2
2        14         3
3        12         1
4        15         4
> X[X$Variable1!=11 & X$Variable1!=12, ]
  Variable1 Variable2
2        14         3
4        15         4
> X[ ! X$Variable1 %in% c(11,12), ]
  Variable1 Variable2
2        14         3
4        15         4

You can functionalize this however you like.

Get sum of MySQL column in PHP

$query = "SELECT * FROM tableName";
$query_run = mysql_query($query);

$qty= 0;
while ($num = mysql_fetch_assoc ($query_run)) {
    $qty += $num['ColumnName'];
}
echo $qty;

How to add a button programmatically in VBA next to some sheet cell data?

Suppose your function enters data in columns A and B and you want to a custom Userform to appear if the user selects a cell in column C. One way to do this is to use the SelectionChange event:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim clickRng As Range
    Dim lastRow As Long

    lastRow = Range("A1").End(xlDown).Row
    Set clickRng = Range("C1:C" & lastRow) //Dynamically set cells that can be clicked based on data in column A

    If Not Intersect(Target, clickRng) Is Nothing Then
        MyUserForm.Show //Launch custom userform
    End If

End Sub

Note that the userform will appear when a user selects any cell in Column C and you might want to populate each cell in Column C with something like "select cell to launch form" to make it obvious that the user needs to perform an action (having a button naturally suggests that it should be clicked)

How do you delete an ActiveRecord object?

  1. User.destroy

User.destroy(1) will delete user with id == 1 and :before_destroy and :after_destroy callbacks occur. For example if you have associated records

has_many :addresses, :dependent => :destroy

After user is destroyed his addresses will be destroyed too. If you use delete action instead, callbacks will not occur.

  1. User.destroy, User.delete

  2. User.destroy_all(<conditions>) or User.delete_all(<conditions>)

Notice: User is a class and user is an instance object

Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope?

The controller function/object represents an abstraction model-view-controller (MVC). While there is nothing new to write about MVC, it is still the most significant advanatage of angular: split the concerns into smaller pieces. And that's it, nothing more, so if you need to react on Model changes coming from View the Controller is the right person to do that job.

The story about link function is different, it is coming from different perspective then MVC. And is really essential, once we want to cross the boundaries of a controller/model/view (template).

Let' start with the parameters which are passed into the link function:

function link(scope, element, attrs) {
  • scope is an Angular scope object.
  • element is the jqLite-wrapped element that this directive matches.
  • attrs is an object with the normalized attribute names and their corresponding values.

To put the link into the context, we should mention that all directives are going through this initialization process steps: Compile, Link. An Extract from Brad Green and Shyam Seshadri book Angular JS:

Compile phase (a sister of link, let's mention it here to get a clear picture):

In this phase, Angular walks the DOM to identify all the registered directives in the template. For each directive, it then transforms the DOM based on the directive’s rules (template, replace, transclude, and so on), and calls the compile function if it exists. The result is a compiled template function,

Link phase:

To make the view dynamic, Angular then runs a link function for each directive. The link functions typically creates listeners on the DOM or the model. These listeners keep the view and the model in sync at all times.

A nice example how to use the link could be found here: Creating Custom Directives. See the example: Creating a Directive that Manipulates the DOM, which inserts a "date-time" into page, refreshed every second.

Just a very short snippet from that rich source above, showing the real manipulation with DOM. There is hooked function to $timeout service, and also it is cleared in its destructor call to avoid memory leaks

.directive('myCurrentTime', function($timeout, dateFilter) {

 function link(scope, element, attrs) {

 ...

 // the not MVC job must be done
 function updateTime() {
   element.text(dateFilter(new Date(), format)); // here we are manipulating the DOM
 }

 function scheduleUpdate() {
   // save the timeoutId for canceling
   timeoutId = $timeout(function() {
     updateTime(); // update DOM
     scheduleUpdate(); // schedule the next update
   }, 1000);
 }

 element.on('$destroy', function() {
   $timeout.cancel(timeoutId);
 });

 ...

define a List like List<int,string>?

You could use an immutable struct

public struct Data
{
    public Data(int intValue, string strValue)
    {
        IntegerData = intValue;
        StringData = strValue;
    }

    public int IntegerData { get; private set; }
    public string StringData { get; private set; }
}

var list = new List<Data>();

Or a KeyValuePair<int, string>

using Data = System.Collections.Generic.KeyValuePair<int, string>
...
var list = new List<Data>();
list.Add(new Data(12345, "56789"));

Setting the Textbox read only property to true using JavaScript

Using asp.net, I believe you can do it this way :

myTextBox.Attributes.Add("readonly","readonly")

Best way to convert list to comma separated string in java

From Apache Commons library:

import org.apache.commons.lang3.StringUtils

Use:

StringUtils.join(slist, ',');

Another similar question and answer here

How to set layout_gravity programmatically?

I use someting like that: (Xamarin and C# code)

  LinearLayout linLayout= new LinearLayout(this); 
    linLayout.SetGravity(GravityFlags.Center);

    TextView txtView= new TextView(this);  
     linLayout.AddView(txtView); 

the SetGravity puts my textView in the center of the layout. So SetGravity layout property refer to layout content

Shuffle DataFrame rows

shuffle the pandas data frame by taking a sample array in this case index and randomize its order then set the array as an index of data frame. Now sort the data frame according to index. Here goes your shuffled dataframe

import random
df = pd.DataFrame({"a":[1,2,3,4],"b":[5,6,7,8]})
index = [i for i in range(df.shape[0])]
random.shuffle(index)
df.set_index([index]).sort_index()

output

    a   b
0   2   6
1   1   5
2   3   7
3   4   8

Insert you data frame in the place of mine in above code .

In jQuery how can I set "top,left" properties of an element with position values relative to the parent and not the document?

I found that if the value passed is a string type, it must be followed by 'px' (i.e. 90px), where if the value is an integer, it will append the px automatically. the width and height properties are more forgiving (either type works).

var x = "90";
var y = "120"
$(selector).css( { left: x, top: y } )        //doesn't work
$(selector).css( { left: x + "px", top: y + "px" } )        //does work

x = 90;
y = 120;
$(selector).css( { left: x, top: y } )        //does work

What are the differences between the BLOB and TEXT datatypes in MySQL?

TEXT and CHAR will convert to/from the character set they have associated with time. BLOB and BINARY simply store bytes.

BLOB is used for storing binary data while Text is used to store large string.

BLOB values are treated as binary strings (byte strings). They have no character set, and sorting and comparison are based on the numeric values of the bytes in column values.

TEXT values are treated as nonbinary strings (character strings). They have a character set, and values are sorted and compared based on the collation of the character set.

http://dev.mysql.com/doc/refman/5.0/en/blob.html

Interfaces with static fields in java for sharing 'constants'

Instead of implementing a "constants interface", in Java 1.5+, you can use static imports to import the constants/static methods from another class/interface:

import static com.kittens.kittenpolisher.KittenConstants.*;

This avoids the ugliness of making your classes implement interfaces that have no functionality.

As for the practice of having a class just to store constants, I think it's sometimes necessary. There are certain constants that just don't have a natural place in a class, so it's better to have them in a "neutral" place.

But instead of using an interface, use a final class with a private constructor. (Making it impossible to instantiate or subclass the class, sending a strong message that it doesn't contain non-static functionality/data.)

Eg:

/** Set of constants needed for Kitten Polisher. */
public final class KittenConstants
{
    private KittenConstants() {}

    public static final String KITTEN_SOUND = "meow";
    public static final double KITTEN_CUTENESS_FACTOR = 1;
}

Best approach to converting Boolean object to string in java

public class Sandbox {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Boolean b = true;
        boolean z = false;
        echo (b);
        echo (z);
        echo ("Value of b= " + b +"\nValue of z= " + z);
    }

    public static void echo(Object obj){
        System.out.println(obj);
    } 

}
Result
--------------
true
false
Value of b= true
Value of z= false
--------------

problem with <select> and :after with CSS in WebKit

This is a modern solution I cooked up using font-awesome. Vendor extensions have been omitted for brevity.

HTML

<fieldset>
    <label for="color">Select Color</label>
    <div class="select-wrapper">
        <select id="color">
            <option>Red</option>
            <option>Blue</option>
            <option>Yellow</option>
        </select>
        <i class="fa fa-chevron-down"></i>
    </div>
</fieldset>

SCSS

fieldset {
    .select-wrapper {
        position: relative;

        select {
            appearance: none;
            position: relative;
            z-index: 1;
            background: transparent;

            + i {
                position: absolute;
                top: 40%;
                right: 15px;
            }
        }
    }

If your select element has a defined background color, then this won't work as this snippet essentially places the Chevron icon behind the select element (to allow clicking on top of the icon to still initiate the select action).

However, you can style the select-wrapper to the same size as the select element and style its background to achieve the same effect.

Check out my CodePen for a working demo that shows this bit of code on both a dark and light themed select box using a regular label and a "placeholder" label and other cleaned up styles such as borders and widths.

P.S. This is an answer I had posted to another, duplicate question earlier this year.

Recommended way to insert elements into map

To quote:

Because map containers do not allow for duplicate key values, the insertion operation checks for each element inserted whether another element exists already in the container with the same key value, if so, the element is not inserted and its mapped value is not changed in any way.

So insert will not change the value if the key already exists, the [] operator will.

EDIT:

This reminds me of another recent question - why use at() instead of the [] operator to retrieve values from a vector. Apparently at() throws an exception if the index is out of bounds whereas [] operator doesn't. In these situations it's always best to look up the documentation of the functions as they will give you all the details. But in general, there aren't (or at least shouldn't be) two functions/operators that do the exact same thing.

My guess is that, internally, insert() will first check for the entry and afterwards itself use the [] operator.

Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly

Use this, FrontData is JSON string:

var objResponse1 = JsonConvert.DeserializeObject<List<DataTransfer>>(FrontData);  

and extract list:

var a = objResponse1[0];
var b = a.CustomerData;

Definition of "downstream" and "upstream"

In terms of source control, you're "downstream" when you copy (clone, checkout, etc) from a repository. Information flowed "downstream" to you.

When you make changes, you usually want to send them back "upstream" so they make it into that repository so that everyone pulling from the same source is working with all the same changes. This is mostly a social issue of how everyone can coordinate their work rather than a technical requirement of source control. You want to get your changes into the main project so you're not tracking divergent lines of development.

Sometimes you'll read about package or release managers (the people, not the tool) talking about submitting changes to "upstream". That usually means they had to adjust the original sources so they could create a package for their system. They don't want to keep making those changes, so if they send them "upstream" to the original source, they shouldn't have to deal with the same issue in the next release.

How to convert a string to integer in C?

You can always roll your own!

#include <stdio.h>
#include <string.h>
#include <math.h>

int my_atoi(const char* snum)
{
    int idx, strIdx = 0, accum = 0, numIsNeg = 0;
    const unsigned int NUMLEN = (int)strlen(snum);

    /* Check if negative number and flag it. */
    if(snum[0] == 0x2d)
        numIsNeg = 1;

    for(idx = NUMLEN - 1; idx >= 0; idx--)
    {
        /* Only process numbers from 0 through 9. */
        if(snum[strIdx] >= 0x30 && snum[strIdx] <= 0x39)
            accum += (snum[strIdx] - 0x30) * pow(10, idx);

        strIdx++;
    }

    /* Check flag to see if originally passed -ve number and convert result if so. */
    if(!numIsNeg)
        return accum;
    else
        return accum * -1;
}

int main()
{
    /* Tests... */
    printf("Returned number is: %d\n", my_atoi("34574"));
    printf("Returned number is: %d\n", my_atoi("-23"));

    return 0;
}

This will do what you want without clutter.

How can I store JavaScript variable output into a PHP variable?

You have to remember that if JS and PHP live in the same document, the PHP will be executed first (at the server) and the JS will be executed second (at the browser)--and the two will NEVER interact (excepting where you output JS with PHP, which is not really an interaction between the two engines).

With that in mind, the closest you could come is to use a PHP variable in your JS:

<?php
$a = 'foo'; // $a now holds PHP string foo
?>
<script>
    var a = '<?php echo $a; ?>'; //outputting string foo in context of JS
                                 //must wrap in quotes so that it is still string foo when JS does execute
                                 //when this DOES execute in the browser, PHP will have already completed all processing and exited
</script>
<?php
//do something else with $a
//JS still hasn't executed at this point
?>

As I stated, in this scenario the PHP (ALL of it) executes FIRST at the server, causing:

  1. a PHP variable $a to be created as string 'foo'
  2. the value of $a to be outputted in context of some JavaScript (which is not currently executing)
  3. more done with PHP's $a
  4. all output, including the JS with the var assignment, is sent to the browser.

As written, this results in the following being sent to the browser for execution (I removed the JS comments for clarity):

<script>
    var a = 'foo';
</script>

Then, and only then, will the JS start executing with its own variable a set to "foo" (at which point PHP is out of the picture).

In other words, if the two live in the same document and no extra interaction with the server is performed, JS can NOT cause any effect in PHP. Furthermore, PHP is limited in its effect on JS to the simple ability to output some JS or something in context of JS.

How to set the JDK Netbeans runs on?

IN windows open cmd

go to directory where your netbeans downloaded

then run below command JDK path may be different from the path I mentioned

netbeans-8.2-windows.exe --javahome "C:\Program Files\Java\jdk-9.0.1"

if you face issue in existing installed in netbeans you can find details in here

How can I cast int to enum?

From a string: (Enum.Parse is out of Date, use Enum.TryParse)

enum Importance
{}

Importance importance;

if (Enum.TryParse(value, out importance))
{
}

How to get span tag inside a div in jQuery and assign a text?

$("#message > span").text("your text");

or

$("#message").find("span").text("your text");

or

$("span","#message").text("your text");

or

$("#message > a.close-notify").siblings('span').text("your text");

Ignoring new fields on JSON objects using Jackson

Make sure that you place the @JsonIgnoreProperties(ignoreUnknown = true) annotation to the parent POJO class which you want to populate as a result of parsing the JSON response and not the class where the conversion from JSON to Java Object is taking place.

Wrapping a react-router Link in an html button

I use Router and < Button/>. No < Link/>

<Button onClick={()=> {this.props.history.replace('/mypage')}}>
   HERE
</Button>

Is it valid to replace http:// with // in a <script src="http://...">?

We are seeing 404 errors in our logs when using //somedomain.com as references to JS files.

The references that cause the 404s come out looking like this: ref:

<script src="//somedomain.com/somescript.js" />

404 request:

http://mydomain.com//somedomain.com/somescript.js

With these showing up regularly in our web server logs, it is safe to say that: All browsers and Bots DO NOT honor RFC 3986 section 4.2. The safest bet is to include the protocol whenever possible.

Incomplete type is not allowed: stringstream

Some of the system headers provide a forward declaration of std::stringstream without the definition. This makes it an 'incomplete type'. To fix that you need to include the definition, which is provided in the <sstream> header:

#include <sstream>

How to set HTML Auto Indent format on Sublime Text 3?

Create a Keybinding

To auto indent on Sublime text 3 with a key bind try going to

Preferences > Key Bindings - users

And adding this code between the square brackets

{"keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false}}

it sets shift + alt + f to be your full page auto indent.

Source here

Note: if this doesn't work correctly then you should convert your indentation to tabs. Also comments in your code can push your code to the wrong indentation level and may have to be moved manually.

R color scatter plot points based on values

Also it'd work to just specify ifelse() twice:

plot(pos,cn, col= ifelse(cn >= 3, "red", ifelse(cn <= 1,"blue", "black")), ylim = c(0, 10))

SHA-1 fingerprint of keystore certificate

I had a problem during opening with command

[keytool -list -v -keystore C:\Users\MG\Desktop\test.jks -alias test]

Therefore, i download https://sourceforge.net/projects/portecle/. Then just open .jks file from the jar program. it will show you all relevant information

snapshot of the program

Get User Selected Range

You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):

Sub Count_Selection()
    Dim cell As Object
    Dim count As Integer
    count = 0
    For Each cell In Selection
        count = count + 1
    Next cell
    MsgBox count & " item(s) selected"
End Sub

Test method is inconclusive: Test wasn't run. Error?

In my case, ReSharper gave me this additional exception in the test window:

2017.06.15 12:56:57.621   ERROR Exploration failed with the exception:
System.AggregateException: One or more errors occurred. ---> System.Threading.Tasks.TaskCanceledException: A task was canceled.
   --- End of inner exception stack trace ---
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at JetBrains.ReSharper.UnitTestFramework.Launch.Stages.DiscoveryStage.Run(CancellationToken token)
---> (Inner Exception #0) System.Threading.Tasks.TaskCanceledException: A task was canceled.<---

it ended up that the test projects giving this error both were not set to build at all in the Configuration Manager. Checking the checkbox to build the 2 test projects and rebuilding sorted for me.

enter image description here

How to remove trailing and leading whitespace for user-provided input in a batch file?

A very short & easy solution i'm using is this:

@ECHO OFF

SET /p NAME=- NAME ? 
ECHO "%NAME%"
CALL :TRIM %NAME% NAME
ECHO "%NAME%"
PAUSE

:TRIM
SET %2=%1
GOTO :EOF

Results in:

- NAME ?  my_name
" my_name "
"my_name"

Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"

It wasn't in the path. Finally fixed by uninstalling java, removing all references to it from the registry, and then re-installing. None the wiser, but back working again. Thanks all @Highland Mark- Can you tell me the process to removing references from registry. I tried all possible way people mentioned here, nothing worked.

Java 8 Distinct by property

Maybe will be useful for somebody. I had a little bit another requirement. Having list of objects A from 3rd party remove all which have same A.b field for same A.id (multiple A object with same A.id in list). Stream partition answer by Tagir Valeev inspired me to use custom Collector which returns Map<A.id, List<A>>. Simple flatMap will do the rest.

 public static <T, K, K2> Collector<T, ?, Map<K, List<T>>> groupingDistinctBy(Function<T, K> keyFunction, Function<T, K2> distinctFunction) {
    return groupingBy(keyFunction, Collector.of((Supplier<Map<K2, T>>) HashMap::new,
            (map, error) -> map.putIfAbsent(distinctFunction.apply(error), error),
            (left, right) -> {
                left.putAll(right);
                return left;
            }, map -> new ArrayList<>(map.values()),
            Collector.Characteristics.UNORDERED)); }

What is the best way to implement nested dictionaries?

I find setdefault quite useful; It checks if a key is present and adds it if not:

d = {}
d.setdefault('new jersey', {}).setdefault('mercer county', {})['plumbers'] = 3

setdefault always returns the relevant key, so you are actually updating the values of 'd' in place.

When it comes to iterating, I'm sure you could write a generator easily enough if one doesn't already exist in Python:

def iterateStates(d):
    # Let's count up the total number of "plumbers" / "dentists" / etc.
    # across all counties and states
    job_totals = {}

    # I guess this is the annoying nested stuff you were talking about?
    for (state, counties) in d.iteritems():
        for (county, jobs) in counties.iteritems():
            for (job, num) in jobs.iteritems():
                # If job isn't already in job_totals, default it to zero
                job_totals[job] = job_totals.get(job, 0) + num

    # Now return an iterator of (job, number) tuples
    return job_totals.iteritems()

# Display all jobs
for (job, num) in iterateStates(d):
    print "There are %d %s in total" % (job, num)

How do I start my app on startup?

This is how to make an activity start running after android device reboot:

Insert this code in your AndroidManifest.xml file, within the <application> element (not within the <activity> element):

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

<receiver
    android:enabled="true"
    android:exported="true" 
    android:name="yourpackage.yourActivityRunOnStartup"
    android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.QUICKBOOT_POWERON" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>

</receiver>

Then create a new class yourActivityRunOnStartup (matching the android:name specified for the <receiver> element in the manifest):

package yourpackage;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class yourActivityRunOnStartup extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            Intent i = new Intent(context, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        }
    }

}

Note: The call i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); is important because the activity is launched from a context outside the activity. Without this, the activity will not start.

Also, the values android:enabled, android:exported and android:permission in the <receiver> tag do not seem mandatory. The app receives the event without these values. See the example here.

javascript how to create a validation error message without using alert

You need to stop the submission if an error occured:

HTML

<form name ="myform" onsubmit="return validation();"> 

JS

if (document.myform.username.value == "") {
     document.getElementById('errors').innerHTML="*Please enter a username*";
     return false;
}

SQL SELECT multi-columns INTO multi-variable

SELECT @variable1 = col1, @variable2 = col2
FROM table1

How to use onClick() or onSelect() on option tag in a JSP page?

In my case:

<html>
 <head>
  <script type="text/javascript">

    function changeFunction(val) {

       //Show option value
       console.log(val.value);
    }

  </script>
 </head>
 <body>
   <select id="selectBox" onchange="changeFunction(this)">
     <option value="1">Option #1</option>
     <option value="2">Option #2</option>
   </select>
 </body>
</html>

UITextField border color

Here's a Swift implementation. You can make an extension so that it will be usable by other views if you like.

extension UIView {
    func addBorderAndColor(color: UIColor, width: CGFloat, corner_radius: CGFloat = 0, clipsToBounds: Bool = false) {
        self.layer.borderWidth  = width
        self.layer.borderColor  = color.cgColor
        self.layer.cornerRadius = corner_radius
        self.clipsToBounds      = clipsToBounds
    }
}

Call this like: email.addBorderAndColor(color: UIColor.white, width: 0.5, corner_radius: 5, clipsToBounds: true).

Manifest merger failed : uses-sdk:minSdkVersion 14

Solution 1:

Change uses-sdk to <uses-sdk tools:node="replace" /> and add xmlns:tools="http://schemas.android.com/tools" in AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.demo.android"
    android:versionCode="16"
    android:versionName="3.3.1">
    .
    .
    <uses-sdk tools:node="replace" />
    .
    .
</manifest>

Make sure you use gradle 0.11 and above to use Manifest merger.

Solution 2:

  • Change compile 'com.android.support:support-v4:+' to compile 'com.android.support:support-v4:20.+' in build.gradle. This will prevent gradle from using v4:21.0.0 that requires version L.

  • However, if your any of your external dependencies uses the same. You will probably have to wait for them to update the same.

Solution 3:

  • Remove/Comment <version>21.0.0-rc1</version> in your file <android-sdk>/extras/android/m2repository/com/android/support-v4/maven-metadata.xml

  • Repeat the same for support-v7

Node.js Mongoose.js string to ObjectId function

Judging from the comments, you are looking for:

mongoose.mongo.BSONPure.ObjectID.isValid

Or

mongoose.Types.ObjectId.isValid

Equivalent of Oracle's RowID in SQL Server

I took this example from MS SQL example and you can see the @ID can be interchanged with integer or varchar or whatever. This was the same solution I was looking for, so I am sharing it. Enjoy!!

-- UPDATE statement with CTE references that are correctly matched.
DECLARE @x TABLE (ID int, Stad int, Value int, ison bit);
INSERT @x VALUES (1, 0, 10, 0), (2, 1, 20, 0), (6, 0, 40, 0), (4, 1, 50, 0), (5, 3, 60, 0), (9, 6, 20, 0), (7, 5, 10, 0), (8, 8, 220, 0);
DECLARE @Error int;
DECLARE @id int;

WITH cte AS (SELECT top 1 * FROM @x WHERE Stad=6)
UPDATE x -- cte is referenced by the alias.
SET ison=1, @id=x.ID
FROM cte AS x

SELECT *, @id as 'random' from @x
GO

How to convert a string Date to long millseconds

Try below code

        SimpleDateFormat f = new SimpleDateFormat("your_string_format", Locale.getDefault());
        Date d = null;
        try {
            d = f.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long timeInMillis = d.getTime();

Why does Firebug say toFixed() is not a function?

You need convert to number type:

(+Low).toFixed(2)

Why do we use volatile keyword?

Consider this code,

int some_int = 100;

while(some_int == 100)
{
   //your code
}

When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int, so it may be tempted to optimize the while loop by changing it from while(some_int == 100) to something which is equivalent to while(true) so that the execution could be fast (since the condition in while loop appears to be true always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int and compare it with 100, in each iteration which obviously is a little bit slow.)

However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!

So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while loop. That is where the volatile keyword plays its role. All you need to do is this,

volatile int some_int = 100; //note the 'volatile' qualifier now!

In other words, I would explain this as follows:

volatile tells the compiler that,

"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"

Well, that is how volatile prevents the compiler from optimizing code. Now search the web to see some sample examples.


Quoting from the C++ Standard ($7.1.5.1/8)

[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]

Related topic:

Does making a struct volatile make all its members volatile?

Issue with adding common code as git submodule: "already exists in the index"

You need to remove your submodule git repository (projectfolder in this case) first for git path.

rm -rf projectfolder

git rm -r projectfolder

and then add submodule

git submodule add <git_submodule_repository> projectfolder

Force HTML5 youtube video

I tried using the iframe embed code and the HTML5 player appeared, however, for some reason the iframe was completely breaking my site.

I messed around with the old object embed code and it works perfectly fine. So if you're having problems with the iframe here's the code i used:

<object width="640" height="360">
<param name="movie" value="http://www.youtube.com/embed/VIDEO_ID?html5=1&amp;rel=0&amp;hl=en_US&amp;version=3"/>
<param name="allowFullScreen" value="true"/>
<param name="allowscriptaccess" value="always"/>
<embed width="640" height="360" src="http://www.youtube.com/embed/VIDEO_ID?html5=1&amp;rel=0&amp;hl=en_US&amp;version=3" class="youtube-player" type="text/html" allowscriptaccess="always" allowfullscreen="true"/>
</object>

hope this is useful for someone

Using BufferedReader to read Text File

Use try with resources. this will automatically close the resources.

try (BufferedReader br = new BufferedReader(new FileReader("C:/test.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (Exception e) {

}

Create a new database with MySQL Workbench

In MySQL Work bench 6.0 CE.

  1. You launch MySQL Workbench.
  2. From Menu Bar click on Database and then select "Connect to Database"
  3. It by default showing you default settings other wise you choose you host name, user name and password. and click to ok.
  4. As in above define that you should click write on existing database but if you don't have existing new database then you may choose the option from the icon menu that is provided on below the menu bar. Now keep the name as you want and enjoy ....

Intent from Fragment to Activity

Try this code once-

public class FindPeopleFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_home,
        container, false);
        Button button = (Button) rootView.findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        updateDetail();
        }
        });
        return rootView;
        }

public void updateDetail() {
        Intent intent = new Intent(getActivity(), MainActivityList.class);
        startActivity(intent);
        }
}

And as suggested by Raghunandan remove below code from your fragment_home.xml-

android:onClick="goToAttract"

Can I access a form in the controller?

Definitely you can't access form in scope bec. it is not created. The DOM from html template is loaded little bit slowly like controller constructor. the solution is to watch until DOM loaded and all the scope defined!

in controller:

$timeout(function(){
    console.log('customerForm:', $scope.customerForm);
    // everything else what you need
});

Why I've got no crontab entry on OS X when using vim?

Other option is not to use crontab -e at all. Instead I used:

(crontab -l && echo "1 1  * * *  /path/to/my/script.sh") | crontab -

Notice that whatever you print before | crontab - will replace the entire crontab file, so use crontab -l && echo "<your new schedule>" to get the previous content and the new schedule.

Uncaught SyntaxError: Invalid or unexpected token

I also had an issue with multiline strings in this scenario. @Iman's backtick(`) solution worked great in the modern browsers but caused an invalid character error in Internet Explorer. I had to use the following:

'@item.MultiLineString.Replace(Environment.NewLine, "<br />")'

Then I had to put the carriage returns back again in the js function. Had to use RegEx to handle multiple carriage returns.

// This will work for the following:
// "hello\nworld"
// "hello<br>world"
// "hello<br />world"
$("#MyTextArea").val(multiLineString.replace(/\n|<br\s*\/?>/gi, "\r"));

WHERE statement after a UNION in SQL?

You probably need to wrap the UNION in a sub-SELECT and apply the WHERE clause afterward:

SELECT * FROM (
    SELECT * FROM Table1 WHERE Field1 = Value1
    UNION
    SELECT * FROM Table2 WHERE Field1 = Value2
) AS t WHERE Field2 = Value3

Basically, the UNION is looking for two complete SELECT statements to combine, and the WHERE clause is part of the SELECT statement.

It may make more sense to apply the outer WHERE clause to both of the inner queries. You'll probably want to benchmark the performance of both approaches and see which works better for you.

How can I strip all punctuation from a string in JavaScript using regex?

Here are the standard punctuation characters for US-ASCII: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

For Unicode punctuation (such as curly quotes, em-dashes, etc), you can easily match on specific block ranges. The General Punctuation block is \u2000-\u206F, and the Supplemental Punctuation block is \u2E00-\u2E7F.

Put together, and properly escaped, you get the following RegExp:

/[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]/

That should match pretty much any punctuation you encounter. So, to answer the original question:

var punctRE = /[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,\-.\/:;<=>?@\[\]^_`{|}~]/g;
var spaceRE = /\s+/g;
var str = "This, -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
str.replace(punctRE, '').replace(spaceRE, ' ');

>> "This is an example of a string with punctuation"

US-ASCII source: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#posix

Unicode source: http://kourge.net/projects/regexp-unicode-block

JavaScript dictionary with names

An easier, native and more efficient way of emulating a dict in JavaScript than a hash table:

It also exploits that JavaScript is weakly typed. Rather type inference.

Here's how (an excerpt from Google Chrome's console):

var myDict = {};

myDict.one = 1;
1

myDict.two = 2;
2

if (myDict.hasOwnProperty('three'))
{
  console.log(myDict.two);
}
else
{
  console.log('Key does not exist!');
}
Key does not exist! VM361:8

if (myDict.hasOwnProperty('two'))
{
  console.log(myDict.two);
}
else
{
  console.log('Key does not exist!');
}
2 VM362:4

Object.keys(myDict);
["one", "two"]

delete(myDict.two);
true

myDict.hasOwnProperty('two');
false

myDict.two
undefined

myDict.one
1

How to update and delete a cookie?

http://www.quirksmode.org/js/cookies.html

update would just be resetting it using createCookie

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 *1000));
        var expires = "; expires=" + date.toGMTString();
    } else {
        var expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1,c.length);
        }
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length,c.length);
        }
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

How to put more than 1000 values into an Oracle IN clause

Use ...from table(... :

create or replace type numbertype
as object
(nr number(20,10) )
/ 

create or replace type number_table
as table of numbertype
/ 

create or replace procedure tableselect
( p_numbers in number_table
, p_ref_result out sys_refcursor)
is
begin
  open p_ref_result for
    select *
    from employees , (select /*+ cardinality(tab 10) */ tab.nr from table(p_numbers) tab) tbnrs 
    where id = tbnrs.nr; 
end; 
/ 

This is one of the rare cases where you need a hint, else Oracle will not use the index on column id. One of the advantages of this approach is that Oracle doesn't need to hard parse the query again and again. Using a temporary table is most of the times slower.

edit 1 simplified the procedure (thanks to jimmyorr) + example

create or replace procedure tableselect
( p_numbers in number_table
, p_ref_result out sys_refcursor)
is
begin
  open p_ref_result for
    select /*+ cardinality(tab 10) */ emp.*
    from  employees emp
    ,     table(p_numbers) tab
    where tab.nr = id;
end;
/

Example:

set serveroutput on 

create table employees ( id number(10),name varchar2(100));
insert into employees values (3,'Raymond');
insert into employees values (4,'Hans');
commit;

declare
  l_number number_table := number_table();
  l_sys_refcursor sys_refcursor;
  l_employee employees%rowtype;
begin
  l_number.extend;
  l_number(1) := numbertype(3);
  l_number.extend;
  l_number(2) := numbertype(4);
  tableselect(l_number, l_sys_refcursor);
  loop
    fetch l_sys_refcursor into l_employee;
    exit when l_sys_refcursor%notfound;
    dbms_output.put_line(l_employee.name);
  end loop;
  close l_sys_refcursor;
end;
/

This will output:

Raymond
Hans

Validation of radio button group using jQuery validation plugin

With newer releases of jquery (1.3+ I think), all you have to do is set one of the members of the radio set to be required and jquery will take care of the rest:

<input type="radio" name="myoptions" value="blue" class="required"> Blue<br />
<input type="radio" name="myoptions" value="red"> Red<br />
<input type="radio" name="myoptions" value="green"> Green

The above would require at least 1 of the 3 radio options w/ the name of "my options" to be selected before proceeding.

The label suggestion by Mahes, btw, works wonderfully!

How do I horizontally center an absolute positioned element inside a 100% width div?

Its easy, just wrap it in a relative box like so:

<div class="relative">
 <div class="absolute">LOGO</div>
</div>

The relative box has a margin: 0 Auto; and, important, a width...

Installing specific laravel version with composer create-project

If you want to use a stable version of your preferred Laravel version of choice, use:

composer create-project --prefer-dist laravel/laravel project-name "5.5.*"

That will pick out the most recent or best update of version 5.5.* (5.5.28)

Finish all previous activities

Log in->Home->screen 1->screen 2->screen 3->screen 4->screen 5

on screen 4 (or any other) ->

StartActivity(Log in)
with
FLAG_ACTIVITY_CLEAR_TOP

How to 'grep' a continuous stream?

Turn on grep's line buffering mode when using BSD grep (FreeBSD, Mac OS X etc.)

tail -f file | grep --line-buffered my_pattern

It looks like a while ago --line-buffered didn't matter for GNU grep (used on pretty much any Linux) as it flushed by default (YMMV for other Unix-likes such as SmartOS, AIX or QNX). However, as of November 2020, --line-buffered is needed (at least with GNU grep 3.5 in openSUSE, but it seems generally needed based on comments below).

jQuery UI accordion that keeps multiple sections open?

Pretty simple:

<script type="text/javascript">
    (function($) {
        $(function() {
            $("#accordion > div").accordion({ header: "h3", collapsible: true });
        })
    })(jQuery);
</script>

<div id="accordion">
    <div>
        <h3><a href="#">First</a></h3>
        <div>Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet.</div>
    </div>
    <div>
        <h3><a href="#">Second</a></h3>
        <div>Phasellus mattis tincidunt nibh.</div>
    </div>
    <div>
        <h3><a href="#">Third</a></h3>
        <div>Nam dui erat, auctor a, dignissim quis.</div>
    </div>
</div>

How does internationalization work in JavaScript?

Some of it is native, the rest is available through libraries.

For example Datejs is a good international date library.

For the rest, it's just about language translation, and JavaScript is natively Unicode compatible (as well as all major browsers).

HTML5 Local storage vs. Session storage

  • sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores)

  • localStorage does the same thing, but persists even when the browser is closed and reopened.

I took this from Web Storage API

How to loop through a HashMap in JSP?

Below code works for me

first I defined the partnerTypesMap like below in the server side,

Map<String, String> partnerTypes = new HashMap<>();

after adding values to it I added the object to model,

model.addAttribute("partnerTypesMap", partnerTypes);

When rendering the page I use below foreach to print them one by one.

<c:forEach items="${partnerTypesMap}" var="partnerTypesMap">
      <form:option value="${partnerTypesMap['value']}">${partnerTypesMap['key']}</form:option>
</c:forEach>

How to get the URL of the current page in C#

Try this :

string url = HttpContext.Current.Request.Url.AbsoluteUri;
// http://localhost:1302/TESTERS/Default6.aspx

string path = HttpContext.Current.Request.Url.AbsolutePath;
// /TESTERS/Default6.aspx

string host = HttpContext.Current.Request.Url.Host;
// localhost

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

Every Driver service in selenium calls the similar code(following is the firefox specific code) while creating the driver object

 @Override
 protected File findDefaultExecutable() {
      return findExecutable(
        "geckodriver", GECKO_DRIVER_EXE_PROPERTY,
        "https://github.com/mozilla/geckodriver",
        "https://github.com/mozilla/geckodriver/releases");
    }

now for the driver that you want to use, you have to set the system property with the value of path to the driver executable.

for firefox GECKO_DRIVER_EXE_PROPERTY = "webdriver.gecko.driver" and this can be set before creating the driver object as below

System.setProperty("webdriver.gecko.driver", "./libs/geckodriver.exe");
WebDriver driver = new FirefoxDriver();

How do I find an element that contains specific text in Selenium WebDriver (Python)?

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[contains(text(), 'YourTextHere')]")));
assertNotNull(driver.findElement(By.xpath("//*[contains(text(), 'YourTextHere')]")));
String yourButtonName = driver.findElement(By.xpath("//*[contains(text(), 'YourTextHere')]")).getAttribute("innerText");
assertTrue(yourButtonName.equalsIgnoreCase("YourTextHere"));

Access-control-allow-origin with multiple domains

Look into the Thinktecture IdentityModel library -- it has full CORS support:

http://brockallen.com/2012/06/28/cors-support-in-webapi-mvc-and-iis-with-thinktecture-identitymodel/

And it can dynamically emit the ACA-Origin you want.

Determine if 2 lists have the same elements, regardless of order?

You can simply check whether the multisets with the elements of x and y are equal:

import collections
collections.Counter(x) == collections.Counter(y)

This requires the elements to be hashable; runtime will be in O(n), where n is the size of the lists.

If the elements are also unique, you can also convert to sets (same asymptotic runtime, may be a little bit faster in practice):

set(x) == set(y)

If the elements are not hashable, but sortable, another alternative (runtime in O(n log n)) is

sorted(x) == sorted(y)

If the elements are neither hashable nor sortable you can use the following helper function. Note that it will be quite slow (O(n²)) and should generally not be used outside of the esoteric case of unhashable and unsortable elements.

def equal_ignore_order(a, b):
    """ Use only when elements are neither hashable nor sortable! """
    unmatched = list(b)
    for element in a:
        try:
            unmatched.remove(element)
        except ValueError:
            return False
    return not unmatched

Converting a SimpleXML Object to an Array

I found this in the PHP manual comments:

/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

It could help you. However, if you convert XML to an array you will loose all attributes that might be present, so you cannot go back to XML and get the same XML.

Get $_POST from multiple checkboxes

<input type="checkbox" name="check_list[<? echo $row['Report ID'] ?>]" value="<? echo $row['Report ID'] ?>">

And after the post, you can loop through them:

   if(!empty($_POST['check_list'])){
     foreach($_POST['check_list'] as $report_id){
        echo "$report_id was checked! ";
     }
   }

Or get a certain value posted from previous page:

if(isset($_POST['check_list'][$report_id])){
  echo $report_id . " was checked!<br/>";
}

Reading Space separated input in python

For python 3 it would be like this n,m,p=map(int,input().split())

Where does Git store files?

usually it goes to Documents folder in windows : C:\Users\<"name of user account">\Documents\GitHub

How to make a DIV not wrap?

This worked for me:

_x000D_
_x000D_
.container {_x000D_
  display: inline-flex;_x000D_
}_x000D_
_x000D_
.slide {_x000D_
  float: left;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="slide">something1</div>_x000D_
  <div class="slide">something2</div>_x000D_
  <div class="slide">something3</div>_x000D_
  <div class="slide">something4</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

Solution:

Add the below line in your application tag:

android:usesCleartextTraffic="true"

As shown below:

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"

No Need to set clear text traffic to true as shown above, instead use the below code:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        ....
        ....
    </domain-config>

    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>  

Set the cleartextTrafficPermitted to true

Hope it helps.

Spark RDD to DataFrame python

I liked Arun's answer better but there is a tiny problem and I could not comment or edit the answer. sparkContext does not have createDeataFrame, sqlContext does (as Thiago mentioned). So:

from pyspark.sql import SQLContext

# assuming the spark environemnt is set and sc is spark.sparkContext 
sqlContext = SQLContext(sc)
schemaPeople = sqlContext.createDataFrame(RDDName)
schemaPeople.createOrReplaceTempView("RDDName")

TypeScript typed array usage

You could try either of these. They are not giving me errors.

It is also the suggested method from typescript for array declaration.

By using the Array<Thing> it is making use of the generics in typescript. It is similar to asking for a List<T> in c# code.

// Declare with default value
private _possessions: Array<Thing> = new Array<Thing>();
// or
private _possessions: Array<Thing> = [];
// or -> prefered by ts-lint
private _possessions: Thing[] = [];

or

// declare
private _possessions: Array<Thing>;
// or -> preferd by ts-lint
private _possessions: Thing[];

constructor(){
    //assign
    this._possessions = new Array<Thing>();
    //or
    this._possessions = [];
}

oracle.jdbc.driver.OracleDriver ClassNotFoundException

In Eclipse,

When you use JDBC in your servlet, the driver jar must be placed in the WEB-INF/lib directory of your project.

How can I tell jackson to ignore a property for which I don't have control over the source code?

You can use Jackson Mixins. For example:

class YourClass {
  public int ignoreThis() { return 0; }    
}

With this Mixin

abstract class MixIn {
  @JsonIgnore abstract int ignoreThis(); // we don't need it!  
}

With this:

objectMapper.getSerializationConfig().addMixInAnnotations(YourClass.class, MixIn.class);

Edit:

Thanks to the comments, with Jackson 2.5+, the API has changed and should be called with objectMapper.addMixIn(Class<?> target, Class<?> mixinSource)

jQuery - Sticky header that shrinks when scrolling down

Based on twitter scroll trouble (http://ejohn.org/blog/learning-from-twitter/).

Here is my solution, throttling the js scroll event (usefull for mobile devices)

JS:

$(function() {
    var $document, didScroll, offset;
    offset = $('.menu').position().top;
    $document = $(document);
    didScroll = false;
    $(window).on('scroll touchmove', function() {
      return didScroll = true;
    });
    return setInterval(function() {
      if (didScroll) {
        $('.menu').toggleClass('fixed', $document.scrollTop() > offset);
        return didScroll = false;
      }
    }, 250);
  });

CSS:

.menu {
  background: pink;
  top: 5px;
}

.fixed {
  width: 100%;
  position: fixed;
  top: 0;
}

HTML:

<div class="menu">MENU FIXED ON TOP</div>

http://codepen.io/anon/pen/BgqHw

What is the size of column of int(11) in mysql in bytes?

I think max value of int(11) is 4294967295

MySQL: can't access root account

There is a section in the MySQL manual on how to reset the root password which will solve your problem.

$(form).ajaxSubmit is not a function

$(form).ajaxSubmit(); 

triggers another validation resulting to a recursion. try changing it to

form.ajaxSubmit(); 

How to enter in a Docker container already running with a new TTY

The "nsinit" way is:

install nsinit

git clone [email protected]:dotcloud/docker.git
cd docker
make shell

from inside the container:

go install github.com/dotcloud/docker/pkg/libcontainer/nsinit/nsinit

from outside:

docker cp id_docker_container:/go/bin/nsinit /root/

use it

cd /var/lib/docker/execdriver/native/<container_id>/
nsinit exec bash

How to print a date in a regular format?

The WHY: dates are objects

In Python, dates are objects. Therefore, when you manipulate them, you manipulate objects, not strings or timestamps.

Any object in Python has TWO string representations:

  • The regular representation that is used by print can be get using the str() function. It is most of the time the most common human readable format and is used to ease display. So str(datetime.datetime(2008, 11, 22, 19, 53, 42)) gives you '2008-11-22 19:53:42'.

  • The alternative representation that is used to represent the object nature (as a data). It can be get using the repr() function and is handy to know what kind of data your manipulating while you are developing or debugging. repr(datetime.datetime(2008, 11, 22, 19, 53, 42)) gives you 'datetime.datetime(2008, 11, 22, 19, 53, 42)'.

What happened is that when you have printed the date using print, it used str() so you could see a nice date string. But when you have printed mylist, you have printed a list of objects and Python tried to represent the set of data, using repr().

The How: what do you want to do with that?

Well, when you manipulate dates, keep using the date objects all long the way. They got thousand of useful methods and most of the Python API expect dates to be objects.

When you want to display them, just use str(). In Python, the good practice is to explicitly cast everything. So just when it's time to print, get a string representation of your date using str(date).

One last thing. When you tried to print the dates, you printed mylist. If you want to print a date, you must print the date objects, not their container (the list).

E.G, you want to print all the date in a list :

for date in mylist :
    print str(date)

Note that in that specific case, you can even omit str() because print will use it for you. But it should not become a habit :-)

Practical case, using your code

import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print mylist[0] # print the date object, not the container ;-)
2008-11-22

# It's better to always use str() because :

print "This is a new day : ", mylist[0] # will work
>>> This is a new day : 2008-11-22

print "This is a new day : " + mylist[0] # will crash
>>> cannot concatenate 'str' and 'datetime.date' objects

print "This is a new day : " + str(mylist[0]) 
>>> This is a new day : 2008-11-22

Advanced date formatting

Dates have a default representation, but you may want to print them in a specific format. In that case, you can get a custom string representation using the strftime() method.

strftime() expects a string pattern explaining how you want to format your date.

E.G :

print today.strftime('We are the %d, %b %Y')
>>> 'We are the 22, Nov 2008'

All the letter after a "%" represent a format for something:

  • %d is the day number (2 digits, prefixed with leading zero's if necessary)
  • %m is the month number (2 digits, prefixed with leading zero's if necessary)
  • %b is the month abbreviation (3 letters)
  • %B is the month name in full (letters)
  • %y is the year number abbreviated (last 2 digits)
  • %Y is the year number full (4 digits)

etc.

Have a look at the official documentation, or McCutchen's quick reference you can't know them all.

Since PEP3101, every object can have its own format used automatically by the method format of any string. In the case of the datetime, the format is the same used in strftime. So you can do the same as above like this:

print "We are the {:%d, %b %Y}".format(today)
>>> 'We are the 22, Nov 2008'

The advantage of this form is that you can also convert other objects at the same time.
With the introduction of Formatted string literals (since Python 3.6, 2016-12-23) this can be written as

import datetime
f"{datetime.datetime.now():%Y-%m-%d}"
>>> '2017-06-15'

Localization

Dates can automatically adapt to the local language and culture if you use them the right way, but it's a bit complicated. Maybe for another question on SO(Stack Overflow) ;-)

SQL Not Like Statement not working

Is the value of your particular COMMENT column null?

Sometimes NOT LIKE doesn't know how to behave properly around nulls.

How to select the first, second, or third element with a given class name?

In the future (perhaps) you will be able to use :nth-child(an+b of s)

Actually, browser support for the “of” filter is very limited. Only Safari seems to support the syntax.

https://css-tricks.com/almanac/selectors/n/nth-child/

Ruby: Calling class method from instance

To access a class method inside a instance method, do the following:

self.class.default_make

Here is an alternative solution for your problem:

class Truck

  attr_accessor :make, :year

  def self.default_make
    "Toyota"
  end

  def make
    @make || self.class.default_make
  end

  def initialize(make=nil, year=nil)
    self.year, self.make = year, make
  end
end

Now let's use our class:

t = Truck.new("Honda", 2000)
t.make
# => "Honda"
t.year
# => "2000"

t = Truck.new
t.make
# => "Toyota"
t.year
# => nil

Absolute position of an element on the screen using jQuery

For the absolute coordinates of any jquery element I wrote this function, it probably doesnt work for all css position types but maybe its a good start for someone ..

function AbsoluteCoordinates($element) {
    var sTop = $(window).scrollTop();
    var sLeft = $(window).scrollLeft();
    var w = $element.width();
    var h = $element.height();
    var offset = $element.offset(); 
    var $p = $element;
    while(typeof $p == 'object') {
        var pOffset = $p.parent().offset();
        if(typeof pOffset == 'undefined') break;
        offset.left = offset.left + (pOffset.left);
        offset.top = offset.top + (pOffset.top);
        $p = $p.parent();
    }

    var pos = {
          left: offset.left + sLeft,
          right: offset.left + w + sLeft,
          top:  offset.top + sTop,
          bottom: offset.top + h + sTop,
    }
    pos.tl = { x: pos.left, y: pos.top };
    pos.tr = { x: pos.right, y: pos.top };
    pos.bl = { x: pos.left, y: pos.bottom };
    pos.br = { x: pos.right, y: pos.bottom };
    //console.log( 'left: ' + pos.left + ' - right: ' + pos.right +' - top: ' + pos.top +' - bottom: ' + pos.bottom  );
    return pos;
}

PHP Fatal error: Using $this when not in object context

Fast method : (new foobar())->foobarfunc();

You need to load your class replace :

foobar::foobarfunc();

by :

(new foobar())->foobarfunc();

or :

$Foobar = new foobar();
$Foobar->foobarfunc();

Or make static function to use foobar::.

class foobar {
    //...

    static function foobarfunc() {
        return $this->foo();
    }
}

Binding an Image in WPF MVVM

Displaying an Image in WPF is much easier than that. Try this:

<Image Source="{Binding DisplayedImagePath}" HorizontalAlignment="Left" 
    Margin="0,0,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Bottom" 
    Grid.Row="8" Width="200"  Grid.ColumnSpan="2" />

And the property can just be a string:

public string DisplayedImage 
{
    get { return @"C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg"; }
}

Although you really should add your images to a folder named Images in the root of your project and set their Build Action to Resource in the Properties Window in Visual Studio... you could then access them using this format:

public string DisplayedImage 
{
    get { return "/AssemblyName;component/Images/ImageName.jpg"; }
}

UPDATE >>>

As a final tip... if you ever have a problem with a control not working as expected, simply type 'WPF', the name of that control and then the word 'class' into a search engine. In this case, you would have typed 'WPF Image Class'. The top result will always be MSDN and if you click on the link, you'll find out all about that control and most pages have code examples as well.


UPDATE 2 >>>

If you followed the examples from the link to MSDN and it's not working, then your problem is not the Image control. Using the string property that I suggested, try this:

<StackPanel>
    <Image Source="{Binding DisplayedImagePath}" />
    <TextBlock Text="{Binding DisplayedImagePath}" />
</StackPanel>

If you can't see the file path in the TextBlock, then you probably haven't set your DataContext to the instance of your view model. If you can see the text, then the problem is with your file path.


UPDATE 3 >>>

In .NET 4, the above Image.Source values would work. However, Microsoft made some horrible changes in .NET 4.5 that broke many different things and so in .NET 4.5, you'd need to use the full pack path like this:

<Image Source="pack://application:,,,/AssemblyName;component/Images/image_to_use.png">

For further information on pack URIs, please see the Pack URIs in WPF page on Microsoft Docs.

postgresql: INSERT INTO ... (SELECT * ...)

This notation (first seen here) looks useful too:

insert into postagem (
  resumopostagem,
  textopostagem,
  dtliberacaopostagem,
  idmediaimgpostagem,
  idcatolico,
  idminisermao,
  idtipopostagem
) select
  resumominisermao,
  textominisermao,
  diaminisermao,
  idmediaimgminisermao,
  idcatolico ,
  idminisermao,
  1
from
  minisermao    

Update MongoDB field using value of another field

Regarding this answer, the snapshot function is deprecated in version 3.6, according to this update. So, on version 3.6 and above, it is possible to perform the operation this way:

db.person.find().forEach(
    function (elem) {
        db.person.update(
            {
                _id: elem._id
            },
            {
                $set: {
                    name: elem.firstname + ' ' + elem.lastname
                }
            }
        );
    }
);

Java SimpleDateFormat for time zone with a colon separator?

tl;dr

OffsetDateTime.parse( "2010-03-01T00:00:00-08:00" )

Details

The answer by BalusC is correct, but now outdated as of Java 8.

java.time

The java.time framework is the successor to both Joda-Time library and the old troublesome date-time classes bundled with the earliest versions of Java (java.util.Date/.Calendar & java.text.SimpleDateFormat).

ISO 8601

Your input data string happens to comply with the ISO 8601 standard.

The java.time classes use ISO 8601 formats by default when parsing/generating textual representations of date-time values. So no need to define a formatting pattern.

OffsetDateTime

The OffsetDateTime class represents a moment on the time line adjusted to some particular offset-from-UTC. In your input, the offset is 8 hours behind UTC, commonly used on much of the west coast of North America.

OffsetDateTime odt = OffsetDateTime.parse( "2010-03-01T00:00:00-08:00" );

You seem to want the date-only, in which case use the LocalDate class. But keep in mind you are discarding data, (a) time-of-day, and (b) the time zone. Really, a date has no meaning without the context of a time zone. For any given moment the date varies around the world. For example, just after midnight in Paris is still “yesterday” in Montréal. So while I suggest sticking with date-time values, you can easily convert to a LocalDate if you insist.

LocalDate localDate = odt.toLocalDate();

Time Zone

If you know the intended time zone, apply it. A time zone is an offset plus the rules to use for handling anomalies such as Daylight Saving Time (DST). Applying a ZoneId gets us a ZonedDateTime object.

ZoneId zoneId = ZoneId.of( "America/Los_Angeles" );
ZonedDateTime zdt = odt.atZoneSameInstant( zoneId );

Generating strings

To generate a string in ISO 8601 format, call toString.

String output = odt.toString();

If you need strings in other formats, search Stack Overflow for use of the java.util.format package.

Converting to java.util.Date

Best to avoid java.util.Date, but if you must, you can convert. Call the new methods added to the old classes such as java.util.Date.from where you pass an Instant. An Instant is a moment on the timeline in UTC. We can extract an Instant from our OffsetDateTime.

java.util.Date utilDate = java.util.Date( odt.toInstant() );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to get a list of user accounts using the command line in MySQL?

MySQL stores the user information in its own database. The name of the database is MySQL. Inside that database, the user information is in a table, a dataset, named user. If you want to see what users are set up in the MySQL user table, run the following command:

SELECT User, Host FROM mysql.user;

+------------------+-----------+
| User             | Host      |
+------------------+-----------+
| root             | localhost |
| root             | demohost  |
| root             | 127.0.0.1 |
| debian-sys-maint | localhost |
|                  | %         |
+------------------+-----------+

How to get PID by process name?

If your OS is Unix base use this code:

import os
def check_process(name):
    output = []
    cmd = "ps -aef | grep -i '%s' | grep -v 'grep' | awk '{ print $2 }' > /tmp/out"
    os.system(cmd % name)
    with open('/tmp/out', 'r') as f:
        line = f.readline()
        while line:
            output.append(line.strip())
            line = f.readline()
            if line.strip():
                output.append(line.strip())

    return output

Then call it and pass it a process name to get all PIDs.

>>> check_process('firefox')
['499', '621', '623', '630', '11733']

How to check if array element is null to avoid NullPointerException in Java

It does not.

See below. The program you posted runs as supposed.

C:\oreyes\samples\java\arrays>type ArrayNullTest.java
public class ArrayNullTest {
    public static void main( String [] args ) {
        Object[][] someArray = new Object[5][];
            for (int i=0; i<=someArray.length-1; i++) {
                 if (someArray[i]!=null ) {
                     System.out.println("It wasn't null");
                 } else {
                     System.out.printf("Element at %d was null \n", i );
                 }
             }
     }
}


C:\oreyes\samples\java\arrays>javac ArrayNullTest.java

C:\oreyes\samples\java\arrays>java ArrayNullTest
Element at 0 was null
Element at 1 was null
Element at 2 was null
Element at 3 was null
Element at 4 was null

C:\oreyes\samples\java\arrays>

In Java, should I escape a single quotation mark (') in String (double quoted)?

You don't need to escape the ' character in a String (wrapped in "), and you don't have to escape a " character in a char (wrapped in ').

How to represent the double quotes character (") in regex?

Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex.

However, because java uses double quotes to delimit String constants, if you want to create a string in java with a double quote in it, you must escape them.

This code will test if your String matches:

if (str.matches("\".*\"")) {
    // this string starts and end with a double quote
}

Note that you don't need to add start and end of input markers (^ and $) in the regex, because matches() requires that the whole input be matched to return true - ^ and $ are implied.

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

please try to execute java from

C:\Program Files\Java\jdk1.7.0_10\bin

i.e from the location where java is installed.

If it is successful, it means that the error lies somewhere in the classpath.

Also, this guy seems to have had the same problem as yours, check it out

ORA-06550: line 1, column 7 (PL/SQL: Statement ignored) Error

If the value stored in PropertyLoader.RET_SECONDARY_V_ARRAY is not "V_ARRAY", then you are using different types; even if they are declared identically (e.g. both are table of number) this will not work.

You're hitting this data type compatibility restriction:

You can assign a collection to a collection variable only if they have the same data type. Having the same element type is not enough.

You're trying to call the procedure with a parameter that is a different type to the one it's expecting, which is what the error message is telling you.

CSS show div background image on top of other contained elements

I would put an absolutely positioned, z-index: 100; span (or spans) with the background: url("myImageWithRoundedCorners.jpg"); set on it inside the #mainWrapperDivWithBGImage .

Java: Local variable mi defined in an enclosing scope must be final or effectively final

One solution is to create a named class instead of using an anonymous class. Give that named class a constructor that takes whatever parameters you wish and assigns them to class fields:

class MenuActionListener implements ActionListener {
    private Color kolorIkony;

    public MenuActionListener(Color kolorIkony) {
        this.kolorIkony = kolorIkony
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JMenuItem item = (JMenuItem) e.getSource();
        IconA icon = (IconA) item.getIcon();
        // Use the class field here
        textArea.setForeground(kolorIkony);
    }
});

Now you can create an instance of this class as usual:

Jmi.addActionListener(new MenuActionListener(getColor(colors[mi]));

Function for Factorial in Python

For performance reasons, please do not use recursion. It would be disastrous.

def fact(n, total=1):
    while True:
        if n == 1:
            return total
        n, total = n - 1, total * n

Check running results

cProfile.run('fact(126000)')

4 function calls in 5.164 seconds

Using the stack is convenient(like recursive call), but it comes at a cost: storing detailed information can take up a lot of memory.

If the stack is high, it means that the computer stores a lot of information about function calls.

The method only takes up constant memory(like iteration).

Or Using for loop

def fact(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

Check running results

cProfile.run('fact(126000)')

4 function calls in 4.708 seconds

Or Using builtin function math

def fact(n):
    return math.factorial(n)

Check running results

cProfile.run('fact(126000)')

5 function calls in 0.272 seconds

How to trim a string after a specific character in java

Try this:

String result = "34.1 -118.33\n<!--ABCDEFG-->";
result = result.substring(0, result.indexOf("\n"));

How do I fix 'ImportError: cannot import name IncompleteRead'?

This should work for you. Follow these simple steps.

First, let's remove the pip which is already installed so it won't cause any error.

Open Terminal.

Type: sudo apt-get remove python-pip

It removes pip that is already installed.

Method-1

Step: 1 sudo easy_install -U pip

It will install pip latest version.

And will return its address: Installed /usr/local/lib/python2.7/dist-packages/pip-6.1.1-py2.7.egg

or

Method-2

Step: 1 go to this link.

Step: 2 Right click >> Save as.. with name get-pip.py .

Step: 3 use: cd to go to the same directory as your get-pip.py file

Step: 4 use: sudo python get-pip.py

It will install pip latest version.

or

Method-3

Step: 1 use: sudo apt-get install python-pip

It will install pip latest version.

Android, How can I Convert String to Date?

using SimpleDateFormat or DateFormat class through

for e.g.

try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
    // handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}

Passing an integer by reference in Python

class Obj:
  def __init__(self,a):
    self.value = a
  def sum(self, a):
    self.value += a
    
a = Obj(1)
b = a
a.sum(1)
print(a.value, b.value)// 2 2

How to make an ng-click event conditional?

You could try to use ng-class.
Here is my simple example:
http://plnkr.co/edit/wS3QkQ5dvHNdc6Lb8ZSF?p=preview

<div ng-repeat="object in objects">
  <span ng-class="{'disabled': object.status}" ng-click="disableIt(object)">
    {{object.value}}
  </span>
</div>

The status is a custom attribute of object, you could name it whatever you want.
The disabled in ng-class is a CSS class name, the object.status should be true or false

You could change every object's status in function disableIt.
In your Controller, you could do this:

$scope.disableIt = function(obj) {
  obj.status = !obj.status
}

How can I set the form action through JavaScript?

Do as Rabbott says, or if you refuse jQuery:

<script type="text/javascript">
function get_action() { // inside script tags
  return form_action;
}
</script>

<form action="" onsubmit="this.action=get_action();">
...
</form>

Where should my npm modules be installed on Mac OS X?

If you want to know the location of you NPM packages, you should:

which npm // locate a program file in the user's path SEE man which
// OUTPUT SAMPLE
/usr/local/bin/npm
la /usr/local/bin/npm // la: aliased to ls -lAh SEE which la THEN man ls
lrwxr-xr-x  1 t04435  admin    46B 18 Sep 10:37 /usr/local/bin/npm -> /usr/local/lib/node_modules/npm/bin/npm-cli.js

So given that npm is a NODE package itself, it is installed in the same location as other packages(EUREKA). So to confirm you should cd into node_modules and list the directory.

cd /usr/local/lib/node_modules/
ls
#SAMPLE OUTPUT
@angular npm .... all global npm packages installed

OR

npm root -g

As per @anthonygore 's comment

How do I create HTML table using jQuery dynamically?

FOR EXAMPLE YOU HAVE RECIEVED JASON DATA FROM SERVER.

                var obj = JSON.parse(msg);
                var tableString ="<table id='tbla'>";
                tableString +="<th><td>Name<td>City<td>Birthday</th>";


                for (var i=0; i<obj.length; i++){
                    //alert(obj[i].name);
                    tableString +=gg_stringformat("<tr><td>{0}<td>{1}<td>{2}</tr>",obj[i].name, obj[i].age, obj[i].birthday);
                }
                tableString +="</table>";
                alert(tableString);
                $('#divb').html(tableString);

HERE IS THE CODE FOR gg_stringformat

function gg_stringformat() {
var argcount = arguments.length,
    string,
    i;

if (!argcount) {
    return "";
}
if (argcount === 1) {
    return arguments[0];
}
string = arguments[0];
for (i = 1; i < argcount; i++) {
    string = string.replace(new RegExp('\\{' + (i - 1) + '}', 'gi'), arguments[i]);
}
return string;

}

Writing a VLOOKUP function in vba

Please find the code below for Vlookup:

Function vlookupVBA(lookupValue, rangeString, colOffset)
vlookupVBA = "#N/A"
On Error Resume Next
Dim table_lookup As range
Set table_lookup = range(rangeString)
vlookupVBA = Application.WorksheetFunction.vlookup(lookupValue, table_lookup, colOffset, False)
End Function

Converting UTF-8 to ISO-8859-1 in Java - how to keep it as single byte

If you're dealing with character encodings other than UTF-16, you shouldn't be using java.lang.String or the char primitive -- you should only be using byte[] arrays or ByteBuffer objects. Then, you can use java.nio.charset.Charset to convert between encodings:

Charset utf8charset = Charset.forName("UTF-8");
Charset iso88591charset = Charset.forName("ISO-8859-1");

ByteBuffer inputBuffer = ByteBuffer.wrap(new byte[]{(byte)0xC3, (byte)0xA2});

// decode UTF-8
CharBuffer data = utf8charset.decode(inputBuffer);

// encode ISO-8559-1
ByteBuffer outputBuffer = iso88591charset.encode(data);
byte[] outputData = outputBuffer.array();

Numpy: Creating a complex array from 2 real ones?

If you really want to eke out performance (with big arrays), numexpr can be used, which takes advantage of multiple cores.

Setup:

>>> import numpy as np
>>> Data = np.random.randn(64, 64, 64, 2)
>>> x, y = Data[...,0], Data[...,1]

With numexpr:

>>> import numexpr as ne
>>> %timeit result = ne.evaluate("complex(x, y)")
573 µs ± 21.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Compared to fast numpy method:

>>> %timeit result = np.empty(x.shape, dtype=complex); result.real = x; result.imag = y
1.39 ms ± 5.74 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)