Programs & Examples On #Valign

Valign is an HTML attribute used to designate a vertical alignment of an entity.

Create a simple Login page using eclipse and mysql

use this code it is working

// index.jsp or login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>

</body>
</html>

// authentication servlet class

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class auth extends HttpServlet {
        private static final long serialVersionUID = 1L;

        public auth() {
            super();
        }
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

        }

        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            String username = request.getParameter("username");
            String pass = request.getParameter("pass");

            String sql = "select * from reg where username='" + username + "'";
            Connection conn = null;

            try {
                conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
                        "root", "");
                Statement s = conn.createStatement();

                java.sql.ResultSet rs = s.executeQuery(sql);
                String un = null;
                String pw = null;
                String name = null;

            /* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */   

            PrintWriter prwr1 = response.getWriter();               
            if(!rs.isBeforeFirst()){
                prwr1.write("<h1> No Such User in Database<h1>");
            } else {

/* Conditions to be executed after at least one row is returned by query execution */ 
                while (rs.next()) {
                    un = rs.getString("username");
                    pw = rs.getString("password");
                    name = rs.getString("name");
                }

                PrintWriter pww = response.getWriter();

                if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
                                // use this or create request dispatcher 
                    response.setContentType("text/html");
                    pww.write("<h1>Welcome, " + name + "</h1>");
                } else {
                    pww.write("wrong username or password\n");
                }
              }

            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }

Htaccess: add/remove trailing slash from URL

To complement Jon Lin's answer, here is a no-trailing-slash technique that also works if the website is located in a directory (like example.org/blog/):

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [R=301,L]


For the sake of completeness, here is an alternative emphasizing that REQUEST_URI starts with a slash (at least in .htaccess files):

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} /(.*)/$
RewriteRule ^ /%1 [R=301,L] <-- added slash here too, don't forget it

Just don't use %{REQUEST_URI} (.*)/$. Because in the root directory REQUEST_URI equals /, the leading slash, and it would be misinterpreted as a trailing slash.


If you are interested in more reading:

(update: this technique is now implemented in Laravel 5.5)

html tables & inline styles

Forget float, margin and html 3/5. The mail is very obsolete. You need do all with table. One line = one table. You need margin or padding ? Do another column.

Codepen

Example : i need one line with 1 One Picture of 40*40 2 One margin of 10 px 3 One text of 400px

I start my line :

<table style=" background-repeat:no-repeat; width:450px;margin:0;" cellpadding="0" cellspacing="0" border="0">
   <tr style="height:40px; width:450px; margin:0;">
     <td style="height:40px; width:40px; margin:0;">
        <img src="" style="width=40px;height40;margin:0;display:block"
     </td>
     <td style="height:40px; width:10px; margin:0;">        
     </td>
     <td style="height:40px; width:400px; margin:0;">
     <p style=" margin:0;"> my text   </p>
     </td>
   </tr>
</table>

HTTP Status 500 - org.apache.jasper.JasperException: java.lang.NullPointerException

In Tomcat a .java and .class file will be created for every jsp files with in the application and the same can be found from the path below, Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\index_jsp.java

In your case the jsp name is error.jsp so the path should be something like below Apache-Tomcat\work\Catalina\localhost\'ApplicationName'\org\apache\jsp\error_jsp.java in line no 124 you are trying to access a null object which results in null pointer exception.

How to change font-size of a tag using inline css?

Strange it doesn't change, as inline styles are most specific, if style sheet has !important declared, it wont over ride, try this and see

<span style="font-size: 11px !important; color: #aaaaaa;">Hello</span>

Uncaught ReferenceError: $ is not defined

This can also happen, if there is network issue. Which means, that even though the " jquery scripts " are in place, and are included prior to usage, since the jquery-scripts are not accessible, at the time of loading the page, hence the definitions to the "$" are treated as "undefined references".

FOR TEST/DEBUG PURPOSES :: You can try to access the "jquery-script" url on browser. If it is accessible, your page, should load properly, else it will show the said error (or other script relevant errors). Example - http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js should be accessible, on the browser (or browser context stances).

I had similar problem, in which I was able to load the html-page (using scripts) in my windows-host-browser, but was not able to load in vm-ubuntu. Solving the network issue, got the issue resolved.

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

While Python 3 deals in Unicode, the Windows console or POSIX tty that you're running inside does not. So, whenever you print, or otherwise send Unicode strings to stdout, and it's attached to a console/tty, Python has to encode it.

The error message indirectly tells you what character set Python was trying to use:

  File "C:\Python32\lib\encodings\cp850.py", line 19, in encode

This means the charset is cp850.

You can test or yourself that this charset doesn't have the appropriate character just by doing '\u2013'.encode('cp850'). Or you can look up cp850 online (e.g., at Wikipedia).

It's possible that Python is guessing wrong, and your console is really set for, say UTF-8. (In that case, just manually set sys.stdout.encoding='utf-8'.) It's also possible that you intended your console to be set for UTF-8 but did something wrong. (In that case, you probably want to follow up at superuser.com.)

But if nothing is wrong, you just can't print that character. You will have to manually encode it with one of the non-strict error-handlers. For example:

>>> '\u2013'.encode('cp850')
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 0: character maps to <undefined>
>>> '\u2013'.encode('cp850', errors='replace')
b'?'

So, how do you print a string that won't print on your console?

You can replace every print function with something like this:

>>> print(r['body'].encode('cp850', errors='replace').decode('cp850'))
?

… but that's going to get pretty tedious pretty fast.

The simple thing to do is to just set the error handler on sys.stdout:

>>> sys.stdout.errors = 'replace'
>>> print(r['body'])
?

For printing to a file, things are pretty much the same, except that you don't have to set f.errors after the fact, you can set it at construction time. Instead of this:

with open('path', 'w', encoding='cp850') as f:

Do this:

with open('path', 'w', encoding='cp850', errors='replace') as f:

… Or, of course, if you can use UTF-8 files, just do that, as Mark Ransom's answer shows:

with open('path', 'w', encoding='utf-8') as f:

jQuery append and remove dynamic table row

$(document).ready(function () {
    Addrow();
})
$("#add").click(function () {
    Addrow();
})
rowcount = $("#tbuser td").closest.length;
function Addrow() {
    rowcount++;
    debugger
    var markup = "<tr><td></td><td><input type='text' name='stuclass' id='stuclass'/></td><td><select name='Institute' class='Institute_" + rowcount + "'></select></td><td><input type='text' name='obtmark' id='obtmark'/></td><td><input type='text' name='totalmark' id='totalmark'/></td><td><input type='text' name='per' id='per'/></td><td><button type='button' id='delete' onclick='deleterow(this);'>DELETE</button></td></tr>";
    $(".tbuser tbody").append(markup);

    $.ajax({
        type: 'GET',
        url: '@Url.Action("bindinst", "Home")',
        data: '',
        dataType: "json",
        success: function (data) {
            debugger;
            $(".Institute_" + rowcount).empty();
            $(".Institute_" + rowcount).append('<option Value="">--Select--</option>');
            $.each(data, function (i, result) {

                $(".Institute_" + rowcount).append('<option Value="' + result.Value + '">' + result.Text + '</option>');
            });
        },

    });


}

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

TypeError: $.browser is undefined

$().live(function(){}); and jQuery.browser is undefined in jquery 1.9.0 - $.browser was deprecated in jquery update

sounds like you are using a different version of jquery 1.9 in godaddy so either change your code or include the migrate plugin http://code.jquery.com/jquery-migrate-1.0.0.js

If Radio Button is selected, perform validation on Checkboxes

function validateDays() {
    if (document.getElementById("option1").checked == true) {
        alert("You have selected Option 1");
    }
    else if (document.getElementById("option2").checked == true) {
        alert("You have selected Option 2");
    }
    else if (document.getElementById("option3").checked == true) {
        alert("You have selected Option 3");
    }
    else {
        // DO NOTHING
        }
    }

HTML Table cell background image alignment

This works in IE9 (Compatibility View and Normal Mode), Firefox 17, and Chrome 23:

<table>
    <tr>
        <td style="background-image:url(untitled.png); background-position:right 0px; background-repeat:no-repeat;">
            Hello World
        </td>
    </tr>
</table>

Table Height 100% inside Div element

to set height of table to its container I must do:

1) set "position: absolute"

2) remove redundant contents of cells (!)

Read a HTML file into a string variable in memory

Use File.ReadAllText(path_to_file) to read

How to change background color of cell in table using java script

<table border="1" cellspacing="0" cellpadding= "20">
    <tr>
    <td id="id1" ></td>
    </tr>
</table>
<script>
    document.getElementById('id1').style.backgroundColor='#003F87';
</script>

Put id for cell and then change background of the cell.

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

Please make sure you have downloaded the sqldump fully, this problem is very common when we try to import half/incomplete downloaded sqldump. Please check size of your sqldump file.

td widths, not working?

You can try the "table-layout: fixed;" to your table

table-layout: fixed;
width: 150px;

150px or your desired width.

Reference: https://css-tricks.com/fixing-tables-long-strings/

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

use session_start() at the top of the page.

for more details please read the link session_start

Attribute 'nowrap' is considered outdated. A newer construct is recommended. What is it?

If HTML and use bootstrap they have a helper class.

<span class="text-nowrap">1-866-566-7233</span>

JavaScript get element by name

You want this:

function validate() {
    var acc = document.getElementsByName('acc')[0].value;
    var pass = document.getElementsByName('pass')[0].value;

    alert (acc);
}

javascript - pass selected value from popup window to parent window input box

My approach: use a div instead of a pop-up window.

See it working in the jsfiddle here: http://jsfiddle.net/6RE7w/2/

Or save the code below as test.html and try it locally.

<html>

<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript">
        $(window).load(function(){
            $('.btnChoice').on('click', function(){
                $('#divChoices').show()
                thefield = $(this).prev()
                $('.btnselect').on('click', function(){
                    theselected = $(this).prev()
                    thefield.val( theselected.val() )
                    $('#divChoices').hide()
                })
            })

            $('#divChoices').css({
                'border':'2px solid red',
                'position':'fixed',
                'top':'100',
                'left':'200',
                'display':'none'
            })
        });
    </script>
</head>

<body>

<div class="divform">
    <input type="checkbox" name="kvi1" id="kvi1" value="1">
    <label>Field 1: </label>
    <input size="10" type="number" id="sku1" name="sku1">
    <button id="choice1" class="btnChoice">?</button>
    <br>
    <input type="checkbox" name="kvi2" id="kvi2" value="2">
    <label>Field 2: </label>
    <input size="10"  type="number" id="sku2" name="sku2">
    <button id="choice2" class="btnChoice">?</button>
</div>

<div id="divChoices">
    Select something: 
    <br>
    <input size="10" type="number" id="ch1" name="ch1" value="11">
    <button id="btnsel1" class="btnselect">Select</button>
    <label for="ch1">bla bla bla</label>
    <br>
    <input size="10" type="number" id="ch2" name="ch2" value="22">
    <button id="btnsel2" class="btnselect">Select</button>
    <label for="ch2">ble ble ble</label>
</div>

</body>

</html>

clean and simple.

Positioning <div> element at center of screen

Alternative solution that doesn't use position absolute:
I see a lot of position absolute answers. I couldn't use position absolute without breaking something else. So for those that couldn't as well, here is what I did:
https://stackoverflow.com/a/58622840/6546317 (posted in response to another question).

The solution only focuses on vertically centering because my children elements were already horizontally centered but same could be applied if you couldn't horizontally center them in another way.

jquery - How to determine if a div changes its height or any css attribute?

Please don't use techniques described in other answers here. They are either not working with css3 animations size changes, floating layout changes or changes that don't come from jQuery land. You can use a resize-detector, a event-based approach, that doesn't waste your CPU time.

https://github.com/marcj/css-element-queries

It contains a ResizeSensor class you can use for that purpose.

new ResizeSensor(jQuery('#mainContent'), function(){ 
    console.log('main content dimension changed');
});

Disclaimer: I wrote this library

How do I remove link underlining in my HTML email?

