Programs & Examples On #Setup.py

setup.py is a Python script required by libraries packaged and distributed with Distutils.

What is setup.py?

To install a Python package you've downloaded, you extract the archive and run the setup.py script inside:

python setup.py install

To me, this has always felt odd. It would be more natural to point a package manager at the download, as one would do in Ruby and Nodejs, eg. gem install rails-4.1.1.gem

A package manager is more comfortable too, because it's familiar and reliable. On the other hand, each setup.py is novel, because it's specific to the package. It demands faith in convention "I trust this setup.py takes the same commands as others I have used in the past". That's a regrettable tax on mental willpower.

I'm not saying the setup.py workflow is less secure than a package manager (I understand Pip just runs the setup.py inside), but certainly I feel it's awkard and jarring. There's a harmony to commands all being to the same package manager application. You might even grow fond it.

Why is python setup.py saying invalid command 'bdist_wheel' on Travis CI?

If none of the above works for you, perhaps you are experiencing the same problem that I did. I was only seeing this error when attempting to install pyspark. The solution is explained in this other stackoverflow question unable to install pyspark.

I post this b/c it wasn't immediately obvious to me from the error message that my issue was stemming solely from pyspark's dependency on pypandoc and I'm hoping to save others from hours of head scratching! =)

python setup.py uninstall

