Programs & Examples On #Ireport

iReport is a GUI designer for JasperReports and JasperReports Server. iReport Designer allows you to create sophisticated layouts containing charts, images, subreports, crosstabs and much more. You can access your data through JDBC, TableModels, JavaBeans, XML, Hibernate, CSV, and custom sources, then publish your reports as PDF, RTF, XML, XLS, CSV, HTML, XHTML, text, DOCX, or OpenOffice.

How do I compile jrxml to get jasper?

  1. Open your .jrxml file in iReport Designer.
  2. Open the Report Inspector (Window -> Report Inspector).
  3. Right-click your report name on the top of the inspector and then click "Compile Report".

You can also Preview your report so it's automatically compiled.

How to sum all values in a column in Jaspersoft iReport Designer?

It is quite easy to solve your task. You should create and use a new variable for summing values of the "Doctor Payment" column.

In your case the variable can be declared like this:

<variable name="total" class="java.lang.Integer" calculation="Sum">
    <variableExpression><![CDATA[$F{payment}]]></variableExpression>
</variable>
  • the Calculation type is Sum;
  • the Reset type is Report;
  • the Variable expression is $F{payment}, where $F{payment} is the name of a field contains sum (Doctor Payment).

The working example.

CSV datasource:

doctor_id,payment
A1,123
B1,223
C2,234
D3,678
D1,343

The template:

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport ...>
    <queryString>
        <![CDATA[]]>
    </queryString>
    <field name="doctor_id" class="java.lang.String"/>
    <field name="payment" class="java.lang.Integer"/>
    <variable name="total" class="java.lang.Integer" calculation="Sum">
        <variableExpression><![CDATA[$F{payment}]]></variableExpression>
    </variable>
    <columnHeader>
        <band height="20" splitType="Stretch">
            <staticText>
                <reportElement x="0" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="10" isBold="true" isItalic="true"/>
                </textElement>
                <text><![CDATA[Doctor ID]]></text>
            </staticText>
            <staticText>
                <reportElement x="100" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement textAlignment="Center" verticalAlignment="Middle">
                    <font size="10" isBold="true" isItalic="true"/>
                </textElement>
                <text><![CDATA[Doctor Payment]]></text>
            </staticText>
        </band>
    </columnHeader>
    <detail>
        <band height="20" splitType="Stretch">
            <textField>
                <reportElement x="0" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{doctor_id}]]></textFieldExpression>
            </textField>
            <textField>
                <reportElement x="100" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement/>
                <textFieldExpression><![CDATA[$F{payment}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <summary>
        <band height="20">
            <staticText>
                <reportElement x="0" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement>
                    <font isBold="true"/>
                </textElement>
                <text><![CDATA[Total]]></text>
            </staticText>
            <textField>
                <reportElement x="100" y="0" width="100" height="20"/>
                <box leftPadding="10"/>
                <textElement>
                    <font isBold="true" isItalic="true"/>
                </textElement>
                <textFieldExpression><![CDATA[$V{total}]]></textFieldExpression>
            </textField>
        </band>
    </summary>
</jasperReport>

The result will be:

Generated report via iReport's preview


You can find a lot of info in the JasperReports Ultimate Guide.

iReport not starting using JRE 8

don't uninstall anything. a system with multiple versions of java works just fine. and you don't need to update your environment varables (e.g. java_home, path, etc..).

yes, ireports 3.6.1 needs java 7 (doesn't work with java 8).

all you have to do is edit C:\Program Files\Jaspersoft\iReport-nb-3.6.1\etc\ireport.conf:

# default location of JDK/JRE, can be overridden by using --jdkhome <dir> switch
jdkhome="C:/Program Files/Java/jdk1.7.0_45"

on linux (no spaces and standard file paths) its that much easier. keep your java 8 for other interesting projects...

await is only valid in async function

The current implementation of async / await only supports the await keyword inside of async functions Change your start function signature so you can use await inside start.

 var start = async function(a, b) {

 }

For those interested, the proposal for top-level await is currently in Stage 2: https://github.com/tc39/proposal-top-level-await

How to properly overload the << operator for an ostream?

Assuming that we're talking about overloading operator << for all classes derived from std::ostream to handle the Matrix class (and not overloading << for Matrix class), it makes more sense to declare the overload function outside the Math namespace in the header.

Use a friend function only if the functionality cannot be achieved via the public interfaces.

Matrix.h

namespace Math { 
    class Matrix { 
        //...
    };  
}
std::ostream& operator<<(std::ostream&, const Math::Matrix&);

Note that the operator overload is declared outside the namespace.

Matrix.cpp

using namespace Math;
using namespace std;

ostream& operator<< (ostream& os, const Matrix& obj) {
    os << obj.getXYZ() << obj.getABC() << '\n';
    return os;
}

On the other hand, if your overload function does need to be made a friend i.e. needs access to private and protected members.

Math.h

namespace Math {
    class Matrix {
        public:
            friend std::ostream& operator<<(std::ostream&, const Matrix&);
    };
}

You need to enclose the function definition with a namespace block instead of just using namespace Math;.

Matrix.cpp

using namespace Math;
using namespace std;

namespace Math {
    ostream& operator<<(ostream& os, const Matrix& obj) {
        os << obj.XYZ << obj.ABC << '\n';
        return os;
    }                 
}

open read and close a file in 1 line of code

with open('pagehead.section.htm')as f:contents=f.read()

How to add external JS scripts to VueJS Components

I have downloaded some HTML template that comes with custom js files and jquery. I had to attach those js to my app. and continue with Vue.

Found this plugin, it's a clean way to add external scripts both via CDN and from static files https://www.npmjs.com/package/vue-plugin-load-script

// local files
// you have to put your scripts into the public folder. 
// that way webpack simply copy these files as it is.
Vue.loadScript("/js/jquery-2.2.4.min.js")

// cdn
Vue.loadScript("https://maps.googleapis.com/maps/api/js")

saving a file (from stream) to disk using c#

if the data is already valid and already contains a pdf, word or image, then you could use a StreamWriter and save it.

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

  1. Go and Check if a user is created or not if no please create a user by opening a file in /apache-tomcat-9.0.20/tomcat-users.xml add a line into it

    <user username="tomcat" password="tomcat" roles="admin-gui,manager-gui,manager-script" />

  2. Goto /apache-tomcat-9.0.20/webapps/manager/META-INF/ open context.xml comment everything in context tag example:

<Context antiResourceLocking="false" privileged="true" >
     <!--Valve className="org.apache.catalina.valves.RemoteAddrValve"
            allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" /-->
   </Context>

Cast to generic type in C#

The answer of @DanielPlaisted before generally works, but the generic method must be public or one must use BindingFlags.NonPublic | BindingFlags.Instance! Couldn't post it as a comment for lack of reputation.

How can I add a .npmrc file?

In MacOS Catalina 10.15.5 the .npmrc file path can be found at

/Users/<user-name>/.npmrc

Open in it in (for first time users, create a new file) any editor and copy-paste your token. Save it.

You are ready to go.

Note: As mentioned by @oligofren, the command npm config ls -l will npm configurations. You will get the .npmrc file from config parameter userconfig

In Swift how to call method with parameters on GCD main thread?

Here's the nicer (IMO) Swifty/Cocoa style syntax to achieve the same result as the other answers:

NSOperationQueue.mainQueue().addOperationWithBlock({
    // Your code here
})

Or you could grab the popular Async Swift library for even less code and more functionality:

Async.main {
    // Your code here
}

Javascript Date - set just the date, ignoring time?

If you don't mind creating an extra date object, you could try:

var tempDate = new Date(parseInt(item.timestamp, 10));
var visitDate = new Date (tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate());

I do something very similar to get a date of the current month without the time.

Calling a Variable from another Class

That would just be:

 Console.WriteLine(Variables.name);

and it needs to be public also:

public class Variables
{
   public static string name = "";
}

How do I remove an item from a stl vector with a certain value?

A shorter solution (which doesn't force you to repeat the vector name 4 times) would be to use Boost:

#include <boost/range/algorithm_ext/erase.hpp>

// ...

boost::remove_erase(vec, int_to_remove);

See http://www.boost.org/doc/libs/1_64_0/libs/range/doc/html/range/reference/algorithms/new/remove_erase.html

How to generate a random alpha-numeric string

Java supplies a way of doing this directly. If you don't want the dashes, they are easy to strip out. Just use uuid.replace("-", "")

import java.util.UUID;

public class randomStringGenerator {
    public static void main(String[] args) {
        System.out.println(generateString());
    }

    public static String generateString() {
        String uuid = UUID.randomUUID().toString();
        return "uuid = " + uuid;
    }
}

Output

uuid = 2d7428a6-b58c-4008-8575-f05549f16316

Reloading submodules in IPython

http://shawnleezx.github.io/blog/2015/08/03/some-notes-on-ipython-startup-script/

To avoid typing those magic function again and again, they could be put in the ipython startup script(Name it with .py suffix under .ipython/profile_default/startup. All python scripts under that folder will be loaded according to lexical order), which looks like the following:

from IPython import get_ipython
ipython = get_ipython()

ipython.magic("pylab")
ipython.magic("load_ext autoreload")
ipython.magic("autoreload 2")

jQuery-- Populate select from json

fiddle

var $select = $('#down'); 
$select.find('option').remove();  
$.each(temp,function(key, value) 
{
    $select.append('<option value=' + key + '>' + value + '</option>');
});

How to export SQL Server database to MySQL?

I had some data I had to get from mssql into mysql, had difficulty finding a solution. So what I did in the end (a bit of a long winded way to do it, but as a last resort it works) was:

  • Open the mssql database in sql server management studio express (I used 2005)
  • Open each table in turn and
  • Click the top left corner box to select whole table:

  • Copy data to clipboard (ctrl + v)

  • Open ms excel
  • Paste data from clipboard
  • Save excel file as .csv
  • Repeat the above for each table
  • You should now be able to import the data into mysql

Hope this helps

Win32Exception (0x80004005): The wait operation timed out

Look into re-indexing tables in your database.

You can first find out the fragmentation level - and if it's above 10% or so you could benefit from re-indexing. If it's very high it's likely this is creating a significant performance bottle neck.

http://blog.sqlauthority.com/2009/01/30/sql-server-2008-2005-rebuild-every-index-of-all-tables-of-database-rebuild-index-with-fillfactor/

This should be done regularly.

get list of pandas dataframe columns based on data type

use df.info(verbose=True) where df is a pandas datafarme, by default verbose=False

Disable vertical sync for glxgears

I found a solution that works in the intel card and in the nvidia card using Bumblebee.

> export vblank_mode=0
glxgears
...
optirun glxgears
...
export vblank_mode=1

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

Perhaps it is indirect to gdb (because it's an IDE), but my recommendations would be KDevelop. Being quite spoiled with Visual Studio's debugger (professionally at work for many years), I've so far felt the most comfortable debugging in KDevelop (as hobby at home, because I could not afford Visual Studio for personal use - until Express Edition came out). It does "look something similar to" Visual Studio compared to other IDE's I've experimented with (including Eclipse CDT) when it comes to debugging step-through, step-in, etc (placing break points is a bit awkward because I don't like to use mouse too much when coding, but it's not difficult).

How to add a custom right-click menu to a webpage?

According to the answers here and on other 'flows, I've made a version that looks like the one of Google Chrome, with css3 transition. JS Fiddle

Lets start eazy, since we have the js above on this page, we can worry about the css and layout. The layout that we will be using is an <a> element with a <img> element or a font awesome icon (<i class="fa fa-flag"></i>) and a <span> to show the keyboard shortcuts. So this is the structure:

<a href="#" onclick="doSomething()">
  <img src="path/to/image.gif" />
  This is a menu option
  <span>Ctrl + K</span>
</a>

We will put these in a div and show that div on the right-click. Let's style them like in Google Chrome, shall we?

#menu a {
  display: block;
  color: #555;
  text-decoration: no[...]

Now we will add the code from the accepted answer, and get the X and Y value of the cursor. To do this, we will use e.clientX and e.clientY. We are using client, so the menu div has to be fixed.

var i = document.getElementById("menu").style;
if (document.addEventListener) {
  document.addEventListener('contextmenu', function(e) {
    var posX = e.clientX;
    var posY = e.client[...]

And that is it! Just add the css transisions to fade in and out, and done!

_x000D_
_x000D_
var i = document.getElementById("menu").style;_x000D_
if (document.addEventListener) {_x000D_
  document.addEventListener('contextmenu', function(e) {_x000D_
    var posX = e.clientX;_x000D_
    var posY = e.clientY;_x000D_
    menu(posX, posY);_x000D_
    e.preventDefault();_x000D_
  }, false);_x000D_
  document.addEventListener('click', function(e) {_x000D_
    i.opacity = "0";_x000D_
    setTimeout(function() {_x000D_
      i.visibility = "hidden";_x000D_
    }, 501);_x000D_
  }, false);_x000D_
} else {_x000D_
  document.attachEvent('oncontextmenu', function(e) {_x000D_
    var posX = e.clientX;_x000D_
    var posY = e.clientY;_x000D_
    menu(posX, posY);_x000D_
    e.preventDefault();_x000D_
  });_x000D_
  document.attachEvent('onclick', function(e) {_x000D_
    i.opacity = "0";_x000D_
    setTimeout(function() {_x000D_
      i.visibility = "hidden";_x000D_
    }, 501);_x000D_
  });_x000D_
}_x000D_
_x000D_
function menu(x, y) {_x000D_
  i.top = y + "px";_x000D_
  i.left = x + "px";_x000D_
  i.visibility = "visible";_x000D_
  i.opacity = "1";_x000D_
}
_x000D_
body {_x000D_
  background: white;_x000D_
  font-family: sans-serif;_x000D_
  color: #5e5e5e;_x000D_
}_x000D_
_x000D_
#menu {_x000D_
  visibility: hidden;_x000D_
  opacity: 0;_x000D_
  position: fixed;_x000D_
  background: #fff;_x000D_
  color: #555;_x000D_
  font-family: sans-serif;_x000D_
  font-size: 11px;_x000D_
  -webkit-transition: opacity .5s ease-in-out;_x000D_
  -moz-transition: opacity .5s ease-in-out;_x000D_
  -ms-transition: opacity .5s ease-in-out;_x000D_
  -o-transition: opacity .5s ease-in-out;_x000D_
  transition: opacity .5s ease-in-out;_x000D_
  -webkit-box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1);_x000D_
  -moz-box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1);_x000D_
  box-shadow: 2px 2px 2px 0px rgba(143, 144, 145, 1);_x000D_
  padding: 0px;_x000D_
  border: 1px solid #C6C6C6;_x000D_
}_x000D_
_x000D_
#menu a {_x000D_
  display: block;_x000D_
  color: #555;_x000D_
  text-decoration: none;_x000D_
  padding: 6px 8px 6px 30px;_x000D_
  width: 250px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
#menu a img,_x000D_
#menu a i.fa {_x000D_
  height: 20px;_x000D_
  font-size: 17px;_x000D_
  width: 20px;_x000D_
  position: absolute;_x000D_
  left: 5px;_x000D_
  top: 2px;_x000D_
}_x000D_
_x000D_
#menu a span {_x000D_
  color: #BCB1B3;_x000D_
  float: right;_x000D_
}_x000D_
_x000D_
#menu a:hover {_x000D_
  color: #fff;_x000D_
  background: #3879D9;_x000D_
}_x000D_
_x000D_
#menu hr {_x000D_
  border: 1px solid #EBEBEB;_x000D_
  border-bottom: 0;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<h2>CSS3 and JAVASCRIPT custom menu.</h2>_x000D_
<em>Stephan Stanisic | Lisence free</em>_x000D_
<p>Right-click anywhere on this page to open the custom menu. Styled like the Google Chrome contextmenu. And yes, you can use <i class="fa fa-flag"></i>font-awesome</p>_x000D_
<p style="font-size: small">_x000D_
  <b>Lisence</b>_x000D_
  <br /> "THE PIZZA-WARE LICENSE" (Revision 42):_x000D_
  <br /> You can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a Pizza in return._x000D_
  <br />_x000D_
  <a style="font-size:xx-small" href="https://github.com/KLVN/UrbanDictionary_API#license">https://github.com/KLVN/UrbanDictionary_API#license</a>_x000D_
</p>_x000D_
<br />_x000D_
<br />_x000D_
<small>(The white body background is just because I hate the light blue editor background on the result on jsfiddle)</small>_x000D_
<div id="menu">_x000D_
  <a href="#">_x000D_
    <img src="http://puu.sh/nr60s/42df867bf3.png" /> AdBlock Plus <span>Ctrl + ?!</span>_x000D_
  </a>_x000D_
  <a href="#">_x000D_
    <img src="http://puu.sh/nr5Z6/4360098fc1.png" /> SNTX <span>Ctrl + ?!</span>_x000D_
  </a>_x000D_
  <hr />_x000D_
  <a href="#">_x000D_
    <i class="fa fa-fort-awesome"></i> Fort Awesome <span>Ctrl + ?!</span>_x000D_
  </a>_x000D_
  <a href="#">_x000D_
    <i class="fa fa-flag"></i> Font Awesome <span>Ctrl + ?!</span>_x000D_
  </a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Automatically accept all SDK licences

On Windows 10 opening cmd with administrator privileges and then typing cd C:\Program Files (x86)\Android\android-sdk\tools\bin\ and then sdkmanager --update worked for me. After that I just had to press "y" twice in order to accept the licenses.

When to use references vs. pointers

In my practice I personally settled down with one simple rule - Use references for primitives and values that are copyable/movable and pointers for objects with long life cycle.

For Node example I would definitely use

AddChild(Node* pNode);

Messagebox with input field

You can do it by making form and displaying it using ShowDialogBox....

Form.ShowDialog Method - Shows the form as a modal dialog box.

Example:

public void ShowMyDialogBox()
{
   Form2 testDialog = new Form2();

   // Show testDialog as a modal dialog and determine if DialogResult = OK.
   if (testDialog.ShowDialog(this) == DialogResult.OK)
   {
      // Read the contents of testDialog's TextBox.
      this.txtResult.Text = testDialog.TextBox1.Text;
   }
   else
   {
      this.txtResult.Text = "Cancelled";
   }
   testDialog.Dispose();
}

make script execution to unlimited

As @Peter Cullen answer mention, your script will meet browser timeout first. So its good idea to provide some log output, then flush(), but connection have buffer and you'll not see anything unless much output provided. Here are code snippet what helps provide reliable log:

set_time_limit(0);
...
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();
print "log message";
print "<!--"; print str_repeat (' ', 4000); print "-->"; flush();

Validate select box

Perhaps there is a shorter way but this works for me.

<script language='JavaScript' type='text/javascript'>
    function validateThisFrom(thisForm) {
        if (thisForm.FIELDNAME.value == "") {
            alert("Please make a selection");
            thisForm.FIELDNAME.focus();
            return false;
        }
        if (thisForm.FIELDNAME2.value == "") {
            alert("Please make a selection");
            thisForm.FIELDNAME2.focus();
            return false;
        }
    }
</script>
<form onSubmit="return validateThisFrom (this);">
    <select name="FIELDNAME" class="form-control">
        <option value="">- select -</option>
        <option value="value 1">Visible info of Value 1</option>
        <option value="value 2">Visible info of Value 2</option>
    </select>
    <select name="FIELDNAME2" class="form-control">
        <option value="">- select -</option>
        <option value="value 1">Visible info of Value 1</option>
        <option value="value 2">Visible info of Value 2</option>
    </select>
</form>

Prevent screen rotation on Android

Activity.java

@Override     
 public void onConfigurationChanged(Configuration newConfig) {       
        try {     
            super.onConfigurationChanged(newConfig);      
            if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {      
                // land      
            } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {      
               // port       
            }    
        } catch (Exception ex) {       
     }   

AndroidManifest.xml

 <application android:icon="@drawable/icon" android:label="@string/app_name">
  <activity android:name="QRCodeActivity" android:label="@string/app_name"
  android:screenOrientation="landscape" >
   <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

 </application>

Print all day-dates between two dates

import datetime

begin = datetime.date(2008, 8, 15)
end = datetime.date(2008, 9, 15)

next_day = begin
while True:
    if next_day > end:
        break
    print next_day
    next_day += datetime.timedelta(days=1)

MySQL Multiple Joins in one query?

I shared my experience of using two LEFT JOINS in a single SQL query.

I have 3 tables:

Table 1) Patient consists columns PatientID, PatientName

Table 2) Appointment consists columns AppointmentID, AppointmentDateTime, PatientID, DoctorID

Table 3) Doctor consists columns DoctorID, DoctorName