I used a combination of not showing links in google, adding links for mso (outlook) and the shy tag, to keep the looks and feels for my company. Some code may be redundant (for my company the looks where more important then the be clickable part. (it felt like a jigsaw, as every change brakes something else)

<td style="color:rgb(69, 54, 53)">
<!--[if gte mso 9]>
<a href="http://www.immothekerfinotheker.be" style="text-decoration:none;">
<span style="text-decoration:none;">
<![endif]-->
www&shy;.&shy;immothekerfinotheker&shy;.&shy;be
<!--[if gte mso 9]>
</a>
</span>
<![endif]-->
</td>

Hope this helps someone

How to find tags with only certain attributes - BeautifulSoup

find using an attribute in any tag

<th class="team" data-sort="team">Team</th>    
soup.find_all(attrs={"class": "team"}) 

<th data-sort="team">Team</th>  
soup.find_all(attrs={"data-sort": "team"}) 
 

Uncaught ReferenceError: jQuery is not defined

jQuery needs to be the first script you import. The first script on your page

<script type="text/javascript" src="/test/wp-content/themes/child/script/jquery.jcarousel.min.js"></script>

appears to be a jQuery plugin, which is likely generating an error since jQuery hasn't been loaded on the page yet.

JQuery, select first row of table

jQuery is not necessary, you can use only javascript.

<table id="table">
  <tr>...</tr>
  <tr>...</tr>
  <tr>...</tr>
   ......
  <tr>...</tr>
</table>

The table object has a collection of all rows.

var myTable = document.getElementById('table');
var rows =  myTable.rows;
var firstRow = rows[0];

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

/* cellpadding */
th, td { padding: 5px; }

/* cellspacing */
table { border-collapse: separate; border-spacing: 5px; } /* cellspacing="5" */
table { border-collapse: collapse; border-spacing: 0; }   /* cellspacing="0" */

/* valign */
th, td { vertical-align: top; }

/* align (center) */
table { margin: 0 auto; }

Formatting html email for Outlook

To be able to give you specific help, you's have to explain what particular parts specifically "get messed up", or perhaps offer a screenshot. It also helps to know what version of Outlook you encounter the problem in.

Either way, CampaignMonitor.com's CSS guide has often helped me out debugging email client inconsistencies.

From that guide you can see several things just won't work well or at all in Outlook, here are some highlights of the more important ones:

  • Various types of more sophisticated selectors, e.g. E:first-child, E:hover, E > F (Child combinator), E + F (Adjacent sibling combinator), E ~ F (General sibling combinator). This unfortunately means resorting to workarounds like inline styles.
  • Some font properties, e.g. white-space won't work.
  • The background-image property won't work.
  • There are several issues with the Box Model properties, most importantly height, width, and the max- versions are either not usable or have bugs for certain elements.
  • Positioning and Display issues (e.g. display, floats and position are all out).

In short: combining CSS and Outlook can be a pain. Be prepared to use many ugly workarounds.

PS. In your specific case, there are two minor issues in your html that may cause you odd behavior. There's "align=top" where you probably meant to use vertical-align. Also: cell-padding for tds doesn't exist.

Get the Id of current table row with Jquery

You can use .closest() to get up to the current <tr> parent, like this:

$('input[type=button]' ).click(function() {
   var bid = this.id; // button ID 
   var trid = $(this).closest('tr').attr('id'); // table row ID 
 });

top align in html table?

<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
    <TR style="vertical-align:top">
        <TD>
            <!-- The log text-box -->
            <div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
                Log:
            </div>
        </TD>
        <TD>
            <!-- The 2nd column -->
        </TD>
        <TD>
            <!-- The 3rd column -->
        </TD>
    </TR>
</TABLE>

What are .tpl files? PHP, web design

You have to learn Smarty syntax. That's a template system.

Set colspan dynamically with jquery

I've also found that if you had display:none, then programmatically changed it to be visible, you might also have to set

$tr.css({display:'table-row'});

rather than display:inline or display:block otherwise the cell might only show as taking up 1 cell, no matter how large you have the colspan set to.

HTML CSS How to stop a table cell from expanding

This could be useful. Like another answer it is just CSS.

td {
    word-wrap: break-word;
}

Button inside of anchor link works in Firefox but not in Internet Explorer?

This is very simple actually, no javascript required.

First, put the anchor inside the button

<button><a href="#">Bar</a></button>

Then, turn the anchor tag into a block type element and fill its container

button a {
  display:block;
  height:100%;
  width:100%;
}

Finally, add other styles as necessary.

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
   t
1 20
2  0
3 30

Angular2 - Input Field To Accept Only Numbers

Just use HTML5, input type=”number”

Unable to start the mysql server in ubuntu

I think this is because you are using client software and not the server.

  • mysql is client
  • mysqld is the server

Try: sudo service mysqld start

To check that service is running use: ps -ef | grep mysql | grep -v grep.

Uninstalling:

sudo apt-get purge mysql-server
sudo apt-get autoremove
sudo apt-get autoclean

Re-Installing:

sudo apt-get update
sudo apt-get install mysql-server

Backup entire folder before doing this:

sudo rm /etc/apt/apt.conf.d/50unattended-upgrades*
sudo apt-get update
sudo apt-get upgrade

Newline in markdown table?

When you're exporting to HTML, using <br> works. However, if you're using pandoc to export to LaTeX/PDF as well, you should use grid tables:

+---------------+---------------+--------------------+
| Fruit         | Price         | Advantages         |
+===============+===============+====================+
| Bananas       | first line\   | first line\        |
|               | next line     | next line          |
+---------------+---------------+--------------------+
| Bananas       | first line\   | first line\        |
|               | next line     | next line          |
+---------------+---------------+--------------------+

How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

Use try_files and named location block ('@apachesite'). This will remove unnecessary regex match and if block. More efficient.

location / {
    root /path/to/root/of/static/files;
    try_files $uri $uri/ @apachesite;

    expires max;
    access_log off;
}

location @apachesite {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

Update: The assumption of this config is that there doesn't exist any php script under /path/to/root/of/static/files. This is common in most modern php frameworks. In case your legacy php projects have both php scripts and static files mixed in the same folder, you may have to whitelist all of the file types you want nginx to serve.

jQuery Change event on an <input> element - any way to retain previous value?

Some points.

Use $.data Instead of $.fn.data

// regular
$(elem).data(key,value);
// 10x faster
$.data(elem,key,value);

Then, You can get the previous value through the event object, without complicating your life:

    $('#myInputElement').change(function(event){
        var defaultValue = event.target.defaultValue;
        var newValue = event.target.value;
    });

Be warned that defaultValue is NOT the last set value. It's the value the field was initialized with. But you can use $.data to keep track of the "oldValue"

I recomend you always declare the "event" object in your event handler functions and inspect them with firebug (console.log(event)) or something. You will find a lot of useful things there that will save you from creating/accessing jquery objects (which are great, but if you can be faster...)

How to force a hover state with jQuery?

I think the best solution I have come across is on this stackoverflow. This short jQuery code allows all your hover effects to show on click or touch..
No need to add anything within the function.

$('body').on('touchstart', function() {});

Hope this helps.

Can I hide the HTML5 number input’s spin box?

This is more better answer i would like to suggest on mouse over and without mouse over

input[type='number'] {
  appearance: textfield;
}
input[type='number']::-webkit-inner-spin-button,
input[type='number']::-webkit-outer-spin-button,
input[type='number']:hover::-webkit-inner-spin-button, 
input[type='number']:hover::-webkit-outer-spin-button {
-webkit-appearance: none; 
 margin: 0; }

How to count occurrences of a column value efficiently in SQL?

Here's another solution. this one uses very simple syntax. The first example of the accepted solution did not work on older versions of Microsoft SQL (i.e 2000)

SELECT age, count(*)
FROM Students 
GROUP by age
ORDER BY age

Get index of a row of a pandas dataframe as an integer

The nature of wanting to include the row where A == 5 and all rows upto but not including the row where A == 8 means we will end up using iloc (loc includes both ends of slice).

In order to get the index labels we use idxmax. This will return the first position of the maximum value. I run this on a boolean series where A == 5 (then when A == 8) which returns the index value of when A == 5 first happens (same thing for A == 8).

Then I use searchsorted to find the ordinal position of where the index label (that I found above) occurs. This is what I use in iloc.

i5, i8 = df.index.searchsorted([df.A.eq(5).idxmax(), df.A.eq(8).idxmax()])
df.iloc[i5:i8]

enter image description here


numpy

you can further enhance this by using the underlying numpy objects the analogous numpy functions. I wrapped it up into a handy function.

def find_between(df, col, v1, v2):
    vals = df[col].values
    mx1, mx2 = (vals == v1).argmax(), (vals == v2).argmax()
    idx = df.index.values
    i1, i2 = idx.searchsorted([mx1, mx2])
    return df.iloc[i1:i2]

find_between(df, 'A', 5, 8)

enter image description here


timing
enter image description here

text-align:center won't work with form <label> tag (?)

This is because label is an inline element, and is therefore only as big as the text it contains.

The possible is to display your label as a block element like this:

#formItem label {
    display: block;
    text-align: center;
    line-height: 150%;
    font-size: .85em;
}

However, if you want to use the label on the same line with other elements, you either need to set display: inline-block; and give it an explicit width (which doesn't work on most browsers), or you need to wrap it inside a div and do the alignment in the div.

Change the Theme in Jupyter Notebook?

You Can Follow These Steps.

  1. pip install jupyterthemes or pip install --upgrade jupyterthemes to upgrade to latest version of theme.
  2. after that to list all the themes you have :jt -l
  3. after that jt-t <themename>for example jt -t solarizedl

Adding elements to a collection during iteration

Forget about iterators, they don't work for adding, only for removing. My answer applies to lists only, so don't punish me for not solving the problem for collections. Stick to the basics:

    List<ZeObj> myList = new ArrayList<ZeObj>();
    // populate the list with whatever
            ........
    int noItems = myList.size();
    for (int i = 0; i < noItems; i++) {
        ZeObj currItem = myList.get(i);
        // when you want to add, simply add the new item at last and
        // increment the stop condition
        if (currItem.asksForMore()) {
            myList.add(new ZeObj());
            noItems++;
        }
    }

Multiple controllers with AngularJS in single page app

You could also have embed all of your template views into your main html file. For Example:

<body ng-app="testApp">
  <h1>Test App</h1>
  <div ng-view></div>
  <script type = "text/ng-template" id = "index.html">
    <h1>Index Page</h1>
    <p>{{message}}</p>
  </script>
  <script type = "text/ng-template" id = "home.html">
    <h1>Home Page</h1>
    <p>{{message}}</p>
  </script>
</body>

This way if each template requires a different controller then you can still use the angular-router. See this plunk for a working example http://plnkr.co/edit/9X0fT0Q9MlXtHVVQLhgr?p=preview

This way once the application is sent from the server to your client, it is completely self contained assuming that it doesn't need to make any data requests, etc.

ORA-01652: unable to extend temp segment by 128 in tablespace SYSTEM: How to extend?

Each tablespace has one or more datafiles that it uses to store data.

The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.

To find out if the actual limit is 32gb, run the following:

select value from v$parameter where name = 'db_block_size';

Compare the result you get with the first column below, and that will indicate what your max datafile size is.

I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).

Block Sz   Max Datafile Sz (Gb)   Max DB Sz (Tb)

--------   --------------------   --------------

   2,048                  8,192          524,264

   4,096                 16,384        1,048,528

   8,192                 32,768        2,097,056

  16,384                 65,536        4,194,112

  32,768                131,072        8,388,224

You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):

select bytes/1024/1024 as mb_size,
       maxbytes/1024/1024 as maxsize_set,
       x.*
from   dba_data_files x

MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).

If your datafile has a low max size or autoextend is not on you could simply run:

alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;

However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:

alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;

C# elegant way to check if a property's property is null

var result = nullableproperty ?? defaultvalue;

The ?? (null-coalescing operator) means if the first argument is null, return the second one instead.

How do I debug jquery AJAX calls?

you can use success function, once see this jquery.ajax settings

 $('#ChangePermission').click(function(){
    $.ajax({
        url: 'change_permission.php',
        type: 'POST',
        data: {
        'user': document.GetElementById("user").value,
        'perm': document.GetElementById("perm").value
        }
       success:function(result)//we got the response
       {
        //you can try to write alert(result) to see what is the response,this result variable will contains what you prints in the php page
       }
    })
})

we can also have error() function

hope this helps you

Set System.Drawing.Color values

You could do:

Color c = Color.FromArgb(red, green, blue); //red, green and blue are integer variables containing red, green and blue components

[] and {} vs list() and dict(), which is better?

In the case of difference between [] and list(), there is a pitfall that I haven't seen anyone else point out. If you use a dictionary as a member of the list, the two will give entirely different results:

In [1]: foo_dict = {"1":"foo", "2":"bar"}

In [2]: [foo_dict]
Out [2]: [{'1': 'foo', '2': 'bar'}]

In [3]: list(foo_dict)
Out [3]: ['1', '2'] 

Wpf control size to content?

I had a problem like this whereby I had specified the width of my Window, but had the height set to Auto. The child DockPanel had it's VerticalAlignment set to Top and the Window had it's VerticalContentAlignment set to Top, yet the Window would still be much taller than the contents.

Using Snoop, I discovered that the ContentPresenter within the Window (part of the Window, not something I had put there) has it's VerticalAlignment set to Stretch and can't be changed without retemplating the entire Window!

After a lot of frustration, I discovered the SizeToContent property - you can use this to specify whether you want the Window to size vertically, horizontally or both, according to the size of the contents - everything is sizing nicely now, I just can't believe it took me so long to find that property!

close fancy box from function from within open 'fancybox'

Add $.fancybox.close() to where ever you want it to be trigged, in a function or a callback, end of an ajax call!

Woohoo.

PHP: merge two arrays while keeping keys instead of reindexing?

Hello year 2010 question.

The OP.'s requirement is preserve keys (keep keys) and not overlap (I think overwrite). In some case such as numeric keys it is possible but if string keys it seems to be not possible.

If you use array_merge() the numeric keys will always re-index or renumbered.
If you use array_replace(), array_replace_recursive() it will be overlap or overwrite from the right to the left. The value with the same key on first array will be replaced with second array.
If you use $array1 + $array2 as the comment was mentioned, if the keys are same then it will keep the value from first array but drop the second array.

Custom function.

Here is my function that I just wrote to work on the same requirements. You are free to use for any purpose.

/**
 * Array custom merge. Preserve indexed array key (numbers) but overwrite string key (same as PHP's `array_merge()` function).
 * 
 * If the another array key is string, it will be overwrite the first array.<br>
 * If the another array key is integer, it will be add to first array depend on duplicated key or not. 
 * If it is not duplicate key with the first, the key will be preserve and add to the first array.
 * If it is duplicated then it will be re-index the number append to the first array.
 *
 * @param array $array1 The first array is main array.
 * @param array ...$arrays The another arrays to merge with the first.
 * @return array Return merged array.
 */
function arrayCustomMerge(array $array1, array ...$arrays): array
{
    foreach ($arrays as $additionalArray) {
        foreach ($additionalArray as $key => $item) {
            if (is_string($key)) {
                // if associative array.
                // item on the right will always overwrite on the left.
                $array1[$key] = $item;
            } elseif (is_int($key) && !array_key_exists($key, $array1)) {
                // if key is number. this should be indexed array.
                // and if array 1 is not already has this key.
                // add this array with the key preserved to array 1.
                $array1[$key] = $item;
            } else {
                // if anything else...
                // get all keys from array 1 (numbers only).
                $array1Keys = array_filter(array_keys($array1), 'is_int');
                // next key index = get max array key number + 1.
                $nextKeyIndex = (intval(max($array1Keys)) + 1);
                unset($array1Keys);
                // set array with the next key index.
                $array1[$nextKeyIndex] = $item;
                unset($nextKeyIndex);
            }
        }// endforeach; $additionalArray
        unset($item, $key);
    }// endforeach;
    unset($additionalArray);

    return $array1;
}// arrayCustomMerge

Testing.

<?php
$array1 = [
    'cat', 
    'bear', 
    'fruitred' => 'apple',
    3.1 => 'dog',
    null => 'null',
];
$array2 = [
    1 => 'polar bear',
    20 => 'monkey',
    'fruitred' => 'strawberry',
    'fruityellow' => 'banana',
    null => 'another null',
];

// require `arrayCustomMerge()` function here.

function printDebug($message)
{
    echo '<pre>';
    print_r($message);
    echo '</pre>' . PHP_EOL;
}

echo 'array1: <br>';
printDebug($array1);
echo 'array2: <br>';
printDebug($array2);


echo PHP_EOL . '<hr>' . PHP_EOL . PHP_EOL;


echo 'arrayCustomMerge:<br>';
$merged = arrayCustomMerge($array1, $array2);
printDebug($merged);


assert($merged[0] == 'cat', 'array key 0 should be \'cat\'');
assert($merged[1] == 'bear', 'array key 1 should be \'bear\'');
assert($merged['fruitred'] == 'strawberry', 'array key \'fruitred\' should be \'strawberry\'');
assert($merged[3] == 'dog', 'array key 3 should be \'dog\'');
assert(array_search('another null', $merged) !== false, '\'another null\' should be merged.');
assert(array_search('polar bear', $merged) !== false, '\'polar bear\' should be merged.');
assert($merged[20] == 'monkey', 'array key 20 should be \'monkey\'');
assert($merged['fruityellow'] == 'banana', 'array key \'fruityellow\' should be \'banana\'');
The results.
array1:

Array
(
    [0] => cat
    [1] => bear
    [fruitred] => apple
    [3] => dog
    [] => null
)

array2:

Array
(
    [1] => polar bear
    [20] => monkey
    [fruitred] => strawberry
    [fruityellow] => banana
    [] => another null
)

---
arrayCustomMerge:

Array
(
    [0] => cat
    [1] => bear
    [fruitred] => strawberry
    [3] => dog
    [] => another null
    [4] => polar bear
    [20] => monkey
    [fruityellow] => banana
)

How to execute function in SQL Server 2008

It looks like there's something else called Afisho_rankimin in your DB so the function is not being created. Try calling your function something else. E.g.

CREATE FUNCTION dbo.Afisho_rankimin1(@emri_rest int)
RETURNS int
AS
   BEGIN
       Declare @rankimi int
       Select @rankimi=dbo.RESTORANTET.Rankimi
       From RESTORANTET
       Where  dbo.RESTORANTET.ID_Rest=@emri_rest
       RETURN @rankimi
  END
  GO

Note that you need to call this only once, not every time you call the function. After that try calling

SELECT dbo.Afisho_rankimin1(5) AS Rankimi 

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

If you use a fullscreen transparent activity, there is no need to specify the orientation lock on the activity. It will take the configuration settings of the parent activity. So if the parent activity has in the manifest:

android:screenOrientation="portrait"

your translucent activity will have the same orientation lock: portrait.

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

Try executing your command with sudo(Super User), this worked for me :)
Run : $ sudo your_command
After than enter the super user password. Thats All..

Password masking console application

Mine ignores control characters and handles line wrapping:

public static string ReadLineMasked(char mask = '*')
{
    var sb = new StringBuilder();
    ConsoleKeyInfo keyInfo;
    while ((keyInfo = Console.ReadKey(true)).Key != ConsoleKey.Enter)
    {
        if (!char.IsControl(keyInfo.KeyChar))
        {
            sb.Append(keyInfo.KeyChar);
            Console.Write(mask);
        }
        else if (keyInfo.Key == ConsoleKey.Backspace && sb.Length > 0)
        {
            sb.Remove(sb.Length - 1, 1);

            if (Console.CursorLeft == 0)
            {
                Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
                Console.Write(' ');
                Console.SetCursorPosition(Console.BufferWidth - 1, Console.CursorTop - 1);
            }
            else Console.Write("\b \b");
        }
    }
    Console.WriteLine();
    return sb.ToString();
}

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

How to convert string to long

You can also try following,

