Programs & Examples On #Cursors

Cursors are used by database programmers to process individual rows returned by database system queries.

How can you create multiple cursors in Visual Studio Code

As of Visual Studio Code version 0.10.9, you can now do a Create Multiple Cursors from Selected Lines by selecting multiple lines, and pressing Shift+Alt+I

Note: This is similar to Sublime Text's Ctrl+Shift+L functionality.

Source: https://code.visualstudio.com/updates/vJanuary#_thank-you
Relevant PR: https://github.com/Microsoft/vscode/pull/1479

DataFrame constructor not properly called! error

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

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

df = DataFrame(eval(data))

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

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

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

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

Sublime Text 2 multiple line edit

I'm not sure it's possible "out of the box". And, unfortunately, I don't know an appropriate plugin either. To solve the problem you suggested you could use regular expressions.

  1. Cmd + F (Find)
  2. Regexp: [^ ]+ (or \d+, or whatever you prefer)
  3. Option + F (Find All)
  4. Edit it

Hotkeys may vary depending on you OS and personal preferences (mine are for OS X).

Python MySQLdb TypeError: not all arguments converted during string formatting

The accepted answer by @kevinsa5 is correct, but you might be thinking "I swear this code used to work and now it doesn't," and you would be right.

There was an API change in the MySQLdb library between 1.2.3 and 1.2.5. The 1.2.3 versions supported

cursor.execute("SELECT * FROM foo WHERE bar = %s", 'baz')

but the 1.2.5 versions require

cursor.execute("SELECT * FROM foo WHERE bar = %s", ['baz'])

as the other answers state. I can't find the change in the changelogs, and it's possible the earlier behavior was considered a bug.

The Ubuntu 14.04 repository has python-mysqldb 1.2.3, but Ubuntu 16.04 and later have python-mysqldb 1.3.7+.

If you're dealing with a legacy codebase that requires the old behavior but your platform is a newish Ubuntu, install MySQLdb from PyPI instead:

$ pip install MySQL-python==1.2.3

Using external images for CSS custom cursors

Originally from a Codepen pen by Chris Coyier of Codepen/CSS-Tricks

_x000D_
_x000D_
.auto            { cursor: auto; }
.default         { cursor: default; }
.none            { cursor: none; }
.context-menu    { cursor: context-menu; }
.help            { cursor: help; }
.pointer         { cursor: pointer; }
.progress        { cursor: progress; }
.wait            { cursor: wait; }
.cell            { cursor: cell; }
.crosshair       { cursor: crosshair; }
.text            { cursor: text; }
.vertical-text   { cursor: vertical-text; }
.alias           { cursor: alias; }
.copy            { cursor: copy; }
.move            { cursor: move; }
.no-drop         { cursor: no-drop; }
.not-allowed     { cursor: not-allowed; }
.all-scroll      { cursor: all-scroll; }
.col-resize      { cursor: col-resize; }
.row-resize      { cursor: row-resize; }
.n-resize        { cursor: n-resize; }
.e-resize        { cursor: e-resize; }
.s-resize        { cursor: s-resize; }
.w-resize        { cursor: w-resize; }
.ns-resize       { cursor: ns-resize; }
.ew-resize       { cursor: ew-resize; }
.ne-resize       { cursor: ne-resize; }
.nw-resize       { cursor: nw-resize; }
.se-resize       { cursor: se-resize; }
.sw-resize       { cursor: sw-resize; }
.nesw-resize     { cursor: nesw-resize; }
.nwse-resize     { cursor: nwse-resize; }

body {
  text-align: center;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";

}
.cursors {
  display: flex;
  flex-wrap: wrap;
}
.cursors > div {
  flex: 150px;
  padding: 10px 2px;
  white-space: nowrap;
  border: 1px solid #eee;
  border-radius: 5px;
  margin: 0 5px 5px 0;
}
.cursors > div:hover {
  background: #eee;
}

HTML CSSResult
EDIT ON
.svg {
  cursor: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/9632/heart.svg), auto;
}

.svg-base64 {
  cursor: url(data:text/html;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4Ig0KCSB2aWV3Qm94PSItMjQxIDI0MyAxNiAxNiIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPg0KCS5zdDB7ZmlsbDojRkYwMDAwO30NCjwvc3R5bGU+DQo8cGF0aCBjbGFzcz0ic3QwIiBkPSJNLTIyOS4yLDI0NGMtMS43LDAtMy4xLDEuNC0zLjgsMi44Yy0wLjctMS40LTIuMS0yLjgtMy44LTIuOGMtMi4zLDAtNC4yLDEuOS00LjIsNC4yYzAsNC43LDQuOCw2LDgsMTAuNg0KCWMzLjEtNC42LDgtNi4xLDgtMTAuNkMtMjI1LDI0NS45LTIyNi45LDI0NC0yMjkuMiwyNDRMLTIyOS4yLDI0NHoiLz4NCjwvc3ZnPg0K), auto;
}

.png-base64 {
  cursor: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyhpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMDY3IDc5LjE1Nzc0NywgMjAxNS8wMy8zMC0yMzo0MDo0MiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTUgKE1hY2ludG9zaCkiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6M0EwMEYyRjlDMjZFMTFFNUI4QkRFMkRBRDg3QkNFRUQiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6M0EwMEYyRkFDMjZFMTFFNUI4QkRFMkRBRDg3QkNFRUQiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDozQTAwRjJGN0MyNkUxMUU1QjhCREUyREFEODdCQ0VFRCIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDozQTAwRjJGOEMyNkUxMUU1QjhCREUyREFEODdCQ0VFRCIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pi/X/ugAAAY6SURBVHja7J1bbBVFHMZ3pVajTQoxCCgaNECqJiJV41NFCdF6CRKrvrRcXkyMD6gQE16MMSbESx9INCYkeHkywRhNiJFUoK3EqDVoRVQIiBpoQDFKC4jYtK7fZP+L0+2e6V7ncvx/ydc953S7Z+b7dWbP7O6Z9YMg8Fj26AKOgIGwGAgDYTEQBsKqQA3yE9/3C28wCLd5C3wnfCPcAl8NN8GNtNrv8M/wN/BuuAfvfNxkECj3HCzuhm+ncs+DL6Nfj8Jn4CPwASp3H7wH5R4r/N7y0EM8iVygMj7cBm+BhwOx2Wweh3fCDwYaW614L3rPnVSGrOUepjqLuvtFgJxnUAQIgVgBD+aoTC0fhDuKVDBluTvovcoq9yBl4RsBgrUXwZ+VWKG4xX/ttRXAuIa2XVW5RSaLtAHBWtPgZ+GxCisV+QzcVSKMLtpm1eUeo4ymVQoEa8yEd2moUNyb0lZO8U+0yUC5RVYzKwGC386F9xuoVOT3g/8+pWWB0Uh/a6rcIrO5pQIhGEMGKxV5WxYoBGObBeUeUkHJBASvzoC/s6BSkd9J031RN7XVonKLDGcUAkIfD3ssqlTkF1MAecHCcvckfSzOAmSDhZWK/IgCxkMWl3tDLiB41gKPWlyxkSA8vBEv97ycRwt0WWTakgfIDosrFblP7gKoi93lQLl3ZAKCR+0OVCryGqncaxwqd3sSEF8GER3txSv9WCxx5Ij1r/ACenwInuVIuT9G2nfEj/Y2JPTBrQ7B8AjAeumxK1oisgaUr2qeDyGtdPC8zpOOno8SWU8AMqHLoj7rGDybz91p0S/wFXKfFT8ZdAPD0KrZlHnNc+pLOSPtWqoCspjz0a7FKiALOR/tWqgCMp/z0a75KiBNnI92Nak+9vJ3E0woCPxaLYRlWAzEvP5RARnhfLRrRAXkBOejXScYiF0aUgE5zPlo10EVkP2cj3Z9qwKyl/PRri9VA8Nm/DzpVfhVANYE/QlPx8BwLLGF+OFHMG4l+tQb/wZW0sDwA85Jm96LvzDpqhM8uxkP93BWlUt8b3EOWsgfMoNJLcQPdzIHOK/K9a6AEX+x1rGsLZxX5Xot6cVaF8pNpxHkpZxbJfoESbdFT5RdFnVbw1hs5twq0/O1fpHYQqiViKsAD3MrKV0f+eEEBV7qFkKtRFwz2835lSox5livWmGqE1QveeEUGKxy1O3Hjl2l7rKkruseLD7kLAtLHLgVF1efm5Rxmi5L6rq2Y/EG51l4ENiZBCNrlxXpKfhHzjW3ngaMwTQrTtllSV3XTVh8Dl/E+WbS20i1U7VCpi5L6rq+xuIxzjeTxDHBR7P8QabLgADlLSxe5pxT6Si8HJmdzZRx2i5L6rrELApb4Q7OvKbEjHltfspT4rm6LKmVjHthn9jPuSfqNHyfn/P6hFxXLuLN/sZiBfwF5z9Bf4lckM9A3g3kvpSUTve2e3wyS4ZxP3LpLbKRQtf2+uEFEcu4pXin4HuLwji/QylhVtJmeMChWRTKnnPlttIYlAGEoFwC9/7PYPwG31pqoygLCEG52PB0ejp9ND6rj3VAonEK/Hqdw/h+qnkUrQFCUMR34zbWKYyBNDONWgVEAvNEzim8bfV2sa8sPSddQAiKmG7vXB3AeDNInqzHLSAERUxWf9JhGBsrnYteNxCCcj18xDEQortdW/Wo0ggQgnIlvNcRGKOqmU/rAog0qu9zYPS9TNdxF6NACEqjZbNOx0ffrToPhBkHQlDE3W1etQyGmKN9ge4jk1YAkcA8ZwmMH+CrjGRgExCCstYwjH3w5cbqbxsQgtJlaFQ/QF+/8BjIZCidmqEIGM3G620rEILygKabAFgBw3ogBGV5xVCsgeEEkIqh7DO9z3ASCEF5uOR9ivhoa91E0c4AISirS4JxXNxU0so6ugSEoKwrCONUYPEk0c4BISjdBe66eZfVdXMUiE+3zMsK5HHPcjkJhKCIy4w+zQDjFc8BOQuEoMxKeeZxN3whA9EDpRU+q4BxLHDoPijOAyEoqxTnwducqks9ACEomxOAPONcPeoIiNjJD0ow+ovcd52BlAPlOtqfnLZ1JJ4FSIPnuPzwBvLr8HAcj39yvj6utox6Fd+ugoGwGAgDYeXVvwIMAGCAb3XkplDRAAAAAElFTkSuQmCC"), auto;
}

.png {
  cursor: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/9632/heart.png"), auto;
}

.gif {
  cursor: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/9632/tina.gif"), auto;
}

.cursors {
  display: flex;
  justify-content: flex-start;
  align-items: stretch;
  height: 100vh;
}

.cursors > div {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-grow: 1;
  box-sizing: border-box;
  padding: 10px 2px;
  text-align: center;
}
_x000D_
<h1>The Cursors of CSS</h1>

<div class="cursors">
    <div class="auto">auto</div>
    <div class="default">default</div>
    <div class="none">none</div>
    <div class="context-menu">context-menu</div>
    <div class="help">help</div>
    <div class="pointer">pointer</div>
    <div class="progress">progress</div>
    <div class="wait">wait</div>
    <div class="cell">cell</div>
    <div class="crosshair">crosshair</div>
    <div class="text">text</div>
    <div class="vertical-text">vertical-text</div>
    <div class="alias">alias</div>
    <div class="copy">copy</div>
    <div class="move">move</div>
    <div class="no-drop">no-drop</div>
    <div class="not-allowed">not-allowed</div>
    <div class="all-scroll">all-scroll</div>
    <div class="col-resize">col-resize</div>
    <div class="row-resize">row-resize</div>
    <div class="n-resize">n-resize</div>
    <div class="s-resize">s-resize</div>
    <div class="e-resize">e-resize</div>
    <div class="w-resize">w-resize</div>
    <div class="ns-resize">ns-resize</div>
    <div class="ew-resize">ew-resize</div>
    <div class="ne-resize">ne-resize</div>
    <div class="nw-resize">nw-resize</div>
    <div class="se-resize">se-resize</div>
    <div class="sw-resize">sw-resize</div>
    <div class="nesw-resize">nesw-resize</div>
    <div class="nwse-resize">nwse-resize</div>
</div>
<br><br><br><br><br><br><br><br><br>
<h1>Custom Image</h1>
<div class="cursors">
  <div class="svg"><p>SVG</p></div>
  <div class="svg-base64">Base 64 SVG</div>
  <div class="png-base64">Base 64 PNG</div>
  <div class="png">PNG</div>
  <div class="gif">GIF</div>
</div>
_x000D_
_x000D_
_x000D_

How to update cursor limit for ORA-01000: maximum open cursors exceed

Assuming that you are using a spfile to start the database

alter system set open_cursors = 1000 scope=both;

If you are using a pfile instead, you can change the setting for the running instance

alter system set open_cursors = 1000 

You would also then need to edit the parameter file to specify the new open_cursors setting. It would generally be a good idea to restart the database shortly thereafter to make sure that the parameter file change works as expected (it's highly annoying to discover months later the next time that you reboot the database that some parameter file change than no one remembers wasn't done correctly).

I'm also hoping that you are certain that you actually need more than 300 open cursors per session. A large fraction of the time, people that are adjusting this setting actually have a cursor leak and they are simply trying to paper over the bug rather than addressing the root cause.

Multiple Cursors in Sublime Text 2 Windows

In Sublime Text, after you select multiple regions of text, a click is considered a way to exit the multi-select mode. Move the cursor with the keyboard keys (arrows, Ctrl+arrows, etc.) instead, and you'll be fine

How to debug a stored procedure in Toad?

Basic Steps to Debug a Procedure in Toad

  1. Load your Procedure in Toad Editor.
  2. Put debug point on the line where you want to debug.See the first screenshot.
  3. Right click on the editor Execute->Execute PLSQL(Debugger).See the second screeshot.
  4. A window opens up,you need to select the procedure from the left side and pass parameters for that procedure and then click Execute.See the third screenshot.
  5. Now start your debugging check Debug-->Step Over...Add Watch etc.

Reference:Toad Debugger

Debug

Execute In Debug

parameter

How to retrieve data from sqlite database in android and display it in TextView

First cast your Edit text like this:

TextView tekst = (TextView) findViewById(R.id.editText1);
tekst.setText(text);

And after that close the DB not befor this line...

 myDataBaseHelper.close(); 

How to insert data into SQL Server

string saveStaff = "INSERT into student (stud_id,stud_name) " + " VALUES ('" + SI+ "', '" + SN + "');";
cmd = new SqlCommand(saveStaff,con);
cmd.ExecuteNonQuery();

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

I too had faced this issue.The below exception used to come

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

I was using Spring Framework with Spring JDBC for dao layer.

My application used to leak cursors somehow and after few minutes or so, It used to give me this exception.

After a lot of thorough debugging and analysis, I found that there was the problem with the Indexing, Primary Key and Unique Constraints in one of the Table being used in the Query i was executing.

My application was trying to update the Columns which were mistakenly Indexed. So, whenever my application was hitting the update query on the indexed columns, The database was trying to do the reindexing based on the updated values. It was leaking the cursors.

I was able to solve the problem by doing Proper Indexing on the columns which were used to search in the query and applying appropriate constraints wherever required.

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

What do \t and \b do?

This behaviour is terminal-specific and specified by the terminal emulator you use (e.g. xterm) and the semantics of terminal that it provides. The terminal behaviour has been very stable for the last 20 years, and you can reasonably rely on the semantics of \b.

Python: Maximum recursion depth exceeded

You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:

import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values

... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.

CSS for grabbing cursors (drag & drop)

You can create your own cursors and set them as the cursor using cursor: url('path-to-your-cursor');, or find Firefox's and copy them (bonus: a nice consistent look in every browser).

libxml install error using pip

On osx 10.10.5 and in a virtualenv, maybe you can resolve that problem like below:

sudo C_INCLUDE_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/libxml2:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/libxml2/libxml:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include pip install -r lxml

Get Multiple Values in SQL Server Cursor

Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:

declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for 
    select
         row_number() over (order by(select null)) as RowNum
        ,Data -- you fields
    from YourIntTable
open @cur
begin try
    fetch last from @cur into @lastNum, @data
    fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value 
    while @i < @lastNum
    begin
        set @i += 1

        --Do your job here
        print @data

        fetch next from @cur into @rowNum, @data
    end
end try
begin catch
    close @cur      --|
    deallocate @cur --|-remove this 3 lines if you do not throw
    ;throw          --|
end catch
close @cur
deallocate @cur

How do I join two SQLite tables in my Android application?

In addition to @pawelzieba's answer, which definitely is correct, to join two tables, while you can use an INNER JOIN like this

SELECT * FROM expense INNER JOIN refuel
ON exp_id = expense_id
WHERE refuel_id = 1

via raw query like this -

String rawQuery = "SELECT * FROM " + RefuelTable.TABLE_NAME + " INNER JOIN " + ExpenseTable.TABLE_NAME
        + " ON " + RefuelTable.EXP_ID + " = " + ExpenseTable.ID
        + " WHERE " + RefuelTable.ID + " = " +  id;
Cursor c = db.rawQuery(
        rawQuery,
        null
);

because of SQLite's backward compatible support of the primitive way of querying, we turn that command into this -

SELECT *
FROM expense, refuel
WHERE exp_id = expense_id AND refuel_id = 1

and hence be able to take advanatage of the SQLiteDatabase.query() helper method