Query:

SELECT Patient.patientname, AppointmentDateTime, Doctor.doctorname

FROM Appointment 

LEFT JOIN Doctor ON Appointment.doctorid = Doctor.doctorId  //have doctorId column common

LEFT JOIN Patient ON Appointment.PatientId = Patient.PatientId      //have patientid column common

WHERE Doctor.Doctorname LIKE 'varun%' // setting doctor name by using LIKE

AND Appointment.AppointmentDateTime BETWEEN '1/16/2001' AND '9/9/2014' //comparison b/w dates 

ORDER BY AppointmentDateTime ASC;  // getting data as ascending order

I wrote the solution to get date format like "mm/dd/yy" (under my name "VARUN TEJ REDDY")

Accessing items in an collections.OrderedDict by index

If its an OrderedDict() you can easily access the elements by indexing by getting the tuples of (key,value) pairs as follows

>>> import collections
>>> d = collections.OrderedDict()
>>> d['foo'] = 'python'
>>> d['bar'] = 'spam'
>>> d.items()
[('foo', 'python'), ('bar', 'spam')]
>>> d.items()[0]
('foo', 'python')
>>> d.items()[1]
('bar', 'spam')

Note for Python 3.X

dict.items would return an iterable dict view object rather than a list. We need to wrap the call onto a list in order to make the indexing possible

>>> items = list(d.items())
>>> items
[('foo', 'python'), ('bar', 'spam')]
>>> items[0]
('foo', 'python')
>>> items[1]
('bar', 'spam')

How do you find the first key in a dictionary?

As many others have pointed out there is no first value in a dictionary. The sorting in them is arbitrary and you can't count on the sorting being the same every time you access the dictionary. However if you wanted to print the keys there a couple of ways to it:

for key, value in prices.items():
    print(key)

This method uses tuple assignment to access the key and the value. This handy if you need to access both the key and the value for some reason.

for key in prices.keys():
    print(key)

This will only gives access to the keys as the keys() method implies.

SQL Server Insert Example

To insert a single row of data:

INSERT INTO USERS
VALUES (1, 'Mike', 'Jones');

To do an insert on specific columns (as opposed to all of them) you must specify the columns you want to update.

INSERT INTO USERS (FIRST_NAME, LAST_NAME)
VALUES ('Stephen', 'Jiang');

To insert multiple rows of data in SQL Server 2008 or later:

INSERT INTO USERS VALUES
(2, 'Michael', 'Blythe'),
(3, 'Linda', 'Mitchell'),
(4, 'Jillian', 'Carson'),
(5, 'Garrett', 'Vargas');

To insert multiple rows of data in earlier versions of SQL Server, use "UNION ALL" like so:

INSERT INTO USERS (FIRST_NAME, LAST_NAME)
SELECT 'James', 'Bond' UNION ALL
SELECT 'Miss', 'Moneypenny' UNION ALL
SELECT 'Raoul', 'Silva'

Note, the "INTO" keyword is optional in INSERT queries. Source and more advanced querying can be found here.

SELECT * FROM X WHERE id IN (...) with Dapper ORM

In my case I've used this:

var query = "select * from table where Id IN @Ids";
var result = conn.Query<MyEntity>(query, new { Ids = ids });

my variable "ids" in the second line is an IEnumerable of strings, also they can be integers I guess.

PHP: Split a string in to an array foreach char

you can convert a string to array with str_split and use foreach

$chars = str_split($str);
foreach($chars as $char){
    // your code
}

google-services.json for different productFlavors

Place your "google-services.json" file under app/src/flavors respectively then in build.gradle of app, under android add below code

gradle.taskGraph.beforeTask { Task task ->
        if (task.name ==~ /process.*GoogleServices/) {
            android.applicationVariants.all { variant ->
                if (task.name ==~ /(?i)process${variant.name}GoogleServices/) {
                    copy {
                        from "/src/${variant.flavorName}"
                        into '.'
                        include 'google-services.json'
                    }
                }
            }
        }
    }

Declaring a boolean in JavaScript using just var

As this very useful tutorial says:

var age = 0;

// bad
var hasAge = new Boolean(age);

// good
var hasAge = Boolean(age);

// good
var hasAge = !!age;

Git: How to update/checkout a single file from remote origin master?

Following code worked for me:

     git fetch
     git checkout <branch from which file needs to be fetched> <filepath> 

Can the :not() pseudo-class have multiple arguments?

Why :not just use two :not:

input:not([type="radio"]):not([type="checkbox"])

Yes, it is intentional

char initial value in Java

you can initialize it to ' ' instead. Also, the reason that you received an error -1 being too many characters is because it is treating '-' and 1 as separate.

how to run a command at terminal from java program?

You don't actually need to run a command from an xterm session, you can run it directly:

String[] arguments = new String[] {"/path/to/executable", "arg0", "arg1", "etc"};
Process proc = new ProcessBuilder(arguments).start();

If the process responds interactively to the input stream, and you want to inject values, then do what you did before:

OutputStream out = proc.getOutputStream();  
out.write("command\n");  
out.flush();

Don't forget the '\n' at the end though as most apps will use it to identify the end of a single command's input.

How to start Fragment from an Activity

You can either add or replace fragment in your activity. Create a FrameLayout in activity layout xml file.

Then do this in your activity to add fragment:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();

And to replace fragment do this:

FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container,YOUR_FRAGMENT_NAME,YOUR_FRAGMENT_STRING_TAG);
transaction.addToBackStack(null);
transaction.commit();

See Android documentation on adding a fragment to an activity or following related questions on SO:

Difference between add(), replace(), and addToBackStack()

Basic difference between add() and replace() method of Fragment

Difference between add() & replace() with Fragment's lifecycle

How to specify a local file within html using the file: scheme?

The 'file' protocol is not a network protocol. Therefore file://192.168.1.57/~User/2ndFile.html simply does not make much sense.

Question is how you load the first file. Is that really done using a web server? Does not really sound like. If it is, then why not use the same protocol, most likely http? You cannot expect to simply switch the protocol and use two different protocols the same way...

I suspect the first file is really loaded using the apache server at all, but simply by opening the file? href="2ndFile.html" simply works because it uses a "relative url". This makes the browser use the same protocol and path as where he got the first (current) file from.

How to get text with Selenium WebDriver in Python

I've found this absolutely invaluable when unable to grab something in a custom class or changing id's:

driver.find_element_by_xpath("//*[contains(text(), 'Show Next Date Available')]").click()
driver.find_element_by_xpath("//*[contains(text(), 'Show Next Date Available')]").text
driver.find_element_by_xpath("//*[contains(text(), 'Available')]").text
driver.find_element_by_xpath("//*[contains(text(), 'Avail')]").text