long lg;
String Str = "1333073704000"
lg = Long.parseLong(Str);

How can we run a test method with multiple parameters in MSTest?

It is unfortunately not supported in older versions of MSTest. Apparently there is an extensibility model and you can implement it yourself. Another option would be to use data-driven tests.

My personal opinion would be to just stick with NUnit though...

As of Visual Studio 2012, update 1, MSTest has a similar feature. See McAden's answer.

INNER JOIN ON vs WHERE clause

I have two points for the implicit join (The second example):

  1. Tell the database what you want, not what it should do.
  2. You can write all tables in a clear list that is not cluttered by join conditions. Then you can much easier read what tables are all mentioned. The conditions come all in the WHERE part, where they are also all lined up one below the other. Using the JOIN keyword mixes up tables and conditions.

How to sort multidimensional array by column?

sorted(list, key=lambda x: x[1])

Note: this works on time variable too.

How do I access my webcam in Python?

OpenCV has support for getting data from a webcam, and it comes with Python wrappers by default, you also need to install numpy for the OpenCV Python extension (called cv2) to work. As of 2019, you can install both of these libraries with pip: pip install numpy pip install opencv-python

More information on using OpenCV with Python.

An example copied from Displaying webcam feed using opencv and python:

import cv2

cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)

if vc.isOpened(): # try to get the first frame
    rval, frame = vc.read()
else:
    rval = False

while rval:
    cv2.imshow("preview", frame)
    rval, frame = vc.read()
    key = cv2.waitKey(20)
    if key == 27: # exit on ESC
        break
cv2.destroyWindow("preview")

Youtube API Limitations

Version 3 of the YouTube Data API has concrete quota numbers listed in the Google API Console where you register for your API Key. You can use 10,000 units per day. Projects that had enabled the YouTube Data API before April 20, 2016, have a default quota of 50M/day.

You can read about what a unit is here: https://developers.google.com/youtube/v3/getting-started#quota

  • A simple read operation that only retrieves the ID of each returned resource has a cost of approximately 1 unit.
  • A write operation has a cost of approximately 50 units.
  • A video upload has a cost of approximately 1600 units.

If you hit the limits, Google will stop returning results until your quota is reset. You can apply for more than 1M requests per day, but you will have to pay for those extra requests.

Also, you can read about why Google has deferred support to StackOverflow on their YouTube blog here: https://youtube-eng.googleblog.com/2012/09/the-youtube-api-on-stack-overflow_14.html

There are a number of active members on the YouTube Developer Relations team here including Jeff Posnick, Jarek Wilkiewicz, and Ibrahim Ulukaya who all have knowledge of Youtube internals...

UPDATE: Increased the quota numbers to reflect current limits on December 10, 2013.

UPDATE: Decreased the quota numbers from 50M to 1M per day to reflect current limits on May 13, 2016.

UPDATE: Decreased the quota numbers from 1M to 10K per day as of January 11, 2019.

ImportError: No module named PyQt4

I solved the same problem for my own program by installing python3-pyqt4.

I'm not using Python 3 but it still helped.

Exit a while loop in VBS/VBA

Use Do...Loop with Until keyword

num=0
Do Until //certain_condition_to_break_loop
 num=num+1
Loop

This loop will continue to execute, Until the condition becomes true

While...Wend is the old syntax and does not provide feature to break loop! Prefer do while loops

How to deal with "data of class uneval" error from ggplot2?

This could also occur if you refer to a variable in the data.frame that doesn't exist. For example, recently I forgot to tell ddply to summarize by one of my variables that I used in geom_line to specify line color. Then, ggplot didn't know where to find the variable I hadn't created in the summary table, and I got this error.

Convert Difference between 2 times into Milliseconds?

    public static Int64 GetDifferencesBetweenTwoDate(DateTime newDate, DateTime oldDate, string type)
    {
        var span = newDate - oldDate;
        switch (type)
        {
            case "tt": return (int)span.Ticks;
            case "ms": return (int)span.TotalMilliseconds;
            case "ss": return (int)span.TotalSeconds;
            case "mm": return (int)span.TotalMinutes;
            case "hh": return (int)span.TotalHours;
            case "dd": return (int)span.TotalDays;
        }
        return 0;
    }

How to INNER JOIN 3 tables using CodeIgniter

$this->db->select('*');    
$this->db->from('table1');
$this->db->join('table2', 'table1.id = table2.id', 'inner');
$this->db->join('table3', 'table1.id = table3.id', 'inner');
$this->db->where("table1", $id );
$query = $this->db->get();

Where you can specify which id should be viewed or select in specific table. You can also select which join portion either left, right, outer, inner, left outer, and right outer on the third parameter of join method.

what is this value means 1.845E-07 in excel?

1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.

1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.

C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.

You can specify a format string if you don't want to use the e-notation.

Skip to next iteration in loop vba

Just do nothing once the criteria is met, otherwise do the processing you require and the For loop will go to the next item.

For i = 2 To 24
    Level = Cells(i, 4)
    Return = Cells(i, 5)

    If Return = 0 And Level = 0 Then
        'Do nothing
    Else
        'Do something
    End If
Next i

Or change the clause so it only processes if the conditions are met:

For i = 2 To 24
    Level = Cells(i, 4)
    Return = Cells(i, 5)

    If Return <> 0 Or Level <> 0 Then
        'Do something
    End If
Next i

What is the difference between an abstract function and a virtual function?

If a class derives from this abstract class, it is then forced to override the abstract member. This is different from the virtual modifier, which specifies that the member may optionally be overridden.

Understanding passport serialize deserialize

  1. Where does user.id go after passport.serializeUser has been called?

The user id (you provide as the second argument of the done function) is saved in the session and is later used to retrieve the whole object via the deserializeUser function.

serializeUser determines which data of the user object should be stored in the session. The result of the serializeUser method is attached to the session as req.session.passport.user = {}. Here for instance, it would be (as we provide the user id as the key) req.session.passport.user = {id: 'xyz'}

  1. We are calling passport.deserializeUser right after it where does it fit in the workflow?

The first argument of deserializeUser corresponds to the key of the user object that was given to the done function (see 1.). So your whole object is retrieved with help of that key. That key here is the user id (key can be any key of the user object i.e. name,email etc). In deserializeUser that key is matched with the in memory array / database or any data resource.

The fetched object is attached to the request object as req.user

Visual Flow

passport.serializeUser(function(user, done) {
    done(null, user.id);
});              ¦
                 ¦ 
                 ¦
                 +--------------------? saved to session
                                   ¦    req.session.passport.user = {id: '..'}
                                   ¦
                                   ?           
passport.deserializeUser(function(id, done) {
                   +---------------+
                   ¦
                   ? 
    User.findById(id, function(err, user) {
        done(err, user);
    });            +--------------? user object attaches to the request as req.user   
});

Please enter a commit message to explain why this merge is necessary, especially if it merges an updated upstream into a topic branch

Since your local repository is few commits ahead, git tries to merge your remote to your local repo. This can be handled via merge, but in your case, perhaps you are looking for rebase, i.e. add your commit to the top. You can do this with

git rebase or git pull --rebase

Here is a good article explaining the difference between git pull & git pull --rebase.

https://www.derekgourlay.com/blog/git-when-to-merge-vs-when-to-rebase/

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

jQuery post() with serialize and extra data

You can use serializeArray [docs] and add the additional data:

var data = $('#myForm').serializeArray();
data.push({name: 'wordlist', value: wordlist});

$.post("page.php", data);

Plot different DataFrames in the same figure

If you a running Jupyter/Ipython notebook and having problems using;

ax = df1.plot()

df2.plot(ax=ax)

Run the command inside of the same cell!! It wont, for some reason, work when they are separated into sequential cells. For me at least.

How can I dynamically add a directive in AngularJS?

The accepted answer by Josh David Miller works great if you are trying to dynamically add a directive that uses an inline template. However if your directive takes advantage of templateUrl his answer will not work. Here is what worked for me:

.directive('helperModal', [, "$compile", "$timeout", function ($compile, $timeout) {
    return {
        restrict: 'E',
        replace: true,
        scope: {}, 
        templateUrl: "app/views/modal.html",
        link: function (scope, element, attrs) {
            scope.modalTitle = attrs.modaltitle;
            scope.modalContentDirective = attrs.modalcontentdirective;
        },
        controller: function ($scope, $element, $attrs) {
            if ($attrs.modalcontentdirective != undefined && $attrs.modalcontentdirective != '') {
                var el = $compile($attrs.modalcontentdirective)($scope);
                $timeout(function () {
                    $scope.$digest();
                    $element.find('.modal-body').append(el);
                }, 0);
            }
        }
    }
}]);

How to create a TextArea in Android

       <EditText
            android:layout_width="match_parent"
            android:layout_height="160dp"
            android:ems="10"
            android:gravity="left|top"
            android:hint="Write your comment.."
            android:inputType="textMultiLine"
            android:textSize="15sp">
            <requestFocus />
       </EditText>

Any reason not to use '+' to concatenate two strings?

According to Python docs, using str.join() will give you performance consistence across various implementations of Python. Although CPython optimizes away the quadratic behavior of s = s + t, other Python implementations may not.

CPython implementation detail: If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s = s + t or s += t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.

Sequence Types in Python docs (see the foot note [6])

get path for my .exe

System.Reflection.Assembly.GetEntryAssembly().Location;

Best way to update data with a RecyclerView adapter

DiffUtil can the best choice for updating the data in the RecyclerView Adapter which you can find in the android framework. DiffUtil is a utility class that can calculate the difference between two lists and output a list of update operations that converts the first list into the second one.

Most of the time our list changes completely and we set new list to RecyclerView Adapter. And we call notifyDataSetChanged to update adapter. NotifyDataSetChanged is costly. DiffUtil class solves that problem now. It does its job perfectly!

Form inline inside a form horizontal in twitter bootstrap?

to make it simple, just add a class="form-inline" before the input.

example:

<div class="col-md-4 form-inline"> //add the class here...
     <label>Lot Size:</label>
     <input type="text" value="" name="" class="form-control" >
 </div>

UIView touch event in controller

Updating @Crashalot's answer for Swift 3.x:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    if let touch = touches.first {
        let currentPoint = touch.location(in: self)
        // do something with your currentPoint
    }
}

Check if a value exists in ArrayList

We can use contains method to check if an item exists if we have provided the implementation of equals and hashCode else object reference will be used for equality comparison. Also in case of a list contains is O(n) operation where as it is O(1) for HashSet so better to use later. In Java 8 we can use streams also to check item based on its equality or based on a specific property.

Java 8

CurrentAccount conta5 = new CurrentAccount("João Lopes", 3135);
boolean itemExists = lista.stream().anyMatch(c -> c.equals(conta5)); //provided equals and hashcode overridden
System.out.println(itemExists); // true

String nameToMatch = "Ricardo Vitor";
boolean itemExistsBasedOnProp = lista.stream().map(CurrentAccount::getName).anyMatch(nameToMatch::equals);
System.out.println(itemExistsBasedOnProp); //true

How to save an image locally using Python whose URL address I already know?

If you don't already have the url for the image, you could scrape it with gazpacho:

from gazpacho import Soup
base_url = "http://books.toscrape.com"

soup = Soup.get(base_url)
links = [img.attrs["src"] for img in soup.find("img")]

And then download the asset with urllib as mentioned:

from pathlib import Path
from urllib.request import urlretrieve as download

directory = "images"
Path(directory).mkdir(exist_ok=True)

link = links[0]
name = link.split("/")[-1]

download(f"{base_url}/{link}", f"{directory}/{name}")

T-SQL split string