Cursor c = db.query(
        RefuelTable.TABLE_NAME + " , " + ExpenseTable.TABLE_NAME,
        Utils.concat(RefuelTable.PROJECTION, ExpenseTable.PROJECTION),
        RefuelTable.EXP_ID + " = " + ExpenseTable.ID + " AND " + RefuelTable.ID + " = " +  id,
        null,
        null,
        null,
        null
);

For a detailed blog post check this http://blog.championswimmer.in/2015/12/doing-a-table-join-in-android-without-using-rawquery

Best Way to Refresh Adapter/ListView on Android

Perhaps their problem is the moment when the search is made in the database. In his Fragment Override cycles of its Fragment.java to figure out just: try testing with the methods:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_x, container, false); //Your query and ListView code probably will be here
    Log.i("FragmentX", "Step OnCreateView");// Try with it
    return rootView; 
}

Try it similarly put Log.i ... "onStart" and "onResume".

Finally cut the code in "onCreate" e put it in "onStart" for example:

@Override
public void onStart(){
    super.onStart();
    Log.i("FragmentX","Step OnStart");
    dbManager = new DBManager(getContext());
    Cursor cursor = dbManager.getAllNames();
    listView = (ListView)getView().findViewById(R.id.lvNames);
    adapter = new CustomCursorAdapter(getContext(),cursor,0);// your adapter
    adapter.notifyDataSetChanged();
    listView.setAdapter(adapter);
}

Notepad++ Multi editing

In the position where you want to add text, do:

Shift + Alt + down arrow

and select the lines you want. Then type. The text you type is inserted on all of the lines you selected.

Can I loop through a table variable in T-SQL?

My two cents.. From KM.'s answer, if you want to drop one variable, you can do a countdown on @RowsToProcess instead of counting up.

DECLARE @RowsToProcess  int;

DECLARE @table1 TABLE (RowID int not null primary key identity(1,1), col1 int )  
INSERT into @table1 (col1) SELECT col1 FROM table2
SET @RowsToProcess = @@ROWCOUNT 

WHILE @RowsToProcess > 0 -- Countdown
BEGIN
    SELECT *
        FROM @table1
        WHERE RowID=@RowsToProcess

    --do your thing here--

    SET @RowsToProcess = @RowsToProcess - 1; -- Countdown
END

How to detect the currently pressed key?

if (Form.ModifierKeys == Keys.Shift)

does work for a text box if the above code is in the form's keydown event and no other control captures the keydown event for the key down.

Also one may wish stop further key processing with:

e.Handled = true;

How to find Current open Cursors in Oracle

Here's how to find open cursors that have been parsed. You need to be logged in as a user with access to v$open_cursor and v$session.

COLUMN USER_NAME FORMAT A15

SELECT s.machine, oc.user_name, oc.sql_text, count(1) 
FROM v$open_cursor oc, v$session s
WHERE oc.sid = s.sid
GROUP BY user_name, sql_text, machine
HAVING COUNT(1) > 2
ORDER BY count(1) DESC
;

If gives you part of the SQL text so it can be useful for identifying leaky applications. If a cursor has not been parsed, then it does not appear here. Note that Oralce will sometimes keep things open longer than you do.

Displaying tooltip on mouse hover of a text

You shouldn't use the control private tooltip, but the form one. This example works well:

public partial class Form1 : Form
{
    private System.Windows.Forms.ToolTip toolTip1;

    public Form1()
    {
        InitializeComponent();
        this.components = new System.ComponentModel.Container();
        this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);

        MyRitchTextBox myRTB = new MyRitchTextBox();
        this.Controls.Add(myRTB);

        myRTB.Location = new Point(10, 10);
        myRTB.MouseEnter += new EventHandler(myRTB_MouseEnter);
        myRTB.MouseLeave += new EventHandler(myRTB_MouseLeave);
    }


    void myRTB_MouseEnter(object sender, EventArgs e)
    {
        MyRitchTextBox rtb = (sender as MyRitchTextBox);
        if (rtb != null)
        {
            this.toolTip1.Show("Hello!!!", rtb);
        }
    }

    void myRTB_MouseLeave(object sender, EventArgs e)
    {
        MyRitchTextBox rtb = (sender as MyRitchTextBox);
        if (rtb != null)
        {
            this.toolTip1.Hide(rtb);
        }
    }


    public class MyRitchTextBox : RichTextBox
    {
    }

}

Changing the cursor in WPF sometimes works, sometimes doesn't

If your application uses async stuff and you're fiddling with Mouse's cursor, you probably want to do it only in main UI thread. You can use app's Dispatcher thread for that:

Application.Current.Dispatcher.Invoke(() =>
{
    // The check is required to prevent cursor flickering
    if (Mouse.OverrideCursor != cursor)
        Mouse.OverrideCursor = cursor;
});

Why do people hate SQL cursors so much?

In general, because on a relational database, the performance of code using cursors is an order of magnitude worse than set-based operations.

What is the difference between explicit and implicit cursors in Oracle?

An explicit cursor is one you declare, like:

CURSOR my_cursor IS
  SELECT table_name FROM USER_TABLES

An implicit cursor is one created to support any in-line SQL you write (either static or dynamic).

How to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

VERSION NOTE: You must be using SQL Server 2005 or greater with Compatibility Level set to 90 or greater for this solution.

See this MSDN article for the first example of creating a user-defined aggregate function that concatenates a set of string values taken from a column in a table.

My humble recommendation would be to leave out the appended comma so you can use your own ad-hoc delimiter, if any.

Referring to the C# version of Example 1:

change:  this.intermediateResult.Append(value.Value).Append(',');
    to:  this.intermediateResult.Append(value.Value);

And

change:  output = this.intermediateResult.ToString(0, this.intermediateResult.Length - 1);
    to:  output = this.intermediateResult.ToString();

That way when you use your custom aggregate, you can opt to use your own delimiter, or none at all, such as:

SELECT dbo.CONCATENATE(column1 + '|') from table1

NOTE: Be careful about the amount of the data you attempt to process in your aggregate. If you try to concatenate thousands of rows or many very large datatypes you may get a .NET Framework error stating "[t]he buffer is insufficient."

Why do I have to "git push --set-upstream origin <branch>"?

TL;DR: git branch --set-upstream-to origin/solaris


The answer to the question you asked—which I'll rephrase a bit as "do I have to set an upstream"—is: no, you don't have to set an upstream at all.

If you do not have upstream for the current branch, however, Git changes its behavior on git push, and on other commands as well.

The complete push story here is long and boring and goes back in history to before Git version 1.5. To shorten it a whole lot, git push was implemented poorly.1 As of Git version 2.0, Git now has a configuration knob spelled push.default which now defaults to simple. For several versions of Git before and after 2.0, every time you ran git push, Git would spew lots of noise trying to convince you to set push.default just to get git push to shut up.

You do not mention which version of Git you are running, nor whether you have configured push.default, so we must guess. My guess is that you are using Git version 2-point-something, and that you have set push.default to simple to get it to shut up. Precisely which version of Git you have, and what if anything you have push.default set to, does matter, due to that long and boring history, but in the end, the fact that you're getting yet another complaint from Git indicates that your Git is configured to avoid one of the mistakes from the past.

What is an upstream?

An upstream is simply another branch name, usually a remote-tracking branch, associated with a (regular, local) branch.

Every branch has the option of having one (1) upstream set. That is, every branch either has an upstream, or does not have an upstream. No branch can have more than one upstream.

The upstream should, but does not have to be, a valid branch (whether remote-tracking like origin/B or local like master). That is, if the current branch B has upstream U, git rev-parse U should work. If it does not work—if it complains that U does not exist—then most of Git acts as though the upstream is not set at all. A few commands, like git branch -vv, will show the upstream setting but mark it as "gone".

What good is an upstream?

If your push.default is set to simple or upstream, the upstream setting will make git push, used with no additional arguments, just work.

That's it—that's all it does for git push. But that's fairly significant, since git push is one of the places where a simple typo causes major headaches.

If your push.default is set to nothing, matching, or current, setting an upstream does nothing at all for git push.

(All of this assumes your Git version is at least 2.0.)

The upstream affects git fetch

If you run git fetch with no additional arguments, Git figures out which remote to fetch from by consulting the current branch's upstream. If the upstream is a remote-tracking branch, Git fetches from that remote. (If the upstream is not set or is a local branch, Git tries fetching origin.)

The upstream affects git merge and git rebase too

If you run git merge or git rebase with no additional arguments, Git uses the current branch's upstream. So it shortens the use of these two commands.

The upstream affects git pull

You should never2 use git pull anyway, but if you do, git pull uses the upstream setting to figure out which remote to fetch from, and then which branch to merge or rebase with. That is, git pull does the same thing as git fetch—because it actually runs git fetch—and then does the same thing as git merge or git rebase, because it actually runs git merge or git rebase.

(You should usually just do these two steps manually, at least until you know Git well enough that when either step fails, which they will eventually, you recognize what went wrong and know what to do about it.)

The upstream affects git status

This may actually be the most important. Once you have an upstream set, git status can report the difference between your current branch and its upstream, in terms of commits.

If, as is the normal case, you are on branch B with its upstream set to origin/B, and you run git status, you will immediately see whether you have commits you can push, and/or commits you can merge or rebase onto.

This is because git status runs:

  • git rev-list --count @{u}..HEAD: how many commits do you have on B that are not on origin/B?
  • git rev-list --count HEAD..@{u}: how many commits do you have on origin/B that are not on B?

Setting an upstream gives you all of these things.

How come master already has an upstream set?

When you first clone from some remote, using:

$ git clone git://some.host/path/to/repo.git

or similar, the last step Git does is, essentially, git checkout master. This checks out your local branch master—only you don't have a local branch master.

On the other hand, you do have a remote-tracking branch named origin/master, because you just cloned it.

Git guesses that you must have meant: "make me a new local master that points to the same commit as remote-tracking origin/master, and, while you're at it, set the upstream for master to origin/master."

This happens for every branch you git checkout that you do not already have. Git creates the branch and makes it "track" (have as an upstream) the corresponding remote-tracking branch.

But this doesn't work for new branches, i.e., branches with no remote-tracking branch yet.

If you create a new branch:

$ git checkout -b solaris

there is, as yet, no origin/solaris. Your local solaris cannot track remote-tracking branch origin/solaris because it does not exist.

When you first push the new branch:

$ git push origin solaris

that creates solaris on origin, and hence also creates origin/solaris in your own Git repository. But it's too late: you already have a local solaris that has no upstream.3

Shouldn't Git just set that, now, as the upstream automatically?

Probably. See "implemented poorly" and footnote 1. It's hard to change now: There are millions4 of scripts that use Git and some may well depend on its current behavior. Changing the behavior requires a new major release, nag-ware to force you to set some configuration field, and so on. In short, Git is a victim of its own success: whatever mistakes it has in it, today, can only be fixed if the change is either mostly invisible, clearly-much-better, or done slowly over time.

The fact is, it doesn't today, unless you use --set-upstream or -u during the git push. That's what the message is telling you.

You don't have to do it like that. Well, as we noted above, you don't have to do it at all, but let's say you want an upstream. You have already created branch solaris on origin, through an earlier push, and as your git branch output shows, you already have origin/solaris in your local repository.

You just don't have it set as the upstream for solaris.

To set it now, rather than during the first push, use git branch --set-upstream-to. The --set-upstream-to sub-command takes the name of any existing branch, such as origin/solaris, and sets the current branch's upstream to that other branch.

That's it—that's all it does—but it has all those implications noted above. It means you can just run git fetch, then look around, then run git merge or git rebase as appropriate, then make new commits and run git push, without a bunch of additional fussing-around.


1To be fair, it was not clear back then that the initial implementation was error-prone. That only became clear when every new user made the same mistakes every time. It's now "less poor", which is not to say "great".

2"Never" is a bit strong, but I find that Git newbies understand things a lot better when I separate out the steps, especially when I can show them what git fetch actually did, and they can then see what git merge or git rebase will do next.

3If you run your first git push as git push -u origin solaris—i.e., if you add the -u flag—Git will set origin/solaris as the upstream for your current branch if (and only if) the push succeeds. So you should supply -u on the first push. In fact, you can supply it on any later push, and it will set or change the upstream at that point. But I think git branch --set-upstream-to is easier, if you forgot.

4Measured by the Austin Powers / Dr Evil method of simply saying "one MILLLL-YUN", anyway.

Detect when browser receives file download

A quick solution if you only want to display a message or a loader gif until the download dialog is displayed is to put the message in a hidden container and when you click on the button that generate the file to be downloaded you make the container visible. Then use jquery or javascript to catch the focusout event of the button to hide the container that contain the message

Collision resolution in Java HashMap

First of all, you have got the concept of hashing a little wrong and it had been rectified by Mr. Sanjay.

And yes, Java indeed implement a collision resolution technique. When two keys get hashed to a same value (as the internal array used is finite in size and at some point the hashcode() method will return same hash value for two different keys) at this time, a linked list is formed at the bucket location where all the informations are entered as an Map.Entry object that contains a key-value pair. Accessing an object via a key will at worst require O(n) if the entry in present in such a lists. Comparison between the key you passed with each key in such list will be done by the equals() method.

Although, from Java 8 , the linked lists are replaced with trees (O(log n))

How to get the onclick calling object?

The easiest way is to pass this to the click123 function or you can also do something like this(cross-browser):

function click123(e){
  e = e || window.event;
  var src = e.target || e.srcElement;
  //src element is the eventsource
}

Read file line by line in PowerShell

Not much documentation on PowerShell loops.

Documentation on loops in PowerShell is plentiful, and you might want to check out the following help topics: about_For, about_ForEach, about_Do, about_While.

foreach($line in Get-Content .\file.txt) {
    if($line -match $regex){
        # Work here
    }
}

Another idiomatic PowerShell solution to your problem is to pipe the lines of the text file to the ForEach-Object cmdlet:

Get-Content .\file.txt | ForEach-Object {
    if($_ -match $regex){
        # Work here
    }
}

Instead of regex matching inside the loop, you could pipe the lines through Where-Object to filter just those you're interested in:

Get-Content .\file.txt | Where-Object {$_ -match $regex} | ForEach-Object {
    # Work here
}

Object of custom type as dictionary key

You need to add 2 methods, note __hash__ and __eq__:

class MyThing:
    def __init__(self,name,location,length):
        self.name = name
        self.location = location
        self.length = length

    def __hash__(self):
        return hash((self.name, self.location))

    def __eq__(self, other):
        return (self.name, self.location) == (other.name, other.location)

    def __ne__(self, other):
        # Not strictly necessary, but to avoid having both x==y and x!=y
        # True at the same time
        return not(self == other)

The Python dict documentation defines these requirements on key objects, i.e. they must be hashable.

Android Notification Sound

What was missing from my previous code:

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(alarmSound);

How to add a custom HTTP header to every WCF call?

If I understand your requirement correctly, the simple answer is: you can't.

That's because the client of the WCF service may be generated by any third party that uses your service.

IF you have control of the clients of your service, you can create a base client class that add the desired header and inherit the behavior on the worker classes.

Windows Application has stopped working :: Event Name CLR20r3

Some times this problem arise when Application is build in one PC and try to run another PC. And also build the application with Visual Studio 2010.I have the following problem

Problem Description
    Stop Working
Problem Signature
  Problem Event Name:   CLR20r3
  Problem Signature 01: diagnosticcentermngr.exe
  Problem Signature 02: 1.0.0.0
  Problem Signature 03: 4f8c1772
  Problem Signature 04: System.Drawing
  Problem Signature 05: 2.0.0.0
  Problem Signature 06: 4a275e83
  Problem Signature 07: 7af
  Problem Signature 08: 6c
  Problem Signature 09: System.ArgumentException
  OS Version:   6.1.7600.2.0.0.256.1
  Locale ID:    1033

Read our privacy statement online:
  http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409

If the online privacy statement is not available, please read our privacy statement offline:
  C:\Windows\system32\en-US\erofflps.txt

Dont worry, Please check out following link and install .net framework 4.Although my application .net properties was .net framework 2.

http://www.microsoft.com/download/en/details.aspx?id=17718

restart your PC and try again.

Why does my favicon not show up?

Favicons only work when served from a web-server which sets mime-types correctly for served content. Loading from a local file might not work in chromium. Loading from an incorrectly configured web-server will not work.

Web-servers such as lighthttpd must be configured manually to set the mime type correctly.

Because of the likelihood that mimetype assignment will not work in all environments, I would suggest you use an inline base64 encoded ico file instead. This will load faster as well, as it reduces the number of http requests sent to the server.

On POSIX based systems you can base64 encode a file with the base64 command.

To create a base64 encoded ico line use the command:

$ base64 favicon.ico --wrap 0

And insert the output into the line:

<link href="data:image/x-icon;base64,HERE" rel="icon" type="image/x-icon" />

Replacing the word HERE like so:

<link href="data:image/x-icon;base64,AAABAAEAEBAQAAEABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAA////AERpOgA5cCcA7vDtAF6jSABllFcAuuCvAK2trQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFjMzMzMzNxARYzMzMzVBEEERYzMzNhERZxRGMzZxQEA2FER3cRSAgTNxgEEREIQBMzFIARERFEEzNhERARFAATMzYREBEAhBMzMzEYEBFEEzMzNhEQQRQDMzMzcRgEAAMzMzNhERgIEzMzMyERgEQDMzMzMRAEgEMzMzMxERAEEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" rel="icon" type="image/x-icon" />

The model backing the <Database> context has changed since the database was created

Here I want to share another method that prevent the error of model backing when context changed is:

1) Open your DbContext File

2) Add namespace using Microsoft.AspNet.Identity.EntityFramework;

3) public MyDbContext() : base("name=MyDbContext") { Database.SetInitializer(new DropCreateDatabaseAlways()); }

How to create a DataFrame from a text file in Spark

