Programs & Examples On #Beamer

Beamer is a LaTeX class for creating presentations.

Plot size and resolution with R markdown, knitr, pandoc, beamer

I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```

Then all the images will be written as PDF files, and LaTeX will be happy.

Your second problem is you are mixing up the HTML units with LaTeX units in out.width / out.height. LaTeX and HTML are very different technologies. You should not expect \maxwidth to work in HTML, or 200px in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width / out.height (use fig.width / fig.height and let LaTeX use the original size).

LaTeX beamer: way to change the bullet indentation?

Beamer just delegates responsibility for managing layout of itemize environments back to the base LaTeX packages, so there's nothing funky you need to do in Beamer itself to alter the apperaance / layout of your lists.

Since Beamer redefines itemize, item, etc., the fully proper way to manipulate things like indentation is to redefine the Beamer templates. I get the impression that you're not looking to go that far, but if that's not the case, let me know and I'll elaborate.

There are at least three ways of accomplishing your goal from within your document, without mussing about with Beamer templates.

With itemize

In the following code snippet, you can change the value of \itemindent from 0em to whatever you please, including negative values. 0em is the default item indentation.

The advantage of this method is that the list is styled normally. The disadvantage is that Beamer's redefinition of itemize and \item means that the number of paramters that can be manipulated to change the list layout is limited. It can be very hard to get the spacing right with multi-line items.

\begin{itemize}
  \setlength{\itemindent}{0em}
  \item This is a normally-indented item.
\end{itemize}

With list

In the following code snippet, the second parameter to \list is the bullet to use, and the third parameter is a list of layout parameters to change. The \leftmargin parameter adjusts the indentation of the entire list item and all of its rows; \itemindent alters the indentation of subsequent lines.

The advantage of this method is that you have all of the flexibility of lists in non-Beamer LaTeX. The disadvantage is that you have to setup the bullet style (and other visual elements) manually (or identify the right command for the template you're using). Note that if you leave the second argument empty, no bullet will be displayed and you'll save some horizontal space.

\begin{list}{$\square$}{\leftmargin=1em \itemindent=0em}
  \item This item uses the margin and indentation provided above.
\end{list}

Defining a customlist environment

The shortcomings of the list solution can be ameliorated by defining a new customlist environment that basically redefines the itemize environment from Beamer but also incorporates the \leftmargin and \itemindent (etc.) parameters. Put the following in your preamble:

\makeatletter
\newenvironment{customlist}[2]{
  \ifnum\@itemdepth >2\relax\@toodeep\else
      \advance\@itemdepth\@ne%
      \beamer@computepref\@itemdepth%
      \usebeamerfont{itemize/enumerate \beameritemnestingprefix body}%
      \usebeamercolor[fg]{itemize/enumerate \beameritemnestingprefix body}%
      \usebeamertemplate{itemize/enumerate \beameritemnestingprefix body begin}%
      \begin{list}
        {
            \usebeamertemplate{itemize \beameritemnestingprefix item}
        }
        { \leftmargin=#1 \itemindent=#2
            \def\makelabel##1{%
              {%  
                  \hss\llap{{%
                    \usebeamerfont*{itemize \beameritemnestingprefix item}%
                        \usebeamercolor[fg]{itemize \beameritemnestingprefix item}##1}}%
              }%  
            }%  
        }
  \fi
}
{
  \end{list}
  \usebeamertemplate{itemize/enumerate \beameritemnestingprefix body end}%
}
\makeatother

Now, to use an itemized list with custom indentation, you can use the following environment. The first argument is for \leftmargin and the second is for \itemindent. The default values are 2.5em and 0em respectively.

\begin{customlist}{2.5em}{0em}
   \item Any normal item can go here.
\end{customlist}

A custom bullet style can be incorporated into the customlist solution using the standard Beamer mechanism of \setbeamertemplate. (See the answers to this question on the TeX Stack Exchange for more information.)

Alternatively, the bullet style can just be modified directly within the environment, by replacing \usebeamertemplate{itemize \beameritemnestingprefix item} with whatever bullet style you'd like to use (e.g. $\square$).

Beamer: How to show images as step-by-step images

This is what I did:

\begin{frame}{series of images}
\begin{center}
\begin{overprint}

\only<2>{\includegraphics[scale=0.40]{image1.pdf}}
\hspace{-0.17em}\only<3>{\includegraphics[scale=0.40]{image2.pdf}}
\hspace{-0.34em}\only<4>{\includegraphics[scale=0.40]{image3.pdf}}
\hspace{-0.17em}\only<5>{\includegraphics[scale=0.40]{image4.pdf}}

\only<2-5>{\mbox{\structure{Figure:} something}}

\end{overprint}
\end{center}
\end{frame}

How to create dynamic href in react render function?

Use string concatenation:

href={'/posts/' + post.id}

The JSX syntax allows either to use strings or expressions ({...}) as values. You cannot mix both. Inside an expression you can, as the name suggests, use any JavaScript expression to compute the value.

Using async/await for multiple tasks

int[] ids = new[] { 1, 2, 3, 4, 5 };
Parallel.ForEach(ids, i => DoSomething(1, i, blogClient).Wait());

Although you run the operations in parallel with the above code, this code blocks each thread that each operation runs on. For example, if the network call takes 2 seconds, each thread hangs for 2 seconds w/o doing anything but waiting.

int[] ids = new[] { 1, 2, 3, 4, 5 };
Task.WaitAll(ids.Select(i => DoSomething(1, i, blogClient)).ToArray());

On the other hand, the above code with WaitAll also blocks the threads and your threads won't be free to process any other work till the operation ends.

Recommended Approach

I would prefer WhenAll which will perform your operations asynchronously in Parallel.

public async Task DoWork() {

    int[] ids = new[] { 1, 2, 3, 4, 5 };
    await Task.WhenAll(ids.Select(i => DoSomething(1, i, blogClient)));
}

In fact, in the above case, you don't even need to await, you can just directly return from the method as you don't have any continuations:

public Task DoWork() 
{
    int[] ids = new[] { 1, 2, 3, 4, 5 };
    return Task.WhenAll(ids.Select(i => DoSomething(1, i, blogClient)));
}

To back this up, here is a detailed blog post going through all the alternatives and their advantages/disadvantages: How and Where Concurrent Asynchronous I/O with ASP.NET Web API

How does "FOR" work in cmd batch file?

FOR is essentially iterating over the "lines" in the data set. In this case, there is one line that contains the path. The "delims=;" is just telling it to separate on semi-colons. If you change the body to echo %%g,%%h,%%i,%%j,%%k you'll see that it is treating the input as a single line and breaking it into multiple tokens.

How to delete a selected DataGridViewRow and update a connected database table?

if(this.dgvpurchase.Rows.Count>1)
{
    if(this.dgvpurchase.CurrentRow.Index<this.dgvpurchase.Rows.Count)
    {
        this.txtname.Text = this.dgvpurchase.CurrentRow.Cells[1].Value.ToString();
        this.txttype.Text = this.dgvpurchase.CurrentRow.Cells[2].Value.ToString();
        this.cbxcode.Text = this.dgvpurchase.CurrentRow.Cells[3].Value.ToString();
        this.cbxcompany.Text = this.dgvpurchase.CurrentRow.Cells[4].Value.ToString();
        this.dtppurchase.Value = Convert.ToDateTime(this.dgvpurchase.CurrentRow.Cells[5].Value);
        this.txtprice.Text = this.dgvpurchase.CurrentRow.Cells[6].Value.ToString();
        this.txtqty.Text = this.dgvpurchase.CurrentRow.Cells[7].Value.ToString();
        this.txttotal.Text = this.dgvpurchase.CurrentRow.Cells[8].Value.ToString();
        this.dgvpurchase.Rows.RemoveAt(this.dgvpurchase.CurrentRow.Index);
        refreshid();
    }
}

How can I extract a predetermined range of lines from a text file on Unix?

I was about to post the head/tail trick, but actually I'd probably just fire up emacs. ;-)

  1. esc-x goto-line ret 16224
  2. mark (ctrl-space)
  3. esc-x goto-line ret 16482
  4. esc-w

open the new output file, ctl-y save

Let's me see what's happening.

How to use store and use session variables across pages?

Starting a Session:

Put below code at the top of file.

<?php session_start();?>

Storing a session variable:

<?php $_SESSION['id']=10; ?>

To Check if data stored in session variable:

<?php if(isset($_SESSION['id']) && !empty(isset($_SESSION['id'])))
echo “Session id “.$_SESSION['id'].” exist”;
else
echo “Session not set “;?>

?> detail here http://skillrow.com/sessions-in-php-4/

React.js, wait for setState to finish before triggering a function?

According to the docs of setState() the new state might not get reflected in the callback function findRoutes(). Here is the extract from React docs:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

So here is what I propose you should do. You should pass the new states input in the callback function findRoutes().

handleFormSubmit: function(input){
    // Form Input
    this.setState({
        originId: input.originId,
        destinationId: input.destinationId,
        radius: input.radius,
        search: input.search
    });
    this.findRoutes(input);    // Pass the input here
}

The findRoutes() function should be defined like this:

findRoutes: function(me = this.state) {    // This will accept the input if passed otherwise use this.state
    if (!me.originId || !me.destinationId) {
        alert("findRoutes!");
        return;
    }
    var p1 = new Promise(function(resolve, reject) {
        directionsService.route({
            origin: {'placeId': me.originId},
            destination: {'placeId': me.destinationId},
            travelMode: me.travelMode
        }, function(response, status){
            if (status === google.maps.DirectionsStatus.OK) {
                // me.response = response;
                directionsDisplay.setDirections(response);
                resolve(response);
            } else {
                window.alert('Directions config failed due to ' + status);
            }
        });
    });
    return p1
}

Correct way to push into state array

You should not be operating the state at all. At least, not directly. If you want to update your array, you'll want to do something like this.

var newStateArray = this.state.myArray.slice();
newStateArray.push('new value');
this.setState(myArray: newStateArray);

Working on the state object directly is not desirable. You can also take a look at React's immutability helpers.

https://facebook.github.io/react/docs/update.html

Function not defined javascript

The actual problem is with your

showList function.

There is an extra ')' after 'visible'.

Remove that and it will work fine.

function showList()
{
  if (document.getElementById("favSports").style.visibility == "hidden") 
    {
       // document.getElementById("favSports").style.visibility = "visible");  
       // your code
       document.getElementById("favSports").style.visibility = "visible";
       // corrected code
    }
}

pypi UserWarning: Unknown distribution option: 'install_requires'

As far as I can tell, this is a bug in setuptools where it isn't removing the setuptools specific options before calling up to the base class in the standard library: https://bitbucket.org/pypa/setuptools/issue/29/avoid-userwarnings-emitted-when-calling

If you have an unconditional import setuptools in your setup.py (as you should if using the setuptools specific options), then the fact the script isn't failing with ImportError indicates that setuptools is properly installed.

You can silence the warning as follows:

python -W ignore::UserWarning:distutils.dist setup.py <any-other-args>

Only do this if you use the unconditional import that will fail completely if setuptools isn't installed :)

(I'm seeing this same behaviour in a checkout from the post-merger setuptools repo, which is why I'm confident it's a setuptools bug rather than a system config problem. I expect pre-merge distribute would have the same problem)

How to retrieve the current value of an oracle sequence without increment it?

I also tried to use CURRVAL, in my case to find out if some process inserted new rows to some table with that sequence as Primary Key. My assumption was that CURRVAL would be the fastest method. But a) CurrVal does not work, it will just get the old value because you are in another Oracle session, until you do a NEXTVAL in your own session. And b) a select max(PK) from TheTable is also very fast, probably because a PK is always indexed. Or select count(*) from TheTable. I am still experimenting, but both SELECTs seem fast.

I don't mind a gap in a sequence, but in my case I was thinking of polling a lot, and I would hate the idea of very large gaps. Especially if a simple SELECT would be just as fast.

Conclusion:

  • CURRVAL is pretty useless, as it does not detect NEXTVAL from another session, it only returns what you already knew from your previous NEXTVAL
  • SELECT MAX(...) FROM ... is a good solution, simple and fast, assuming your sequence is linked to that table

Ship an application with a database

Currently there is no way to precreate an SQLite database to ship with your apk. The best you can do is save the appropriate SQL as a resource and run them from your application. Yes, this leads to duplication of data (same information exists as a resrouce and as a database) but there is no other way right now. The only mitigating factor is the apk file is compressed. My experience is 908KB compresses to less than 268KB.

The thread below has the best discussion/solution I have found with good sample code.

http://groups.google.com/group/android-developers/msg/9f455ae93a1cf152

I stored my CREATE statement as a string resource to be read with Context.getString() and ran it with SQLiteDatabse.execSQL().

I stored the data for my inserts in res/raw/inserts.sql (I created the sql file, 7000+ lines). Using the technique from the link above I entered a loop, read the file line by line and concactenated the data onto "INSERT INTO tbl VALUE " and did another SQLiteDatabase.execSQL(). No sense in saving 7000 "INSERT INTO tbl VALUE "s when they can just be concactenated on.

It takes about twenty seconds on the emulator, I do not know how long this would take on a real phone, but it only happens once, when the user first starts the application.

Eclipse shows errors but I can't find them

This happens from time to time in Eclipse. In the "Project" menu there's a "Clean" option, that usually takes care of the problem.

Scroll Automatically to the Bottom of the Page

You may try Gentle Anchors a nice javascript plugin.

Example:

function SomeFunction() {
  // your code
  // Pass an id attribute to scroll to. The # is required
  Gentle_Anchors.Setup('#destination');
  // maybe some more code
}

Compatibility Tested on:

  • Mac Firefox, Safari, Opera
  • Windows Firefox, Opera, Safari, Internet Explorer 5.55+
  • Linux untested but should be fine with Firefox at least

Converting HTML to XML

Remember that HTML and XML are two distinct concepts in the tree of markup languages. You can't exactly replace HTML with XML . XML can be viewed as a generalized form of HTML, but even that is imprecise. You mainly use HTML to display data, and XML to carry(or store) the data.

This link is helpful: How to read HTML as XML?

More here - difference between HTML and XML

How to Change Font Size in drawString Java

code example below:

g.setFont(new Font("TimesRoman", Font.PLAIN, 30));
g.drawString("Welcome to the Java Applet", 20 , 20);

How to generate Javadoc HTML files in Eclipse?

This is a supplement answer related to the OP:

An easy and reliable solution to add Javadocs comments in Eclipse:

  1. Go to Help > Eclipse Marketplace....
  2. Find "JAutodoc".
  3. Install it and restart Eclipse.

To use this tool, right-click on class and click on JAutodoc.

error: Error parsing XML: not well-formed (invalid token) ...?

Verify that you don't have any spaces or tabs before

<?xml version="1.0" encoding="utf-8"?>

also refresh and clean your project in eclipse.

I get this error every now and then and the above suggestions fix the issue 99% of the time

LINQ with groupby and count

Assuming userInfoList is a List<UserInfo>:

        var groups = userInfoList
            .GroupBy(n => n.metric)
            .Select(n => new
            {
                MetricName = n.Key,
                MetricCount = n.Count()
            }
            )
            .OrderBy(n => n.MetricName);

The lambda function for GroupBy(), n => n.metric means that it will get field metric from every UserInfo object encountered. The type of n is depending on the context, in the first occurrence it's of type UserInfo, because the list contains UserInfo objects. In the second occurrence n is of type Grouping, because now it's a list of Grouping objects.

Groupings have extension methods like .Count(), .Key() and pretty much anything else you would expect. Just as you would check .Lenght on a string, you can check .Count() on a group.

In Javascript, how do I check if an array has duplicate values?

If you have an ES2015 environment (as of this writing: io.js, IE11, Chrome, Firefox, WebKit nightly), then the following will work, and will be fast (viz. O(n)):

function hasDuplicates(array) {
    return (new Set(array)).size !== array.length;
}

If you only need string values in the array, the following will work:

function hasDuplicates(array) {
    var valuesSoFar = Object.create(null);
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (value in valuesSoFar) {
            return true;
        }
        valuesSoFar[value] = true;
    }
    return false;
}

We use a "hash table" valuesSoFar whose keys are the values we've seen in the array so far. We do a lookup using in to see if that value has been spotted already; if so, we bail out of the loop and return true.


If you need a function that works for more than just string values, the following will work, but isn't as performant; it's O(n2) instead of O(n).

function hasDuplicates(array) {
    var valuesSoFar = [];
    for (var i = 0; i < array.length; ++i) {
        var value = array[i];
        if (valuesSoFar.indexOf(value) !== -1) {
            return true;
        }
        valuesSoFar.push(value);
    }
    return false;
}

The difference is simply that we use an array instead of a hash table for valuesSoFar, since JavaScript "hash tables" (i.e. objects) only have string keys. This means we lose the O(1) lookup time of in, instead getting an O(n) lookup time of indexOf.

Should I test private methods or only public ones?

Unit tests I believe are for testing public methods. Your public methods use your private methods, so indirectly they are also getting tested.

How does Tomcat locate the webapps directory?

It can be changed in the $CATALINA_BASE/conf/server.xml in the <Host />. See the Tomcat documentation, specifically the section in regards to the Host container:

Tomcat 6 Configuration

Tomcat 7 Configuration

The default is webapps relative to the $CATALINA_BASE. An absolute pathname can be used.

Hope that helps.

How to insert logo with the title of a HTML page?

Put this in the <head> section:

<link rel="icon" href="http://www.domain.com/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.domain.com/favicon.ico" type="image/x-icon" />

Keep the picture file named "favicon.ico". You'll have to look online to get a .ico file generator.

Adding two Java 8 streams, or an extra element to a stream

If you don't mind using 3rd Party Libraries cyclops-react has an extended Stream type that will allow you to do just that via the append / prepend operators.

Individual values, arrays, iterables, Streams or reactive-streams Publishers can be appended and prepended as instance methods.

Stream stream = ReactiveSeq.of(1,2)
                           .filter(x -> x!=0)
                           .append(ReactiveSeq.of(3,4))
                           .filter(x -> x!=1)
                           .append(5)
                           .filter(x -> x!=2);

[Disclosure I am the lead developer of cyclops-react]

How to automatically import data from uploaded CSV or XLS file into Google Sheets

In case anyone would be searching - I created utility for automated import of xlsx files into google spreadsheet: xls2sheets. One can do it automatically via setting up the cronjob for ./cmd/sheets-refresh, readme describes it all. Hope that would be of use.

One or more types required to compile a dynamic expression cannot be found. Are you missing references to Microsoft.CSharp.dll and System.Core.dll?

None of these worked for me.

My class libraries were definitely all referencing both System.Core and Microsoft.CSharp. Web Application was 4.0 and couldn't upgrade to 4.5 due to support issues.

I was encountering the error compiling a razor template using the Razor Engine, and only encountering it intermittently, like after web application has been restarted.

The solution that worked for me was manually loading the assembly then reattempting the same operation...

        bool retry = true;
        while (retry)
        {
            try
            {
                string textTemplate = File.ReadAllText(templatePath);
                Razor.CompileWithAnonymous(textTemplate, templateFileName);
                retry = false;
            }
            catch (TemplateCompilationException ex)
            {
                LogTemplateException(templatePath, ex);
                retry = false;

                if (ex.Errors.Any(e  => e.ErrorNumber == "CS1969"))
                {
                    try
                    {
                        _logger.InfoFormat("Attempting to manually load the Microsoft.CSharp.RuntimeBinder.Binder");
                        Assembly csharp = Assembly.Load("Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
                        Type type = csharp.GetType("Microsoft.CSharp.RuntimeBinder.Binder");
                        retry = true;
                    }
                    catch(Exception exLoad)
                    {
                        _logger.Error("Failed to manually load runtime binder", exLoad);
                    }
                }

                if (!retry)
                    throw;
            }
        }

Hopefully this might help someone else out there.

database attached is read only

Giving the sql service account 'NT SERVICE\MSSQLSERVER' "Full Control" of the database files

If you have access to the server files/folders you can try this solution that worked for me:

SQL Server 2012 on Windows Server 2008 R2

  1. Right click the database (mdf/ldf) file or folder and select "Properties".
  2. Select "Security" tab and click the "Edit" button.
  3. Click the "Add" button.
  4. Enter the object name to select as 'NT SERVICE\MSSQLSERVER' and click "Check Names" button.
  5. Select the MSSQLSERVER (RDN) and click the "OK" button twice.
  6. Give this service account "Full control" to the file or folder.
  7. Back in SSMS, right click the database and select "Properties".
  8. Under "Options", scroll down to the "State" section and change "Database Read-Only" from "True" to "False".

time delayed redirect?

You can easily create timed redirections with JavaScript. But I suggest you to use location.replace('url') instead of location.href. It prevents to browser to push the site into the history. I found this JavaScript redirect tool. I think you could use this.

Example code (with 5 secs delay):

<!-- Pleace this snippet right after opening the head tag to make it work properly -->

<!-- This code is licensed under GNU GPL v3 -->
<!-- You are allowed to freely copy, distribute and use this code, but removing author credit is strictly prohibited -->
<!-- Generated by http://insider.zone/tools/client-side-url-redirect-generator/ -->

<!-- REDIRECTING STARTS -->
<link rel="canonical" href="https://yourdomain.com/"/>
<noscript>
    <meta http-equiv="refresh" content="5;URL=https://yourdomain.com/">
</noscript>
<!--[if lt IE 9]><script type="text/javascript">var IE_fix=true;</script><![endif]-->
<script type="text/javascript">
    var url = "https://yourdomain.com/";
    var delay = "5000";
    window.onload = function ()
    {
        setTimeout(GoToURL, delay);
    }
    function GoToURL()
    {
        if(typeof IE_fix != "undefined") // IE8 and lower fix to pass the http referer
        {
            var referLink = document.createElement("a");
            referLink.href = url;
            document.body.appendChild(referLink);
            referLink.click();
        }
        else { window.location.replace(url); } // All other browsers
    }
</script>
<!-- Credit goes to http://insider.zone/ -->
<!-- REDIRECTING ENDS -->

Twig: in_array or similar possible within if statement?

It should help you.

{% for user in users if user.active and user.id not 1 %}
   {{ user.name }}
{% endfor %}

More info: http://twig.sensiolabs.org/doc/tags/for.html

Get content of a DIV using JavaScript

You need to set Div2 to Div1's innerHTML. Also, JavaScript is case sensitive - in your HTML, the id Div2 is DIV2. Also, you should use document, not Document:

var MyDiv1 = document.getElementById('DIV1');
var MyDiv2 = document.getElementById('DIV2');
MyDiv2.innerHTML = MyDiv1.innerHTML; 

Here is a JSFiddle: http://jsfiddle.net/gFN6r/.

How can I truncate a double to only two decimal places in Java?

Formating as a string and converting back to double i think will give you the result you want.

The double value will not be round(), floor() or ceil().

A quick fix for it could be:

 String sValue = (String) String.format("%.2f", oldValue);
 Double newValue = Double.parseDouble(sValue);

You can use the sValue for display purposes or the newValue for calculation.

Is there a way to create interfaces in ES6 / Node 4?

Interfaces are not part of the ES6 but classes are.

If you really need them, you should look at TypeScript which support them.

How to add and get Header values in WebApi

try these line of codes working in my case:

IEnumerable<string> values = new List<string>();
this.Request.Headers.TryGetValues("Authorization", out values);

What is the default access specifier in Java?

Here is a quote about package level visibility from an interview with James Gosling, the creator of Java:

Bill Venners: Java has four access levels. The default is package. I have always wondered if making package access default was convenient because the three keywords that people from C++ already knew about were private, protected, and public. Or if you had some particular reason that you felt package access should be the default.

James Gosling: A package is generally a set of things that are kind of written together. So generically I could have done one of two things. One was force you always to put in a keyword that gives you the domain. Or I could have had a default value. And then the question is, what makes a sensible default? And I tend to go for what is the least dangerous thing.

So public would have been a really bad thing to make the default. Private would probably have been a bad thing to make a default, if only because people actually don't write private methods that often. And same thing with protected. And in looking at a bunch of code that I had, I decided that the most common thing that was reasonably safe was in the package. And C++ didn't have a keyword for that, because they didn't have a notion of packages.

But I liked it rather than the friends notion, because with friends you kind of have to enumerate who all of your friends are, and so if you add a new class to a package, then you generally end up having to go to all of the classes in that package and update their friends, which I had always found to be a complete pain in the butt.

But the friends list itself causes sort of a versioning problem. And so there was this notion of a friendly class. And the nice thing that I was making that the default -- I'll solve the problem so what should the keyword be?

For a while there actually was a friendly keyword. But because all the others start with "P," it was "phriendly" with a "PH." But that was only in there for maybe a day.

http://www.artima.com/intv/gosling2P.html

How to check if a std::thread is still running?

If you are willing to make use of C++11 std::async and std::future for running your tasks, then you can utilize the wait_for function of std::future to check if the thread is still running in a neat way like this:

#include <future>
#include <thread>
#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono_literals;

    /* Run some task on new thread. The launch policy std::launch::async
       makes sure that the task is run asynchronously on a new thread. */
    auto future = std::async(std::launch::async, [] {
        std::this_thread::sleep_for(3s);
        return 8;
    });

    // Use wait_for() with zero milliseconds to check thread status.
    auto status = future.wait_for(0ms);

    // Print status.
    if (status == std::future_status::ready) {
        std::cout << "Thread finished" << std::endl;
    } else {
        std::cout << "Thread still running" << std::endl;
    }

    auto result = future.get(); // Get result.
}

If you must use std::thread then you can use std::promise to get a future object:

#include <future>
#include <thread>
#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono_literals;

    // Create a promise and get its future.
    std::promise<bool> p;
    auto future = p.get_future();

    // Run some task on a new thread.
    std::thread t([&p] {
        std::this_thread::sleep_for(3s);
        p.set_value(true); // Is done atomically.
    });

    // Get thread status using wait_for as before.
    auto status = future.wait_for(0ms);

    // Print status.
    if (status == std::future_status::ready) {
        std::cout << "Thread finished" << std::endl;
    } else {
        std::cout << "Thread still running" << std::endl;
    }

    t.join(); // Join thread.
}

Both of these examples will output:

Thread still running

This is of course because the thread status is checked before the task is finished.

But then again, it might be simpler to just do it like others have already mentioned:

#include <thread>
#include <atomic>
#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono_literals;

    std::atomic<bool> done(false); // Use an atomic flag.

    /* Run some task on a new thread.
       Make sure to set the done flag to true when finished. */
    std::thread t([&done] {
        std::this_thread::sleep_for(3s);
        done = true;
    });

    // Print status.
    if (done) {
        std::cout << "Thread finished" << std::endl;
    } else {
        std::cout << "Thread still running" << std::endl;
    }

    t.join(); // Join thread.
}

Edit:

There's also the std::packaged_task for use with std::thread for a cleaner solution than using std::promise:

#include <future>
#include <thread>
#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono_literals;

    // Create a packaged_task using some task and get its future.
    std::packaged_task<void()> task([] {
        std::this_thread::sleep_for(3s);
    });
    auto future = task.get_future();

    // Run task on new thread.
    std::thread t(std::move(task));

    // Get thread status using wait_for as before.
    auto status = future.wait_for(0ms);

    // Print status.
    if (status == std::future_status::ready) {
        // ...
    }

    t.join(); // Join thread.
}

How to flatten only some dimensions of a numpy array

A slight generalization to Peter's answer -- you can specify a range over the original array's shape if you want to go beyond three dimensional arrays.

e.g. to flatten all but the last two dimensions:

arr = numpy.zeros((3, 4, 5, 6))
new_arr = arr.reshape(-1, *arr.shape[-2:])
new_arr.shape
# (12, 5, 6)

EDIT: A slight generalization to my earlier answer -- you can, of course, also specify a range at the beginning of the of the reshape too:

arr = numpy.zeros((3, 4, 5, 6, 7, 8))
new_arr = arr.reshape(*arr.shape[:2], -1, *arr.shape[-2:])
new_arr.shape
# (3, 4, 30, 7, 8)

How to sort a Pandas DataFrame by index?

Slightly more compact:

df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)

Note:

Eclipse HotKey: how to switch between tabs?

How can I switch between opened windows in Eclipse

CTRL+F7 works here - Eclipse Photon on Windows.

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

Init method in Spring Controller (annotation version)

There are several ways to intercept the initialization process in Spring. If you have to initialize all beans and autowire/inject them there are at least two ways that I know of that will ensure this. I have only testet the second one but I belive both work the same.

If you are using @Bean you can reference by initMethod, like this.

@Configuration
public class BeanConfiguration {

  @Bean(initMethod="init")
  public BeanA beanA() {
    return new BeanA();
  }
}

public class BeanA {

  // method to be initialized after context is ready
  public void init() {
  }

} 

If you are using @Component you can annotate with @EventListener like this.

@Component
public class BeanB {

  @EventListener
  public void onApplicationEvent(ContextRefreshedEvent event) {
  }
}

In my case I have a legacy system where I am now taking use of IoC/DI where Spring Boot is the choosen framework. The old system brings many circular dependencies to the table and I therefore must use setter-dependency a lot. That gave me some headaches since I could not trust @PostConstruct since autowiring/injection by setter was not yet done. The order is constructor, @PostConstruct then autowired setters. I solved it with @EventListener annotation which wil run last and at the "same" time for all beans. The example shows implementation of InitializingBean aswell.

I have two classes (@Component) with dependency to each other. The classes looks the same for the purpose of this example displaying only one of them.

@Component
public class BeanA implements InitializingBean {
  private BeanB beanB;

  public BeanA() {
    log.debug("Created...");
  }

  @PostConstruct
  private void postConstruct() {
    log.debug("@PostConstruct");
  }

  @Autowired
  public void setBeanB(BeanB beanB) {
    log.debug("@Autowired beanB");
    this.beanB = beanB;
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    log.debug("afterPropertiesSet()");
  }

  @EventListener
  public void onApplicationEvent(ContextRefreshedEvent event) {
    log.debug("@EventListener");
  } 
}

This is the log output showing the order of the calls when the container starts.

2018-11-30 18:29:30.504 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : Created...
2018-11-30 18:29:30.509 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : Created...
2018-11-30 18:29:30.517 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @Autowired beanA
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @PostConstruct
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : afterPropertiesSet()
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @Autowired beanB
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @PostConstruct
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : afterPropertiesSet()
2018-11-30 18:29:30.607 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @EventListener
2018-11-30 18:29:30.607 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @EventListener

As you can see @EventListener is run last after everything is ready and configured.

Difference between "char" and "String" in Java

A char simply contains a single alphabet and a string has a full word or number of words woth having a escape sequence inserted in the end automatically to tell the compiler that string has been ended here.(0)

Why is volatile needed in C?

Volatile is also useful, when you want to force the compiler not to optimize a specific code sequence (e.g. for writing a micro-benchmark).

SQL Add foreign key to existing column

In the future.

ALTER TABLE Employees
ADD UserID int;

ALTER TABLE Employees
ADD CONSTRAINT FK_ActiveDirectories_UserID FOREIGN KEY (UserID)
    REFERENCES ActiveDirectories(id);

JavaScript variable number of arguments to function

Another option is to pass in your arguments in a context object.

function load(context)
{
    // do whatever with context.name, context.address, etc
}

and use it like this

load({name:'Ken',address:'secret',unused:true})

This has the advantage that you can add as many named arguments as you want, and the function can use them (or not) as it sees fit.

Normalization in DOM parsing with java - how does it work?

In simple, Normalisation is Reduction of Redundancies.
Examples of Redundancies:
a) white spaces outside of the root/document tags(...<document></document>...)
b) white spaces within start tag (<...>) and end tag (</...>)
c) white spaces between attributes and their values (ie. spaces between key name and =")
d) superfluous namespace declarations
e) line breaks/white spaces in texts of attributes and tags
f) comments etc...

Can two applications listen to the same port?

No. Only one application can bind to a port at a time, and behavior if the bind is forced is indeterminate.

With multicast sockets -- which sound like nowhere near what you want -- more than one application can bind to a port as long as SO_REUSEADDR is set in each socket's options.

You could accomplish this by writing a "master" process, which accepts and processes all connections, then hands them off to your two applications who need to listen on the same port. This is the approach that Web servers and such take, since many processes need to listen to 80.

Beyond this, we're getting into specifics -- you tagged both TCP and UDP, which is it? Also, what platform?

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

How to set default value for HTML select?

Simplay you can place HTML select attribute to option a like shown below

Define the attributes like selected="selected"

<select>
   <option selected="selected">a</option>
   <option>b</option>
   <option>c</option>
</select>

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

FFMPEG mp4 from http live streaming m3u8 file?

Aergistal's answer works, but I found that converting to mp4 can make some m3u8 videos broken. If you are stuck with this problem, try to convert them to mkv, and convert them to mp4 later.

What's the difference between a Future and a Promise?

Not sure if this can be an answer but as I see what others have said for someone it may look like you need two separate abstractions for both of these concepts so that one of them (Future) is just a read-only view of the other (Promise) ... but actually this is not needed.

For example take a look at how promises are defined in javascript:

https://promisesaplus.com/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

The focus is on the composability using the then method like:

asyncOp1()
.then(function(op1Result){
  // do something
  return asyncOp2();
})
.then(function(op2Result){
  // do something more
  return asyncOp3();
})
.then(function(op3Result){
  // do something even more
  return syncOp4(op3Result);
})
...
.then(function(result){
  console.log(result);
})
.catch(function(error){
  console.log(error);
})

which makes asynchronous computation to look like synchronous:

try {
  op1Result = syncOp1();
  // do something
  op1Result = syncOp2();
  // do something more
  op3Result = syncOp3();
  // do something even more
  syncOp4(op3Result);
  ...
  console.log(result);
} catch(error) {
  console.log(error);
}

which is pretty cool. (Not as cool as async-await but async-await just removes the boilerplate ....then(function(result) {.... from it).

And actually their abstraction is pretty good as the promise constructor

new Promise( function(resolve, reject) { /* do it */ } );

allows you to provide two callbacks which can be used to either complete the Promise successfully or with an error. So that only the code that constructs the Promise can complete it and the code that receives an already constructed Promise object has the read-only view.

With inheritance the above can be achieved if resolve and reject are protected methods.

What is the purpose of the HTML "no-js" class?

This is not only applicable in Modernizer. I see some site implement like below to check whether it has javascript support or not.

<body class="no-js">
    <script>document.body.classList.remove('no-js');</script>
    ...
</body>

If javascript support is there, then it will remove no-js class. Otherwise no-js will remain in the body tag. Then they control the styles in the css when no javascript support.

.no-js .some-class-name {

}

New og:image size for Facebook share?

UPDATE: The image size Must be larger than (600 x 315px)

The image size can be any size because Faceboook re-size the image width & height.

The default height is 208px & width is 398px for a post permalink:

www.facebook.com/{username}/posts/{post_id}

But for a timeline view:

www.facebook.com/{username}

width is 377px & height is 197px

I hope this will help you!

What is the purpose of the return statement?

Think of the print statement as causing a side-effect, it makes your function write some text out to the user, but it can't be used by another function.

I'll attempt to explain this better with some examples, and a couple definitions from Wikipedia.

Here is the definition of a function from Wikipedia

A function, in mathematics, associates one quantity, the argument of the function, also known as the input, with another quantity, the value of the function, also known as the output..

Think about that for a second. What does it mean when you say the function has a value?

What it means is that you can actually substitute the value of a function with a normal value! (Assuming the two values are the same type of value)

Why would you want that you ask?

What about other functions that may accept the same type of value as an input?

def square(n):
    return n * n

def add_one(n):
    return n + 1

print square(12)

# square(12) is the same as writing 144

print add_one(square(12))
print add_one(144)
#These both have the same output

There is a fancy mathematical term for functions that only depend on their inputs to produce their outputs: Referential Transparency. Again, a definition from Wikipedia.

Referential transparency and referential opaqueness are properties of parts of computer programs. An expression is said to be referentially transparent if it can be replaced with its value without changing the behavior of a program

It might be a bit hard to grasp what this means if you're just new to programming, but I think you will get it after some experimentation. In general though, you can do things like print in a function, and you can also have a return statement at the end.

Just remember that when you use return you are basically saying "A call to this function is the same as writing the value that gets returned"

Python will actually insert a return value for you if you decline to put in your own, it's called "None", and it's a special type that simply means nothing, or null.

Responsive image map

Check out the image-map plugin on Github. It works both with vanilla JavaScript and as a jQuery plugin.

$('img[usemap]').imageMap();     // jQuery

ImageMap('img[usemap]')          // JavaScript

Check out the demo.

How to set the max size of upload file

More specifically, in your application.yml configuration file, add the following to the "spring:" section.

http:
    multipart:
        max-file-size: 512MB
        max-request-size: 512MB

Whitespace is important and you cannot use tabs for indentation.

Keyboard shortcut to change font size in Eclipse?

The Eclipse-Fonts extension will add toolbar buttons and keyboard shortcuts for changing font size. You can then use AutoHotkey to make Ctrl+Mousewheel zoom.

Under Help | Install New Software... in the menu, paste the update URL (http://eclipse-fonts.googlecode.com/svn/trunk/FontsUpdate/) into the Works with: text box and press Enter. Expand the tree and select FontsFeature as in the following image:

Eclipse extension installation screen capture

Complete the installation and restart Eclipse, then you should see the A toolbar buttons (circled in red in the following image) and be able to use the keyboard shortcuts Ctrl+- and Ctrl+= to zoom (although you may have to unbind those keys from Eclipse first).

Eclipse screen capture with the font size toolbar buttons circled

To get Ctrl+MouseWheel zooming, you can use AutoHotkey with the following script:

; Ctrl+MouseWheel zooming in Eclipse.
; Requires Eclipse-Fonts (https://code.google.com/p/eclipse-fonts/).
; Thank you for the unique window class, SWT/Eclipse.
#IfWinActive ahk_class SWT_Window0
    ^WheelUp:: Send ^{=}
    ^WheelDown:: Send ^-
#IfWinActive

Add floating point value to android resources/values

I found a solution, which works, but does result in a Warning (WARN/Resources(268): Converting to float: TypedValue{t=0x3/d=0x4d "1.2" a=2 r=0x7f06000a}) in LogCat.

<resources>
    <string name="text_line_spacing">1.2</string>
</resources>

<android:lineSpacingMultiplier="@string/text_line_spacing"/>

install apt-get on linux Red Hat server

wget http://dag.wieers.com/packages/apt/apt-0.5.15lorg3.1-4.el4.rf.i386.rpm

rpm -ivh apt-0.5.15lorg3.1-4.el4.rf.i386.rpm

wget http://dag.wieers.com/packages/rpmforge-release/rpmforge-release-0.3.4-1.el4.rf.i386.rpm

rpm -Uvh rpmforge-release-0.3.4-1.el4.rf.i386.rpm

maybe some URL is broken,please research it. Enjoy~~

Execute SQL script to create tables and rows

In the MySQL interactive client you can type:

source yourfile.sql

Alternatively you can pipe the data into mysql from the command line:

mysql < yourfile.sql

If the file doesn't specify a database then you will also need to add that:

mysql db_name < yourfile.sql

See the documentation for more details:

For each row return the column name of the largest value

One option from dplyr 1.0.0 could be:

DF %>%
 rowwise() %>%
 mutate(row_max = names(.)[which.max(c_across(everything()))])

     V1    V2    V3 row_max
  <dbl> <dbl> <dbl> <chr>  
1     2     7     9 V3     
2     8     3     6 V1     
3     1     5     4 V2     

Sample data:

DF <- structure(list(V1 = c(2, 8, 1), V2 = c(7, 3, 5), V3 = c(9, 6, 
4)), class = "data.frame", row.names = c(NA, -3L))

Read values into a shell variable from a pipe

I think you were trying to write a shell script which could take input from stdin. but while you are trying it to do it inline, you got lost trying to create that test= variable. I think it does not make much sense to do it inline, and that's why it does not work the way you expect.

I was trying to reduce

$( ... | head -n $X | tail -n 1 )

to get a specific line from various input. so I could type...

cat program_file.c | line 34

so I need a small shell program able to read from stdin. like you do.

22:14 ~ $ cat ~/bin/line 
#!/bin/sh

if [ $# -ne 1 ]; then echo enter a line number to display; exit; fi
cat | head -n $1 | tail -n 1
22:16 ~ $ 

there you go.

Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

My simple solution

BitReverse(IN)
    OUT = 0x00;
    R = 1;      // Right mask   ...0000.0001
    L = 0;      // Left mask    1000.0000...
    L = ~0; 
    L = ~(i >> 1);
    int size = sizeof(IN) * 4;  // bit size

    while(size--){
        if(IN & L) OUT = OUT | R; // start from MSB  1000.xxxx
        if(IN & R) OUT = OUT | L; // start from LSB  xxxx.0001
        L = L >> 1;
        R = R << 1; 
    }
    return OUT;

Error while retrieving information from the server RPC:s-7:AEC-0 in Google play?

I had the same issue - it sorted itself out in ~3 hours after I uploaded the app to the Play console. According to Google:

Warning: It may take up to 2-3 hours after uploading the APK for Google Play to recognize your updated APK version. If you try to test your application before your uploaded APK is recognized by Google Play, your application will receive a ‘purchase cancelled’ response with an error message “This version of the application is not enabled for In-app Billing.

While the message is not the same, I suspect the root cause to be the same.

xxxxxx.exe is not a valid Win32 application

It's Feb 2013, and I can now target XP in VS2012 by setting:

Project Properties -> General -> Platform Toolset to:

Visual Studio 2012 - Windows XP (v110_xp)

You will have to redistribute the msvcp110.dll libraries et al with your application, which are found here: "<Program Files>\Microsoft Visual Studio 11.0\VC\redist\x86\Microsoft.VC110.CRT\"


Update Aug 2015 with Visual Studio 2015

There seems to be quite a selection now. I was able to compile application in VS2015 using Visual Studio 2015 - Windows XP (v140_xp) setting. To make it actually run on Win XP I had to deploy (copy alongside application) msvcr100.dll for Release build and msvcr110.dll and msvcr100d.dll for Debug build (note there is a difference in numbers 100 and 110, also debug lib msvcr100d.dll may not be redistributable) Targeting Windows XP with Visual Studio 2015

How to horizontally align ul to center of div?

Following is a list of solutions to centering things in CSS horizontally. The snippet includes all of them.

_x000D_
_x000D_
html {_x000D_
  font: 1.25em/1.5 Georgia, Times, serif;_x000D_
}_x000D_
_x000D_
pre {_x000D_
  color: #fff;_x000D_
  background-color: #333;_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
blockquote {_x000D_
  max-width: 400px;_x000D_
  background-color: #e0f0d1;_x000D_
}_x000D_
_x000D_
blockquote > p {_x000D_
  font-style: italic;_x000D_
}_x000D_
_x000D_
blockquote > p:first-of-type::before {_x000D_
  content: open-quote;_x000D_
}_x000D_
_x000D_
blockquote > p:last-of-type::after {_x000D_
  content: close-quote;_x000D_
}_x000D_
_x000D_
blockquote > footer::before {_x000D_
  content: "\2014";_x000D_
}_x000D_
_x000D_
.container,_x000D_
blockquote {_x000D_
  position: relative;_x000D_
  padding: 20px;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  background-color: tomato;_x000D_
}_x000D_
_x000D_
.container::after,_x000D_
blockquote::after {_x000D_
  position: absolute;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  padding: 2px 10px;_x000D_
  border: 1px dotted #000;_x000D_
  background-color: #fff;_x000D_
}_x000D_
_x000D_
.container::after {_x000D_
  content: ".container-" attr(data-num);_x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
blockquote::after {_x000D_
  content: ".quote-" attr(data-num);_x000D_
  z-index: 2;_x000D_
}_x000D_
_x000D_
.container-4 {_x000D_
  margin-bottom: 200px;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 1_x000D_
 */_x000D_
.quote-1 {_x000D_
  max-width: 400px;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 2_x000D_
 */_x000D_
.container-2 {_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.quote-2 {_x000D_
  display: inline-block;_x000D_
  text-align: left;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 3_x000D_
 */_x000D_
.quote-3 {_x000D_
  display: table;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 4_x000D_
 */_x000D_
.container-4 {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.quote-4 {_x000D_
  position: absolute;_x000D_
  left: 50%;_x000D_
  transform: translateX(-50%);_x000D_
}_x000D_
_x000D_
/**_x000D_
 * Solution 5_x000D_
 */_x000D_
.container-5 {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<main>_x000D_
  <h1>CSS: Horizontal Centering</h1>_x000D_
_x000D_
  <h2>Uncentered Example</h2>_x000D_
  <p>This is the scenario: We have a container with an element inside of it that we want to center. I just added a little padding and background colors so both elements are distinquishable.</p>_x000D_
_x000D_
  <div class="container  container-0" data-num="0">_x000D_
    <blockquote class="quote-0" data-num="0">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 1: Using <code>max-width</code> & <code>margin</code> (IE7)</h2>_x000D_
_x000D_
  <p>This method is widely used. The upside here is that only the element which one wants to center needs rules.</p>_x000D_
_x000D_
<pre><code>.quote-1 {_x000D_
  max-width: 400px;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-1" data-num="1">_x000D_
    <blockquote class="quote  quote-1" data-num="1">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 2: Using <code>display: inline-block</code> and <code>text-align</code> (IE8)</h2>_x000D_
_x000D_
  <p>This method utilizes that <code>inline-block</code> elements are treated as text and as such they are affected by the <code>text-align</code> property. This does not rely on a fixed width which is an upside. This is helpful for when you don’t know the number of elements in a container for example.</p>_x000D_
_x000D_
<pre><code>.container-2 {_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.quote-2 {_x000D_
  display: inline-block;_x000D_
  text-align: left;_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-2" data-num="2">_x000D_
    <blockquote class="quote  quote-2" data-num="2">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 3: Using <code>display: table</code> and <code>margin</code> (IE8)</h2>_x000D_
_x000D_
  <p>Very similar to the second solution but only requires to apply rules on the element that is to be centered.</p>_x000D_
_x000D_
<pre><code>.quote-3 {_x000D_
  display: table;_x000D_
  margin-right: auto;_x000D_
  margin-left: auto;_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-3" data-num="3">_x000D_
    <blockquote class="quote  quote-3" data-num="3">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 4: Using <code>translate()</code> and <code>position</code> (IE9)</h2>_x000D_
_x000D_
  <p>Don’t use as a general approach for horizontal centering elements. The downside here is that the centered element will be removed from the document flow. Notice the container shrinking to zero height with only the padding keeping it visible. This is what <i>removing an element from the document flow</i> means.</p>_x000D_
_x000D_
  <p>There are however applications for this technique. For example, it works for <b>vertically</b> centering by using <code>top</code> or <code>bottom</code> together with <code>translateY()</code>.</p>_x000D_
_x000D_
<pre><code>.container-4 {_x000D_
    position: relative;_x000D_
}_x000D_
_x000D_
.quote-4 {_x000D_
  position: absolute;_x000D_
  left: 50%;_x000D_
  transform: translateX(-50%);_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-4" data-num="4">_x000D_
    <blockquote class="quote  quote-4" data-num="4">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
_x000D_
  <h2>Solution 5: Using Flexible Box Layout Module (IE10+ with vendor prefix)</h2>_x000D_
_x000D_
  <p></p>_x000D_
_x000D_
<pre><code>.container-5 {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}</code></pre>_x000D_
_x000D_
  <div class="container  container-5" data-num="5">_x000D_
    <blockquote class="quote  quote-5" data-num="5">_x000D_
      <p>My friend Data. You see things with the wonder of a child. And that makes you more human than any of us.</p>_x000D_
      <footer>Tasha Yar about Data</footer>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
</main>
_x000D_
_x000D_
_x000D_


display: flex

.container {
  display: flex;
  justify-content: center;
}

Notes:


max-width & margin

You can horizontally center a block-level element by assigning a fixed width and setting margin-right and margin-left to auto.

.container ul {
  /* for IE below version 7 use `width` instead of `max-width` */
  max-width: 800px;
  margin-right: auto;
  margin-left: auto;
}

Notes:

  • No container needed
  • Requires (maximum) width of the centered element to be known

IE9+: transform: translatex(-50%) & left: 50%

This is similar to the quirky centering method which uses absolute positioning and negative margins.

.container {
  position: relative;
}

.container ul {
  position: absolute;
  left: 50%;
  transform: translatex(-50%);
}

Notes:

  • The centered element will be removed from document flow. All elements will completely ignore of the centered element.
  • This technique allows vertical centering by using top instead of left and translateY() instead of translateX(). The two can even be combined.
  • Browser support: transform2d

IE8+: display: table & margin

Just like the first solution, you use auto values for right and left margins, but don’t assign a width. If you don’t need to support IE7 and below, this is better suited, although it feels kind of hacky to use the table property value for display.

.container ul {
  display: table;
  margin-right: auto;
  margin-left: auto;
}

IE8+: display: inline-block & text-align

Centering an element just like you would do with regular text is possible as well. Downside: You need to assign values to both a container and the element itself.

.container {
  text-align: center;
}

.container ul {
  display: inline-block;

  /* One most likely needs to realign flow content */
  text-align: initial;
}

Notes:

  • Does not require to specify a (maximum) width
  • Aligns flow content to the center (potentially unwanted side effect)
  • Works kind of well with a dynamic number of menu items (i.e. in cases where you can’t know the width a single item will take up)

Count number of occurrences for each unique value

Yes, you can use GROUP BY:

SELECT time,
       activities,
       COUNT(*)
FROM table
GROUP BY time, activities;

How to display request headers with command line curl

I believe the command line switch you are looking for to pass to curl is -I.

Example usage:

$ curl -I http://heatmiser.counterhack.com/zone-5-15614E3A-CEA7-4A28-A85A-D688CC418287  
HTTP/1.1 301 Moved Permanently
Date: Sat, 29 Dec 2012 15:22:05 GMT
Server: Apache
Location: http://heatmiser.counterhack.com/zone-5-15614E3A-CEA7-4A28-A85A-D688CC418287/
Content-Type: text/html; charset=iso-8859-1

Additionally, if you encounter a response HTTP status code of 301, you might like to also pass a -L argument switch to tell curl to follow URL redirects, and, in this case, print the headers of all pages (including the URL redirects), illustrated below:

$ curl -I -L http://heatmiser.counterhack.com/zone-5-15614E3A-CEA7-4A28-A85A-D688CC418287
HTTP/1.1 301 Moved Permanently
Date: Sat, 29 Dec 2012 15:22:13 GMT
Server: Apache
Location: http://heatmiser.counterhack.com/zone-5-15614E3A-CEA7-4A28-A85A-D688CC418287/
Content-Type: text/html; charset=iso-8859-1

HTTP/1.1 302 Found
Date: Sat, 29 Dec 2012 15:22:13 GMT
Server: Apache
Set-Cookie: UID=b8c37e33defde51cf91e1e03e51657da
Location: noaccess.php
Content-Type: text/html

HTTP/1.1 200 OK
Date: Sat, 29 Dec 2012 15:22:13 GMT
Server: Apache
Content-Type: text/html

Test if a vector contains a given element

I will group the options based on output. Assume the following vector for all the examples.

v <- c('z', 'a','b','a','e')

For checking presence:

%in%

> 'a' %in% v
[1] TRUE

any()

> any('a'==v)
[1] TRUE

is.element()

> is.element('a', v)
[1] TRUE

For finding first occurance:

match()

> match('a', v)
[1] 2

For finding all occurances as vector of indices:

which()

> which('a' == v)
[1] 2 4

For finding all occurances as logical vector:

==

> 'a' == v
[1] FALSE  TRUE FALSE  TRUE FALSE

Edit: Removing grep() and grepl() from the list for reason mentioned in comments

Caching a jquery ajax response in javascript/browser

I was looking for caching for my phonegap app storage and I found the answer of @TecHunter which is great but done using localCache.

I found and come to know that localStorage is another alternative to cache the data returned by ajax call. So, I created one demo using localStorage which will help others who may want to use localStorage instead of localCache for caching.

Ajax Call:

$.ajax({
    type: "POST",
    dataType: 'json',
    contentType: "application/json; charset=utf-8",
    url: url,
    data: '{"Id":"' + Id + '"}',
    cache: true, //It must "true" if you want to cache else "false"
    //async: false,
    success: function (data) {
        var resData = JSON.parse(data);
        var Info = resData.Info;
        if (Info) {
            customerName = Info.FirstName;
        }
    },
    error: function (xhr, textStatus, error) {
        alert("Error Happened!");
    }
});

To store data into localStorage:

$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.cache) {
    var success = originalOptions.success || $.noop,
        url = originalOptions.url;

    options.cache = false; //remove jQuery cache as we have our own localStorage
    options.beforeSend = function () {
        if (localStorage.getItem(url)) {
            success(localStorage.getItem(url));
            return false;
        }
        return true;
    };
    options.success = function (data, textStatus) {
        var responseData = JSON.stringify(data.responseJSON);
        localStorage.setItem(url, responseData);
        if ($.isFunction(success)) success(responseJSON); //call back to original ajax call
    };
}
});

If you want to remove localStorage, use following statement wherever you want:

localStorage.removeItem("Info");

Hope it helps others!

What properties does @Column columnDefinition make redundant?

columnDefinition will override the sql DDL generated by hibernate for this particular column, it is non portable and depends on what database you are using. You can use it to specify nullable, length, precision, scale... ect.

How do I set the icon for my application in visual studio 2008?

First go to Resource View (from menu: View --> Other Window --> Resource View). Then in Resource View navigate through resources, if any. If there is already a resource of Icon type, added by Visual Studio, then open and edit it. Otherwise right-click and select Add Resource, and then add a new icon.

Use the embedded image editor in order to edit the existing or new icon. Note that an icon can include several types (sizes), selected from Image menu.

Then compile your project and see the effect.

See: http://social.microsoft.com/Forums/en-US/vcgeneral/thread/87614e26-075c-4d5d-a45a-f462c79ab0a0

Create Excel files from C# without office

Try EPPlus if you use Excel 2007. Supports ranges, cellstyling, charts, shapes, pictures and a lot of other stuff

Making text background transparent but not text itself

If you use RGBA for modern browsers you don't need let older IEs use only the non-transparent version of the given color with RGB.

If you don't stick to CSS-only solutions, give CSS3PIE a try. With this syntax you can see exactly the same result in older IEs that you see in modern browsers:

div {
    -pie-background: rgba(223,231,233,0.8);
    behavior: url(../PIE.htc);
}

Iterator invalidation rules

Here is a nice summary table from cppreference.com:

enter image description here

Here, insertion refers to any method which adds one or more elements to the container and erasure refers to any method which removes one or more elements from the container.

Calling the base constructor in C#

If you need to call the base constructor but not right away because your new (derived) class needs to do some data manipulation, the best solution is to resort to factory method. What you need to do is to mark private your derived constructor, then make a static method in your class that will do all the necessary stuff and later call the constructor and return the object.

public class MyClass : BaseClass
{
    private MyClass(string someString) : base(someString)
    {
        //your code goes in here
    }

    public static MyClass FactoryMethod(string someString)
    {
        //whatever you want to do with your string before passing it in
        return new MyClass(someString);
    }
}

Split string based on a regular expression

The str.split method will automatically remove all white space between items:

>>> str1 = "a    b     c      d"
>>> str1.split()
['a', 'b', 'c', 'd']

Docs are here: http://docs.python.org/library/stdtypes.html#str.split

Javascript extends class

Douglas Crockford has some very good explanations of inheritance in JavaScript:

  1. prototypal inheritance: the 'natural' way to do things in JavaScript
  2. classical inheritance: closer to what you find in most OO languages, but kind of runs against the grain of JavaScript

Swift Bridging Header import issue

After initial few days of struggle, I finally managed to successfully integrate Facebook signup to my iOS app. Here are the steps(I am assuming you have already installed Facebook SDK v4.1 or above in your machines):

  1. Add the Facebook frameworks - FBSDKCoreKit,FBSDKLoginKit under your project.
  2. Make no changes in the Build settings as FB SDK v4.1 and above doesn't need anymore bridging header files.
  3. Import the FBSDKCorekit, FBSDKLoginKit in ViewController.swift, AppDelegate.swift files
  4. Add informations in the pList as mentioned here

  5. Build your app. And wohoo! no compile time errors.

Unix's 'ls' sort by name

The ls utility should conform to IEEE Std 1003.1-2001 (POSIX.1) which states:

22027: it shall sort directory and non-directory operands separately according to the collating sequence in the current locale.

26027: By default, the format is unspecified, but the output shall be sorted alphabetically by symbol name:

  • Library or object name, if -A is specified
  • Symbol name
  • Symbol type
  • Value of the symbol
  • The size associated with the symbol, if applicable

How to import a module in Python with importlib.import_module

And don't forget to create a __init__.py with each folder/subfolder (even if they are empty)

Run cURL commands from Windows console

If you use the Chocolatey package manager, you can install cURL by running this command from the command line or from PowerShell:

choco install curl

How to SELECT based on value of another SELECT

If you want to SELECT based on the value of another SELECT, then you probably want a "subselect":

http://beginner-sql-tutorial.com/sql-subquery.htm

For example, (from the link above):

  1. You want the first and last names from table "student_details" ...

  2. But you only want this information for those students in "science" class:

     SELECT id, first_name
     FROM student_details
     WHERE first_name IN (SELECT first_name
     FROM student_details
     WHERE subject= 'Science'); 
    

Frankly, I'm not sure this is what you're looking for or not ... but I hope it helps ... at least a little...

IMHO...

How to resolve symbolic links in a shell script

This is a symlink resolver in Bash that works whether the link is a directory or a non-directory:

function readlinks {(
  set -o errexit -o nounset
  declare n=0 limit=1024 link="$1"

  # If it's a directory, just skip all this.
  if cd "$link" 2>/dev/null
  then
    pwd -P
    return 0
  fi

  # Resolve until we are out of links (or recurse too deep).
  while [[ -L $link ]] && [[ $n -lt $limit ]]
  do
    cd "$(dirname -- "$link")"
    n=$((n + 1))
    link="$(readlink -- "${link##*/}")"
  done
  cd "$(dirname -- "$link")"

  if [[ $n -ge $limit ]]
  then
    echo "Recursion limit ($limit) exceeded." >&2
    return 2
  fi

  printf '%s/%s\n' "$(pwd -P)" "${link##*/}"
)}

Note that all the cd and set stuff takes place in a subshell.

Convert a object into JSON in REST service by Spring MVC

Finally I got solution using Jackson library along with Spring MVC. I got this solution from an example of Journal Dev( http://www.journaldev.com/2552/spring-restful-web-service-example-with-json-jackson-and-client-program )

So, the code changes I have done are:

  • Include the library in Maven.
  • Add JSON conversion Servlet into servlet-context.xml.
  • Change the Model into Serializable.

I didn't made any changes to my REST service controller. By default it converts into JSON.

Maven project.build.directory

You can find the most up to date answer for the value in your project just execute the

mvn3 help:effective-pom

command and find the <build> ... <directory> tag's value in the result aka in the effective-pom. It will show the value of the Super POM unless you have overwritten.

What is the use of ObservableCollection in .net?

ObservableCollection Caveat

Mentioned above (Said Roohullah Allem)

What makes the ObservableCollection class unique is that this class supports an event named CollectionChanged.

Keep this in mind...If you adding a large number of items to an ObservableCollection the UI will also update that many times. This can really gum up or freeze your UI. A work around would be to create a new list, add all the items then set your property to the new list. This hits the UI once. Again...this is for adding a large number of items.

How to cast from List<Double> to double[] in Java?

You can convert to a Double[] by calling frameList.toArray(new Double[frameList.size()]), but you'll need to iterate the list/array to convert to double[]

How can I check if a view is visible or not in Android?

You'd use the corresponding method getVisibility(). Method names prefixed with 'get' and 'set' are Java's convention for representing properties. Some language have actual language constructs for properties but Java isn't one of them. So when you see something labeled 'setX', you can be 99% certain there's a corresponding 'getX' that will tell you the value.

JavaScript getElementByID() not working

You need to put the JavaScript at the end of the body tag.

It doesn't find it because it's not in the DOM yet!

You can also wrap it in the onload event handler like this:

window.onload = function() {
var refButton = document.getElementById( 'btnButton' );
refButton.onclick = function() {
   alert( 'I am clicked!' );
}
}

Issue with virtualenv - cannot activate

:: location of bat file
::C:\Users\gaojia\Dropbox\Projects\free_return\venv\Scripts\activate.bat 
:: location of the cmd bat file and the ipython notebook
::C:\Users\gaojia\Dropbox\Projects\free_return\scripts\pre_analysis
source ..\..\venv\Scripts\activate
PAUSE
jupyter nbconvert --to html --execute consumer_response_DID.ipynb
PAUSE

Above is my bat file through which I try to execute an ipython notebook. But the cmd window gives me nothing and shut down instantly, any suggestion why would this happen?

How can I use a C++ library from node.js?

There is a fresh answer to that question now. SWIG, as of version 3.0 seems to provide javascript interface generators for Node.js, Webkit and v8.

I've been using SWIG extensively for Java and Python for a while, and once you understand how SWIG works, there is almost no effort(compared to ffi or the equivalent in the target language) needed for interfacing C++ code to the languages that SWIG supports.

As a small example, say you have a library with the header myclass.h:

#include<iostream>

class MyClass {
        int myNumber;
public:
        MyClass(int number): myNumber(number){}
        void sayHello() {
                std::cout << "Hello, my number is:" 
                << myNumber <<std::endl;
        }
};

In order to use this class in node, you simply write the following SWIG interface file (mylib.i):

%module "mylib"
%{
#include "myclass.h"
%}
%include "myclass.h"

Create the binding file binding.gyp:

{
  "targets": [
    {
      "target_name": "mylib",
      "sources": [ "mylib_wrap.cxx" ]
    }
  ]
}

Run the following commands:

swig -c++ -javascript -node mylib.i
node-gyp build

Now, running node from the same folder, you can do:

> var mylib = require("./build/Release/mylib")
> var c = new mylib.MyClass(5)
> c.sayHello()
Hello, my number is:5

Even though we needed to write 2 interface files for such a small example, note how we didn't have to mention the MyClass constructor nor the sayHello method anywhere, SWIG discovers these things, and automatically generates natural interfaces.

how to change class name of an element by jquery

$('.IsBestAnswer').addClass('bestanswer').removeClass('IsBestAnswer');

Case in method names is important, so no addclass.

jQuery addClass()
jQuery removeClass()

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

If this is a SQL question, and I understand what you are asking, (it's not entirely clear), just add distinct to the query

   Select Distinct * From TempTable

How can one display images side by side in a GitHub README.md?

This is the best way to make add images/screenshots of your app and keep your repository look clean.

Create a screenshot folder in your repository and add the images you want to display.

Now go to README.md and add this HTML code to form a table.

#### Flutter App Screenshots

<table>
  <tr>
    <td>First Screen Page</td>
     <td>Holiday Mention</td>
     <td>Present day in purple and selected day in pink</td>
  </tr>
  <tr>
    <td><img src="screenshots/Screenshot_1582745092.png" width=270 height=480></td>
    <td><img src="screenshots/Screenshot_1582745125.png" width=270 height=480></td>
    <td><img src="screenshots/Screenshot_1582745139.png" width=270 height=480></td>
  </tr>
 </table>

In the <td><img src="(COPY IMAGE PATH HERE)" width=270 height=480></td>

** To get the image path --> Go to the screenshot folder and open the image and on the right most side, you will find Copy path button.

You will get a table like this in your repository--->

enter image description here

AngularJS sorting by property

Don't forget that parseInt() only works for Integer values. To sort string values you need to swap this:

array.sort(function(a, b){
  a = parseInt(a[attribute]);
  b = parseInt(b[attribute]);
  return a - b;
});

with this:

array.sort(function(a, b){
  var alc = a[attribute].toLowerCase(),
      blc = b[attribute].toLowerCase();
  return alc > blc ? 1 : alc < blc ? -1 : 0;
});

Can anyone recommend a simple Java web-app framework?

The correct answer IMO depends on two things: 1. What is the purpose of the web application you want to write? You only told us that you want to write it fast, but not what you are actually trying to do. Eg. does it need a database? Is it some sort of business app (hint: maybe search for "scaffolding")? ..or a game? ..or are you just experimenting with sthg? 2. What frameworks are you most familiar with right now? What often takes most time is reading docs and figuring out how things (really) work. If you want it done quickly, stick to things you already know well.

Regular Expression to get a string between parentheses in Javascript

You need to create a set of escaped (with \) parentheses (that match the parentheses) and a group of regular parentheses that create your capturing group:

_x000D_
_x000D_
var regExp = /\(([^)]+)\)/;_x000D_
var matches = regExp.exec("I expect five hundred dollars ($500).");_x000D_
_x000D_
//matches[1] contains the value between the parentheses_x000D_
console.log(matches[1]);
_x000D_
_x000D_
_x000D_

Breakdown:

  • \( : match an opening parentheses
  • ( : begin capturing group
  • [^)]+: match one or more non ) characters
  • ) : end capturing group
  • \) : match closing parentheses

Here is a visual explanation on RegExplained

How do you install an APK file in the Android emulator?

In Genymotion just drag and drop the *.apk file in to the emulator and it will automatically installs and runs.

http://www.genymotion.com/

Replace all double quotes within String

Here's how

String details = "Hello \"world\"!";
details = details.replace("\"","\\\"");
System.out.println(details);               // Hello \"world\"!

Note that strings are immutable, thus it is not sufficient to simply do details.replace("\"","\\\""). You must reassign the variable details to the resulting string.


Using

details = details.replaceAll("\"","&quote;");

instead, results in

Hello &quote;world&quote;!

Customize Bootstrap checkboxes

As others have said, the style you're after is actually just the Mac OS checkbox style, so it will look radically different on other devices.

In fact both screenshots you linked show what checkboxes look like on Mac OS in Chrome, the grey one is shown at non-100% zoom levels.

show and hide divs based on radio button click

You're on the right track, but you forgot two things:

  1. add the desc classes to your description divs
  2. You have numeric values for the input but text for the id.

I have fixed the above and also added a line to initially hide() the third description div.

Check it out in action - http://jsfiddle.net/VgAgu/3/

HTML

<div id="myRadioGroup">
    2 Cars<input type="radio" name="cars" checked="checked" value="2"  />
    3 Cars<input type="radio" name="cars" value="3" />

    <div id="Cars2" class="desc">
        2 Cars Selected
    </div>
    <div id="Cars3" class="desc" style="display: none;">
        3 Cars
    </div>
</div>

JQuery

$(document).ready(function() {
    $("input[name$='cars']").click(function() {
        var test = $(this).val();

        $("div.desc").hide();
        $("#Cars" + test).show();
    });
});

jQuery returning "parsererror" for ajax request

I was also getting "Request return with error:parsererror." in the javascript console. In my case it wasn´t a matter of Json, but I had to pass to the view text area a valid encoding.

  String encodedString = getEncodedString(text, encoding);
  view.setTextAreaContent(encodedString);

Excel: Search for a list of strings within a particular string using array formulas?

This will return the matching word or an error if no match is found. For this example I used the following.

List of words to search for: G1:G7
Cell to search in: A1

=INDEX(G1:G7,MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*(ROW(G1:G7)-ROW(G1)+1)))

Enter as an array formula by pressing Ctrl+Shift+Enter.

This formula works by first looking through the list of words to find matches, then recording the position of the word in the list as a positive value if it is found or as a negative value if it is not found. The largest value from this array is the position of the found word in the list. If no word is found, a negative value is passed into the INDEX() function, throwing an error.

To return the row number of a matching word, you can use the following:

=MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*ROW(G1:G7))

This also must be entered as an array formula by pressing Ctrl+Shift+Enter. It will return -1 if no match is found.

Javascript "Cannot read property 'length' of undefined" when checking a variable's length

You can simply check whether the element length is undefined or not just by using

var theHref = $(obj.mainImg_select).attr('href');
if (theHref){
   //get the length here if the element is not undefined
   elementLength = theHref.length
   // do stuff
} else {
   // do other stuff
}

Euclidean distance of two vectors

Use the dist() function, but you need to form a matrix from the two inputs for the first argument to dist():

dist(rbind(x1, x2))

For the input in the OP's question we get:

> dist(rbind(x1, x2))
        x1
x2 7.94821

a single value that is the Euclidean distance between x1 and x2.

Converting a float to a string without rounding it

len(repr(float(x)/3))

However I must say that this isn't as reliable as you think.

Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:

>>> print len(repr(0.1))
19
>>> print repr(0.1)
0.10000000000000001

The explanation on why this happens is in this chapter of the python tutorial.

A solution would be to use a type that specifically tracks decimal numbers, like python's decimal.Decimal:

>>> print len(str(decimal.Decimal('0.1')))
3

How do I jump to a closing bracket in Visual Studio Code?

The out-of-the-box way to do it is

Ctrl + Shift + |

Address in mailbox given [] does not comply with RFC 2822, 3.6.2. when email is in a variable

Its because the email address which is being sent is blank. see those empty brackets? that means the email address is not being put in the $address of the swiftmailer function.

How do you find the first key in a dictionary?

For Python 3 below eliminates overhead of list conversion:

first = next(iter(prices.values()))

datatable jquery - table header width not aligned with body width

I did have this problem for a while and I realised that my table was drawn before it was shown.

<div class="row">
    <div class="col-md-12" id="divResults">
    </div>
</div>        

function ShowResults(data) {
    $div.fadeOut('fast', function () {
        $div.html(data);
        // I used to call DataTable() here (there may be multiple tables in data)
        // each header's width was 0 and missaligned with the columns
        // the width woulld resize when I sorted a column or resized the window 
        // $div.find('table').DataTable(options);
        $div.fadeIn('fast', function () {
            Loading(false);
            $div.find('table').DataTable(options); // moved the call here and everything is now dandy!!!
        });
    });
}     

MySQL Data Source not appearing in Visual Studio

i install mysql for visual studio and the problem simply solved.although version of my visual studio is 2012!

What exactly does Perl's "bless" do?

Short version: it's marking that hash as attached to the current package namespace (so that that package provides its class implementation).

MySQL "incorrect string value" error when save unicode string in Django

If you have this problem here's a python script to change all the columns of your mysql database automatically.

#! /usr/bin/env python
import MySQLdb

host = "localhost"
passwd = "passwd"
user = "youruser"
dbname = "yourdbname"

db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=dbname)
cursor = db.cursor()

cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)

sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
cursor.execute(sql)

results = cursor.fetchall()
for row in results:
  sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
  cursor.execute(sql)
db.close()

Convert string[] to int[] in one line of code using LINQ

you can simply cast a string array to int array by:

var converted = arr.Select(int.Parse)

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

Using ! on the IPython console within spyder allows you to use pip. So, in the example, you could do:

[1] !pip install pymorph

Note, this is also available (though perhaps unreliably) on the Python console for Spyder versions before ~2.3.3. Thanks to @CarlosCordoba for this clarification.

Generate list of all possible permutations of a string

def permutation(str)
  posibilities = []
  str.split('').each do |char|
    if posibilities.size == 0
      posibilities[0] = char.downcase
      posibilities[1] = char.upcase
    else
      posibilities_count = posibilities.length
      posibilities = posibilities + posibilities
      posibilities_count.times do |i|
        posibilities[i] += char.downcase
        posibilities[i+posibilities_count] += char.upcase
      end
    end
  end
  posibilities
end

Here is my take on a non recursive version

Java - remove last known item from ArrayList

The compiler complains that you are trying something of a list of ClientThread objects to a String. Either change the type of hey to ClientThread or clients to List<String>.

In addition: Valid indices for lists are from 0 to size()-1.

So you probably want to write

   String hey = clients.get(clients.size()-1);

Python: Number of rows affected by cursor.execute("SELECT ...)

To get the number of selected rows I usually use the following:

cursor.execute(sql)
count = (len(cursor.fetchall))

How to get the integer value of day of week

Another way to get Monday with integer value 1 and Sunday with integer value 7

int day = ((int)DateTime.Now.DayOfWeek + 6) % 7 + 1;

Set title background color

There is another way to change the background color, however it is a hack and might fail on future versions of Android if the View hierarchy of the Window and its title is changed. However, the code won't crash, just miss setting the wanted color, in such a case.

In your Activity, like onCreate, do:

View titleView = getWindow().findViewById(android.R.id.title);
if (titleView != null) {
  ViewParent parent = titleView.getParent();
  if (parent != null && (parent instanceof View)) {
    View parentView = (View)parent;
    parentView.setBackgroundColor(Color.rgb(0x88, 0x33, 0x33));
  }
}

How can I add C++11 support to Code::Blocks compiler?

Use g++ -std=c++11 -o <output_file_name> <file_to_be_compiled>

Using setImageDrawable dynamically to set image in an ImageView

Try this,

int id = getResources().getIdentifier("yourpackagename:drawable/" + StringGenerated, null, null);

This will return the id of the drawable you want to access... then you can set the image in the imageview by doing the following

imageview.setImageResource(id);

How to add new item to hash

Create hash as:

h = Hash.new
=> {}

Now insert into hash as:

h = Hash["one" => 1]

Could not find any resources appropriate for the specified culture or the neutral culture

I resolved this by going to the project where my resources file was saved, scrolling down to its ItemGroup and adding a logical name that corresponded to the path the compiler expected.

My EmbeddedResource looked like this:

   <ItemGroup>
    <EmbeddedResource Update="Properties\TextResources.resx">
      <Generator>PublicResXFileCodeGenerator</Generator>
      <LastGenOutput>TextResources.Designer.cs</LastGenOutput>
    </EmbeddedResource>
  </ItemGroup>

Now it looks like this

  <ItemGroup>
    <EmbeddedResource Update="Properties\TextResources.resx">
      <Generator>PublicResXFileCodeGenerator</Generator>
      <LastGenOutput>TextResources.Designer.cs</LastGenOutput>
      <LogicalName>MyProject.Properties.Resources.resources</LogicalName>
    </EmbeddedResource>
  </ItemGroup>

Android: Clear Activity Stack

In my case, LoginActivity was closed as well. As a result,

Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK

did not help.

However, setting

Intent.FLAG_ACTIVITY_NEW_TASK

helped me.

Weblogic Transaction Timeout : how to set in admin console in WebLogic AS 8.1

Its possible at application level. Click on the EJB under the deployment(like Home > >Summary of Deployments >). Click on the Configuration tab and there is "Transaction Timeout:"

Why does the 'int' object is not callable error occur when using the sum() function?

In the interpreter its easy to restart it and fix such problems. If you don't want to restart the interpreter, there is another way to fix it:

Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> l = [1,2,3]
>>> sum(l)
6
>>> sum = 0 # oops! shadowed a builtin!
>>> sum(l)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> import sys
>>> sum = sys.modules['__builtin__'].sum # -- fixing sum
>>> sum(l)
6

This also comes in handy if you happened to assign a value to any other builtin, like dict or list

syntax error when using command line in python

Running from the command line means running from the terminal or DOS shell. You are running it from Python itself.

CSS Disabled scrolling

overflow-x: hidden;
would hide any thing on the x-axis that goes outside of the element, so there would be no need for the horizontal scrollbar and it get removed.

overflow-y: hidden;
would hide any thing on the y-axis that goes outside of the element, so there would be no need for the vertical scrollbar and it get removed.

overflow: hidden;
would remove both scrollbars

DD/MM/YYYY Date format in Moment.js

You can use this

moment().format("DD/MM/YYYY");

However, this returns a date string in the specified format for today, not a moment date object. Doing the following will make it a moment date object in the format you want.

var someDateString = moment().format("DD/MM/YYYY");
var someDate = moment(someDateString, "DD/MM/YYYY");

Scanner is skipping nextLine() after using next() or nextFoo()?

If you want to scan input fast without getting confused into Scanner class nextLine() method , Use Custom Input Scanner for it .

Code :

class ScanReader {
/**
* @author Nikunj Khokhar
*/
    private byte[] buf = new byte[4 * 1024];
    private int index;
    private BufferedInputStream in;
    private int total;

    public ScanReader(InputStream inputStream) {
        in = new BufferedInputStream(inputStream);
    }

    private int scan() throws IOException {
        if (index >= total) {
            index = 0;
            total = in.read(buf);
            if (total <= 0) return -1;
        }
        return buf[index++];
    }
    public char scanChar(){
        int c=scan();
        while (isWhiteSpace(c))c=scan();
        return (char)c;
    }


    public int scanInt() throws IOException {
        int integer = 0;
        int n = scan();
        while (isWhiteSpace(n)) n = scan();
        int neg = 1;
        if (n == '-') {
            neg = -1;
            n = scan();
        }
        while (!isWhiteSpace(n)) {
            if (n >= '0' && n <= '9') {
                integer *= 10;
                integer += n - '0';
                n = scan();
            }
        }
        return neg * integer;
    }

    public String scanString() throws IOException {
        int c = scan();
        while (isWhiteSpace(c)) c = scan();
        StringBuilder res = new StringBuilder();
        do {
            res.appendCodePoint(c);
            c = scan();
        } while (!isWhiteSpace(c));
        return res.toString();
    }

    private boolean isWhiteSpace(int n) {
        if (n == ' ' || n == '\n' || n == '\r' || n == '\t' || n == -1) return true;
        else return false;
    }

    public long scanLong() throws IOException {
        long integer = 0;
        int n = scan();
        while (isWhiteSpace(n)) n = scan();
        int neg = 1;
        if (n == '-') {
            neg = -1;
            n = scan();
        }
        while (!isWhiteSpace(n)) {
            if (n >= '0' && n <= '9') {
                integer *= 10;
                integer += n - '0';
                n = scan();
            }
        }
        return neg * integer;
    }

    public void scanLong(long[] A) throws IOException {
        for (int i = 0; i < A.length; i++) A[i] = scanLong();
    }

    public void scanInt(int[] A) throws IOException {
        for (int i = 0; i < A.length; i++) A[i] = scanInt();
    }

    public double scanDouble() throws IOException {
        int c = scan();
        while (isWhiteSpace(c)) c = scan();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = scan();
        }
        double res = 0;
        while (!isWhiteSpace(c) && c != '.') {
            if (c == 'e' || c == 'E') {
                return res * Math.pow(10, scanInt());
            }
            res *= 10;
            res += c - '0';
            c = scan();
        }
        if (c == '.') {
            c = scan();
            double m = 1;
            while (!isWhiteSpace(c)) {
                if (c == 'e' || c == 'E') {
                    return res * Math.pow(10, scanInt());
                }
                m /= 10;
                res += (c - '0') * m;
                c = scan();
            }
        }
        return res * sgn;
    }

}

Advantages :

  • Scans Input faster than BufferReader
  • Reduces Time Complexity
  • Flushes Buffer for every next input

Methods :

  • scanChar() - scan single character
  • scanInt() - scan Integer value
  • scanLong() - scan Long value
  • scanString() - scan String value
  • scanDouble() - scan Double value
  • scanInt(int[] array) - scans complete Array(Integer)
  • scanLong(long[] array) - scans complete Array(Long)

Usage :

  1. Copy the Given Code below your java code.
  2. Initialise Object for Given Class

ScanReader sc = new ScanReader(System.in); 3. Import necessary Classes :

import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; 4. Throw IOException from your main method to handle Exception 5. Use Provided Methods. 6. Enjoy

Example :

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
class Main{
    public static void main(String... as) throws IOException{
        ScanReader sc = new ScanReader(System.in);
        int a=sc.scanInt();
        System.out.println(a);
    }
}
class ScanReader....

DateTime group by date and hour

SELECT [activity_dt], COUNT(*) as [Count]
  FROM 
 (SELECT dateadd(hh, datediff(hh, '20010101', [activity_dt]), '20010101') as [activity_dt]
    FROM table) abc
 GROUP BY [activity_dt]

How to convert JSON object to JavaScript array?

As simple as this !

var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [json_data];
console.log(result);

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

What are the differences between normal and slim package of jquery?

I could see $.ajax is removed from jQuery slim 3.2.1

From the jQuery docs

You can also use the slim build, which excludes the ajax and effects modules

Below is the comment from the slim version with the features removed

/*! jQuery v3.2.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-effects/animatedSelector | (c) JS Foundation and other contributors | jquery.org/license */

DSO missing from command line

DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

That is, try adding -lpthread to your command line.

Intermediate language used in scalac?

maybe this will help you out:

http://lampwww.epfl.ch/~paltherr/phd/altherr-phd.pdf

or this page:

www.scala-lang.org/node/6372‎

Jquery href click - how can I fire up an event?

If you own the HTML code then it might be wise to assign an id to this href. Then your code would look like this:

<a id="sign_up" class="sign_new">Sign up</a>

And jQuery:

$(document).ready(function(){
    $('#sign_up').click(function(){
        alert('Sign new href executed.');
    });
});

If you do not own the HTML then you'd need to change $('#sign_up') to $('a.sign_new'). You might also fire event.stopPropagation() if you have a href in anchor and do not want it handled (AFAIR return false might work as well).

$(document).ready(function(){
    $('#sign_up').click(function(event){
        alert('Sign new href executed.');
        event.stopPropagation();
    });
});

Is there an easy way to convert jquery code to javascript?

I just found this quite impressive tutorial about jquery to javascript conversion from Jeffrey Way on Jan 19th 2012 *Copyright © 2014 Envato* :

http://net.tutsplus.com/tutorials/javascript-ajax/from-jquery-to-javascript-a-reference/

Whether we like it or not, more and more developers are being introduced to the world of JavaScript through jQuery first. In many ways, these newcomers are the lucky ones. They have access to a plethora of new JavaScript APIs, which make the process of DOM traversal (something that many folks depend on jQuery for) considerably easier. Unfortunately, they don’t know about these APIs!

In this article, we’ll take a variety of common jQuery tasks, and convert them to both modern and legacy JavaScript.

I proposed it in a comment to OP, and after his suggestion, i publish it has an answer for everyone to refer to.

Also, Jeffrey Way mentioned about his inspiration witch seems to be a good primer for understanding : http://sharedfil.es/js-48hIfQE4XK.html

Has a teaser, this document comparison of jQuery to javascript :

$(document).ready(function() {
  // code…
});

document.addEventListener("DOMContentLoaded", function() {
  // code…
});

$("a").click(function() {
  // code…
})

[].forEach.call(document.querySelectorAll("a"), function(el) {
  el.addEventListener("click", function() {
    // code…
  });
});

You should take a look.

'IF' in 'SELECT' statement - choose output value based on column values

Use a case statement:

select id,
    case report.type
        when 'P' then amount
        when 'N' then -amount
    end as amount
from
    `report`

Visual Studio Code: format is not using indent settings

Most likely you have some formatting extension installed, e.g. JS-CSS-HTML Formatter.

If it is the case, then just open Command Palette, type "Formatter" and select Formatter Config. Then edit the value of "indent_size" as you like.

P.S. Don't forget to restart Visual Studio Code after editing :)

scp via java

I looked at a lot of these solutions and didn't like many of them. Mostly because the annoying step of having to identify your known hosts. That and JSCH is at a ridiculously low level relative to the scp command.

I found a library that doesn't require this but it's bundled up and used as a command line tool. https://code.google.com/p/scp-java-client/

I looked through the source code and discovered how to use it without the command line. Here's an example of uploading:

    uk.co.marcoratto.scp.SCP scp = new uk.co.marcoratto.scp.SCP(new uk.co.marcoratto.scp.listeners.SCPListenerPrintStream());
    scp.setUsername("root");
    scp.setPassword("blah");
    scp.setTrust(true);
    scp.setFromUri(file.getAbsolutePath());
    scp.setToUri("root@host:/path/on/remote");
    scp.execute();

The biggest downside is that it's not in a maven repo (that I could find). But, the ease of use is worth it to me.

Get unique values from arraylist in java

ArrayList values = ... // your values
Set uniqueValues = new HashSet(values); //now unique

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

The reason is your current ruby environment, you got a different version of bundler with the version in Gemfile.lock.

  • Safe way, install bundler with the same version in Gemfile.lock, this won't break anything if there is some incampatibly thing happened.
  • Hard way, just remove Gemfile.lock, and run bundle install.

How to get all possible combinations of a list’s elements?

Here's a lazy one-liner, also using itertools:

from itertools import compress, product

def combinations(items):
    return ( set(compress(items,mask)) for mask in product(*[[0,1]]*len(items)) )
    # alternative:                      ...in product([0,1], repeat=len(items)) )

Main idea behind this answer: there are 2^N combinations -- same as the number of binary strings of length N. For each binary string, you pick all elements corresponding to a "1".

items=abc * mask=###
 |
 V
000 -> 
001 ->   c
010 ->  b
011 ->  bc
100 -> a
101 -> a c
110 -> ab
111 -> abc

Things to consider:

  • This requires that you can call len(...) on items (workaround: if items is something like an iterable like a generator, turn it into a list first with items=list(_itemsArg))
  • This requires that the order of iteration on items is not random (workaround: don't be insane)
  • This requires that the items are unique, or else {2,2,1} and {2,1,1} will both collapse to {2,1} (workaround: use collections.Counter as a drop-in replacement for set; it's basically a multiset... though you may need to later use tuple(sorted(Counter(...).elements())) if you need it to be hashable)

Demo

>>> list(combinations(range(4)))
[set(), {3}, {2}, {2, 3}, {1}, {1, 3}, {1, 2}, {1, 2, 3}, {0}, {0, 3}, {0, 2}, {0, 2, 3}, {0, 1}, {0, 1, 3}, {0, 1, 2}, {0, 1, 2, 3}]

>>> list(combinations('abcd'))
[set(), {'d'}, {'c'}, {'c', 'd'}, {'b'}, {'b', 'd'}, {'c', 'b'}, {'c', 'b', 'd'}, {'a'}, {'a', 'd'}, {'a', 'c'}, {'a', 'c', 'd'}, {'a', 'b'}, {'a', 'b', 'd'}, {'a', 'c', 'b'}, {'a', 'c', 'b', 'd'}]

Oracle: How to find out if there is a transaction pending?

The easiest and most reliable solution is to try and start a transaction and see it if succeeds. If some code already started a transaction but has not yet issued any DML, then the V$TRANSACTION view won't show anything.

In this example below, I handle the exception to raise a user-defined application error. To defer to an existing exception handler, just do a SET TRANSACTION and then immediately COMMIT to undo it.

DECLARE
    transaction_in_progress EXCEPTION;
    PRAGMA EXCEPTION_INIT(transaction_in_progress, -1453);
BEGIN
    SET TRANSACTION NAME 'CHECK_FOR_TRANSACTION_ALREADY_SET';
    COMMIT; -- end transaction
EXCEPTION
    WHEN transaction_in_progress THEN
        RAISE_APPLICATION_ERROR(-20000,'Transaction is already in progress');
END;
/

What is setContentView(R.layout.main)?

Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.

  • Activity is basically a empty window
  • SetContentView is used to fill the window with the UI provided from layout file incase of setContentView(R.layout.somae_file).
  • Here layoutfile is inflated to view and added to the Activity context(Window).

Converting a PDF to PNG

Couldn't get the accepted answer to work. Then found out that actually the solution is much simpler anyway as Ghostscript not just natively supports PNG but even multiple different "encodings":

  • png256
  • png16
  • pnggray
  • pngmono
  • ...

The shell command that works for me is:

gs -dNOPAUSE -q -sDEVICE=pnggray -r500 -dBATCH -dFirstPage=2 -dLastPage=2 -sOutputFile=test.png test.pdf

It will save page 2 of test.pdf to test.png using the pnggray encoding and 500 DPI.

How to convert JSON string into List of Java object?

For any one who looks for answer yet:

1.Add jackson-databind library to your build tools like Gradle or Maven

2.in your Code:

ObjectMapper mapper = new ObjectMapper();

List<Student> studentList = new ArrayList<>();

studentList = Arrays.asList(mapper.readValue(jsonStringArray, Student[].class));

Get file name from URL

If you don't need to get rid of the file extension, here's a way to do it without resorting to error-prone String manipulation and without using external libraries. Works with Java 1.7+:

import java.net.URI
import java.nio.file.Paths

String url = "http://example.org/file?p=foo&q=bar"
String filename = Paths.get(new URI(url).getPath()).getFileName().toString()

How to get all properties values of a JavaScript Object (without knowing the keys)?

var objects={...}; this.getAllvalues = function () {
        var vls = [];
        for (var key in objects) {
            vls.push(objects[key]);
        }
        return vls;
    }

AttributeError: 'tuple' object has no attribute

Variables names are only locally meaningful.

Once you hit

return s1,s2,s3,s4

at the end of the method, Python constructs a tuple with the values of s1, s2, s3 and s4 as its four members at index 0, 1, 2 and 3 - NOT a dictionary of variable names to values, NOT an object with variable names and their values, etc.

If you want the variable names to be meaningful after you hit return in the method, you must create an object or dictionary.

Oracle - how to remove white spaces?

SQL Plus will format the columns to hold the maximum possible value, which in this case is 255 characters.

To confirm that your output does not actually contain those extra spaces, try this:

SELECT
  '/' || TRIM(A) || '/' AS COLUMN_A
 ,'/' || TRIM(B) || '/' AS COLUMN_B
FROM
  MY_TABLE;

If the '/' characters are separated from your output, then that indicates that it's not spaces, but some other whitespace character that got in there (tabs, for example). If that is the case, then it is probably an input validation issue somewhere in your application.

However, the most likely scenario is that the '/' characters will in fact touch the rest of your strings, thus proving that the whitespace is actually trimmed.

If you wish to output them together, then the answer given by Quassnoi should do it.

If it is purely a display issue, then the answer given by Tony Andrews should work fine.

JavaScript closures vs. anonymous functions

Let's look at both ways:

(function(){
    var i2 = i;
    setTimeout(function(){
        console.log(i2);
    }, 1000)
})();

Declares and immediately executes an anonymous function that runs setTimeout() within its own context. The current value of i is preserved by making a copy into i2 first; it works because of the immediate execution.

setTimeout((function(i2){
    return function() {
        console.log(i2);
    }
})(i), 1000);

Declares an execution context for the inner function whereby the current value of i is preserved into i2; this approach also uses immediate execution to preserve the value.

Important

It should be mentioned that the run semantics are NOT the same between both approaches; your inner function gets passed to setTimeout() whereas his inner function calls setTimeout() itself.

Wrapping both codes inside another setTimeout() doesn't prove that only the second approach uses closures, there's just not the same thing to begin with.

Conclusion

Both methods use closures, so it comes down to personal taste; the second approach is easier to "move" around or generalize.

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:

cursor.execute('INSERT INTO images VALUES(?)', (img,))

Without the comma, (img) is just a grouped expression, not a tuple, and thus the img string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.

>>> len(img)
74
>>> len((img,))
1

If you find it easier to read, you can also use a list literal:

cursor.execute('INSERT INTO images VALUES(?)', [img])

How do I put an already-running process under nohup?

Node's answer is really great, but it left open the question how can get stdout and stderr redirected. I found a solution on Unix & Linux, but it is also not complete. I would like to merge these two solutions. Here it is:

For my test I made a small bash script called loop.sh, which prints the pid of itself with a minute sleep in an infinite loop.

$./loop.sh

Now get the PID of this process somehow. Usually ps -C loop.sh is good enough, but it is printed in my case.

Now we can switch to another terminal (or press ^Z and in the same terminal). Now gdb should be attached to this process.

$ gdb -p <PID>

This stops the script (if running). Its state can be checked by ps -f <PID>, where the STAT field is 'T+' (or in case of ^Z 'T'), which means (man ps(1))

    T Stopped, either by a job control signal or because it is being traced
    + is in the foreground process group

(gdb) call close(1)
$1 = 0

Close(1) returns zero on success.

(gdb) call open("loop.out", 01102, 0600)
$6 = 1

Open(1) returns the new file descriptor if successful.

This open is equal with open(path, O_TRUNC|O_CREAT|O_RDWR, S_IRUSR|S_IWUSR). Instead of O_RDWR O_WRONLY could be applied, but /usr/sbin/lsof says 'u' for all std* file handlers (FD column), which is O_RDWR.

I checked the values in /usr/include/bits/fcntl.h header file.

The output file could be opened with O_APPEND, as nohup would do, but this is not suggested by man open(2), because of possible NFS problems.

If we get -1 as a return value, then call perror("") prints the error message. If we need the errno, use p errno gdb comand.

Now we can check the newly redirected file. /usr/sbin/lsof -p <PID> prints:

loop.sh <PID> truey    1u   REG   0,26        0 15008411 /home/truey/loop.out

If we want, we can redirect stderr to another file, if we want to using call close(2) and call open(...) again using a different file name.

Now the attached bash has to be released and we can quit gdb:

(gdb) detach
Detaching from program: /bin/bash, process <PID>
(gdb) q

If the script was stopped by gdb from an other terminal it continues to run. We can switch back to loop.sh's terminal. Now it does not write anything to the screen, but running and writing into the file. We have to put it into the background. So press ^Z.

^Z
[1]+  Stopped                 ./loop.sh

(Now we are in the same state as if ^Z was pressed at the beginning.)

Now we can check the state of the job:

$ ps -f 24522
UID        PID  PPID  C STIME TTY      STAT   TIME CMD
<UID>    <PID><PPID>  0 11:16 pts/36   S      0:00 /bin/bash ./loop.sh
$ jobs
[1]+  Stopped                 ./loop.sh

So process should be running in the background and detached from the terminal. The number in the jobs command's output in square brackets identifies the job inside bash. We can use in the following built in bash commands applying a '%' sign before the job number :

$ bg %1
[1]+ ./loop.sh &
$ disown -h %1
$ ps -f <PID>
UID        PID  PPID  C STIME TTY      STAT   TIME CMD
<UID>    <PID><PPID>  0 11:16 pts/36   S      0:00 /bin/bash ./loop.sh

And now we can quit from the calling bash. The process continues running in the background. If we quit its PPID become 1 (init(1) process) and the control terminal become unknown.

$ ps -f <PID>
UID        PID  PPID  C STIME TTY      STAT   TIME CMD
<UID>    <PID>     1  0 11:16 ?        S      0:00 /bin/bash ./loop.sh
$ /usr/bin/lsof -p <PID>
...
loop.sh <PID> truey    0u   CHR 136,36                38 /dev/pts/36 (deleted)
loop.sh <PID> truey    1u   REG   0,26     1127 15008411 /home/truey/loop.out
loop.sh <PID> truey    2u   CHR 136,36                38 /dev/pts/36 (deleted)

COMMENT

The gdb stuff can be automatized creating a file (e.g. loop.gdb) containing the commands and run gdb -q -x loop.gdb -p <PID>. My loop.gdb looks like this:

call close(1)
call open("loop.out", 01102, 0600)
# call close(2)
# call open("loop.err", 01102, 0600)
detach
quit

Or one can use the following one liner instead:

gdb -q -ex 'call close(1)' -ex 'call open("loop.out", 01102, 0600)' -ex detach -ex quit -p <PID>

I hope this is a fairly complete description of the solution.

VBA check if file exists

something like this

best to use a workbook variable to provide further control (if needed) of the opened workbook

updated to test that file name was an actual workbook - which also makes the initial check redundant, other than to message the user than the Textbox is blank

Dim strFile As String
Dim WB As Workbook
strFile = Trim(TextBox1.Value)
Dim DirFile As String
If Len(strFile) = 0 Then Exit Sub

DirFile = "C:\Documents and Settings\Administrator\Desktop\" & strFile
If Len(Dir(DirFile)) = 0 Then
  MsgBox "File does not exist"
Else
 On Error Resume Next
 Set WB = Workbooks.Open(DirFile)
 On Error GoTo 0
 If WB Is Nothing Then MsgBox DirFile & " is invalid", vbCritical
End If

How to retrieve field names from temporary table (SQL Server 2008)

you can do it by following way too ..

create table #test (a int, b char(1))

select * From #test

exec tempdb..sp_columns '#test'

How to copy part of an array to another array in C#?

See this question. LINQ Take() and Skip() are the most popular answers, as well as Array.CopyTo().

A purportedly faster extension method is described here.

DB query builder toArray() laravel 4

Easiest way is using laravel toArray function itself:

    $result = array_map(function ($value) {
        return $value instanceof Arrayable ? $value->toArray() : $value;
    }, $result);

Using PUT method in HTML form

According to the HTML standard, you can not. The only valid values for the method attribute are get and post, corresponding to the GET and POST HTTP methods. <form method="put"> is invalid HTML and will be treated like <form>, i.e. send a GET request.

Instead, many frameworks simply use a POST parameter to tunnel the HTTP method:

<form method="post" ...>
  <input type="hidden" name="_method" value="put" />
...

Of course, this requires server-side unwrapping.

Encrypt and decrypt a password in Java

You can use java.security.MessageDigest with SHA as your algorithm choice.

For reference,

Try available example here

How can I create a link to a local file on a locally-run web page?

back to 2017:

use URL.createObjectURL( file ) to create local link to file system that user select;

don't forgot to free memory by using URL.revokeObjectURL()

How do I use Bash on Windows from the Visual Studio Code integrated terminal?

For me this is the only combination worked!

"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\git-cmd.exe",
"terminal.integrated.shellArgs.windows": [
  "--command=usr/bin/bash.exe",
  "-l",
  "-i"
]

With git-bash.exe as the ...shell.windows, every time the bash was opening outside VS!!

Thank God it worked finally!! Else, I was planning to wipe out VS completely and reinstall it (making me to reinstall all my extensions and redo my customizations!)

How to listen state changes in react.js?

I haven't used Angular, but reading the link above, it seems that you're trying to code for something that you don't need to handle. You make changes to state in your React component hierarchy (via this.setState()) and React will cause your component to be re-rendered (effectively 'listening' for changes). If you want to 'listen' from another component in your hierarchy then you have two options:

  1. Pass handlers down (via props) from a common parent and have them update the parent's state, causing the hierarchy below the parent to be re-rendered.
  2. Alternatively, to avoid an explosion of handlers cascading down the hierarchy, you should look at the flux pattern, which moves your state into data stores and allows components to watch them for changes. The Fluxxor plugin is very useful for managing this.

Adding calculated column(s) to a dataframe in pandas

For the second part of your question, you can also use shift, for example:

df['t-1'] = df['t'].shift(1)

t-1 would then contain the values from t one row above.

http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html

In Java, what does NaN mean?

NaN = Not a Number.

Excel - programm cells to change colour based on another cell

  1. Select cell B3 and click the Conditional Formatting button in the ribbon and choose "New Rule".
  2. Select "Use a formula to determine which cells to format"
  3. Enter the formula: =IF(B2="X",IF(B3="Y", TRUE, FALSE),FALSE), and choose to fill green when this is true
  4. Create another rule and enter the formula =IF(B2="X",IF(B3="W", TRUE, FALSE),FALSE) and choose to fill red when this is true.

More details - conditional formatting with a formula applies the format when the formula evaluates to TRUE. You can use a compound IF formula to return true or false based on the values of any cells.

Checking for empty or null JToken in a JObject

You can proceed as follows to check whether a JToken Value is null

JToken token = jObject["key"];

if(token.Type == JTokenType.Null)
{
    // Do your logic
}

href="javascript:" vs. href="javascript:void(0)"

Using 'javascript:void 0' will do cause problem in IE

when you click the link, it will trigger onbeforeunload event of window !

<!doctype html>
<html>
<head>
</head>
<body>
<a href="javascript:void(0);" >Click me!</a>
<script>
window.onbeforeunload = function() {
    alert( 'oops!' );
};
</script>
</body>
</html>

Temporary tables in stored procedures

For short: No


Explanation:

According to the official docs: https://docs.microsoft.com/en-us/sql/t-sql/statements/create-table-transact-sql?view=sql-server-ver15

If a local temporary table is created in a stored procedure or application that can be executed at the same time by several users, the Database Engine must be able to distinguish the tables created by the different users. The Database Engine does this by internally appending a numeric suffix to each local temporary table name. The full name of a temporary table as stored in the sysobjects table in tempdb is made up of the table name specified in the CREATE TABLE statement and the system-generated numeric suffix. To allow for the suffix, table_name specified for a local temporary name cannot exceed 116 characters.

Histogram Matplotlib

This might be useful for someone.

Numpy's histogram function returns the edges of each bin, rather than the value of the bin. This makes sense for floating-point numbers, which can lie within an interval, but may not be the desired result when dealing with discrete values or integers (0, 1, 2, etc). In particular, the length of bins returned from np.histogram is not equal to the length of the counts / density.

To get around this, I used np.digitize to quantize the input, and count the fraction of counts for each bin. You could easily edit to get the integer number of counts.

def compute_PMF(data):
    import numpy as np
    from collections import Counter
    _, bins = np.histogram(data, bins='auto', range=(data.min(), data.max()), density=False)
    h = Counter(np.digitize(data,bins) - 1)
    weights = np.asarray(list(h.values())) 
    weights = weights / weights.sum()
    values = np.asarray(list(h.keys()))
    return weights, values
####

Refs:

[1] https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html

[2] https://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html

Programmatically Install Certificate into Mozilla

I had a similar issue on a client site where the client required a authority certificate to be installed automatically for 2000+ windows users.

I created the following .vbs script to import the certificate into the current logged on users firefox cert store.

The script needs to be put in the directory containing a working copy of certutil.exe (the nss version) but programatically determines the firefox profiles location.

Option Explicit

On error resume next

Const DEBUGGING              = true
const SCRIPT_VERSION        = 0.1
Const EVENTLOG_WARNING      = 2
Const CERTUTIL_EXCUTABLE    = "certutil.exe"
Const ForReading = 1


Dim strCertDirPath, strCertutil, files, slashPosition, dotPosition, strCmd, message
Dim file, filename, filePath, fileExtension

Dim WshShell            : Set WshShell            = WScript.CreateObject("WScript.Shell")
Dim objFilesystem      : Set objFilesystem    = CreateObject("Scripting.FileSystemObject") 
Dim certificates        : Set certificates      = CreateObject("Scripting.Dictionary")
Dim objCertDir
Dim UserFirefoxDBDir
Dim UserFirefoxDir
Dim vAPPDATA
Dim objINIFile
Dim strNextLine,Tmppath,intLineFinder, NickName

vAPPDATA = WshShell.ExpandEnvironmentStrings("%APPDATA%") 
strCertDirPath    = WshShell.CurrentDirectory
strCertutil      = strCertDirPath & "\" & CERTUTIL_EXCUTABLE
UserFirefoxDir = vAPPDATA & "\Mozilla\Firefox"
NickName = "Websense Proxy Cert"


Set objINIFile = objFilesystem.OpenTextFile( UserFireFoxDir & "\profiles.ini", ForReading)

Do Until objINIFile.AtEndOfStream
    strNextLine = objINIFile.Readline

    intLineFinder = InStr(strNextLine, "Path=")
    If intLineFinder <> 0 Then
        Tmppath = Split(strNextLine,"=")
        UserFirefoxDBDir = UserFirefoxDir & "\" & replace(Tmppath(1),"/","\")

    End If  
Loop
objINIFile.Close

'output UserFirefoxDBDir

If objFilesystem.FolderExists(strCertDirPath) And objFilesystem.FileExists(strCertutil) Then
    Set objCertDir = objFilesystem.GetFolder(strCertDirPath)
    Set files = objCertDir.Files

    For each file in files
        slashPosition = InStrRev(file, "\")
        dotPosition  = InStrRev(file, ".")
        fileExtension = Mid(file, dotPosition + 1)
        filename      = Mid(file, slashPosition + 1, dotPosition - slashPosition - 1)

        If LCase(fileExtension) = "cer" Then        
            strCmd = chr(34) & strCertutil & chr(34) &" -A -a -n " & chr(34) & NickName & chr(34) & " -i " & chr(34) & file & chr(34) & " -t " & chr(34) & "TCu,TCu,TCu" & chr(34) & " -d " & chr(34) & UserFirefoxDBDir & chr(34)
            'output(strCmd)
            WshShell.Exec(strCmd)
        End If        
    Next        
    WshShell.LogEvent EVENTLOG_WARNING, "Script: " & WScript.ScriptFullName & " - version:" & SCRIPT_VERSION & vbCrLf & vbCrLf & message
End If

function output(message)
    If DEBUGGING Then
        Wscript.echo message
    End if
End function

Set WshShell  = Nothing
Set objFilesystem = Nothing

How to split a string of space separated numbers into integers?

Here is my answer for python 3.

some_string = "2 3 8 61 "

list(map(int, some_string.strip().split()))

Get Character value from KeyCode in JavaScript... then trim

I recently wrote a module called keysight that translates keypress, keydown, and keyup events into characters and keys respectively.

Example:

 element.addEventListener("keydown", function(event) {
    var character = keysight(event).char
 })

List of Python format characters

In docs.python.org Topic = 5.6.2. String Formatting Operations http://docs.python.org/library/stdtypes.html#string-formatting then further down to the chart (text above chart is "The conversion types are:")

The chart lists 16 types and some following notes.

My comment: help does not include attitude which is a bonus. The attitude post enabled me to search further and find the info.

The following classes could not be instantiated: - android.support.v7.widget.Toolbar

I had the same error on my Android Studio screen when i wanted to prevew my project. I fix the problem by this ways:

1- I chang the version from 22 to 21. But if I change back to version 22, the rendering breaks, if I switch back to 21, it works again. Thank you @Overloaded_Operator

I updated my Android Studio but not working. Thank you @Salvuccio96

Oracle 10g: Extract data (select) from XML (CLOB Type)

You can achieve with below queries

  1. select extract(xmltype(xml), '//fax/text()').getStringVal() from mytab;

  2. select extractvalue(xmltype(xml), '//fax') from mytab;

What is a JavaBean exactly?

As per the Wikipedia:

  1. The class must have a public default constructor (with no arguments). This allows easy instantiation within editing and activation frameworks.

  2. The class properties must be accessible using get, set, is (can be used for boolean properties instead of get), and other methods (so-called accessor methods and mutator methods) according to a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties. Setters can have one or more than one argument.

  3. The class should be serializable. (This allows applications and frameworks to reliably save, store, and restore the bean's state in a manner independent of the VM and of the platform.)

For more information follow this link.

SQL Inner join 2 tables with multiple column conditions and update

UPDATE
    T1
SET
    T1.Inci = T2.Inci 
FROM
    T1
INNER JOIN
    T2
ON
    T1.Brands = T2.Brands
AND
    T1.Category= T2.Category
AND
    T1.Date = T2.Date

<code> vs <pre> vs <samp> for inline and block code snippets

Consider Prism.js: https://prismjs.com/#examples

It makes <pre><code> work and is attractive.

How to get access to job parameters from ItemReader, in Spring Batch?

To be able to use the jobParameters I think you need to define your reader as scope 'step', but I am not sure if you can do it using annotations.

Using xml-config it would go like this:

<bean id="foo-readers" scope="step"
  class="...MyReader">
  <property name="fileName" value="#{jobExecutionContext['fileName']}" />
</bean>

See further at the Spring Batch documentation.

Perhaps it works by using @Scope and defining the step scope in your xml-config:

<bean class="org.springframework.batch.core.scope.StepScope" />

SQL query with avg and group by

As I understand, you want the average value for each id at each pass. The solution is

SELECT id, pass, avg(value) FROM data_r1
GROUP BY id, pass;

Google Chrome default opening position and size

You should just grab the window by the title bar and snap it to the left side of your screen (close browser) then reopen the browser ans snap it to the top... problem is over.

GIT_DISCOVERY_ACROSS_FILESYSTEM not set

ran across this page and several like it all talking about the GIT_DISCOVERY_ACROSS_FILESYSTEM not set message. In my case our sys admin had decided that the apache2 directory needed to be on a mounted filesystem in case the disk for the server stopped working and had to get rebuilt. I found this with a simple df command:

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:48:43)--> df -h
Filesystem                           Size  Used Avail Use% Mounted on
<snip>
/dev/mapper/vgraid-lvapache           63G   54M   60G   1% /etc/apache2
<snip>

To fix this I just put the following in the root user's shell (as they are the only ones who need to be looking at etckeeper revisions:

export GIT_DISCOVERY_ACROSS_FILESYSTEM=1

and all was well and good...much joy.

More notes:

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:48:54)--> export GIT_DISCOVERY_ACROSS_FILESYSTEM=0

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:57:35)--> git status
On branch master
nothing to commit, working tree clean

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:57:40)--> touch apache2/me

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:57:45)--> git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    apache2/me

nothing added to commit but untracked files present (use "git add" to track)

-->  UBIk  <--:root@ns1:[/etc]
--PRODUCTION--(16:57:47)--> cd apache2

-->  UBIk  <--:root@ns1:[/etc/apache2]
--PRODUCTION--(16:57:50)--> git status
fatal: Not a git repository (or any parent up to mount point /etc/apache2)
Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set).
-->  UBIk  <--:root@ns1:[/etc/apache2]
--PRODUCTION--(16:57:52)--> export GIT_DISCOVERY_ACROSS_FILESYSTEM=1

-->  UBIk  <--:root@ns1:[/etc/apache2]
--PRODUCTION--(16:58:59)--> git status
On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    me

nothing added to commit but untracked files present (use "git add" to track)

Hopefully that will help someone out somewhere... -wc

How to install Jdk in centos

Try the following to see if you have the proper repository installed:

# yum search java | grep 'java-'

This is going to return a list of available packages that have java in the title. Specifically we are interested in the java- anything, as the jdk will typically be in 'java-version#' type format... Anyhow, if you have to install a repo look at Dag Wieers repo:

http://dag.wieers.com/rpm/FAQ.php#B

After you've got it installed try yum search again... This time you'll have a bunch of java stuff.

# yum search java | grep 'java-'

This will return the list of the available java packages. You can install one like this:

# yum install java-1.7.0-openjdk.x86_64

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

I had missed another tiny detail: I forgot the brackets "(100)" behind NVARCHAR.

Align an element to bottom with flexbox

You can use auto margins

Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

So you can use one of these (or both):

p { margin-bottom: auto; } /* Push following elements to the bottom */
a { margin-top: auto; } /* Push it and following elements to the bottom */

_x000D_
_x000D_
.content {_x000D_
  height: 200px;_x000D_
  border: 1px solid;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
h1, h2 {_x000D_
  margin: 0;_x000D_
}_x000D_
a {_x000D_
  margin-top: auto;_x000D_
}
_x000D_
<div class="content">_x000D_
  <h1>heading 1</h1>_x000D_
  <h2>heading 2</h2>_x000D_
  <p>Some text more or less</p>_x000D_
  <a href="/" class="button">Click me</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Alternatively, you can make the element before the a grow to fill the available space:

p { flex-grow: 1; } /* Grow to fill available space */

_x000D_
_x000D_
.content {_x000D_
  height: 200px;_x000D_
  border: 1px solid;_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
h1, h2 {_x000D_
  margin: 0;_x000D_
}_x000D_
p {_x000D_
  flex-grow: 1;_x000D_
}
_x000D_
<div class="content">_x000D_
  <h1>heading 1</h1>_x000D_
  <h2>heading 2</h2>_x000D_
  <p>Some text more or less</p>_x000D_
  <a href="/" class="button">Click me</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to convert a byte array to a hex string in Java?

Adding a utility jar for simple function is not good option. Instead assemble your own utility classes. following is possible faster implementation.

public class ByteHex {

    public static int hexToByte(char ch) {
        if ('0' <= ch && ch <= '9') return ch - '0';
        if ('A' <= ch && ch <= 'F') return ch - 'A' + 10;
        if ('a' <= ch && ch <= 'f') return ch - 'a' + 10;
        return -1;
    }

    private static final String[] byteToHexTable = new String[]
    {
        "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F",
        "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F",
        "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F",
        "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F",
        "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F",
        "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F",
        "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F",
        "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F",
        "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F",
        "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F",
        "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF",
        "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF",
        "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF",
        "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF",
        "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF",
        "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF"
    };

    private static final String[] byteToHexTableLowerCase = new String[]
    {
        "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f",
        "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f",
        "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f",
        "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f",
        "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f",
        "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f",
        "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f",
        "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f",
        "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f",
        "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f",
        "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af",
        "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf",
        "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf",
        "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df",
        "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "ec", "ed", "ee", "ef",
        "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"
    };

    public static String byteToHex(byte b){
        return byteToHexTable[b & 0xFF];
    }

    public static String byteToHex(byte[] bytes){
        if(bytes == null) return null;
        StringBuilder sb = new StringBuilder(bytes.length*2);
        for(byte b : bytes) sb.append(byteToHexTable[b & 0xFF]);
        return sb.toString();
    }

    public static String byteToHex(short[] bytes){
        StringBuilder sb = new StringBuilder(bytes.length*2);
        for(short b : bytes) sb.append(byteToHexTable[((byte)b) & 0xFF]);
        return sb.toString();
    }

    public static String byteToHexLowerCase(byte[] bytes){
        StringBuilder sb = new StringBuilder(bytes.length*2);
        for(byte b : bytes) sb.append(byteToHexTableLowerCase[b & 0xFF]);
        return sb.toString();
    }

    public static byte[] hexToByte(String hexString) {
        if(hexString == null) return null;
        byte[] byteArray = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i += 2) {
            byteArray[i / 2] = (byte) (hexToByte(hexString.charAt(i)) * 16 + hexToByte(hexString.charAt(i+1)));
        }
        return byteArray;
    }

    public static byte hexPairToByte(char ch1, char ch2) {
        return (byte) (hexToByte(ch1) * 16 + hexToByte(ch2));
    }


}

Angular JS Uncaught Error: [$injector:modulerr]

I had the same problem. You should type your Angular js code outside of any function like this:

$( document ).ready(function() {});

Call one constructor from another

I am improving upon supercat's answer. I guess the following can also be done:

class Sample
{
    private readonly int _intField;
    public int IntProperty
    {
        get { return _intField; }
    }

    void setupStuff(ref int intField, int newValue)
    {
        //Do some stuff here based upon the necessary initialized variables.
        intField = newValue;
    }

    public Sample(string theIntAsString, bool? doStuff = true)
    {
        //Initialization of some necessary variables.
        //==========================================
        int i = int.Parse(theIntAsString);
        // ................
        // .......................
        //==========================================

        if (!doStuff.HasValue || doStuff.Value == true)
           setupStuff(ref _intField,i);
    }

    public Sample(int theInt): this(theInt, false) //"false" param to avoid setupStuff() being called two times
    {
        setupStuff(ref _intField, theInt);
    }
}

mysql - move rows from one table to another

BEGIN;
INSERT INTO persons_table select * from customer_table where person_name = 'tom';
DELETE FROM customer_table where person_name = 'tom';
COMMIT;

What is the Maximum Size that an Array can hold?

This answer is about .NET 4.5

According to MSDN, the index for array of bytes cannot be greater than 2147483591. For .NET prior to 4.5 it also was a memory limit for an array. In .NET 4.5 this maximum is the same, but for other types it can be up to 2146435071.

This is the code for illustration:

    static void Main(string[] args)
    {
        // -----------------------------------------------
        // Pre .NET 4.5 or gcAllowVeryLargeObjects unset
        const int twoGig = 2147483591; // magic number from .NET

        var type = typeof(int);          // type to use
        var size = Marshal.SizeOf(type); // type size
        var num = twoGig / size;         // max element count

        var arr20 = Array.CreateInstance(type, num);
        var arr21 = new byte[num];

        // -----------------------------------------------
        // .NET 4.5 with x64 and gcAllowVeryLargeObjects set
        var arr451 = new byte[2147483591];
        var arr452 = Array.CreateInstance(typeof(int), 2146435071);
        var arr453 = new byte[2146435071]; // another magic number

        return;
    }

what is numeric(18, 0) in sql server 2008 r2

The first value is the precision and the second is the scale, so 18,0 is essentially 18 digits with 0 digits after the decimal place. If you had 18,2 for example, you would have 18 digits, two of which would come after the decimal...

example of 18,2: 1234567890123456.12

There is no functional difference between numeric and decimal, other that the name and I think I recall that numeric came first, as in an earlier version.

And to answer, "can I add (-10) in that column?" - Yes, you can.

Load CSV data into MySQL in Python

The above answer seems good. But another way of doing this is adding the auto commit option along with the db connect. This automatically commits every other operations performed in the db, avoiding the use of mentioning sql.commit() every time.

 mydb = MySQLdb.connect(host='localhost',
        user='root',
        passwd='',
        db='mydb',autocommit=true)