ALTER table - adding AUTOINCREMENT in MySQL

CREATE TABLE ALLITEMS(
    itemid INT(10)UNSIGNED,
    itemname VARCHAR(50)
);

ALTER TABLE ALLITEMS CHANGE itemid itemid INT(10)AUTO_INCREMENT PRIMARY KEY;

DESC ALLITEMS;

INSERT INTO ALLITEMS(itemname)
VALUES
    ('Apple'),
    ('Orange'),
    ('Banana');

SELECT
    *
FROM
    ALLITEMS;

I was confused with CHANGE and MODIFY keywords before too:

ALTER TABLE ALLITEMS CHANGE itemid itemid INT(10)AUTO_INCREMENT PRIMARY KEY;

ALTER TABLE ALLITEMS MODIFY itemid INT(5);

While we are there, also note that AUTO_INCREMENT can also start with a predefined number:

ALTER TABLE tbl AUTO_INCREMENT = 100;

'dict' object has no attribute 'has_key'

has_key has been deprecated in Python 3.0. Alternatively you can use 'in'

graph={'A':['B','C'],
   'B':['C','D']}

print('A' in graph)
>> True

print('E' in graph)
>> False

How to break out of nested loops?

No, don't spoil the fun with a break. This is the last remaining valid use of goto ;)

If not this then you could use flags to break out of deep nested loops.

Another approach to breaking out of a nested loop is to factor out both loops into a separate function, and return from that function when you want to exit.

Summarized - to break out of nested loops:

  1. use goto
  2. use flags
  3. factor out loops into separate function calls

Couldn't resist including xkcd here :)

enter image description here

source

Goto's are considered harmful but as many people in the comments suggest it need not be. If used judiciously it can be a great tool. Anything used in moderation is fun.

This version of Android Studio cannot open this project, please retry with Android Studio 3.4 or newer

Open android studio then go to help menu > check for update > Update your Android Studio to newer version.

How to escape the % (percent) sign in C's printf?

you are using incorrect format specifier you should use %% for printing %. Your code should be:

printf("hello%%");  

Read more all format specifiers used in C.

How can I see CakePHP's SQL dump in the controller?

Try this:

$log = $this->Model->getDataSource()->getLog(false, false);
debug($log);

http://api.cakephp.org/2.3/class-Model.html#_getDataSource

You will have to do this for each datasource if you have more than one though.

DateTime "null" value

You can use a nullable class.

DateTime? date = new DateTime?();

Oracle client and networking components were not found

1.Go to My Computer Properties
2.Then click on Advance setting.
3.Go to Environment variable
4.Set the path to

 F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib;F:\oracle\product\10.2.0\db_2\perl\5.8.3\lib\MSWin32-x86;F:\oracle\product\10.2.0\db_2\perl\site\5.8.3;F:\oracle\product\10.2.0\db_2\perl\site\5.8.3\lib;F:\oracle\product\10.2.0\db_2\sysman\admin\scripts;

change your drive and folder depending on your requirement...

jQuery scrollTop() doesn't seem to work in Safari or Chrome (Windows)

The browser support status is this:

IE8, Firefox, Opera: $("html")

Chrome, Safari: $("body")

So this works:

bodyelem = $.browser.safari ? $("body") : $("html") ;
bodyelem.animate( {scrollTop: 0}, 500 );

How to compare only date in moment.js

The docs are pretty clear that you pass in a second parameter to specify granularity.

If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.

moment('2010-10-20').isAfter('2010-01-01', 'year'); // false
moment('2010-10-20').isAfter('2009-12-31', 'year'); // true

As the second parameter determines the precision, and not just a single value to check, using day will check for year, month and day.

For your case you would pass 'day' as the second parameter.

Can someone give an example of cosine similarity, in a very simple, graphical way?

This Python code is my quick and dirty attempt to implement the algorithm:

import math
from collections import Counter

def build_vector(iterable1, iterable2):
    counter1 = Counter(iterable1)
    counter2 = Counter(iterable2)
    all_items = set(counter1.keys()).union(set(counter2.keys()))
    vector1 = [counter1[k] for k in all_items]
    vector2 = [counter2[k] for k in all_items]
    return vector1, vector2

def cosim(v1, v2):
    dot_product = sum(n1 * n2 for n1, n2 in zip(v1, v2) )
    magnitude1 = math.sqrt(sum(n ** 2 for n in v1))
    magnitude2 = math.sqrt(sum(n ** 2 for n in v2))
    return dot_product / (magnitude1 * magnitude2)


l1 = "Julie loves me more than Linda loves me".split()
l2 = "Jane likes me more than Julie loves me or".split()


v1, v2 = build_vector(l1, l2)
print(cosim(v1, v2))

3D Plotting from X, Y, Z Data, Excel or other Tools

You really can't display 3 columns of data as a 'surface'. Only having one column of 'Z' data will give you a line in 3 dimensional space, not a surface (Or in the case of your data, 3 separate lines). For Excel to be able to work with this data, it needs to be formatted as shown below:

      13    21   29      37    45   
1000  75.2                              
1000       79.21                            
1000             80.02                      
5000             87.9                   
5000                    88.54               
5000                           88.56            
10000            90.11      
10000                   90.79   
10000                          90.87

Then, to get an actual surface, you would need to fill in all the missing cells with the appropriate Z-values. If you don't have those, then you are better off showing this as 3 separate 2D lines, because there isn't enough data for a surface.

The best 3D representation that Excel will give you of the above data is pretty confusing:

enter image description here

Representing this limited dataset as 2D data might be a better choice:

enter image description here

As a note for future reference, these types of questions usually do a little better on superuser.com.

Returning Month Name in SQL Server Query

Try this:

SELECT LEFT(DATENAME(MONTH,Getdate()),3)

ReCaptcha API v2 Styling

Unfortunately we cant style reCaptcha v2, but it is possible to make it look better, here is the code:

Click here to preview

.g-recaptcha-outer{
    text-align: center;
    border-radius: 2px;
    background: #f9f9f9;
    border-style: solid;
    border-color: #37474f;
    border-width: 1px;
    border-bottom-width: 2px;
}
.g-recaptcha-inner{
    width: 154px;
    height: 82px;
    overflow: hidden;
    margin: 0 auto;
}
.g-recaptcha{
    position:relative;
    left: -2px;
    top: -1px;
}

<div class="g-recaptcha-outer">
    <div class="g-recaptcha-inner">
        <div class="g-recaptcha" data-size="compact" data-sitekey="YOUR KEY"></div>
    </div>
</div>

Get variable from PHP to JavaScript

You can pass PHP Variables to your JavaScript by generating it with PHP:

<?php
$someVar = 1;
?>

<script type="text/javascript">
    var javaScriptVar = "<?php echo $someVar; ?>";
</script>

SQL 'LIKE' query using '%' where the search criteria contains '%'

You need to escape it: on many databases this is done by preceding it with backslash, \%.

So abc becomes abc\%.

Your programming language will have a database-specific function to do this for you. For example, PHP has mysql_escape_string() for the MySQL database.

C read file line by line

Use fgets() to read a line from a file handle.

What does <> mean?

could be a shorthand for React.Fragment

Check box size change with CSS

Try this

<input type="checkbox" style="zoom:1.5;" />
/* The value 1.5 i.e., the size of checkbox will be increased by 0.5% */

"Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." when using GCC

I had the same issue when I tried to use git.

It is possible to install git without it. And I doubt that gcc on mac is truly dependent on XCode. And I don't want to use root to accept something unless I'm sure I need it.

I uninstalled XCode by navigating to the applications folder and dragging XCode to the trash.

Now my git commands work as usual. I'll re-install XCode if/when I truly need it.

How to convert a DataTable to a string in C#?

public static string DataTable2String(DataTable dataTable)
{
    StringBuilder sb = new StringBuilder();
    if (dataTable != null)
    {
        string seperator = " | ";

        #region get min length for columns
        Hashtable hash = new Hashtable();
        foreach (DataColumn col in dataTable.Columns)
            hash[col.ColumnName] = col.ColumnName.Length;
        foreach (DataRow row in dataTable.Rows)
            for (int i = 0; i < row.ItemArray.Length; i++)
                if (row[i] != null)
                    if (((string)row[i]).Length > (int)hash[dataTable.Columns[i].ColumnName])
                        hash[dataTable.Columns[i].ColumnName] = ((string)row[i]).Length;
        int rowLength = (hash.Values.Count + 1) * seperator.Length;
        foreach (object o in hash.Values)
            rowLength += (int)o;
        #endregion get min length for columns

        sb.Append(new string('=', (rowLength - " DataTable ".Length) / 2));
        sb.Append(" DataTable ");
        sb.AppendLine(new string('=', (rowLength - " DataTable ".Length) / 2));
        if (!string.IsNullOrEmpty(dataTable.TableName))
            sb.AppendLine(String.Format("{0,-" + rowLength + "}", String.Format("{0," + ((rowLength + dataTable.TableName.Length) / 2).ToString() + "}", dataTable.TableName)));

        #region write values
        foreach (DataColumn col in dataTable.Columns)
            sb.Append(seperator + String.Format("{0,-" + hash[col.ColumnName] + "}", col.ColumnName));
        sb.AppendLine(seperator);
        sb.AppendLine(new string('-', rowLength));
        foreach (DataRow row in dataTable.Rows)
        {
            for (int i = 0; i < row.ItemArray.Length; i++)
            {
                sb.Append(seperator + String.Format("{0," + hash[dataTable.Columns[i].ColumnName] + "}", row[i]));
                if (i == row.ItemArray.Length - 1)
                    sb.AppendLine(seperator);
            }
        }
        #endregion write values

        sb.AppendLine(new string('=', rowLength));
    }
    else
        sb.AppendLine("================ DataTable is NULL ================");

    return sb.ToString();
}

output:

======================= DataTable =======================
                         MyTable                          
 | COL1 | COL2                    | COL3 1000000ng name | 
----------------------------------------------------------
 |    1 |                       2 |                   3 | 
 |  abc | Dienstag, 12. März 2013 |                 xyz | 
 | Have |                  a nice |                day! | 
==========================================================

Input button target="_blank" isn't causing the link to load in a new window/tab

An input element does not support the target attribute. The target attribute is for a tags and that is where it should be used.

Loaded nib but the 'view' outlet was not set

I had the same problem, I figured out and it is because of i had ticked "Static cells" in the properties of Table View under Content option. Worked when it changed to "Dynamic Prototypes". Screenshot is below. enter image description here

Single Page Application: advantages and disadvantages

Let's look at one of the most popular SPA sites, GMail.

1. SPA is extremely good for very responsive sites:

Server-side rendering is not as hard as it used to be with simple techniques like keeping a #hash in the URL, or more recently HTML5 pushState. With this approach the exact state of the web app is embedded in the page URL. As in GMail every time you open a mail a special hash tag is added to the URL. If copied and pasted to other browser window can open the exact same mail (provided they can authenticate). This approach maps directly to a more traditional query string, the difference is merely in the execution. With HTML5 pushState() you can eliminate the #hash and use completely classic URLs which can resolve on the server on the first request and then load via ajax on subsequent requests.

2. With SPA we don't need to use extra queries to the server to download pages.

The number of pages user downloads during visit to my web site?? really how many mails some reads when he/she opens his/her mail account. I read >50 at one go. now the structure of the mails is almost the same. if you will use a server side rendering scheme the server would then render it on every request(typical case). - security concern - you should/ should not keep separate pages for the admins/login that entirely depends upon the structure of you site take paytm.com for example also making a web site SPA does not mean that you open all the endpoints for all the users I mean I use forms auth with my spa web site. - in the probably most used SPA framework Angular JS the dev can load the entire html temple from the web site so that can be done depending on the users authentication level. pre loading html for all the auth types isn't SPA.

3. May be any other advantages? Don't hear about any else..

  • these days you can safely assume the client will have javascript enabled browsers.
  • only one entry point of the site. As I mentioned earlier maintenance of state is possible you can have any number of entry points as you want but you should have one for sure.
  • even in an SPA user only see to what he has proper rights. you don't have to inject every thing at once. loading diff html templates and javascript async is also a valid part of SPA.

Advantages that I can think of are:

  1. rendering html obviously takes some resources now every user visiting you site is doing this. also not only rendering major logics are now done client side instead of server side.
  2. date time issues - I just give the client UTC time is a pre set format and don't even care about the time zones I let javascript handle it. this is great advantage to where I had to guess time zones based on location derived from users IP.
  3. to me state is more nicely maintained in an SPA because once you have set a variable you know it will be there. this gives a feel of developing an app rather than a web page. this helps a lot typically in making sites like foodpanda, flipkart, amazon. because if you are not using client side state you are using expensive sessions.
  4. websites surely are extremely responsive - I'll take an extreme example for this try making a calculator in a non SPA website(I know its weird).

Updates from Comments

It doesn't seem like anyone mentioned about sockets and long-polling. If you log out from another client say mobile app, then your browser should also log out. If you don't use SPA, you have to re-create the socket connection every time there is a redirect. This should also work with any updates in data like notifications, profile update etc

An alternate perspective: Aside from your website, will your project involve a native mobile app? If yes, you are most likely going to be feeding raw data to that native app from a server (ie JSON) and doing client-side processing to render it, correct? So with this assertion, you're ALREADY doing a client-side rendering model. Now the question becomes, why shouldn't you use the same model for the website-version of your project? Kind of a no-brainer. Then the question becomes whether you want to render server-side pages only for SEO benefits and convenience of shareable/bookmarkable URLs