I know I am quite late to answer this but I have come up with a different answer:

val rdd = sc.textFile("/home/training/mydata/file.txt")

val text = rdd.map(lines=lines.split(",")).map(arrays=>(ararys(0),arrays(1))).toDF("id","name").show 

Converting a view to Bitmap without displaying it in Android?

Layout or view to bitmap:

 private Bitmap createBitmapFromLayout(View tv) {      
    int spec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    tv.measure(spec, spec);
    tv.layout(0, 0, tv.getMeasuredWidth(), tv.getMeasuredHeight());
    Bitmap b = Bitmap.createBitmap(tv.getMeasuredWidth(), tv.getMeasuredWidth(),
            Bitmap.Config.ARGB_8888);
    Canvas c = new Canvas(b);
    c.translate((-tv.getScrollX()), (-tv.getScrollY()));
    tv.draw(c);
    return b;
}

Calling Method:

Bitmap src = createBitmapFromLayout(View.inflate(this, R.layout.sample, null)/* or pass your view object*/);

Difference between string and text in rails?

The difference relies in how the symbol is converted into its respective column type in query language.

with MySQL :string is mapped to VARCHAR(255)

:string |                   VARCHAR                | :limit => 1 to 255 (default = 255)  
:text   | TINYTEXT, TEXT, MEDIUMTEXT, or LONGTEXT2 | :limit => 1 to 4294967296 (default = 65536)

Reference:

https://hub.packtpub.com/working-rails-activerecord-migrations-models-scaffolding-and-database-completion/

When should each be used?

As a general rule of thumb, use :string for short text input (username, email, password, titles, etc.) and use :text for longer expected input such as descriptions, comment content, etc.

How to update nested state properties in React

I take very seriously the concerns already voiced around creating a complete copy of your component state. With that said, I would strongly suggest Immer.

import produce from 'immer';

<Input
  value={this.state.form.username}
  onChange={e => produce(this.state, s => { s.form.username = e.target.value }) } />

This should work for React.PureComponent (i.e. shallow state comparisons by React) as Immer cleverly uses a proxy object to efficiently copy an arbitrarily deep state tree. Immer is also more typesafe compared to libraries like Immutability Helper, and is ideal for Javascript and Typescript users alike.


Typescript utility function

function setStateDeep<S>(comp: React.Component<any, S, any>, fn: (s: 
Draft<Readonly<S>>) => any) {
  comp.setState(produce(comp.state, s => { fn(s); }))
}

onChange={e => setStateDeep(this, s => s.form.username = e.target.value)}

Any way to declare an array in-line?

Another way to do that, if you want the result as a List inline, you can do it like this:

Arrays.asList(new String[] { "String1", "string2" });

How to bind to a PasswordBox in MVVM

Maybe I am missing something, but it seems like most of these solutions overcomplicate things and do away with secure practices.

This method does not violate the MVVM pattern and maintains complete security. Yes, technically it is code behind, but it is nothing more than a "special case" binding. The ViewModel still has no knowledge of the View implementation, which in my mind it does if you are trying to pass the PasswordBox in to the ViewModel.

Code Behind != Automatic MVVM violation. It all depends on what you do with it. In this case, we are just manually coding a binding, so its all considered part of the UI implementation and therefore is ok.

In the ViewModel, just a simple property. I made it "write only" since there shouldn't be a need to retrieve it from outside the ViewModel for any reason, but it doesn't have to be. Note that it is a SecureString, not just a string.

public SecureString SecurePassword { private get; set; }

In the xaml, you set up a PasswordChanged event handler.

<PasswordBox PasswordChanged="PasswordBox_PasswordChanged"/>

In the code behind:

private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
{
    if (this.DataContext != null)
    { ((dynamic)this.DataContext).SecurePassword = ((PasswordBox)sender).SecurePassword; }
}

With this method, your password remains in a SecureString at all times and therefore provides maximum security. If you really don't care about security or you need the clear text password for a downstream method that requires it (note: most .NET methods that require a password also support a SecureString option, so you may not really need a clear text password even if you think you do), you can just use the Password property instead. Like this:

(ViewModel property)

public string Password { private get; set; }

(Code behind)

private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
{
    if (this.DataContext != null)
    { ((dynamic)this.DataContext).Password = ((PasswordBox)sender).Password; }
}

If you wanted to keep things strongly typed, you could substitute the (dynamic) cast with the interface of your ViewModel. But really, "normal" data bindings aren't strongly typed either, so its not that big a deal.

private void PasswordBox_PasswordChanged(object sender, RoutedEventArgs e)
{
    if (this.DataContext != null)
    { ((IMyViewModel)this.DataContext).Password = ((PasswordBox)sender).Password; }
}

So best of all worlds - your password is secure, your ViewModel just has a property like any other property, and your View is self contained with no external references required.

SQL like search string starts with

Aside from using %, age of empires III to lower case is age of empires iii so your query should be:

select *
from games
where lower(title) like 'age of empires iii%'

How to pass arguments and redirect stdin from a file to program run in gdb?

You can do this:

gdb --args path/to/executable -every -arg you can=think < of

The magic bit being --args.

Just type run in the gdb command console to start debugging.

What's the bad magic number error?

In my case it was not .pyc but old binary .mo translation files after I renamed my own module, so inside this module folder I had to run

find . -name \*.po -execdir sh -c 'msgfmt "$0" -o `basename $0 .po`.mo' '{}' \;

(please do backup and try to fix .pyc files first)

What's the use of "enum" in Java?

An enumerated type is basically a data type that lets you describe each member of a type in a more readable and reliable way.

Here is a simple example to explain why:

Assuming you are writing a method that has something to do with seasons:

The int enum pattern

First, you declared some int static constants to represent each season.

public static final int SPRING = 0;
public static final int SUMMER = 1;
public static final int FALL = 2;
public static final int WINTER = 2;

Then, you declared a method to print name of the season into the console.

public void printSeason(int seasonCode) {
    String name = "";
    if (seasonCode == SPRING) {
        name = "Spring";
    }
    else if (seasonCode == SUMMER) {
        name = "Summer";
    }
    else if (seasonCode == FALL) {
        name = "Fall";
    }
    else if (seasonCode == WINTER) {
        name = "Winter";
    }
    System.out.println("It is " + name + " now!");
}

So, after that, you can print a season name like this.

printSeason(SPRING);
printSeason(WINTER);

This is a pretty common (but bad) way to do different things for different types of members in a class. However, since these code involves integers, so you can also call the method like this without any problems.

printSeason(0);
printSeason(1);

or even like this

printSeason(x - y);
printSeason(10000);

The compiler will not complain because these method calls are valid, and your printSeason method can still work.

But something is not right here. What does a season code of 10000 supposed to mean? What if x - y results in a negative number? When your method receives an input that has no meaning and is not supposed to be there, your program knows nothing about it.

You can fix this problem, for example, by adding an additional check.

...
else if (seasonCode == WINTER) {
    name = "Winter";
}
else {
    throw new IllegalArgumentException();
}
System.out.println(name);

Now the program will throw a RunTimeException when the season code is invalid. However, you still need to decide how you are going to handle the exception.

By the way, I am sure you noticed the code of FALL and WINTER are both 2, right?

You should get the idea now. This pattern is brittle. It makes you write condition checks everywhere. If you're making a game, and you want to add an extra season into your imaginary world, this pattern will make you go though all the methods that do things by season, and in most case you will forget some of them.

You might think class inheritance is a good idea for this case. But we just need some of them and no more.

That's when enum comes into play.


Use enum type

In Java, enum types are classes that export one instance for each enumeration constant via a public static final field.

Here you can declare four enumeration constants: SPRING, SUMMER, FALL, WINTER. Each has its own name.

public enum Season {
    SPRING("Spring"), SUMMER("Summer"), FALL("Fall"), WINTER("Winter");

    private String name;