Now python gives you the choice to install pip during the installation (I am on Windows, and at least python does so for Windows!). Considering you had chosen to install pip during installation of python (you don't actually have to choose because it is default), pip is already installed for you. Then, type in pip in command prompt, you should see a help come up. You can find necessary usage instructions there. E.g. pip list shows you the list of installed packages. You can use

pip uninstall package_name

to uninstall any package that you don't want anymore. Read more here (pip documentation).

No module named setuptools

The PyPA recommended tool for installing and managing Python packages is pip. pip is included with Python 3.4 (PEP 453), but for older versions here's how to install it (on Windows, using Python 3.3):

Download https://bootstrap.pypa.io/get-pip.py

>c:\Python33\python.exe get-pip.py
Downloading/unpacking pip
Downloading/unpacking setuptools
Installing collected packages: pip, setuptools
Successfully installed pip setuptools
Cleaning up...

Sample usage:

>c:\Python33\Scripts\pip.exe install pymysql
Downloading/unpacking pymysql
Installing collected packages: pymysql
Successfully installed pymysql
Cleaning up...

In your case it would be this (it appears that pip caches independent of Python version):

C:\Python27>python.exe \code\Python\get-pip.py
Requirement already up-to-date: pip in c:\python27\lib\site-packages
Collecting wheel
  Downloading wheel-0.29.0-py2.py3-none-any.whl (66kB)
    100% |################################| 69kB 255kB/s
Installing collected packages: wheel
Successfully installed wheel-0.29.0

C:\Python27>cd Scripts

C:\Python27\Scripts>pip install twilio
Collecting twilio
  Using cached twilio-5.3.0.tar.gz
Collecting httplib2>=0.7 (from twilio)
  Using cached httplib2-0.9.2.tar.gz
Collecting six (from twilio)
  Using cached six-1.10.0-py2.py3-none-any.whl
Collecting pytz (from twilio)
  Using cached pytz-2015.7-py2.py3-none-any.whl
Building wheels for collected packages: twilio, httplib2
  Running setup.py bdist_wheel for twilio ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e0\f2\a7\c57f6d153c440b93bd24c1243123f276dcacbf43cc43b7f906
  Running setup.py bdist_wheel for httplib2 ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e1\a3\05\e66aad1380335ee0a823c8f1b9006efa577236a24b3cb1eade
Successfully built twilio httplib2
Installing collected packages: httplib2, six, pytz, twilio
Successfully installed httplib2-0.9.2 pytz-2015.7 six-1.10.0 twilio-5.3.0

How do I install Python packages in Google's Colab?

Joining the party late, but just as a complement, I ran into some problems with Seaborn not so long ago, because CoLab installed a version with !pip that wasn't updated. In my specific case, I couldn't use Scatterplot, for example. The answer to this is below:

To install the module, all you need is:

!pip install seaborn

To upgrade it to the most updated version:

!pip install --upgrade seaborn

If you want to install a specific version

!pip install seaborn==0.9.0

I believe all the rules common to pip apply normally, so that pretty much should work.

error: Unable to find vcvarsall.bat

I tried many solutions but only one worked for me, the install of Microsoft Visual Studio 2008 Express C++.

I got this issue with a Python 2.7 module written in C (yEnc, which has other issues with MS VS). Note that Python 2.7 is built with MS VS 2008 version, not 2010!

Despite the fact it's free, it is quite hard to find since MS is promoting VS 2010. Still, the MSDN official very direct links are still working: check https://stackoverflow.com/a/15319069/2227298 for download links.

Python 3: ImportError "No Module named Setuptools"

For others with the same issue due to a different reason: This can also happen when there's a pyproject.toml in the same directory as the setup.py, even when setuptools is available.

Removing pyproject.toml fixed the issue for me.

Unable to convert MySQL date/time value to System.DateTime

In a Stimulsoft report add this parameter to the connection string (right click on datasource->edit)

Convert Zero Datetime=True;

Using a cursor with dynamic SQL in a stored procedure

First off, avoid using a cursor if at all possible. Here are some resources for rooting it out when it seems you can't do without:

There Must Be 15 Ways To Lose Your Cursors... part 1, Introduction

Row-By-Row Processing Without Cursor

That said, though, you may be stuck with one after all--I don't know enough from your question to be sure that either of those apply. If that's the case, you've got a different problem--the select statement for your cursor must be an actual SELECT statement, not an EXECUTE statement. You're stuck.

But see the answer from cmsjr (which came in while I was writing) about using a temp table. I'd avoid global cursors even more than "plain" ones....

Why can't I define a default constructor for a struct in .NET?

A struct is a value type and a value type must have a default value as soon as it is declared.

MyClass m;
MyStruct m2;

If you declare two fields as above without instantiating either, then break the debugger, m will be null but m2 will not. Given this, a parameterless constructor would make no sense, in fact all any constructor on a struct does is assign values, the thing itself already exists just by declaring it. Indeed m2 could quite happily be used in the above example and have its methods called, if any, and its fields and properties manipulated!

In SQL Server, how to create while loop in select

No functions, no cursors. Try this

with cte as(
select CHAR(65) chr, 65 i 
union all
select CHAR(i+1) chr, i=i+1 from cte
where CHAR(i) <'Z'
)
select * from(
SELECT id, Case when LEN(data)>len(REPLACE(data, chr,'')) then chr+chr end data 
FROM table1, cte) x
where Data is not null

Creating columns in listView and add items

You need to set property for the control:

listView1.View = View.Details;

Install a module using pip for specific python version

For Python 3

sudo apt-get install python3-pip
sudo pip3 install beautifulsoup4

For Python 2

sudo apt-get install python2-pip
sudo pip2 install beautifulsoup4

On Debian/Ubuntu, pip is the command to use when installing packages for Python 2, while pip3 is the command to use when installing packages for Python 3.

Why does JPA have a @Transient annotation?

Java's transient keyword is used to denote that a field is not to be serialized, whereas JPA's @Transient annotation is used to indicate that a field is not to be persisted in the database, i.e. their semantics are different.

find all the name using mysql query which start with the letter 'a'

try using CHARLIST as shown below:

select distinct name from artists where name RLIKE '^[abc]';

use distinct only if you want distinct values only. To read about it Click here.

Automatically add all files in a folder to a target using CMake?

Extension for @Kleist answer:

Since CMake 3.12 additional option CONFIGURE_DEPENDS is supported by commands file(GLOB) and file(GLOB_RECURSE). With this option there is no needs to manually re-run CMake after addition/deletion of a source file in the directory - CMake will be re-run automatically on next building the project.

However, the option CONFIGURE_DEPENDS implies that corresponding directory will be re-checked every time building is requested, so build process would consume more time than without CONFIGURE_DEPENDS.

Even with CONFIGURE_DEPENDS option available CMake documentation still does not recommend using file(GLOB) or file(GLOB_RECURSE) for collect the sources.

Adding Table rows Dynamically in Android

You can use an inflater with TableRow:

for (int i = 0; i < months; i++) {
    
    View view = getLayoutInflater ().inflate (R.layout.list_month_data, null, false);
        
    TextView textView = view.findViewById (R.id.title);
    
    textView.setText ("Text");
        
    tableLayout.addView (view);
    
}

Layout:

<TableRow
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_centerInParent="true"
    android:gravity="center_horizontal"
    android:paddingTop="15dp"
    android:paddingRight="15dp"
    android:paddingLeft="15dp"
    android:paddingBottom="10dp"
    >
    
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:gravity="center"
        />
    
</TableRow>

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

There is a bug in Chrome (not in Safari at the time we checked) that gives unexpected results in Javascript's various width and height measurements when opening tabs in the background (bug details here) - we logged the bug in June and it's remained unresolved since.

It's possible you've encountered the bug in what you're attempting to do.

Jquery Date picker Default Date

Use the defaultDate option

$( ".selector" ).datepicker({ defaultDate: '01/01/01' });

If you change your date format, make sure to change the input into defaultDate (e.g. '01-01-2001')

How to label each equation in align environment?

Usually my align environments are set up like

\begin{align} 
  \label{eqn1}
  \lambda_i + \mu_i = 0 \\
  \label{eqn2}
  \mu_i \xi_i = 0 \\
  \label{eqn3}
  \lambda_i [y_i( w^T x_i + b) - 1 + \xi_i] = 0
\end{align} 

The \label command should be placed in the line you want to reference, the placement in the line does not matter. I prefer to place it at the beginning at the line (as a sort of description) while others place them at the end.

How to install plugins to Sublime Text 2 editor?

Without Package Manager

I highly recommend using the Package Manager as described in other answers as it's far more convenient for both installing and updating. However, sometimes plugins are not in the directory, so here is the manual approach.

First off, find your Packages directory in your Application Support/Sublime Text 2 directory, for example:

~/Library/Application Support/Sublime Text 2/Packages

Now, take your Plugin folder (which you can download as a zip from GitHub, for example) and simply copy the folder into your Packages directory:

cp ~/Downloads/SomePlugin-master/ 
   ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/SomePlugin`

Restart Sublime Text 2 and boom! you're done.

With Package Manager

Refer to one of the other answers here or go to the Package Manager home page.

Bonus Points

If there's a plugin that isn't in the Package Manager, why not submit it on behalf of the author by following the steps found here.

Is Safari on iOS 6 caching $.ajax results?

For those that use Struts 1, here is how I fixed the issue.

web.xml

<filter>
    <filter-name>SetCacheControl</filter-name>
    <filter-class>com.example.struts.filters.CacheControlFilter</filter-class>
</filter>

<filter-mapping>
    <filter-name>SetCacheControl</filter-name>
    <url-pattern>*.do</url-pattern>
    <http-method>POST</http-method>
</filter-mapping>

com.example.struts.filters.CacheControlFilter.js

package com.example.struts.filters;

import java.io.IOException;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;

public class CacheControlFilter implements Filter {

        public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain) throws IOException, ServletException {

        HttpServletResponse resp = (HttpServletResponse) response;
        resp.setHeader("Expires", "Mon, 18 Jun 1973 18:00:00 GMT");
        resp.setHeader("Last-Modified", new Date().toString());
        resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
        resp.setHeader("Pragma", "no-cache");

        chain.doFilter(request, response);
    }

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void destroy() {
    }

}

What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64

Perhaps you're looking for the x86_64 ABI?

If that's not precisely what you're after, use 'x86_64 abi' in your preferred search engine to find alternative references.

HttpServletRequest get JSON POST data

Are you posting from a different source (so different port, or hostname)? If so, this very very recent topic I just answered might be helpful.

The problem was the XHR Cross Domain Policy, and a useful tip on how to get around it by using a technique called JSONP. The big downside is that JSONP does not support POST requests.

I know in the original post there is no mention of JavaScript, however JSON is usually used for JavaScript so that's why I jumped to that conclusion

How to set the height and the width of a textfield in Java?

What type of LayoutManager are you using for the panel you're adding the JTextField to?

Different layout managers approach sizing elements on them in different ways, some respect SetPreferredSize(), while others will scale the compoenents to fit their container.

See: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

ps. this has nothing to do with eclipse, its java.

How to check for null in Twig?

you can use the following code to check whether

{% if var is defined %}

var is variable is SET

{% endif %}

How to redirect the output of an application in background to /dev/null

These will also redirect both:

yourcommand  &> /dev/null

yourcommand  >& /dev/null

though the bash manual says the first is preferred.

Include CSS and Javascript in my django template

Read this https://docs.djangoproject.com/en/dev/howto/static-files/:

For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.

And try:

~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp

Then add 'myapp' to INSTALLED_APPS (myprj/settings.py).

~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html

Edit myprj/urls.py:

from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView

class HelloView(TemplateView):
    template_name = "hello.html"

urlpatterns = patterns('',
    url(r'^$', HelloView.as_view(), name='hello'),
)

And run it:

~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver

It works!

How to make android listview scrollable?

This is my working code. you may try with this.

row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/listEmployeeDetails"
        android:layout_height="match_parent" 
        android:layout_width="match_parent"
        android:layout_marginTop="5dp"
        android:layout_marginBottom="5dp"
        android:layout_gravity="center"
        android:background="#ffffff">

        <TextView android:id="@+id/tvEmpId"
                      android:layout_height="wrap_content"
                      android:textSize="12sp"
                      android:padding="2dp"
                      android:layout_width="0dp"
                      android:layout_weight="0.3"/>
            <TextView android:id="@+id/tvNameEmp"
                      android:layout_height="wrap_content"
                      android:textSize="12sp"                     
                      android:padding="2dp"
                      android:layout_width="0dp"
                      android:layout_weight="0.5"/>
             <TextView
                    android:layout_height="wrap_content"
                    android:id="@+id/tvStatusEmp"
                    android:textSize="12sp"
                    android:padding="2dp"
                    android:layout_width="0dp"
                    android:layout_weight="0.2"/>               
</LinearLayout> 

details.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/listEmployeeDetails"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/page_bg"
    android:orientation="vertical" >
    <LinearLayout
        android:id="@+id/lLayoutGrid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/page_bg"
        android:orientation="vertical" >

        ................... others components here............................

        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:alwaysDrawnWithCache="true"
            android:dividerHeight="1dp"
            android:horizontalSpacing="3dp"
            android:scrollingCache="true"
            android:smoothScrollbar="true"
            android:stretchMode="columnWidth"
            android:verticalSpacing="3dp" 
            android:layout_marginBottom="30dp">
        </ListView>
    </LinearLayout>
</RelativeLayout>

Adapter class :

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListViewAdapter extends BaseAdapter {
    private Context context;
    private List<EmployeeBean> employeeList; 

    publicListViewAdapter(Context context, List<EmployeeBean> employeeList) {
            this.context = context;
            this.employeeList = employeeList;
        }

    public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            EmployeeBeanHolder holder = null;
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            row = inflater.inflate(R.layout.row, parent, false);

            holder = new EmployeeBeanHolder();
            holder.employeeBean = employeeList.get(position);
            holder.tvEmpId = (TextView) row.findViewById(R.id.tvEmpId);
            holder.tvName = (TextView) row.findViewById(R.id.tvNameEmp);
            holder.tvStatus = (TextView) row.findViewById(R.id.tvStatusEmp);

            row.setTag(holder);
            holder.tvEmpId.setText(holder.employeeBean.getEmpId());
            holder.tvName.setText(holder.employeeBean.getName());
            holder.tvStatus.setText(holder.employeeBean.getStatus());

             if (position % 2 == 0) {
                    row.setBackgroundColor(Color.rgb(213, 229, 241));
                } else {                    
                    row.setBackgroundColor(Color.rgb(255, 255, 255));
                }        

            return row;
        }

   public static class EmployeeBeanHolder {
        EmployeeBean employeeBean;
        TextView tvEmpId;
        TextView tvName;
        TextView tvStatus;
    }

    @Override
    public int getCount() {
            return employeeList.size();
        }

    @Override
    public Object getItem(int position) {
            return null;
        }

    @Override
    public long getItemId(int position) {
            return 0;
    }
}

employee bean class:

public class EmployeeBean {
    private String empId;
    private String name;
    private String status;

    public EmployeeBean(){      
    }

    public EmployeeBean(String empId, String name, String status) {
        this.empId= empId;
        this.name = name;
        this.status = status;
    }

    public String getEmpId() {
        return empId;
    }

    public void setEmpId(String empId) {
        this.empId= empId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status =status;
    }
}

in Activity class:

onCreate method:

public static List<EmployeeBean> EMPLOYEE_LIST = new ArrayList<EmployeeBean>();

//create emplyee data
for(int i=0;i<=10;i++) {
  EmployeeBean emplyee = new EmployeeBean("EmpId"+i,"Name "+i, "Active");
  EMPLOYEE_LIST .add(emplyee );
}

ListView listView;
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(new ListViewAdapter(this, EMPLOYEE_LIST));

What is the difference between '@' and '=' in directive scope in AngularJS?

@ binds a local/directive scope property to the evaluated value of the DOM attribute. = binds a local/directive scope property to a parent scope property. & binding is for passing a method into your directive's scope so that it can be called within your directive.

@ Attribute string binding = Two-way model binding & Callback method binding

How do you convert a C++ string to an int?

Let me add my vote for boost::lexical_cast

#include <boost/lexical_cast.hpp>

int val = boost::lexical_cast<int>(strval) ;

It throws bad_lexical_cast on error.

Getting Checkbox Value in ASP.NET MVC 4

@Html.EditorFor(x => x.Remember)

Will generate:

<input id="Remember" type="checkbox" value="true" name="Remember" />
<input type="hidden" value="false" name="Remember" />

How does it work:

  • If checkbox remains unchecked, the form submits only the hidden value (false)
  • If checked, then the form submits two fields (false and true) and MVC sets true for the model's bool property

<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />

This will always send the default value, if checked.

How big can a MySQL database get before performance starts to degrade

In general this is a very subtle issue and not trivial whatsoever. I encourage you to read mysqlperformanceblog.com and High Performance MySQL. I really think there is no general answer for this.

I'm working on a project which has a MySQL database with almost 1TB of data. The most important scalability factor is RAM. If the indexes of your tables fit into memory and your queries are highly optimized, you can serve a reasonable amount of requests with a average machine.

The number of records do matter, depending of how your tables look like. It's a difference to have a lot of varchar fields or only a couple of ints or longs.

The physical size of the database matters as well: think of backups, for instance. Depending on your engine, your physical db files on grow, but don't shrink, for instance with innodb. So deleting a lot of rows, doesn't help to shrink your physical files.

There's a lot to this issues and as in a lot of cases the devil is in the details.

Javascript can't find element by id?

The problem is that you are trying to access the element before it exists. You need to wait for the page to be fully loaded. A possible approach is to use the onload handler:

window.onload = function () {
    var e = document.getElementById("db_info");
    e.innerHTML='Found you';
};

Most common JavaScript libraries provide a DOM-ready event, though. This is better, since window.onload waits for all images, too. You do not need that in most cases.

Another approach is to place the script tag right before your closing </body>-tag, since everything in front of it is loaded at the time of execution, then.

How to hide Android soft keyboard on EditText

weekText = (EditText) layout.findViewById(R.id.weekEditText);
weekText.setInputType(InputType.TYPE_NULL);

How to change screen resolution of Raspberry Pi

After uncommenting disable_overscan=1 follow my lead. In the link, http://elinux.org/RPiconfig when you search for Video options, you'll also get hdmi_group and hdmi_mode. For, hdmi_group choose 1 if you're using you TV as an video output or choose 2 for monitors. Then in hdmi_mode, you can select the resolution you want from the list. I chose :- hdmi_group=2 hdmi_mode=23 And it worked.enter image description here

python - checking odd/even numbers and changing outputs on number size

Regarding the printout, here's how I would do it using the Format Specification Mini Language (section: Aligning the text and specifying a width):

Once you have your length, say length = 11:

rowstring = '{{: ^{length:d}}}'.format(length = length) # center aligned, space-padded format string of length <length>
for i in xrange(length, 0, -2): # iterate from top to bottom with step size 2
    print rowstring.format( '*' * i )

What is __pycache__?

Python Version 2.x will have .pyc when interpreter compiles the code.

Python Version 3.x will have __pycache__ when interpreter compiles the code.

alok@alok:~$ ls
module.py  module.pyc  __pycache__  test.py
alok@alok:~$

Block Comments in a Shell Script

Use : ' to open and ' to close.

For example:

: '
This is a
very neat comment
in bash
'

This is from Vegas's example found here

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

$.ajax({
                    url:"",
                    type: "POST",
                    data: new FormData($('#uploadDatabaseForm')[0]),
                    contentType:false,
                    cache: false,
                    processData:false,
                    success:function (msg) {}
                  });

How to declare a variable in MySQL?

For any person using @variable in concat_ws function to get concatenated values, don't forget to reinitialize it with empty value. Otherwise it can use old value for same session.

Set @Ids = '';

select 
  @Ids := concat_ws(',',@Ids,tbl.Id),
  tbl.Col1,
  ...
from mytable tbl;

Similarity String Comparison in Java

Thank to the first answerer, I think there are 2 calculations of computeEditDistance(s1, s2). Due to high time spending of it, decided to improve the code's performance. So:

public class LevenshteinDistance {

public static int computeEditDistance(String s1, String s2) {
    s1 = s1.toLowerCase();
    s2 = s2.toLowerCase();

    int[] costs = new int[s2.length() + 1];
    for (int i = 0; i <= s1.length(); i++) {
        int lastValue = i;
        for (int j = 0; j <= s2.length(); j++) {
            if (i == 0) {
                costs[j] = j;
            } else {
                if (j > 0) {
                    int newValue = costs[j - 1];
                    if (s1.charAt(i - 1) != s2.charAt(j - 1)) {
                        newValue = Math.min(Math.min(newValue, lastValue),
                                costs[j]) + 1;
                    }
                    costs[j - 1] = lastValue;
                    lastValue = newValue;
                }
            }
        }
        if (i > 0) {
            costs[s2.length()] = lastValue;
        }
    }
    return costs[s2.length()];
}

public static void printDistance(String s1, String s2) {
    double similarityOfStrings = 0.0;
    int editDistance = 0;
    if (s1.length() < s2.length()) { // s1 should always be bigger
        String swap = s1;
        s1 = s2;
        s2 = swap;
    }
    int bigLen = s1.length();
    editDistance = computeEditDistance(s1, s2);
    if (bigLen == 0) {
        similarityOfStrings = 1.0; /* both strings are zero length */
    } else {
        similarityOfStrings = (bigLen - editDistance) / (double) bigLen;
    }
    //////////////////////////
    //System.out.println(s1 + "-->" + s2 + ": " +
      //      editDistance + " (" + similarityOfStrings + ")");
    System.out.println(editDistance + " (" + similarityOfStrings + ")");
}

public static void main(String[] args) {
    printDistance("", "");
    printDistance("1234567890", "1");
    printDistance("1234567890", "12");
    printDistance("1234567890", "123");
    printDistance("1234567890", "1234");
    printDistance("1234567890", "12345");
    printDistance("1234567890", "123456");
    printDistance("1234567890", "1234567");
    printDistance("1234567890", "12345678");
    printDistance("1234567890", "123456789");
    printDistance("1234567890", "1234567890");
    printDistance("1234567890", "1234567980");

    printDistance("47/2010", "472010");
    printDistance("47/2010", "472011");

    printDistance("47/2010", "AB.CDEF");
    printDistance("47/2010", "4B.CDEFG");
    printDistance("47/2010", "AB.CDEFG");

    printDistance("The quick fox jumped", "The fox jumped");
    printDistance("The quick fox jumped", "The fox");
    printDistance("The quick fox jumped",
            "The quick fox jumped off the balcany");
    printDistance("kitten", "sitting");
    printDistance("rosettacode", "raisethysword");
    printDistance(new StringBuilder("rosettacode").reverse().toString(),
            new StringBuilder("raisethysword").reverse().toString());
    for (int i = 1; i < args.length; i += 2) {
        printDistance(args[i - 1], args[i]);
    }


 }
}

Is it not possible to stringify an Error using JSON.stringify?

As no one is talking about the why part, I'm gonna answer it.

Why this JSON.stringify returns an empty object?

> JSON.stringify(error);
'{}'

Answer

From the document of JSON.stringify(),

For all the other Object instances (including Map, Set, WeakMap and WeakSet), only their enumerable properties will be serialized.

and Error object doesn't have its enumerable properties, that's why it prints an empty object.

getting a checkbox array value from POST

Check out the implode() function as an alternative. This will convert the array into a list. The first param is how you want the items separated. Here I have used a comma with a space after it.

$invite = implode(', ', $_POST['invite']);
echo $invite;

Inline elements shifting when made bold on hover

try this:

.nav {
  font-family: monospace;
}

Error when testing on iOS simulator: Couldn't register with the bootstrap server

This error used to occur in older versions of the iOS Simulator because older instances of a job in another device that was shutting down could collide with the new instance.

iOS 6.0 and later should not experience issues like this because iOS 6.0 introduced the usage of bootstrap subsets, and iOS 7.0 introduced the usage of a dedicated bootstrap server (launchd_sim) which is completely isolated from the host's bootstrap server.

SQL update from one Table to another based on a ID match

Generic answer for future developers.

SQL Server

UPDATE 
     t1
SET 
     t1.column = t2.column
FROM 
     Table1 t1 
     INNER JOIN Table2 t2 
     ON t1.id = t2.id;

Oracle (and SQL Server)

UPDATE 
     t1
SET 
     t1.colmun = t2.column 
FROM 
     Table1 t1, 
     Table2 t2 
WHERE 
     t1.ID = t2.ID;

MySQL

UPDATE 
     Table1 t1, 
     Table2 t2
SET 
     t1.column = t2.column 
WHERE
     t1.ID = t2.ID;

Archive the artifacts in Jenkins

Also, does Jenkins delete the artifacts after each build ? (not the archived artifacts, I know I can tell it to delete those)

No, Hudson/Jenkins does not, by itself, clear the workspace after a build. You might have actions in your build process that erase, overwrite, or move build artifacts from where you left them. There is an option in the job configuration, in Advanced Project Options (which must be expanded), called "Clean workspace before build" that will wipe the workspace at the beginning of a new build.

Setting focus to iframe contents

Using the contentWindow.focus() method, the timeout is probably necessary to wait for the iframe to be completely loaded.

For me, also using attribute onload="this.contentWindow.focus()" works, with firefox, into the iframe tag

How to re-sign the ipa file?

  1. Unzip the .ipa file by changing its extension with .zip
  2. Go to Payload. You will find .app file
  3. Right click the .app file and click Show package contents
  4. Delete the _CodeSigned folder
  5. Replace the embedded.mobileprovision file with the new provision profile
  6. Go to KeyChain Access and make sure the certificate associated with the provisional profile is present
  7. Execute the below mentioned command: /usr/bin/codesign -f -s "iPhone Distribution: Certificate Name" --resource-rules "Payload/Application.app/ResourceRules.plist" "Payload/Application.app"

  8. Now zip the Payload folder again and change the .zip extension with .ipa

Hope this helpful.

For reference follow below mentioned link: http://www.modelmetrics.com/tomgersic/codesign-re-signing-an-ipa-between-apple-accounts/

How do I get the directory that a program is running from?

The linux bash command which progname will report a path to program.

Even if one could issue the which command from within your program and direct the output to a tmp file and the program subsequently reads that tmp file, it will not tell you if that program is the one executing. It only tells you where a program having that name is located.

What is required is to obtain your process id number, and to parse out the path to the name

In my program I want to know if the program was executed from the user's bin directory or from another in the path or from /usr/bin. /usr/bin would contain the supported version. My feeling is that in Linux there is the one solution that is portable.

Binding List<T> to DataGridView in WinForm

Yes, it is possible to do with out rebinding by implementing INotifyPropertyChanged Interface.

Pretty Simple example is available here,

http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

How to remove all event handlers from an event

I found this answer and it almost fit my needs. Thanks to SwDevMan81 for the class. I have modified it to allow suppression and resumation of individual methods, and I thought I'd post it here.

// This class allows you to selectively suppress event handlers for controls.  You instantiate
// the suppressor object with the control, and after that you can use it to suppress all events
// or a single event.  If you try to suppress an event which has already been suppressed
// it will be ignored.  Same with resuming; you can resume all events which were suppressed,
// or a single one.  If you try to resume an un-suppressed event handler, it will be ignored.

//cEventSuppressor _supButton1 = null;
//private cEventSuppressor SupButton1 {
//    get {
//        if (_supButton1 == null) {
//            _supButton1 = new cEventSuppressor(this.button1);
//        }
//        return _supButton1;
//    }
//}
//private void button1_Click(object sender, EventArgs e) {
//    MessageBox.Show("Clicked!");
//}

//private void button2_Click(object sender, EventArgs e) {
//    SupButton1.Suppress("button1_Click");
//}

//private void button3_Click(object sender, EventArgs e) {
//    SupButton1.Resume("button1_Click");
//}
using System;
using System.Collections.Generic;
using System.Text;

using System.Reflection;
using System.Windows.Forms;
using System.ComponentModel;

namespace Crystal.Utilities {
    public class cEventSuppressor {
        Control _source;
        EventHandlerList _sourceEventHandlerList;
        FieldInfo _headFI;
        Dictionary<object, Delegate[]> suppressedHandlers = new Dictionary<object, Delegate[]>();
        PropertyInfo _sourceEventsInfo;
        Type _eventHandlerListType;
        Type _sourceType;

        public cEventSuppressor(Control control) {
            if (control == null)
                throw new ArgumentNullException("control", "An instance of a control must be provided.");

            _source = control;
            _sourceType = _source.GetType();
            _sourceEventsInfo = _sourceType.GetProperty("Events", BindingFlags.Instance | BindingFlags.NonPublic);
            _sourceEventHandlerList = (EventHandlerList)_sourceEventsInfo.GetValue(_source, null);
            _eventHandlerListType = _sourceEventHandlerList.GetType();
            _headFI = _eventHandlerListType.GetField("head", BindingFlags.Instance | BindingFlags.NonPublic);
        }
        private Dictionary<object, Delegate[]> BuildList() {
            Dictionary<object, Delegate[]> retval = new Dictionary<object, Delegate[]>();
            object head = _headFI.GetValue(_sourceEventHandlerList);
            if (head != null) {
                Type listEntryType = head.GetType();
                FieldInfo delegateFI = listEntryType.GetField("handler", BindingFlags.Instance | BindingFlags.NonPublic);
                FieldInfo keyFI = listEntryType.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
                FieldInfo nextFI = listEntryType.GetField("next", BindingFlags.Instance | BindingFlags.NonPublic);
                retval = BuildListWalk(retval, head, delegateFI, keyFI, nextFI);
            }
            return retval;
        }

        private Dictionary<object, Delegate[]> BuildListWalk(Dictionary<object, Delegate[]> dict,
                                    object entry, FieldInfo delegateFI, FieldInfo keyFI, FieldInfo nextFI) {
            if (entry != null) {
                Delegate dele = (Delegate)delegateFI.GetValue(entry);
                object key = keyFI.GetValue(entry);
                object next = nextFI.GetValue(entry);

                if (dele != null) {
                    Delegate[] listeners = dele.GetInvocationList();
                    if (listeners != null && listeners.Length > 0) {
                        dict.Add(key, listeners);
                    }
                }
                if (next != null) {
                    dict = BuildListWalk(dict, next, delegateFI, keyFI, nextFI);
                }
            }
            return dict;
        }
        public void Resume() {
        }
        public void Resume(string pMethodName) {
            //if (_handlers == null)
            //    throw new ApplicationException("Events have not been suppressed.");
            Dictionary<object, Delegate[]> toRemove = new Dictionary<object, Delegate[]>();

            // goes through all handlers which have been suppressed.  If we are resuming,
            // all handlers, or if we find the matching handler, add it back to the
            // control's event handlers
            foreach (KeyValuePair<object, Delegate[]> pair in suppressedHandlers) {

                for (int x = 0; x < pair.Value.Length; x++) {

                    string methodName = pair.Value[x].Method.Name;
                    if (pMethodName == null || methodName.Equals(pMethodName)) {
                        _sourceEventHandlerList.AddHandler(pair.Key, pair.Value[x]);
                        toRemove.Add(pair.Key, pair.Value);
                    }
                }
            }
            // remove all un-suppressed handlers from the list of suppressed handlers
            foreach (KeyValuePair<object, Delegate[]> pair in toRemove) {
                for (int x = 0; x < pair.Value.Length; x++) {
                    suppressedHandlers.Remove(pair.Key);
                }
            }
            //_handlers = null;
        }
        public void Suppress() {
            Suppress(null);
        }
        public void Suppress(string pMethodName) {
            //if (_handlers != null)
            //    throw new ApplicationException("Events are already being suppressed.");

            Dictionary<object, Delegate[]> dict = BuildList();

            foreach (KeyValuePair<object, Delegate[]> pair in dict) {
                for (int x = pair.Value.Length - 1; x >= 0; x--) {
                    //MethodInfo mi = pair.Value[x].Method;
                    //string s1 = mi.Name; // name of the method
                    //object o = pair.Value[x].Target;
                    // can use this to invoke method    pair.Value[x].DynamicInvoke
                    string methodName = pair.Value[x].Method.Name;

                    if (pMethodName == null || methodName.Equals(pMethodName)) {
                        _sourceEventHandlerList.RemoveHandler(pair.Key, pair.Value[x]);
                        suppressedHandlers.Add(pair.Key, pair.Value);
                    }
                }
            }
        }
    } 
}

Verify object attribute value with mockito

One more possibility, if you don't want to use ArgumentCaptor (for example, because you're also using stubbing), is to use Hamcrest Matchers in combination with Mockito.

import org.mockito.Mockito
import org.hamcrest.Matchers
...

Mockito.verify(mockedObject).someMethodOnMockedObject(MockitoHamcrest.argThat(
    Matchers.<SomeObjectAsArgument>hasProperty("propertyName", desiredValue)));

Is it possible to use 'else' in a list comprehension?

To use the else in list comprehensions in python programming you can try out the below snippet. This would resolve your problem, the snippet is tested on python 2.7 and python 3.5.

obj = ["Even" if i%2==0 else "Odd" for i in range(10)]

Action Image MVC3 Razor

You can create an extension method for HtmlHelper to simplify the code in your CSHTML file. You could replace your tags with a method like this:

// Sample usage in CSHTML
@Html.ActionImage("Edit", new { id = MyId }, "~/Content/Images/Image.bmp", "Edit")

Here is a sample extension method for the code above:

// Extension method
public static MvcHtmlString ActionImage(this HtmlHelper html, string action, object routeValues, string imagePath, string alt)
{
    var url = new UrlHelper(html.ViewContext.RequestContext);

    // build the <img> tag
    var imgBuilder = new TagBuilder("img");
    imgBuilder.MergeAttribute("src", url.Content(imagePath));
    imgBuilder.MergeAttribute("alt", alt);
    string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

    // build the <a> tag
    var anchorBuilder = new TagBuilder("a");
    anchorBuilder.MergeAttribute("href", url.Action(action, routeValues));
    anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
    string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

    return MvcHtmlString.Create(anchorHtml);
}

How do you make an element "flash" in jQuery

I can't believe this isn't on this question yet. All you gotta do:

("#someElement").show('highlight',{color: '#C8FB5E'},'fast');

This does exactly what you want it to do, is super easy, works for both show() and hide() methods.

How do I upload a file with metadata using a REST web service?

I agree with Greg that a two phase approach is a reasonable solution, however I would do it the other way around. I would do:

POST http://server/data/media
body:
{
    "Name": "Test",
    "Latitude": 12.59817,
    "Longitude": 52.12873
}

To create the metadata entry and return a response like:

201 Created
Location: http://server/data/media/21323
{
    "Name": "Test",
    "Latitude": 12.59817,
    "Longitude": 52.12873,
    "ContentUrl": "http://server/data/media/21323/content"
}

The client can then use this ContentUrl and do a PUT with the file data.

The nice thing about this approach is when your server starts get weighed down with immense volumes of data, the url that you return can just point to some other server with more space/capacity. Or you could implement some kind of round robin approach if bandwidth is an issue.

Float to String format specifier

In C#, float is an alias for System.Single (a bit like intis an alias for System.Int32).

DataTable, How to conditionally delete rows

I don't have a windows box handy to try this but I think you can use a DataView and do something like so:

DataView view = new DataView(ds.Tables["MyTable"]);
view.RowFilter = "MyValue = 42"; // MyValue here is a column name

// Delete these rows.
foreach (DataRowView row in view)
{
  row.Delete();
}

I haven't tested this, though. You might give it a try.

Find Java classes implementing an interface

If you were asking from the perspective of working this out with a running program then you need to look to the java.lang.* package. If you get a Class object, you can use the isAssignableFrom method to check if it is an interface of another Class.

There isn't a simple built in way of searching for these, tools like Eclipse build an index of this information.

If you don't have a specific list of Class objects to test you can look to the ClassLoader object, use the getPackages() method and build your own package hierarchy iterator.

Just a warning though that these methods and classes can be quite slow.

PHP Accessing Parent Class Variable

all the properties and methods of the parent class is inherited in the child class so theoretically you can access them in the child class but beware using the protected keyword in your class because it throws a fatal error when used in the child class.
as mentioned in php.net

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

Need help rounding to 2 decimal places

The problem will be that you cannot represent 0.575 exactly as a binary floating point number (eg a double). Though I don't know exactly it seems that the representation closest is probably just a bit lower and so when rounding it uses the true representation and rounds down.

If you want to avoid this problem then use a more appropriate data type. decimal will do what you want:

Math.Round(0.575M, 2, MidpointRounding.AwayFromZero)

Result: 0.58

The reason that 0.75 does the right thing is that it is easy to represent in binary floating point since it is simple 1/2 + 1/4 (ie 2^-1 +2^-2). In general any finite sum of powers of two can be represented in binary floating point. Exceptions are when your powers of 2 span too great a range (eg 2^100+2 is not exactly representable).

Edit to add:

Formatting doubles for output in C# might be of interest in terms of understanding why its so hard to understand that 0.575 is not really 0.575. The DoubleConverter in the accepted answer will show that 0.575 as an Exact String is 0.5749999999999999555910790149937383830547332763671875 You can see from this why rounding give 0.57.

Counting number of occurrences in column?

Put the following in B3 (credit to @Alexander-Ivanov for the countif condition):

={UNIQUE(A3:A),ARRAYFORMULA(COUNTIF(UNIQUE(A3:A),"=" & UNIQUE(A3:A)))}

Benefits: It only requires editing 1 cell, it includes the name filtered by uniqueness, and it is concise.

Downside: it runs the unique function 3x

To use the unique function only once, split it into 2 cells:

B3: =UNIQUE(A3:A)

C3: =ARRAYFORMULA(COUNTIF(B3:B,"=" & B3:B))

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

Stephen Darlington makes a very good point, and you can see that if you change my benchmark to use a more realistically sized table if I fill the table out to 10000 rows using the following:

begin 
  for i in 2 .. 10000 loop
    insert into t (NEEDED_FIELD, cond) values (i, 10);
  end loop;
end;

Then re-run the benchmarks. (I had to reduce the loop counts to 5000 to get reasonable times).

declare
  otherVar  number;
  cnt number;
begin
  for i in 1 .. 5000 loop
     select count(*) into cnt from t where cond = 0;

     if (cnt = 1) then
       select NEEDED_FIELD INTO otherVar from t where cond = 0;
     else
       otherVar := 0;
     end if;
   end loop;
end;
/

PL/SQL procedure successfully completed.

Elapsed: 00:00:04.34

declare
  otherVar  number;
begin
  for i in 1 .. 5000 loop
     begin
       select NEEDED_FIELD INTO otherVar from t where cond = 0;
     exception
       when no_data_found then
         otherVar := 0;
     end;
   end loop;
end;
/

PL/SQL procedure successfully completed.

Elapsed: 00:00:02.10

The method with the exception is now more than twice as fast. So, for almost all cases,the method:

SELECT NEEDED_FIELD INTO var WHERE condition;
EXCEPTION
WHEN NO_DATA_FOUND....

is the way to go. It will give correct results and is generally the fastest.

C++ IDE for Macs

It's not really an IDE per se, but I really like TextMate, and with the C++ bundle that ships with it, it can do a lot of the things you'd find in an IDE (without all the bloat!).

How to save MySQL query output to excel or .txt file?

From Save MySQL query results into a text or CSV file:

MySQL provides an easy mechanism for writing the results of a select statement into a text file on the server. Using extended options of the INTO OUTFILE nomenclature, it is possible to create a comma separated value (CSV) which can be imported into a spreadsheet application such as OpenOffice or Excel or any other application which accepts data in CSV format.

Given a query such as

SELECT order_id,product_name,qty FROM orders

which returns three columns of data, the results can be placed into the file /tmp/orders.txt using the query:

SELECT order_id,product_name,qty FROM orders
INTO OUTFILE '/tmp/orders.txt'

This will create a tab-separated file, each row on its own line. To alter this behavior, it is possible to add modifiers to the query:

SELECT order_id,product_name,qty FROM orders
INTO OUTFILE '/tmp/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

In this example, each field will be enclosed in double quotes, the fields will be separated by commas, and each row will be output on a new line separated by a newline (\n). Sample output of this command would look like:

"1","Tech-Recipes sock puppet","14.95" "2","Tech-Recipes chef's hat","18.95"

Keep in mind that the output file must not already exist and that the user MySQL is running as has write permissions to the directory MySQL is attempting to write the file to.

Syntax

   SELECT Your_Column_Name
    FROM Your_Table_Name
    INTO OUTFILE 'Filename.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

Or you could try to grab the output via the client:

You could try executing the query from the your local client and redirect the output to a local file destination:

mysql -user -pass -e "select cols from table where cols not null" > /tmp/output

Hint: If you don't specify an absoulte path but use something like INTO OUTFILE 'output.csv' or INTO OUTFILE './output.csv', it will store the output file to the directory specified by show variables like 'datadir';.

Apache shutdown unexpectedly

In my situation I had moved the htdocs to a new location updated in httpd.conf, which worked fine. I then received the same error after updating the httpd-vhost.conf file.

I found that the error was caused by a typo in the vhost configuration file. Previously I changed all "DocumentRoot" ’s to the new htdocs location, but had forgot to update the new location for "ErrorLog". After correcting the missing path, Apache was running smooth again.

What does void do in java?

The reason the code will not work without void is because the System.out.println(String string) method returns nothing and just prints the supplied arguments to the standard out terminal, which is the computer monitor in most cases. When a method returns "nothing" you have to specify that by putting the void keyword in its signature.

You can see the documentation of the System.out.println here:

http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html#println%28java.lang.String%29

To press the issue further, println is a classic example of a method which is performing computation as a "side effect."

How to delete a folder and all contents using a bat file in windows?

@RD /S /Q "D:\PHP_Projects\testproject\Release\testfolder"

Explanation:

Removes (deletes) a directory.

RMDIR [/S] [/Q] [drive:]path RD [/S] [/Q] [drive:]path

/S      Removes all directories and files in the specified directory
        in addition to the directory itself.  Used to remove a directory
        tree.

/Q      Quiet mode, do not ask if ok to remove a directory tree with /S

handle textview link click in my android app

Just to share an alternative solution using a library I created. With Textoo, this can be achieved like:

TextView locNotFound = Textoo
    .config((TextView) findViewById(R.id.view_location_disabled))
    .addLinksHandler(new LinksHandler() {
        @Override
        public boolean onClick(View view, String url) {
            if ("internal://settings/location".equals(url)) {
                Intent locSettings = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(locSettings);
                return true;
            } else {
                return false;
            }
        }
    })
    .apply();

Or with dynamic HTML source:

String htmlSource = "Links: <a href='http://www.google.com'>Google</a>";
Spanned linksLoggingText = Textoo
    .config(htmlSource)
    .parseHtml()
    .addLinksHandler(new LinksHandler() {
        @Override
        public boolean onClick(View view, String url) {
            Log.i("MyActivity", "Linking to google...");
            return false; // event not handled.  Continue default processing i.e. link to google
        }
    })
    .apply();
textView.setText(linksLoggingText);

Pygame Drawing a Rectangle

import pygame, sys
from pygame.locals import *

def main():
    pygame.init()

    DISPLAY=pygame.display.set_mode((500,400),0,32)

    WHITE=(255,255,255)
    BLUE=(0,0,255)

    DISPLAY.fill(WHITE)

    pygame.draw.rect(DISPLAY,BLUE,(200,150,100,50))

    while True:
        for event in pygame.event.get():
            if event.type==QUIT:
                pygame.quit()
                sys.exit()
        pygame.display.update()

main()

This creates a simple window 500 pixels by 400 pixels that is white. Within the window will be a blue rectangle. You need to use the pygame.draw.rect to go about this, and you add the DISPLAY constant to add it to the screen, the variable blue to make it blue (blue is a tuple that values which equate to blue in the RGB values and it's coordinates.

Look up pygame.org for more info

Android: show/hide status bar/power bar

For Some People, Showing status bar by clearing FLAG_FULLSCREEN may not work,

Here is the solution that worked for me, (Documentation) (Flag Reference)

Hide Status Bar

// Hide Status Bar
if (Build.VERSION.SDK_INT < 16) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
else {
   View decorView = getWindow().getDecorView();
  // Hide Status Bar.
   int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
   decorView.setSystemUiVisibility(uiOptions);
}

Show Status Bar

   if (Build.VERSION.SDK_INT < 16) {
              getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }
    else {
       View decorView = getWindow().getDecorView();
      // Show Status Bar.
       int uiOptions = View.SYSTEM_UI_FLAG_VISIBLE;
       decorView.setSystemUiVisibility(uiOptions);
    }

shell-script headers (#!/bin/sh vs #!/bin/csh)

This is known as a Shebang:

http://en.wikipedia.org/wiki/Shebang_(Unix)

#!interpreter [optional-arg]

A shebang is only relevant when a script has the execute permission (e.g. chmod u+x script.sh).

When a shell executes the script it will use the specified interpreter.

Example:

#!/bin/bash
# file: foo.sh
echo 1

$ chmod u+x foo.sh
$ ./foo.sh
  1

Dynamically add script tag with src that may include document.write

I tried it by recursively appending each script

Note If your scripts are dependent one after other, then position will need to be in sync.

Major Dependency should be in last in array so that initial scripts can use it

_x000D_
_x000D_
const scripts = ['https://www.gstatic.com/firebasejs/6.2.0/firebase-storage.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js']_x000D_
let count = 0_x000D_
_x000D_
  _x000D_
 const recursivelyAddScript = (script, cb) => {_x000D_
  const el = document.createElement('script')_x000D_
  el.src = script_x000D_
  if(count < scripts.length) {_x000D_
    count ++_x000D_
    el.onload = recursivelyAddScript(scripts[count])_x000D_
    document.body.appendChild(el)_x000D_
  } else {_x000D_
    console.log('All script loaded')_x000D_
    return_x000D_
  }_x000D_
}_x000D_
 _x000D_
  recursivelyAddScript(scripts[count])
_x000D_
_x000D_
_x000D_

How to calculate difference between two dates in oracle 11g SQL

basically the to_char(sysdate,'DDD') returns no of days from 1-jan-yyyy to sysdate so that if subtract two dates it will return that,you will get difference between two dates

select to_char(sysdate,'DDD') -to_char(to_date('19-08-1995','dd-mm-yyyy'),'DDD') from dual;

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

Try to trigger() event in your function:

$("form").trigger('submit'); // and then... do submit()

Check if string contains a value in array

Simple str_replace with count parameter would work here:

$count = 0;
str_replace($owned_urls, '', $string, $count);
// if replace is successful means the array value is present(Match Found).
if ($count > 0) {
  echo "One of Array value is present in the string.";
}

More Info - https://www.techpurohit.com/extended-behaviour-explode-and-strreplace-php

How do I turn off Oracle password expiration?

I believe that the password expiration behavior, by default, is to never expire. However, you could set up a profile for your dev user set and set the PASSWORD_LIFE_TIME. See the orafaq for more details. You can see here for an example of one person's perspective and usage.

Remove specific characters from a string in Python

How about this:

def text_cleanup(text):
    new = ""
    for i in text:
        if i not in " ?.!/;:":
            new += i
    return new

Git fatal: protocol 'https' is not supported

You tried this:

clt + V

Just right click and click on paste

Hope this will work

Pretty-Print JSON Data to a File using Python

You can use json module of python to pretty print.

>>> import json
>>> print json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4)
{
    "4": 5,
    "6": 7
}

So, in your case

>>> print json.dumps(json_output, indent=4)

How to change the Jupyter start-up folder

You can use a program called FileMenuTools from Lopesoft for your command prompt and just type 'jupyter notebook'.

Alternatively, you can also use it to create a dedicated shortcut using program C:/windows/System32/cmd.exe and arguments /k jupyter notebook --notebook-dir="%FOLDERPATH%" but this opens the notebook in the parent folder so you have to click down.

socket.emit() vs. socket.send()

https://socket.io/docs/client-api/#socket-send-args-ack

socket.send // Sends a message event

socket.emit(eventName[, ...args][, ack]) // you can custom eventName

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

There is also a great open source tool called clink, which extends cmd by many features. One of them is being able to use ctrl+v to insert text.

HTML: can I display button text in multiple lines?

This CSS might work for <input type="button" ..:

white-space: normal

How to generate a simple popup using jQuery

Try the Magnific Popup, it's responsive and weights just around 3KB.

Elegant Python function to convert CamelCase to snake_case?

I don't know why these are all so complicating.

for most cases, the simple expression ([A-Z]+) will do the trick

>>> re.sub('([A-Z]+)', r'_\1','CamelCase').lower()
'_camel_case'  
>>> re.sub('([A-Z]+)', r'_\1','camelCase').lower()
'camel_case'
>>> re.sub('([A-Z]+)', r'_\1','camel2Case2').lower()
'camel2_case2'
>>> re.sub('([A-Z]+)', r'_\1','camelCamelCase').lower()
'camel_camel_case'
>>> re.sub('([A-Z]+)', r'_\1','getHTTPResponseCode').lower()
'get_httpresponse_code'

To ignore the first character simply add look behind (?!^)

>>> re.sub('(?!^)([A-Z]+)', r'_\1','CamelCase').lower()
'camel_case'
>>> re.sub('(?!^)([A-Z]+)', r'_\1','CamelCamelCase').lower()
'camel_camel_case'
>>> re.sub('(?!^)([A-Z]+)', r'_\1','Camel2Camel2Case').lower()
'camel2_camel2_case'
>>> re.sub('(?!^)([A-Z]+)', r'_\1','getHTTPResponseCode').lower()
'get_httpresponse_code'

If you want to separate ALLCaps to all_caps and expect numbers in your string you still don't need to do two separate runs just use | This expression ((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z])) can handle just about every scenario in the book

>>> a = re.compile('((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))')
>>> a.sub(r'_\1', 'getHTTPResponseCode').lower()
'get_http_response_code'
>>> a.sub(r'_\1', 'get2HTTPResponseCode').lower()
'get2_http_response_code'
>>> a.sub(r'_\1', 'get2HTTPResponse123Code').lower()
'get2_http_response123_code'
>>> a.sub(r'_\1', 'HTTPResponseCode').lower()
'http_response_code'
>>> a.sub(r'_\1', 'HTTPResponseCodeXYZ').lower()
'http_response_code_xyz'

It all depends on what you want so use the solution that best suits your needs as it should not be overly complicated.

nJoy!

How do I remove the passphrase for the SSH key without having to create a new key?

On windows, you can use PuttyGen to load the private key file, remove the passphrase and then overwrite the existing private key file.

Using AND/OR in if else PHP statement

<?php
$val1 = rand(1,4); 
$val2=rand(1,4); 

if ($pars[$last0] == "reviews" && $pars[$last] > 0) { 
    echo widget("Bootstrap Theme - Member Profile - Read Review",'',$w[website_id],$w);
} else { ?>
    <div class="w100">
        <div style="background:transparent!important;" class="w100 well" id="postreview">
            <?php 
            $_GET[user_id] = $user[user_id];
            $_GET[member_id] = $_COOKIE[userid];
            $_GET[subaction] = "savereview"; 
            $_GET[ip] = $_SERVER[REMOTE_ADDR]; 
            $_GET[httpr] = $_ENV[requesturl]; 
            echo form("member_review","",$w[website_id],$w);?>
        </div></div>

ive replaced the 'else' with '&&' so both are placed ... argh

Capturing "Delete" Keypress with jQuery

event.key === "Delete"

More recent and much cleaner: use event.key. No more arbitrary number codes!

NOTE: The old properties (.keyCode and .which) are Deprecated.

document.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Delete") {
        // Do things
    }
});

Mozilla Docs

Supported Browsers

possibly undefined macro: AC_MSG_ERROR

For Debian. Required packages are: m4 automake pkg-config libtool

How to lock specific cells but allow filtering and sorting

This is a very old, but still very useful thread. I came here recently with the same issue. I suggest protecting the sheet when appropriate and unprotecting it when the filter row (eg Row 1) is selected. My solution doesn't use password protection - I don't need it (its a safeguard, not a security feature). I can't find an event handler that recognizes selection of a filter button - so I gave the instruction to my users to first select the filter cell then click the filter button. Here's what I advocate, (I only change protection if it needs to be changed, that may or may not save time - I don't know, but it "feels" right):

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  Const FilterRow = 1
  Dim c As Range
  Dim NotFilterRow As Boolean
  Dim oldstate As Boolean
  Dim ws As Worksheet
  Set ws = ActiveSheet
  oldstate = ws.ProtectContents
  NotFilterRow = False
  For Each c In Target.Cells
     NotFilterRow = c.Row <> FilterRow
     If NotFilterRow Then Exit For
  Next c
  If NotFilterRow <> oldstate Then
     If NotFilterRow Then
        ws.Protect
     Else
        ws.Unprotect
     End If
  End If
  Set ws = Nothing
End Sub

"Prevent saving changes that require the table to be re-created" negative effects

The table is only dropped and re-created in cases where that's the only way SQL Server's Management Studio has been programmed to know how to do it.

There are certainly cases where it will do that when it doesn't need to, but there will also be cases where edits you make in Management Studio will not drop and re-create because it doesn't have to.

The problem is that enumerating all of the cases and determining which side of the line they fall on will be quite tedious.

This is why I like to use ALTER TABLE in a query window, instead of visual designers that hide what they're doing (and quite frankly have bugs) - I know exactly what is going to happen, and I can prepare for cases where the only possibility is to drop and re-create the table (which is some number less than how often SSMS will do that to you).

Which ORM should I use for Node.js and MySQL?

May I suggest Node ORM?

https://github.com/dresende/node-orm2

There's documentation on the Readme, supports MySQL, PostgreSQL and SQLite.

MongoDB is available since version 2.1.x (released in July 2013)

UPDATE: This package is no longer maintained, per the project's README. It instead recommends bookshelf and sequelize

Set LIMIT with doctrine 2?

$query_ids = $this->getEntityManager()
      ->createQuery(
        "SELECT e_.id
        FROM MuzichCoreBundle:Element e_
        WHERE [...]
        GROUP BY e_.id")
     ->setMaxResults(5)
     ->setMaxResults($limit) 
    ;

HERE in the second query the result of the first query should be passed ..

$query_select = "SELECT e
      FROM MuzichCoreBundle:Element e 
      WHERE e.id IN (".$query_ids->getResult().")
      ORDER BY e.created DESC, e.name DESC"
    ;


$query = $this->getEntityManager()
      ->createQuery($query_select)
      ->setParameters($params)
      ->setMaxResults($limit);
    ;

$resultCollection = $query->getResult();

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

Updated Answer

Trying to open multiple panels of a collapse control that is setup as an accordion i.e. with the data-parent attribute set, can prove quite problematic and buggy (see this question on multiple panels open after programmatically opening a panel)

Instead, the best approach would be to:

  1. Allow each panel to toggle individually
  2. Then, enforce the accordion behavior manually where appropriate.

To allow each panel to toggle individually, on the data-toggle="collapse" element, set the data-target attribute to the .collapse panel ID selector (instead of setting the data-parent attribute to the parent control. You can read more about this in the question Modify Twitter Bootstrap collapse plugin to keep accordions open.

Roughly, each panel should look like this:

<div class="panel panel-default">
   <div class="panel-heading">
         <h4 class="panel-title"
             data-toggle="collapse" 
             data-target="#collapseOne">
             Collapsible Group Item #1
         </h4>
    </div>
    <div id="collapseOne" 
         class="panel-collapse collapse">
        <div class="panel-body"></div>
    </div>
</div>

To manually enforce the accordion behavior, you can create a handler for the collapse show event which occurs just before any panels are displayed. Use this to ensure any other open panels are closed before the selected one is shown (see this answer to multiple panels open). You'll also only want the code to execute when the panels are active. To do all that, add the following code:

$('#accordion').on('show.bs.collapse', function () {
    if (active) $('#accordion .in').collapse('hide');
});

Then use show and hide to toggle the visibility of each of the panels and data-toggle to enable and disable the controls.

$('#collapse-init').click(function () {
    if (active) {
        active = false;
        $('.panel-collapse').collapse('show');
        $('.panel-title').attr('data-toggle', '');
        $(this).text('Enable accordion behavior');
    } else {
        active = true;
        $('.panel-collapse').collapse('hide');
        $('.panel-title').attr('data-toggle', 'collapse');
        $(this).text('Disable accordion behavior');
    }
});

Working demo in jsFiddle

The request failed or the service did not respond in a timely fashion?

If you are running SQL Server in a local environment and not over a TCP/IP connection. Go to Protocols under SQL Server Configuration Manager, Properties, and disable TCP/IP. Once this is done then the error message will go away when restarting the service.

How to printf long long

  • Your scanf() statement needs to use %lld too.
  • Your loop does not have a terminating condition.
  • There are far too many parentheses and far too few spaces in the expression

    pi += pow(-1.0, e) / (2.0*e + 1.0);
    
  • You add one on the first iteration of the loop, and thereafter zero to the value of 'pi'; this does not change the value much.
  • You should use an explicit return type of int for main().
  • On the whole, it is best to specify int main(void) when it ignores its arguments, though that is less of a categorical statement than the rest.
  • I dislike the explicit licence granted in C99 to omit the return from the end of main() and don't use it myself; I write return 0; to be explicit.

I think the whole algorithm is dubious when written using long long; the data type probably should be more like long double (with %Lf for the scanf() format, and maybe %19.16Lf for the printf() formats.

How to change default text color using custom theme?

You can't use @android:style/TextAppearance as the parent for the whole app's theme; that's why koopaking3's solution seems quite broken.

To change default text colour everywhere in your app using a custom theme, try something like this. Works at least on Android 4.0+ (API level 14+).

res/values/themes.xml:

<resources>    
    <style name="MyAppTheme" parent="android:Theme.Holo.Light">
        <!-- Change default text colour from dark grey to black -->
        <item name="android:textColor">@android:color/black</item>
    </style>
</resources>

Manifest:

<application
    ...
    android:theme="@style/MyAppTheme">

Update

A shortcoming with the above is that also disabled Action Bar overflow menu items use the default colour, instead of being greyed out. (Of course, if you don't use disabled menu items anywhere in your app, this may not matter.)

As I learned by asking this question, a better way is to define the colour using a drawable:

<item name="android:textColor">@drawable/default_text_color</item>

...with res/drawable/default_text_color.xml specifying separate state_enabled="false" colour:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:color="@android:color/darker_gray"/>
    <item android:color="@android:color/black"/>
</selector>

Responsive Google Map?

It's better to use Google Map API. I've created an example here: http://jsfiddle.net/eugenebolotin/8m1s69e5/1/

Key features are using of functions:

//Full example is here: http://jsfiddle.net/eugenebolotin/8m1s69e5/1/

map.setCenter(map_center);
// Scale map to fit specified points
map.fitBounds(path_bounds);

It handles resize event and automaticaly adjusts size.

Clear android application user data

To clear Application Data Please Try this way.

    public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null &amp;&amp; dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete();
}

Django optional url parameters

You can use nested routes

Django <1.8

urlpatterns = patterns(''
    url(r'^project_config/', include(patterns('',
        url(r'^$', ProjectConfigView.as_view(), name="project_config")
        url(r'^(?P<product>\w+)$', include(patterns('',
            url(r'^$', ProductView.as_view(), name="product"),
            url(r'^(?P<project_id>\w+)$', ProjectDetailView.as_view(), name="project_detail")
        ))),
    ))),
)

Django >=1.8

urlpatterns = [
    url(r'^project_config/', include([
        url(r'^$', ProjectConfigView.as_view(), name="project_config")
        url(r'^(?P<product>\w+)$', include([
            url(r'^$', ProductView.as_view(), name="product"),
            url(r'^(?P<project_id>\w+)$', ProjectDetailView.as_view(), name="project_detail")
        ])),
    ])),
]

This is a lot more DRY (Say you wanted to rename the product kwarg to product_id, you only have to change line 4, and it will affect the below URLs.

Edited for Django 1.8 and above

How to set text color in submit button?

.btn{
    font-size: 20px;
    color:black;
}

Radio/checkbox alignment in HTML/CSS

I wouldn't use tables for this at all. CSS can easily do this.

I would do something like this:

   <p class="clearfix">
      <input id="option1" type="radio" name="opt" />
      <label for="option1">Option 1</label>
   </p>

p { margin: 0px 0px 10px 0px; }
input { float: left; width: 50px; }
label { margin: 0px 0px 0px 10px; float: left; }

Note: I have used the clearfix class from : http://www.positioniseverything.net/easyclearing.html

.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}

.clearfix {display: inline-block;}

/* Hides from IE-mac \*/
* html .clearfix {height: 1%;}
.clearfix {display: block;}
/* End hide from IE-mac */

Is there a simple way to use button to navigate page as a link does in angularjs

With bootstrap you can use

<a href="#/new-page.html" class="btn btn-primary">
    Click
</a>

How can I query for null values in entity framework?

There is a slightly simpler workaround that works with LINQ to Entities:

var result = from entry in table
         where entry.something == value || (value == null && entry.something == null)
         select entry;

This works becasuse, as AZ noticed, LINQ to Entities special cases x == null (i.e. an equality comparison against the null constant) and translates it to x IS NULL.

We are currently considering changing this behavior to introduce the compensating comparisons automatically if both sides of the equality are nullable. There are a couple of challenges though:

  1. This could potentially break code that already depends on the existing behavior.
  2. The new translation could affect the performance of existing queries even when a null parameter is seldom used.

In any case, whether we get to work on this is going to depend greatly on the relative priority our customers assign to it. If you care about the issue, I encourage you to vote for it in our new Feature Suggestion site: https://data.uservoice.com.

Reading all files in a directory, store them in objects, and send the object

So, there are three parts. Reading, storing and sending.

Here's the reading part:

var fs = require('fs');

function readFiles(dirname, onFileContent, onError) {
  fs.readdir(dirname, function(err, filenames) {
    if (err) {
      onError(err);
      return;
    }
    filenames.forEach(function(filename) {
      fs.readFile(dirname + filename, 'utf-8', function(err, content) {
        if (err) {
          onError(err);
          return;
        }
        onFileContent(filename, content);
      });
    });
  });
}

Here's the storing part:

var data = {};
readFiles('dirname/', function(filename, content) {
  data[filename] = content;
}, function(err) {
  throw err;
});

The sending part is up to you. You may want to send them one by one or after reading completion.

If you want to send files after reading completion you should either use sync versions of fs functions or use promises. Async callbacks is not a good style.

Additionally you asked about stripping an extension. You should proceed with questions one by one. Nobody will write a complete solution just for you.

Display an image with Python

In a much simpler way, you can do the same using

from PIL import Image

image = Image.open('image.jpg')
image.show()

What is Persistence Context?

"A set of persist-able (entity) instances managed by an entity manager instance at a given time" is called persistence context.

JPA @Entity annotation indicates a persist-able entity.

Refer JPA Definition here

How to call a C# function from JavaScript?

You can use a Web Method and Ajax:

<script type="text/javascript">             //Default.aspx
   function DeleteKartItems() {     
         $.ajax({
         type: "POST",
         url: 'Default.aspx/DeleteItem',
         data: "",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (msg) {
             $("#divResult").html("success");
         },
         error: function (e) {
             $("#divResult").html("Something Wrong.");
         }
     });
   }
</script>

[WebMethod]                                 //Default.aspx.cs
public static void DeleteItem()
{
    //Your Logic
}

Auto start print html page using javascript

Use this script

 <script type="text/javascript">
      window.onload = function() { window.print(); }
 </script>

Cloning a private Github repo

This worked for me:

git clone https://[email protected]/username/repo_name

Simple regular expression for a decimal with a precision of 2

Try this

 (\\+|-)?([0-9]+(\\.[0-9]+))

It will allow positive and negative signs also.

Easiest way to open a download window without navigating away from the page

I always add a target="_blank" to the download link. This will open a new window, but as soon as the user clicks save, the new window is closed.

Create a text file for download on-the-fly

Check out this SO question's accepted solution. Substitute your own filename for basename($File) and change filesize($File) to strlen($your_string). (You may want to use mb_strlen just in case the string contains multibyte characters.)

pip3: command not found

Try this if other methods do not work:

  1. brew install python3
  2. brew link --overwrite python
  3. brew postinstall python3

Login credentials not working with Gmail SMTP

I ran into a similar problem and stumbled on this question. I got an SMTP Authentication Error but my user name / pass was correct. Here is what fixed it. I read this:

https://support.google.com/accounts/answer/6010255

In a nutshell, google is not allowing you to log in via smtplib because it has flagged this sort of login as "less secure", so what you have to do is go to this link while you're logged in to your google account, and allow the access:

https://www.google.com/settings/security/lesssecureapps

Once that is set (see my screenshot below), it should work.

Less Secure Apps

Login now works:

smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login('[email protected]', 'me_pass')

Response after change:

(235, '2.7.0 Accepted')

Response prior:

smtplib.SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 g66sm2224117qgf.37 - gsmtp')

Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:

https://accounts.google.com/DisplayUnlockCaptcha

Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.

This doesn't seem to work right away you may be stuck for a while getting this error in smptlib:

235 == 'Authentication successful'
503 == 'Error: already authenticated'

The message says to use the browser to sign in:

SMTPAuthenticationError: (534, '5.7.9 Please log in with your web browser and then try again. Learn more at\n5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qo11sm4014232igb.17 - gsmtp')

After enabling 'lesssecureapps', go for a coffee, come back, and try the 'DisplayUnlockCaptcha' link again. From user experience, it may take up to an hour for the change to kick in. Then try the sign-in process again.

UPDATE:: See my answer here: How to send an email with Gmail as provider using Python?

What is the precise meaning of "ours" and "theirs" in git?

Just to clarify -- as noted above when rebasing the sense is reversed, so if you see

<<<<<<< HEAD
        foo = 12;
=======
        foo = 22;
>>>>>>> [your commit message]

Resolve using 'mine' -> foo = 12

Resolve using 'theirs' -> foo = 22

How do I center a Bootstrap div with a 'spanX' class?

Update

As of BS3 there's a .center-block helper class. From the docs:

// Classes
.center-block {
  display: block;
  margin-left: auto;
  margin-right: auto;
}

// Usage as mixins
.element {
  .center-block();
}

There is hidden complexity in this seemingly simple problem. All the answers given have some issues.

1. Create a Custom Class (Major Gotcha)

Create .col-centred class, but there is a major gotcha.

.col-centred {
   float: none !important;
   margin: 0 auto;
}

<!-- Bootstrap 3 -->
<div class="col-lg-6 col-centred">
  Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 col-centred">
  Centred content.
</div>

The Gotcha

Bootstrap requires columns add up to 12. If they do not they will overlap, which is a problem. In this case the centred column will overlap the column above it. Visually the page may look the same, but mouse events will not work on the column being overlapped (you can't hover or click links, for example). This is because mouse events are registering on the centred column that's overlapping the elements you try to click.

The Fixes

You can resolve this issue by using a clearfix element. Using z-index to bring the centred column to the bottom will not work because it will be overlapped itself, and consequently mouse events will work on it.

<div class="row">
  <div class="col-lg-12">
    I get overlapped by `col-lg-7 centered` unless there's a clearfix.
  </div>
  <div class="clearfix"></div>
  <div class="col-lg-7 centred">
  </div>
</div>

Or you can isolate the centred column in its own row.

<div class="row">
  <div class="col-lg-12">
  </div>
</div>
<div class="row">
  <div class="col-lg-7 centred">
    Look I am in my own row.
  </div>
</div>

2. Use col-lg-offset-x or spanx-offset (Major Gotcha)

<!-- Bootstrap 3 -->
<div class="col-lg-6 col-lg-offset-3">
  Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 span-offset-3">
  Centred content.
</div>

The first problem is that your centred column must be an even number because the offset value must divide evenly by 2 for the layout to be centered (left/right).

Secondly, as some have commented, using offsets is a bad idea. This is because when the browser resizes the offset will turn into blank space, pushing the actual content down the page.

3. Create an Inner Centred Column

This is the best solution in my opinion. No hacking required and you don't mess around with the grid, which could cause unintended consequences, as per solutions 1 and 2.

.col-centred {
   margin: 0 auto;
}

<div class="row">
  <div class="col-lg-12">
    <div class="centred">
        Look I am in my own row.
    </div>
  </div>
</div>

jQuery autocomplete tagging plug-in like StackOverflow's input tags?

This originally answered a supplemental question about the wisdom of downloading jQuery versus accessing it via a CDN, which is no longer present...

To answer the thing about Google. I have moved over to accessing JQuery and most other of these sorts of libraries via the corresponding CDN in my sites.

As more people do this means that it's more likely to be cached on user's machines, so my vote goes for good idea.

In the five years since I first offered this, it has become common wisdom.

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

I found that none of the answers provided actually worked for me; what actually worked for me is to do:

git push --set-upstream origin *BRANCHNAME*

After creating a new branch, then it gets tracked properly. (I have Git 2.7.4)

How do I convert a decimal to an int in C#?

System.Decimal implements the IConvertable interface, which has a ToInt32() member.

Does calling System.Decimal.ToInt32() work for you?

What is the difference between x86 and x64

Oddly enough it was an Intel thing not a Microsoft thing. X86 referred to the Intel CPU series from the 8086 to the 80486. The Pentium series still use the same addressing system. The x64 refers to the I64 addressing system that Intel came out with later for the 64-bit CPUs. So Windows was just following Intel's architecture naming.

How do include paths work in Visual Studio?

If you are only trying to change the include paths for a project and not for all solutions then in Visual Studio 2008 do this: Right-click on the name of the project in the Solution Navigator. From the popup menu select Properties. In the property pages dialog select Configuration Properties->C/C++/General. Click in the text box next to the "Additional Include Files" label and browse for the appropriate directory. Select OK.

What annoys me is that some of the answers to the original question asked do not apply to the version of Visual Studio that was mentioned.

Offset a background image from the right using CSS

If you would like to use this for adding arrows/other icons to a button for example then you could use css pseudo-elements?

If it's really a background-image for the whole button, I tend to incorporate the spacing into the image, and just use

background-position: right 0;

But if I have to add for example a designed arrow to a button, I tend to have this html:

<a href="[url]" class="read-more">Read more</a>

And tend to do the following with CSS:

.read-more{
    position: relative;
    padding: 6px 15px 6px 35px;//to create space on the right
    font-size: 13px;
    font-family: Arial;
}

.read-more:after{
    content: '';
    display: block;
    width: 10px;
    height: 15px;
    background-image: url('../images/btn-white-arrow-right.png');
    position: absolute;
    right: 12px;
    top: 10px;
}

By using the :after selector, I add a element using CSS just to contain this small icon. You could do the same by just adding a span or <i> element inside the a-element. But I think this is a cleaner way of adding icons to buttons and it is cross-browser supported.

you can check out the fiddle here: http://codepen.io/anon/pen/PNzYzZ

Background color in input and text fields

The best solution is the attribute selector in CSS (input[type="text"]) as the others suggested.

But if you have to support Internet Explorer 6, you cannot use it (QuirksMode). Well, only if you have to and also are willing to support it.

In this case your only option seems to be to define classes on input elements.

<input type="text" class="input-box" ... />
<input type="submit" class="button" ... />
...

and target them with a class selector:

input.input-box, textarea { background: cyan; }

How do I iterate over an NSArray?

Here is how you declare an array of strings and iterate over them:

NSArray *langs = @[@"es", @"en", @"pt", @"it", @"fr"];

for (int i = 0; i < [langs count]; i++) {
  NSString *lang = (NSString*) [langs objectAtIndex:i];
  NSLog(@"%@, ",lang);
}

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

Other possibility would be place the html in a non overflow:hidden element placed 'out' of screen, like a position absolute top and left lesse then 5000px, then read this elements height. Its ugly, but work well.

How to check if smtp is working from commandline (Linux)

Syntax for establishing a raw network connection using telnet is this:

telnet {domain_name} {port_number}

So telnet to your smtp server like

telnet smtp.mydomain.com 25

And copy and paste the below

helo client.mydomain.com
mail from:<[email protected]>
rcpt to:<[email protected]>
data
From: [email protected]
Subject: test mail from command line

this is test number 1
sent from linux box
.
quit

Note : Do not forgot the "." at the end which represents the end of the message. The "quit" line exits ends the session.

How to delete a file via PHP?

You can delete the file using

unlink($Your_file_path);

but if you are deleting a file from it's http path then this unlink is not work proper. You have to give a file path correct.

ionic build Android | error: No installed build tools found. Please install the Android build tools

In my case, the Enviroument Variable ANDROID_HOME was pointed to wrong (old) directory. I reallocated to correct one. In my case

ANDROID_HOME=F:\Program Files (x86)\Android\android-sdk

MySQL Insert query doesn't work with WHERE clause

A way to use INSERT and WHERE is

INSERT INTO MYTABLE SELECT 953,'Hello',43 WHERE 0 in (SELECT count(*) FROM MYTABLE WHERE myID=953); In this case ist like an exist-test. There is no exception if you run it two or more times...

How is the default max Java heap size determined?

Finally!

As of Java 8u191 you now have the options:

-XX:InitialRAMPercentage
-XX:MaxRAMPercentage
-XX:MinRAMPercentage

that can be used to size the heap as a percentage of the usable physical RAM. (which is same as the RAM installed less what the kernel uses).

See Release Notes for Java8 u191 for more information. Note that the options are mentioned under a Docker heading but in fact they apply whether you are in Docker environment or in a traditional environment.

The default value for MaxRAMPercentage is 25%. This is extremely conservative.

My own rule: If your host is more or less dedicated to running the given java application, then you can without problems increase dramatically. If you are on Linux, only running standard daemons and have installed RAM from somewhere around 1 Gb and up then I wouldn't hesitate to use 75% for the JVM's heap. Again, remember that this is 75% of the RAM available, not the RAM installed. What is left is the other user land processes that may be running on the host and the other types of memory that the JVM needs (eg for stack). All together, this will typically fit nicely in the 25% that is left. Obviously, with even more installed RAM the 75% is a safer and safer bet. (I wish the JDK folks had implemented an option where you could specify a ladder)

Setting the MaxRAMPercentage option look like this:

java -XX:MaxRAMPercentage=75.0  ....

Note that these percentage values are of 'double' type and therefore you must specify them with a decimal dot. You get a somewhat odd error if you use "75" instead of "75.0".

jquery - disable click

Use off() method after click event is triggered to disable element for the further click.

$('#clickElement').off('click');

How to make an element width: 100% minus padding?

What about wrapping it in a container. Container shoud have style like:

{
    width:100%;
    border: 10px solid transparent;
}

java.lang.UnsupportedClassVersionError Unsupported major.minor version 51.0

Make sure you're using the correct SDK when compiling/running and also, make sure you use source/target 1.7.

How to enable GZIP compression in IIS 7.5

If anyone runs across this and is looking for a bit more up-to-date answer or copy-paste answer or answer targeting multiple versions than JC Raja's post, here's what I've found:

Google's got a pretty solid, easy-to-understand introduction to how this works and what is advantageous and not. https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/optimize-encoding-and-transfer They recommend the HTML5 Boilerplate project, which has solutions for different versions of IIS:

  • .NET version 3
  • .NET version 4
  • .NET version 4.5 / MVC 5

Available here: https://github.com/h5bp/server-configs-iis They have web.configs that you can copy and paste changes from theirs to yours and see the changes, much easier than digging through a bunch of blog posts.

Here's the web.config settings for .NET version 4.5: https://github.com/h5bp/server-configs-iis/blob/master/dotnet%204.5/MVC5/Web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <!--
            Set compilation debug="true" to insert debugging
            symbols into the compiled page. Because this
            affects performance, set this value to true only
            during development.
    -->
    <compilation debug="true" targetFramework="4.5" />

    <!-- Security through obscurity, removes  X-AspNet-Version HTTP header from the response -->
    <!-- Allow zombie DOS names to be captured by ASP.NET (/con, /com1, /lpt1, /aux, /prt, /nul, etc) -->
    <httpRuntime targetFramework="4.5" requestValidationMode="2.0" requestPathInvalidCharacters="" enableVersionHeader="false" relaxedUrlToFileSystemMapping="true" />

    <!-- httpCookies httpOnlyCookies setting defines whether cookies 
             should be exposed to client side scripts
             false (Default): client side code can access cookies
             true: client side code cannot access cookies
             Require SSL is situational, you can also define the 
             domain of cookies with optional "domain" property -->
    <httpCookies httpOnlyCookies="true" requireSSL="false" />

    <trace writeToDiagnosticsTrace="false" enabled="false" pageOutput="false" localOnly="true" />
  </system.web>


  <system.webServer>
    <!-- GZip static file content.  Overrides the server default which only compresses static files over 2700 bytes -->
    <httpCompression directory="%SystemDrive%\websites\_compressed" minFileSizeForComp="1024">
      <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
      <staticTypes>
        <add mimeType="text/*" enabled="true" />
        <add mimeType="message/*" enabled="true" />
        <add mimeType="application/javascript" enabled="true" />
        <add mimeType="application/json" enabled="true" />
        <add mimeType="*/*" enabled="false" />
      </staticTypes>
    </httpCompression>

    <httpErrors existingResponse="PassThrough" errorMode="Custom">
      <!-- Catch IIS 404 error due to paths that exist but shouldn't be served (e.g. /controllers, /global.asax) or IIS request filtering (e.g. bin, web.config, app_code, app_globalresources, app_localresources, app_webreferences, app_data, app_browsers) -->
      <remove statusCode="404" subStatusCode="-1" />
      <error statusCode="404" subStatusCode="-1" path="/notfound" responseMode="ExecuteURL" />
      <remove statusCode="500" subStatusCode="-1" />
      <error statusCode="500" subStatusCode="-1" path="/error" responseMode="ExecuteURL" />
    </httpErrors>

    <directoryBrowse enabled="false" />
    <validation validateIntegratedModeConfiguration="false" />

    <!-- Microsoft sets runAllManagedModulesForAllRequests to true by default
             You should handle this according to need but consider the performance hit.
             Good source of reference on this matter: http://www.west-wind.com/weblog/posts/2012/Oct/25/Caveats-with-the-runAllManagedModulesForAllRequests-in-IIS-78
        -->
    <modules runAllManagedModulesForAllRequests="false" />

    <urlCompression doStaticCompression="true" doDynamicCompression="true" />
    <staticContent>
      <!-- Set expire headers to 30 days for static content-->
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
      <!-- use utf-8 encoding for anything served text/plain or text/html -->
      <remove fileExtension=".css" />
      <mimeMap fileExtension=".css" mimeType="text/css" />
      <remove fileExtension=".js" />
      <mimeMap fileExtension=".js" mimeType="text/javascript" />
      <remove fileExtension=".json" />
      <mimeMap fileExtension=".json" mimeType="application/json" />
      <remove fileExtension=".rss" />
      <mimeMap fileExtension=".rss" mimeType="application/rss+xml; charset=UTF-8" />
      <remove fileExtension=".html" />
      <mimeMap fileExtension=".html" mimeType="text/html; charset=UTF-8" />
      <remove fileExtension=".xml" />
      <mimeMap fileExtension=".xml" mimeType="application/xml; charset=UTF-8" />
      <!-- HTML5 Audio/Video mime types-->
      <remove fileExtension=".mp3" />
      <mimeMap fileExtension=".mp3" mimeType="audio/mpeg" />
      <remove fileExtension=".mp4" />
      <mimeMap fileExtension=".mp4" mimeType="video/mp4" />
      <remove fileExtension=".ogg" />
      <mimeMap fileExtension=".ogg" mimeType="audio/ogg" />
      <remove fileExtension=".ogv" />
      <mimeMap fileExtension=".ogv" mimeType="video/ogg" />
      <remove fileExtension=".webm" />
      <mimeMap fileExtension=".webm" mimeType="video/webm" />
      <!-- Proper svg serving. Required for svg webfonts on iPad -->
      <remove fileExtension=".svg" />
      <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
      <remove fileExtension=".svgz" />
      <mimeMap fileExtension=".svgz" mimeType="image/svg+xml" />
      <!-- HTML4 Web font mime types -->
      <!-- Remove default IIS mime type for .eot which is application/octet-stream -->
      <remove fileExtension=".eot" />
      <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
      <remove fileExtension=".ttf" />
      <mimeMap fileExtension=".ttf" mimeType="application/x-font-ttf" />
      <remove fileExtension=".ttc" />
      <mimeMap fileExtension=".ttc" mimeType="application/x-font-ttf" />
      <remove fileExtension=".otf" />
      <mimeMap fileExtension=".otf" mimeType="font/opentype" />
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
      <remove fileExtension=".crx" />
      <mimeMap fileExtension=".crx" mimeType="application/x-chrome-extension" />
      <remove fileExtension=".xpi" />
      <mimeMap fileExtension=".xpi" mimeType="application/x-xpinstall" />
      <remove fileExtension=".safariextz" />
      <mimeMap fileExtension=".safariextz" mimeType="application/octet-stream" />
      <!-- Flash Video mime types-->
      <remove fileExtension=".flv" />
      <mimeMap fileExtension=".flv" mimeType="video/x-flv" />
      <remove fileExtension=".f4v" />
      <mimeMap fileExtension=".f4v" mimeType="video/mp4" />
      <!-- Assorted types -->
      <remove fileExtension=".ico" />
      <mimeMap fileExtension=".ico" mimeType="image/x-icon" />
      <remove fileExtension=".webp" />
      <mimeMap fileExtension=".webp" mimeType="image/webp" />
      <remove fileExtension=".htc" />
      <mimeMap fileExtension=".htc" mimeType="text/x-component" />
      <remove fileExtension=".vcf" />
      <mimeMap fileExtension=".vcf" mimeType="text/x-vcard" />
      <remove fileExtension=".torrent" />
      <mimeMap fileExtension=".torrent" mimeType="application/x-bittorrent" />
      <remove fileExtension=".cur" />
      <mimeMap fileExtension=".cur" mimeType="image/x-icon" />
      <remove fileExtension=".webapp" />
      <mimeMap fileExtension=".webapp" mimeType="application/x-web-app-manifest+json; charset=UTF-8" />
    </staticContent>
    <httpProtocol>
      <customHeaders>

        <!--#### SECURITY Related Headers ###
            More information: https://www.owasp.org/index.php/List_of_useful_HTTP_headers
        -->
        <!--
                # Access-Control-Allow-Origin
                The 'Access Control Allow Origin' HTTP header is used to control which
                sites are allowed to bypass same-origin policies and send cross-origin requests.

                Secure configuration: Either do not set this header or return the 'Access-Control-Allow-Origin'
                header restricting it to only a trusted set of sites.
                http://enable-cors.org/

                <add name="Access-Control-Allow-Origin" value="*" />
                -->

        <!--
                # Cache-Control
                The 'Cache-Control' response header controls how pages can be cached
                either by proxies or the user's browser.
                This response header can provide enhanced privacy by not caching
                sensitive pages in the user's browser cache.

                <add name="Cache-Control" value="no-store, no-cache"/>
                -->

        <!--
                # Strict-Transport-Security
                The HTTP Strict Transport Security header is used to control
                if the browser is allowed to only access a site over a secure connection
                and how long to remember the server response for, forcing continued usage.
                Note* Currently a draft standard which only Firefox and Chrome support. But is supported by sites like PayPal.
                <add name="Strict-Transport-Security" value="max-age=15768000"/>
                -->

        <!--
                # X-Frame-Options
                The X-Frame-Options header indicates whether a browser should be allowed
                to render a page within a frame or iframe.
                The valid options are DENY (deny allowing the page to exist in a frame)
                or SAMEORIGIN (allow framing but only from the originating host)
                Without this option set, the site is at a higher risk of click-jacking.

                <add name="X-Frame-Options" value="SAMEORIGIN" />
                -->

        <!--
                # X-XSS-Protection
                The X-XSS-Protection header is used by Internet Explorer version 8+
                The header instructs IE to enable its inbuilt anti-cross-site scripting filter.
                If enabled, without 'mode=block', there is an increased risk that
                otherwise, non-exploitable cross-site scripting vulnerabilities may potentially become exploitable

                <add name="X-XSS-Protection" value="1; mode=block"/>
                -->

        <!--    
                # MIME type sniffing security protection
                Enabled by default as there are very few edge cases where you wouldn't want this enabled.
                Theres additional reading below; but the tldr, it reduces the ability of the browser (mostly IE) 
                being tricked into facilitating driveby attacks.
                http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx
                http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
        -->
        <add name="X-Content-Type-Options" value="nosniff" />

        <!-- A little extra security (by obscurity), removings fun but adding your own is better -->
        <remove name="X-Powered-By" />
        <add name="X-Powered-By" value="My Little Pony" />

        <!--
                 With Content Security Policy (CSP) enabled (and a browser that supports it (http://caniuse.com/#feat=contentsecuritypolicy),
         you can tell the browser that it can only download content from the domains you explicitly allow
         CSP can be quite difficult to configure, and cause real issues if you get it wrong
         There is website that helps you generate a policy here http://cspisawesome.com/
         <add name="Content-Security-Policy" "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' https://www.google-analytics.com;" />
                -->

        <!--//#### SECURITY Related Headers ###-->

        <!--
                Force the latest IE version, in various cases when it may fall back to IE7 mode
                github.com/rails/rails/commit/123eb25#commitcomment-118920
                Use ChromeFrame if it's installed for a better experience for the poor IE folk
                -->
        <add name="X-UA-Compatible" value="IE=Edge,chrome=1" />
        <!--
                Allow cookies to be set from iframes (for IE only)
                If needed, uncomment and specify a path or regex in the Location directive

                <add name="P3P" value="policyref=&quot;/w3c/p3p.xml&quot;, CP=&quot;IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT&quot;" />
                -->

      </customHeaders>
    </httpProtocol>

    <!--
        <rewrite>
            <rules>

            Remove/force the WWW from the URL.
            Requires IIS Rewrite module http://learn.iis.net/page.aspx/460/using-the-url-rewrite-module/
            Configuration lifted from http://nayyeri.net/remove-www-prefix-from-urls-with-url-rewrite-module-for-iis-7-0

            NOTE* You need to install the IIS URL Rewriting extension (Install via the Web Platform Installer)
            http://www.microsoft.com/web/downloads/platform.aspx

            ** Important Note
            using a non-www version of a webpage will set cookies for the whole domain making cookieless domains
            (eg. fast CD-like access to static resources like CSS, js, and images) impossible.

            # IMPORTANT: THERE ARE TWO RULES LISTED. NEVER USE BOTH RULES AT THE SAME TIME!

                <rule name="Remove WWW" stopProcessing="true">
                    <match url="^(.*)$" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
                    </conditions>
                    <action type="Redirect" url="http://example.com{PATH_INFO}" redirectType="Permanent" />
                </rule>
                <rule name="Force WWW" stopProcessing="true">
                    <match url=".*" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^example.com$" />
                    </conditions>
                    <action type="Redirect" url="http://www.example.com/{R:0}" redirectType="Permanent" />
                </rule>


                # E-TAGS
                E-Tags are actually quite useful in cache management especially if you have a front-end caching server such as Varnish. http://en.wikipedia.org/wiki/HTTP_ETag / http://developer.yahoo.com/performance/rules.html#etags
                But in load balancing and simply most cases ETags are mishandled in IIS, and it can be advantageous to remove them.
        # removed as in https://stackoverflow.com/questions/7947420/iis-7-5-remove-etag-headers-from-response

        <rewrite>
           <outboundRules>
              <rule name="Remove ETag">
                 <match serverVariable="RESPONSE_ETag" pattern=".+" />
                 <action type="Rewrite" value="" />
              </rule>
           </outboundRules>
        </rewrite>

            -->
    <!--
            ### Built-in filename-based cache busting

            In a managed language such as .net, you should really be using the internal bundler for CSS + js
            or get cassette or similar.

            If you're not using the build script to manage your filename version revving,
            you might want to consider enabling this, which will route requests for
            /css/style.20110203.css to /css/style.css

            To understand why this is important and a better idea than all.css?v1231,
            read: github.com/h5bp/html5-boilerplate/wiki/Version-Control-with-Cachebusting

                <rule name="Cachebusting">
                    <match url="^(.+)\.\d+(\.(js|css|png|jpg|gif)$)" />
                    <action type="Rewrite" url="{R:1}{R:2}" />
                </rule>

            </rules>
        </rewrite>-->

  </system.webServer>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Edit: One update if you need Gzip compression on WebAPI responses. I wasn't aware our WebAPI wasn't returning Gzipped responses until recently and scratched my head for a while because we had dynamic and static compression turned on in web.config. We looked at writing our own compression services and response handlers (still on WebAPI 2 not on .NET Core where it's easier now), but that was too cumbersome for what seemed like something we should just be able to turn on.

(If you're interested here's what we were looking at for our own compression service https://krzysztofjakielaszek.com/2017/03/26/webapi2-response-compression-gzip-brotli-deflate/ EDIT: Link is now offline, but you can view the code/content here: https://web.archive.org/web/20190608161201/https://krzysztofjakielaszek.com/2017/03/26/webapi2-response-compression-gzip-brotli-deflate/ )

Instead, we found this great post by Ben Foster (http://benfoster.io/blog/aspnet-web-api-compression) If you can modify applicationHost.config (running your own servers), you can pop that config file open and add the mimeTypes you want to compress (I pulled the relevant ones based on what our API was returning to clients from our Web.Config). Save that file, IIS will pickup your changes, recycle app pools, and your WebAPI will start returning gzip compressed responses to clients who request it.

If you don't see gzipped responses, check the response content type with Fiddler or Chrome/Firefox Dev Tools, and ensure it matches what you added. I had to change the view mode (use large request rows) in Chrome Dev Tools to ensure it showed the total size vs transferred size. If everything validates, try rebooting the server once to just ensure it was properly applied. I did have one syntax error where when I opened up the site in IIS, IIS poppped open a message about a parsing error that I had to fix in the config file.

<httpCompression directory="%TEMP%\iisexpress\IIS Temporary Compressed Files">
    <scheme name="gzip" dll="%IIS_BIN%\gzip.dll" />
    <dynamicTypes>
        ...

        <!-- compress JSON responses from Web API -->           
        <add mimeType="application/json" enabled="true" /> 

        ...
    </dynamicTypes>
    <staticTypes>
        ...
    </staticTypes>
</httpCompression>

How to control the line spacing in UILabel

This should help with it. You can then assign your label to this custom class within the storyboard and use it's parameters directly within the properties:

open class SpacingLabel : UILabel {

    @IBInspectable open var lineHeight:CGFloat = 1 {
        didSet {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.lineSpacing = 1.0
            paragraphStyle.lineHeightMultiple = self.lineHeight
            paragraphStyle.alignment = self.textAlignment

            let attrString = NSMutableAttributedString(string: self.text!)
            attrString.addAttribute(NSAttributedStringKey.font, value: self.font, range: NSMakeRange(0, attrString.length))
            attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
            self.attributedText = attrString
        }
    } 
}

Remove First and Last Character C++

My BASIC interpreter chops beginning and ending quotes with

str->pop_back();
str->erase(str->begin());

Of course, I always expect well-formed BASIC style strings, so I will abort with failed assert if not:

assert(str->front() == '"' && str->back() == '"');

Just my two cents.

Rename a file using Java

Running code is here.

private static void renameFile(File fileName) {

    FileOutputStream fileOutputStream =null;

    BufferedReader br = null;
    FileReader fr = null;

    String newFileName = "yourNewFileName"

    try {
        fileOutputStream = new FileOutputStream(newFileName);

        fr = new FileReader(fileName);
        br = new BufferedReader(fr);

        String sCurrentLine;

        while ((sCurrentLine = br.readLine()) != null) {
            fileOutputStream.write(("\n"+sCurrentLine).getBytes());
        }

        fileOutputStream.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            fileOutputStream.close();
            if (br != null)
                br.close();

            if (fr != null)
                fr.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

How to plot an array in python?

if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:

np.squeez doc: Remove single-dimensional entries from the shape of an array.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()

But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:

Jupyter matplotlib plot

Why isn't Python very good for functional programming?

Guido has a good explanation of this here. Here's the most relevant part:

I have never considered Python to be heavily influenced by functional languages, no matter what people say or think. I was much more familiar with imperative languages such as C and Algol 68 and although I had made functions first-class objects, I didn't view Python as a functional programming language. However, earlier on, it was clear that users wanted to do much more with lists and functions.

...

It is also worth noting that even though I didn't envision Python as a functional language, the introduction of closures has been useful in the development of many other advanced programming features. For example, certain aspects of new-style classes, decorators, and other modern features rely upon this capability.

Lastly, even though a number of functional programming features have been introduced over the years, Python still lacks certain features found in “real” functional programming languages. For instance, Python does not perform certain kinds of optimizations (e.g., tail recursion). In general, because Python's extremely dynamic nature, it is impossible to do the kind of compile-time optimization known from functional languages like Haskell or ML. And that's fine.

I pull two things out of this:

  1. The language's creator doesn't really consider Python to be a functional language. Therefore, it's possible to see "functional-esque" features, but you're unlikely to see anything that is definitively functional.
  2. Python's dynamic nature inhibits some of the optimizations you see in other functional languages. Granted, Lisp is just as dynamic (if not more dynamic) as Python, so this is only a partial explanation.

angular js unknown provider

Your code looks good, in fact it works (apart from the calls themselves) when copied & pasted into a sample jsFiddle: http://jsfiddle.net/VGaWD/

Hard to say what is going on without seeing a more complete example but I hope that the above jsFiddle will be helpful. What I'm suspecting is that you are not initializing your app with the 'productServices' module. It would give the same error, we can see this in another jsFiddle: http://jsfiddle.net/a69nX/1/

If you are planning to work with AngularJS and MongoLab I would suggest using an existing adapter for the $resource and MongoLab: https://github.com/pkozlowski-opensource/angularjs-mongolab It eases much of the pain working with MongoLab, you can see it in action here: http://jsfiddle.net/pkozlowski_opensource/DP4Rh/ Disclaimer! I'm maintaining this adapter (written based on AngularJS examples) so I'm obviously biased here.

Escaping Strings in JavaScript

You can also use this

_x000D_
_x000D_
let str = "hello single ' double \" and slash \\ yippie";

let escapeStr = escape(str);
document.write("<b>str : </b>"+str);
document.write("<br/><b>escapeStr : </b>"+escapeStr);
document.write("<br/><b>unEscapeStr : </b> "+unescape(escapeStr));
_x000D_
_x000D_
_x000D_

What is the maximum length of a String in PHP?

The maximum length of a string variable is only 2GiB - (2^(32-1) bits). Variables can be addressed on a character (8 bits/1 byte) basis and the addressing is done by signed integers which is why the limit is what it is. Arrays can contain multiple variables that each follow the previous restriction but can have a total cumulative size up to memory_limit of which a string variable is also subject to.

angular2 submit form by pressing enter without submit button

You can also add (keyup.enter)="xxxx()"

Completely remove MariaDB or MySQL from CentOS 7 or RHEL 7

These steps are working on CentOS 6.5 so they should work on CentOS 7 too:

(EDIT - exactly the same steps work for MariaDB 10.3 on CentOS 8)

  1. yum remove mariadb mariadb-server
  2. rm -rf /var/lib/mysql If your datadir in /etc/my.cnf points to a different directory, remove that directory instead of /var/lib/mysql
  3. rm /etc/my.cnf the file might have already been deleted at step 1
  4. Optional step: rm ~/.my.cnf
  5. yum install mariadb mariadb-server

[EDIT] - Update for MariaDB 10.1 on CentOS 7

The steps above worked for CentOS 6.5 and MariaDB 10.

I've just installed MariaDB 10.1 on CentOS 7 and some of the steps are slightly different.

Step 1 would become:

yum remove MariaDB-server MariaDB-client

Step 5 would become:

yum install MariaDB-server MariaDB-client

The other steps remain the same.

SQLite: How do I save the result of a query as a CSV file?

All the existing answers only work from the sqlite command line, which isn't ideal if you'd like to build a reusable script. Python makes it easy to build a script that can be executed programatically.

import pandas as pd
import sqlite3

conn = sqlite3.connect('your_cool_database.sqlite')

df = pd.read_sql('SELECT * from orders', conn)
df.to_csv('orders.csv', index = False)

You can customize the query to only export part of the sqlite table to the CSV file.

You can also run a single command to export all sqlite tables to CSV files:

for table in c.execute("SELECT name FROM sqlite_master WHERE type='table';").fetchall():
    t = table[0]
    df = pd.read_sql('SELECT * from ' + t, conn)
    df.to_csv(t + '_one_command.csv', index = False)

See here for more info.

What exactly is \r in C language?

' \r ' means carriage return.

The \r means nothing special as a consequence.For character-mode terminals (typically emulating even-older printing ones as above), in raw mode, \r and \n act similarly (except both in terms of the cursor, as there is no carriage or roller . Historically a \n was used to move the carriage down, while the \r was used to move the carriage back to the left side of the screen.

How do I manage MongoDB connections in a Node.js web application?

If you have Express.js, you can use express-mongo-db for caching and sharing the MongoDB connection between requests without a pool (since the accepted answer says it is the right way to share the connection).

If not - you can look at its source code and use it in another framework.

How do I display a text file content in CMD?

If you want it to display the content of the file live, and update when the file is altered, just use this script:

@echo off
:start
cls
type myfile.txt
goto start

That will repeat forever until you close the cmd window.

How to set background color in jquery

How about this:

$(this).css('background-color', '#FFFFFF');

Related post: Add background color and border to table row on hover using jquery

How to read keyboard-input?

It seems that you are mixing different Pythons here (Python 2.x vs. Python 3.x)... This is basically correct:

nb = input('Choose a number: ')

The problem is that it is only supported in Python 3. As @sharpner answered, for older versions of Python (2.x), you have to use the function raw_input:

nb = raw_input('Choose a number: ')

If you want to convert that to a number, then you should try:

number = int(nb)

... though you need to take into account that this can raise an exception:

try:
    number = int(nb)
except ValueError:
    print("Invalid number")

And if you want to print the number using formatting, in Python 3 str.format() is recommended:

print("Number: {0}\n".format(number))

Instead of:

print('Number %s \n' % (nb))

But both options (str.format() and %) do work in both Python 2.7 and Python 3.

Composer update memory limit

In Windows 10 (Git bash), i had to use this

php -d memory_limit=-1 C:\\composer\\composer.phar install

How to select rows for a specific date, ignoring time in SQL Server

I know this is an old topic, but I managed to do it in this simple way:

select count(*) from `tablename`
where date(`datecolumn`) = '2021-02-17';

Developing for Android in Eclipse: R.java not regenerating

After reading through many posts and YouTube videos, I found that each of us have R.java missing for different reasons.

Here's how I fixed this in Eclipse:

  • Create R.java in gen folder manually and save.
  • After that go to Project and click "Clean"

The following message will display and your file will automatically be rewritten:

R.java was modified manually! Reverting to generated version!

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

We found a different solution to a problem with the same symptom:

We saw this error when we updated the project from .net 4.7.1 to 4.7.2.

The problem was that even though we were not referencing System.Net.Http any more in the project, it was listed in the dependentAssembily section of our web.config. Removing this and any other unused assembly references from the web.config solved the problem.

Error: Cannot find module '../lib/utils/unsupported.js' while using Ionic

This is a helpful video and blog post about removing node from your computer OS. It is a different method of removal based on how you installed node in the first place (brew vs. binary file downloaded from https://nodejs.org/en/

  • if you installed node with Homebrew then brew uninstall node will work. Verify that with running a node -v command in your terminal.

  • Otherwise and if you have installed the binary file from nodeJS's websitethen you have to run this command in your terminal: sudo rm -rf /usr/local/{bin/{node,npm},lib/node_modules/npm,lib/node,share/man/*/node.*}. Again, verify that with running a node -v command.

  • In both cases, successful removal of node should result in bash not recognizing what node is if it is completely removed

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

Enter the original date into a Date object and then print out the result with a DateFormat. You may have to split up the string into smaller pieces to create the initial Date object, if the automatic parse method does not accept your format.

Pseudocode:

Date inputDate = convertYourInputIntoADateInWhateverWayYouPrefer(inputString);
DateFormat outputFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
String outputString = outputFormat.format(inputDate);

import error: 'No module named' *does* exist

My usual trick is to simply print sys.path in the actual context where the import problem happens. In your case it'd seem that the place for the print is in /home/hughdbrown/.local/bin/pserve . Then check dirs & files in the places that path shows..

You do that by first having:

import sys

and in python 2 with print expression:

print sys.path

or in python 3 with the print function:

print(sys.path)

sorting dictionary python 3

I like python numpy for this kind of stuff! eg:

r=readData()
nsorted = np.lexsort((r.calls, r.slow_requests, r.very_slow_requests, r.stalled_requests))

I have an example of importing CSV data into a numpy and ordering by column priorities. https://github.com/unixunion/toolbox/blob/master/python/csv-numpy.py

Kegan

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

How to use sed to remove all double quotes within a file

For replacing in place you can also do:

sed -i '' 's/\"//g' file.txt

or in Linux

sed -i 's/\"//g' file.txt

notifyDataSetChange not working from custom adapter

I have the same problem, and i realize that. When we create adapter and set it to listview, listview will point to object somewhere in memory which adapter hold, data in this object will show in listview.

adapter = new CustomAdapter(data);
listview.setadapter(adapter);

if we create an object for adapter with another data again and notifydatasetchanged():

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

this will do not affect to data in listview because the list is pointing to different object, this object does not know anything about new object in adapter, and notifyDataSetChanged() affect nothing. So we should change data in object and avoid to create a new object again for adapter

Django. Override save for model

I have found one another simple way to store the data into the database

models.py

class LinkModel(models.Model):
    link = models.CharField(max_length=500)
    shortLink = models.CharField(max_length=30,unique=True)

In database I have only 2 variables

views.py

class HomeView(TemplateView):
    def post(self,request, *args, **kwargs):
        form = LinkForm(request.POST)

        if form.is_valid():
            text = form.cleaned_data['link'] # text for link

        dbobj = LinkModel()
        dbobj.link = text
        self.no = self.gen.generateShortLink() # no for shortLink
        dbobj.shortLink = str(self.no)
        dbobj.save()         # Saving from views.py

In this I have created the instance of model in views.py only and putting/saving data into 2 variables from views only.

Git: how to reverse-merge a commit?

To create a new commit that 'undoes' the changes of a past commit, use:

$ git revert <commit-hash>

It's also possible to actually remove a commit from an arbitrary point in the past by rebasing and then resetting, but you really don't want to do that if you have already pushed your commits to another repository (or someone else has pulled from you).

If your previous commit is a merge commit you can run this command

$ git revert -m 1 <commit-hash>

See schacon.github.com/git/howto/revert-a-faulty-merge.txt for proper ways to re-merge an un-merged branch

how to check for special characters php

preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);

Access index of the parent ng-repeat from child ng-repeat

According to ng-repeat docs http://docs.angularjs.org/api/ng.directive:ngRepeat, you can store the key or array index in the variable of your choice. (indexVar, valueVar) in values

so you can write

<div ng-repeat="(fIndex, f) in foos">
  <div>
    <div ng-repeat="b in foos.bars">
      <a ng-click="addSomething(fIndex)">Add Something</a>
    </div>
  </div>
</div>

One level up is still quite clean with $parent.$index but several parents up, things can get messy.

Note: $index will continue to be defined at each scope, it is not replaced by fIndex.

How do I cancel a build that is in progress in Visual Studio?

Go to Visual Studio Build Menu -> cancel build , easy :)

Socket transport "ssl" in PHP not enabled

I was having problem in Windows 7 with PHP 5.4.0 in command line, using Xampp 1.8.1 server. This is what i did:

  1. Rename php.ini-production to php.ini (in C:\xampp\php\ folder)
  2. Edit php.ini and uncomment extension_dir=ext.
  3. Also uncomment extension=php_openssl.dll.

After that it worked fine.

Simple PowerShell LastWriteTime compare

(Get-Item $source).LastWriteTime is my preferred way to do it.

Oracle: how to set user password unexpire?

The following statement causes a user's password to expire:

ALTER USER user PASSWORD EXPIRE;

If you cause a database user's password to expire with PASSWORD EXPIRE, then the user (or the DBA) must change the password before attempting to log in to the database following the expiration. Tools such as SQL*Plus allow the user to change the password on the first attempted login following the expiration.

ALTER USER scott IDENTIFIED BY password;

Will set/reset the users password.

See the alter user doc for more info

How to delete a row from GridView?

Delete the row from the table dtPrf_Mstr rather than from the grid view.

How to avoid soft keyboard pushing up my layout?

To solve this simply add android:windowSoftInputMode="stateVisible|adjustPan to that activity in android manifest file. for example

<activity 
    android:name="com.comapny.applicationname.activityname"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="stateVisible|adjustPan"/>

How do you get a timestamp in JavaScript?

JavaScript works with the number of milliseconds since the epoch whereas most other languages work with the seconds. You could work with milliseconds but as soon as you pass a value to say PHP, the PHP native functions will probably fail. So to be sure I always use the seconds, not milliseconds.

This will give you a Unix timestamp (in seconds):

var unix = Math.round(+new Date()/1000);

This will give you the milliseconds since the epoch (not Unix timestamp):

var milliseconds = new Date().getTime();

Swift - Integer conversion to Hours/Minutes/Seconds

In Swift 5:

    var i = 9897

    func timeString(time: TimeInterval) -> String {
        let hour = Int(time) / 3600
        let minute = Int(time) / 60 % 60
        let second = Int(time) % 60

        // return formated string
        return String(format: "%02i:%02i:%02i", hour, minute, second)
    }

To call function

    timeString(time: TimeInterval(i))

Will return 02:44:57

Custom Adapter for List View

Google has an example called EfficientAdapter, which in my opinion is the best simple example of how to implement custom adapters. http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html @CommonsWare has written a good explanation of the patterns used in the above example http://commonsware.com/Android/excerpt.pdf

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

If you have multiple tooltip configurations that you want to initialise, this works well for me.

$("body").tooltip({
    selector: '[data-toggle="tooltip"]'
});

You can then set the property on individual elements using data attributes.

in iPhone App How to detect the screen resolution of the device

Use this code it will help for getting any type of device's screen resolution

 [[UIScreen mainScreen] bounds].size.height
 [[UIScreen mainScreen] bounds].size.width

How to copy an object in Objective-C

Apple documentation says

A subclass version of the copyWithZone: method should send the message to super first, to incorporate its implementation, unless the subclass descends directly from NSObject.

to add to the existing answer

@interface YourClass : NSObject <NSCopying> 
{
   SomeOtherObject *obj;
}

// In the implementation
-(id)copyWithZone:(NSZone *)zone
{
  YourClass *another = [super copyWithZone:zone];
  another.obj = [obj copyWithZone: zone];

  return another;
}

import sun.misc.BASE64Encoder results in error compiled in Eclipse

I know this is very Old post. Since we don't have any thing sun.misc in maven we can easily use

StringUtils.newStringUtf8(Base64.encodeBase64(encVal)); From org.apache.commons.codec.binary.Base64

How to switch text case in visual studio code

Echoing justanotherdev's comment:

Mind-blowing and useful:

  1. Command Palette: CTRL + SHIFT + p (Mac: CMD + SHIFT + p)
  2. type >transform pick upper/lower case and press enter

enter image description here

Html5 Full screen video

No, there is no way to do this yet. I wish they add a future like this in browsers.

EDIT:

Now there is a Full Screen API for the web You can requestFullscreen on an Video or Canvas element to ask user to give you permisions and make it full screen.

Let's consider this element:

<video controls id="myvideo">
  <source src="somevideo.webm"></source>
  <source src="somevideo.mp4"></source>
</video>

We can put that video into fullscreen mode with script like this:

var elem = document.getElementById("myvideo");
if (elem.requestFullscreen) {
  elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) {
  elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
  elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) { 
  elem.msRequestFullscreen();
}

Full documentation

Allow 2 decimal places in <input type="number">

Use this code

<input type="number" step="0.01" name="amount" placeholder="0.00">

By default Step value for HTML5 Input elements is step="1".

How can I get the Windows last reboot reason

Take a look at the Event Log API. Case a) (bluescreen, user cut the power cord or system hang) causes a note ('system did not shutdown correctly' or something like that) to be left in the 'System' event log the next time the system is rebooted properly. You should be able to access it programmatically using the above API (honestly, I've never used it but it should work).

Leading zeros for Int in Swift

Swift 3.0+

Left padding String extension similar to padding(toLength:withPad:startingAt:) in Foundation

extension String {
    func leftPadding(toLength: Int, withPad: String = " ") -> String {

        guard toLength > self.characters.count else { return self }

        let padding = String(repeating: withPad, count: toLength - self.characters.count)
        return padding + self
    }
}

Usage:

let s = String(123)
s.leftPadding(toLength: 8, withPad: "0") // "00000123"

how to assign a block of html code to a javascript variable

Greetings! I know this is an older post, but I found it through Google when searching for "javascript add large block of html as variable". I thought I'd post an alternate solution.

First, I'd recommend using single-quotes around the variable itself ... makes it easier to preserve double-quotes in the actual HTML code.

You can use a backslash to separate lines if you want to maintain a sense of formatting to the code:

var code = '<div class="my-class"> \
        <h1>The Header</h1> \
        <p>The paragraph of text</p> \
        <div class="my-quote"> \
            <p>The quote I\'d like to put in a div</p> \
        </div> \
    </div>';

Note: You'll obviously need to escape any single-quotes inside the code (e.g. inside the last 'p' tag)

Anyway, I hope that helps someone else that may be looking for the same answer I was ... Cheers!

sass :first-child not working

First of all, there are still browsers out there that don't support those pseudo-elements (ie. :first-child, :last-child), so you have to 'deal' with this issue.

There is a good example how to make that work without using pseudo-elements:

http://www.darowski.com/tracesofinspiration/2010/01/11/this-newbies-first-impressions-of-haml-and-sass/

       -- see the divider pipe example.

I hope that was useful.

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

Adding Buttons To Google Sheets and Set value to Cells on clicking

It is possible to insert an image in a Google Spreadsheet using Google Apps Script. However, the image should have been hosted publicly over internet. At present, it is not possible to insert private images from Google Drive.

You can use following code to insert an image through script.

  function insertImageOnSpreadsheet() {
  var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
  // Name of the specific sheet in the spreadsheet.
  var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';

  var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
  var sheet = ss.getSheetByName(SHEET_NAME);

  var response = UrlFetchApp.fetch(
      'https://developers.google.com/adwords/scripts/images/reports.png');
  var binaryData = response.getContent();

  // Insert the image in cell A1.
  var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
  sheet.insertImage(blob, 1, 1);
}

Above example has been copied from this link. Check noogui's reply for details.

In case you need to insert image from Google Drive, please check this link for current updates.

Check for column name in a SqlDataReader object

Here is a working sample for Jasmin's idea:

var cols = r.GetSchemaTable().Rows.Cast<DataRow>().Select
    (row => row["ColumnName"] as string).ToList(); 

if (cols.Contains("the column name"))
{

}

Recommendation for compressing JPG files with ImageMagick

Here's a complete solution for those using Imagick in PHP:

$im = new \Imagick($filePath);
$im->setImageCompression(\Imagick::COMPRESSION_JPEG);
$im->setImageCompressionQuality(85);
$im->stripImage();
$im->setInterlaceScheme(\Imagick::INTERLACE_PLANE);

// Try between 0 or 5 radius. If you find radius of 5 
// produces too blurry  pictures decrease to 0 until you 
// find a good balance between size and quality. 
$im->gaussianBlurImage(0.05, 5);



// Include this part if you also want to specify a maximum size for the images

$size = $im->getImageGeometry();
$maxWidth = 1920;
$maxHeight = 1080;


// ----------
// |        |
// ----------
if($size['width'] >= $size['height']){
  if($size['width'] > $maxWidth){
    $im->resizeImage($maxWidth, 0, \Imagick::FILTER_LANCZOS, 1);
  }
}


// ------
// |    |
// |    |
// |    |
// |    |
// ------
else{
  if($size['height'] > $maxHeight){
    $im->resizeImage(0, $maxHeight, \Imagick::FILTER_LANCZOS, 1);
  }
}

How can I search an array in VB.NET?

Dim inputString As String = "ra"
Enumerable.Range(0, arr.Length).Where(Function(x) arr(x).ToLower().Contains(inputString.ToLower()))

Force IE compatibility mode off using tags

I believe this will do the trick:

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

Change the Blank Cells to "NA"

As of (dplyr 1.0.0) we can use across()

For all columns:

dat <- dat %>%
   mutate(across(everything(), ~ifelse(.=="", NA, as.character(.))))

For individual columns:

dat <- dat %>%
   mutate(across(c("Age","Gender"), ~ifelse(.=="", NA, as.character(.))))

As of (dplyr 0.8.0 above) the way this should be written has changed. Before it was, funs() in .funs (funs(name = f(.)). Instead of funs, now we use list (list(name = ~f(.)))

Note that there is also a much simpler way to list the column names ! (both the name of the column and column index work)

dat <- dat %>%
mutate_at(.vars = c("Age","Gender"),
    .funs = list(~ifelse(.=="", NA, as.character(.))))

Original Answer:

You can also use mutate_at in dplyr

dat <- dat %>%
mutate_at(vars(colnames(.)),
        .funs = funs(ifelse(.=="", NA, as.character(.))))

Select individual columns to change:

dat <- dat %>%
mutate_at(vars(colnames(.)[names(.) %in% c("Age","Gender")]),
        .funs = funs(ifelse(.=="", NA, as.character(.))))

List tables in a PostgreSQL schema

Alternatively to information_schema it is possible to use pg_tables:

select * from pg_tables where schemaname='public';

How to fire AJAX request Periodically?

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

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

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

How to format DateTime to 24 hours time?

Use upper-case HH for 24h format:

String s = curr.ToString("HH:mm");

See DateTime.ToString Method.

MS Access - execute a saved query by name in VBA

To use CurrentDb.Execute, your query must be an action query, AND in quotes.

CurrentDb.Execute "queryname"

Should I put #! (shebang) in Python scripts, and what form should it take?

Should I put the shebang in my Python scripts?

Put a shebang into a Python script to indicate:

  • this module can be run as a script
  • whether it can be run only on python2, python3 or is it Python 2/3 compatible
  • on POSIX, it is necessary if you want to run the script directly without invoking python executable explicitly

Are these equally portable? Which form is used most?

If you write a shebang manually then always use #!/usr/bin/env python unless you have a specific reason not to use it. This form is understood even on Windows (Python launcher).

Note: installed scripts should use a specific python executable e.g., /usr/bin/python or /home/me/.virtualenvs/project/bin/python. It is bad if some tool breaks if you activate a virtualenv in your shell. Luckily, the correct shebang is created automatically in most cases by setuptools or your distribution package tools (on Windows, setuptools can generate wrapper .exe scripts automatically).

In other words, if the script is in a source checkout then you will probably see #!/usr/bin/env python. If it is installed then the shebang is a path to a specific python executable such as #!/usr/local/bin/python (NOTE: you should not write the paths from the latter category manually).

To choose whether you should use python, python2, or python3 in the shebang, see PEP 394 - The "python" Command on Unix-Like Systems:

  • ... python should be used in the shebang line only for scripts that are source compatible with both Python 2 and 3.

  • in preparation for an eventual change in the default version of Python, Python 2 only scripts should either be updated to be source compatible with Python 3 or else to use python2 in the shebang line.

Change the selected value of a drop-down list with jQuery

These solutions seem to assume that each item in your drop down lists has a val() value relating to their position in the drop down list.

Things are a little more complicated if this isn't the case.

To read the selected index of a drop down list, you would use this:

$("#dropDownList").prop("selectedIndex");

To set the selected index of a drop down list, you would use this:

$("#dropDownList").prop("selectedIndex", 1);

Note that the prop() feature requires JQuery v1.6 or later.

Let's see how you would use these two functions.

Supposing you had a drop down list of month names.

<select id="listOfMonths">
  <option id="JAN">January</option>
  <option id="FEB">February</option>
  <option id="MAR">March</option>
</select>

You could add a "Previous Month" and "Next Month" button, which looks at the currently selected drop down list item, and changes it to the previous/next month:

<button id="btnPrevMonth" title="Prev" onclick="btnPrevMonth_Click();return false;" />
<button id="btnNextMonth" title="Next" onclick="btnNextMonth_Click();return false;" />

And here's the JavaScript which these buttons would run:

function btnPrevMonth_Click() {
    var selectedIndex = $("#listOfMonths").prop("selectedIndex");
    if (selectedIndex > 0) {
        $("#listOfMonths").prop("selectedIndex", selectedIndex - 1);
    }
}
function btnNextMonth_Click() {
    //  Note:  the JQuery "prop" function requires JQuery v1.6 or later
    var selectedIndex = $("#listOfMonths").prop("selectedIndex");
    var itemsInDropDownList = $("#listOfMonths option").length;

    //  If we're not already selecting the last item in the drop down list, then increment the SelectedIndex
    if (selectedIndex < (itemsInDropDownList - 1)) {
        $("#listOfMonths").prop("selectedIndex", selectedIndex + 1);
    }
}

My site is also useful for showing how to populate a drop down list with JSON data:

http://mikesknowledgebase.com/pages/Services/WebServices-Page8.htm

Seeing the console's output in Visual Studio 2010?

In Program.cs, between:

static int Main(string[] agrs)
{

and the rest of your code, add:

#if DEBUG
    int rtn = Main2(args);
    Console.WriteLine("return " + rtn);
    Console.WriteLine("ENTER to continue.");
    Console.Read();
    return rtn;
}

static int Main2(string[] args)
{
#endif