Calculate correlation with cor(), only for numerical columns

I found an easier way by looking at the R script generated by Rattle. It looks like below:

correlations <- cor(mydata[,c(1,3,5:87,89:90,94:98)], use="pairwise", method="spearman")

Python script to convert from UTF-8 to ASCII

data="UTF-8 DATA"
udata=data.decode("utf-8")
asciidata=udata.encode("ascii","ignore")

What is a practical, real world example of the Linked List?

I don't think there is a good analogy that could highlight the two important characteristics as opposed to an array: 1. efficient to insert after current item and 2. inefficient to find a specific item by index.

There's nothing like that because normally people don't deal with very large number of items where you need to insert or locate specific items. For example, if you have a bag of sand, that would be hundreds of millions of grains, but you don't need to locate a specific grain, and the order of grains isn't important.

When you deal with smaller collections, you can locate the needed item visually, or, in case of books in a library, you will have a dictinary-like organization.

The closest analogy is having a blind man who goes through linked items like links of chain, beads on a necklace, train cars, etc. He may be looking for specific item or needing to insert an item after current one. It might be good to add that the blind man can go through them very quickly, e.g. one million beads per second, but can only feel one link at a time, and cannot see the whole chain or part of it.

Note that this analogy is similar to a double-linked list, I can't think of a similar analogy with singly linked one, because having a physical connection implies ability to backtrack.

Detect changed input text box

I think you can use keydown too:

$('#fieldID').on('keydown', function (e) {
  //console.log(e.which);
  if (e.which === 8) {
    //do something when pressing delete
    return true;
  } else {
    //do something else
    return false;
  }
});

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

Here you go:

USE information_schema;
SELECT *
FROM
  KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = 'X'
  AND REFERENCED_COLUMN_NAME = 'X_id';

If you have multiple databases with similar tables/column names you may also wish to limit your query to a particular database:

SELECT *
FROM
  KEY_COLUMN_USAGE
WHERE
  REFERENCED_TABLE_NAME = 'X'
  AND REFERENCED_COLUMN_NAME = 'X_id'
  AND TABLE_SCHEMA = 'your_database_name';

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

I also had this issue, where trying to run in production without precompiling it would still throw not-precompiled errors. I had to change which line was commented application.rb:

  # If you precompile assets before deploying to production, use this line
  # Bundler.require(*Rails.groups(:assets => %w(development test)))
  # If you want your assets lazily compiled in production, use this line
  Bundler.require(:default, :assets, Rails.env)

How do I do word Stemming or Lemmatization?

Martin Porter's official page contains a Porter Stemmer in PHP as well as other languages.

If you're really serious about good stemming though you're going to need to start with something like the Porter Algorithm, refine it by adding rules to fix incorrect cases common to your dataset, and then finally add a lot of exceptions to the rules. This can be easily implemented with key/value pairs (dbm/hash/dictionaries) where the key is the word to look up and the value is the stemmed word to replace the original. A commercial search engine I worked on once ended up with 800 some exceptions to a modified Porter algorithm.

querySelector, wildcard element match?

I was messing/musing on one-liners involving querySelector() & ended up here, & have a possible answer to the OP question using tag names & querySelector(), with credits to @JaredMcAteer for answering MY question, aka have RegEx-like matches with querySelector() in vanilla Javascript

Hoping the following will be useful & fit the OP's needs or everyone else's:

// basically, of before:
var youtubeDiv = document.querySelector('iframe[src="http://www.youtube.com/embed/Jk5lTqQzoKA"]')

// after     
var youtubeDiv = document.querySelector('iframe[src^="http://www.youtube.com"]');
// or even, for my needs
var youtubeDiv = document.querySelector('iframe[src*="youtube"]');

Then, we can, for example, get the src stuff, etc ...

console.log(youtubeDiv.src);
//> "http://www.youtube.com/embed/Jk5lTqQzoKA"
console.debug(youtubeDiv);
//> (...)

Return background color of selected cell

If you are looking at a Table, a Pivot Table, or something with conditional formatting, you can try:

ActiveCell.DisplayFormat.Interior.Color

This also seems to work just fine on regular cells.

Python - abs vs fabs