/*

Answer to T-SQL split string
Based on answers from Andy Robinson and AviG
Enhanced functionality ref: LEN function not including trailing spaces in SQL Server
This 'file' should be valid as both a markdown file and an SQL file


*/

    CREATE FUNCTION dbo.splitstring ( --CREATE OR ALTER
        @stringToSplit NVARCHAR(MAX)
    ) RETURNS @returnList TABLE ([Item] NVARCHAR (MAX))
    AS BEGIN
        DECLARE @name NVARCHAR(MAX)
        DECLARE @pos BIGINT
        SET @stringToSplit = @stringToSplit + ','             -- this should allow entries that end with a `,` to have a blank value in that "column"
        WHILE ((LEN(@stringToSplit+'_') > 1)) BEGIN           -- `+'_'` gets around LEN trimming terminal spaces. See URL referenced above
            SET @pos = COALESCE(NULLIF(CHARINDEX(',', @stringToSplit),0),LEN(@stringToSplit+'_')) -- COALESCE grabs first non-null value
            SET @name = SUBSTRING(@stringToSplit, 1, @pos-1)  --MAX size of string of type nvarchar is 4000 
            SET @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, 4000) -- With SUBSTRING fn (MS web): "If start is greater than the number of characters in the value expression, a zero-length expression is returned."
            INSERT INTO @returnList SELECT @name --additional debugging parameters below can be added
            -- + ' pos:' + CAST(@pos as nvarchar) + ' remain:''' + @stringToSplit + '''(' + CAST(LEN(@stringToSplit+'_')-1 as nvarchar) + ')'
        END
        RETURN
    END
    GO

/*

Test cases: see URL referenced as "enhanced functionality" above

SELECT *,LEN(Item+'_')-1 'L' from splitstring('a,,b')

Item | L
---  | ---
a    | 1
     | 0
b    | 1

SELECT *,LEN(Item+'_')-1 'L' from splitstring('a,,')

Item | L   
---  | ---
a    | 1
     | 0
     | 0

SELECT *,LEN(Item+'_')-1 'L' from splitstring('a,, ')

Item | L   
---  | ---
a    | 1
     | 0
     | 1

SELECT *,LEN(Item+'_')-1 'L' from splitstring('a,, c ')

Item | L   
---  | ---
a    | 1
     | 0
 c   | 3

*/

fs.writeFile in a promise, asynchronous-synchronous stuff

Finally, the latest node.js release v10.3.0 has natively supported fs promises.

const fsPromises = require('fs').promises; // or require('fs/promises') in v10.0.0
fsPromises.writeFile(ASIN + '.json', JSON.stringify(results))
  .then(() => {
    console.log('JSON saved');
  })
  .catch(er => {
    console.log(er);
  });

You can check the official documentation for more details. https://nodejs.org/api/fs.html#fs_fs_promises_api

Granting Rights on Stored Procedure to another user of Oracle

SQL> grant create any procedure to testdb;

This is a command when we want to give create privilege to "testdb" user.

How to detect a docker daemon port

If you run ps -aux | dockerd you should see the tcp endpoint it is running on.

jQuery changing style of HTML element

$('#navigation ul li').css('display', 'inline-block');

not a colon, a comma

Handling multiple IDs in jQuery

Solution:

To your secondary question

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector.

elem1.css({'display':'none'}); //will work

In the below case selector is already stored in a variable.

$(elem1,elem2,elem3).css({'display':'none'}); // will not work

What is the 'new' keyword in JavaScript?

In addition to Daniel Howard's answer, here is what new does (or at least seems to do):

function New(func) {
    var res = {};
    if (func.prototype !== null) {
        res.__proto__ = func.prototype;
    }
    var ret = func.apply(res, Array.prototype.slice.call(arguments, 1));
    if ((typeof ret === "object" || typeof ret === "function") && ret !== null) {
        return ret;
    }
    return res;
}

While

var obj = New(A, 1, 2);

is equivalent to

var obj = new A(1, 2);

How do I find out which process is locking a file using .NET?

It is very complex to invoke Win32 from C#.

You should use the tool Handle.exe.

After that your C# code have to be the following:

string fileName = @"c:\aaa.doc";//Path to locked file

Process tool = new Process();
tool.StartInfo.FileName = "handle.exe";
tool.StartInfo.Arguments = fileName+" /accepteula";
tool.StartInfo.UseShellExecute = false;
tool.StartInfo.RedirectStandardOutput = true;
tool.Start();           
tool.WaitForExit();
string outputTool = tool.StandardOutput.ReadToEnd();

string matchPattern = @"(?<=\s+pid:\s+)\b(\d+)\b(?=\s+)";
foreach(Match match in Regex.Matches(outputTool, matchPattern))
{
    Process.GetProcessById(int.Parse(match.Value)).Kill();
}

offsetTop vs. jQuery.offset().top

I think you are right by saying that people cannot click half pixels, so personally, I would use rounded jQuery offset...

Retrieve only the queried element in an object array in MongoDB collection

db.test.find( {"shapes.color": "red"}, {_id: 0})

Drawing Circle with OpenGL

I have done it using the following code,

glBegin(GL.GL_LINE_LOOP);
     for(int i =0; i <= 300; i++){
         double angle = 2 * Math.PI * i / 300;
         double x = Math.cos(angle);
         double y = Math.sin(angle);
         gl.glVertex2d(x,y);
     }
glEnd();

How to fix/convert space indentation in Sublime Text?

Recently I faced a similar problem. I was using the sublime editor. it's not an issue with the code but with the editor.

Below change in the preference settings worked for me.

Sublime Text menu -> Preferences -> Settings: Syntax-Specific:

{
    "tab_size": 4,
    "translate_tabs_to_spaces": true
}

How to get primary key of table?

MySQL has a SQL query "SHOW INDEX FROM" which returns the indexes from a table. For eg. - the following query will show all the indexes for the products table:-

SHOW INDEXES FROM products \G

It returns a table with type, column_name, Key_name, etc. and displays output with all indexes and primary keys as -

*************************** 1. row ***************************
        Table: products
   Non_unique: 0
     Key_name: PRIMARY
 Seq_in_index: 1
  Column_name: product_id
    Collation: A
  Cardinality: 0
     Sub_part: NULL
       Packed: NULL
         Null: 
   Index_type: BTREE
      Comment: 
Index_comment: 

To just display primary key from the table use :-

SHOW INDEXES FROM table_name WHERE Key_name = 'PRIMARY'

Android Saving created bitmap to directory on sd card

This answer is an update with a little more consideration for OOM and various other leaks.

Assumes you have a directory intended as the destination and a name String already defined.

    File destination = new File(directory.getPath() + File.separatorChar + filename);

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    source.compress(Bitmap.CompressFormat.PNG, 100, bytes);

    FileOutputStream fo = null;
    try {
        destination.createNewFile();

        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
    } catch (IOException e) {

    } finally {
        try {
            fo.close();
        } catch (IOException e) {}
    }

Convert JSON String to Pretty Print JSON output using Jackson

For Jackson 1.9, We can use the following code for pretty print.

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);

How to display images from a folder using php - PHP

You have two ways to do that:

METHOD 1. The secure way.

Put the images on /www/htdocs/

<?php
    $www_root = 'http://localhost/images';
    $dir = '/var/www/images';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if ( file_exists( $dir ) == false ) {
       echo 'Directory \'', $dir, '\' not found!';
    } else {
       $dir_contents = scandir( $dir );

        foreach ( $dir_contents as $file ) {
           $file_type = strtolower( end( explode('.', $file ) ) );
           if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
              echo '<img src="', $www_root, '/', $file, '" alt="', $file, '"/>';
           break;
           }
        }
    }
?>

METHOD 2. Unsecure but more flexible.

Put the images on any directory (apache must have permission to read the file).

<?php
    $dir = '/home/user/Pictures';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if ( file_exists( $dir ) == false ) {
       echo 'Directory \'', $dir, '\' not found!';
    } else {
       $dir_contents = scandir( $dir );

        foreach ( $dir_contents as $file ) {
           $file_type = strtolower( end( explode('.', $file ) ) );
           if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
              echo '<img src="file_viewer.php?file=', base64_encode($dir . '/' . $file), '" alt="', $file, '"/>';
           break;
           }
        }
    }
?>

And create another script to read the image file.

<?php
    $filename = base64_decode($_GET['file']);
    // Check the folder location to avoid exploit
    if (dirname($filename) == '/home/user/Pictures')
        echo file_get_contents($filename);
?>

How to do case insensitive search in Vim

As others suggested:

:set ic

But the cool stuff is You can toggle such modes with:

:set ic!

Convert string to Date in java

This code will help you to make a result like FEB 17 20:49 .

    String myTimestamp="2014/02/17 20:49";

    SimpleDateFormat form = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    Date date = null;
    Date time = null;
    try 
    {
        date = form.parse(myTimestamp);
        time = new Date(myTimestamp);
        SimpleDateFormat postFormater = new SimpleDateFormat("MMM dd");
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
        String newDateStr = postFormater.format(date).toUpperCase();
        String newTimeStr = sdf.format(time);
        System.out.println("Date  : "+newDateStr);
        System.out.println("Time  : "+newTimeStr);
    }
    catch (Exception e) 
    {
        e.printStackTrace();
    }

Result :

Date : FEB 17

Time : 20:49

Spring mvc @PathVariable

Let us assume you hit a url as www.example.com/test/111 . Now you have to retrieve value 111 (which is dynamic) to your controller method .At time you ll be using @PathVariable as follows :

@RequestMapping(value = " /test/{testvalue}", method=RequestMethod.GET)
public void test(@PathVariable String testvalue){
//you can use test value here
}

SO the variable value is retrieved from the url

Compile c++14-code with g++

The -std=c++14 flag is not supported on GCC 4.8. If you want to use C++14 features you need to compile with -std=c++1y. Using godbolt.org it appears that the earilest version to support -std=c++14 is GCC 4.9.0 or Clang 3.5.0

How to apply a function to two columns of Pandas dataframe

Here's an example using apply on the dataframe, which I am calling with axis = 1.

Note the difference is that instead of trying to pass two values to the function f, rewrite the function to accept a pandas Series object, and then index the Series to get the values needed.

In [49]: df
Out[49]: 
          0         1
0  1.000000  0.000000
1 -0.494375  0.570994
2  1.000000  0.000000
3  1.876360 -0.229738
4  1.000000  0.000000

In [50]: def f(x):    
   ....:  return x[0] + x[1]  
   ....:  

In [51]: df.apply(f, axis=1) #passes a Series object, row-wise
Out[51]: 
0    1.000000
1    0.076619
2    1.000000
3    1.646622
4    1.000000

Depending on your use case, it is sometimes helpful to create a pandas group object, and then use apply on the group.

Difference between Hive internal tables and external tables?

Consider this scenario which best suits for External Table:

A MapReduce (MR) job filters a huge log file to spit out n sub log files (e.g. each sub log file contains a specific message type log) and the output i.e n sub log files are stored in hdfs.

These log files are to be loaded into Hive tables for performing further analytic, in this scenario I would recommend an External Table(s), because the actual log files are generated and owned by an external process i.e. a MR job besides you can avoid an additional step of loading each generated log file into respective Hive table as well.

Disable cache for some images

Solution 1 is not great. It does work, but adding hacky random or timestamped query strings to the end of your image files will make the browser re-download and cache every version of every image, every time a page is loaded, regardless of weather the image has changed or not on the server.

Solution 2 is useless. Adding nocache headers to an image file is not only very difficult to implement, but it's completely impractical because it requires you to predict when it will be needed in advance, the first time you load any image which you think might change at some point in the future.

Enter Etags...

The absolute best way I've found to solve this is to use ETAGS inside a .htaccess file in your images directory. The following tells Apache to send a unique hash to the browser in the image file headers. This hash only ever changes when time the image file is modified and this change triggers the browser to reload the image the next time it is requested.

<FilesMatch "\.(jpg|jpeg)$">
FileETag MTime Size
</FilesMatch>

How to stop Python closing immediately when executed in Microsoft Windows

Very simple:

  1. Open command prompt as an administrator.
  2. Type python.exe (provided you have given path of it in environmental variables)

Then, In the same command prompt window the python interpreter will start with >>>

This worked for me.

How do I create test and train samples from one dataframe with pandas?

You can use ~ (tilde operator) to exclude the rows sampled using df.sample(), letting pandas alone handle sampling and filtering of indexes, to obtain two sets.

train_df = df.sample(frac=0.8, random_state=100)
test_df = df[~df.index.isin(train_df.index)]

How to discard all changes made to a branch?

git checkout -f

This is suffice for your question. Only thing is, once its done, its done. There is no undo.

Can't find @Nullable inside javax.annotation.*

If anyone has this issue when building a Maven project created in IntelliJ IDEA externally, I used the following dependency instead of the answer:

<dependency>
  <groupId>org.jetbrains</groupId>
  <artifactId>annotations</artifactId>
  <version>15.0</version>
</dependency>

Using this will allow the project to build on IntelliJ IDEA and by itself using Maven.

You can find it here.

Using global variables between files?

Your 2nd attempt will work perfectly, and is actually a really good way to handle variable names that you want to have available globally. But you have a name error in the last line. Here is how it should be:

# ../myproject/main.py

# Import globfile    
import globfile

# Save myList into globfile
globfile.myList = []

# Import subfile
import subfile

# Do something
subfile.stuff()
print(globfile.myList[0])

See the last line? myList is an attr of globfile, not subfile. This will work as you want.

Mike

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

This function will generate a random key using numbers and letters:

function random_string($length) {
    $key = '';
    $keys = array_merge(range(0, 9), range('a', 'z'));

    for ($i = 0; $i < $length; $i++) {
        $key .= $keys[array_rand($keys)];
    }

    return $key;
}

echo random_string(50);

Example output:

zsd16xzv3jsytnp87tk7ygv73k8zmr0ekh6ly7mxaeyeh46oe8

Spring Data JPA findOne() change to Optional how to use this?

Optional api provides methods for getting the values. You can check isPresent() for the presence of the value and then make a call to get() or you can make a call to get() chained with orElse() and provide a default value.

The last thing you can try doing is using @Query() over a custom method.

Spring Boot application as a Service

I am trying to make springboot applications that are presented as a "init.d" style shell script with a compressed java application tacked on the end

By symlinking these scripts from /etc/init.d/spring-app to /opt/spring-app.jar and chmod'ing the jar to be executable it is possible to make "/etc/init.d/spring-app start" "/etc/init.d/spring-app stop" and other possibilities like status work

Presumably, as the init.d style scripts from springboot look that they have the neccessary magic strings ( like # Default-Start: 2 3 4 5) chkconfig would be able to add it as a "service"

But I wanted to get it to work with systemd

To make this work I tried many of the recipies in the other answers above but none of them worked for me on Centos 7.2 with Springboot 1.3 Mostly they would start the service but not be able to track the pid

In the end I found the following did work for me, when the /etc/init.d link was in place also. A file similar to the one below should be installed as /usr/lib/systemd/system/spring-app.service

[Unit]
Description=My loverly application
After=syslog.target 

[Service]
Type=forking
PIDFile=/var/run/spring-app/spring-app.pid
ExecStart=/etc/init.d/spring-app start
SuccessExitStatus=143

[Install]
WantedBy=multi-user.target

recyclerview No adapter attached; skipping layout

I lost 16 minutes of my life with this issue, so I'll just admit to this incredibly embarrassing mistake that I was making- I'm using Butterknife and I bind the view in onCreateView in this fragment.

It took a long time to figure out why I had no layoutmanager - but obviously the views are injected so they won't actually be null, so the the recycler will never be null .. whoops!

@BindView(R.id.recycler_view)
RecyclerView recyclerView;

    @Override
public View onCreateView(......) {
    View v = ...;
    ButterKnife.bind(this, v);
    setUpRecycler()
 }

public void setUpRecycler(Data data)
   if (recyclerView == null) {
 /*very silly because this will never happen*/
       LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
       //more setup
       //...
    }
    recyclerView.setAdapter(new XAdapter(data));
}

If you are getting an issue like this trace your view and use something like uiautomatorviewer

Replace invalid values with None in Pandas DataFrame

Setting null values can be done with np.nan:

import numpy as np
df.replace('-', np.nan)

Advantage is that df.last_valid_index() recognizes these as invalid.

How to display gpg key details without importing it?

The option --list-packets parses pgp data from a file and outputs its structure - in a very technical way, though. When parsing a public key, you can easily extract the user ids and the key ids of the signatures.

Be wary that this command only parses the data format, it does no validation of signatures or similar things.

Git diff -w ignore whitespace only at start & end of lines

This is an old question, but is still regularly viewed/needed. I want to post to caution readers like me that whitespace as mentioned in the OP's question is not the same as Regex's definition, to include newlines, tabs, and space characters -- Git asks you to be explicit. See some options here: https://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration

As stated, git diff -b or git diff --ignore-space-change will ignore spaces at line ends. If you desire that setting to be your default behavior, the following line adds that intent to your .gitconfig file, so it will always ignore the space at line ends:

git config --global core.whitespace trailing-space

In my case, I found this question because I was interested in ignoring "carriage return whitespace differences", so I needed this:

git diff --ignore-cr-at-eol or git config --global core.whitespace cr-at-eol from here.

You can also make it the default only for that repo by omitting the --global parameter, and checking in the settings file for that repo. For the CR problem I faced, it goes away after check-in if warncrlf or autocrlf = true in the [core] section of the .gitconfig file.

Android device chooser - My device seems offline

I tried everything mutliple times in multiple orders, then stumbled across my particular answer:

Use a different USB cable - suddenly everything worked perfectly.

(Another potential answer for people that I found - make sure there is more than 15mb free space on the device.)

check all socket opened in linux OS

/proc/net/tcp -a list of open tcp sockets

/proc/net/udp -a list of open udp sockets

/proc/net/raw -a list all the 'raw' sockets

These are the files, use cat command to view them. For example:

cat /proc/net/tcp

You can also use the lsof command.

lsof is a command meaning "list open files", which is used in many Unix-like systems to report a list of all open files and the processes that opened them.

How do I make WRAP_CONTENT work on a RecyclerView

i suggest you to put the recyclerview in any other layout (Relative layout is preferable). Then change recyclerview's height/width as match parent to that layout and set the parent layout's height/width as wrap content. it works for me

How to write and read java serialized objects into a file

As others suggested, you can serialize and deserialize the whole list at once, which is simpler and seems to comply perfectly with what you intend to do.

In that case the serialization code becomes

ObjectOutputStream oos = null;
FileOutputStream fout = null;
try{
    fout = new FileOutputStream("G:\\address.ser", true);
    oos = new ObjectOutputStream(fout);
    oos.writeObject(myClassList);
} catch (Exception ex) {
    ex.printStackTrace();
} finally {
    if(oos != null){
        oos.close();
    } 
}

And deserialization becomes (assuming that myClassList is a list and hoping you will use generics):

ObjectInputStream objectinputstream = null;
try {
    FileInputStream streamIn = new FileInputStream("G:\\address.ser");
    objectinputstream = new ObjectInputStream(streamIn);
    List<MyClass> readCase = (List<MyClass>) objectinputstream.readObject();
    recordList.add(readCase);
    System.out.println(recordList.get(i));
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if(objectinputstream != null){
        objectinputstream .close();
    } 
}

You can also deserialize several objects from a file, as you intended to:

ObjectInputStream objectinputstream = null;
try {
    streamIn = new FileInputStream("G:\\address.ser");
    objectinputstream = new ObjectInputStream(streamIn);
    MyClass readCase = null;
    do {
        readCase = (MyClass) objectinputstream.readObject();
        if(readCase != null){
            recordList.add(readCase);
        } 
    } while (readCase != null)        
    System.out.println(recordList.get(i));
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if(objectinputstream != null){
        objectinputstream .close();
    } 
}

Please do not forget to close stream objects in a finally clause (note: it can throw exception).

EDIT

As suggested in the comments, it should be preferable to use try with resources and the code should get quite simpler.

Here is the list serialization :

try(
    FileOutputStream fout = new FileOutputStream("G:\\address.ser", true);
    ObjectOutputStream oos = new ObjectOutputStream(fout);
){
    oos.writeObject(myClassList);
} catch (Exception ex) {
    ex.printStackTrace();
}

Explicitly select items from a list or tuple

What about this:

from operator import itemgetter
itemgetter(0,2,3)(myList)
('foo', 'baz', 'quux')

Declare a const array

If you declare an array behind an IReadOnlyList interface you get a constant array with constant values that is declared at runtime:

public readonly IReadOnlyList<string> Titles = new [] {"German", "Spanish", "Corrects", "Wrongs" };

Available in .NET 4.5 and higher.

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

"unexpected token import" in Nodejs5 and babel?

Until modules are implemented you can use the Babel "transpiler" to run your code:

npm install --save babel-cli babel-preset-node6

and then

./node_modules/babel-cli/bin/babel-node.js --presets node6 ./your_script.js

If you dont want to type --presets node6 you can save it .babelrc file by:

{
  "presets": [
    "node6"
  ]
}

See https://www.npmjs.com/package/babel-preset-node6 and https://babeljs.io/docs/usage/cli/

set up device for development (???????????? no permissions)

Without unplugging

All the provided answers assume that you are able to unplug and reconnect the USB cable. In situations where this is not possible (e.g., when you are remote), you can do the following to essentially do what the suggested udev rules would do on re-plug:

lsusb

Find the device you care about, e.g.:

Bus 003 Device 005: ID 18d1:4ee4 Google Inc. Nexus

Take note of the bus number it is on and then execute, e.g. for bus 003:

sudo chmod a+w /dev/bus/usb/003/*

Clearly this may be more permissive than you want (there may be more devices attached than just this one), but you get the idea.

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

UPDATE: 2019-12-30

It seem that this tool is no longer working! [Request for update!]

UPDATE 2019-01-06: You can bypass X-Frame-Options in an <iframe> using my X-Frame-Bypass Web Component. It extends the IFrame element by using multiple CORS proxies and it was tested in the latest Firefox and Chrome.

You can use it as follows:

  1. (Optional) Include the Custom Elements with Built-in Extends polyfill for Safari:

    <script src="https://unpkg.com/@ungap/custom-elements-builtin"></script>
    
  2. Include the X-Frame-Bypass JS module:

    <script type="module" src="x-frame-bypass.js"></script>
    
  3. Insert the X-Frame-Bypass Custom Element:

    <iframe is="x-frame-bypass" src="https://example.org/"></iframe>
    

Convert timestamp to date in Oracle SQL

Try using TRUNC and TO_DATE instead

WHERE
    TRUNC(start_ts) = TO_DATE('2016-05-13', 'YYYY-MM-DD')

Alternatively, you can use >= and < instead to avoid use of function in the start_ts column:

WHERE
   start_ts >= TO_DATE('2016-05-13', 'YYYY-MM-DD')
   AND start_ts < TO_DATE('2016-05-14', 'YYYY-MM-DD')

Oracle date difference to get number of years

If you just want the difference in years, there's:

SELECT EXTRACT(YEAR FROM date1) - EXTRACT(YEAR FROM date2) FROM mytable

Or do you want fractional years as well?

SELECT (date1 - date2) / 365.242199 FROM mytable

365.242199 is 1 year in days, according to Google.

get current date from [NSDate date] but set the time to 10:00 am

As with all date manipulation you have to use NSDateComponents and NSCalendar

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
[components setHour:10];
NSDate *today10am = [calendar dateFromComponents:components];

in iOS8 Apple introduced a convenience method that saves a few lines of code:

NSDate *d = [calendar dateBySettingHour:10 minute:0 second:0 ofDate:[NSDate date] options:0];

Swift:

let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let now: NSDate! = NSDate()

let date10h = calendar.dateBySettingHour(10, minute: 0, second: 0, ofDate: now, options: NSCalendarOptions.MatchFirst)!

Java Regex Replace with Capturing Group

How about:

if (regexMatcher.find()) {
    resultString = regexMatcher.replaceAll(
            String.valueOf(3 * Integer.parseInt(regexMatcher.group(1))));
}

To get the first match, use #find(). After that, you can use #group(1) to refer to this first match, and replace all matches by the first maches value multiplied by 3.

And in case you want to replace each match with that match's value multiplied by 3:

    Pattern p = Pattern.compile("(\\d{1,2})");
    Matcher m = p.matcher("12 54 1 65");
    StringBuffer s = new StringBuffer();
    while (m.find())
        m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1))));
    System.out.println(s.toString());

You may want to look through Matcher's documentation, where this and a lot more stuff is covered in detail.

How to get text in QlineEdit when QpushButton is pressed in a string?

My first suggestion is to use Designer to create your GUIs. Typing them out yourself sucks, takes more time, and you will definitely make more mistakes than Designer.

Here are some PyQt tutorials to help get you on the right track. The first one in the list is where you should start.

A good guide for figuring out what methods are available for specific classes is the PyQt4 Class Reference. In this case you would look up QLineEdit and see the there is a text method.

To answer your specific question:

To make your GUI elements available to the rest of the object, preface them with self.

import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect") 

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)

        self.setLayout(layout)
        self.connect(self.pb, SIGNAL("clicked()"),self.button_click)
        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print shost


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

Regular expression for validating names and surnames?

I would just allow everything (except an empty string) and assume the user knows what his name is.

There are 2 common cases:

  1. You care that the name is accurate and are validating against a real paper passport or other identity document, or against a credit card.
  2. You don't care that much and the user will be able to register as "Fred Smith" (or "Jane Doe") anyway.

In case (1), you can allow all characters because you're checking against a paper document.

In case (2), you may as well allow all characters because "123 456" is really no worse a pseudonym than "Abc Def".

Fail to create Android virtual Device, "No system image installed for this Target"

In order to create an Android Wear emulator you need to follow the instructions below:

  1. If your version of Android SDK Tools is lower than 22.6, you must update

  2. Under Android 4.4.2, select Android Wear ARM EABI v7a System Image and install it.

  3. Under Extras, ensure that you have the latest version of the Android Support Library. If an update is available, select Android Support Library. If you're using Android Studio, also select Android Support Repository.

Below is the snapshot of what it should look like:

Screenshot1

Then you must check the following in order to create a Wearable AVD:

  1. For the Device, select Android Wear Square or Android Wear Round.

  2. For the Target, select Android 4.4.2 - API Level 19 (or higher, otherwise corresponding system image will not show up.).

  3. For the CPU/ABI, select Android Wear ARM (armeabi-v7a).

  4. For the Skin, select AndroidWearSquare or AndroidWearRound.

  5. Leave all other options set to their defaults and click OK.

Screenshot2

Then you are good to go. For more information you can always refer to the developer site.

TypeError: window.initMap is not a function

Actually the error is being generated by the initMap in the Google's api script

 <script async defer
  src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

so basically when the Google Map API is loaded then the initMap function is executed. If you don't have an initMap function, then the initMap is not a function error is generated.

So basically what you have to do is one of the following options:

  1. to create an initMap function
  2. replace the callback function with one of your own that created for the same purpose but named it something else
  3. replace the &callback=angular.noop if you just want an empty function() (only if you use angular)

What's causing my java.net.SocketException: Connection reset?

I got this error when the text file I was trying to read contained a string that matched an antivirus signature on our firewall.

CSV file written with Python has blank lines between each row

The simple answer is that csv files should always be opened in binary mode whether for input or output, as otherwise on Windows there are problems with the line ending. Specifically on output the csv module will write \r\n (the standard CSV row terminator) and then (in text mode) the runtime will replace the \n by \r\n (the Windows standard line terminator) giving a result of \r\r\n.

Fiddling with the lineterminator is NOT the solution.

How to run a Maven project from Eclipse?

Your Maven project doesn't seem to be configured as a Eclipse Java project, that is the Java nature is missing (the little 'J' in the project icon).

To enable this, the <packaging> element in your pom.xml should be jar (or similar).

Then, right-click the project and select Maven > Update Project Configuration

For this to work, you need to have m2eclipse installed. But since you had the _ New ... > New Maven Project_ wizard, I assume you have m2eclipse installed.

How to handle anchor hash linking in AngularJS

In my case, I noticed that the routing logic was kicking in if I modified the $location.hash(). The following trick worked..

$scope.scrollTo = function(id) {
    var old = $location.hash();
    $location.hash(id);
    $anchorScroll();
    //reset to old to keep any additional routing logic from kicking in
    $location.hash(old);
};

How to use <sec:authorize access="hasRole('ROLES)"> for checking multiple Roles?

i used hasAnyRole('ROLE_ADMIN','ROLE_USER') but i was getting bean creation below error

Error creating bean with name     'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0': Cannot create inner bean '(inner bean)' of type [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource] while setting bean property 'securityMetadataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#2': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource]: Constructor threw exception; nested exception is java.lang.IllegalArgumentException: Expected a single expression attribute for [/user/*]

then i tried

access="hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')" and it's working fine for me.

as one of my user is admin as well as user.

for this you need to add use-expressions="true" auto-config="true" followed by http tag

<http use-expressions="true" auto-config="true" >.....</http>

Push items into mongo array via mongoose

The $push operator appends a specified value to an array.

{ $push: { <field1>: <value1>, ... } }

$push adds the array field with the value as its element.

Above answer fulfils all the requirements, but I got it working by doing the following

var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
Friend.findOneAndUpdate(
   { _id: req.body.id }, 
   { $push: { friends: objFriends  } },
  function (error, success) {
        if (error) {
            console.log(error);
        } else {
            console.log(success);
        }
    });
)

calling java methods in javascript code

Java is a server side language, whereas javascript is a client side language. Both cannot communicate. If you have setup some server side script using Java you could use AJAX on the client in order to send an asynchronous request to it and thus invoke any possible Java functions. For example if you use jQuery as js framework you may take a look at the $.ajax() method. Or if you wanted to do it using plain javascript, here's a tutorial.

Tell Ruby Program to Wait some amount of time

sleep 6 will sleep for 6 seconds. For a longer duration, you can also use sleep(6.minutes) or sleep(6.hours).

How to Migrate to WKWebView?

WKWebView using Swift in iOS 8..

The whole ViewController.swift file now looks like this:

import UIKit
import WebKit

class ViewController: UIViewController {

    @IBOutlet var containerView : UIView! = nil
    var webView: WKWebView?

    override func loadView() {
        super.loadView()

        self.webView = WKWebView()
        self.view = self.webView!
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var url = NSURL(string:"http://www.kinderas.com/")
        var req = NSURLRequest(URL:url)
        self.webView!.loadRequest(req)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

How to delete object?

FLCL's idea is very correct, I show you in a code:

    public class O1<T> where T: class
    {
        public Guid Id { get; }
        public O1(Guid id)
        {
            Id = id;
        }
        public bool IsNull => !GlobalHolder.Holder.ContainsKey(Id);
        public T Val => GlobalHolder.Holder.ContainsKey(Id) ? (T)GlobalHolder.Holder[Id] : null;
    }
    public class GlobalHolder
    {
        public static readonly Dictionary<Guid, object> Holder = new Dictionary<Guid, object>();
        public static O1<T> Instantiate<T>() where T: class, new()
        {
            var a = new T();
            var nguid = Guid.NewGuid();
            var b = new O1<T>(nguid);
            Holder[nguid] = a;
            return b;
        }
        public static void Destroy<T>(O1<T> obj) where T: class
        {
            Holder.Remove(obj.Id);
        }
    }

    public class Animal
    {

    }

    public class AnimalTest
    {
        public static void Test()
        {
            var tom = GlobalHolder.Instantiate<Animal>();
            var duplicateTomReference = tom;
            GlobalHolder.Destroy(tom);
            Console.WriteLine($"{duplicateTomReference.IsNull}");
            // prints true
        }
    }

Note: In this code sample, my naming convention comes from Unity.

List to array conversion to use ravel() function

Use the following code:

import numpy as np

myArray=np.array([1,2,4])  #func used to convert [1,2,3] list into an array
print(myArray)

Error including image in Latex

Using .jpg files do not forget about compiling directly to .pdf (pdflatex) and use: graphicx package with pdftex option (\usepackage[pdftex]{graphicx}).

How do I extract Month and Year in a MySQL date and compare them?

in Mysql Doku: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_extract

SELECT EXTRACT( YEAR_MONTH FROM `date` ) 
FROM `Table` WHERE Condition = 'Condition';

Controlling execution order of unit tests in Visual Studio

Here is a class that can be used to setup and run ordered tests independent of MS Ordered Tests framework for whatever reason--like not have to adjust mstest.exe arguments on a build machine, or mixing ordered with non-ordered in a class.

The original testing framework only sees the list of ordered tests as a single test so any init/cleanup like [TestInitalize()] Init() is only called before and after the entire set.

Usage:

        [TestMethod] // place only on the list--not the individuals
        public void OrderedStepsTest()
        {
            OrderedTest.Run(TestContext, new List<OrderedTest>
            {
                new OrderedTest ( T10_Reset_Database, false ),
                new OrderedTest ( T20_LoginUser1, false ),
                new OrderedTest ( T30_DoLoginUser1Task1, true ), // continue on failure
                new OrderedTest ( T40_DoLoginUser1Task2, true ), // continue on failure
                // ...
            });                
        }

Implementation:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace UnitTests.Utility
{    
    /// <summary>
    /// Define and Run a list of ordered tests. 
    /// 2016/08/25: Posted to SO by crokusek 
    /// </summary>    
    public class OrderedTest
    {
        /// <summary>Test Method to run</summary>
        public Action TestMethod { get; private set; }

        /// <summary>Flag indicating whether testing should continue with the next test if the current one fails</summary>
        public bool ContinueOnFailure { get; private set; }

        /// <summary>Any Exception thrown by the test</summary>
        public Exception ExceptionResult;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="testMethod"></param>
        /// <param name="continueOnFailure">True to continue with the next test if this test fails</param>
        public OrderedTest(Action testMethod, bool continueOnFailure = false)
        {
            TestMethod = testMethod;
            ContinueOnFailure = continueOnFailure;
        }

        /// <summary>
        /// Run the test saving any exception within ExceptionResult
        /// Throw to the caller only if ContinueOnFailure == false
        /// </summary>
        /// <param name="testContextOpt"></param>
        public void Run()
        {
            try
            {
                TestMethod();
            }
            catch (Exception ex)
            {
                ExceptionResult = ex;
                throw;
            }
        }

        /// <summary>
        /// Run a list of OrderedTest's
        /// </summary>
        static public void Run(TestContext testContext, List<OrderedTest> tests)
        {
            Stopwatch overallStopWatch = new Stopwatch();
            overallStopWatch.Start();

            List<Exception> exceptions = new List<Exception>();

            int testsAttempted = 0;
            for (int i = 0; i < tests.Count; i++)
            {
                OrderedTest test = tests[i];

                Stopwatch stopWatch = new Stopwatch();
                stopWatch.Start();

                testContext.WriteLine("Starting ordered test step ({0} of {1}) '{2}' at {3}...\n",
                    i + 1,
                    tests.Count,
                    test.TestMethod.Method,
                    DateTime.Now.ToString("G"));

                try
                {
                    testsAttempted++;
                    test.Run();
                }
                catch
                {
                    if (!test.ContinueOnFailure)
                        break;
                }
                finally
                {
                    Exception testEx = test.ExceptionResult;

                    if (testEx != null)  // capture any "continue on fail" exception
                        exceptions.Add(testEx);

                    testContext.WriteLine("\n{0} ordered test step {1} of {2} '{3}' in {4} at {5}{6}\n",
                        testEx != null ? "Error:  Failed" : "Successfully completed",
                        i + 1,
                        tests.Count,
                        test.TestMethod.Method,
                        stopWatch.ElapsedMilliseconds > 1000
                            ? (stopWatch.ElapsedMilliseconds * .001) + "s"
                            : stopWatch.ElapsedMilliseconds + "ms",
                        DateTime.Now.ToString("G"),
                        testEx != null
                            ? "\nException:  " + testEx.Message +
                                "\nStackTrace:  " + testEx.StackTrace +
                                "\nContinueOnFailure:  " + test.ContinueOnFailure
                            : "");
                }
            }

            testContext.WriteLine("Completed running {0} of {1} ordered tests with a total of {2} error(s) at {3} in {4}",
                testsAttempted,
                tests.Count,
                exceptions.Count,
                DateTime.Now.ToString("G"),
                overallStopWatch.ElapsedMilliseconds > 1000
                    ? (overallStopWatch.ElapsedMilliseconds * .001) + "s"
                    : overallStopWatch.ElapsedMilliseconds + "ms");

            if (exceptions.Any())
            {
                // Test Explorer prints better msgs with this hierarchy rather than using 1 AggregateException().
                throw new Exception(String.Join("; ", exceptions.Select(e => e.Message), new AggregateException(exceptions)));
            }
        }
    }
}

Converting year and month ("yyyy-mm" format) to a date?

Since dates correspond to a numeric value and a starting date, you indeed need the day. If you really need your data to be in Date format, you can just fix the day to the first of each month manually by pasting it to the date:

month <- "2009-03"
as.Date(paste(month,"-01",sep=""))

Detect application heap size in Android

There are two ways to think about your phrase "application heap size available":

  1. How much heap can my app use before a hard error is triggered? And

  2. How much heap should my app use, given the constraints of the Android OS version and hardware of the user's device?

There is a different method for determining each of the above.

For item 1 above: maxMemory()

which can be invoked (e.g., in your main activity's onCreate() method) as follows:

Runtime rt = Runtime.getRuntime();
long maxMemory = rt.maxMemory();
Log.v("onCreate", "maxMemory:" + Long.toString(maxMemory));

This method tells you how many total bytes of heap your app is allowed to use.

For item 2 above: getMemoryClass()

which can be invoked as follows:

ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass();
Log.v("onCreate", "memoryClass:" + Integer.toString(memoryClass));

This method tells you approximately how many megabytes of heap your app should use if it wants to be properly respectful of the limits of the present device, and of the rights of other apps to run without being repeatedly forced into the onStop() / onResume() cycle as they are rudely flushed out of memory while your elephantine app takes a bath in the Android jacuzzi.

This distinction is not clearly documented, so far as I know, but I have tested this hypothesis on five different Android devices (see below) and have confirmed to my own satisfaction that this is a correct interpretation.

For a stock version of Android, maxMemory() will typically return about the same number of megabytes as are indicated in getMemoryClass() (i.e., approximately a million times the latter value).

The only situation (of which I am aware) for which the two methods can diverge is on a rooted device running an Android version such as CyanogenMod, which allows the user to manually select how large a heap size should be allowed for each app. In CM, for example, this option appears under "CyanogenMod settings" / "Performance" / "VM heap size".

NOTE: BE AWARE THAT SETTING THIS VALUE MANUALLY CAN MESS UP YOUR SYSTEM, ESPECIALLY if you select a smaller value than is normal for your device.

Here are my test results showing the values returned by maxMemory() and getMemoryClass() for four different devices running CyanogenMod, using two different (manually-set) heap values for each:

  • G1:
    • With VM Heap Size set to 16MB:
      • maxMemory: 16777216
      • getMemoryClass: 16
    • With VM Heap Size set to 24MB:
      • maxMemory: 25165824
      • getMemoryClass: 16
  • Moto Droid:
    • With VM Heap Size set to 24MB:
      • maxMemory: 25165824
      • getMemoryClass: 24
    • With VM Heap Size set to 16MB:
      • maxMemory: 16777216
      • getMemoryClass: 24
  • Nexus One:
    • With VM Heap size set to 32MB:
      • maxMemory: 33554432
      • getMemoryClass: 32
    • With VM Heap size set to 24MB:
      • maxMemory: 25165824
      • getMemoryClass: 32
  • Viewsonic GTab:
    • With VM Heap Size set to 32:
      • maxMemory: 33554432
      • getMemoryClass: 32
    • With VM Heap Size set to 64:
      • maxMemory: 67108864
      • getMemoryClass: 32

In addition to the above, I tested on a Novo7 Paladin tablet running Ice Cream Sandwich. This was essentially a stock version of ICS, except that I've rooted the tablet through a simple process that does not replace the entire OS, and in particular does not provide an interface that would allow the heap size to be manually adjusted.

For that device, here are the results:

  • Novo7
    • maxMemory: 62914560
    • getMemoryClass: 60

Also (per Kishore in a comment below):

  • HTC One X
    • maxMemory: 67108864
    • getMemoryClass: 64

And (per akauppi's comment):

  • Samsung Galaxy Core Plus
    • maxMemory: (Not specified in comment)
    • getMemoryClass: 48
    • largeMemoryClass: 128

Per a comment from cmcromance:

  • Galaxy S3 (Jelly Bean) large heap
    • maxMemory: 268435456
    • getMemoryClass: 64

And (per tencent's comments):

  • LG Nexus 5 (4.4.3) normal
    • maxMemory: 201326592
    • getMemoryClass: 192
  • LG Nexus 5 (4.4.3) large heap
    • maxMemory: 536870912
    • getMemoryClass: 192
  • Galaxy Nexus (4.3) normal
    • maxMemory: 100663296
    • getMemoryClass: 96
  • Galaxy Nexus (4.3) large heap
    • maxMemory: 268435456
    • getMemoryClass: 96
  • Galaxy S4 Play Store Edition (4.4.2) normal
    • maxMemory: 201326592
    • getMemoryClass: 192
  • Galaxy S4 Play Store Edition (4.4.2) large heap
    • maxMemory: 536870912
    • getMemoryClass: 192

Other Devices

  • Huawei Nexus 6P (6.0.1) normal
    • maxMemory: 201326592
    • getMemoryClass: 192

I haven't tested these two methods using the special android:largeHeap="true" manifest option available since Honeycomb, but thanks to cmcromance and tencent we do have some sample largeHeap values, as reported above.

My expectation (which seems to be supported by the largeHeap numbers above) would be that this option would have an effect similar to setting the heap manually via a rooted OS - i.e., it would raise the value of maxMemory() while leaving getMemoryClass() alone. There is another method, getLargeMemoryClass(), that indicates how much memory is allowable for an app using the largeHeap setting. The documentation for getLargeMemoryClass() states, "most applications should not need this amount of memory, and should instead stay with the getMemoryClass() limit."

If I've guessed correctly, then using that option would have the same benefits (and perils) as would using the space made available by a user who has upped the heap via a rooted OS (i.e., if your app uses the additional memory, it probably will not play as nicely with whatever other apps the user is running at the same time).

Note that the memory class apparently need not be a multiple of 8MB.

We can see from the above that the getMemoryClass() result is unchanging for a given device/OS configuration, while the maxMemory() value changes when the heap is set differently by the user.

My own practical experience is that on the G1 (which has a memory class of 16), if I manually select 24MB as the heap size, I can run without erroring even when my memory usage is allowed to drift up toward 20MB (presumably it could go as high as 24MB, although I haven't tried this). But other similarly large-ish apps may get flushed from memory as a result of my own app's pigginess. And, conversely, my app may get flushed from memory if these other high-maintenance apps are brought to the foreground by the user.

So, you cannot go over the amount of memory specified by maxMemory(). And, you should try to stay within the limits specified by getMemoryClass(). One way to do that, if all else fails, might be to limit functionality for such devices in a way that conserves memory.

Finally, if you do plan to go over the number of megabytes specified in getMemoryClass(), my advice would be to work long and hard on the saving and restoring of your app's state, so that the user's experience is virtually uninterrupted if an onStop() / onResume() cycle occurs.

In my case, for reasons of performance I'm limiting my app to devices running 2.2 and above, and that means that almost all devices running my app will have a memoryClass of 24 or higher. So I can design to occupy up to 20MB of heap and feel pretty confident that my app will play nice with the other apps the user may be running at the same time.

But there will always be a few rooted users who have loaded a 2.2 or above version of Android onto an older device (e.g., a G1). When you encounter such a configuration, ideally, you ought to pare down your memory use, even if maxMemory() is telling you that you can go much higher than the 16MB that getMemoryClass() is telling you that you should be targeting. And if you cannot reliably ensure that your app will live within that budget, then at least make sure that onStop() / onResume() works seamlessly.

getMemoryClass(), as indicated by Diane Hackborn (hackbod) above, is only available back to API level 5 (Android 2.0), and so, as she advises, you can assume that the physical hardware of any device running an earlier version of the OS is designed to optimally support apps occupying a heap space of no more than 16MB.

By contrast, maxMemory(), according to the documentation, is available all the way back to API level 1. maxMemory(), on a pre-2.0 version, will probably return a 16MB value, but I do see that in my (much later) CyanogenMod versions the user can select a heap value as low as 12MB, which would presumably result in a lower heap limit, and so I would suggest that you continue to test the maxMemory() value, even for versions of the OS prior to 2.0. You might even have to refuse to run in the unlikely event that this value is set even lower than 16MB, if you need to have more than maxMemory() indicates is allowed.

Find records from one table which don't exist in another

SELECT Call.ID, Call.date, Call.phone_number 
FROM Call 
LEFT OUTER JOIN Phone_Book 
  ON (Call.phone_number=Phone_book.phone_number) 
  WHERE Phone_book.phone_number IS NULL

Should remove the subquery, allowing the query optimiser to work its magic.

Also, avoid "SELECT *" because it can break your code if someone alters the underlying tables or views (and it's inefficient).

How to use a table type in a SELECT FROM statement?

Prior to Oracle 12C you cannot select from PL/SQL-defined tables, only from tables based on SQL types like this:

CREATE OR REPLACE TYPE exch_row AS OBJECT(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);


CREATE OR REPLACE TYPE exch_tbl AS TABLE OF exch_row;

In Oracle 12C it is now possible to select from PL/SQL tables that are defined in a package spec.

How to check if a registry value exists using C#?

public static bool RegistryValueExists(string hive_HKLM_or_HKCU, string registryRoot, string valueName)
{
    RegistryKey root;
    switch (hive_HKLM_or_HKCU.ToUpper())
    {
        case "HKLM":
            root = Registry.LocalMachine.OpenSubKey(registryRoot, false);
            break;
        case "HKCU":
            root = Registry.CurrentUser.OpenSubKey(registryRoot, false);
            break;
        default:
            throw new System.InvalidOperationException("parameter registryRoot must be either \"HKLM\" or \"HKCU\"");
    }

    return root.GetValue(valueName) != null;
}

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

Neither code is always better. They do different things, so they are good at different things.

InvariantCultureIgnoreCase uses comparison rules based on english, but without any regional variations. This is good for a neutral comparison that still takes into account some linguistic aspects.

OrdinalIgnoreCase compares the character codes without cultural aspects. This is good for exact comparisons, like login names, but not for sorting strings with unusual characters like é or ö. This is also faster because there are no extra rules to apply before comparing.

Make button width fit to the text

If you are developing to a modern browser. https://caniuse.com/#search=fit%20content

You can use:

width: fit-content;

How can I parse a JSON file with PHP?

Try

<?php
$string = file_get_contents("/home/michael/test.json");
$json_a = json_decode($string,true);

foreach ($json_a as $key => $value){
  echo  $key . ':' . $value;
}
?>

How to mention C:\Program Files in batchfile

Now that bash is out for windows 10, if you want to access program files from bash, you can do it like so: cd /mnt/c/Program\ Files.

How can I see the request headers made by curl when sending a request to the server?

I think curl --verbose/-v is the easiest. It will spit out the request headers (lines prefixed with '>') without having to write to a file:

$ curl -v -I -H "Testing: Test header so you see this works" http://stackoverflow.com/
* About to connect() to stackoverflow.com port 80 (#0)
*   Trying 69.59.196.211... connected
* Connected to stackoverflow.com (69.59.196.211) port 80 (#0)
> HEAD / HTTP/1.1
> User-Agent: curl/7.16.3 (i686-pc-cygwin) libcurl/7.16.3 OpenSSL/0.9.8h zlib/1.2.3 libssh2/0.15-CVS
> Host: stackoverflow.com
> Accept: */*
> Testing: Test header so you see this works
>
< HTTP/1.0 200 OK
...

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

Problem Solved,

I edited the file /etc/postfix/master.cf

and commented

-o smtpd_relay_restrictions=permit_sasl_authenticated,reject

and changed the line from

-o smtpd_tls_security_level=encrypt 

to

-o smtpd_tls_security_level=may

And worked on fine

Meaning of Choreographer messages in Logcat

Choreographer lets apps to connect themselves to the vsync, and properly time things to improve performance.

Android view animations internally uses Choreographer for the same purpose: to properly time the animations and possibly improve performance.

Since Choreographer is told about every vsync events, it can tell if one of the Runnables passed along by the Choreographer.post* apis doesn't finish in one frame's time, causing frames to be skipped.

In my understanding Choreographer can only detect the frame skipping. It has no way of telling why this happens.

The message "The application may be doing too much work on its main thread." could be misleading.

Facebook development in localhost

Try this ---

https://www.facebook.com/help/community/question/?id=589302607826562

1 - Click Apps and then select your app.

2 - Click the Settings button on the left side of the screen.

3 - In the Basic settings, click the Add Platform button below the settings configuration.

4 - Select Website in the platform dialog.

5 - Enter your URL (localhost works here).

6 - In the App Domains text input, add your domain that matches the one in the URL.

7 - Save your settings.

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

There is no "best way" to create an object. Each way has benefits depending on your use case.

The constructor pattern (a function paired with the new operator to invoke it) provides the possibility of using prototypal inheritance, whereas the other ways don't. So if you want prototypal inheritance, then a constructor function is a fine way to go.

However, if you want prototypal inheritance, you may as well use Object.create, which makes the inheritance more obvious.

Creating an object literal (ex: var obj = {foo: "bar"};) works great if you happen to have all the properties you wish to set on hand at creation time.

For setting properties later, the NewObject.property1 syntax is generally preferable to NewObject['property1'] if you know the property name. But the latter is useful when you don't actually have the property's name ahead of time (ex: NewObject[someStringVar]).

Hope this helps!

jQuery get text as number

Use the javascript parseInt method (http://www.w3schools.com/jsref/jsref_parseint.asp)

var number = parseInt($(this).find('.number').text(), 10);
var current = 600;
if (current > number){
     // do something
}

Don't forget to specify the radix value of 10 which tells parseInt that it's in base 10.

Regular Expression to reformat a US phone number in Javascript

The solutions above are superior, especially if using Java, and encountering more numbers with more than 10 digits such as the international code prefix or additional extension numbers. This solution is basic (I'm a beginner in the regex world) and designed with US Phone numbers in mind and is only useful for strings with just 10 numbers with perhaps some formatting characters, or perhaps no formatting characters at all (just 10 numbers). As such I would recomend this solution only for semi-automatic applications. I Personally prefer to store numbers as just 10 numbers without formatting characters, but also want to be able to convert or clean phone numbers to the standard format normal people and apps/phones will recognize instantly at will.

I came across this post looking for something I could use with a text cleaner app that has PCRE Regex capabilities (but no java functions). I will post this here for people who could use a simple pure Regex solution that could work in a variety of text editors, cleaners, expanders, or even some clipboard managers. I personally use Sublime and TextSoap. This solution was made for Text Soap as it lives in the menu bar and provides a drop-down menu where you can trigger text manipulation actions on what is selected by the cursor or what's in the clipboard.

My approach is essentially two substitution/search and replace regexes. Each substitution search and replace involves two regexes, one for search and one for replace.

Substitution/ Search & Replace #1

  • The first substitution/ search & replace strips non-numeric numbers from an otherwise 10-digit number to a 10-digit string.

First Substitution/ Search Regex: \D

  • This search string matches all characters that is not a digit.

First Substitution/ Replace Regex: "" (nothing, not even a space)

  • Leave the substitute field completely blank, no white space should exist including spaces. This will result in all matched non-digit characters being deleted. You should have gone in with 10 digits + formatting characters prior this operation and come out with 10 digits sans formatting characters.

Substitution/ Search & Replace #2

  • The second substitution/search and replace search part of the operation captures groups for area code $1, a capture group for the second set of three numbers $2, and the last capture group for the last set of four numbers $3. The regex for the substitute portion of the operation inserts US phone number formatting in between the captured group of digits.

Second Substitution/ Search Regex: (\d{3})(\d{3})(\d{4})

Second Substitution/ Replace Regex: \($1\) $2\-$3

  • The backslash \ escapes the special characters (, ) , (<-whitespace), and - since we are inserting them between our captured numbers in capture groups $1, $2, & $3 for US phone number formatting purposes.

  • In TextSoap I created a custom cleaner that includes the two substitution operation actions, so in practice it feels identical to executing a script. I'm sure this solution could be improved but I expect complexity to go up quite a bit. An improved version of this solution is welcomed as a learning experience if anyone wants to add to this.

What's the difference between SCSS and Sass?

The Sass .sass file is visually different from .scss file, e.g.

Example.sass - sass is the older syntax

$color: red

=my-border($color)
  border: 1px solid $color

body
  background: $color
  +my-border(green)

Example.scss - sassy css is the new syntax as of Sass 3

$color: red;

@mixin my-border($color) {
  border: 1px solid $color;
}

body {
  background: $color;
  @include my-border(green);
}

Any valid CSS document can be converted to Sassy CSS (SCSS) simply by changing the extension from .css to .scss.

How can I check if a file exists in Perl?

Test whether something exists at given path using the -e file-test operator.

print "$base_path exists!\n" if -e $base_path;

However, this test is probably broader than you intend. The code above will generate output if a plain file exists at that path, but it will also fire for a directory, a named pipe, a symlink, or a more exotic possibility. See the documentation for details.

Given the extension of .TGZ in your question, it seems that you expect a plain file rather than the alternatives. The -f file-test operator asks whether a path leads to a plain file.

print "$base_path is a plain file!\n" if -f $base_path;

The perlfunc documentation covers the long list of Perl's file-test operators that covers many situations you will encounter in practice.

  • -r
    File is readable by effective uid/gid.
  • -w
    File is writable by effective uid/gid.
  • -x
    File is executable by effective uid/gid.
  • -o
    File is owned by effective uid.
  • -R
    File is readable by real uid/gid.
  • -W
    File is writable by real uid/gid.
  • -X
    File is executable by real uid/gid.
  • -O
    File is owned by real uid.
  • -e
    File exists.
  • -z
    File has zero size (is empty).
  • -s
    File has nonzero size (returns size in bytes).
  • -f
    File is a plain file.
  • -d
    File is a directory.
  • -l
    File is a symbolic link (false if symlinks aren’t supported by the file system).
  • -p
    File is a named pipe (FIFO), or Filehandle is a pipe.
  • -S
    File is a socket.
  • -b
    File is a block special file.
  • -c
    File is a character special file.
  • -t
    Filehandle is opened to a tty.
  • -u
    File has setuid bit set.
  • -g
    File has setgid bit set.
  • -k
    File has sticky bit set.
  • -T
    File is an ASCII or UTF-8 text file (heuristic guess).
  • -B
    File is a “binary” file (opposite of -T).
  • -M
    Script start time minus file modification time, in days.
  • -A
    Same for access time.
  • -C
    Same for inode change time (Unix, may differ for other platforms)

Converting HTML to PDF using PHP?

If you wish to create a pdf from php, pdflib will help you (as some others suggested).

Else, if you want to convert an HTML page to PDF via PHP, you'll find a little trouble outta here.. For 3 years I've been trying to do it as best as I can.

So, the options I know are:

DOMPDF : php class that wraps the html and builds the pdf. Works good, customizable (if you know php), based on pdflib, if I remember right it takes even some CSS. Bad news: slow when the html is big or complex.

HTML2PS: same as DOMPDF, but this one converts first to a .ps (ghostscript) file, then, to whatever format you need (pdf, jpg, png). For me is little better than dompdf, but has the same speed problem.. but, better compatibility with CSS.

Those two are php classes, but if you can install some software on the server, and access it throught passthru() or system(), give a look to these too:

wkhtmltopdf: based on webkit (safari's wrapper), is really fast and powerful.. seems like this is the best one (atm) for converting html pages to pdf on the fly; taking only 2 seconds for a 3 page xHTML document with CSS2. It is a recent project, anyway, the google.code page is often updated.

htmldoc : This one is a tank, it never really stops/crashes.. the project looks dead since 2007, but anyway if you don't need CSS compatibility this can be nice for you.

How to set the project name/group/version, plus {source,target} compatibility in the same file?

I found the solution to a similar problem. I am using Gradle 1.11 (as April, 2014). The project name can be changed directly in settings.gradle file as following:

  rootProject.name='YourNewName'

This takes care of uploading to repository (Artifactory w/ its plugin for me) with the correct artifactId.

Creating the Singleton design pattern in PHP5

Here's my example that provides ability to call as $var = new Singleton() and also creating 3 variables to test if it creates new object:

class Singleton{

    private static $data;

    function __construct(){
        if ($this::$data == null){
            $this->makeSingleton();
        }
        echo "<br/>".$this::$data;
    }

    private function makeSingleton(){
        $this::$data = rand(0, 100);
    }

    public function change($new_val){
        $this::$data = $new_val;
    }

    public function printme(){
        echo "<br/>".$this::$data;
    }

}


$a = new Singleton();
$b = new Singleton();
$c = new Singleton();

$a->change(-2);
$a->printme();
$b->printme();

$d = new Singleton();
$d->printme();

How to change int into int64?

This is probably obvious, but simplest:

i64 := int64(23)

MongoDB Show all contents from all collections

Once you are in terminal/command line, access the database/collection you want to use as follows:

show dbs
use <db name>
show collections

choose your collection and type the following to see all contents of that collection:

db.collectionName.find()

More info here on the MongoDB Quick Reference Guide.

Directory-tree listing in Python

A recursive implementation

import os

def scan_dir(dir):
    for name in os.listdir(dir):
        path = os.path.join(dir, name)
        if os.path.isfile(path):
            print path
        else:
            scan_dir(path)

How to frame two for loops in list comprehension python

tags = [u'man', u'you', u'are', u'awesome']
entries = [[u'man', u'thats'],[ u'right',u'awesome']]

result = []
[result.extend(entry) for tag in tags for entry in entries if tag in entry]

print(result)

Output:

['man', 'thats', 'right', 'awesome']

Android Location Providers - GPS or Network Provider?

There are 3 location providers in Android.

They are:

gps –> (GPS, AGPS): Name of the GPS location provider. This provider determines location using satellites. Depending on conditions, this provider may take a while to return a location fix. Requires the permission android.permission.ACCESS_FINE_LOCATION.

network –> (AGPS, CellID, WiFi MACID): Name of the network location provider. This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION.

passive –> (CellID, WiFi MACID): A special location provider for receiving locations without actually initiating a location fix. This provider can be used to passively receive location updates when other applications or services request them without actually requesting the locations yourself. This provider will return locations generated by other providers. Requires the permission android.permission.ACCESS_FINE_LOCATION, although if the GPS is not enabled this provider might only return coarse fixes. This is what Android calls these location providers, however, the underlying technologies to make this stuff work is mapped to the specific set of hardware and telco provided capabilities (network service).

The best way is to use the “network” or “passive” provider first, and then fallback on “gps”, and depending on the task, switch between providers. This covers all cases, and provides a lowest common denominator service (in the worst case) and great service (in the best case).

enter image description here

Article Reference : Android Location Providers - gps, network, passive By Nazmul Idris

Code Reference : https://stackoverflow.com/a/3145655/28557

-----------------------Update-----------------------

Now Android have Fused location provider

The Fused Location Provider intelligently manages the underlying location technology and gives you the best location according to your needs. It simplifies ways for apps to get the user’s current location with improved accuracy and lower power usage

Fused location provider provide three ways to fetch location

  1. Last Location: Use when you want to know current location once.
  2. Request Location using Listener: Use when application is on screen / frontend and require continues location.
  3. Request Location using Pending Intent: Use when application in background and require continues location.

References :

Official site : http://developer.android.com/google/play-services/location.html

Fused location provider example: GIT : https://github.com/kpbird/fused-location-provider-example

http://blog.lemberg.co.uk/fused-location-provider

--------------------------------------------------------

How to execute an external program from within Node.js?

The simplest way is:

const { exec } = require("child_process")
exec('yourApp').unref()

unref is necessary to end your process without waiting for "yourApp"

Here are the exec docs

Open a file with Notepad in C#

You need System.Diagnostics.Process.Start().

The simplest example:

Process.Start("notepad.exe", fileName);

More Generic Approach:

Process.Start(fileName);

The second approach is probably a better practice as this will cause the windows Shell to open up your file with it's associated editor. Additionally, if the file specified does not have an association, it'll use the Open With... dialog from windows.

Note to those in the comments, thankyou for your input. My quick n' dirty answer was slightly off, i've updated the answer to reflect the correct way.

How do I find a list of Homebrew's installable packages?

From the man page:

search, -S text|/text/
Perform a substring search of formula names for text. If text is surrounded with slashes,
then it is interpreted as a regular expression. If no search term is given,
all available formula are displayed.

For your purposes, brew search will suffice.

zsh compinit: insecure directories

  1. run compaudit and it will give you a list of directories it thinks are insecure

  2. sudo chown -R username:root target_directory

  3. sudo chmod -R 755 target_directory

Can a website detect when you are using Selenium with chromedriver?

Firefox is said to set window.navigator.webdriver === true if working with a webdriver. That was according to one of the older specs (e.g.: archive.org) but I couldn't find it in the new one except for some very vague wording in the appendices.

A test for it is in the selenium code in the file fingerprint_test.js where the comment at the end says "Currently only implemented in firefox" but I wasn't able to identify any code in that direction with some simple greping, neither in the current (41.0.2) Firefox release-tree nor in the Chromium-tree.

I also found a comment for an older commit regarding fingerprinting in the firefox driver b82512999938 from January 2015. That code is still in the Selenium GIT-master downloaded yesterday at javascript/firefox-driver/extension/content/server.js with a comment linking to the slightly differently worded appendix in the current w3c webdriver spec.

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

Boundary Control Entity pattern have two versions:
- old structural, described at 127 (entity as an data model elements, control as an functions, boundary as an application interface)
- new object pattern


As an object pattern:
- Boundary is an interface for "other world"
- Control in an any internal logic (like a service in DDD pattern)
- Entity is an an persistence serwis for objects (like a repository in DDD pattern).
All classes have operations (see Fowler anemic domain model anti-pattern)
All of them is an Model component in MVC pattern. The rules:
- Only Boundary provide services for the "other world"
- Boundary can call only to Controll
- Control can call anybody
- Entity can't call anybody (!), only be called.

jz

How to navigate back to the last cursor position in Visual Studio Code?

As an alternative to the keyboard shortcuts, here's an extension named "Back and Forward buttons" that adds the forward and back buttons to the status bar:

https://marketplace.visualstudio.com/items?itemName=grimmer.vscode-back-forward-button

Android charting libraries

AchartEngine

You can create a plethora of different chart types relatively quickly with loads of customizable options.

Auto Generate Database Diagram MySQL

phpMyAdmin has what you are looking for (for many years now): It takes a small bit of configuration, but gives you additional benefits too: http://www.phpmyadmin.net/documentation/#pmadb

Measuring elapsed time with the Time module

For users that want better formatting,

import time
start_time = time.time()
# your script
elapsed_time = time.time() - start_time
time.strftime("%H:%M:%S", time.gmtime(elapsed_time))

will print out, for 2 seconds:

'00:00:02'

and for 7 minutes one second:

'00:07:01'

note that the minimum time unit with gmtime is seconds. If you need microseconds consider the following:

import datetime
start = datetime.datetime.now()
# some code
end = datetime.datetime.now()
elapsed = end - start
print(elapsed)
# or
print(elapsed.seconds,":",elapsed.microseconds) 

strftime documentation

Create Carriage Return in PHP String?

Carriage return is "\r". Mind the double quotes!

I think you want "\r\n" btw to put a line break in your text so it will be rendered correctly in different operating systems.

  • Mac: \r
  • Linux/Unix: \n
  • Windows: \r\n

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IList'

SonarQube reported Return an empty collection instead of null. and I had a problem with the error with casting as in the title of this question. I was able to get rid of both only using return XYZ.ToList().AsQueryable(); in a method with IQueryable like so:

public IQueryable<SomeType> MethodName (...) {
  IQueryable<SomeType> XYZ;
  ...
  return XYZ.ToList().AsQueryable();
}

Hope so it helps for those in a similar scenario(s).

Accuracy Score ValueError: Can't Handle mix of binary and continuous target

I was facing the same issue.The dtypes of y_test and y_pred were different. Make sure that the dtypes are same for both. The dtypes of y_test and y_pred were different

Page Redirect after X seconds wait using JavaScript

You actually need to pass a function inside the window.setTimeout() which you want to execute after 5000 milliseconds, like this:

$(document).ready(function () {
    // Handler for .ready() called.
    window.setTimeout(function () {
        location.href = "https://www.google.co.in";
    }, 5000);
});

For More info: .setTimeout()

How to force composer to reinstall a library?

As user @aaracrr pointed out in a comment on another answer probably the best answer is to re-require the package with the same version constraint.

ie.

composer require vendor/package

or specifying a version constraint

composer require vendor/package:^1.0.0

How to avoid "StaleElementReferenceException" in Selenium?

In my project I introduced a notion of StableWebElement. It is a wrapper for WebElement which is able to detect if element is Stale and find a new reference to the original element. I have added a helper methods to locating elements which return StableWebElement instead of WebElement and the problem with StaleElementReference disappeared.

public static IStableWebElement FindStableElement(this ISearchContext context, By by)
{
    var element = context.FindElement(by);
    return new StableWebElement(context, element, by, SearchApproachType.First);
} 

The code in C# is available on my project's page but it could be easily ported to java https://github.com/cezarypiatek/Tellurium/blob/master/Src/MvcPages/SeleniumUtils/StableWebElement.cs

Difference between a Structure and a Union

The uses of union Unions are used frequently when specialized type conversations are needed. To get an idea of the usefulness of union. The c/c standard library defines no function specifically designed to write short integers to a file. Using fwrite() incurs encurs excessive overhead for simple operation. However using a union you can easily create a function which writes binary of a short integer to a file one byte at a time. I assume that short integers are 2 byte long

THE EXAMPLE:

#include<stdio.h>
union pw {
short int i;
char ch[2];
};
int putw(short int num, FILE *fp);
int main (void)
{
FILE *fp;
fp fopen("test.tmp", "wb ");
putw(1000, fp); /* write the value 1000 as an integer*/
fclose(fp);
return 0;
}
int putw(short int num, FILE *fp)
{
pw word;
word.i = num;
putc(word.c[0] , fp);
return putc(word.c[1] , fp);
}    

although putw() i called with short integer, it was possble to use putc() and fwrite(). But i wanted to show an example to dominstrate how a union can be used

Programmatically navigate using React router

React Router v5.1.0 with hooks

There is a new useHistory hook in React Router >5.1.0 if you are using React >16.8.0 and functional components.

import { useHistory } from "react-router-dom";

function HomeButton() {
  const history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

React Router v4

With v4 of React Router, there are three approaches that you can take to programmatic routing within components.

  1. Use the withRouter higher-order component.
  2. Use composition and render a <Route>
  3. Use the context.

React Router is mostly a wrapper around the history library. history handles interaction with the browser's window.history for you with its browser and hash histories. It also provides a memory history which is useful for environments that don't have a global history. This is particularly useful in mobile app development (react-native) and unit testing with Node.

A history instance has two methods for navigating: push and replace. If you think of the history as an array of visited locations, push will add a new location to the array and replace will replace the current location in the array with the new one. Typically you will want to use the push method when you are navigating.

In earlier versions of React Router, you had to create your own history instance, but in v4 the <BrowserRouter>, <HashRouter>, and <MemoryRouter> components will create a browser, hash, and memory instances for you. React Router makes the properties and methods of the history instance associated with your router available through the context, under the router object.

1. Use the withRouter higher-order component

The withRouter higher-order component will inject the history object as a prop of the component. This allows you to access the push and replace methods without having to deal with the context.

import { withRouter } from 'react-router-dom'
// this also works with react-router-native

const Button = withRouter(({ history }) => (
  <button
    type='button'
    onClick={() => { history.push('/new-location') }}
  >
    Click Me!
  </button>
))

2. Use composition and render a <Route>

The <Route> component isn't just for matching locations. You can render a pathless route and it will always match the current location. The <Route> component passes the same props as withRouter, so you will be able to access the history methods through the history prop.

import { Route } from 'react-router-dom'

const Button = () => (
  <Route render={({ history}) => (
    <button
      type='button'
      onClick={() => { history.push('/new-location') }}
    >
      Click Me!
    </button>
  )} />
)

3. Use the context*

But you probably should not

The last option is one that you should only use if you feel comfortable working with React's context model (React's Context API is stable as of v16).

const Button = (props, context) => (
  <button
    type='button'
    onClick={() => {
      // context.history.push === history.push
      context.history.push('/new-location')
    }}
  >
    Click Me!
  </button>
)

// you need to specify the context type so that it
// is available within the component
Button.contextTypes = {
  history: React.PropTypes.shape({
    push: React.PropTypes.func.isRequired
  })
}

1 and 2 are the simplest choices to implement, so for most use cases, they are your best bets.

JavaScript click event listener on class

Yow can use querySelectorAll to select all the classes and loop through them to assign the eventListener. The if condition checks if it contains the class name.

const arrClass = document.querySelectorAll(".className");
for (let i of arrClass) {
  i.addEventListener("click", (e) => {
    if (e.target.classList.contains("className")) {
        console.log("Perfrom Action")
    }
  })
}

How do I test a single file using Jest?

At this time, I did it by using:

yarn test TestFileName.spec.js

You shouldn't put the complete path. That works for me on a Windows 10 machine.

Why can't I shrink a transaction log file, even after backup?

I know this is a few years old, but wanted to add some info.

I found on very large logs, specifically when the DB was not set to backup transaction logs (logs were very big), the first backup of the logs would not set log_reuse_wait_desc to nothing but leave the status as still backing up. This would block the shrink. Running the backup a second time properly reset the log_reuse_wait_desc to NOTHING, allowing the shrink to process.

Turn a string into a valid filename?

Keep in mind, there are actually no restrictions on filenames on Unix systems other than

  • It may not contain \0
  • It may not contain /

Everything else is fair game.

$ touch "
> even multiline
> haha
> ^[[31m red ^[[0m
> evil"
$ ls -la 
-rw-r--r--       0 Nov 17 23:39 ?even multiline?haha??[31m red ?[0m?evil
$ ls -lab
-rw-r--r--       0 Nov 17 23:39 \neven\ multiline\nhaha\n\033[31m\ red\ \033[0m\nevil
$ perl -e 'for my $i ( glob(q{./*even*}) ){ print $i; } '
./
even multiline
haha
 red 
evil

Yes, i just stored ANSI Colour Codes in a file name and had them take effect.

For entertainment, put a BEL character in a directory name and watch the fun that ensues when you CD into it ;)

How to delete last character from a string using jQuery?

Why use jQuery for this?

str = "123-4"; 
alert(str.substring(0,str.length - 1));

Of course if you must:

Substr w/ jQuery:

//example test element
 $(document.createElement('div'))
    .addClass('test')
    .text('123-4')
    .appendTo('body');

//using substring with the jQuery function html
alert($('.test').html().substring(0,$('.test').html().length - 1));

Generate a Hash from string in Javascript

I have combined the two solutions (users esmiralha and lordvlad) to get a function that should be faster for browsers that support the js function reduce() and still compatible with old browsers:

String.prototype.hashCode = function() {

    if (Array.prototype.reduce) {
        return this.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);   
    } else {

        var hash = 0, i, chr, len;
        if (this.length == 0) return hash;
        for (i = 0, len = this.length; i < len; i++) {
        chr   = this.charCodeAt(i);
        hash  = ((hash << 5) - hash) + chr;
        hash |= 0; // Convert to 32bit integer
        }
        return hash;
    }
};

Example:

my_string = 'xyz';
my_string.hashCode();

How to cast an object in Objective-C

Sure, the syntax is exactly the same as C - NewObj* pNew = (NewObj*)oldObj;

In this situation you may wish to consider supplying this list as a parameter to the constructor, something like:

// SelectionListViewController
-(id) initWith:(SomeListClass*)anItemList
{
  self = [super init];

  if ( self ) {
    [self setList: anItemList];
  }

  return self;
}

Then use it like this:

myEditController = [[SelectionListViewController alloc] initWith: listOfItems];

Convert file path to a file URI?

UrlCreateFromPath to the rescue! Well, not entirely, as it doesn't support extended and UNC path formats, but that's not so hard to overcome:

public static Uri FileUrlFromPath(string path)
{
    const string prefix = @"\\";
    const string extended = @"\\?\";
    const string extendedUnc = @"\\?\UNC\";
    const string device = @"\\.\";
    const StringComparison comp = StringComparison.Ordinal;

    if(path.StartsWith(extendedUnc, comp))
    {
        path = prefix+path.Substring(extendedUnc.Length);
    }else if(path.StartsWith(extended, comp))
    {
        path = prefix+path.Substring(extended.Length);
    }else if(path.StartsWith(device, comp))
    {
        path = prefix+path.Substring(device.Length);
    }

    int len = 1;
    var buffer = new StringBuilder(len);
    int result = UrlCreateFromPath(path, buffer, ref len, 0);
    if(len == 1) Marshal.ThrowExceptionForHR(result);

    buffer.EnsureCapacity(len);
    result = UrlCreateFromPath(path, buffer, ref len, 0);
    if(result == 1) throw new ArgumentException("Argument is not a valid path.", "path");
    Marshal.ThrowExceptionForHR(result);
    return new Uri(buffer.ToString());
}

[DllImport("shlwapi.dll", CharSet=CharSet.Auto, SetLastError=true)]
static extern int UrlCreateFromPath(string path, StringBuilder url, ref int urlLength, int reserved);

In case the path starts with with a special prefix, it gets removed. Although the documentation doesn't mention it, the function outputs the length of the URL even if the buffer is smaller, so I first obtain the length and then allocate the buffer.

Some very interesting observation I had is that while "\\device\path" is correctly transformed to "file://device/path", specifically "\\localhost\path" is transformed to just "file:///path".

The WinApi function managed to encode special characters, but leaves Unicode-specific characters unencoded, unlike the Uri construtor. In that case, AbsoluteUri contains the properly encoded URL, while OriginalString can be used to retain the Unicode characters.

How to specify the default error page in web.xml?

You can also specify <error-page> for exceptions using <exception-type>, eg below:

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/errorpages/exception.html</location>
</error-page>

Or map a error code using <error-code>:

<error-page>
    <error-code>404</error-code>
    <location>/errorpages/404error.html</location>
</error-page>

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

Can I use a binary literal in C or C++?

You can use a bitset

bitset<8> b(string("00010000"));
int i = (int)(bs.to_ulong());
cout<<i;

How to get the index of a maximum element in a NumPy array along one axis

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,3,1]])
>>> i,j = np.unravel_index(a.argmax(), a.shape)
>>> a[i,j]
4

PHP Sort a multidimensional array by element containing date

You can simply solve this problem using usort() with callback function. No need to write any custom function.

$your_date_field_name = 'datetime';
usort($your_given_array_name, function ($a, $b) use (&$your_date_field_name) {
    return strtotime($a[$your_date_field_name]) - strtotime($b[$your_date_field_name]);
});

Check if a variable exists in a list in Bash

IMHO easiest solution is to prepend and append the original string with a space and check against a regex with [[ ]]

haystack='foo bar'
needle='bar'

if [[ " $haystack " =~ .*\ $needle\ .* ]]; then
    ...
fi

this will not be false positive on values with values containing the needle as a substring, e.g. with a haystack foo barbaz.

(The concept is shamelessly stolen form JQuery's hasClass()-Method)

Where does R store packages?

Thanks for the direction from the above two answerers. James Thompson's suggestion worked best for Windows users.

  1. Go to where your R program is installed. This is referred to as R_Home in the literature. Once you find it, go to the /etc subdirectory.

    C:\R\R-2.10.1\etc
    
  2. Select the file in this folder named Rprofile.site. I open it with VIM. You will find this is a bare-bones file with less than 20 lines of code. I inserted the following inside the code:

    # my custom library path
    .libPaths("C:/R/library")
    

    (The comment added to keep track of what I did to the file.)

  3. In R, typing the .libPaths() function yields the first target at C:/R/Library

NOTE: there is likely more than one way to achieve this, but other methods I tried didn't work for some reason.

Stacked bar chart

You will need to melt your dataframe to get it into the so-called long format:

require(reshape2)
sample.data.M <- melt(sample.data)

Now your field values are represented by their own rows and identified through the variable column. This can now be leveraged within the ggplot aesthetics:

require(ggplot2)
c <- ggplot(sample.data.M, aes(x = Rank, y = value, fill = variable))
c + geom_bar(stat = "identity")

Instead of stacking you may also be interested in showing multiple plots using facets:

c <- ggplot(sample.data.M, aes(x = Rank, y = value))
c + facet_wrap(~ variable) + geom_bar(stat = "identity")

How to run java application by .bat file

Simply create a .bat file with the following lines in it:

@ECHO OFF
set CLASSPATH=.
set CLASSPATH=%CLASSPATH%;path/to/needed/jars/my.jar

%JAVA_HOME%\bin\java -Xms128m -Xmx384m -Xnoclassgc ro.my.class.MyClass

jQuery .val change doesn't change input value

Changing the value property does not change the defaultValue. In the code (retrieved with .html() or innerHTML) the value attribute will contain the defaultValue, not the value property.

Does the target directory for a git clone have to match the repo name?

Yes, it is possible:

git clone https://github.com/pitosalas/st3_packages Packages 

You can specify the local root directory when using git clone.

<directory> 

The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
Cloning into an existing directory is only allowed if the directory is empty.


As Chris comments, you can then rename that top directory.
Git only cares about the .git within said top folder, which you can get with various commands:

git rev-parse --show-toplevel git rev-parse --git-dir 

ssh: Could not resolve hostname github.com: Name or service not known; fatal: The remote end hung up unexpectedly

Recently, I have seen this problem too. Below, you have my solution:

  1. ping github.com, if ping failed. it is DNS error.
  2. sudo vim /etc/resolv.conf, the add: nameserver 8.8.8.8 nameserver 8.8.4.4

Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart or fix it up


I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):

ssh -T [email protected]

Upon receiving a successful response, I could fetch/push to the repo with ssh.

I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.

html select only one checkbox in a group

There are already a few answers to this based on pure JS but none of them are quite as concise as I would like them to be.

Here is my solution based on using name tags (as with radio buttons) and a few lines of javascript.

_x000D_
_x000D_
function onlyOne(checkbox) {_x000D_
    var checkboxes = document.getElementsByName('check')_x000D_
    checkboxes.forEach((item) => {_x000D_
        if (item !== checkbox) item.checked = false_x000D_
    })_x000D_
}
_x000D_
<input type="checkbox" name="check" onclick="onlyOne(this)">_x000D_
<input type="checkbox" name="check" onclick="onlyOne(this)">_x000D_
<input type="checkbox" name="check" onclick="onlyOne(this)">_x000D_
<input type="checkbox" name="check" onclick="onlyOne(this)">
_x000D_
_x000D_
_x000D_

How to serve an image using nodejs

You should use the express framework.

npm install express

and then

var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
app.listen(8080);

and then the URL localhost:8080/images/logo.gif should work.

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

How to add Active Directory user group as login in SQL Server

You can use T-SQL:

use master
GO
CREATE LOGIN [NT AUTHORITY\LOCALSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
CREATE LOGIN [NT AUTHORITY\NETWORKSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName

I use this as a part of restore from production server to testing machine:

USE master
GO
ALTER DATABASE yourDbName SET OFFLINE WITH ROLLBACK IMMEDIATE
RESTORE DATABASE yourDbName FROM DISK = 'd:\DropBox\backup\myDB.bak'
ALTER DATABASE yourDbName SET ONLINE
GO
CREATE LOGIN [NT AUTHORITY\LOCALSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
CREATE LOGIN [NT AUTHORITY\NETWORKSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO

You will need to use localized name of services in case of German or French Windows, see How to create a SQL Server login for a service account on a non-English Windows?

How do I redirect in expressjs while passing some context?

Here s what I suggest without using any other dependency , just node and express, use app.locals, here s an example :

    app.get("/", function(req, res) {
        var context = req.app.locals.specialContext;
        req.app.locals.specialContext = null;
        res.render("home.jade", context); 
        // or if you are using ejs
        res.render("home", {context: context}); 
    });

    function middleware(req, res, next) {
        req.app.locals.specialContext = * your context goes here *
        res.redirect("/");
    }

String comparison using '==' vs. 'strcmp()'

strcmp() and === are both case sensitive but === is much faster

sample code: http://snipplr.com/view/758/

Generating Random Passwords

Added some supplemental code to the accepted answer. It improves upon answers just using Random and allows for some password options. I also liked some of the options from the KeePass answer but did not want to include the executable in my solution.

private string RandomPassword(int length, bool includeCharacters, bool includeNumbers, bool includeUppercase, bool includeNonAlphaNumericCharacters, bool includeLookAlikes)
{
    if (length < 8 || length > 128) throw new ArgumentOutOfRangeException("length");
    if (!includeCharacters && !includeNumbers && !includeNonAlphaNumericCharacters) throw new ArgumentException("RandomPassword-Key arguments all false, no values would be returned");

    string pw = "";
    do
    {
        pw += System.Web.Security.Membership.GeneratePassword(128, 25);
        pw = RemoveCharacters(pw, includeCharacters, includeNumbers, includeUppercase, includeNonAlphaNumericCharacters, includeLookAlikes);
    } while (pw.Length < length);

    return pw.Substring(0, length);
}

private string RemoveCharacters(string passwordString, bool includeCharacters, bool includeNumbers, bool includeUppercase, bool includeNonAlphaNumericCharacters, bool includeLookAlikes)
{
    if (!includeCharacters)
    {
        var remove = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
        foreach (string r in remove)
        {
            passwordString = passwordString.Replace(r, string.Empty);
            passwordString = passwordString.Replace(r.ToUpper(), string.Empty);
        }
    }

    if (!includeNumbers)
    {
        var remove = new string[] { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
        foreach (string r in remove)
            passwordString = passwordString.Replace(r, string.Empty);
    }

    if (!includeUppercase)
        passwordString = passwordString.ToLower();

    if (!includeNonAlphaNumericCharacters)
    {
        var remove = new string[] { "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "_", "+", "=", "{", "}", "[", "]", "|", "\\", ":", ";", "<", ">", "/", "?", "." };
        foreach (string r in remove)
            passwordString = passwordString.Replace(r, string.Empty);
    }

    if (!includeLookAlikes)
    {
        var remove = new string[] { "(", ")", "0", "O", "o", "1", "i", "I", "l", "|", "!", ":", ";" };
        foreach (string r in remove)
            passwordString = passwordString.Replace(r, string.Empty);
    }

    return passwordString;
}

This was the first link when I searched for generating random passwords and the following is out of scope for the current question but might be important to consider.

  • Based upon the assumption that System.Web.Security.Membership.GeneratePassword is cryptographically secure with a minimum of 20% of the characters being Non-Alphanumeric.
  • Not sure if removing characters and appending strings is considered good practice in this case and provides enough entropy.
  • Might want to consider implementing in some way with SecureString for secure password storage in memory.

What does LINQ return when the results are empty

var lst = new List<int>() { 1, 2, 3 };
var ans = lst.Where( i => i > 3 );

(ans == null).Dump();  // False
(ans.Count() == 0 ).Dump();  // True

(Dump is from LinqPad)

How do I create a crontab through a script

It is an approach to incrementally add the cron job:

  ssh USER_NAME@$PRODUCT_IP nohup "echo '*/2 * * * * ping -c2 PRODUCT_NAME.com >> /var/www/html/test.html' | crontab -u USER_NAME -"