    Season(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

Now, back to the method.

public void printSeason(Season season) {
    System.out.println("It is " + season.getName() + " now!");
}

Instead of using int, you can now use Season as input. Instead of a condition check, you can tell Season to give you its name.

This is how you use this method now:

printSeason(Season.SPRING);
printSeason(Season.WINTER);
printSeason(Season.WHATEVER); <-- compile error

You will get a compile-time error when you use an incorrect input, and you're guaranteed to get a non-null singleton reference of Season as long as the program compiles.

When we need an additional season, we simply add another constant in Season and no more.

public enum Season {
    SPRING("Spring"), SUMMER("Summer"), FALL("Fall"), WINTER("Winter"), 
    MYSEASON("My Season");

...

Whenever you need a fixed set of constants, enum can be a good choice (but not always). It's a more readable, more reliable and more powerful solution.

jQuery: get parent, parent id?

$(this).parent().parent().attr('id');

Is how you would get the id of the parent's parent.

EDIT:

$(this).closest('ul').attr('id');

Is a more foolproof solution for your case.

How do I find the mime-type of a file with php?

If you are sure you're only ever working with images, you can check out the getimagesize() exif_imagetype() PHP function, which attempts to return the image mime-type.

If you don't mind external dependencies, you can also check out the excellent getID3 library which can determine the mime-type of many different file types.

Lastly, you can check out the mime_content_type() function - but it has been deprecated for the Fileinfo PECL extension.

How do I make a request using HTTP basic authentication with PHP curl?

Other way with Basic method is:

$curl = curl_init();

$public_key = "public_key";
$private_key = "private_key";

curl_setopt_array($curl, array(
CURLOPT_URL => "https://url.endpoint.co/login",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array(
"Content-Type: application/json",
"Authorization: Basic ".base64_encode($public_key.":".$private_key)
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;

Date validation with ASP.NET validator

Best option would be

Add a compare validator to the web form. Set its controlToValidate. Set its Type property to Date. Set its operator property to DataTypeCheck eg:

<asp:CompareValidator
    id="dateValidator" runat="server" 
    Type="Date"
    Operator="DataTypeCheck"
    ControlToValidate="txtDatecompleted" 
    ErrorMessage="Please enter a valid date.">
</asp:CompareValidator>

PySpark: withColumn() with two conditions and three outcomes

There are a few efficient ways to implement this. Let's start with required imports:

from pyspark.sql.functions import col, expr, when

You can use Hive IF function inside expr:

new_column_1 = expr(
    """IF(fruit1 IS NULL OR fruit2 IS NULL, 3, IF(fruit1 = fruit2, 1, 0))"""
)

or when + otherwise:

new_column_2 = when(
    col("fruit1").isNull() | col("fruit2").isNull(), 3
).when(col("fruit1") == col("fruit2"), 1).otherwise(0)

Finally you could use following trick:

from pyspark.sql.functions import coalesce, lit

new_column_3 = coalesce((col("fruit1") == col("fruit2")).cast("int"), lit(3))

With example data:

df = sc.parallelize([
    ("orange", "apple"), ("kiwi", None), (None, "banana"), 
    ("mango", "mango"), (None, None)
]).toDF(["fruit1", "fruit2"])

you can use this as follows:

(df
    .withColumn("new_column_1", new_column_1)
    .withColumn("new_column_2", new_column_2)
    .withColumn("new_column_3", new_column_3))

and the result is:

+------+------+------------+------------+------------+
|fruit1|fruit2|new_column_1|new_column_2|new_column_3|
+------+------+------------+------------+------------+
|orange| apple|           0|           0|           0|
|  kiwi|  null|           3|           3|           3|
|  null|banana|           3|           3|           3|
| mango| mango|           1|           1|           1|
|  null|  null|           3|           3|           3|
+------+------+------------+------------+------------+

Contains case insensitive

if (referrer.toUpperCase().indexOf("RAL") == -1) { ...

C# Encoding a text string with line breaks

Yes - it means you're using \n as the line break instead of \r\n. Notepad only understands the latter.

(Note that Environment.NewLine suggested by others is fine if you want the platform default - but if you're serving from Mono and definitely want \r\n, you should specify it explicitly.)

How to get the request parameters in Symfony 2?

public function indexAction(Request $request)
{
   $data = $request->get('corresponding_arg');
   // this also works
   $data1 = $request->query->get('corresponding_arg1');
}

JPG vs. JPEG image formats

There's no difference between the file extensions, and they are used interchangeably. I guess the 3-letter version stems from the DOS era...

However, there are different "flavors" of JPEG files. Most notably the JFIF standard and the EXIF standard. Most often these just use .jpg or .jpeg as file extensions, JFIF sometimes uses .jif or .jfif.

"detached entity passed to persist error" with JPA/EJB code

if you use to generate the id = GenerationType.AUTO strategy in your entity.

Replaces user.setId (1) by user.setId (null), and the problem is solved.

How to fix apt-get: command not found on AWS EC2?

please, be sure your connected to a ubuntu server, I Had the same problem but I was connected to other distro, check the AMI value in your details instance, it should be something like

AMI: ubuntu/images/ebs/ubuntu-precise-12.04-amd64-server-20130411.1 

hope it helps

HTML 5 input type="number" element for floating point numbers on Chrome

Try <input type="number" step="any" />

It won't have validation problems and the arrows will have step of "1"

Constraint validation: When the element has an allowed value step, and the result of applying the algorithm to convert a string to a number to the string given by the element's value is a number, and that number subtracted from the step base is not an integral multiple of the allowed value step, the element is suffering from a step mismatch.

The following range control only accepts values in the range 0..1, and allows 256 steps in that range:

<input name=opacity type=range min=0 max=1 step=0.00392156863>

The following control allows any time in the day to be selected, with any accuracy (e.g. thousandth-of-a-second accuracy or more):

<input name=favtime type=time step=any>

Normally, time controls are limited to an accuracy of one minute.

http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-attributes.html#attr-input-step

Do Git tags only apply to the current branch?

When calling just git tag <TAGNAME> without any additional parameters, Git will create a new tag from your current HEAD (i.e. the HEAD of your current branch). When adding additional commits into this branch, the branch HEAD will keep up with those new commits, while the tag always refers to the same commit.

When calling git tag <TAGNAME> <COMMIT> you can even specify which commit to use for creating the tag.

Regardless, a tag is still simply a "pointer" to a certain commit (not a branch).

How to get file path from OpenFileDialog and FolderBrowserDialog?

For OpenFileDialog:

OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = true;

if (choofdlog.ShowDialog() == DialogResult.OK)    
{     
    string sFileName = choofdlog.FileName; 
    string[] arrAllFiles = choofdlog.FileNames; //used when Multiselect = true           
}

For FolderBrowserDialog:

FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Custom Description"; 

if (fbd.ShowDialog() == DialogResult.OK)
{
    string sSelectedPath = fbd.SelectedPath;
}

To access selected folder and selected file name you can declare both string at class level.

namespace filereplacer
{
   public partial class Form1 : Form
   {
      string sSelectedFile;
      string sSelectedFolder;

      public Form1()
      {
         InitializeComponent();
      }

      private void direc_Click(object sender, EventArgs e)
      {
         FolderBrowserDialog fbd = new FolderBrowserDialog();
         //fbd.Description = "Custom Description"; //not mandatory

         if (fbd.ShowDialog() == DialogResult.OK)      
               sSelectedFolder = fbd.SelectedPath;
         else
               sSelectedFolder = string.Empty;    
      }

      private void choof_Click(object sender, EventArgs e)
      {
         OpenFileDialog choofdlog = new OpenFileDialog();
         choofdlog.Filter = "All Files (*.*)|*.*";
         choofdlog.FilterIndex = 1;
         choofdlog.Multiselect = true;

         if (choofdlog.ShowDialog() == DialogResult.OK)                 
             sSelectedFile = choofdlog.FileName;            
         else
             sSelectedFile = string.Empty;       
      }

      private void replacebtn_Click(object sender, EventArgs e)
      {
          if(sSelectedFolder != string.Empty && sSelectedFile != string.Empty)
          {
               //use selected folder path and file path
          }
      }
      ....
}

NOTE:

As you have kept choofdlog.Multiselect=true;, that means in the OpenFileDialog() you are able to select multiple files (by pressing ctrl key and left mouse click for selection).

In that case you could get all selected files in string[]:

At Class Level:

string[] arrAllFiles;

Locate this line (when Multiselect=true this line gives first file only):

sSelectedFile = choofdlog.FileName; 

To get all files use this:

arrAllFiles = choofdlog.FileNames; //this line gives array of all selected files

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

It is:

<%=Html.ActionLink("Home", "Index", MyRouteValObj, new with {.class = "tab" })%>

In VB.net you set an anonymous type using

new with {.class = "tab" }

and, as other point out, your third parameter should be an object (could be an anonymous type, also).

Terminating idle mysql connections

I don't see any problem, unless you are not managing them using a connection pool.

If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.

Foreign Key to multiple tables

Another approach is to create an association table that contains columns for each potential resource type. In your example, each of the two existing owner types has their own table (which means you have something to reference). If this will always be the case you can have something like this:

CREATE TABLE dbo.Group
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL
)  

CREATE TABLE dbo.User
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL
)

CREATE TABLE dbo.Ticket
(
    ID int NOT NULL,
    Owner_ID int NOT NULL,
    Subject varchar(50) NULL
)

CREATE TABLE dbo.Owner
(
    ID int NOT NULL,
    User_ID int NULL,
    Group_ID int NULL,
    {{AdditionalEntity_ID}} int NOT NULL
)

With this solution, you would continue to add new columns as you add new entities to the database and you would delete and recreate the foreign key constraint pattern shown by @Nathan Skerl. This solution is very similar to @Nathan Skerl but looks different (up to preference).

If you are not going to have a new Table for each new Owner type then maybe it would be good to include an owner_type instead of a foreign key column for each potential Owner:

CREATE TABLE dbo.Group
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL
)  

CREATE TABLE dbo.User
(
    ID int NOT NULL,
    Name varchar(50) NOT NULL
)

CREATE TABLE dbo.Ticket
(
    ID int NOT NULL,
    Owner_ID int NOT NULL,
    Owner_Type string NOT NULL, -- In our example, this would be "User" or "Group"
    Subject varchar(50) NULL
)

With the above method, you could add as many Owner Types as you want. Owner_ID would not have a foreign key constraint but would be used as a reference to the other tables. The downside is that you would have to look at the table to see what the owner types there are since it isn't immediately obvious based upon the schema. I would only suggest this if you don't know the owner types beforehand and they won't be linking to other tables. If you do know the owner types beforehand, I would go with a solution like @Nathan Skerl.

Sorry if I got some SQL wrong, I just threw this together.

How do I skip an iteration of a `foreach` loop?

foreach ( int number in numbers )
{
    if ( number < 0 )
    {
        continue;
    }

    //otherwise process number
}

NLS_NUMERIC_CHARACTERS setting for decimal

Best way is,

SELECT to_number(replace(:Str,',','')/100) --into num2 
FROM dual;

Get button click inside UITableViewCell

I find it simplest to subclass the button inside your cell (Swift 3):

class MyCellInfoButton: UIButton {
    var indexPath: IndexPath?
}

In your cell class:

class MyCell: UICollectionViewCell {
    @IBOutlet weak var infoButton: MyCellInfoButton!
   ...
}

In the table view's or collection view's data source, when dequeueing the cell, give the button its index path:

cell.infoButton.indexPath = indexPath

So you can just put these code into your table view controller:

@IBAction func handleTapOnCellInfoButton(_ sender: MyCellInfoButton) {
        print(sender.indexPath!) // Do whatever you want with the index path!
}

And don't forget to set the button's class in your Interface Builder and link it to the handleTapOnCellInfoButton function!


edited:

Using dependency injection. To set up calling a closure:

class MyCell: UICollectionViewCell {
    var someFunction: (() -> Void)?
    ...
    @IBAction func didTapInfoButton() {
        someFunction?()
    }
}

and inject the closure in the willDisplay method of the collection view's delegate:

 func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    (cell as? MyCell)?.someFunction = {
        print(indexPath) // Do something with the indexPath.
    }
}

This could be due to the service endpoint binding not using the HTTP protocol

I think there is serialization problem, you can find exact error just need to add below code in service config in <configuration> section.

After config update "App_tracelog.svclog" file will create, where your service exist just need to open .svclog file and find red color line on left side panel which is error and see its description for more info.

I hope this will help to find your error.

<configuration>
...
...

<system.diagnostics>
    <sources>
      <source name="System.ServiceModel.MessageLogging" switchValue="Warning, ActivityTracing">
        <listeners>
          <add name="ServiceModelTraceListener" />
        </listeners>
      </source>
      <source name="System.ServiceModel" switchValue="Verbose,ActivityTracing">
        <listeners>
          <add name="ServiceModelTraceListener" />
        </listeners>
      </source>
      <source name="System.Runtime.Serialization" switchValue="Verbose,ActivityTracing">
        <listeners>
          <add name="ServiceModelTraceListener" />
        </listeners>
      </source>
    </sources>
    <sharedListeners>
      <add initializeData="App_tracelog.svclog" type="System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" name="ServiceModelTraceListener" traceOutputOptions="Timestamp" />
    </sharedListeners>
  </system.diagnostics>

  </configuration>

Update: If you will not able to find updated "App_tracelog.svclog" file then please find "<some GUID>App_tracelog.svclog" like "a39e3026-5dd8-4d39-842a-04d486615eedApp_tracelog.svclog"

MongoDB not equal to

Use $ne instead of $not

http://docs.mongodb.org/manual/reference/operator/ne/#op._S_ne

db.collections.find({"name": {$ne: ""}});

TypeError: 'function' object is not subscriptable - Python

You can use this:

bankHoliday= [1, 0, 1, 1, 2, 0, 0, 1, 0, 0, 0, 2] #gives the list of bank holidays in each month

def bank_holiday(month):
   month -= 1#Takes away the numbers from the months, as months start at 1 (January) not at 0. There is no 0 month.
   print(bankHoliday[month])

bank_holiday(int(input("Which month would you like to check out: ")))

What is tail recursion?

here is a Perl 5 version of the tailrecsum function mentioned earlier.

sub tail_rec_sum($;$){
  my( $x,$running_total ) = (@_,0);

  return $running_total unless $x;

  @_ = ($x-1,$running_total+$x);
  goto &tail_rec_sum; # throw away current stack frame
}

How to get Real IP from Visitor?

This is my approach:

 function getRealUserIp(){
    switch(true){
      case (!empty($_SERVER['HTTP_X_REAL_IP'])) : return $_SERVER['HTTP_X_REAL_IP'];
      case (!empty($_SERVER['HTTP_CLIENT_IP'])) : return $_SERVER['HTTP_CLIENT_IP'];
      case (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) : return $_SERVER['HTTP_X_FORWARDED_FOR'];
      default : return $_SERVER['REMOTE_ADDR'];
    }
 }

How to use:

$ip = getRealUserIp();

Which JRE am I using?

The following command will tell you a lot of information about your java version, including the vendor:

java -XshowSettings:properties -version

It works on Windows, Mac, and Linux.

Custom date format with jQuery validation plugin

You can create your own custom validation method using the addMethod function. Say you wanted to validate "dd/mm/yyyy":

$.validator.addMethod(
    "australianDate",
    function(value, element) {
        // put your own logic here, this is just a (crappy) example
        return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
    },
    "Please enter a date in the format dd/mm/yyyy."
);

And then on your form add:

$('#myForm')
    .validate({
        rules : {
            myDate : {
                australianDate : true
            }
        }
    })
;

html <input type="text" /> onchange event not working

onchange is only triggered when the control is blurred. Try onkeypress instead.

HTML for the Pause symbol in audio and video control

Modern browsers support 'DOUBLE VERTICAL BAR' (U+23F8), too:

http://www.fileformat.info/info/unicode/char/23f8/index.htm

For a music player it can act as a companion for 'BLACK RIGHT-POINTING POINTER' (U+25BA) because they both share equal width and height making it perfect for a play/pause button:

http://www.fileformat.info/info/unicode/char/25ba/index.htm

Webview load html from assets directory

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView wb = new WebView(this);
        wb.loadUrl("file:///android_asset/index.html");
        setContentView(wb);
    }


keep your .html in `asset` folder

remove duplicates from sql union

Using UNION automatically removes duplicate rows unless you specify UNION ALL: http://msdn.microsoft.com/en-us/library/ms180026(SQL.90).aspx

What's the difference between REST & RESTful

Web services are essentially web sites whose content is consumed by computer programs, not people. REST is a set of architectural principles that stipulate that web services should maximally leverage HTTP and other web standards, so that programs gain all the good stuff that people already can get out of the web. REST is often contrasted with SOAP web services, and other "remote procedure call" oriented web services.

Stefan Tilkov's presentations on REST at Parleys.com are quite good, especially this one.

For a book, you can't get any better than Richardson and Ruby's Restful Web Services.

How to make inline functions in C#

Yes, C# supports that. There are several syntaxes available.

  • Anonymous methods were added in C# 2.0:

    Func<int, int, int> add = delegate(int x, int y)
    {
        return x + y;
    };
    Action<int> print = delegate(int x)
    {
        Console.WriteLine(x);
    }
    Action<int> helloWorld = delegate // parameters can be elided if ignored
    {
        Console.WriteLine("Hello world!");
    }
    
  • Lambdas are new in C# 3.0 and come in two flavours.

    • Expression lambdas:

      Func<int, int, int> add = (int x, int y) => x + y; // or...
      Func<int, int, int> add = (x, y) => x + y; // types are inferred by the compiler
      
    • Statement lambdas:

      Action<int> print = (int x) => { Console.WriteLine(x); };
      Action<int> print = x => { Console.WriteLine(x); }; // inferred types
      Func<int, int, int> add = (x, y) => { return x + y; };
      
  • Local functions have been introduced with C# 7.0:

    int add(int x, int y) => x + y;
    void print(int x) { Console.WriteLine(x); }
    

There are basically two different types for these: Func and Action. Funcs return values but Actions don't. The last type parameter of a Func is the return type; all the others are the parameter types.

There are similar types with different names, but the syntax for declaring them inline is the same. An example of this is Comparison<T>, which is roughly equivalent to Func<T, T, int>.

Func<string, string, int> compare1 = (l,r) => 1;
Comparison<string> compare2 = (l, r) => 1;
Comparison<string> compare3 = compare1; // this one only works from C# 4.0 onwards

These can be invoked directly as if they were regular methods:

int x = add(23, 17); // x == 40
print(x); // outputs 40
helloWorld(x); // helloWorld has one int parameter declared: Action<int>
               // even though it does not make any use of it.

Replace multiple strings at once

One method would be:

var text = $(this).val();
text = text.replace(/</g, "&lt;").replace(/>/g, "&gt;");
$("#output").html(text);

AttributeError: 'numpy.ndarray' object has no attribute 'append'

I got this error after change a loop in my program, let`s see:

for ...
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

In fact, I was reusing the variable and forgot to reset them inside the external loop, like the comment of John Lyon:

for ...
  x_batch = []
  y_batch = []
  for ... 
     x_batch.append(one_hot(int_word, vocab_size))
     y_batch.append(one_hot(int_nb, vocab_size, value))
  ...
  ...
  if ...
        x_batch = np.asarray(x_batch)
        y_batch = np.asarray(y_batch)
...

Then, check if you are using np.asarray() or something like that.

How to check if a text field is empty or not in swift

Swift 4/xcode 9

IBAction func button(_ sender: UIButton) {
        if (textField1.text?.isEmpty)! || (textfield2.text?.isEmpty)!{
                ..............
        }
}

How to change maven logging level to display only warning and errors?

You can achieve this with MAVEN_OPTS, for example
MAVEN_OPTS=-Dorg.slf4j.simpleLogger.defaultLogLevel=warn mvn clean

Rather than putting the system property directly on the command line. (At least for maven 3.3.1.)

Consider using ~/.mavenrc for setting MAVEN_OPTS if you would like logging changed for your login across all maven invocations.

How to copy static files to build directory with Webpack?

The way I load static images and fonts:

module: {
    rules: [
      ....

      {
        test: /\.(jpe?g|png|gif|svg)$/i,
        /* Exclude fonts while working with images, e.g. .svg can be both image or font. */
        exclude: path.resolve(__dirname, '../src/assets/fonts'),
        use: [{
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: 'images/'
          }
        }]
      },
      {
        test: /\.(woff(2)?|ttf|eot|svg|otf)(\?v=\d+\.\d+\.\d+)?$/,
        /* Exclude images while working with fonts, e.g. .svg can be both image or font. */
        exclude: path.resolve(__dirname, '../src/assets/images'),
        use: [{
          loader: 'file-loader',
          options: {
            name: '[name].[ext]',
            outputPath: 'fonts/'
          },
        }
    ]
}

Don't forget to install file-loader to have that working.

How should I import data from CSV into a Postgres table using pgAdmin 3?

pgAdmin has GUI for data import since 1.16. You have to create your table first and then you can import data easily - just right-click on the table name and click on Import.

enter image description here

enter image description here

What is <scope> under <dependency> in pom.xml for?

added good images with explain scopes

enter image description here

enter image description here

How to center a button within a div?

Margin: 0 auto; is the correct answer for horizontal centering only. For centering both ways something like this will work, using jquery:

var cenBtn = function() {
   var W = $(window).width();
   var H = $(window).height();
   var BtnW = insert button width;
   var BtnH = insert button height;
   var LeftOff = (W / 2) - (BtnW / 2);
   var TopOff = (H / 2) - (BtnH /2);
       $("#buttonID").css({left: LeftOff, top: TopOff});
};

$(window).bind("load, resize", cenBtn);

Update ... five years later, one could use flexbox on the parent DIV element to easily center the button both horizontally and vertically.

Including all browser prefixes, for best support

div {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-align : center;
  -moz-box-align    : center;
  -ms-flex-align    : center;
  -webkit-align-items : center;
  align-items : center ;
  justify-content : center;
  -webkit-justify-content : center;
  -webkit-box-pack : center;
  -moz-box-pack : center;
  -ms-flex-pack : center;
}

_x000D_
_x000D_
#container {_x000D_
  position: relative;_x000D_
  margin: 20px;_x000D_
  background: red;_x000D_
  height: 300px;_x000D_
  width: 400px;_x000D_
}_x000D_
_x000D_
#container div {_x000D_
  display: -webkit-box;_x000D_
  display: -moz-box;_x000D_
  display: -ms-flexbox;_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-box-align: center;_x000D_
  -moz-box-align: center;_x000D_
  -ms-flex-align: center;_x000D_
  -webkit-align-items: center;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
  -webkit-box-pack: center;_x000D_
  -moz-box-pack: center;_x000D_
  -ms-flex-pack: center;_x000D_
  -webkit-justify-content: center;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<!-- using a container to make the 100% width and height mean something -->_x000D_
<div id="container"> _x000D_
  <div style="width:100%; height:100%">_x000D_
    <button type="button">hello</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

This worked for me !! :

Go to this path or where ever you have your keytool.exe file

C:\Program Files\Java\jre7\bin

Hold shift and right click -> then press Open command window here

terminal will pop up, paste this in:

keytool -list -v -keystore "C:\Users\"Your-User-Name(no quotes)"\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

gives you both MD5 and SHA1

Best C# API to create PDF

My work uses Winnovative's PDF generator (We've used it mainly to convert HTML to PDF, but you can generate it other ways as well)

convert array into DataFrame in Python

In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column

import pandas as pd    
import numpy as np   
e = np.random.normal(size=100)  
e_dataframe = pd.DataFrame(e)      

e_dataframe.rename(index=str, columns={0:'new_column_name'})

How to loop backwards in python?

def reverse(text):
    reversed = ''
    for i in range(len(text)-1, -1, -1):
        reversed += text[i]
    return reversed

print("reverse({}): {}".format("abcd", reverse("abcd")))

How to find out mySQL server ip address from phpmyadmin

You can ssh to your server and run this command

 ln -s /usr/share/phpmyadmin /var/www/phpmyadmin

It worked for me..

mySQL convert varchar to date

As gratitude to the timely help I got from here - a minor update to above.

$query = "UPDATE `db`.`table` SET `fieldname`=  str_to_date(  fieldname, '%d/%m/%Y')";

How to fire AJAX request Periodically?

Yes, you could use either the JavaScript setTimeout() method or setInterval() method to invoke the code that you would like to run. Here's how you might do it with setTimeout:

function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}

$(document).ready(function() {
  // run the first time; all subsequent calls will take care of themselves
  setTimeout(executeQuery, 5000);
});

window.onload vs $(document).ready()

The $(document).ready() is a jQuery event which occurs when the HTML document has been fully loaded, while the window.onload event occurs later, when everything including images on the page loaded.

Also window.onload is a pure javascript event in the DOM, while the $(document).ready() event is a method in jQuery.

$(document).ready() is usually the wrapper for jQuery to make sure the elements all loaded in to be used in jQuery...

Look at to jQuery source code to understand how it's working:

jQuery.ready.promise = function( obj ) {
    if ( !readyList ) {

        readyList = jQuery.Deferred();

        // Catch cases where $(document).ready() is called after the browser event has already occurred.
        // we once tried to use readyState "interactive" here, but it caused issues like the one
        // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
        if ( document.readyState === "complete" ) {
            // Handle it asynchronously to allow scripts the opportunity to delay ready
            setTimeout( jQuery.ready );

        // Standards-based browsers support DOMContentLoaded
        } else if ( document.addEventListener ) {
            // Use the handy event callback
            document.addEventListener( "DOMContentLoaded", completed, false );

            // A fallback to window.onload, that will always work
            window.addEventListener( "load", completed, false );

        // If IE event model is used
        } else {
            // Ensure firing before onload, maybe late but safe also for iframes
            document.attachEvent( "onreadystatechange", completed );

            // A fallback to window.onload, that will always work
            window.attachEvent( "onload", completed );

            // If IE and not a frame
            // continually check to see if the document is ready
            var top = false;

            try {
                top = window.frameElement == null && document.documentElement;
            } catch(e) {}

            if ( top && top.doScroll ) {
                (function doScrollCheck() {
                    if ( !jQuery.isReady ) {

                        try {
                            // Use the trick by Diego Perini
                            // http://javascript.nwbox.com/IEContentLoaded/
                            top.doScroll("left");
                        } catch(e) {
                            return setTimeout( doScrollCheck, 50 );
                        }

                        // detach all dom ready events
                        detach();

                        // and execute any waiting functions
                        jQuery.ready();
                    }
                })();
            }
        }
    }
    return readyList.promise( obj );
};
jQuery.fn.ready = function( fn ) {
    // Add the callback
    jQuery.ready.promise().done( fn );

    return this;
};

Also I have created the image below as a quick references for both:

enter image description here

How do I disable a Pylint warning?

Python syntax does permit more than one statement on a line, separated by semicolon (;). However, limiting each line to one statement makes it easier for a human to follow a program's logic when reading through it.

So, another way of solving this issue, is to understand why the lint message is there and not put more than one statement on a line.

Yes, you may find it easier to write multiple statements per line, however, Pylint is for every other reader of your code not just you.

Apache shows PHP code instead of executing it

What worked for me:

In active httpd.conf, find

<IfModule mime_module>
...
</IfModule>

It was missing the following

AddType application/x-httpd-php .php
AddHandler application/x-httpd-php .php

After restarting apache, .php files are correctly parsed.

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

How to move div vertically down using CSS

Try this configuration:

    position to absolute
    width to 100%
    height to 100px
    bottom to 10
    background-color: blue

This can help actually move the div to the bottom. Just modify accordingly.

List all virtualenv

If you are using virtualenv or Python 3's built in venv the above answers might not work.

If you are on Linux, just locate the activate script that is always present inside a env.

locate -b '\activate' | grep "/home"

This will grab all Python virtual environments present inside your home directory.

See Demo Here

Upgrade version of Pandas

Add your C:\WinPython-64bit-3.4.4.1\python_***\Scripts folder to your system PATH variable by doing the following:

  1. Select Start, select Control Panel. double click System, and select the Advanced tab.
  2. Click Environment Variables. ...

  3. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. ...

  4. Reopen Command prompt window

How to delete specific columns with VBA?

You were just missing the second half of the column statement telling it to remove the entire column, since most normal Ranges start with a Column Letter, it was looking for a number and didn't get one. The ":" gets the whole column, or row.

I think what you were looking for in your Range was this:

Range("C:C,F:F,I:I,L:L,O:O,R:R").Delete

Just change the column letters to match your needs.

Why does the 260 character path length limit exist in Windows?

As to how to cope with the path size limitation on Windows - using 7zip to pack (and unpack) your path-length sensitive files seems like a viable workaround. I've used it to transport several IDE installations (those Eclipse plugin paths, yikes!) and piles of autogenerated documentation and haven't had a single problem so far.

Not really sure how it evades the 260 char limit set by Windows (from a technical PoV), but hey, it works!

More details on their SourceForge page here:

"NTFS can actually support pathnames up to 32,000 characters in length."

7-zip also support such long names.

But it's disabled in SFX code. Some users don't like long paths, since they don't understand how to work with them. That is why I have disabled it in SFX code.

and release notes:

9.32 alpha 2013-12-01

  • Improved support for file pathnames longer than 260 characters.

4.44 beta 2007-01-20

  • 7-Zip now supports file pathnames longer than 260 characters.

IMPORTANT NOTE: For this to work properly, you'll need to specify the destination path in the 7zip "Extract" dialog directly, rather than dragging & dropping the files into the intended folder. Otherwise the "Temp" folder will be used as an interim cache and you'll bounce into the same 260 char limitation once Windows Explorer starts moving the files to their "final resting place". See the replies to this question for more information.

What is the difference between Step Into and Step Over in a debugger

You can't go through the details of the method by using the step over. If you want to skip the current line, you can use step over, then you only need to press the F6 for only once to move to the next line. And if you think there's someting wrong within the method, use F5 to examine the details.

Property getters and setters

Setters and Getters apply to computed properties; such properties do not have storage in the instance - the value from the getter is meant to be computed from other instance properties. In your case, there is no x to be assigned.

Explicitly: "How can I do this without explicit backing ivars". You can't - you'll need something to backup the computed property. Try this:

class Point {
  private var _x: Int = 0             // _x -> backingX
  var x: Int {
    set { _x = 2 * newValue }
    get { return _x / 2 }
  }
}

Specifically, in the Swift REPL:

 15> var pt = Point()
pt: Point = {
  _x = 0
}
 16> pt.x = 10
 17> pt
$R3: Point = {
  _x = 20
}
 18> pt.x
$R4: Int = 10

HttpClient not supporting PostAsJsonAsync method C#

Just expanding Jeroen's answer with the tips in comments:

var content = new StringContent(
    JsonConvert.SerializeObject(user), 
    Encoding.UTF8, 
    MediaTypeNames.Application.Json);

var response = await client.PostAsync("api/AgentCollection", content);

Color text in terminal applications in UNIX

This is a little C program that illustrates how you could use color codes:

#include <stdio.h>

#define KNRM  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"

int main()
{
    printf("%sred\n", KRED);
    printf("%sgreen\n", KGRN);
    printf("%syellow\n", KYEL);
    printf("%sblue\n", KBLU);
    printf("%smagenta\n", KMAG);
    printf("%scyan\n", KCYN);
    printf("%swhite\n", KWHT);
    printf("%snormal\n", KNRM);

    return 0;
}

Select where count of one field is greater than one

You can also do this with a self-join:

SELECT t1.* FROM db.table t1
JOIN db.table t2 ON t1.someField = t2.someField AND t1.pk != t2.pk

How to center a window on the screen in Tkinter?

Tk provides a helper function that can do this as tk::PlaceWindow, but I don't believe it has been exposed as a wrapped method in Tkinter. You would center a widget using the following:

from tkinter import *

app = Tk()
app.eval('tk::PlaceWindow %s center' % app.winfo_pathname(app.winfo_id()))
app.mainloop()

This function should deal with multiple displays correctly as well. It also has options to center over another widget or relative to the pointer (used for placing popup menus), so that they don't fall off the screen.

Write output to a text file in PowerShell

Another way this could be accomplished is by using the Start-Transcript and Stop-Transcript commands, respectively before and after command execution. This would capture the entire session including commands.

Start-Transcript

Stop-Transcript

For this particular case Out-File is probably your best bet though.

Is there an equivalent of CSS max-width that works in HTML emails?

Bit late to the party, but this will get it done. I left the example at 600, as that is what most people will use:

Similar to Shay's example except this also includes max-width to work on the rest of the clients that do have support, as well as a second method to prevent the expansion (media query) which is needed for Outlook '11.

In the head:

  <style type="text/css">
    @media only screen and (min-width: 600px) { .maxW { width:600px !important; } }
  </style>

In the body:

<!--[if (gte mso 9)|(IE)]><table width="600" align="center" cellpadding="0" cellspacing="0" border="0"><tr><td><![endif]-->
<div class="maxW" style="max-width:600px;">

<table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
  <tr>
    <td>
main content here
    </td>
  </tr>
</table>

</div>
<!--[if (gte mso 9)|(IE)]></td></tr></table><![endif]-->

Here is another example of this in use: Responsive order confirmation emails for mobile devices?

Warning: require_once(): http:// wrapper is disabled in the server configuration by allow_url_include=0

try to use

<?php require_once($_SERVER['DOCUMENT_ROOT'].'/web/a.php'); ?>

Amazon S3 direct file upload from client browser - private key disclosure

If you don't have any server side code, you security depends on the security of the access to your JavaScript code on the client side (ie everybody who has the code could upload something).

So I would recommend, to simply create a special S3 bucket which is public writeable (but not readable), so you don't need any signed components on the client side.

The bucket name (a GUID eg) will be your only defense against malicious uploads (but a potential attacker could not use your bucket to transfer data, because it is write only to him)

How to set focus on an input field after rendering?

@Dhiraj's answer is correct, and for convenience you can use the autoFocus prop to have an input automatically focus when mounted:

<input autoFocus name=...

Note that in jsx it's autoFocus (capital F) unlike plain old html which is case-insensitive.

Pip error: Microsoft Visual C++ 14.0 is required

You need to install Microsoft Visual C++ 14.0 to install pycrypto:

error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual
C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools

In the comments you ask which link to use. Use the link to Visual C++ 2015 Build Tools. That will install Visual C++ 14.0 without installing Visual Studio.

In the comments you ask about methods of installing pycrypto that do not require installing a compiler. The binaries in the links appear to be for earlier versions of Python than you are using. One link is to a binary in a DropBox account.

I do not recommend downloading binary versions of cryptography libraries provided by third parties. The only way to guarantee that you are getting a version of pycrypto that is compatible with your version of Python and has not been built with any backdoors is to build it from the source.

After you have installed Visual C++, just re-run the original command:

pip install -U steem

To find out what the various install options mean, run this command:

pip help install

The help for the -U option says

-U, --upgrade        Upgrade all specified packages to the newest available
                     version. The handling of dependencies depends on the
                     upgrade-strategy used.

If you do not already have the steem library installed, you can run the command without the -U option.

ORA-28001: The password has expired

you are in wrong cdb/pdb so connect to right pdb

How to use vagrant in a proxy environment?

Auto detect your proxy settings and inject them in all your vagrant VM

install the proxy plugin

vagrant plugin install vagrant-proxyconf

add this conf to you private/user VagrantFile (it will be executed for all your projects) :

vi $HOME/.vagrant.d/Vagrantfile

Vagrant.configure("2") do |config|
  puts "proxyconf..."
  if Vagrant.has_plugin?("vagrant-proxyconf")
    puts "find proxyconf plugin !"
    if ENV["http_proxy"]
      puts "http_proxy: " + ENV["http_proxy"]
      config.proxy.http     = ENV["http_proxy"]
    end
    if ENV["https_proxy"]
      puts "https_proxy: " + ENV["https_proxy"]
      config.proxy.https    = ENV["https_proxy"]
    end
    if ENV["no_proxy"]
      config.proxy.no_proxy = ENV["no_proxy"]
    end
  end
end

now up your VM !

How to remove a web site from google analytics

You can also do in this way : select your profile then go to admin => in admin second column "Property" select the site you want to remove => go to third column "view settings" clic => on the right bottom you ll see delete the view => confirm and it s done , have a nice day all

Can dplyr package be used for conditional mutating?

The derivedFactor function from mosaic package seems to be designed to handle this. Using this example, it would look like:

library(dplyr)
library(mosaic)
df <- mutate(df, g = derivedFactor(
     "2" = (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)),
     "3" = (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
     .method = "first",
     .default = NA
     ))

(If you want the result to be numeric instead of a factor, you can wrap derivedFactor in an as.numeric call.)

derivedFactor can be used for an arbitrary number of conditionals, too.

Attach a body onload event with JS

This takes advantage of DOMContentLoaded - which fires before onload - but allows you to stick in all your unobtrusiveness...

window.onload - Dean Edwards - The blog post talks more about it - and here is the complete code copied from the comments of that same blog.

// Dean Edwards/Matthias Miller/John Resig

function init() {
  // quit if this function has already been called
  if (arguments.callee.done) return;

  // flag this function so we don't do the same thing twice
  arguments.callee.done = true;

  // kill the timer
  if (_timer) clearInterval(_timer);

  // do stuff
};

/* for Mozilla/Opera9 */
if (document.addEventListener) {
  document.addEventListener("DOMContentLoaded", init, false);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
  document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
  var script = document.getElementById("__ie_onload");
  script.onreadystatechange = function() {
    if (this.readyState == "complete") {
      init(); // call the onload handler
    }
  };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
  var _timer = setInterval(function() {
    if (/loaded|complete/.test(document.readyState)) {
      init(); // call the onload handler
    }
  }, 10);
}

/* for other browsers */
window.onload = init;

How to hide/show more text within a certain length (like youtube)

Another possible solution that we can use 2 HTML element to store brief and complete text. Hence we can show/hide appropriate HTML element :-)

<p class="content_description" id="brief_description" style="display: block;"> blah blah blah blah blah  </p><p class="content_description" id="complete_description" style="display: none;"> blah blah blah blah blah with complete text </p>

/* jQuery code to toggle both paragraph. */

(function(){
        $('#toggle_content').on(
                'click', function(){
                                $("#complete_description").toggle();
                                $("#brief_description").toggle();
                                if ($("#complete_description").css("display") == "none") {
                                    $(this).text('More...');
                                }   else{
                                    $(this).text('Less...');
                                }
                        }
                );
    })();

Is there a way to continue broken scp (secure copy) command process in Linux?

This is all you need.

 rsync -e ssh file host:/directory/.

How to check if a line has one of the strings in a list?

This still loops through the cartesian product of the two lists, but it does it one line:

>>> lines1 = ['soup', 'butter', 'venison']
>>> lines2 = ['prune', 'rye', 'turkey']
>>> search_strings = ['a', 'b', 'c']
>>> any(s in l for l in lines1 for s in search_strings)
True
>>> any(s in l for l in lines2 for s in search_strings)
False

This also have the advantage that any short-circuits, and so the looping stops as soon as a match is found. Also, this only finds the first occurrence of a string from search_strings in linesX. If you want to find multiple occurrences you could do something like this:

>>> lines3 = ['corn', 'butter', 'apples']
>>> [(s, l) for l in lines3 for s in search_strings if s in l]
[('c', 'corn'), ('b', 'butter'), ('a', 'apples')]

If you feel like coding something more complex, it seems the Aho-Corasick algorithm can test for the presence of multiple substrings in a given input string. (Thanks to Niklas B. for pointing that out.) I still think it would result in quadratic performance for your use-case since you'll still have to call it multiple times to search multiple lines. However, it would beat the above (cubic, on average) algorithm.

Monitor network activity in Android Phones

Without root, you can use debug proxies like Charlesproxy&Co.

How do I parse a string into a number with Dart?

In Dart 2 int.tryParse is available.

It returns null for invalid inputs instead of throwing. You can use it like this:

int val = int.tryParse(text) ?? defaultValue;

Convert seconds to Hour:Minute:Second

Use function gmdate() only if seconds are less than 86400 (1 day) :

$seconds = 8525;
echo gmdate('H:i:s', $seconds);
# 02:22:05

See: gmdate()

Run the Demo


Convert seconds to format by 'foot' no limit* :

$seconds = 8525;
$H = floor($seconds / 3600);
$i = ($seconds / 60) % 60;
$s = $seconds % 60;
echo sprintf("%02d:%02d:%02d", $H, $i, $s);
# 02:22:05

See: floor(), sprintf(), arithmetic operators

Run the Demo


Example use of DateTime extension:

$seconds = 8525;
$zero    = new DateTime("@0");
$offset  = new DateTime("@$seconds");
$diff    = $zero->diff($offset);
echo sprintf("%02d:%02d:%02d", $diff->days * 24 + $diff->h, $diff->i, $diff->s);
# 02:22:05

See: DateTime::__construct(), DateTime::modify(), clone, sprintf()

Run the Demo


MySQL example range of the result is constrained to that of the TIME data type, which is from -838:59:59 to 838:59:59 :

SELECT SEC_TO_TIME(8525);
# 02:22:05

See: SEC_TO_TIME

Run the Demo


PostgreSQL example:

SELECT TO_CHAR('8525 second'::interval, 'HH24:MI:SS');
# 02:22:05

Run the Demo

What is the best way to iterate over a dictionary?

If say, you want to iterate over the values collection by default, I believe you can implement IEnumerable<>, Where T is the type of the values object in the dictionary, and "this" is a Dictionary.

public new IEnumerator<T> GetEnumerator()
{
   return this.Values.GetEnumerator();
}

Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier

SELECT Id   'PatientId',
       ISNULL(CONVERT(varchar(50),ParentId),'')  'ParentId'
FROM Patients

ISNULL always tries to return a result that has the same data type as the type of its first argument. So, if you want the result to be a string (varchar), you'd best make sure that's the type of the first argument.


COALESCE is usually a better function to use than ISNULL, since it considers all argument data types and applies appropriate precedence rules to determine the final resulting data type. Unfortunately, in this case, uniqueidentifier has higher precedence than varchar, so that doesn't help.

(It's also generally preferred because it extends to more than two arguments)

Pretty-Print JSON in Java

Now this can be achieved with the JSONLib library:

http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONObject.html

If (and only if) you use the overloaded toString(int indentationFactor) method and not the standard toString() method.

I have verified this on the following version of the API:

<dependency>
  <groupId>org.json</groupId>
  <artifactId>json</artifactId>
  <version>20140107</version>
</dependency>

What's the Android ADB shell "dumpsys" tool and what are its benefits?

i use dumpsys to catch if app is crashed and process is still active. situation i used it is to find about remote machine app is crashed or not.

dumpsys | grep myapp | grep "Application Error" 

or

adb shell dumpsys | grep myapp | grep Error

or anything that helps...etc

if app is not running you will get nothing as result. When app is stoped messsage is shown on screen by android, process is still active and if you check via "ps" command or anything else, you will see process state is not showing any error or crash meaning. But when you click button to close message, app process will cleaned from process list. so catching crash state without any code in application is hard to find. but dumpsys helps you.

Listen for key press in .NET console app

If you are using Visual Studio, then you can use "Start Without Debugging" in the Debug menu.

It will automatically write "Press any key to continue . . ." to the console for you upon completion of the application and it will leave the console open for you until a key is pressed.

Rounding numbers to 2 digits after comma

Though we have many answers here with plenty of useful suggestions, each of them still misses some steps.
So here is a complete solution wrapped into small function:

function roundToTwoDigitsAfterComma(floatNumber) {
    return parseFloat((Math.round(floatNumber * 100) / 100).toFixed(2));
}

Just in case you are interested how this works:

  1. Multiple with 100 and then do round to keep precision of 2 digits after comma
  2. Divide back into 100 and use toFixed(2) to keep 2 digits after comma and throw other unuseful part
  3. Convert it back to float by using parseFloat() function as toFixed(2) returns string instead

Note: If you keep last 2 digits after comma because of working with monetary values, and doing financial calculations keep in mind that it's not a good idea and you'd better use integer values instead.

What does "publicPath" in Webpack do?

You can use publicPath to point to the location where you want webpack-dev-server to serve its "virtual" files. The publicPath option will be the same location of the content-build option for webpack-dev-server. webpack-dev-server creates virtual files that it will use when you start it. These virtual files resemble the actual bundled files webpack creates. Basically you will want the --content-base option to point to the directory your index.html is in. Here is an example setup:

//application directory structure
/app/
/build/
/build/index.html
/webpack.config.js


//webpack.config.js
var path = require("path");
module.exports = {
...
  output: {
    path: path.resolve(__dirname, "build"),
    publicPath: "/assets/",
    filename: "bundle.js"
  }
};  


//index.html
<!DOCTYPE>
<html>
...
<script src="assets/bundle.js"></script>
</html>

//starting a webpack-dev-server from the command line
$ webpack-dev-server --content-base build 

webpack-dev-server has created a virtual assets folder along with a virtual bundle.js file that it refers to. You can test this by going to localhost:8080/assets/bundle.js then check in your application for these files. They are only generated when you run the webpack-dev-server.

Clang vs GCC for my Linux Development project

EDIT:

The gcc guys really improved the diagnosis experience in gcc (ah competition). They created a wiki page to showcase it here. gcc 4.8 now has quite good diagnostics as well (gcc 4.9x added color support). Clang is still in the lead, but the gap is closing.


Original:

For students, I would unconditionally recommend Clang.

The performance in terms of generated code between gcc and Clang is now unclear (though I think that gcc 4.7 still has the lead, I haven't seen conclusive benchmarks yet), but for students to learn it does not really matter anyway.

On the other hand, Clang's extremely clear diagnostics are definitely easier for beginners to interpret.

Consider this simple snippet:

#include <string>
#include <iostream>

struct Student {
std::string surname;
std::string givenname;
}

std::ostream& operator<<(std::ostream& out, Student const& s) {
  return out << "{" << s.surname << ", " << s.givenname << "}";
}

int main() {
  Student me = { "Doe", "John" };
  std::cout << me << "\n";
}

You'll notice right away that the semi-colon is missing after the definition of the Student class, right :) ?

Well, gcc notices it too, after a fashion:

prog.cpp:9: error: expected initializer before ‘&’ token
prog.cpp: In function ‘int main()’:
prog.cpp:15: error: no match for ‘operator<<’ in ‘std::cout << me’
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:112: note: candidates are: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>& (*)(std::basic_ostream<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:121: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ios<_CharT, _Traits>& (*)(std::basic_ios<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:131: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::ios_base& (*)(std::ios_base&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:169: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:173: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:177: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(bool) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:97: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(short int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:184: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(short unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:111: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:195: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:204: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long long int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:208: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:213: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(double) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:217: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(float) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:225: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long double) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:229: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(const void*) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:125: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_streambuf<_CharT, _Traits>*) [with _CharT = char, _Traits = std::char_traits<char>]

And Clang is not exactly starring here either, but still:

/tmp/webcompile/_25327_1.cc:9:6: error: redefinition of 'ostream' as different kind of symbol
std::ostream& operator<<(std::ostream& out, Student const& s) {
     ^
In file included from /tmp/webcompile/_25327_1.cc:1:
In file included from /usr/include/c++/4.3/string:49:
In file included from /usr/include/c++/4.3/bits/localefwd.h:47:
/usr/include/c++/4.3/iosfwd:134:33: note: previous definition is here
  typedef basic_ostream<char>           ostream;        ///< @isiosfwd
                                        ^
/tmp/webcompile/_25327_1.cc:9:13: error: expected ';' after top level declarator
std::ostream& operator<<(std::ostream& out, Student const& s) {
            ^
            ;
2 errors generated.

I purposefully choose an example which triggers an unclear error message (coming from an ambiguity in the grammar) rather than the typical "Oh my god Clang read my mind" examples. Still, we notice that Clang avoids the flood of errors. No need to scare students away.

What is the best way to find the users home directory in Java?

Actually with Java 8 the right way is to use:

System.getProperty("user.home");

The bug JDK-6519127 has been fixed and the "Incompatibilities between JDK 8 and JDK 7" section of the release notes states:

Area: Core Libs / java.lang

Synopsis

The steps used to determine the user's home directory on Windows have changed to follow the Microsoft recommended approach. This change might be observable on older editions of Windows or where registry settings or environment variables are set to other directories. Nature of Incompatibility

behavioral RFE

6519127

Despite the question being old I leave this for future reference.

How to get rid of "Unnamed: 0" column in a pandas DataFrame?

It's the index column, pass pd.to_csv(..., index=False) to not write out an unnamed index column in the first place, see the to_csv() docs.

Example:

In [37]:
df = pd.DataFrame(np.random.randn(5,3), columns=list('abc'))
pd.read_csv(io.StringIO(df.to_csv()))

Out[37]:
   Unnamed: 0         a         b         c
0           0  0.109066 -1.112704 -0.545209
1           1  0.447114  1.525341  0.317252
2           2  0.507495  0.137863  0.886283
3           3  1.452867  1.888363  1.168101
4           4  0.901371 -0.704805  0.088335

compare with:

In [38]:
pd.read_csv(io.StringIO(df.to_csv(index=False)))

Out[38]:
          a         b         c
0  0.109066 -1.112704 -0.545209
1  0.447114  1.525341  0.317252
2  0.507495  0.137863  0.886283
3  1.452867  1.888363  1.168101
4  0.901371 -0.704805  0.088335

You could also optionally tell read_csv that the first column is the index column by passing index_col=0:

In [40]:
pd.read_csv(io.StringIO(df.to_csv()), index_col=0)

Out[40]:
          a         b         c
0  0.109066 -1.112704 -0.545209
1  0.447114  1.525341  0.317252
2  0.507495  0.137863  0.886283
3  1.452867  1.888363  1.168101
4  0.901371 -0.704805  0.088335

How to read a text file in project's root directory?

In this code you access to root directory project:

 string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);

then:

StreamReader r = new StreamReader(_filePath + "/cities2.json"))

Excel Formula which places date/time in cell when data is entered in another cell in the same row

Not sure if this works for cells with functions but I found this code elsewhere for single cell entries and modified it for my use. If done properly, you do not need to worry about entering a function in a cell or the file changing the dates to that day's date every time it is opened.

  • open Excel
  • press "Alt+F11"
  • Double-click on the worksheet that you want to apply the change to (listed on the left)
  • copy/paste the code below
  • adjust the Range(:) input to correspond to the column you will update
  • adjust the Offset(0,_) input to correspond to the column where you would like the date displayed (in the version below I am making updates to column D and I want the date displayed in column F, hence the input entry of "2" for 2 columns over from column D)
  • hit save
  • repeat steps above if there are other worksheets in your workbook that need the same code
  • you may have to change the number format of the column displaying the date to "General" and increase the column's width if it is displaying "####" after you make an updated entry

Copy/Paste Code below:


Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range("D:D")) Is Nothing Then Exit Sub
Target.Offset(0, 2) = Date

End Sub


Good luck...

MySQL: Selecting multiple fields into multiple variables in a stored procedure

Alternatively to Martin's answer, you could also add the INTO part at the end of the query to make the query more readable:

SELECT Id, dateCreated FROM products INTO iId, dCreate

Batch / Find And Edit Lines in TXT file

On a native Windows install, you can either use batch(cmd.exe) or vbscript without the need to get external tools. Here's an example in vbscript:

Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "c:\test\file.txt"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
    strLine = objFile.ReadLine
    If InStr(strLine,"ex3")> 0 Then
        strLine = Replace(strLine,"ex3","ex5")
    End If 
    WScript.Echo strLine
Loop    

Save as myreplace.vbs and on the command line:

c:\test> cscript /nologo myreplace.vbs  > newfile
c:\test> ren newfile file.txt

Sass and combined child selector

For that single rule you have, there isn't any shorter way to do it. The child combinator is the same in CSS and in Sass/SCSS and there's no alternative to it.

However, if you had multiple rules like this:

#foo > ul > li > ul > li > a:nth-child(3n+1) {
    color: red;
}

#foo > ul > li > ul > li > a:nth-child(3n+2) {
    color: green;
}

#foo > ul > li > ul > li > a:nth-child(3n+3) {
    color: blue;
}

You could condense them to one of the following:

/* Sass */
#foo > ul > li > ul > li
    > a:nth-child(3n+1)
        color: red
    > a:nth-child(3n+2)
        color: green
    > a:nth-child(3n+3)
        color: blue

/* SCSS */
#foo > ul > li > ul > li {
    > a:nth-child(3n+1) { color: red; }
    > a:nth-child(3n+2) { color: green; }
    > a:nth-child(3n+3) { color: blue; }
}

How to get min, seconds and milliseconds from datetime.now() in python?

What about:

datetime.now().strftime('%M:%S.%f')[:-4]

I'm not sure what you mean by "Milliseconds only 2 digits", but this should keep it to 2 decimal places. There may be a more elegant way by manipulating the strftime format string to cut down on the precision as well -- I'm not completely sure.

EDIT

If the %f modifier doesn't work for you, you can try something like:

now=datetime.now()
string_i_want=('%02d:%02d.%d'%(now.minute,now.second,now.microsecond))[:-4]

Again, I'm assuming you just want to truncate the precision.

How to create a DOM node as an object?

First make your template into a jQuery object:

 var template = $("<li><div class='bar'>bla</div></li>");

Then set the attributes and append it to the DOM.

 template.find('li').attr('id','1234');
 $(document.body).append(template);

Note that it however makes no sense at all to add a li directly to the DOM since li should always be children of ul or ol. Also it is better to not make jQuery parse raw HTML. Instead create a li, set its attributes. Create a div and set it's attributes. Insert the div into the li and then append the li to the DOM.

Count indexes using "for" in Python

use enumerate:

>>> l = ['a', 'b', 'c', 'd']
>>> for index, val in enumerate(l):
...    print "%d: %s" % (index, val)
... 
0: a
1: b
2: c
3: d

printf %f with only 2 numbers after the decimal point?

as described in Formatter class, you need to declare precision. %.2f in your case.

custom facebook share button

This solution is using javascript to open a new window when a user clicks on your custom share button.

HTML:

<a href="#" onclick="share_fb('http://urlhere.com/test/55d7258b61707022e3050000');return false;" rel="nofollow" share_url="http://urlhere.com/test/55d7258b61707022e3050000" target="_blank">

  //using fontawesome
  <i class="uk-icon-facebook uk-float-left"></i>
    Share
</a>

and in your javascript file. note window.open params are (url, dialogue title, width, height)

function share_fb(url) {
  window.open('https://www.facebook.com/sharer/sharer.php?u='+url,'facebook-share-dialog',"width=626, height=436")
}

How to convert array to a string using methods other than JSON?

You are looking for serialize(). Here is an example:

$array = array('foo', 'bar');

//Array to String
$string = serialize($array);

//String to array
$array = unserialize($string);

How do I clear a search box with an 'x' in bootstrap 3?

AngularJS / UI-Bootstrap Answer

  • Use Bootstrap's has-feedback class to show an icon inside the input field.
  • Make sure the icon has style="cursor: pointer; pointer-events: all;"
  • Use ng-click to clear the text.

JavaScript (app.js)

var app = angular.module('plunker', ['ui.bootstrap']);

app.controller('MainCtrl', function($scope) {

  $scope.params = {};

  $scope.clearText = function() {
    $scope.params.text = null;
  }

});

HTML (index.html snippet)

      <div class="form-group has-feedback">
        <label>text box</label>
        <input type="text"
               ng-model="params.text"
               class="form-control"
               placeholder="type something here...">
        <span ng-if="params.text"
              ng-click="clearText()"
              class="glyphicon glyphicon-remove form-control-feedback" 
              style="cursor: pointer; pointer-events: all;"
              uib-tooltip="clear">
        </span>
      </div>

Here's the plunker: http://plnkr.co/edit/av9VFw?p=preview

Write to text file without overwriting in Java

You can change your PrintWriter and use method getAbsoluteFile(), this function returns the absolute File object of the given abstract pathname.

PrintWriter out = new PrintWriter(new FileWriter(log.getAbsoluteFile(), true));

How to upload a file using Java HttpClient library working with PHP

Aah you just need to add a name parameter in the

FileBody constructor. ContentBody cbFile = new FileBody(file, "image/jpeg", "FILE_NAME");

Hope it helps.

Getting attribute of element in ng-click function in angularjs

Addition to the answer of Brett DeWoody: (which is updated now)

var dataValue = obj.srcElement.attributes.data.nodeValue;

Works fine in IE(9+) and Chrome, but Firefox does not know the srcElement property. I found:

var dataValue = obj.currentTarget.attributes.data.nodeValue;

Works in IE, Chrome and FF, I did not test Safari.

Running javascript in Selenium using Python

Try browser.execute_script instead of selenium.GetEval.

See this answer for example.

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

I've updated com.google.gms:google-services from 3.1.1 to 3.2.0 and the warning stopped appearing.

buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.1.0'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files

    classpath 'com.google.gms:google-services:3.2.0'
    }
}

TypeError: unsupported operand type(s) for -: 'list' and 'list'

You can't subtract a list from a list.

>>> [3, 7] - [1, 2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'

Simple way to do it is using numpy:

>>> import numpy as np
>>> np.array([3, 7]) - np.array([1, 2])
array([2, 5])

You can also use list comprehension, but it will require changing code in the function:

>>> [a - b for a, b in zip([3, 7], [1, 2])]
[2, 5]

>>> import numpy as np
>>>
>>> def Naive_Gauss(Array,b):
...     n = len(Array)
...     for column in xrange(n-1):
...         for row in xrange(column+1, n):
...             xmult = Array[row][column] / Array[column][column]
...             Array[row][column] = xmult
...             #print Array[row][col]
...             for col in xrange(0, n):
...                 Array[row][col] = Array[row][col] - xmult*Array[column][col]
...             b[row] = b[row]-xmult*b[column]
...     print Array
...     print b
...     return Array, b  # <--- Without this, the function will return `None`.
...
>>> print Naive_Gauss(np.array([[2,3],[4,5]]),
...                   np.array([[6],[7]]))
[[ 2  3]
 [-2 -1]]
[[ 6]
 [-5]]
(array([[ 2,  3],
       [-2, -1]]), array([[ 6],
       [-5]]))

Add CSS or JavaScript files to layout head from views or partial views

You can define the section by RenderSection method in layout.

Layout

<head>
  <link href="@Url.Content("~/Content/themes/base/Site.css")"
    rel="stylesheet" type="text/css" />
  @RenderSection("heads", required: false)
</head>

Then you can include your css files in section area in your view except partial view.

The section work in view, but not work in partial view by design.

<!--your code -->
@section heads
{
  <link href="@Url.Content("~/Content/themes/base/AnotherPage.css")"
  rel="stylesheet" type="text/css" />
}

If you really want to using section area in partial view, you can follow the article to redefine RenderSection method.

Razor, Nested Layouts and Redefined Sections – Marcin On ASP.NET

Delayed rendering of React components

We can solve this using Hooks:

First we'll need a timeout hook for the delay.

This one is inspired by Dan Abramov's useInterval hook (see Dan's blog post for an in depth explanation), the differences being:

  1. we use we setTimeout not setInterval
  2. we return a reset function allowing us to restart the timer at any time

_x000D_
_x000D_
import { useEffect, useRef, useCallback } from 'react';_x000D_
_x000D_
const useTimeout = (callback, delay) => {_x000D_
  // save id in a ref_x000D_
  const timeoutId = useRef('');_x000D_
_x000D_
  // save callback as a ref so we can update the timeout callback without resetting the clock_x000D_
  const savedCallback = useRef();_x000D_
  useEffect(_x000D_
    () => {_x000D_
      savedCallback.current = callback;_x000D_
    },_x000D_
    [callback],_x000D_
  );_x000D_
_x000D_
  // clear the timeout and start a new one, updating the timeoutId ref_x000D_
  const reset = useCallback(_x000D_
    () => {_x000D_
      clearTimeout(timeoutId.current);_x000D_
_x000D_
      const id = setTimeout(savedCallback.current, delay);_x000D_
      timeoutId.current = id;_x000D_
    },_x000D_
    [delay],_x000D_
  );_x000D_
_x000D_
  useEffect(_x000D_
    () => {_x000D_
      if (delay !== null) {_x000D_
        reset();_x000D_
_x000D_
        return () => clearTimeout(timeoutId.current);_x000D_
      }_x000D_
    },_x000D_
    [delay, reset],_x000D_
  );_x000D_
_x000D_
  return { reset };_x000D_
};
_x000D_
_x000D_
_x000D_

and now we need a hook which will capture previous children and use our useTimeout hook to swap in the new children after a delay

_x000D_
_x000D_
import { useState, useEffect } from 'react';_x000D_
_x000D_
const useDelayNextChildren = (children, delay) => {_x000D_
  const [finalChildren, setFinalChildren] = useState(children);_x000D_
_x000D_
  const { reset } = useTimeout(() => {_x000D_
    setFinalChildren(children);_x000D_
  }, delay);_x000D_
_x000D_
  useEffect(_x000D_
    () => {_x000D_
      reset();_x000D_
    },_x000D_
    [reset, children],_x000D_
  );_x000D_
_x000D_
  return finalChildren || children || null;_x000D_
};
_x000D_
_x000D_
_x000D_

Note that the useTimeout callback will always have the latest children, so even if we attempt to render multiple different new children within the delay time, we'll always get the latest children once the timeout finally completes.

Now in your case, we want to also delay the initial render, so we make this change:

_x000D_
_x000D_
const useDelayNextChildren = (children, delay) => {_x000D_
  const [finalChildren, setFinalChildren] = useState(null); // initial state set to null_x000D_
_x000D_
  // ... stays the same_x000D_
_x000D_
  return finalChildren || null;  // remove children from return_x000D_
};
_x000D_
_x000D_
_x000D_

and using the above hook, your entire child component becomes

_x000D_
_x000D_
import React, { memo } from 'react';_x000D_
import { useDelayNextChildren } from 'hooks';_x000D_
_x000D_
const Child = ({ delay }) => useDelayNextChildren(_x000D_
  <div>_x000D_
    ... Child JSX goes here_x000D_
    ... etc_x000D_
  </div>_x000D_
  , delay_x000D_
);_x000D_
_x000D_
export default memo(Child);
_x000D_
_x000D_
_x000D_

or if you prefer: ( dont say i havent given you enough code ;) )

_x000D_
_x000D_
const Child = ({ delay }) => {_x000D_
  const render = <div>... Child JSX goes here ... etc</div>;_x000D_
_x000D_
  return useDelayNextChildren(render, delay);_x000D_
};
_x000D_
_x000D_
_x000D_

which will work exactly the same in the Parent render function as in the accepted answer

...

except the delay will be the same on every subsequent render too,

AND we used hooks, so that stateful logic is reusable across any component

...

...

use hooks. :D

How can I change cols of textarea in twitter-bootstrap?

I don't know if this is the correct way however I did this:

<div class="control-group">
  <label class="control-label" for="id1">Label:</label>
  <div class="controls">
    <textarea id="id1" class="textareawidth" rows="10" name="anyname">value</textarea>
  </div>
</div>

and put this in my bootstrapcustom.css file:

@media (min-width: 768px) {
    .textareawidth {
        width:500px;
    }
}
@media (max-width: 767px) {
    .textareawidth {

    }
}

This way it resizes based on the viewport. Seems to line everything up nicely on a big browser and on a small mobile device.

Confused about __str__ on list in Python

Python has two different ways to convert an object to a string: str() and repr(). Printing an object uses str(); printing a list containing an object uses str() for the list itself, but the implementation of list.__str__() calls repr() for the individual items.

So you should also overwrite __repr__(). A simple

__repr__ = __str__

at the end of the class body will do the trick.

How to view the list of compile errors in IntelliJ?

I think this comes closest to what you wish:

(From IntelliJ IDEA Q&A for Eclipse Users):

enter image description here

The above can be combined with a recently introduced option in Compiler settings to get a view very similar to that of Eclipse.

Things to do:

  1. Switch to 'Problems' view in the Project pane:

    enter image description here

  2. Enable the setting to compile the project automatically :

    enter image description here

  3. Finally, look at the Problems view:

    enter image description here

Here is a comparison of what the same project (with a compilation error) looks like in Intellij IDEA 13.xx and Eclipse Kepler:

enter image description here

enter image description here

Relevant Links: The maven project shown above : https://github.com/ajorpheus/CompileTimeErrors
FAQ For 'Eclipse Mode' / 'Automatically Compile' a project : http://devnet.jetbrains.com/docs/DOC-1122

How do I use PHP to get the current year?

If you are using the Carbon PHP API extension for DateTime, you can achieve it easy:

<?php echo Carbon::now()->year; ?>

How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

You missed the second statement: 1) NOT LIKE A, AND 2) NOT LIKE B

SELECT word FROM table WHERE word NOT LIKE '%a%' AND word NOT LIKE '%b%'

How to parse XML using shellscript?

There's also xmlstarlet (which is available for Windows as well).

http://xmlstar.sourceforge.net/doc/xmlstarlet.txt

POST request not allowed - 405 Not Allowed - nginx, even with headers included

This configuration to your nginx.conf should help you.

https://gist.github.com/baskaran-md/e46cc25ccfac83f153bb

server {
    listen       80;
    server_name  localhost;

    location / {
        root   html;
        index  index.html index.htm;
    }

    error_page  404     /404.html;
    error_page  403     /403.html;

    # To allow POST on static pages
    error_page  405     =200 $uri;

    # ...
}

Difference between SurfaceView and View?

updated 05/09/2014

OK. We have official document now. It talked all I have mentioned, in a better way.


Read more detailed here.

Yes, the main difference is surfaceView can be updated on the background thread. However, there are more you might care.

  • surfaceView has dedicate surface buffer while all the view shares one surface buffer that is allocated by ViewRoot. In another word, surfaceView cost more resources.

  • surfaceView cannot be hardware accelerated (as of JB4.2) while 95% operations on normal View are HW accelerated using openGL ES.

  • More work should be done to create your customized surfaceView. You need to listener to the surfaceCreated/Destroy Event, create an render thread, more importantly, synchronized the render thread and main thread. However, to customize the View, all you need to do is override onDraw method.

  • The timing to update is different. Normal view update mechanism is constraint or controlled by the framework:You call view.invalidate in the UI thread or view.postInvalid in other thread to indicate to the framework that the view should be updated. However, the view won't be updated immediately but wait until next VSYNC event arrived. The easy approach to understand VSYNC is to consider it is as a timer that fire up every 16ms for a 60fps screen. In Android, all the normal view update (and display actually but I won't talk it today), is synchronized with VSYNC to achieve better smoothness. Now,back to the surfaceView, you can render it anytime as you wish. However, I can hardly tell if it is an advantage, since the display is also synchronized with VSYNC, as stated previously.

Getting "conflicting types for function" in C, why?

A C Function-Declaration Backgrounder

In C, function declarations don't work like they do in other languages: The C compiler itself doesn't search backward and forward in the file to find the function's declaration from the place you call it, and it doesn't scan the file multiple times to figure out the relationships either: The compiler only scans forward in the file exactly once, from top to bottom. Connecting function calls to function declarations is part of the linker's job, and is only done after the file is compiled down to raw assembly instructions.

This means that as the compiler scans forward through the file, the very first time the compiler encounters the name of a function, one of two things have to be the case: It either is seeing the function declaration itself, in which case the compiler knows exactly what the function is and what types it takes as arguments and what types it returns — or it's a call to the function, and the compiler has to guess how the function will eventually be declared.

(There's a third option, where the name is used in a function prototype, but we'll ignore that for now, since if you're seeing this problem in the first place, you're probably not using prototypes.)

History Lesson

In the earliest days of C, the fact that the compiler had to guess types wasn't really an issue: All of the types were more-or-less the same — pretty much everything was either an int or a pointer, and they were the same size. (In fact, in B, the language that preceded C, there were no types at all; everything was just an int or pointer and its type was determined solely by how you used it!) So the compiler could safely guess the behavior of any function just based on the number of parameters that were passed: If you passed two parameters, the compiler would push two things onto the call stack, and presumably the callee would have two arguments declared, and that would all line up. If you passed only one parameter but the function expected two, it would still sort-of work, and the second argument would just be ignored/garbage. If you passed three parameters and the function expected two, it would also still sort-of work, and the third parameter would be ignored and stomped on by the function's local variables. (Some old C code still expects these mismatched-argument rules will work, too.)

But having the compiler let you pass anything to anything isn't really a good way to design a programming language. It worked well in the early days because the early C programmers were mostly wizards, and they knew not to pass the wrong type to functions, and even if they did get the types wrong, there were always tools like lint that could do deeper double-checking of your C code and warn you about such things.

Fast-forward to today, and we're not quite in the same boat. C has grown up, and a lot of people are programming in it who aren't wizards, and to accommodate them (and to accommodate everyone else who regularly used lint anyway), the compilers have taken on many of the abilities that were previously part of lint — especially the part where they check your code to ensure it's type-safe. Early C compilers would let you write int foo = "hello"; and it would just blithely assign the pointer to the integer, and it was up to you to make sure you weren't doing anything stupid. Modern C compilers complain loudly when you get your types wrong, and that's a good thing.

Type Conflicts

So what's all this got to do with the mysterious conflicting-type error on the line of the function declaration? As I said above, C compilers still have to either know or guess what a name means the first time they see that name as they scan forward through the file: They can know what it means it if it's an actual function declaration itself (or a function "prototype," more on that shortly), but if it's just a call to the function, they have to guess. And, sadly, the guess is often wrong.

When the compiler saw your call to do_something(), it looked at how it was invoked, and it concluded that do_something() would eventually be declared like this:

int do_something(char arg1[], char arg2[])
{
    ...
}

Why did it conclude that? Because that's how you called it! (Some C compilers may conclude that it was int do_something(int arg1, int arg2), or simply int do_something(...), both of which are even farther from what you want, but the important point is that regardless of how the compiler guesses the types, it guesses them differently from what your actual function uses.)

Later on, as the compiler scans forward in the file, it sees your actual declaration of char *do_something(char *, char *). That function declaration isn't even close to the declaration that the compiler guessed, which means that the line where the compiler compiled the call was compiled wrong, and the program is just not going to work. So it rightly prints an error telling you that your code isn't going to work as written.

You might be wondering, "Why does it assume I'm returning an int?" Well, it assumes that type because there's no information to the contrary: printf() can take in any type in its variable arguments, so without a better answer, int is as good a guess as any. (Many early C compilers always assumed int for every unspecified type, and assumed you meant ... for the arguments for every function declared f() — not void — which is why many modern code standards recommend always putting void in for the arguments if there really aren't supposed to be any.)

The Fix

There are two common fixes for the function-declaration error.

The first solution, which is recommended by many other answers here, is to put a prototype in the source code above the place where the function is first called. A prototype looks just like the function's declaration, but it has a semicolon where the body should be:

char *do_something(char *dest, const char *src);

By putting the prototype first, the compiler then knows what the function will eventually look like, so it doesn't have to guess. By convention, programmers often put prototypes at the top of the file, just under the #include statements, to ensure that they'll always be defined before any potential usages of them.

The other solution, which also shows up in some real-world code, is to simply reorder your functions so that the function declarations are always before anything that calls them! You could move the entire char *do_something(char *dest, const char *src) { ... } function above the first call to it, and the compiler then would know exactly what the function looks like and wouldn't have to guess.

In practice, most people use function prototypes, because you can also take function prototypes and move them into header (.h) files so that code in other .c files can call those functions. But either solution works, and many codebases use both.

C99 and C11

It is useful to note that the rules are slightly different in the newer versions of the C standard. In the earlier versions (C89 and K&R), the compiler really would guess the types at function-call time (and K&R-era compilers often wouldn't even warn you if they were wrong). C99 and C11 both require that the function declaration/prototype must precede the first call, and it's an error if it doesn't. But many modern C compilers — mainly for backward compatibility with earlier code — will only warn about a missing prototype and not consider it an error.

How can I select all elements without a given class in jQuery?

if (!$(row).hasClass("changed")) {
    // do your stuff
}

How to use setInterval and clearInterval?

I used angular with electron,

In my case, setInterval returns a Nodejs Timer object. which when I called clearInterval(timerobject) it did not work.

I had to get the id first and call to clearInterval

clearInterval(timerobject._id)

I have struggled many hours with this. hope this helps.

Mercurial: how to amend the last commit?

I'm tuning into what krtek has written. More specifically solution 1:

Assumptions:

  • you've committed one (!) changeset but have not pushed it yet
  • you want to modify this changeset (e.g. add, remove or change files and/or the commit message)

Solution:

  • use hg rollback to undo the last commit
  • commit again with the new changes in place

The rollback really undoes the last operation. Its way of working is quite simple: normal operations in HG will only append to files; this includes a commit. Mercurial keeps track of the file lengths of the last transaction and can therefore completely undo one step by truncating the files back to their old lengths.

How to set conditional breakpoints in Visual Studio?

  1. Set a breakpoint as usual
  2. Right click on the breakpoint and select Condition
  3. You'll see a dialog that says "Breakpoint Condition"
  4. Put a condition in the field e.g. "i==5"

The breakpoint will only get hit when i is 5.

document.createElement("script") synchronously

This looks like a decent overview of dynamic script loading: http://unixpapa.com/js/dyna.html

How to read the post request parameters using JavaScript

One option is to set a cookie in PHP.

For example: a cookie named invalid with the value of $invalid expiring in 1 day:

setcookie('invalid', $invalid, time() + 60 * 60 * 24);

Then read it back out in JS (using the JS Cookie plugin):

var invalid = Cookies.get('invalid');

if(invalid !== undefined) {
    Cookies.remove('invalid');
}

You can now access the value from the invalid variable in JavaScript.

Generating Unique Random Numbers in Java

I have easy solution for this problem, With this we can easily generate n number of unique random numbers, Its just logic anyone can use it in any language.

for(int i=0;i<4;i++)
        {
            rn[i]= GenerateRandomNumber();
            for (int j=0;j<i;j++)
            {
                if (rn[i] == rn[j])
                {
                    i--;
                }
            }
        }

Need a query that returns every field that contains a specified letter

You can use a cursor and temp table approach so you aren't doing full table scan each time. What this would be doing is populating the temp table with all of your keywords, and then with each string in the @letters XML, it would remove any records from the temp table. At the end, you only have records in your temp table that have each of your desired strings in it.

declare @letters xml

SET @letters = '&lt;letters&gt;
            &lt;letter&gt;a&lt;/letter&gt;
            &lt;letter&gt;b&lt;/letter&gt;
        &lt;/letters&gt;'

-- SELECTING LETTERS FROM THE XML
SELECT Letters.l.value('.', 'nvarchar(50)') AS letter
FROM @letters.nodes('/letters/letter') AS Letters(l)

-- CREATE A TEMP TABLE WE CAN DELETE FROM IF A RECORD DOESN'T HAVE THE LETTER
CREATE TABLE #TempResults (keywordID int not null, keyWord nvarchar(50) not null)
INSERT INTO #TempResults (keywordID, keyWord)
SELECT employeeID, firstName FROM Employee

-- CREATE A CURSOR, SO WE CAN LOOP THROUGH OUR LETTERS AND REMOVE KEYWORDS THAT DON'T MATCH
DECLARE Cursor_Letters CURSOR READ_ONLY
FOR 
    SELECT Letters.l.value('.', 'nvarchar(50)') AS letter
    FROM @letters.nodes('/letters/letter') AS Letters(l)

DECLARE @letter varchar(50)
OPEN Cursor_Letters

FETCH NEXT FROM Cursor_Letters INTO @letter
WHILE (@@fetch_status <> -1)
BEGIN
    IF (@@fetch_status <> -2)
    BEGIN
        DELETE FROM #TempResults 
        WHERE  keywordID NOT IN 
        (SELECT keywordID FROM #TempResults WHERE keyWord LIKE '%' + @letter + '%')
    END
    FETCH NEXT FROM Cursor_Letters INTO @letter
END

CLOSE Cursor_Letters
DEALLOCATE Cursor_Letters

SELECT * FROM #TempResults

DROP Table #TempResults
GO

Where's the IE7/8/9/10-emulator in IE11 dev tools?

I posted an answer to this already when someone else asked the same question (see How to bring back "Browser mode" in IE11?).

Read my answer there for a fuller explaination, but in short:

  • They removed it deliberately, because compat mode is not actually really very good for testing compatibility.

  • If you really want to test for compatibility with any given version of IE, you need to test in a real copy of that IE version. MS provide free VMs on http://modern.ie/ for you to use for this purpose.

  • The only way to get compat mode in IE11 is to set the X-UA-Compatible header. When you have this and the site defaults to compat mode, you will be able to set the mode in dev tools, but only between edge or the specified compat mode; other modes will still not be available.

go get results in 'terminal prompts disabled' error for github private repo

If you configure your gitconfig with this option, you will later have a problem cloning other repos of GitHub

git config --global --add url. "[email protected]". Instead, "https://github.com/"

Instead, I recommend that you use this option

echo "export GIT_TERMINAL_PROMPT=1" >> ~/.bashrc || ~/.zshrc

and do not forget to generate an access token from your private repository. When prompted to enter your password, just paste the access token. Happy clone :)

Adding a module (Specifically pymorph) to Spyder (Python IDE)

You can add the Standard Installation location to the PYTHONPATH manager. This way you don't need to add a specific path for each module. Only to update module names.

On Unix this location is usually:

/usr/local/lib/pythonX.Y/site-packages

On Windows:

C:\PythonXY\Lib\site-packages

See the modules install Documentation.

How can I recover a lost commit in Git?

Try this, This will show all commits recorded in git for a period of time

git reflog

Find the commit you want with

git log HEAD@{3}

or

git log -p HEAD@{3}    

Then check it out if it's the right one:

git checkout HEAD@{3}

This will create a detached head for that commit. Add and commit any changes if needed

git status 
git add
git commit -m "temp_work" 

Now if want to restore commit back to a branch lets say master you will need to name this branch switch to master then merge to master.

git branch temp
git checkout master
git merge temp

Here's also a link specifically for reflog on a Git tutorial site: Atlassian Git Tutorial

Make Adobe fonts work with CSS3 @font-face in IE9

You can solve it by following code

@font-face {
  font-family: 'Font-Name';
  src: url('../fonts/Font-Name.ttf');
  src: url('../fonts/Font-Name.eot?#iefix') format('embedded-opentype');
}

Viewing localhost website from mobile device

Use Conveyor by Keyoti (extensión de Visual Studio). Extension visual studio

UITableView example for Swift

//    UITableViewCell set Identify "Cell"
//    UITableView Name is  tableReport

UIViewController,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    @IBOutlet weak var tableReport: UITableView!  

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return 5;
        }

        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableReport.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
            cell.textLabel?.text = "Report Name"
            return cell;
        }
}

Resize jqGrid when browser is resized?

Hello Stack overflow enthusiasts. I enjoyed most of answers, and I even up-voted a couple, but none of them worked for me on IE 8 for some strange reason... I did however run into these links... This guy wrote a library that seems to work. Include it in your projects in adittion to jquery UI, throw in the name of your table and the div.

http://stevenharman.net/blog/archive/2009/08/21/creating-a-fluid-jquery-jqgrid.aspx

http://code.google.com/p/codeincubator/source/browse/#svn%2FSamples%2Fsteveharman%2FjQuery%2Fjquery.jqgrid.fluid%253Fstate%253Dclosed

Get string character by index - Java

You're pretty stuck with substring(), given your requirements. The standard way would be charAt(), but you said you won't accept a char data type.

How to make the Facebook Like Box responsive?

The answer you're looking for as of June, 2013 can be found here:

https://gist.github.com/dineshcooper/2111366

It's accomplished using jQuery to rewrite the inner HTML of the parent container that holds the facebook widget.

Hope this helps!

Finding first and last index of some value in a list in Python

If you are searching for the index of the last occurrence of myvalue in mylist:

len(mylist) - mylist[::-1].index(myvalue) - 1

How to test if list element exists?

Here is a performance comparison of the proposed methods in other answers.

> foo <- sapply(letters, function(x){runif(5)}, simplify = FALSE)
> microbenchmark::microbenchmark('k' %in% names(foo), 
                                 is.null(foo[['k']]), 
                                 exists('k', where = foo))
Unit: nanoseconds
                     expr  min   lq    mean median   uq   max neval cld
      "k" %in% names(foo)  467  933 1064.31    934  934 10730   100  a 
      is.null(foo[["k"]])    0    0  168.50      1  467  3266   100  a 
 exists("k", where = foo) 6532 6998 7940.78   7232 7465 56917   100   b

If you are planing to use the list as a fast dictionary accessed many times, then the is.null approach might be the only viable option. I assume it is O(1), while the %in% approach is O(n)?

Powershell send-mailmessage - email to multiple recipients

to send a .NET / C# powershell eMail use such a structure:

for best behaviour create a class with a method like this

 using (PowerShell PowerShellInstance = PowerShell.Create())
            {
                PowerShellInstance.AddCommand("Send-MailMessage")
                                  .AddParameter("SMTPServer", "smtp.xxx.com")
                                  .AddParameter("From", "[email protected]")
                                  .AddParameter("Subject", "xxx Notification")
                                  .AddParameter("Body", body_msg)
                                  .AddParameter("BodyAsHtml")
                                  .AddParameter("To", recipients);

                // invoke execution on the pipeline (ignore output) --> nothing will be displayed
                PowerShellInstance.Invoke();
            }              

Whereby these instance is called in a function like:

        public void sendEMailPowerShell(string body_msg, string[] recipients)

Never forget to use a string array for the recepients, which can be look like this:

string[] reportRecipient = { 
                        "xxx <[email protected]>",
                        "xxx <[email protected]>"
                        };

body_msg

this message can be overgiven as parameter to the method itself, HTML coding enabled!!

recipients

never forget to use a string array in case of multiple recipients, otherwise only the last address in the string will be used!!!

calling the function can look like this:

        mail reportMail = new mail(); //instantiate from class
        reportMail.sendEMailPowerShell(reportMessage, reportRecipient); //msg + email addresses

ThumbUp

How to convert milliseconds into a readable date?

Using the library Datejs you can accomplish this quite elegantly, with its toString format specifiers: http://jsfiddle.net/TeRnM/1/.

var date = new Date(1324339200000);

date.toString("MMM dd"); // "Dec 20"

Query Mongodb on month, day, year... of a datetime

You cannot straightly query mongodb collections by date components like day or month. But its possible by using the special $where javascript expression

db.mydatabase.mycollection.find({$where : function() { return this.date.getMonth() == 11} })

or simply

db.mydatabase.mycollection.find({$where : 'return this.date.getMonth() == 11'})

(But i prefer the first one)

Check out the below shell commands to get the parts of date

>date = ISODate("2011-09-25T10:12:34Z")
> date.getYear()
111
> date.getMonth()
8
> date.getdate()
25

EDIT:

Use $where only if you have no other choice. It comes with the performance problems. Please check out the below comments by @kamaradclimber and @dcrosta. I will let this post open so the other folks get the facts about it.

and check out the link $where Clauses and Functions in Queries for more info

How to change Named Range Scope

This still needs more refining however works with all simple references, without killing existing local names.

Type GlobalNamesToLocalNames_Type
   Name As String
   Sheet As String
   Ref As String
End Type

Sub GlobalNamesToLocalNames(Optional Void As Variant)
   Dim List() As GlobalNamesToLocalNames_Type
   Dim Count As Long
   Dim Name As Name
   Dim Dat() As String
   Dim X As Long

   ' count the size
   For Each Name In ActiveWorkbook.Names
      Count = Count + 1
   Next
   ReDim List(Count - 1)
   Count = 0

   ' Collecect all name data
   For Each Name In ActiveWorkbook.Names
      With List(Count)
         ' Pick up only the name
         If InStr(Name.Name, "!") > 0 Then
            Dat = Split(Name.Name, "!")
            .Name = Dat(1)
         Else
            .Name = Name.Name
         End If
         ' pick up the sheet and refer
         Dat = Split(Name.RefersTo, "!")
         .Sheet = Mid(Dat(0), 2)
         .Ref = Dat(1)
         ' make local sheet name
         .Name = .Sheet & "!" & .Name
      End With
      Count = Count + 1
   Next

   ' Delete all names
   For Each Name In ActiveWorkbook.Names
      Name.Delete
   Next

   'rebuild all the names
   For X = 0 To Count - 1
      With List(X)
         If Left(.Ref, 1) <> "#" Then
            ActiveWorkbook.Names.Add Name:=.Name, RefersToLocal:="=" & .Sheet & "!" & .Ref
         End If
      End With
   Next
End Sub

Put spacing between divs in a horizontal row?

Another idea: Compensate for your margin on the opposite side of the div.

For the side with the spacing you are looking to achieve as an example: 10px, and for the opposing side, compensate with a -10px. It works for me. This likely won't work in all scenarios, but depending on your layout and spacing of other elements, it might work great.

Set the value of a variable with the result of a command in a Windows batch file

One needs to be somewhat careful, since the Windows batch command:

for /f "delims=" %%a in ('command') do @set theValue=%%a

does not have the same semantics as the Unix shell statement:

theValue=`command`

Consider the case where the command fails, causing an error.

In the Unix shell version, the assignment to "theValue" still occurs, any previous value being replaced with an empty value.

In the Windows batch version, it's the "for" command which handles the error, and the "do" clause is never reached -- so any previous value of "theValue" will be retained.

To get more Unix-like semantics in Windows batch script, you must ensure that assignment takes place:

set theValue=
for /f "delims=" %%a in ('command') do @set theValue=%%a

Failing to clear the variable's value when converting a Unix script to Windows batch can be a cause of subtle errors.

How do I find Waldo with Mathematica?

My guess at a "bulletproof way to do this" (think CIA finding Waldo in any satellite image any time, not just a single image without competing elements, like striped shirts)... I would train a Boltzmann machine on many images of Waldo - all variations of him sitting, standing, occluded, etc.; shirt, hat, camera, and all the works. You don't need a large corpus of Waldos (maybe 3-5 will be enough), but the more the better.

This will assign clouds of probabilities to various elements occurring in whatever the correct arrangement, and then establish (via segmentation) what an average object size is, fragment the source image into cells of objects which most resemble individual people (considering possible occlusions and pose changes), but since Waldo pictures usually include a LOT of people at about the same scale, this should be a very easy task, then feed these segments of the pre-trained Boltzmann machine. It will give you probability of each one being Waldo. Take one with the highest probability.

This is how OCR, ZIP code readers, and strokeless handwriting recognition work today. Basically you know the answer is there, you know more or less what it should look like, and everything else may have common elements, but is definitely "not it", so you don't bother with the "not it"s, you just look of the likelihood of "it" among all possible "it"s you've seen before" (in ZIP codes for example, you'd train BM for just 1s, just 2s, just 3s, etc., then feed each digit to each machine, and pick one that has most confidence). This works a lot better than a single neural network learning features of all numbers.

A free tool to check C/C++ source code against a set of coding standards?

Try nsiqcppstyle. It's a Python based coding style checker for C/C++. It's easy to extend to add your own rules.

Check cell for a specific letter or set of letters

You can use RegExMatch:

=IF(RegExMatch(A1;"Bla");"YES";"NO")

File path issues in R using Windows ("Hex digits in character string" error)

Solution

Try this: x <- read.csv("C:/Users/surfcat/Desktop/2006_dissimilarity.csv", header=TRUE)

Explanation

R is not able to understand normal windows paths correctly because the "\" has special meaning - it is used as escape character to give following characters special meaning (\n for newline, \t for tab, \r for carriage return, ..., have a look here ).

Because R does not know the sequence \U it complains. Just replace the "\" with "/" or use an additional "\" to escape the "\" from its special meaning and everything works smooth.

Alternative

On windows, I think the best thing to do to improve your workflow with windows specific paths in R is to use e.g. AutoHotkey which allows for custom hotkeys:

  • define a Hotkey, e.g. Cntr-Shift-V
  • assigns it an procedure that replaces backslashes within your Clipboard with slaches ...
  • when ever you want to copy paste a path into R you can use Cntr-Shift-V instead of Cntr-V
  • Et-voila

AutoHotkey Code Snippet (link to homepage)

^+v::
StringReplace, clipboard, clipboard, \, /, All 
SendInput, %clipboard% 

MySQL select one column DISTINCT, with corresponding other columns

SELECT DISTINCT (column1), column2
FROM table1
GROUP BY column1

Add Marker function with Google Maps API

THis is other method
You can also use setCenter method with add new marker

check below code

$('#my_map').gmap3({
      action: 'setCenter',
      map:{
         options:{
          zoom: 10
         }
      },
      marker:{
         values:
          [
            {latLng:[position.coords.latitude, position.coords.longitude], data:"Netherlands !"}
          ]
      }
   });

Refresh Page and Keep Scroll Position

document.location.reload() stores the position, see in the docs.

Add additional true parameter to force reload, but without restoring the position.

document.location.reload(true)

MDN docs:

The forcedReload flag changes how some browsers handle the user's scroll position. Usually reload() restores the scroll position afterward, but forced mode can scroll back to the top of the page, as if window.scrollY === 0.

Check if bash variable equals 0

You can try this:

: ${depth?"Error Message"} ## when your depth variable is not even declared or is unset.

NOTE: Here it's just ? after depth.

or

: ${depth:?"Error Message"} ## when your depth variable is declared but is null like: "depth=". 

NOTE: Here it's :? after depth.

Here if the variable depth is found null it will print the error message and then exit.

jQuery - simple input validation - "empty" and "not empty"

Actually there is a simpler way to do this, just:

if ($("#input").is(':empty')) {
console.log('empty');
} else {
console.log('not empty');
}

src: https://www.geeksforgeeks.org/how-to-check-an-html-element-is-empty-using-jquery/

How to bind inverse boolean properties in WPF?

Following @Paul's answer, I wrote the following in the ViewModel:

public bool ShowAtView { get; set; }
public bool InvShowAtView { get { return !ShowAtView; } }

I hope having a snippet here will help someone, probably newbie as I am.
And if there's a mistake, please let me know!

BTW, I also agree with @heltonbiker comment - it's definitely the correct approach only if you don't have to use it more than 3 times...

How to figure out the SMTP server host?

Quick example:

On Ubuntu, if you are interested, for instance, in Gmail then open the Terminal and type:

nslookup -q=mx gmail.com

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

Someone should mark Johannes Weiß's comment as the answer to this question. That is exactly why xml documents can't just be loaded in a DOM Document class.

http://en.wikipedia.org/wiki/Byte_order_mark

How to communicate between iframe and the parent site?

You can also use

postMessage(message, '*');

Sniff HTTP packets for GET and POST requests from an application

Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet, then expand the Hypertext Transfer Protocol field. The POST data will be right there on top.

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

I'm not sure if I am correct, but from the request header that you post:

Request headers

Accept: Application/json

Origin: chrome-extension://hgmloofddffdnphfgcellkdfbfbjeloo

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36

Content-Type: application/x-www-form-urlencoded

Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8

it seems like you didn't config your request body to JSON type.

Converting a string to int in Groovy

Several ways to do it, this one's my favorite:

def number = '123' as int

How to connect wireless network adapter to VMWare workstation?

Here is a simple way to connect with your WIFI -

  1. Click on Edit from the menu section
  2. Virtual Network Editor
  3. Change Settings
  4. Add Network
  5. Select a network name
  6. Select Bridged option in VMnet Information -> Bridge to : Automatic
  7. Apply

That's it. You might be asked password to connect. Add it and you would be able to connect to the network.

Kind Regards,

Rahul Tilloo

CSS3 Rotate Animation

if you want to flip image you can use it.

.image{
    width: 100%;
    -webkit-animation:spin 3s linear infinite;
    -moz-animation:spin 3s linear infinite;
    animation:spin 3s linear infinite;
}
@-moz-keyframes spin { 50% { -moz-transform: rotateY(90deg); } }
@-webkit-keyframes spin { 50% { -webkit-transform: rotateY(90deg); } }
@keyframes spin { 50% { -webkit-transform: rotateY(90deg); transform:rotateY(90deg); } }

How to auto-generate a C# class file from a JSON string

If you install Web Essentials into Visual studio you can go to Edit => Past special => paste JSON as class.

That is probably the easiest there is.

Web Essentials: http://vswebessentials.com/

Set margins in a LinearLayout programmatically

/*
 * invalid margin
 */
private void invalidMarginBottom() {
    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) frameLayoutContent.getLayoutParams();
    lp.setMargins(0, 0, 0, 0);
    frameLayoutContent.setLayoutParams(lp);
}

you should be ware of the type of the view's viewGroup.In the code above, for example,I want to change the frameLayout's margin,and the frameLayout's view group is a RelativeLayout,so you need to covert to (RelativeLayout.LayoutParams)

Can I invoke an instance method on a Ruby module without including it?

Another way to do it if you "own" the module is to use module_function.

module UsefulThings
  def a
    puts "aaay"
  end
  module_function :a

  def b
    puts "beee"
  end
end

def test
  UsefulThings.a
  UsefulThings.b # Fails!  Not a module method
end

test

Int division: Why is the result of 1/3 == 0?

public static void main(String[] args) {
    double g = 1 / 3;
    System.out.printf("%.2f", g);
}

Since both 1 and 3 are ints the result not rounded but it's truncated. So you ignore fractions and take only wholes.

To avoid this have at least one of your numbers 1 or 3 as a decimal form 1.0 and/or 3.0.

Git: Permission denied (publickey) fatal - Could not read from remote repository. while cloning Git repository

Useful thread and I don't bring much new to the table. The step I took is also part of the description Maxime helpfully points to but some may overlook it. The section is Adding your SSH key to the ssh-agent.

I had already generated my ssh-key but after a reboot I was unable to clone one of my own repositories.

I had to start the ssh-agent and add the private key to this agent in order to clone.

eval $(ssh-agent -s)
ssh-add ~/.ssh/id_rsa

How to access Session variables and set them in javascript?

Assign value to a hidden field in the code-behind file. Access this value in your javascript like a normal HTML control.

Adding a new entry to the PATH variable in ZSH

You can append to your PATH in a minimal fashion. No need for parentheses unless you're appending more than one element. It also usually doesn't need quotes. So the simple, short way to append is:

path+=/some/new/bin/dir

This lower-case syntax is using path as an array, yet also affects its upper-case partner equivalent, PATH (to which it is "bound" via typeset).

(Notice that no : is needed/wanted as a separator.)

Common interactive usage

Then the common pattern for testing a new script/executable becomes:

path+=$PWD/.
# or
path+=$PWD/bin

Common config usage

You can sprinkle path settings around your .zshrc (as above) and it will naturally lead to the earlier listed settings taking precedence (though you may occasionally still want to use the "prepend" form path=(/some/new/bin/dir $path)).

Related tidbits

Treating path this way (as an array) also means: no need to do a rehash to get the newly pathed commands to be found.

Also take a look at vared path as a dynamic way to edit path (and other things).

You may only be interested in path for this question, but since we're talking about exports and arrays, note that arrays generally cannot be exported.

You can even prevent PATH from taking on duplicate entries (refer to this and this):

typeset -U path

Validate form field only on submit or user input

You can use angularjs form state form.$submitted. Initially form.$submitted value will be false and will became true after successful form submit.

How to Convert Int to Unsigned Byte and Back

A byte is always signed in Java. You may get its unsigned value by binary-anding it with 0xFF, though:

int i = 234;
byte b = (byte) i;
System.out.println(b); // -22
int i2 = b & 0xFF;
System.out.println(i2); // 234

Tools to search for strings inside files without indexing

If you don't want to install Non-Microsoft tools, please download STRINGS.EXE from Microsoft Sysinternals and make a procedure like this one:

@echo off
if '%1' == '' goto NOPARAM
if '%2' == '' goto NOPARAM
if not exist %1 goto NOFOLDER

echo ------------------------------------------
echo - %1 : folder
echo - %2 : string to be searched in the folder
echo - PLEASE WAIT FOR THE RESULTS ...
strings -s %1\* | findstr /i %2 > grep.txt
notepad.exe grep.txt

goto END

:NOPARAM rem - input command not correct
echo ====================================
echo Usage of GREP.CMD:
echo   Grep "SearchFolder" SearchString
echo Please specify all parameters
echo ====================================
goto END

:NOFOLDER
echo Folder %1 does not exist
goto END

:END rem - exit

Python decorators in classes

import functools


class Example:

    def wrapper(func):
        @functools.wraps(func)
        def wrap(self, *args, **kwargs):
            print("inside wrap")
            return func(self, *args, **kwargs)
        return wrap

    @wrapper
    def method(self):
        print("METHOD")

    wrapper = staticmethod(wrapper)


e = Example()
e.method()

"Prevent saving changes that require the table to be re-created" negative effects

Reference - Turning off this option can help you avoid re-creating a table, it can also lead to changes being lost. For example, suppose that you enable the Change Tracking feature in SQL Server 2008 to track changes to the table. When you perform an operation that causes the table to be re-created, you receive the error message that is mentioned in the "Symptoms" section. However, if you turn off this option, the existing change tracking information is deleted when the table is re-created. Therefore,Microsoft recommend that you do not work around this problem by turning off the option.

Browse files and subfolders in Python

I had a similar thing to work on, and this is how I did it.

import os

rootdir = os.getcwd()

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        #print os.path.join(subdir, file)
        filepath = subdir + os.sep + file

        if filepath.endswith(".html"):
            print (filepath)

Hope this helps.