abs() : Returns the absolute value as per the argument i.e. if argument is int then it returns int, if argument is float it returns float. Also it works on complex variable also i.e. abs(a+bj) also works and returns absolute value i.e.math.sqrt(((a)**2)+((b)**2)

math.fabs() : It only works on the integer or float values. Always returns the absolute float value no matter what is the argument type(except for the complex numbers).

How to delete the last row of data of a pandas dataframe

Surprised nobody brought this one up:

# To remove last n rows
df.head(-n)

# To remove first n rows
df.tail(-n)

Running a speed test on a DataFrame of 1000 rows shows that slicing and head/tail are ~6 times faster than using drop:

>>> %timeit df[:-1]
125 µs ± 132 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

>>> %timeit df.head(-1)
129 µs ± 1.18 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

>>> %timeit df.drop(df.tail(1).index)
751 µs ± 20.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Is Python interpreted, or compiled, or both?

It really depends on the implementation of the language being used! There is a common step in any implementation, though: your code is first compiled (translated) to intermediate code - something between your code and machine (binary) code - called bytecode (stored into .pyc files). Note that this is a one-time step that will not be repeated unless you modify your code.

And that bytecode is executed every time you are running the program. How? Well, when we run the program, this bytecode (inside a .pyc file) is passed as input to a Virtual Machine (VM)1 - the runtime engine allowing our programs to be executed - that executes it.

Depending on the language implementation, the VM will either interpret the bytecode (in the case of CPython2 implementation) or JIT-compile3 it (in the case of PyPy4 implementation).

Notes:

1 an emulation of a computer system

2 a bytecode interpreter; the reference implementation of the language, written in C and Python - most widely used

3 compilation that is being done during the execution of a program (at runtime)

4 a bytecode JIT compiler; an alternative implementation to CPython, written in RPython (Restricted Python) - often runs faster than CPython

wampserver doesn't go green - stays orange

If you install WAMPServer before you install the C++ Redistributable, it won't work even after you've installed it because you will miss a critical step in the installation where you tell Windows Firewall to let Apache run.

  1. Uninstall WAMP by running the unins file in the wamp directory
  2. Download and install the vbasic package here [http://www.microsoft.com/en-us/download/details.aspx?id=8328]
  3. Restart your computer
  4. Install WAMP again. You should see a message with a purple feather telling you to allow access. Do so, and you should be all good

Ruby on Rails 3 Can't connect to local MySQL server through socket '/tmp/mysql.sock' on OSX

I have had the same problem, but none of the answers quite gave a step by step of what I needed to do. This error happens because your socket file has not been created yet. All you have to do is:

  1. Start you mysql server, so your /tmp/mysql.sock is created, to do that you run: mysql server start
  2. Once that is done, go to your app directory end edit the config/database.yml file and add/edit the socket: /tmp/mysql.sock entry
  3. Run rake:dbmigrate once again and everything should workout fine

Object passed as parameter to another class, by value or reference?

I found the other examples unclear, so I did my own test which confirmed that a class instance is passed by reference and as such actions done to the class will affect the source instance.

In other words, my Increment method modifies its parameter myClass everytime its called.

class Program
{
    static void Main(string[] args)
    {
        MyClass myClass = new MyClass();
        Console.WriteLine(myClass.Value);  // Displays 1
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 2
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 3           
        Increment(myClass);
        Console.WriteLine(myClass.Value);  // Displays 4
        Console.WriteLine("Hit Enter to exit.");
        Console.ReadLine();
    }

    public static void Increment(MyClass myClassRef)
    {
        myClassRef.Value++;
    }
}

public class MyClass
{
    public int Value {get;set;}
    public MyClass()
    {
        Value = 1;
    }
}

How do I check if a string contains another string in Swift?

Here you are:

let s = "hello Swift"
if let textRange = s.rangeOfString("Swift") {
    NSLog("exists")
}

What is PHPSESSID?

Check php.ini for auto session id.

If you enable it, you will have PHPSESSID in your cookies.

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

Creating an XmlNode/XmlElement in C# without an XmlDocument?

From W3C Document Object Model (Core) Level 1 specification (bold is mine):

Most of the APIs defined by this specification are interfaces rather than classes. That means that an actual implementation need only expose methods with the defined names and specified operation, not actually implement classes that correspond directly to the interfaces. This allows the DOM APIs to be implemented as a thin veneer on top of legacy applications with their own data structures, or on top of newer applications with different class hierarchies. This also means that ordinary constructors (in the Java or C++ sense) cannot be used to create DOM objects, since the underlying objects to be constructed may have little relationship to the DOM interfaces. The conventional solution to this in object-oriented design is to define factory methods that create instances of objects that implement the various interfaces. In the DOM Level 1, objects implementing some interface "X" are created by a "createX()" method on the Document interface; this is because all DOM objects live in the context of a specific Document.

AFAIK, you can not create any XmlNode (XmlElement, XmlAttribute, XmlCDataSection, etc) except XmlDocument from a constructor.

Moreover, note that you can not use XmlDocument.AppendChild() for nodes that are not created via the factory methods of the same document. In case you have a node from another document, you must use XmlDocument.ImportNode().

How do I insert a drop-down menu for a simple Windows Forms app in Visual Studio 2008?

You can use ComboBox, then point your mouse to the upper arrow facing right, it will unfold a box called ComboBox Tasks and in there you can go ahead and edit your items or fill in the items / strings one per line. This should be the easiest.

Reading binary file and looping over each byte

Reading binary file in Python and looping over each byte

New in Python 3.5 is the pathlib module, which has a convenience method specifically to read in a file as bytes, allowing us to iterate over the bytes. I consider this a decent (if quick and dirty) answer:

import pathlib

for byte in pathlib.Path(path).read_bytes():
    print(byte)

Interesting that this is the only answer to mention pathlib.

In Python 2, you probably would do this (as Vinay Sajip also suggests):

with open(path, 'b') as file:
    for byte in file.read():
        print(byte)

In the case that the file may be too large to iterate over in-memory, you would chunk it, idiomatically, using the iter function with the callable, sentinel signature - the Python 2 version:

with open(path, 'b') as file:
    callable = lambda: file.read(1024)
    sentinel = bytes() # or b''
    for chunk in iter(callable, sentinel): 
        for byte in chunk:
            print(byte)

(Several other answers mention this, but few offer a sensible read size.)

Best practice for large files or buffered/interactive reading

Let's create a function to do this, including idiomatic uses of the standard library for Python 3.5+:

from pathlib import Path
from functools import partial
from io import DEFAULT_BUFFER_SIZE

def file_byte_iterator(path):
    """given a path, return an iterator over the file
    that lazily loads the file
    """
    path = Path(path)
    with path.open('rb') as file:
        reader = partial(file.read1, DEFAULT_BUFFER_SIZE)
        file_iterator = iter(reader, bytes())
        for chunk in file_iterator:
            yield from chunk

Note that we use file.read1. file.read blocks until it gets all the bytes requested of it or EOF. file.read1 allows us to avoid blocking, and it can return more quickly because of this. No other answers mention this as well.

Demonstration of best practice usage:

Let's make a file with a megabyte (actually mebibyte) of pseudorandom data:

import random
import pathlib
path = 'pseudorandom_bytes'
pathobj = pathlib.Path(path)

pathobj.write_bytes(
  bytes(random.randint(0, 255) for _ in range(2**20)))

Now let's iterate over it and materialize it in memory:

>>> l = list(file_byte_iterator(path))
>>> len(l)
1048576

We can inspect any part of the data, for example, the last 100 and first 100 bytes:

>>> l[-100:]
[208, 5, 156, 186, 58, 107, 24, 12, 75, 15, 1, 252, 216, 183, 235, 6, 136, 50, 222, 218, 7, 65, 234, 129, 240, 195, 165, 215, 245, 201, 222, 95, 87, 71, 232, 235, 36, 224, 190, 185, 12, 40, 131, 54, 79, 93, 210, 6, 154, 184, 82, 222, 80, 141, 117, 110, 254, 82, 29, 166, 91, 42, 232, 72, 231, 235, 33, 180, 238, 29, 61, 250, 38, 86, 120, 38, 49, 141, 17, 190, 191, 107, 95, 223, 222, 162, 116, 153, 232, 85, 100, 97, 41, 61, 219, 233, 237, 55, 246, 181]
>>> l[:100]
[28, 172, 79, 126, 36, 99, 103, 191, 146, 225, 24, 48, 113, 187, 48, 185, 31, 142, 216, 187, 27, 146, 215, 61, 111, 218, 171, 4, 160, 250, 110, 51, 128, 106, 3, 10, 116, 123, 128, 31, 73, 152, 58, 49, 184, 223, 17, 176, 166, 195, 6, 35, 206, 206, 39, 231, 89, 249, 21, 112, 168, 4, 88, 169, 215, 132, 255, 168, 129, 127, 60, 252, 244, 160, 80, 155, 246, 147, 234, 227, 157, 137, 101, 84, 115, 103, 77, 44, 84, 134, 140, 77, 224, 176, 242, 254, 171, 115, 193, 29]

Don't iterate by lines for binary files

Don't do the following - this pulls a chunk of arbitrary size until it gets to a newline character - too slow when the chunks are too small, and possibly too large as well:

    with open(path, 'rb') as file:
        for chunk in file: # text newline iteration - not for bytes
            yield from chunk

The above is only good for what are semantically human readable text files (like plain text, code, markup, markdown etc... essentially anything ascii, utf, latin, etc... encoded) that you should open without the 'b' flag.

Convert bytes to int?

int.from_bytes( bytes, byteorder, *, signed=False )

doesn't work with me I used function from this website, it works well

https://coderwall.com/p/x6xtxq/convert-bytes-to-int-or-int-to-bytes-in-python

def bytes_to_int(bytes):
    result = 0
    for b in bytes:
        result = result * 256 + int(b)
    return result

def int_to_bytes(value, length):
    result = []
    for i in range(0, length):
        result.append(value >> (i * 8) & 0xff)
    result.reverse()
    return result

Table column sizing

Disclaimer: This answer may be a bit old. Since the bootstrap 4 beta. Bootstrap has changed since then.

The table column size class has been changed from this

<th class="col-sm-3">3 columns wide</th>

to

<th class="col-3">3 columns wide</th>

PHP error: Notice: Undefined index:

Are you putting the form processor in the same script as the form? If so, it is attempting to process before the post values are set (everything is executing).

Wrap all the processing code in a conditional that checks if the form has even been sent.

if(isset($_POST) && array_key_exists('name_of_your_submit_input',$_POST)){
//process form!
}else{
//show form, don't process yet!  You can break out of php here and render your form
}

Scripts execute from the top down when programming procedurally. You need to make sure the program knows to ignore the processing logic if the form has not been sent. Likewise, after processing, you should redirect to a success page with something like

header('Location:http://www.yourdomainhere.com/formsuccess.php');

I would not get into the habit of supressing notices or errors.

Please don't take offense if I suggest that if you are having these problems and you are attempting to build a shopping cart, that you instead utilize a mature ecommerce solution like Magento or OsCommerce. A shopping cart is an interface that requires a high degree of security and if you are struggling with these kind of POST issues I can guarantee you will be fraught with headaches later. There are many great stable releases, some as simple as mere object models, that are available for download.

SQL left join vs multiple tables on FROM line?

To the database, they end up being the same. For you, though, you'll have to use that second syntax in some situations. For the sake of editing queries that end up having to use it (finding out you needed a left join where you had a straight join), and for consistency, I'd pattern only on the 2nd method. It'll make reading queries easier.

Splitting on first occurrence

For me the better approach is that:

s.split('mango', 1)[-1]

...because if happens that occurrence is not in the string you'll get "IndexError: list index out of range".

Therefore -1 will not get any harm cause number of occurrences is already set to one.

What are C++ functors and their uses?

Functors are used in gtkmm to connect some GUI button to an actual C++ function or method.


If you use the pthread library to make your app multithreaded, Functors can help you.
To start a thread, one of the arguments of the pthread_create(..) is the function pointer to be executed on his own thread.
But there's one inconvenience. This pointer can't be a pointer to a method, unless it's a static method, or unless you specify it's class, like class::method. And another thing, the interface of your method can only be:

void* method(void* something)

So you can't run (in a simple obvious way), methods from your class in a thread without doing something extra.

A very good way of dealing with threads in C++, is creating your own Thread class. If you wanted to run methods from MyClass class, what I did was, transform those methods into Functor derived classes.

Also, the Thread class has this method: static void* startThread(void* arg)
A pointer to this method will be used as an argument to call pthread_create(..). And what startThread(..) should receive in arg is a void* casted reference to an instance in heap of any Functor derived class, which will be casted back to Functor* when executed, and then called it's run() method.

Bash checking if string does not contain other string

Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.

fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf 
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"

jQuery function after .append

Using MutationObserver can act like a callback for the jQuery append method:

I've explained it in another question, and this time I will only give example for modern browsers:

// Somewhere in your app:
var observeDOM = (() => {
    var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

    return function(obj, callback){
        if( MutationObserver ){
            // define a new observer
            var obs = new MutationObserver(function(mutations, observer){
                if( mutations[0].addedNodes.length || mutations[0].removedNodes.length )
                    callback(mutations);
            });
            // have the observer observe foo for changes in children
            obs.observe( obj, { childList:true, subtree:true });

            return obs;
        }
    }
})();

//////////////////
// Your code:

// setup the DOM observer (on the appended content's parent) before appending anything
observeDOM( document.body, ()=>{
    // something was added/removed
}).disconnect(); // don't listen to any more changes

// append something
$('body').append('<p>foo</p>');

How do I build an import library (.lib) AND a DLL in Visual C++?

By selecting 'Class Library' you were accidentally telling it to make a .Net Library using the CLI (managed) extenstion of C++.

Instead, create a Win32 project, and in the Application Settings on the next page, choose 'DLL'.

You can also make an MFC DLL or ATL DLL from those library choices if you want to go that route, but it sounds like you don't.

How to get a complete list of ticker symbols from Yahoo Finance?

I have been researching this for a few days, following endless leads that got close, but not quite, to what I was after.

My need is for a simple list of 'symbol, sector, industry'. I'm working in Java and don't want to use any platform native code.

It seems that most other data, like quotes, etc., is readily available.

Finally, followed a suggestion to look at 'finviz.com'. Looks like just the ticket. Try using the following:

http://finviz.com/export.ashx?v=111&t=aapl,cat&o=ticker This comes back as lines, csv style, with a header row, ordered by ticker symbol. You can keep adding tickers. In code, you can read the stream. Or you can let the browser ask you whether to open or save the file.

http://finviz.com/export.ashx?v=111&&o=ticker Same csv style, but pulls all available symbols (a lot, across global exchanges)

Replace 'export' with 'screener' and the data will show up in the browser.

There are many more options you can use, one for every screener element on the site.

So far, this is the most powerful and convenient programmatic way to get the few pieces of data I couldn't otherwise seem to easily get. And, it looks like this site could well be a single source for most of what you might need other than real- or near-real-time quotes.

Passing data from controller to view in Laravel

The best and easy way to pass single or multiple variables to view from controller is to use compact() method.

For passing single variable to view,

return view("user/regprofile",compact('students'));

For passing multiple variable to view,

return view("user/regprofile",compact('students','teachers','others'));

And in view, you can easily loop through the variable,

@foreach($students as $student)
   {{$student}}
@endforeach

Catching "Maximum request length exceeded"

As GateKiller said you need to change the maxRequestLength. You may also need to change the executionTimeout in case the upload speed is too slow. Note that you don't want either of these settings to be too big otherwise you'll be open to DOS attacks.

The default for the executionTimeout is 360 seconds or 6 minutes.

You can change the maxRequestLength and executionTimeout with the httpRuntime Element.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.web>
        <httpRuntime maxRequestLength="102400" executionTimeout="1200" />
    </system.web>
</configuration>

EDIT:

If you want to handle the exception regardless then as has been stated already you'll need to handle it in Global.asax. Here's a link to a code example.

master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

git pull --rebase origin/master 

is a single command that can help you most of the time.

Edit: Pulls the commits from the origin/master and applies your changes upon the newly pulled branch history.

AlertDialog styling - how to change style (color) of title, message, etc

It depends how much you want to customize the alert dialog. I have different steps in order to customize the alert dialog. Please visit: https://stackoverflow.com/a/33439849/5475941

enter image description here enter image description here enter image description here enter image description here

Best way to test exceptions with Assert to ensure they will be thrown

With most .net unit testing frameworks you can put an [ExpectedException] attribute on the test method. However this can't tell you that the exception happened at the point you expected it to. That's where xunit.net can help.

With xunit you have Assert.Throws, so you can do things like this:

    [Fact]
    public void CantDecrementBasketLineQuantityBelowZero()
    {
        var o = new Basket();
        var p = new Product {Id = 1, NetPrice = 23.45m};
        o.AddProduct(p, 1);
        Assert.Throws<BusinessException>(() => o.SetProductQuantity(p, -3));
    }

[Fact] is the xunit equivalent of [TestMethod]

How to programmatically clear application data

This way added by Sebastiano was OK, but it's necessary, when you run tests from i.e. IntelliJ IDE to add:

 try {
    // clearing app data
    Runtime runtime = Runtime.getRuntime();
    runtime.exec("adb shell pm clear YOUR_APP_PACKAGE_GOES HERE");

}

instead of only "pm package..."

and more important: add it before driver.setCapability(App_package, package_name).

MySQL Workbench not displaying query results

I have updated macOS to 10.13.4 and it works.

Python json.loads shows ValueError: Extra data

I came across this because I was trying to load a JSON file dumped from MongoDB. It was giving me an error

JSONDecodeError: Extra data: line 2 column 1

The MongoDB JSON dump has one object per line, so what worked for me is:

import json
data = [json.loads(line) for line in open('data.json', 'r')]

How does Facebook Sharer select Images and other metadata when sharing my URL?

Old way, no longer works:

<link rel="image_src" href="http://yoururl/yourimage"/>

Reported new way, also does not work:

<meta property="og:image" content="http://yoururl/yourimage"/>

It randomly worked off and on during the first day I implemented it, hasn't worked at all since.

The Facebook linter page, a utility that inspects your page, reports that everything is correct and does display the thumbnail I selected... just that the share.php page itself doesn't seem to be functioning. Has to be a bug over at Facebook, one they apparently don't care to fix as every bug report regarding this issue I've seen in their system all say resolved or fixed.

Capture close event on Bootstrap Modal

This is very similar to another stackoverflow article, Bind a function to Twitter Bootstrap Modal Close. Assuming you are using some version of Bootstap v3 or v4, you can do something like the following:

$("#myModal").on("hidden.bs.modal", function () {
    // put your default event here
});

How-to turn off all SSL checks for postman for a specific site

enter image description here

click here in settings, one pop up window will get open. There we have switcher to make SSL verification certificate (Off)

How to retrieve a single file from a specific revision in Git?

Get the file from a previous commit through checking-out previous commit and copying file.

  • Note which branch you are on: git branch
  • Checkout the previous commit you want: git checkout 27cf8e84bb88e24ae4b4b3df2b77aab91a3735d8
  • Copy the file you want to a temporary location
  • Checkout the branch you started from: git checkout theBranchYouNoted
  • Copy in the file you placed in a temporary location
  • Commit your change to git: git commit -m "added file ?? from previous commit"

Run jar file in command prompt

java [any other JVM options you need to give it] -jar foo.jar

asp:TextBox ReadOnly=true or Enabled=false?

Readonly will allow the user to copy text from it. Disabled will not.

"Application tried to present modally an active controller"?

In my case, I was presenting the rootViewController of an UINavigationController when I was supposed to present the UINavigationController itself.

pretty-print JSON using JavaScript

Based on Pumbaa80's answer I have modified the code to use the console.log colours (working on Chrome for sure) and not HTML. Output can be seen inside console. You can edit the _variables inside the function adding some more styling.

function JSONstringify(json) {
    if (typeof json != 'string') {
        json = JSON.stringify(json, undefined, '\t');
    }

    var 
        arr = [],
        _string = 'color:green',
        _number = 'color:darkorange',
        _boolean = 'color:blue',
        _null = 'color:magenta',
        _key = 'color:red';

    json = json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var style = _number;
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                style = _key;
            } else {
                style = _string;
            }
        } else if (/true|false/.test(match)) {
            style = _boolean;
        } else if (/null/.test(match)) {
            style = _null;
        }
        arr.push(style);
        arr.push('');
        return '%c' + match + '%c';
    });

    arr.unshift(json);

    console.log.apply(console, arr);
}

Here is a bookmarklet you can use:

javascript:function JSONstringify(json) {if (typeof json != 'string') {json = JSON.stringify(json, undefined, '\t');}var arr = [],_string = 'color:green',_number = 'color:darkorange',_boolean = 'color:blue',_null = 'color:magenta',_key = 'color:red';json = json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {var style = _number;if (/^"/.test(match)) {if (/:$/.test(match)) {style = _key;} else {style = _string;}} else if (/true|false/.test(match)) {style = _boolean;} else if (/null/.test(match)) {style = _null;}arr.push(style);arr.push('');return '%c' + match + '%c';});arr.unshift(json);console.log.apply(console, arr);};void(0);

Usage:

var obj = {a:1, 'b':'foo', c:[false,null, {d:{e:1.3e5}}]};
JSONstringify(obj);

Edit: I just tried to escape the % symbol with this line, after the variables declaration:

json = json.replace(/%/g, '%%');

But I find out that Chrome is not supporting % escaping in the console. Strange... Maybe this will work in the future.

Cheers!

enter image description here

How do I protect Python code?

Do not rely on obfuscation. As You have correctly concluded, it offers very limited protection. UPDATE: Here is a link to paper which reverse engineered obfuscated python code in Dropbox. The approach - opcode remapping is a good barrier, but clearly it can be defeated.

Instead, as many posters have mentioned make it:

  • Not worth reverse engineering time (Your software is so good, it makes sense to pay)
  • Make them sign a contract and do a license audit if feasible.

Alternatively, as the kick-ass Python IDE WingIDE does: Give away the code. That's right, give the code away and have people come back for upgrades and support.

What is the difference between encrypting and signing in asymmetric encryption?

Answering this question in the content that the questioners intent was to use the solution for software licensing, the requirements are:

  1. No 3rd party can produce a license key from decompiling the app
  2. The content of the software key does not need to be secure
  3. Software key is not human readable

A Digital Signature will solve this issue as the raw data that makes the key can be signed with a private key which makes it not human readable but could be decoded if reverse engineered. But the private key is safe which means no one will be able to make licenses for your software (which is the point).

Remember you can not prevent a skilled person from removing the software locks on your product. So if they have to hack each version that is released. But you really don't want them to be able to generate new keys for your product that can be shared for all versions.

Python The PyNaCl documentation has an example of 'Digital Signature' which will suite the purpose. http://pynacl.readthedocs.org/en/latest/signing/

and of cause NaCl project to C examples

How to get image size (height & width) using JavaScript?

The thing all other have forgot is that you cant check image size before it loads. When the author checks all of posted methods it will work probably only on localhost. Since jQuery could be used here, remember that 'ready' event is fired before images are loaded. $('#xxx').width() and .height() should be fired in onload event or later.

Bootstrap 3: Keep selected tab on page refresh

For Bootstrap v4.3.1. Try below:

$(document).ready(function() {
    var pathname = window.location.pathname; //get the path of current page
    $('.navbar-nav > li > a[href="'+pathname+'"]').parent().addClass('active');
})

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

I had the same issue in VS2015. I have solved it by compiling the SDL2 sources in VS2015.

  1. Go to http://libsdl.org/download-2.0.php and download SDL 2 source code.
  2. Open SDL_VS2013.sln in VS2015. You will be asked to convert the projects. Do it.
  3. Compile SDL2 project.
  4. Compile SDL2main project.
  5. Use the new generated output files SDL2main.lib, SDL2.lib and SDL2.dll in your SDL 2 project in VS2015.

Get human readable version of file size?

There's always got to be one of those guys. Well today it's me. Here's a one-liner -- or two lines if you count the function signature.

def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']):
    """ Returns a human readable string representation of bytes """
    return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:])

>>> human_size(123)
123 bytes
>>> human_size(123456789)
117GB

If you need sizes bigger than an Exabyte, it's a little bit more gnarly:

def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']):
    return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:]) if units[1:] else f'{bytes>>10}ZB'

PHP: date function to get month of the current date

as date_format uses the same format as date ( http://www.php.net/manual/en/function.date.php ) the "Numeric representation of a month, without leading zeros" is a lowercase n .. so

echo date('n'); // "9"

How to check size of a file using Bash?

stat appears to do this with the fewest system calls:

$ set debian-live-8.2.0-amd64-xfce-desktop.iso

$ strace stat --format %s $1 | wc
    282    2795   27364

$ strace wc --bytes $1 | wc
    307    3063   29091

$ strace du --bytes $1 | wc
    437    4376   41955

$ strace find $1 -printf %s | wc
    604    6061   64793

Selecting data frame rows based on partial string match in a column

Another option would be to simply use grepl function:

df[grepl('er', df$name), ]
CO2[grepl('non', CO2$Treatment), ]

df <- data.frame(name = c('bob','robert','peter'),
                 id = c(1,2,3)
                 )

# name id
# 2 robert  2
# 3  peter  3

Nested classes' scope?

Easiest solution:

class OuterClass:
    outer_var = 1
    class InnerClass:
        def __init__(self):
            self.inner_var = OuterClass.outer_var

It requires you to be explicit, but doesn't take much effort.

remove space between paragraph and unordered list

You can (A) change the markup to not use paragraphs

<span>Text</span>
<br>
<ul>
  <li>One</li>
</ul>
<span>Text 2</span>

Or (B) change the css

p{margin:0px;}

Demos here: http://jsfiddle.net/ZnpVu/1

How to iterate over associative arrays in Bash

Use this higher order function to prevent the pyramid of doom

foreach(){ 
  arr="$(declare -p $1)" ; eval "declare -A f="${arr#*=}; 
  for i in ${!f[@]}; do $2 "$i" "${f[$i]}"; done
}

example:

$ bar(){ echo "$1 -> $2"; }
$ declare -A foo["flap"]="three four" foo["flop"]="one two"
$ foreach foo bar
flap -> three four
flop -> one two

How to call a SOAP web service on Android

I would suggest checking out a very useful tool that helped me a lot. The guys who take care of that project were very helpful, too. www.wsdl2code.com/

Create a user with all privileges in Oracle

There are 2 differences:

2 methods creating a user and granting some privileges to him

create user userName identified by password;
grant connect to userName;

and

grant connect to userName identified by password;

do exactly the same. It creates a user and grants him the connect role.

different outcome

resource is a role in oracle, which gives you the right to create objects (tables, procedures, some more but no views!). ALL PRIVILEGES grants a lot more of system privileges.

To grant a user all privileges run you first snippet or

grant all privileges to userName identified by password;

How do I setup a SSL certificate for an express.js server?

I was able to get SSL working with the following boilerplate code:

var fs = require('fs'),
    http = require('http'),
    https = require('https'),
    express = require('express');

var port = 8000;

var options = {
    key: fs.readFileSync('./ssl/privatekey.pem'),
    cert: fs.readFileSync('./ssl/certificate.pem'),
};

var app = express();

var server = https.createServer(options, app).listen(port, function(){
  console.log("Express server listening on port " + port);
});

app.get('/', function (req, res) {
    res.writeHead(200);
    res.end("hello world\n");
});

How to append a char to a std::string?

If you are using the push_back there is no call for the string constructor. Otherwise it will create a string object via casting, then it will add the character in this string to the other string. Too much trouble for a tiny character ;)

Pass Javascript Array -> PHP

AJAX requests are no different from GET and POST requests initiated through a <form> element. Which means you can use $_GET and $_POST to retrieve the data.

When you're making an AJAX request (jQuery example):

// JavaScript file

elements = [1, 2, 9, 15].join(',')
$.post('/test.php', {elements: elements})

It's (almost) equivalent to posting this form:

<form action="/test.php" method="post">
  <input type="text" name="elements" value="1,2,9,15">
</form>

In both cases, on the server side you can read the data from the $_POST variable:

// test.php file

$elements = $_POST['elements'];
$elements = explode(',', $elements);

For the sake of simplicity I'm joining the elements with comma here. JSON serialization is a more universal solution, though.

Setting Inheritance and Propagation flags with set-acl and powershell

Here's the MSDN page describing the flags and what is the result of their various combinations.

Flag combinations => Propagation results
=========================================
No Flags => Target folder.
ObjectInherit => Target folder, child object (file), grandchild object (file).
ObjectInherit and NoPropagateInherit => Target folder, child object (file).
ObjectInherit and InheritOnly => Child object (file), grandchild object (file).
ObjectInherit, InheritOnly, and NoPropagateInherit => Child object (file).
ContainerInherit => Target folder, child folder, grandchild folder.
ContainerInherit, and NoPropagateInherit => Target folder, child folder.
ContainerInherit, and InheritOnly => Child folder, grandchild folder.
ContainerInherit, InheritOnly, and NoPropagateInherit => Child folder.
ContainerInherit, and ObjectInherit => Target folder, child folder, child object (file), grandchild folder, grandchild object (file).
ContainerInherit, ObjectInherit, and NoPropagateInherit => Target folder, child folder, child object (file).
ContainerInherit, ObjectInherit, and InheritOnly => Child folder, child object (file), grandchild folder, grandchild object (file).
ContainerInherit, ObjectInherit, NoPropagateInherit, InheritOnly => Child folder, child object (file).

To have it apply the permissions to the directory, as well as all child directories and files recursively, you'll want to use these flags:

InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit 
PropagationFlags.None

So the specific code change you need to make for your example is:

$PropagationFlag = [System.Security.AccessControl.PropagationFlags]::None

How can I reverse a list in Python?

Here's a way to lazily evaluate the reverse using a generator:

def reverse(seq):
    for x in range(len(seq), -1, -1): #Iterate through a sequence starting from -1 and increasing by -1.
        yield seq[x] #Yield a value to the generator

Now iterate through like this:

for x in reverse([1, 2, 3]):
    print(x)

If you need a list:

l = list(reverse([1, 2, 3]))

UIView with rounded corners and drop shadow?

import UIKit

extension UIView {

    func addShadow(shadowColor: UIColor, offSet: CGSize, opacity: Float, shadowRadius: CGFloat, cornerRadius: CGFloat, corners: UIRectCorner, fillColor: UIColor = .white) {

        let shadowLayer = CAShapeLayer()
        let size = CGSize(width: cornerRadius, height: cornerRadius)
        let cgPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: size).cgPath //1
        shadowLayer.path = cgPath //2
        shadowLayer.fillColor = fillColor.cgColor //3
        shadowLayer.shadowColor = shadowColor.cgColor //4
        shadowLayer.shadowPath = cgPath
        shadowLayer.shadowOffset = offSet //5
        shadowLayer.shadowOpacity = opacity
        shadowLayer.shadowRadius = shadowRadius
        self.layer.addSublayer(shadowLayer)
    }
}

What is the best method of handling currency/money?

You can pass some options to number_to_currency (a standard Rails 4 view helper):

number_to_currency(12.0, :precision => 2)
# => "$12.00"

As posted by Dylan Markow

OS specific instructions in CMAKE: How to?

I want to leave this here because I struggled with this when compiling for Android in Windows with the Android SDK.

CMake distinguishes between TARGET and HOST platform.

My TARGET was Android so the variables like CMAKE_SYSTEM_NAME had the value "Android" and the variable WIN32 from the other answer here was not defined. But I wanted to know if my HOST system was Windows because I needed to do a few things differently when compiling on either Windows or Linux or IOs. To do that I used CMAKE_HOST_SYSTEM_NAME which I found is barely known or mentioned anywhere because for most people TARGEt and HOST are the same or they don't care.

Hope this helps someone somewhere...

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

For Swift 3+

Simply use UITableViewStyleGrouped and set the footer's height to zero with the following:

override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    return .leastNormalMagnitude
}

Regular expression: zero or more occurrences of optional character /

/*

If your delimiters are slash-based, escape it:

\/*

* means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.

How can I run an external command asynchronously from Python?

Considering "I don't have to wait for it to return", one of the easiest solutions will be this:

subprocess.Popen( \
    [path_to_executable, arg1, arg2, ... argN],
    creationflags = subprocess.CREATE_NEW_CONSOLE,
).pid

But... From what I read this is not "the proper way to accomplish such a thing" because of security risks created by subprocess.CREATE_NEW_CONSOLE flag.

The key things that happen here is use of subprocess.CREATE_NEW_CONSOLE to create new console and .pid (returns process ID so that you could check program later on if you want to) so that not to wait for program to finish its job.

How do you connect localhost in the Android emulator?

Thanks to author of this blog: https://bigdata-etl.com/solved-how-to-connect-from-android-emulator-to-application-on-localhost/

Defining network security config in xml

<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
       <domain includeSubdomains="true">10.0.2.2</domain>
    </domain-config>
</network-security-config>

And setting it on AndroidManifest.xml

 <application
    android:networkSecurityConfig="@xml/network_security_config"
</application>

Solved issue for me!

Please refer: https://developer.android.com/training/articles/security-config

Performing user authentication in Java EE / JSF using j_security_check

After searching the Web and trying many different ways, here's what I'd suggest for Java EE 6 authentication:

Set up the security realm:

In my case, I had the users in the database. So I followed this blog post to create a JDBC Realm that could authenticate users based on username and MD5-hashed passwords in my database table:

http://blog.gamatam.com/2009/11/jdbc-realm-setup-with-glassfish-v3.html

Note: the post talks about a user and a group table in the database. I had a User class with a UserType enum attribute mapped via javax.persistence annotations to the database. I configured the realm with the same table for users and groups, using the userType column as the group column and it worked fine.

Use form authentication:

Still following the above blog post, configure your web.xml and sun-web.xml, but instead of using BASIC authentication, use FORM (actually, it doesn't matter which one you use, but I ended up using FORM). Use the standard HTML , not the JSF .

Then use BalusC's tip above on lazy initializing the user information from the database. He suggested doing it in a managed bean getting the principal from the faces context. I used, instead, a stateful session bean to store session information for each user, so I injected the session context:

 @Resource
 private SessionContext sessionContext;

With the principal, I can check the username and, using the EJB Entity Manager, get the User information from the database and store in my SessionInformation EJB.

Logout:

I also looked around for the best way to logout. The best one that I've found is using a Servlet:

 @WebServlet(name = "LogoutServlet", urlPatterns = {"/logout"})
 public class LogoutServlet extends HttpServlet {
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   HttpSession session = request.getSession(false);

   // Destroys the session for this user.
   if (session != null)
        session.invalidate();

   // Redirects back to the initial page.
   response.sendRedirect(request.getContextPath());
  }
 }

Although my answer is really late considering the date of the question, I hope this helps other people that end up here from Google, just like I did.

Ciao,

Vítor Souza

Box shadow for bottom side only

Specify negative value to spread value. This works for me:

box-shadow: 0 2px 3px -1px rgba(0, 0, 0, 0.1);

How to write a confusion matrix in Python?

In a general sense, you're going to need to change your probability array. Instead of having one number for each instance and classifying based on whether or not it is greater than 0.5, you're going to need a list of scores (one for each class), then take the largest of the scores as the class that was chosen (a.k.a. argmax).

You could use a dictionary to hold the probabilities for each classification:

prob_arr = [{classification_id: probability}, ...]

Choosing a classification would be something like:

for instance_scores in prob_arr :
    predicted_classes = [cls for (cls, score) in instance_scores.iteritems() if score = max(instance_scores.values())]

This handles the case where two classes have the same scores. You can get one score, by choosing the first one in that list, but how you handle that depends on what you're classifying.

Once you have your list of predicted classes and a list of expected classes you can use code like Torsten Marek's to create the confusion array and calculate the accuracy.

IOS - How to segue programmatically using swift

If your segue exists in the storyboard with a segue identifier between your two views, you can just call it programmatically using:

performSegue(withIdentifier: "mySegueID", sender: nil)

For older versions:

performSegueWithIdentifier("mySegueID", sender: nil)

You could also do:

presentViewController(nextViewController, animated: true, completion: nil)

Or if you are in a Navigation controller:

self.navigationController?.pushViewController(nextViewController, animated: true)

Get startup type of Windows service using PowerShell

With PowerShell version 4:

You can run a command as given below:

   Get-Service | select -property name,starttype

Am I trying to connect to a TLS-enabled daemon without TLS?

I tried the solutions here, and boot2docker didn't work.

My solution: Uninstall boot2docker on the Mac, install a Centos 7 VM in VirtualBox, and work with Docker inside that VM.

How to Rotate a UIImage 90 degrees?

Simple. Just change the image orientation flag.

UIImage *oldImage = [UIImage imageNamed:@"whatever.jpg"];
UIImageOrientation newOrientation;
switch (oldImage.imageOrientation) {
    case UIImageOrientationUp:
        newOrientation = UIImageOrientationLandscapeLeft;
        break;
    case UIImageOrientationLandscapeLeft:
        newOrientation = UIImageOrientationDown;
        break;
    case UIImageOrientationDown:
        newOrientation = UIImageOrientationLandscapeRight;
        break;
    case UIImageOrientationLandscapeRight:
        newOrientation = UIImageOrientationUp;
        break;
    // you can also handle mirrored orientations similarly ...
}
UIImage *rotatedImage = [UIImage imageWithCGImage:oldImage.CGImage scale:1.0f orientation:newOrientation];

Filter dataframe rows if value in column is in a set list of values

you can also use ranges by using:

b = df[(df['a'] > 1) & (df['a'] < 5)]

Link a .css on another folder

I think what you want to do is

_x000D_
_x000D_
<link rel="stylesheet" type="text/css" href="font/font-face/my-font-face.css">
_x000D_
_x000D_
_x000D_

Your password does not satisfy the current policy requirements

Step 1: check your default authentication plugin

SHOW VARIABLES LIKE 'default_authentication_plugin';

Step 2: veryfing your password validation requirements

SHOW VARIABLES LIKE 'validate_password%';

Step 3: setting up your user with correct password requirements

CREATE USER '<your_user>'@'localhost' IDENTIFIED WITH '<your_default_auth_plugin>' BY 'password';

C# 4.0: Convert pdf to byte[] and vice versa

using (FileStream fs = new FileStream("sample.pdf", FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[fs.Length];
                int numBytesToRead = (int)fs.Length;
                int numBytesRead = 0;
                while (numBytesToRead > 0)
                {
                    // Read may return anything from 0 to numBytesToRead.
                    int n = fs.Read(bytes, numBytesRead, numBytesToRead);

                    // Break when the end of the file is reached.
                    if (n == 0)
                    {
                        break;
                    }

                    numBytesRead += n;
                    numBytesToRead -= n;
                }
                numBytesToRead = bytes.Length;
}

T-SQL: How to Select Values in Value List that are NOT IN the Table?

Use this : -- SQL Server 2008 or later

SELECT U.* 
FROM USERS AS U
Inner Join (
  SELECT   
    EMail, [Status]
  FROM
    (
      Values
        ('email1', 'Exist'),
        ('email2', 'Exist'),
        ('email3', 'Not Exist'),
        ('email4', 'Exist')
    )AS TempTableName (EMail, [Status])
  Where TempTableName.EMail IN ('email1','email2','email3')
) As TMP ON U.EMail = TMP.EMail

What is a "callable"?

A callable is anything that can be called.

The built-in callable (PyCallable_Check in objects.c) checks if the argument is either:

  • an instance of a class with a __call__ method or
  • is of a type that has a non null tp_call (c struct) member which indicates callability otherwise (such as in functions, methods etc.)

The method named __call__ is (according to the documentation)

Called when the instance is ''called'' as a function

Example

class Foo:
  def __call__(self):
    print 'called'

foo_instance = Foo()
foo_instance() #this is calling the __call__ method

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

This may be late, but sharing it for the new users visiting this question. To drop multiple columns actual syntax is

alter table tablename drop column col1, drop column col2 , drop column col3 ....

So for every column you need to specify "drop column" in Mysql 5.0.45.

How do I calculate the date six months from the current date using the datetime Python module?

How about this? Not using another library (dateutil) or timedelta? building on vartec's answer I did this and I believe it works:

import datetime

today = datetime.date.today()
six_months_from_today = datetime.date(today.year + (today.month + 6)/12, (today.month + 6) % 12, today.day)

I tried using timedelta, but because it is counting the days, 365/2 or 6*356/12 does not always translate to 6 months, but rather 182 days. e.g.

day = datetime.date(2015, 3, 10)
print day
>>> 2015-03-10

print (day + datetime.timedelta(6*365/12))
>>> 2015-09-08

I believe that we usually assume that 6 month's from a certain day will land on the same day of the month but 6 months later (i.e. 2015-03-10 --> 2015-09-10, Not 2015-09-08)

I hope you find this helpful.

How to add default signature in Outlook

I have made this a Community Wiki answer because I could not have created it without PowerUser's research and the help in earlier comments.

I took PowerUser's Sub X and added

Debug.Print "n------"    'with different values for n
Debug.Print ObjMail.HTMLBody

after every statement. From this I discovered the signature is not within .HTMLBody until after ObjMail.Display and then only if I haven't added anything to the body.

I went back to PowerUser's earlier solution that used C:\Users\" & Environ("username") & "\AppData\Roaming\Microsoft\Signatures\Mysig.txt"). PowerUser was unhappy with this because he wanted his solution to work for others who would have different signatures.

My signature is in the same folder and I cannot find any option to change this folder. I have only one signature so by reading the only HTM file in this folder, I obtained my only/default signature.

I created an HTML table and inserted it into the signature immediately following the <body> element and set the html body to the result. I sent the email to myself and the result was perfectly acceptable providing you like my formatting which I included to check that I could.

My modified subroutine is:

Sub X()

  Dim OlApp As Outlook.Application
  Dim ObjMail As Outlook.MailItem

  Dim BodyHtml As String
  Dim DirSig As String
  Dim FileNameHTMSig As String
  Dim Pos1 As Long
  Dim Pos2 As Long
  Dim SigHtm As String

  DirSig = "C:\Users\" & Environ("username") & _
                               "\AppData\Roaming\Microsoft\Signatures"

  FileNameHTMSig = Dir$(DirSig & "\*.htm")

  ' Code to handle there being no htm signature or there being more than one

  SigHtm = GetBoiler(DirSig & "\" & FileNameHTMSig)
  Pos1 = InStr(1, LCase(SigHtm), "<body")

  ' Code to handle there being no body

  Pos2 = InStr(Pos1, LCase(SigHtm), ">")

  ' Code to handle there being no closing > for the body element

   BodyHtml = "<table border=0 width=""100%"" style=""Color: #0000FF""" & _
         " bgColor=#F0F0F0><tr><td align= ""center"">HTML table</td>" & _
         "</tr></table><br>"
  BodyHtml = Mid(SigHtm, 1, Pos2 + 1) & BodyHtml & Mid(SigHtm, Pos2 + 2)

  Set OlApp = Outlook.Application
  Set ObjMail = OlApp.CreateItem(olMailItem)
  ObjMail.BodyFormat = olFormatHTML
  ObjMail.Subject = "Subject goes here"
  ObjMail.Recipients.Add "my email address"
  ObjMail.Display

End Sub

Since both PowerUser and I have found our signatures in C:\Users\" & Environ("username") & "\AppData\Roaming\Microsoft\Signatures I suggest this is the standard location for any Outlook installation. Can this default be changed? I cannot find anything to suggest it can. The above code clearly needs some development but it does achieve PowerUser's objective of creating an email body containing an HTML table above a signature.

Inner join with 3 tables in mysql

SELECT
  student.firstname,
  student.lastname,
  exam.name,
  exam.date,
  grade.grade
FROM grade
 INNER JOIN student
   ON student.studentId = grade.fk_studentId
 INNER JOIN exam
   ON exam.examId = grade.fk_examId
 GROUP BY grade.gradeId
 ORDER BY exam.date

How to iterate over the file in python

The traceback indicates that probably you have an empty line at the end of the file. You can fix it like this:

f = open('test.txt','r')
g = open('test1.txt','w') 
while True:
    x = f.readline()
    x = x.rstrip()
    if not x: break
    print >> g, int(x, 16)

On the other hand it would be better to use for x in f instead of readline. Do not forget to close your files or better to use with that close them for you:

with open('test.txt','r') as f:
    with open('test1.txt','w') as g: 
        for x in f:
            x = x.rstrip()
            if not x: continue
            print >> g, int(x, 16)

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

Although this is almost certainly not the OPs issue, you can also get Unable to establish SSL connection from wget if you're behind a proxy and don't have HTTP_PROXY and HTTPS_PROXY environment variables set correctly. Make sure to set HTTP_PROXY and HTTPS_PROXY to point to your proxy.

This is a common situation if you work for a large corporation.

Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

Works for any number from 0 to 999999999.

This program gets a number from the user, divides it into three parts and stores them separately in an array. The three numbers are passed through a function that convert them into words. Then it adds "million" to the first part and "thousand" to the second part.

#include <iostream>
using namespace std;
int buffer = 0, partFunc[3] = {0, 0, 0}, part[3] = {0, 0, 0}, a, b, c, d;
long input, nFake = 0;
const char ones[][20] = {"",       "one",       "two",      "three",
                         "four",    "five",      "six",      "seven",
                         "eight",   "nine",      "ten",      "eleven",
                         "twelve",  "thirteen",  "fourteen", "fifteen",
                         "sixteen", "seventeen", "eighteen", "nineteen"};
const char tens[][20] = {"",     "ten",   "twenty",  "thirty", "forty",
                         "fifty", "sixty", "seventy", "eighty", "ninety"};
void convert(int funcVar);
int main() {
  cout << "Enter the number:";
  cin >> input;
  nFake = input;
  buffer = 0;
  while (nFake) {
    part[buffer] = nFake % 1000;
    nFake /= 1000;
    buffer++;
  }
  if (buffer == 0) {
    cout << "Zero.";
  } else if (buffer == 1) {
    convert(part[0]);
  } else if (buffer == 2) {
    convert(part[1]);
    cout << " thousand,";
    convert(part[0]);
  } else {
    convert(part[2]);
    cout << " million,";

    if (part[1]) {
      convert(part[1]);
      cout << " thousand,";
    } else {
      cout << "";
    }
    convert(part[0]);
  }
  system("pause");
  return (0);
}

void convert(int funcVar) {
  buffer = 0;
  if (funcVar >= 100) {
    a = funcVar / 100;
    b = funcVar % 100;
    if (b)
      cout << " " << ones[a] << " hundred and";
    else
      cout << " " << ones[a] << " hundred ";
    if (b < 20)
      cout << " " << ones[b];
    else {
      c = b / 10;
      cout << " " << tens[c];
      d = b % 10;
      cout << " " << ones[d];
    }
  } else {
    b = funcVar;
    if (b < 20)
      cout << ones[b];
    else {
      c = b / 10;
      cout << tens[c];
      d = b % 10;
      cout << " " << ones[d];
    }
  }
}

Getting the IP address of the current machine using Java

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class IpAddress {

NetworkInterface ifcfg;
Enumeration<InetAddress> addresses;
String address;

public String getIpAddress(String host) {
    try {
        ifcfg = NetworkInterface.getByName(host);
        addresses = ifcfg.getInetAddresses();
        while (addresses.hasMoreElements()) {
            address = addresses.nextElement().toString();
            address = address.replace("/", "");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return ifcfg.toString();
}
}

how to place last div into right top corner of parent div? (css)

 <div class='block1'>
    <p  style="float:left">text</p>
    <div class='block2' style="float:right">block2</div>
    <p  style="float:left; clear:left">text2</p>

 </div>

You can clear:both or clear:left depending on the exact context. Also, you will have to play around with width to get it to work correctly...

How to replace comma with a dot in the number (or any replacement)

You can also do it like this:

var tt="88,9827";
tt=tt.replace(",", ".");
alert(tt);

working fiddle example

How to map atan2() to degrees 0-360

Just add 360° if the answer from atan2 is less than 0°.

What is recursion and when should I use it?

In the most basic computer science sense, recursion is a function that calls itself. Say you have a linked list structure:

struct Node {
    Node* next;
};

And you want to find out how long a linked list is you can do this with recursion:

int length(const Node* list) {
    if (!list->next) {
        return 1;
    } else {
        return 1 + length(list->next);
    }
}

(This could of course be done with a for loop as well, but is useful as an illustration of the concept)

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

Is calculating an MD5 hash less CPU intensive than SHA family functions?

Yes, MD5 is somewhat less CPU-intensive. On my Intel x86 (Core2 Quad Q6600, 2.4 GHz, using one core), I get this in 32-bit mode:

MD5       411
SHA-1     218
SHA-256   118
SHA-512    46

and this in 64-bit mode:

MD5       407
SHA-1     312
SHA-256   148
SHA-512   189

Figures are in megabytes per second, for a "long" message (this is what you get for messages longer than 8 kB). This is with sphlib, a library of hash function implementations in C (and Java). All implementations are from the same author (me) and were made with comparable efforts at optimizations; thus the speed differences can be considered as really intrinsic to the functions.

As a point of comparison, consider that a recent hard disk will run at about 100 MB/s, and anything over USB will top below 60 MB/s. Even though SHA-256 appears "slow" here, it is fast enough for most purposes.

Note that OpenSSL includes a 32-bit implementation of SHA-512 which is quite faster than my code (but not as fast as the 64-bit SHA-512), because the OpenSSL implementation is in assembly and uses SSE2 registers, something which cannot be done in plain C. SHA-512 is the only function among those four which benefits from a SSE2 implementation.

Edit: on this page (archive), one can find a report on the speed of many hash functions (click on the "Telechargez maintenant" link). The report is in French, but it is mostly full of tables and numbers, and numbers are international. The implemented hash functions do not include the SHA-3 candidates (except SHABAL) but I am working on it.

Xcode 5.1 - No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386)

Add arm64 to the target's valid architectures. Looks like it adds x86-64 architecture to simulator valid architectures as well.

Alter column, add default constraint

Try this

alter table TableName 
 add constraint df_ConstraintNAme 
 default getutcdate() for [Date]

example

create table bla (id int)

alter table bla add constraint dt_bla default 1 for id



insert bla default values

select * from bla

also make sure you name the default constraint..it will be a pain in the neck to drop it later because it will have one of those crazy system generated names...see also How To Name Default Constraints And How To Drop Default Constraint Without A Name In SQL Server

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

Default locations:

Programs > Microsoft SQL Server 2008 R2 > SQL Server Management Studio for Query Analyzer. Programs > Microsoft SQL Server 2008 R2 > Performance Tools > SQL Server Profiler for profiler.

Passing parameters to JavaScript files

Nice question and creative answers but my suggetion is to make your methods paramterized and that should solve all your problems without any tricks.

if you have function:

function A()
{
    var val = external_value_from_query_string_or_global_param;
}

you can change this to:

function B(function_param)
{
    var val = function_param;
}

I think this is most natural approach, you don't need to crate extra documentation about 'file parameters' and you receive the same. This specially useful if you allow other developers to use your js file.

CSS background-image - What is the correct usage?

1) putting quotes is a good habit

2) it can be relative path for example:

background-image: url('images/slides/background.jpg');

will look for images folder in the folder from which css is loaded. So if images are in another folder or out of the CSS folder tree you should use absolute path or relative to the root path (starting with /)

3) you should use complete declaration for background-image to make it behave consistently across standards compliant browsers like:

background:blue url('/images/clouds.jpg') no-repeat scroll left center;

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

This is the only thing that I found to work

-(void) testHTTPS {
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager setSecurityPolicy:securityPolicy];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    [manager GET:[NSString stringWithFormat:@"%@", HOST] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSLog(@"%@", string);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
}

Check if textbox has empty value

Also You can use

$value = $("#txt").val();

if($value == "")
{
    //Your Code Here
}
else
{
   //Your code
}

Try it. It work.

Slick.js: Get current and total slides (ie. 3/5)

This might help:

  • You don't need to enable dots or customPaging.
  • Position .slick-counter with CSS.

CSS

.slick-counter{
  position:absolute;
  top:5px;
  left:5px;
  background:yellow;
  padding:5px;
  opacity:0.8;
  border-radius:5px;
}

JavaScript

var $el = $('.slideshow');

$el.slick({
  slide: 'img',
  autoplay: true,
  onInit: function(e){
    $el.append('<div class="slick-counter">'+ parseInt(e.currentSlide + 1, 10) +' / '+ e.slideCount +'</div>');
  },
  onAfterChange: function(e){
    $el.find('.slick-counter').html(e.currentSlide + 1 +' / '+e.slideCount);
  }
});

http://jsfiddle.net/cpdqhdwy/6/

How do I use Assert.Throws to assert the type of the exception?

To expand on persistent's answer, and to provide more of the functionality of NUnit, you can do this:

public bool AssertThrows<TException>(
    Action action,
    Func<TException, bool> exceptionCondition = null)
    where TException : Exception
{
    try
    {
        action();
    }
    catch (TException ex)
    {
        if (exceptionCondition != null)
        {
            return exceptionCondition(ex);
        }
        return true;
    }
    catch
    {
        return false;
    }

    return false;
}

Examples:

// No exception thrown - test fails.
Assert.IsTrue(
    AssertThrows<InvalidOperationException>(
        () => {}));

// Wrong exception thrown - test fails.
Assert.IsTrue(
    AssertThrows<InvalidOperationException>(
        () => { throw new ApplicationException(); }));

// Correct exception thrown - test passes.
Assert.IsTrue(
    AssertThrows<InvalidOperationException>(
        () => { throw new InvalidOperationException(); }));

// Correct exception thrown, but wrong message - test fails.
Assert.IsTrue(
    AssertThrows<InvalidOperationException>(
        () => { throw new InvalidOperationException("ABCD"); },
        ex => ex.Message == "1234"));

// Correct exception thrown, with correct message - test passes.
Assert.IsTrue(
    AssertThrows<InvalidOperationException>(
        () => { throw new InvalidOperationException("1234"); },
        ex => ex.Message == "1234"));

how to set font size based on container size?

Another js alternative:

Working Example

fontsize = function () {
    var fontSize = $("#container").width() * 0.10; // 10% of container width
    $("#container h1").css('font-size', fontSize);
};
$(window).resize(fontsize);
$(document).ready(fontsize);

Or as stated in torazaburo's answer you could use svg. I put together a simple example as a proof of concept:

SVG Example

<div id="container">
    <svg width="100%" height="100%" viewBox="0 0 13 15">
        <text x="0" y="13">X</text>
    </svg>
</div>

How to install grunt and how to build script with it

To setup GruntJS build here is the steps:

  1. Make sure you have setup your package.json or setup new one:

    npm init
    
  2. Install Grunt CLI as global:

    npm install -g grunt-cli
    
  3. Install Grunt in your local project:

    npm install grunt --save-dev
    
  4. Install any Grunt Module you may need in your build process. Just for sake of this sample I will add Concat module for combining files together:

    npm install grunt-contrib-concat --save-dev
    
  5. Now you need to setup your Gruntfile.js which will describe your build process. For this sample I just combine two JS files file1.js and file2.js in the js folder and generate app.js:

    module.exports = function(grunt) {
    
        // Project configuration.
        grunt.initConfig({
            concat: {
                "options": { "separator": ";" },
                "build": {
                    "src": ["js/file1.js", "js/file2.js"],
                    "dest": "js/app.js"
                }
            }
        });
    
        // Load required modules
        grunt.loadNpmTasks('grunt-contrib-concat');
    
        // Task definitions
        grunt.registerTask('default', ['concat']);
    };
    
  6. Now you'll be ready to run your build process by following command:

    grunt
    

I hope this give you an idea how to work with GruntJS build.

NOTE:

You can use grunt-init for creating Gruntfile.js if you want wizard-based creation instead of raw coding for step 5.

To do so, please follow these steps:

npm install -g grunt-init
git clone https://github.com/gruntjs/grunt-init-gruntfile.git ~/.grunt-init/gruntfile
grunt-init gruntfile

For Windows users: If you are using cmd.exe you need to change ~/.grunt-init/gruntfile to %USERPROFILE%\.grunt-init\. PowerShell will recognize the ~ correctly.

MySQL CURRENT_TIMESTAMP on create and on update

I would say you don't need to have the DEFAULT CURRENT_TIMESTAMP on your ts_update: if it is empty, then it is not updated, so your 'last update' is the ts_create.

What are NDF Files?

Secondary data files are optional, are user-defined, and store user data. Secondary files can be used to spread data across multiple disks by putting each file on a different disk drive. Additionally, if a database exceeds the maximum size for a single Windows file, you can use secondary data files so the database can continue to grow.

Source: MSDN: Understanding Files and Filegroups

The recommended file name extension for secondary data files is .ndf, but this is not enforced.

Where is debug.keystore in Android Studio

[SOLVED] How I made my app run again after I had changed my username on same Windows 10 machine

In Android Studio, File > Project Structure > app > clicked “+” to add new configuration "config" File > Project Structure > app > Signing

In Flavors tab > Signing box, chose new "config" entry File > Project Structure > app > Flavors

This reconfigured the app. Closed & restarted Studio

Clicked Build > Rebuild Project

The app added and showed this automatically: build.gradle

When I tested the app on a cell phone, Studio asked to reinstall the app with this new configuration. App runs as before!

DynaMike

How to convert integers to characters in C?

void main ()
 {
    int temp,integer,count=0,i,cnd=0;
    char ascii[10]={0};
    printf("enter a number");
    scanf("%d",&integer);
     if(integer>>31)
     {
     /*CONVERTING 2's complement value to normal value*/    
     integer=~integer+1;    
     for(temp=integer;temp!=0;temp/=10,count++);    
     ascii[0]=0x2D;
     count++;
     cnd=1;
     }
     else
     for(temp=integer;temp!=0;temp/=10,count++);    
     for(i=count-1,temp=integer;i>=cnd;i--)
     {

        ascii[i]=(temp%10)+0x30;
        temp/=10;
     }
    printf("\n count =%d ascii=%s ",count,ascii);

 }

How to get javax.comm API?

Oracle Java Communications API Reference - http://www.oracle.com/technetwork/java/index-jsp-141752.html

Official 3.0 Download (Solarix, Linux) - http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-misc-419423.html

Unofficial 2.0 Download (All): http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm

Unofficial 2.0 Download (Windows installer) - http://kishor15389.blogspot.hk/2011/05/how-to-install-java-communications.html

In order to ensure there is no compilation error, place the file on your classpath when compiling (-cp command-line option, or check your IDE documentation).

Shell script to set environment variables

Run the script as source= to run in debug mode as well.

source= ./myscript.sh

How to check if number is divisible by a certain number?

n % x == 0

Means that n can be divided by x. So... for instance, in your case:

boolean isDivisibleBy20 = number % 20 == 0;

Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:

boolean even = (number & 1) == 0;
boolean odd  = (number & 1) != 0;

Python `if x is not None` or `if not x is None`?

Code should be written to be understandable to the programmer first, and the compiler or interpreter second. The "is not" construct resembles English more closely than "not is".

How to get the separate digits of an int number?

neither chars() nor codePoints() — the other lambda

String number = Integer.toString( 1100 );

IntStream.range( 0, number.length() ).map( i -> Character.digit( number.codePointAt( i ), 10 ) ).toArray();  // [1, 1, 0, 0]

how get yesterday and tomorrow datetime in c#

You should do it this way, if you want to get yesterday and tomorrow at 00:00:00 time:

DateTime yesterday = DateTime.Today.AddDays(-1);
DateTime tomorrow = DateTime.Today.AddDays(1); // Output example: 6. 02. 2016 00:00:00

Just bare in mind that if you do it this way:

DateTime yesterday = DateTime.Now.AddDays(-1);
DateTime tomorrow = DateTime.Now.AddDays(1); // Output example: 6. 02. 2016 18:09:23

then you will get the current time minus one day, and not yesterday at 00:00:00 time.

How do I update zsh to the latest version?

I just switched the main shell to zsh. It suppresses the warnings and it isn't too complicated.

How to create strings containing double quotes in Excel formulas?

Concatenate " as a ceparate cell:

    A |   B   | C | D
1   " | text  | " | =CONCATENATE(A1; B1; C1);

D1 displays "text"

Setting Spring Profile variable

For Tomcat 8:

Linux :

Create setenv.sh and update it with following:

export SPRING_PROFILES_ACTIVE=dev

Windows:

Create setenv.bat and update it with following:

set SPRING_PROFILES_ACTIVE=dev

Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>

The complete markup should be along these lines:

<select>
    <option selected disabled>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

You can take a look at this fiddle, and here's the result:

enter image description here

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

<select>
    <option selected disabled hidden>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

Check the fiddle here and the screenshot below.

enter image description here


Here is the solution:

<select>
    <option style="display:none;" selected>Select language</option>
    <option>Option 1</option>
    <option>Option 2</option>
</select>

How to interpolate variables in strings in JavaScript, without concatenation?

I wrote this npm package stringinject https://www.npmjs.com/package/stringinject which allows you to do the following

var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);

which will replace the {0} and {1} with the array items and return the following string

"this is a test string for stringInject"

or you could replace placeholders with object keys and values like so:

var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });

"My username is tjcafferkey on Github" 

Passing vector by reference

You can pass vector by reference just like this:

void do_something(int el, std::vector<int> &arr){
    arr.push_back(el);
}

However, note that this function would always add a new element at the back of the vector, whereas your array function actually modifies the first element (or initializes it value).

In order to achieve exactly the same result you should write:

void do_something(int el, std::vector<int> &arr){
    if (arr.size() == 0) { // can't modify value of non-existent element
        arr.push_back(el);
    } else {
        arr[0] = el;
    }
}

In this way you either add the first element (if the vector is empty) or modify its value (if there first element already exists).

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) {}
    }

Read from database and fill DataTable

Connection object is for illustration only. The DataAdapter is the key bit:

Dim strSql As String = "SELECT EmpCode,EmpID,EmpName FROM dbo.Employee"
Dim dtb As New DataTable
Using cnn As New SqlConnection(connectionString)
  cnn.Open()
  Using dad As New SqlDataAdapter(strSql, cnn)
    dad.Fill(dtb)
  End Using
  cnn.Close()
End Using

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

"Case" can return single value only, but you can use complex type:

create type foo as (a int, b text);
select (case 1 when 1 then (1,'qq')::foo else (2,'ww')::foo end).*;

How do you declare an interface in C++?

All good answers above. One extra thing you should keep in mind - you can also have a pure virtual destructor. The only difference is that you still need to implement it.

Confused?


    --- header file ----
    class foo {
    public:
      foo() {;}
      virtual ~foo() = 0;

      virtual bool overrideMe() {return false;}
    };

    ---- source ----
    foo::~foo()
    {
    }

The main reason you'd want to do this is if you want to provide interface methods, as I have, but make overriding them optional.

To make the class an interface class requires a pure virtual method, but all of your virtual methods have default implementations, so the only method left to make pure virtual is the destructor.

Reimplementing a destructor in the derived class is no big deal at all - I always reimplement a destructor, virtual or not, in my derived classes.