Programs & Examples On #Jrails auto complete

Resize svg when window is resized in d3.js

UPDATE just use the new way from @cminatti


old answer for historic purposes

IMO it's better to use select() and on() since that way you can have multiple resize event handlers... just don't get too crazy

d3.select(window).on('resize', resize); 

function resize() {
    // update width
    width = parseInt(d3.select('#chart').style('width'), 10);
    width = width - margin.left - margin.right;

    // resize the chart
    x.range([0, width]);
    d3.select(chart.node().parentNode)
        .style('height', (y.rangeExtent()[1] + margin.top + margin.bottom) + 'px')
        .style('width', (width + margin.left + margin.right) + 'px');

    chart.selectAll('rect.background')
        .attr('width', width);

    chart.selectAll('rect.percent')
        .attr('width', function(d) { return x(d.percent); });

    // update median ticks
    var median = d3.median(chart.selectAll('.bar').data(), 
        function(d) { return d.percent; });

    chart.selectAll('line.median')
        .attr('x1', x(median))
        .attr('x2', x(median));


    // update axes
    chart.select('.x.axis.top').call(xAxis.orient('top'));
    chart.select('.x.axis.bottom').call(xAxis.orient('bottom'));

}

http://eyeseast.github.io/visible-data/2013/08/28/responsive-charts-with-d3/

How do I get today's date in C# in mm/dd/yyyy format?

string today = DateTime.Today.ToString("M/d");

How to make the Facebook Like Box responsive?

NOTE: this answer is obsolete. See the community wiki answer below for an up-to-date solution.


I found this Gist today and it works perfectly: https://gist.github.com/2571173

(Many thanks to https://gist.github.com/smeranda)

/* 
Make the Facebook Like box responsive (fluid width)
https://developers.facebook.com/docs/reference/plugins/like-box/ 
*/

/* 
This element holds injected scripts inside iframes that in 
some cases may stretch layouts. So, we're just hiding it. 
*/

#fb-root {
    display: none;
}

/* To fill the container and nothing else */

.fb_iframe_widget, .fb_iframe_widget span, .fb_iframe_widget span iframe[style] {
    width: 100% !important;
}

How to Force New Google Spreadsheets to refresh and recalculate?

What worked for me is inserting a column before the first column and deleting it immediately. Basically, do a change that will affect all the cells in the worksheet that will trigger recalculation.

How to "crop" a rectangular image into a square with CSS?

Use CSS: overflow:

.thumb {
   width:230px;
   height:230px;
   overflow:hidden
}

How to repeat a char using printf?

Short answer - yes, long answer: not how you want it.

You can use the %* form of printf, which accepts a variable width. And, if you use '0' as your value to print, combined with the right-aligned text that's zero padded on the left..

printf("%0*d\n", 20, 0);

produces:

00000000000000000000

With my tongue firmly planted in my cheek, I offer up this little horror-show snippet of code.

Some times you just gotta do things badly to remember why you try so hard the rest of the time.

#include <stdio.h>

int width = 20;
char buf[4096];

void subst(char *s, char from, char to) {
    while (*s == from)
    *s++ = to;
}

int main() {
    sprintf(buf, "%0*d", width, 0);
    subst(buf, '0', '-');
    printf("%s\n", buf);
    return 0;
}

TensorFlow not found using pip

The correct way to install it would be as mentioned here

$ pip install --upgrade TF_BINARY_URL   # Python 2.7
$ pip3 install --upgrade TF_BINARY_URL  # Python 3.N

Find the correct TF_BINARY_URL for your hardware from the tensor flow official homepage

Ordering issue with date values when creating pivot tables

If you want to use a column with 24/11/15 (for 24th November 2015) in your Pivot that will sort correctly, you can make sure it is properly formatted by doing the following - highlight the column, go to Data – Text to Columns – click Next twice, then select “Date” and use the default of DMY (or select as applicable to your data) and click ok

When you pivot now you should see it sorting properly as we have properly formatted that column to be a date field so Excel can work with it

How to convert a string to character array in c (or) how to extract a single char form string?

In this simple way

char str [10] = "IAmCute";
printf ("%c",str[4]);

How create table only using <div> tag and Css

In building a custom set of layout tags, I found another answer to this problem. Provided here is the custom set of tags and their CSS classes.

HTML

<layout-table>
   <layout-header> 
       <layout-column> 1 a</layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 </layout-column>
       <layout-column> 4 </layout-column>
   </layout-header>

   <layout-row> 
       <layout-column> a </layout-column>
       <layout-column> a 1</layout-column>
       <layout-column> a </layout-column>
       <layout-column> a </layout-column>
   </layout-row>

   <layout-footer> 
       <layout-column> 1 </layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 b</layout-column>
       <layout-column> 4 </layout-column>
   </layout-footer>
</layout-table>

CSS

layout-table
{
    display : table;
    clear : both;
    table-layout : fixed;
    width : 100%;
}

layout-table:unresolved
{
    color : red;
    border: 1px blue solid;
    empty-cells : show;
}

layout-header, layout-footer, layout-row 
{
    display : table-row;
    clear : both;   
    empty-cells : show;
    width : 100%;
}

layout-column 
{ 
    display : table-column;
    float : left;
    width : 25%;
    min-width : 25%;
    empty-cells : show;
    box-sizing: border-box;
    /* border: 1px solid white; */
    padding : 1px 1px 1px 1px;
}

layout-row:nth-child(even)
{ 
    background-color : lightblue;
}

layout-row:hover 
{ background-color: #f5f5f5 }

The key to getting empty cells and cells in general to be the right size, is Box-Sizing and Padding. Border will do the same thing as well, but creates a line in the row. Padding doesn't. And, while I haven't tried it, I think Margin will act the same way as Padding, in forcing and empty cell to be rendered properly.

Alternate background colors for list items

Since you using standard HTML you will need to define separate class for and manual set the rows to the classes.

CSS override rules and specificity

The specificity is calculated based on the amount of id, class and tag selectors in your rule. Id has the highest specificity, then class, then tag. Your first rule is now more specific than the second one, since they both have a class selector, but the first one also has two tag selectors.

To make the second one override the first one, you can make more specific by adding information of it's parents:

table.rule1 tr td.rule2 {
    background-color: #ffff00;
}

Here is a nice article for more information on selector precedence.

Android Studio Google JAR file causing GC overhead limit exceeded error

I forced closed all Java.exe from taskmanger, restarted Android Studio and it worked for me

enter image description here

How to render a PDF file in Android

I have made a hybrid approach from some of the answers given to this and other similar posts:

This solution checks if a PDF reader app is installed and does the following: - If a reader is installed, download the PDF file to the device and start a PDF reader app - If no reader is installed, ask the user if he wants to view the PDF file online through Google Drive

NOTE! This solution uses the Android DownloadManager class, which was introduced in API9 (Android 2.3 or Gingerbread). This means that it doesn't work on Android 2.2 or earlier.

I wrote a blog post about it here, but I've provided the full code below for completeness:

public class PDFTools {
    private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
    private static final String PDF_MIME_TYPE = "application/pdf";
    private static final String HTML_MIME_TYPE = "text/html";

    /**
     * If a PDF reader is installed, download the PDF file and open it in a reader. 
     * Otherwise ask the user if he/she wants to view it in the Google Drive online PDF reader.<br />
     * <br />
     * <b>BEWARE:</b> This method
     * @param context
     * @param pdfUrl
     * @return
     */
    public static void showPDFUrl( final Context context, final String pdfUrl ) {
        if ( isPDFSupported( context ) ) {
            downloadAndOpenPDF(context, pdfUrl);
        } else {
            askToOpenPDFThroughGoogleDrive( context, pdfUrl );
        }
    }

    /**
     * Downloads a PDF with the Android DownloadManager and opens it with an installed PDF reader app.
     * @param context
     * @param pdfUrl
     */
    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
        // Get filename
        final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
        // The place where the downloaded PDF file will be put
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
        if ( tempFile.exists() ) {
            // If we have downloaded the file before, just go ahead and show it.
            openPDF( context, Uri.fromFile( tempFile ) );
            return;
        }

        // Show progress dialog while downloading
        final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );

        // Create the download request
        DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
        r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
        final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
        BroadcastReceiver onComplete = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ( !progress.isShowing() ) {
                    return;
                }
                context.unregisterReceiver( this );

                progress.dismiss();
                long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
                Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

                if ( c.moveToFirst() ) {
                    int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                    if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                        openPDF( context, Uri.fromFile( tempFile ) );
                    }
                }
                c.close();
            }
        };
        context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

        // Enqueue the request
        dm.enqueue( r );
    }

    /**
     * Show a dialog asking the user if he wants to open the PDF through Google Drive
     * @param context
     * @param pdfUrl
     */
    public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
        new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl); 
                }
            })
            .show();
    }

    /**
     * Launches a browser to view the PDF through Google Drive
     * @param context
     * @param pdfUrl
     */
    public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
        context.startActivity( i );
    }
    /**
     * Open a local PDF file with an installed reader
     * @param context
     * @param localUri
     */
    public static final void openPDF(Context context, Uri localUri ) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        i.setDataAndType( localUri, PDF_MIME_TYPE );
        context.startActivity( i );
    }
    /**
     * Checks if any apps are installed that supports reading of PDF files.
     * @param context
     * @return
     */
    public static boolean isPDFSupported( Context context ) {
        Intent i = new Intent( Intent.ACTION_VIEW );
        final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
        i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
        return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
    }

}

JavaFX How to set scene background image

In addition to @Elltz answer, we can use both fill and image for background:

someNode.setBackground(
            new Background(
                    Collections.singletonList(new BackgroundFill(
                            Color.WHITE, 
                            new CornerRadii(500), 
                            new Insets(10))),
                    Collections.singletonList(new BackgroundImage(
                            new Image("image/logo.png", 100, 100, false, true),
                            BackgroundRepeat.NO_REPEAT,
                            BackgroundRepeat.NO_REPEAT,
                            BackgroundPosition.CENTER,
                            BackgroundSize.DEFAULT))));

Use

setBackground(
                new Background(
                        Collections.singletonList(new BackgroundFill(
                                Color.WHITE,
                                new CornerRadii(0),
                                new Insets(0))),
                        Collections.singletonList(new BackgroundImage(
                                new Image("file:clouds.jpg", 100, 100, false, true),
                                BackgroundRepeat.NO_REPEAT,
                                BackgroundRepeat.NO_REPEAT,
                                BackgroundPosition.DEFAULT,
                                new BackgroundSize(1.0, 1.0, true, true, false, false)
                        ))));

(different last argument) to make the image full-window size.

Trim specific character from a string

If you're dealing with longer strings I believe this should outperform most of the other options by reducing the number of allocated strings to either zero or one:

function trim(str, ch) {
    var start = 0, 
        end = str.length;

    while(start < end && str[start] === ch)
        ++start;

    while(end > start && str[end - 1] === ch)
        --end;

    return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}

// Usage:
trim('|hello|world|', '|'); // => 'hello|world'

Or if you want to trim from a set of multiple characters:

function trimAny(str, chars) {
    var start = 0, 
        end = str.length;

    while(start < end && chars.indexOf(str[start]) >= 0)
        ++start;

    while(end > start && chars.indexOf(str[end - 1]) >= 0)
        --end;

    return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}

// Usage:
trimAny('|hello|world   ', [ '|', ' ' ]); // => 'hello|world'
// because '.indexOf' is used, you could also pass a string for the 2nd parameter:
trimAny('|hello| world  ', '| '); // => 'hello|world'

EDIT: For fun, trim words (rather than individual characters)

// Helper function to detect if a string contains another string
//     at a specific position. 
// Equivalent to using `str.indexOf(substr, pos) === pos` but *should* be more efficient on longer strings as it can exit early (needs benchmarks to back this up).
function hasSubstringAt(str, substr, pos) {
    var idx = 0, len = substr.length;

    for (var max = str.length; idx < len; ++idx) {
        if ((pos + idx) >= max || str[pos + idx] != substr[idx])
            break;
    }

    return idx === len;
}

function trimWord(str, word) {
    var start = 0,
        end = str.length,
        len = word.length;

    while (start < end && hasSubstringAt(str, word, start))
        start += word.length;

    while (end > start && hasSubstringAt(str, word, end - len))
        end -= word.length

    return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}

// Usage:
trimWord('blahrealmessageblah', 'blah');

jQuery UI Alert Dialog as a replacement for alert()

Building on eidylon's answer, here's a version that will not show the title bar if TitleMsg is empty:

function jqAlert(outputMsg, titleMsg, onCloseCallback) {
    if (!outputMsg) return;

    var div=$('<div></div>');
    div.html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": function () {
                $(this).dialog("close");
            }
        },
        close: onCloseCallback
    });
    if (!titleMsg) div.siblings('.ui-dialog-titlebar').hide();
}

see jsfiddle

How do you get the "object reference" of an object in java when toString() and hashCode() have been overridden?

Add a unique id to all your instances, i.e.

public interface Idable {
  int id();
}

public class IdGenerator {
  private static int id = 0;
  public static synchronized int generate() { return id++; }
}

public abstract class AbstractSomething implements Idable {
  private int id;
  public AbstractSomething () {
    this.id = IdGenerator.generate();
  }
  public int id() { return id; }
}

Extend from AbstractSomething and query this property. Will be safe inside a single vm (assuming no game playing with classloaders to get around statics).

What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?

As of Spring 3.0, Spring offers support for JSR-330 dependency injection annotations (@Inject, @Named, @Singleton).

There is a separate section in the Spring documentation about them, including comparisons to their Spring equivalents.

Check if a value is in an array or not with Excel VBA

Use Match() function in excel VBA to check whether the value exists in an array.

Sub test()
    Dim x As Long

    vars1 = Array("Abc", "Xyz", "Examples")
    vars2 = Array("Def", "IJK", "MNO")

    If IsNumeric(Application.Match(Range("A1").Value, vars1, 0)) Then
        x = 1
    ElseIf IsNumeric(Application.Match(Range("A1").Value, vars2, 0)) Then
        x = 1
    End If

    MsgBox x
End Sub

Unexpected token < in first line of HTML

I had this problem in an ASP.NET application, specifically a Web Forms.

I was forcing a redirect in Global.asax, but I forgot to check if the request was for resources like css, javascript, etc. I just had to add the following checks:

VB.NET

If Not Response.IsRequestBeingRedirected _
    And Not Request.Url.AbsoluteUri.Contains(".WebResource") _
    And Not Request.Url.AbsoluteUri.Contains(".css") _
    And Not Request.Url.AbsoluteUri.Contains(".js") _
    And Not Request.Url.AbsoluteUri.Contains("images/") _
    And Not Request.Url.AbsoluteUri.Contains("favicon") Then
        Response.Redirect("~/change-password.aspx")
End If

I was forcing logged users which hadn't change their passwords for a long time, to be redirected to the change-password.aspx page. I believe there is a better way to check this, but for now, this worked. Should I find a better solution, I edit my answer.

Compiling php with curl, where is curl installed?

None of these will allow you to compile PHP with cURL enabled.

In order to compile with cURL, you need libcurl header files (.h files). They are usually found in /usr/include/curl. They generally are bundled in a separate development package.

Per example, to install libcurl in Ubuntu:

sudo apt-get install libcurl4-gnutls-dev

Or CentOS:

sudo yum install curl-devel

Then you can just do:

./configure --with-curl # other options...

If you compile cURL manually, you can specify the path to the files without the lib or include suffix. (e.g.: /usr/local if cURL headers are in /usr/local/include/curl).

What is the inclusive range of float and double in Java?

Binary floating-point numbers have interesting precision characteristics, since the value is stored as a binary integer raised to a binary power. When dealing with sub-integer values (that is, values between 0 and 1), negative powers of two "round off" very differently than negative powers of ten.

For example, the number 0.1 can be represented by 1 x 10-1, but there is no combination of base-2 exponent and mantissa that can precisely represent 0.1 -- the closest you get is 0.10000000000000001.

So if you have an application where you are working with values like 0.1 or 0.01 a great deal, but where small (less than 0.000000000000001%) errors cannot be tolerated, then binary floating-point numbers are not for you.

Conversely, if powers of ten are not "special" to your application (powers of ten are important in currency calculations, but not in, say, most applications of physics), then you are actually better off using binary floating-point, since it's usually at least an order of magnitude faster, and it is much more memory efficient.

The article from the Python documentation on floating point issues and limitations does an excellent job of explaining this issue in an easy to understand form. Wikipedia also has a good article on floating point that explains the math behind the representation.

Using $window or $location to Redirect in AngularJS

You have to put:

<html ng-app="urlApp" ng-controller="urlCtrl">

This way the angular function can access into "window" object

Iterate over a Javascript associative array in sorted order

Get the keys in the first for loop, sort it, use the sorted result in the 2nd for loop.

var a = new Array();
a['b'] = 1;
a['z'] = 1;
a['a'] = 1;

var b = [];
for (k in a) b.push(k);
b.sort();
for (var i = 0; i < b.length; ++i) alert(b[i]);

Error message: "'chromedriver' executable needs to be available in the path"

In my case, this error disappears when I have copied chromedriver file to c:\Windows folder. Its because windows directory is in the path which python script check for chromedriver availability.

Load More Posts Ajax Button in WordPress

If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

I as well had the same problem and nearly drove crazy. The solution was pretty unexpected.

My Excel is shipped out by default that I enter formulas in an Excel-Cell as followed:

=COUNTIF(Range; Searchvalue)
=COUNTIF(A1:A10; 7) 'Example

Please note, that parameters are separated with a semicolon;. Now if you paste exactly that string into a formula within VBA, for example like:

Range("C7").FormulaArray = "=COUNTIF(A1:A10; 7)" 'this will not work

You will get this 1004-error with absolutely no explanation. I spent hours to debug this.. All you have to do is replace all semicolon with commas.

Range("C7").FormulaArray = "=COUNTIF(A1:A10, 7)" 'this works

SQL Query To Obtain Value that Occurs more than once

For MySQL:

SELECT lastname AS ln 
    FROM 
    (SELECT lastname, count(*) as Counter 
     FROM `students` 
     GROUP BY `lastname`) AS tbl WHERE Counter > 2

How to install a PHP IDE plugin for Eclipse directly from the Eclipse environment?

Open up eclipse, go to "Help -> Install New Software". Enter:

http://download.eclipse.org/releases/juno

entry from the "Work with" dropdown.

Under the "Web, XML, Java EE and OSGi Enterprise Developmet" category, select "PHP Development Tools (PDT) SDK Feature 3.1.1.201209101312".

How to open Visual Studio Code from the command line on OSX?

You can use the vscode: protocol that Visual Studio Code defines:

open vscode://file/full/path/to/project/or/file

You can also use

/Applications/Visual\ Studio\ Code.app/Contents/Resources/app/bin/code

if you do not fancy modifying your path

Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error?

You could use

var a = document.querySelector('a[data-a="1"]');

instead of

var a = document.querySelector('a[data-a=1]');

What is the difference between null=True and blank=True in Django?

The default values of null and blank are False.

Null: It is database-related. Defines if a given database column will accept null values or not.

Blank: It is validation-related. It will be used during forms validation, when calling form.is_valid().

That being said, it is perfectly fine to have a field with null=True and blank=False. Meaning on the database level the field can be NULL, but in the application level it is a required field.

Now, where most developers get it wrong: Defining null=True for string-based fields such as CharField and TextField. Avoid doing that. Otherwise, you will end up having two possible values for “no data”, that is: None and an empty string. Having two possible values for “no data” is redundant. The Django convention is to use the empty string, not NULL.

Can I specify multiple users for myself in .gitconfig?

GIT_AUTHOR_EMAIL + local .bashrc

.bashrc_local: don't track this file, put it only on your work computer:

export GIT_AUTHOR_EMAIL='[email protected]'
export GIT_COMMITTER_EMAIL="$GIT_AUTHOR_EMAIL"

.bashrc: track this file, make it the same on both work and home computers:

F="$HOME/.bashrc_local"
if [ -r "$F" ]; then
    . "$F"
fi

I'm using https://github.com/technicalpickles/homesick to sync my dotfiles.

If only gitconfig would accept environment variables: Shell variable expansion in git config

Installing Numpy on 64bit Windows 7 with Python 2.7.3

Assuming you have python 2.7 64bit on your computer and have downloaded numpy from here, follow the steps below (changing numpy-1.9.2+mkl-cp27-none-win_amd64.whl as appropriate).

  1. Download (by right click and "save target") get-pip to local drive.

  2. At the command prompt, navigate to the directory containing get-pip.py and run

    python get-pip.py

    which creates files in C:\Python27\Scripts, including pip2, pip2.7 and pip.

  3. Copy the downloaded numpy-1.9.2+mkl-cp27-none-win_amd64.whl into the above directory (C:\Python27\Scripts)

  4. Still at the command prompt, navigate to the above directory and run:

    pip2.7.exe install "numpy-1.9.2+mkl-cp27-none-win_amd64.whl"

How do I disable TextBox using JavaScript?

Form elements can be accessed via the form's DOM element by name, not by "id" value. Give your form elements names if you want to access them like that, or else access them directly by "id" value:

document.getElementById("color").disabled = true;

edit — oh also, as pointed out by others, it's just "text", not "TextBox", for the "type" attribute.

You might want to invest a little time in reading some front-end development tutorials.

Suppress/ print without b' prefix for bytes in Python 3

If the bytes use an appropriate character encoding already; you could print them directly:

sys.stdout.buffer.write(data)

or

nwritten = os.write(sys.stdout.fileno(), data)  # NOTE: it may write less than len(data) bytes

how to convert 2d list to 2d numpy array?

np.array() is even more powerful than what unutbu said above. You also could use it to convert a list of np arrays to a higher dimention array, the following is a simple example:

aArray=np.array([1,1,1])

bArray=np.array([2,2,2])

aList=[aArray, bArray]

xArray=np.array(aList)

xArray's shape is (2,3), it's a standard np array. This operation avoids a loop programming.

Create WordPress Page that redirects to another URL

I'm not familiar with Wordpress templates, but I'm assuming that headers are sent to the browser by WP before your template is even loaded. Because of that, the common redirection method of:

header("Location: new_url");

won't work. Unless there's a way to force sending headers through a template before WP does anything, you'll need to use some Javascript like so:

<script language="javascript" type="text/javascript">
document.location = "new_url";
</script>

Put that in the section and it'll be run when the page loads. This method won't be instant, and it also won't work for people with Javascript disabled.

Listing files in a specific "folder" of a AWS S3 bucket

S3 does not have directories, while you can list files in a pseudo directory manner like you demonstrated, there is no directory "file" per-se.
You may of inadvertently created a data file called users/<user-id>/contacts/<contact-id>/.

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

If you have been given a Session Token also, then you need to manually set it after configure:

aws configure set aws_session_token "<<your session token>>"

Creating temporary files in bash

You might want to look at mktemp

The mktemp utility takes the given filename template and overwrites a portion of it to create a unique filename. The template may be any filename with some number of 'Xs' appended to it, for example /tmp/tfile.XXXXXXXXXX. The trailing 'Xs' are replaced with a combination of the current process number and random letters.

For more details: man mktemp

Is there a decent wait function in C++?

There is a C++11 way of doing it. It is quite simple, and I believe it is portable. Of course, as Lightness Races in Orbit pointed out, you should not do this in order to be able to see an Hello World in your terminal, but there exist some good reason to use a wait function. Without further ado,

#include <chrono> // std::chrono::microseconds
#include <thread> // std::this_thread::sleep_for
std::this_thread::sleep_for(std::chrono::microseconds{});

More details are available here. See also sleep_until.

jquery onclick change css background image

Use your jquery like this

$('.home').css({'background-image':'url(images/tabs3.png)'});

How can I roll back my last delete command in MySQL?

If you haven't made a backup, you are pretty much fudged.

How to generate javadoc comments in Android Studio

Javadoc comments can be automatically appended by using your IDE's autocomplete feature. Try typing /** and hitting Enter to generate a sample Javadoc comment.

 /**
 *
 * @param action          The action to execute.
 * @param args            The exec() arguments.
 * @param callbackContext The callback context used when calling back into JavaScript.
 * @return
 * @throws JSONException
 */

How to grab substring before a specified character jQuery or JavaScript

try this:

streetaddress.substring(0, streetaddress.indexOf(','));

Set an environment variable in git bash

A normal variable is set by simply assigning it a value; note that no whitespace is allowed around the =:

HOME=c

An environment variable is a regular variable that has been marked for export to the environment.

export HOME
HOME=c

You can combine the assignment with the export statement.

export HOME=c

Raise an event whenever a property's value changed?

I use largely the same patterns as Aaronaught, but if you have a lot of properties it could be nice to use a little generic method magic to make your code a little more DRY

public class TheClass : INotifyPropertyChanged {
    private int _property1;
    private string _property2;
    private double _property3;

    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e) {
        PropertyChangedEventHandler handler = PropertyChanged;
        if(handler != null) {
            handler(this, e);
        }
    }

    protected void SetPropertyField<T>(string propertyName, ref T field, T newValue) {
        if(!EqualityComparer<T>.Default.Equals(field, newValue)) {
            field = newValue;
            OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }
    }

    public int Property1 {
        get { return _property1; }
        set { SetPropertyField("Property1", ref _property1, value); }
    }
    public string Property2 {
        get { return _property2; }
        set { SetPropertyField("Property2", ref _property2, value); }
    }
    public double Property3 {
        get { return _property3; }
        set { SetPropertyField("Property3", ref _property3, value); }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

Usually I also make the OnPropertyChanged method virtual to allow sub-classes to override it to catch property changes.

What is the difference between a HashMap and a TreeMap?

Use HashMap most of the times but use TreeMap when you need the key to be sorted (when you need to iterate the keys).

Script to Change Row Color when a cell changes text

//Sets the row color depending on the value in the "Status" column.
function setRowColors() {
  var range = SpreadsheetApp.getActiveSheet().getDataRange();
  var statusColumnOffset = getStatusColumnOffset();

  for (var i = range.getRow(); i < range.getLastRow(); i++) {
    rowRange = range.offset(i, 0, 1);
    status = rowRange.offset(0, statusColumnOffset).getValue();
    if (status == 'Completed') {
      rowRange.setBackgroundColor("#99CC99");
    } else if (status == 'In Progress') {
      rowRange.setBackgroundColor("#FFDD88");    
    } else if (status == 'Not Started') {
      rowRange.setBackgroundColor("#CC6666");          
    }
  }
}

//Returns the offset value of the column titled "Status"
//(eg, if the 7th column is labeled "Status", this function returns 6)
function getStatusColumnOffset() {
  lastColumn = SpreadsheetApp.getActiveSheet().getLastColumn();
  var range = SpreadsheetApp.getActiveSheet().getRange(1,1,1,lastColumn);

  for (var i = 0; i < range.getLastColumn(); i++) {
    if (range.offset(0, i, 1, 1).getValue() == "Status") {
      return i;
    } 
  }
}

Python String and Integer concatenation

for i in range(11):
    string = "string{0}".format(i)

What you did (range[1,10]) is

  • a TypeError since brackets denote an index (a[3]) or a slice (a[3:5]) of a list,
  • a SyntaxError since [1,10] is invalid, and
  • a double off-by-one error since range(1,10) is [1, 2, 3, 4, 5, 6, 7, 8, 9], and you seem to want [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

And string = "string" + i is a TypeError since you can't add an integer to a string (unlike JavaScript).

Look at the documentation for Python's new string formatting method, it is very powerful.

How do you get the currently selected <option> in a <select> via JavaScript?

var payeeCountry = document.getElementById( "payeeCountry" );
alert( payeeCountry.options[ yourSelect.selectedIndex ].value );

Mipmap drawables for icons

When building separate apks for different densities, drawable folders for other densities get stripped. This will make the icons appear blurry in devices that use launcher icons of higher density. Since, mipmap folders do not get stripped, it’s always best to use them for including the launcher icons.

What possibilities can cause "Service Unavailable 503" error?

Your web pages are served by an application pool. If you disable/stop the application pool, and anyone tries to browse the application, you will get a Service Unavailable. It can happen due to multiple reasons...

  1. Your application may have crashed [check the event viewer and see if you can find event logs in your Application/System log]

  2. Your application may be crashing very frequently. If an app pool crashes for 5 times in 5 minutes [check your application pool settings for rapid fail], your application pool is disabled by IIS and you will end up getting this message.

In either case, the issue is that your worker process is failing and you should troubleshoot it from crash perspective.

What is a Crash (technically)... in ASP.NET and what to do if it happens?

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

How do I tell CMake to link in a static library in the source directory?

CMake favours passing the full path to link libraries, so assuming libbingitup.a is in ${CMAKE_SOURCE_DIR}, doing the following should succeed:

add_executable(main main.cpp)
target_link_libraries(main ${CMAKE_SOURCE_DIR}/libbingitup.a)

How to make a HTTP request using Ruby on Rails?

OpenURI is the best; it's as simple as

require 'open-uri'
response = open('http://example.com').read

javascript window.location in new tab

I don't think there's a way to do this, unless you're writing a browser extension. You could try using window.open and hoping that the user has their browser set to open new windows in new tabs.

Streaming video from Android camera to server

I have hosted an open-source project to enable Android phone to IP camera:

http://code.google.com/p/ipcamera-for-android

Raw video data is fetched from LocalSocket, and the MDAT MOOV of MP4 was checked first before streaming. The live video is packed in FLV format, and can be played via Flash video player with a build in web server :)

Controlling execution order of unit tests in Visual Studio

I see that this topic is almost 6 years old, and we now have new version of Visual studio but I will reply anyway. I had that order problem in Visual Studio 19 and I figured it out by adding capital letter (you can also add small letter) in front of your method name and in alphabetical order like this:

[TestMethod]
        public void AName1()
        {}
[TestMethod]
        public void BName2()
        {}

And so on. I know that this doesn't look appealing, but it looks like Visual is sorting your tests in test explorer in alphabetical order, doesn't matter how you write it in your code. Playlist didn't work for me in this case.

Hope that this will help.

adding 30 minutes to datetime php/mysql

Dominc has the right idea, but put the calculation on the other side of the expression.

SELECT * FROM my_table WHERE endTime < DATE_SUB(CONVERT_TZ(NOW(), @@global.time_zone, 'GMT'), INTERVAL 30 MINUTE)

This has the advantage that you're doing the 30 minute calculation once instead of on every row. That also means MySQL can use the index on that column. Both of thse give you a speedup.

std::string to float or double

As to why atof() isn't working in the original question: the fact that it's cast to double makes me suspicious. The code shouldn't compile without #include <stdlib.h>, but if the cast was added to solve a compile warning, then atof() is not correctly declared. If the compiler assumes atof() returns an int, casting it will solve the conversion warning, but it will not cause the return value to be recognized as a double.

#include <stdlib.h>
#include <string>

... 
  std::string num = "0.6";
  double temp = atof(num.c_str());

should work without warnings.

making a paragraph in html contain a text from a file

You can use a simple HTML element <embed src="file.txt"> it loads the external resource and displays it on the screen no js needed

How to set initial size of std::vector?

You need to use the reserve function to set an initial allocated size or do it in the initial constructor.

vector<CustomClass *> content(20000);

or

vector<CustomClass *> content;
...
content.reserve(20000);

When you reserve() elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up push_back() because the memory is already allocated.

How to add a column in TSQL after a specific column?

Even if the question is old, a more accurate answer about Management Studio would be required.

You can create the column manually or with Management Studio. But Management Studio will require to recreate the table and will result in a time out if you have too much data in it already, avoid unless the table is light.

To change the order of the columns you simply need to move them around in Management Studio. This should not require (Exceptions most likely exists) that Management Studio to recreate the table since it most likely change the ordination of the columns in the table definitions.

I've done it this way on numerous occasion with tables that I could not add columns with the GUI because of the data in them. Then moved the columns around with the GUI of Management Studio and simply saved them.

You will go from an assured time out to a few seconds of waiting.

Convert object to JSON in Android

As of Android 3.0 (API Level 11) Android has a more recent and improved JSON Parser.

http://developer.android.com/reference/android/util/JsonReader.html

Reads a JSON (RFC 4627) encoded value as a stream of tokens. This stream includes both literal values (strings, numbers, booleans, and nulls) as well as the begin and end delimiters of objects and arrays. The tokens are traversed in depth-first order, the same order that they appear in the JSON document. Within JSON objects, name/value pairs are represented by a single token.

sqlite3.OperationalError: unable to open database file

In my case, the solution was to use an absolute path, to find an existing file:

import os.path
filepath = os.path.abspath(filepath)
# Leave this out if the file doesn't exist yet
assert os.path.exists(filepath), "The file doesn't exist"
conn = sqlite3.connect(filepath)

I don't know why this fix works: the path only contained ASCII characters and no spaces. Still it made the difference.

For reference: Windows 7, Python 3.6.5 (64-bit).

I was not able to reproduce the issue on another machine (also Windows 7, Python 3.6.4 64-bit), so I have no idea why this fix works.

npm ERR! Error: EPERM: operation not permitted, rename

For me i just closed the Code editor (VS Code) and then run the same command. And that solves the issue for me.

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript.

The CSS:

.carousel .item {-webkit-transition: opacity 3s; -moz-transition: opacity 3s; -ms-transition: opacity 3s; -o-transition: opacity 3s; transition: opacity 3s;}
.carousel .active.left {left:0;opacity:0;z-index:2;}
.carousel .next {left:0;opacity:1;z-index:1;}

I noticed however that the transition end event was firing prematurely with the default interval of 5s and a fade transition of 3s. Bumping the carousel interval to 8s provides a nice effect.

Very smooth.

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

This answer is in three parts, see below for the official release (v3 and v4)

I couldn't even find the col-lg-push-x or pull classes in the original files for RC1 i downloaded, so check your bootstrap.css file. hopefully this is something they will sort out in RC2.

anyways, the col-push-* and pull classes did exist and this will suit your needs. Here is a demo

<div class="row">
    <div class="col-sm-5 col-push-5">
        Content B
    </div>
    <div class="col-sm-5 col-pull-5">
        Content A
    </div>
    <div class="col-sm-2">
        Content C
    </div>
</div>

EDIT: BELOW IS THE ANSWER FOR THE OFFICIAL RELEASE v3.0

Also see This blog post on the subject

  • col-vp-push-x = push the column to the right by x number of columns, starting from where the column would normally render -> position: relative, on a vp or larger view-port.

  • col-vp-pull-x = pull the column to the left by x number of columns, starting from where the column would normally render -> position: relative, on a vp or larger view-port.

    vp = xs, sm, md, or lg

    x = 1 thru 12

I think what messes most people up, is that you need to change the order of the columns in your HTML markup (in the example below, B comes before A), and that it only does the pushing or pulling on view-ports that are greater than or equal to what was specified. i.e. col-sm-push-5 will only push 5 columns on sm view-ports or greater. This is because Bootstrap is a "mobile first" framework, so your HTML should reflect the mobile version of your site. The Pushing and Pulling are then done on the larger screens.

  • (Desktop) Larger view-ports get pushed and pulled.
  • (Mobile) Smaller view-ports render in normal order.

DEMO

<div class="row">
    <div class="col-sm-5 col-sm-push-5">
        Content B
    </div>
    <div class="col-sm-5 col-sm-pull-5">
        Content A
    </div>
    <div class="col-sm-2">
        Content C
    </div>
</div>

View-port >= sm

|A|B|C|

View-port < sm

|B|
|A|
|C|

EDIT: BELOW IS THE ANSWER FOR v4.0

With v4 comes flexbox and other changes to the grid system and the push\pull classes have been removed in favor of using flexbox ordering.

  • Use .order-* classes to control visual order (where * = 1 thru 12)
  • This can also be grid tier specific .order-md-*
  • Also .order-first (-1) and .order-last (13) avalable

_x000D_
_x000D_
<div class="row">_x000D_
  <div class="col order-2">1st yet 2nd</div>_x000D_
  <div class="col order-1">2nd yet 1st</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Force "git push" to overwrite remote files

Simple steps by using tortoisegit

GIT giving local files commit and pushing into git repository.

Steps :

1) stash changes stash name

2) pull

3) stash pop

4) commit 1 or more files and give commit changes description set author and Date

5) push

How to generate random positive and negative numbers in Java

public static int generatRandomPositiveNegitiveValue(int max , int min) {
    //Random rand = new Random();
    int ii = -min + (int) (Math.random() * ((max - (-min)) + 1));
    return ii;
}

Populating a ListView using an ArrayList?

You need to do it through an ArrayAdapter which will adapt your ArrayList (or any other collection) to your items in your layout (ListView, Spinner etc.).

This is what the Android developer guide says:

A ListAdapter that manages a ListView backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

To use something other than TextViews for the array display, for instance ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want.

So your code should look like:

public class YourActivity extends Activity {

    private ListView lv;

    public void onCreate(Bundle saveInstanceState) {
         setContentView(R.layout.your_layout);

         lv = (ListView) findViewById(R.id.your_list_view_id);

         // Instanciating an array list (you don't need to do this, 
         // you already have yours).
         List<String> your_array_list = new ArrayList<String>();
         your_array_list.add("foo");
         your_array_list.add("bar");

         // This is the array adapter, it takes the context of the activity as a 
         // first parameter, the type of list view as a second parameter and your 
         // array as a third parameter.
         ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                 this, 
                 android.R.layout.simple_list_item_1,
                 your_array_list );

         lv.setAdapter(arrayAdapter); 
    }
}

What is JavaScript garbage collection?

To the best of my knowledge, JavaScript's objects are garbage collected periodically when there are no references remaining to the object. It is something that happens automatically, but if you want to see more about how it works, at the C++ level, it makes sense to take a look at the WebKit or V8 source code

Typically you don't need to think about it, however, in older browsers, like IE 5.5 and early versions of IE 6, and perhaps current versions, closures would create circular references that when unchecked would end up eating up memory. In the particular case that I mean about closures, it was when you added a JavaScript reference to a dom object, and an object to a DOM object that referred back to the JavaScript object. Basically it could never be collected, and would eventually cause the OS to become unstable in test apps that looped to create crashes. In practice these leaks are usually small, but to keep your code clean you should delete the JavaScript reference to the DOM object.

Usually it is a good idea to use the delete keyword to immediately de-reference big objects like JSON data that you have received back and done whatever you need to do with it, especially in mobile web development. This causes the next sweep of the GC to remove that object and free its memory.

C++ compiling on Windows and Linux: ifdef switch

It depends on the used compiler.

For example, Windows' definition can be WIN32 or _WIN32.

And Linux' definition can be UNIX or __unix__ or LINUX or __linux__.

Returning data from Axios API

The issue is that the original axiosTest() function isn't returning the promise. Here's an extended explanation for clarity:

function axiosTest() {
    // create a promise for the axios request
    const promise = axios.get(url)

    // using .then, create a new promise which extracts the data
    const dataPromise = promise.then((response) => response.data)

    // return it
    return dataPromise
}

// now we can use that data from the outside!
axiosTest()
    .then(data => {
        response.json({ message: 'Request received!', data })
    })
    .catch(err => console.log(err))

The function can be written more succinctly:

function axiosTest() {
    return axios.get(url).then(response => response.data)
}

Or with async/await:

async function axiosTest() {
    const response = await axios.get(url)
    return response.data
}

How does it work - requestLocationUpdates() + LocationRequest/Listener

I use this one:

LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

For example, using a 1s interval:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);

the time is in milliseconds, the distance is in meters.

This automatically calls:

public void onLocationChanged(Location location) {
    //Code here, location.getAccuracy(), location.getLongitude() etc...
}

I also had these included in the script but didnt actually use them:

public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}

In short:

public class GPSClass implements LocationListener {

    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
    }
}

Python integer division yields float

Oops, immediately found 2//2.

A fast way to delete all rows of a datatable at once

Why dont you just do it in SQL?

DELETE FROM SomeTable

Mockito - difference between doReturn() and when()

The Mockito javadoc seems to tell why use doReturn() instead of when() Use doReturn() in those rare occasions when you cannot use Mockito.when(Object).

Beware that Mockito.when(Object) is always recommended for stubbing because it is argument type-safe and more readable (especially when stubbing consecutive calls).

Here are those rare occasions when doReturn() comes handy:

1. When spying real objects and calling real methods on a spy brings side effects

List list = new LinkedList(); List spy = spy(list);

//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)

when(spy.get(0)).thenReturn("foo");

//You have to use doReturn() for stubbing: doReturn("foo").when(spy).get(0);

2. Overriding a previous exception-stubbing:

when(mock.foo()).thenThrow(new RuntimeException());

//Impossible: the exception-stubbed foo() method is called so RuntimeException is thrown. when(mock.foo()).thenReturn("bar");

//You have to use doReturn() for stubbing:

doReturn("bar").when(mock).foo(); Above scenarios shows a tradeoff of Mockito's elegant syntax. Note that the scenarios are very rare, though. Spying should be sporadic and overriding exception-stubbing is very rare. Not to mention that in general overridding stubbing is a potential code smell that points out too much stubbing.

How to connect to remote Redis server?

In Case of password also we need to pass one more parameter

redis-cli -h host -p port -a password

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

How can I add a line to a file in a shell script?

This adds custom text at the beginning of your file:

echo 'your_custom_escaped_content' > temp_file.csv
cat testfile.csv >> temp_file.csv
mv temp_file.csv testfile.csv

JS strings "+" vs concat method

There was a time when adding strings into an array and finalising the string by using join was the fastest/best method. These days browsers have highly optimised string routines and it is recommended that + and += methods are fastest/best

Find an element in a list of tuples

The filter function can also provide an interesting solution:

result = list(filter(lambda x: x.count(1) > 0, a))

which searches the tuples in the list a for any occurrences of 1. If the search is limited to the first element, the solution can be modified into:

result = list(filter(lambda x: x[0] == 1, a))

How to build a query string for a URL in C#?

I have an extension method for Uri that:

  • Accepts anonymous objects: uri.WithQuery(new { name = "value" })
  • Accepts collections of string/string pairs (e.g. Dictionary`2).
  • Accepts collections of string/object pairs (e.g. RouteValueDictionary).
  • Accepts NameValueCollections.
  • Sorts the query values by key so the same values produce equal URIs.
  • Supports multiple values per key, preserving their original order.

The documented version can be found here.

The extension:

public static Uri WithQuery(this Uri uri, object values)
{
    if (uri == null)
        throw new ArgumentNullException(nameof(uri));

    if (values != null)
    {
        var query = string.Join(
            "&", from p in ParseQueryValues(values)
                 where !string.IsNullOrWhiteSpace(p.Key)
                 let k = HttpUtility.UrlEncode(p.Key.Trim())
                 let v = HttpUtility.UrlEncode(p.Value)
                 orderby k
                 select string.IsNullOrEmpty(v) ? k : $"{k}={v}");

        if (query.Length != 0 || uri.Query.Length != 0)
            uri = new UriBuilder(uri) { Query = query }.Uri;
    }

    return uri;
}

The query parser:

private static IEnumerable<KeyValuePair<string, string>> ParseQueryValues(object values)
{
    // Check if a name/value collection.
    var nvc = values as NameValueCollection;
    if (nvc != null)
        return from key in nvc.AllKeys
               from val in nvc.GetValues(key)
               select new KeyValuePair<string, string>(key, val);

    // Check if a string/string dictionary.
    var ssd = values as IEnumerable<KeyValuePair<string, string>>;
    if (ssd != null)
        return ssd;

    // Check if a string/object dictionary.
    var sod = values as IEnumerable<KeyValuePair<string, object>>;
    if (sod == null)
    {
        // Check if a non-generic dictionary.
        var ngd = values as IDictionary;
        if (ngd != null)
            sod = ngd.Cast<dynamic>().ToDictionary<dynamic, string, object>(
                p => p.Key.ToString(), p => p.Value as object);

        // Convert object properties to dictionary.
        if (sod == null)
            sod = new RouteValueDictionary(values);
    }

    // Normalize and return the values.
    return from pair in sod
           from val in pair.Value as IEnumerable<string>
            ?? new[] { pair.Value?.ToString() }
           select new KeyValuePair<string, string>(pair.Key, val);
}

Here are the tests:

var uri = new Uri("https://stackoverflow.com/yo?oldKey=oldValue");

// Test with a string/string dictionary.
var q = uri.WithQuery(new Dictionary<string, string>
{
    ["k1"] = string.Empty,
    ["k2"] = null,
    ["k3"] = "v3"
});

Debug.Assert(q == new Uri(
    "https://stackoverflow.com/yo?k1&k2&k3=v3"));

// Test with a string/object dictionary.
q = uri.WithQuery(new Dictionary<string, object>
{
    ["k1"] = "v1",
    ["k2"] = new[] { "v2a", "v2b" },
    ["k3"] = null
});

Debug.Assert(q == new Uri(
    "https://stackoverflow.com/yo?k1=v1&k2=v2a&k2=v2b&k3"));

// Test with a name/value collection.
var nvc = new NameValueCollection()
{
    ["k1"] = string.Empty,
    ["k2"] = "v2a"
};

nvc.Add("k2", "v2b");

q = uri.WithQuery(nvc);
Debug.Assert(q == new Uri(
    "https://stackoverflow.com/yo?k1&k2=v2a&k2=v2b"));

// Test with any dictionary.
q = uri.WithQuery(new Dictionary<int, HashSet<string>>
{
    [1] = new HashSet<string> { "v1" },
    [2] = new HashSet<string> { "v2a", "v2b" },
    [3] = null
});

Debug.Assert(q == new Uri(
    "https://stackoverflow.com/yo?1=v1&2=v2a&2=v2b&3"));

// Test with an anonymous object.
q = uri.WithQuery(new
{
    k1 = "v1",
    k2 = new[] { "v2a", "v2b" },
    k3 = new List<string> { "v3" },
    k4 = true,
    k5 = null as Queue<string>
});

Debug.Assert(q == new Uri(
    "https://stackoverflow.com/yo?k1=v1&k2=v2a&k2=v2b&k3=v3&k4=True&k5"));

// Keep existing query using a name/value collection.
nvc = HttpUtility.ParseQueryString(uri.Query);
nvc.Add("newKey", "newValue");

q = uri.WithQuery(nvc);
Debug.Assert(q == new Uri(
    "https://stackoverflow.com/yo?newKey=newValue&oldKey=oldValue"));

// Merge two query objects using the RouteValueDictionary.
var an1 = new { k1 = "v1" };
var an2 = new { k2 = "v2" };

q = uri.WithQuery(
    new RouteValueDictionary(an1).Concat(
        new RouteValueDictionary(an2)));

Debug.Assert(q == new Uri(
    "https://stackoverflow.com/yo?k1=v1&k2=v2"));

how to prevent adding duplicate keys to a javascript array

function check (list){
    var foundRepeatingValue = false;
    var newList = [];
    for(i=0;i<list.length;i++){
        var thisValue = list[i];
        if(i>0){
            if(newList.indexOf(thisValue)>-1){
                foundRepeatingValue = true;
                console.log("getting repeated");
                return true;
            }
       } newList.push(thisValue);
    } return false;
}

 

var list1 = ["dse","dfg","dse"];
check(list1);

Output:

getting repeated
true

Convert String to Float in Swift

This is how I approached it. I did not want to "cross the bridge", as it has been removed from Xcode 6 beta 5 anyway, quick and dirty:

extension String {

    // converting a string to double
    func toDouble() -> Double? {

        // split the string into components
        var comps = self.componentsSeparatedByString(".")

        // we have nothing
        if comps.count == 0 {
            return nil
        }
        // if there is more than one decimal
        else if comps.count > 2 {
            return nil
        }
        else if comps[0] == "" || comps[1] == "" {
            return nil
        }

        // grab the whole portion
        var whole = 0.0
        // ensure we have a number for the whole
        if let w = comps[0].toInt() {
            whole = Double(w)
        }
        else {
            return nil
        }

        // we only got the whole
        if comps.count == 1 {

            return whole

        }

        // grab the fractional
        var fractional = 0.0
        // ensure we have a number for the fractional
        if let f = comps[1].toInt() {

            // use number of digits to get the power
            var toThePower = Double(countElements(comps[1]))

            // compute the fractional portion
            fractional = Double(f) / pow(10.0, toThePower)

        }
        else {
            return nil
        }

        // return the result
        return whole + fractional
    }

    // converting a string to float
    func toFloat() -> Float? {

        if let val = self.toDouble() {
            return Float(val)
        }
        else {
            return nil
        }

    }

}


// test it out
var str = "78.001"

if let val = str.toFloat() {
    println("Str in float: \(val)")
}
else {
    println("Unable to convert Str to float")
}

// now in double
if let val = str.toDouble() {
    println("Str in double: \(val)")
}
else {
    println("Unable to convert Str to double")
}

Display last git commit comment

git log -1 will display the latest commit message or git log -1 --oneline if you only want the sha1 and associated commit message to be displayed.

DataGrid get selected rows' column values

If you are using an SQL query to populate your DataGrid you can do this :

Datagrid fill

Private Sub UserControl_Loaded(sender As Object, e As RoutedEventArgs)
        Dim cmd As SqlCommand
        Dim da As SqlDataAdapter
        Dim dt As DataTable

        cmd = New SqlCommand With {
            .CommandText = "SELECT * FROM temp_rech_dossier_route",
            .Connection = connSQLServer
        }
        da = New SqlDataAdapter(cmd)
        dt = New DataTable("RECH")
        da.Fill(dt)
        DataGridRech.ItemsSource = dt.DefaultView
End Sub

Value diplay

    Private Sub DataGridRech_SelectionChanged(sender As Object, e As SelectionChangedEventArgs) Handles DataGridRech.SelectionChanged
        Dim val As DataRowView
        val = CType(DataGridRech.SelectedItem, DataRowView)
        Console.WriteLine(val.Row.Item("num_dos"))
    End Sub

I know it's in VB.Net but it can be translated into C#. I put this solution here, it might be useful for someone.

How do I get the first n characters of a string without checking the size or going out of bounds?

Here's a neat solution:

String upToNCharacters = s.substring(0, Math.min(s.length(), n));

Opinion: while this solution is "neat", I think it is actually less readable than a solution that uses if / else in the obvious way. If the reader hasn't seen this trick, he/she has to think harder to understand the code. IMO, the code's meaning is more obvious in the if / else version. For a cleaner / more readable solution, see @paxdiablo's answer.

Set the layout weight of a TextView programmatically

TextView txtview = new TextView(v.getContext());
LayoutParams params = new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1f);
txtview.setLayoutParams(params);

1f is denotes as weight=1; you can give 2f or 3f, views will move accoding to the space

Could not load file or assembly ... The parameter is incorrect

Sometimes you, also, need to clean this folder: C:\Windows\Temp\Temporary ASP.NET

SQL count rows in a table

select sum([rows])
from sys.partitions
where object_id=object_id('tablename')
 and index_id in (0,1)

is very fast but very rarely inaccurate.

Unable to Connect to GitHub.com For Cloning

You can make git replace the protocol for you

git config --global url."https://".insteadOf git://

See more at SO Bower install using only https?

SQL JOIN vs IN performance?

That's rather hard to say - in order to really find out which one works better, you'd need to actually profile the execution times.

As a general rule of thumb, I think if you have indices on your foreign key columns, and if you're using only (or mostly) INNER JOIN conditions, then the JOIN will be slightly faster.

But as soon as you start using OUTER JOIN, or if you're lacking foreign key indexes, the IN might be quicker.

Marc

How can I determine if a date is between two dates in Java?

You might want to take a look at Joda Time which is a really good API for dealing with date/time. Even though if you don't really need it for the solution to your current question it is bound to save you pain in the future.

Where does Chrome store extensions?

For Chrome on Mac, if you have multiple profiles, you can find it under your profile folder, either Default or Profile #. i.e either

~/Library/Application Support/Google/Chrome/Default/Extensions/ or ~/Library/Application Support/Google/Chrome/<Profile 1>/Extensions/

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

Shortcut for changing font size

Use : Tools in Menu -> Options -> Environment -> Fonts and Colors

How can I know which radio button is selected via jQuery?

Another way to get it:

_x000D_
_x000D_
 $("#myForm input[type=radio]").on("change",function(){_x000D_
   if(this.checked) {_x000D_
    alert(this.value);_x000D_
    }_x000D_
  });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form id="myForm">_x000D_
   <span><input type="radio" name="q12_3" value="1">1</span><br>_x000D_
   <span><input type="radio" name="q12_3" value="2">2</span>_x000D_
</form>
_x000D_
_x000D_
_x000D_

make html text input field grow as I type?

If you set the span to display: inline-block, automatic horizontal and vertical resizing works very well:

_x000D_
_x000D_
<span contenteditable="true" _x000D_
      style="display: inline-block;_x000D_
             border: solid 1px black;_x000D_
             min-width: 50px; _x000D_
             max-width: 200px">_x000D_
</span>
_x000D_
_x000D_
_x000D_

How to keep form values after post

If you are looking to just repopulate the fields with the values that were posted in them, then just echo the post value back into the field, like so:

<input type="text" name="myField1" value="<?php echo isset($_POST['myField1']) ? $_POST['myField1'] : '' ?>" />

Creating a new dictionary in Python

Call dict with no parameters

new_dict = dict()

or simply write

new_dict = {}

Change name of folder when cloning from GitHub?

You can do this.

git clone https://github.com/sferik/sign-in-with-twitter.git signin

refer the manual here

Is there a short cut for going back to the beginning of a file by vi editor?

After opening a file using vi

1) You can press Shift + g to go the end of the file

and

2) Press g twice to go to the beginning of the file

NOTE : - g is case-sensitive (Thanks to @Ben for pointing it out)

How do I write JSON data to a file?

The accepted answer is fine. However, I ran into "is not json serializable" error using that.

Here's how I fixed it with open("file-name.json", 'w') as output:

output.write(str(response))

Although it is not a good fix as the json file it creates will not have double quotes, however it is great if you are looking for quick and dirty.

How to scale an Image in ImageView to keep the aspect ratio

This worked for me:

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxWidth="39dip"
android:scaleType="centerCrop"
android:adjustViewBounds ="true"

Convert HTML Character Back to Text Using Java Standard Library

Or you can use unescapeHtml4:

    String miCadena="GU&#205;A TELEF&#211;NICA";
    System.out.println(StringEscapeUtils.unescapeHtml4(miCadena));

This code print the line: GUÍA TELEFÓNICA

Get GMT Time in Java

This is pretty simple and straight forward.

Date date = new Date();
TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
date = cal.getTime();

Now date will contain the current GMT time.

Switch case: can I use a range instead of a one number

You can use if-else statements with || operators (or-operator) like:

if(case1 == true || case2 == true || case3 == true)
   {
    Do this!... 
   }
else if(case4 == true || case5 == true || case6 == true)
   {
    Do this!... 
   }
else if(case7 == true || case8 == true || case9 == true)
   {
    Do this!... 
   }

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

Create an environment.plist file in ~/Library/LaunchAgents/ with this content:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>my.startup</string>
  <key>ProgramArguments</key>
  <array>
    <string>sh</string>
    <string>-c</string>
    <string>
    launchctl setenv PRODUCTS_PATH /Users/mortimer/Projects/my_products
    launchctl setenv ANDROID_NDK_HOME /Applications/android-ndk
    launchctl setenv PATH $PATH:/Applications/gradle/bin
    </string>

  </array>
  <key>RunAtLoad</key>
  <true/>
</dict>
</plist>

You can add many launchctl commands inside the <string></string> block.

The plist will activate after system reboot. You can also use launchctl load ~/Library/LaunchAgents/environment.plist to launch it immediately.

[Edit]

The same solution works in El Capitan too.

Xcode 7.0+ doesn't evaluate environment variables by default. The old behaviour can be enabled with this command:

defaults write com.apple.dt.Xcode UseSanitizedBuildSystemEnvironment -bool NO

[Edit]

There a couple of situations where this doesn't quite work. If the computer is restarted and "Reopen windows when logging back in" is selected, the reopened windows may not see the variables (Perhaps they are opened before the agent is run). Also, if you log in via ssh, the variables will not be set (so you'll need to set them in ~/.bash_profile). Finally, this doesn't seem to work for PATH on El Capitan and Sierra. That needs to be set via 'launchctl config user path ...' and in /etc/paths.

Comparing two vectors in an if statement

all is one option:

> A <- c("A", "B", "C", "D")
> B <- A
> C <- c("A", "C", "C", "E")

> all(A==B)
[1] TRUE
> all(A==C)
[1] FALSE

But you may have to watch out for recycling:

> D <- c("A","B","A","B")
> E <- c("A","B")
> all(D==E)
[1] TRUE
> all(length(D)==length(E)) && all(D==E)
[1] FALSE

The documentation for length says it currently only outputs an integer of length 1, but that it may change in the future, so that's why I wrapped the length test in all.

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Straight from the ECMA-262, Fifth Edition ECMAScript Specification:

7.9.1 Rules of Automatic Semicolon Insertion

There are three basic rules of semicolon insertion:

  1. When, as the program is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true:
    • The offending token is separated from the previous token by at least one LineTerminator.
    • The offending token is }.
  2. When, as the program is parsed from left to right, the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete ECMAScript Program, then a semicolon is automatically inserted at the end of the input stream.
  3. When, as the program is parsed from left to right, a token is encountered that is allowed by some production of the grammar, but the production is a restricted production and the token would be the first token for a terminal or nonterminal immediately following the annotation "[no LineTerminator here]" within the restricted production (and therefore such a token is called a restricted token), and the restricted token is separated from the previous token by at least one LineTerminator, then a semicolon is automatically inserted before the restricted token.

However, there is an additional overriding condition on the preceding rules: a semicolon is never inserted automatically if the semicolon would then be parsed as an empty statement or if that semicolon would become one of the two semicolons in the header of a for statement (see 12.6.3).

How do I concatenate multiple C++ strings on one line?

Have you tried to avoid the +=? instead use var = var + ... it worked for me.

#include <iostream.h> // for string

string myName = "";
int _age = 30;
myName = myName + "Vincent" + "Thorpe" + 30 + " " + 2019;

Cursor inside cursor

You could also sidestep nested cursor issues, general cursor issues, and global variable issues by avoiding the cursors entirely.

declare @rowid int
declare @rowid2 int
declare @id int
declare @type varchar(10)
declare @rows int
declare @rows2 int
declare @outer table (rowid int identity(1,1), id int, type varchar(100))
declare @inner table (rowid int  identity(1,1), clientid int, whatever int)

insert into @outer (id, type) 
Select id, type from sometable

select @rows = count(1) from @outer
while (@rows > 0)
Begin
    select top 1 @rowid = rowid, @id  = id, @type = type
    from @outer
    insert into @innner (clientid, whatever ) 
    select clientid whatever from contacts where contactid = @id
    select @rows2 = count(1) from @inner
    while (@rows2 > 0)
    Begin
        select top 1 /* stuff you want into some variables */
        /* Other statements you want to execute */
        delete from @inner where rowid = @rowid2
        select @rows2 = count(1) from @inner
    End  
    delete from @outer where rowid = @rowid
    select @rows = count(1) from @outer
End

How to overwrite the previous print to stdout in python?

Try this:

import time
while True:
    print("Hi ", end="\r")
    time.sleep(1)
    print("Bob", end="\r")
    time.sleep(1)

It worked for me. The end="\r" part is making it overwrite the previous line.

WARNING!

If you print out hi, then print out hello using \r, you’ll get hillo because the output wrote over the previous two letters. If you print out hi with spaces (which don’t show up here), then it will output hi. To fix this, print out spaces using \r.

Relative paths based on file location instead of current working directory

What you want to do is get the absolute path of the script (available via ${BASH_SOURCE[0]}) and then use this to get the parent directory and cd to it at the beginning of the script.

#!/bin/bash
parent_path=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P )

cd "$parent_path"
cat ../some.text

This will make your shell script work independent of where you invoke it from. Each time you run it, it will be as if you were running ./cat.sh inside dir.

Note that this script only works if you're invoking the script directly (i.e. not via a symlink), otherwise the finding the current location of the script gets a little more tricky)

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\ is an escape character in Python. \t gets interpreted as a tab. If you need \ character in a string, you have to use \\.

Your code should be:
test_file=open('c:\\Python27\\test.txt','r')

SQL Server: Best way to concatenate multiple columns?

Through discourse it's clear that the problem lies in using VS2010 to write the query, as it uses the canonical CONCAT() function which is limited to 2 parameters. There's probably a way to change that, but I'm not aware of it.

An alternative:

SELECT '1'+'2'+'3'

This approach requires non-string values to be cast/converted to strings, as well as NULL handling via ISNULL() or COALESCE():

SELECT  ISNULL(CAST(Col1 AS VARCHAR(50)),'')
      + COALESCE(CONVERT(VARCHAR(50),Col2),'')

HTTP Error 404.3-Not Found in IIS 7.5

In windows server 2012, even after installing asp.net you might run into this issue.

Check for "Http activation" feature. This feature is present under Web services as well.

Make sure you add the above and everything should be awesome for you !!!

How can I find the latitude and longitude from address?

Geocoder coder = new Geocoder(this);
        List<Address> addresses;
        try {
            addresses = coder.getFromLocationName(address, 5);
            if (addresses == null) {
            }
            Address location = addresses.get(0);
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            Log.i("Lat",""+lat);
            Log.i("Lng",""+lng);
            LatLng latLng = new LatLng(lat,lng);
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            googleMap.addMarker(markerOptions);
            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,12));
        } catch (IOException e) {
            e.printStackTrace();
        }

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

Per the developers, this error is not an actual failure, but rather "misleading error reports". This bug is fixed in version 40, which is available on the canary and dev channels as of 25 Oct.

Patch

Switch to selected tab by name in Jquery-UI Tabs

I had trouble getting any of the answers to work as they were based on the older versions of JQuery UI. We're using 1.11.4 (CDN Reference).

Here is my Fiddle with working code: http://jsfiddle.net/6b0p02um/ I ended up splicing together bits from four or five different threads to get mine to work:

    $("#tabs").tabs(); 

    //selects the tab index of the <li> relative to the div it is contained within
    $(".btn_tab3").click(function () {
        $( "#tabs" ).tabs( "option", "active", 2 );
    });         

    //selects the tab by id of the <li>
    $(".btn_tab3_id").click(function () {
      function selectTab(tabName) {
          $("#tabs").tabs("option", "active", $(tabName + "").index());
      }

      selectTab("#li_ui_id_3");
    });

Adding extra zeros in front of a number using jQuery?

Just for a laugh do it the long nasty way....:
(NOTE: ive not used this, and i would not advise using this.!)

function pad(str, new_length) {
    ('00000000000000000000000000000000000000000000000000' + str).
    substr((50 + str.toString().length) - new_length, new_length)
}

Does Python have a package/module management system?

On Windows install http://chocolatey.org/ then

choco install python

Open a new cmd-window with the updated PATH. Next, do

choco install pip

After that you can

pip install pyside
pip install ipython
...

What I can do to resolve "1 commit behind master"?

Use

git cherry-pick <commit-hash>

So this will pick your behind commit to git location you are on.

Using global variables between files?

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

# ../myproject/main.py

# Import globfile    
import globfile

# Save myList into globfile
globfile.myList = []

# Import subfile
import subfile

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

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

Mike

How can bcrypt have built-in salts?

I believe that phrase should have been worded as follows:

bcrypt has salts built into the generated hashes to prevent rainbow table attacks.

The bcrypt utility itself does not appear to maintain a list of salts. Rather, salts are generated randomly and appended to the output of the function so that they are remembered later on (according to the Java implementation of bcrypt). Put another way, the "hash" generated by bcrypt is not just the hash. Rather, it is the hash and the salt concatenated.

Submit a form in a popup, and then close the popup

I have executed the code in my machine its working for IE and FF also.

function closeSelf(){
    // do something

    if(condition satisfied){
       alert("conditions satisfied, submiting the form.");
       document.forms['certform'].submit();
       window.close();
    }else{
       alert("conditions not satisfied, returning to form");    
    }
}


<form action="/system/wpacert" method="post" enctype="multipart/form-data" name="certform">
       <div>Certificate 1: <input type="file" name="cert1"/></div>
       <div>Certificate 2: <input type="file" name="cert2"/></div>
       <div>Certificate 3: <input type="file" name="cert3"/></div>

       // change the submit button to normal button
       <div><input type="button" value="Upload"  onclick="closeSelf();"/></div>
</form>

Decimal separator comma (',') with numberDecimal inputType in EditText

You could do the following:

DecimalFormatSymbols d = DecimalFormatSymbols.getInstance(Locale.getDefault());
input.setFilters(new InputFilter[] { new DecimalDigitsInputFilter(5, 2) });
input.setKeyListener(DigitsKeyListener.getInstance("0123456789" + d.getDecimalSeparator()));

And then you could use an input filter:

    public class DecimalDigitsInputFilter implements InputFilter {

Pattern mPattern;

public DecimalDigitsInputFilter(int digitsBeforeZero, int digitsAfterZero) {
    DecimalFormatSymbols d = new DecimalFormatSymbols(Locale.getDefault());
    String s = "\\" + d.getDecimalSeparator();
    mPattern = Pattern.compile("[0-9]{0," + (digitsBeforeZero - 1) + "}+((" + s + "[0-9]{0," + (digitsAfterZero - 1) + "})?)||(" + s + ")?");
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

    Matcher matcher = mPattern.matcher(dest);
    if (!matcher.matches())
        return "";
    return null;
}

}

How to use org.apache.commons package?

Download commons-net binary from here. Extract the files and reference the commons-net-x.x.jar file.

Find the paths between two given nodes?

given the adjacency matrix:

{0, 1, 3, 4, 0, 0}

{0, 0, 2, 1, 2, 0}

{0, 1, 0, 3, 0, 0}

{0, 1, 1, 0, 0, 1}

{0, 0, 0, 0, 0, 6}

{0, 1, 0, 1, 0, 0}

the following Wolfram Mathematica code solve the problem to find all the simple paths between two nodes of a graph. I used simple recursion, and two global var to keep track of cycles and to store the desired output. the code hasn't been optimized just for the sake of code clarity. the "print" should be helpful to clarify how it works.

cycleQ[l_]:=If[Length[DeleteDuplicates[l]] == Length[l], False, True];
getNode[matrix_, node_]:=Complement[Range[Length[matrix]],Flatten[Position[matrix[[node]], 0]]];

builtTree[node_, matrix_]:=Block[{nodes, posAndNodes, root, pos},
    If[{node} != {} && node != endNode ,
        root = node;
        nodes = getNode[matrix, node];
        (*Print["root:",root,"---nodes:",nodes];*)

        AppendTo[lcycle, Flatten[{root, nodes}]];
        If[cycleQ[lcycle] == True,
            lcycle = Most[lcycle]; appendToTree[root, nodes];,
            Print["paths: ", tree, "\n", "root:", root, "---nodes:",nodes];
            appendToTree[root, nodes];

        ];
    ];

appendToTree[root_, nodes_] := Block[{pos, toAdd},
    pos = Flatten[Position[tree[[All, -1]], root]];
    For[i = 1, i <= Length[pos], i++,
        toAdd = Flatten[Thread[{tree[[pos[[i]]]], {#}}]] & /@ nodes;
        (* check cycles!*)            
        If[cycleQ[#] != True, AppendTo[tree, #]] & /@ toAdd;
    ];
    tree = Delete[tree, {#} & /@ pos];
    builtTree[#, matrix] & /@ Union[tree[[All, -1]]];
    ];
];

to call the code: initNode = 1; endNode = 6; lcycle = {}; tree = {{initNode}}; builtTree[initNode, matrix];

paths: {{1}} root:1---nodes:{2,3,4}

paths: {{1,2},{1,3},{1,4}} root:2---nodes:{3,4,5}

paths: {{1,3},{1,4},{1,2,3},{1,2,4},{1,2,5}} root:3---nodes:{2,4}

paths: {{1,4},{1,2,4},{1,2,5},{1,3,4},{1,2,3,4},{1,3,2,4},{1,3,2,5}} root:4---nodes:{2,3,6}

paths: {{1,2,5},{1,3,2,5},{1,4,6},{1,2,4,6},{1,3,4,6},{1,2,3,4,6},{1,3,2,4,6},{1,4,2,5},{1,3,4,2,5},{1,4,3,2,5}} root:5---nodes:{6}

RESULTS:{{1, 4, 6}, {1, 2, 4, 6}, {1, 2, 5, 6}, {1, 3, 4, 6}, {1, 2, 3, 4, 6}, {1, 3, 2, 4, 6}, {1, 3, 2, 5, 6}, {1, 4, 2, 5, 6}, {1, 3, 4, 2, 5, 6}, {1, 4, 3, 2, 5, 6}}

...Unfortunately I cannot upload images to show the results in a better way :(

http://textanddatamining.blogspot.com

How to insert blank lines in PDF?

You can add Blank Line throw PdfContentByte class in itextPdf. As shown below:

package com.pdf.test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;

import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

public class Ranvijay {

    public static final String RESULT = "d:/printReport.pdf";

    public void createPdf(String filename) throws Exception {
        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(filename));
        document.open();

        Font bold = new Font(Font.FontFamily.HELVETICA, 8f, Font.BOLD);
        Font normal = new Font(Font.FontFamily.HELVETICA, 8f, Font.NORMAL);
        PdfPTable tabletmp = new PdfPTable(1);
        tabletmp.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        tabletmp.setWidthPercentage(100);
        PdfPTable table = new PdfPTable(2);
        float[] colWidths = { 45, 55 };
        table.setWidths(colWidths);
        String imageUrl = "http://ssl.gstatic.com/s2/oz/images/logo/2x/googleplus_color_33-99ce54a16a32f6edc61a3e709eb61d31.png";
        Image image2 = Image.getInstance(new URL(imageUrl));
        image2.setWidthPercentage(60);
        table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT);
        table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP);
        PdfPCell cell = new PdfPCell();
        cell.setBorder(Rectangle.NO_BORDER);
        cell.addElement(image2);
        table.addCell(cell);
        String email = "[email protected]";
        String collectionDate = "09/09/09";
        Chunk chunk1 = new Chunk("Date: ", normal);
        Phrase ph1 = new Phrase(chunk1);

        Chunk chunk2 = new Chunk(collectionDate, bold);
        Phrase ph2 = new Phrase(chunk2);

        Chunk chunk3 = new Chunk("\nEmail: ", normal);
        Phrase ph3 = new Phrase(chunk3);

        Chunk chunk4 = new Chunk(email, bold);
        Phrase ph4 = new Phrase(chunk4);

        Paragraph ph = new Paragraph();
        ph.add(ph1);
        ph.add(ph2);
        ph.add(ph3);
        ph.add(ph4);

        table.addCell(ph);
        tabletmp.addCell(table);
        PdfContentByte canvas = writer.getDirectContent();
        canvas.saveState();
        canvas.setLineWidth((float) 10 / 10);
        canvas.moveTo(40, 806 - (5 * 10));
        canvas.lineTo(555, 806 - (5 * 10));
        canvas.stroke();
        document.add(tabletmp);
        canvas.restoreState();
        PdfPTable tabletmp1 = new PdfPTable(1);
        tabletmp1.getDefaultCell().setBorder(Rectangle.NO_BORDER);
        tabletmp1.setWidthPercentage(100);

        document.add(tabletmp1);

        document.close();
    }

    /**
     * Main method.
     * 
     * @param args
     *            no arguments needed
     * @throws DocumentException
     * @throws IOException
     */
    public static void main(String[] args) throws Exception {
        new Ranvijay().createPdf(RESULT);
        System.out.println("Done Please check........");
    }

}

Spring MVC UTF-8 Encoding

right-click to your controller.java then properties and check if your text file is encoded with utf-8, if not this is your mistake.

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

In my case, this error occured when creating a new Android Studio (Android studio 3.2.1) Java Project with

    classpath 'com.android.tools.build:gradle:2.0.0-beta6'

So I´ve downgraded to

       dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
      }

Not the best solution stay at an older version, but maybe it´s just a temporary bug in the beta as the NDK path in local.properties is still the same, but the IDE doesn´t complain anymore

"Line contains NULL byte" in CSV reader (Python)

I've recently fixed this issue and in my instance it was a file that was compressed that I was trying to read. Check the file format first. Then check that the contents are what the extension refers to.

Set a default parameter value for a JavaScript function

_x000D_
_x000D_
function throwIfNoValue() {_x000D_
throw new Error('Missing argument');_x000D_
}_x000D_
function foo(argValue = throwIfNoValue()) {_x000D_
return argValue ;_x000D_
}
_x000D_
_x000D_
_x000D_

Here foo() is a function which has a parameter named argValue. If we don’t pass anything in the function call here, then the function throwIfNoValue() will be called and the returned result will be assigned to the only argument argValue. This is how a function call can be used as a default parameter. Which makes the code more simplified and readable.

This example has been taken from here

How to check encoding of a CSV file

Or you can execute in python console or in Jupyter Notebook:

import csv
data = open("file.csv","r") 
data

You will see information about the data object like this:

<_io.TextIOWrapper name='arch.csv' mode='r' encoding='cp1250'>

As you can see it contains encoding infotmation.

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

I was facing similar issue with openCV on the python:3.7-slim docker box. Following did the trick for me :

apt-get install build-essential libglib2.0-0 libsm6 libxext6 libxrender-dev

Please see if this helps !

How to add message box with 'OK' button?

The code compiles ok for me. May be you have forgotten to add the import:

import android.app.AlertDialog;

Anyway, you have a good tutorial here.

Index (zero based) must be greater than or equal to zero

Your second String.Format uses {2} as a placeholder but you're only passing in one argument, so you should use {0} instead.

Change this:

String.Format("{2}", reader.GetString(0));

To this:

String.Format("{0}", reader.GetString(2));

Twitter Bootstrap Form File Element Upload Button

Here is alternate trick, it's not the best solution but it just give you a choice

HTML code:

<button clss="btn btn-primary" id="btn_upload">Choose File</button>
<input id="fileupload" class="hide" type="file" name="files[]">

Javascript:

$("#btn_upload").click(function(e){
e.preventDefault();
$("#fileupload").trigger('click');
});

javascript createElement(), style problem

You need to call the appendChild function to append your new element to an existing element in the DOM.

HTML list-style-type dash

In my case adding this code to CSS

ul {
    list-style-type: '- ';
}

was enough. Simple as it is.

How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

By default, np.genfromtxt uses dtype=float: that's why you string columns are converted to NaNs because, after all, they're Not A Number...

You can ask np.genfromtxt to try to guess the actual type of your columns by using dtype=None:

>>> from StringIO import StringIO
>>> test = "a,1,2\nb,3,4"
>>> a = np.genfromtxt(StringIO(test), delimiter=",", dtype=None)
>>> print a
array([('a',1,2),('b',3,4)], dtype=[('f0', '|S1'),('f1', '<i8'),('f2', '<i8')])

You can access the columns by using their name, like a['f0']...

Using dtype=None is a good trick if you don't know what your columns should be. If you already know what type they should have, you can give an explicit dtype. For example, in our test, we know that the first column is a string, the second an int, and we want the third to be a float. We would then use

>>> np.genfromtxt(StringIO(test), delimiter=",", dtype=("|S10", int, float))
array([('a', 1, 2.0), ('b', 3, 4.0)], 
      dtype=[('f0', '|S10'), ('f1', '<i8'), ('f2', '<f8')])

Using an explicit dtype is much more efficient than using dtype=None and is the recommended way.

In both cases (dtype=None or explicit, non-homogeneous dtype), you end up with a structured array.

[Note: With dtype=None, the input is parsed a second time and the type of each column is updated to match the larger type possible: first we try a bool, then an int, then a float, then a complex, then we keep a string if all else fails. The implementation is rather clunky, actually. There had been some attempts to make the type guessing more efficient (using regexp), but nothing that stuck so far]

CronJob not running

It might also be a timezone problem.

Cron uses the local time.

Run the command timedatectl to see the machine time and make sure that your crontab is in this same timezone.

How to add footnotes to GitHub-flavoured Markdown?

I used a variant of Mateo's solution. I'm using this in Rmd files written in github flavored markdown (gfm) for a Jekyll powered website but the same Rmd files are being used to produce pdfs in various contexts. The Rmd files are math heavy and the math is displayed with MathJax on the website. So I needed a solution that works with gfm that is processed via Jekyll, works with pandoc->pdflatex, and is compatible with MathJax.

snippet from Rmd file (which is gfm)

Here is a paragraph with an footnote <span id="a1">[[1]](#f1)</span>.

Footnotes
=========

1. <span id="f1"></span> This is a footnote. [$\hookleftarrow$](#a1)

$\hookleftarrow$ is latex, which works for me since I always have MathJax enabled. I use that to make sure it shows up correctly in my pdfs. I put my footnotes in square brackets because superscript is confusing if I am putting a footnote on some inline math.

Here it is in action: https://eeholmes.github.io/posts/2016-5-18-FI-recursion-1/

These notes can be put anywhere in the Rmd. I am putting in a list at the end so they are technically endnotes.

In c++ what does a tilde "~" before a function name signify?

It's the destructor, it destroys the instance, frees up memory, etc. etc.

Here's a description from ibm.com:

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.

See https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_74/rzarg/cplr380.htm

'const int' vs. 'int const' as function parameters in C++ and C

This isn't a direct answer but a related tip. To keep things straight, I always use the convection "put const on the outside", where by "outside" I mean the far left or far right. That way there is no confusion -- the const applies to the closest thing (either the type or the *). E.g.,



int * const foo = ...; // Pointer cannot change, pointed to value can change
const int * bar = ...; // Pointer can change, pointed to value cannot change
int * baz = ...; // Pointer can change, pointed to value can change
const int * const qux = ...; // Pointer cannot change, pointed to value cannot change

What .NET collection provides the fastest search

You should read this blog that speed tested several different types of collections and methods for each using both single and multi-threaded techniques.

According to the results, a BinarySearch on a List and SortedList were the top performers constantly running neck-in-neck when looking up something as a "value".

When using a collection that allows for "keys", the Dictionary, ConcurrentDictionary, Hashset, and HashTables performed the best overall.

JavaScript DOM: Find Element Index In Container

Array.prototype.indexOf.call(this.parentElement.children, this);

Or use let statement.

moment.js, how to get day of week number

From the docs page, notice they have these helpful headers

http://momentjs.com/docs/#/get-set/weekday/
(I didn't see them at first)

With header sections for:

  • Date of Month
  • Day of Week
  • etc

.

  var now = moment();
  var day  = now.day();
  var date = now.date(); // Number

Extract the last substring from a cell

Try this:

Right(RC[-1],Len(RC[-1])-InStrRev(RC[-1]," "))

How to create text file and insert data to that file on Android

If you want to create a file and write and append data to it many times, then use the below code, it will create file if not exits and will append data if it exists.

 SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
        Date now = new Date();
        String fileName = formatter.format(now) + ".txt";//like 2016_01_12.txt


         try
            {
                File root = new File(Environment.getExternalStorageDirectory()+File.separator+"Music_Folder", "Report Files");
                //File root = new File(Environment.getExternalStorageDirectory(), "Notes");
                if (!root.exists()) 
                {
                    root.mkdirs();
                }
                File gpxfile = new File(root, fileName);


                FileWriter writer = new FileWriter(gpxfile,true);
                writer.append(sBody+"\n\n");
                writer.flush();
                writer.close();
                Toast.makeText(this, "Data has been written to Report File", Toast.LENGTH_SHORT).show();
            }
            catch(IOException e)
            {
                 e.printStackTrace();

            }

ArrayList: how does the size increase?

when a ArrayList is declared and initialized using default constructor, memory space for 10 elements will be created. now, when i add 11 th element, what happens is

ArrayList create a new object with the following size

i.e OldCapacity*3/2+1 = 10*3/2+1 =16

How to use multiple @RequestMapping annotations in spring?

Right now with using Spring-Boot 2.0.4 - { } won't work.

@RequestMapping

still has String[] as a value parameter, so declaration looks like this:

 @RequestMapping(value=["/","/index","/login","/home"], method = RequestMethod.GET)

** Update - Works With Spring-Boot 2.2**

 @RequestMapping(value={"/","/index","/login","/home"}, method = RequestMethod.GET)

How do I return the SQL data types from my query?

select * from information_schema.columns

could get you started.

PHP PDO: charset, set names?

I just want to add that you have to make sure your database is created with COLLATE utf8_general_ci or whichever collation you want to use, Else you might end up with another one than intended.

In phpmyadmin you can see the collation by clicking your database and choose operations. If you try create tables with another collation than your database, your tables will end up with the database collation anyways.

So make sure the collation for your database is right before creating tables. Hope this saves someone a few hours lol

Gaussian filter in MATLAB

You first create the filter with fspecial and then convolve the image with the filter using imfilter (which works on multidimensional images as in the example).

You specify sigma and hsize in fspecial.

Code:

%%# Read an image
I = imread('peppers.png');
%# Create the gaussian filter with hsize = [5 5] and sigma = 2
G = fspecial('gaussian',[5 5],2);
%# Filter it
Ig = imfilter(I,G,'same');
%# Display
imshow(Ig)

Command-line Unix ASCII-based charting / plotting tool

Another option I've just run across is bashplotlib. Here's an example run on (roughly) the same data as my eplot example:

[$]> git shortlog -s -n | awk '{print $1}' | hist

 33|   o
 32|   o
 30|   o
 28|   o
 27|   o
 25|   o
 23|   o
 22|   o
 20|   o
 18|   o
 16|   o
 15|   o
 13|   o
 11|   o
 10|   o
  8|   o
  6|   o
  5|   o
  3|   o o     o
  1|   o o     o o       o
  0|   o o o o o o       o
    ----------------------

-----------------------
|       Summary       |
-----------------------
|   observations: 50  |
| min value: 1.000000 |
|  mean : 519.140000  |
|max value: 3207.000000|
-----------------------

Adjusting the bins helps the resolution a bit:

[$]> git shortlog -s -n | awk '{print $1}' | hist --nosummary --bins=40

 18|   o
   |   o
 17|   o
 16|   o
 15|   o
 14|   o
 13|   o
 12|   o
 11|   o
 10|   o
  9|   o
  8|   o
  7|   o
  6|   o
  5|   o   o
  4|   o   o o
  3|   o o o o   o
  2|   o o o o   o
  1|   o o o o   o                     o       o
  0|   o o o o o o           o     o   o o   o o                                 o
   |   o o o o o o           o     o   o o   o o                                 o
    --------------------------------------------------------------------------------

How does one use the onerror attribute of an img element

This is actually tricky, especially if you plan on returning an image url for use cases where you need to concatenate strings with the onerror condition image URL, e.g. you might want to programatically set the url parameter in CSS.

The trick is that image loading is asynchronous by nature so the onerror doesn't happen sunchronously, i.e. if you call returnPhotoURL it immediately returns undefined bcs the asynchronous method of loading/handling the image load just began.

So, you really need to wrap your script in a Promise then call it like below. NOTE: my sample script does some other things but shows the general concept:

returnPhotoURL().then(function(value){
    doc.getElementById("account-section-image").style.backgroundImage = "url('" + value + "')";
}); 


function returnPhotoURL(){
    return new Promise(function(resolve, reject){
        var img = new Image();
        //if the user does not have a photoURL let's try and get one from gravatar
        if (!firebase.auth().currentUser.photoURL) {
            //first we have to see if user han an email
            if(firebase.auth().currentUser.email){
                //set sign-in-button background image to gravatar url
                img.addEventListener('load', function() {
                    resolve (getGravatar(firebase.auth().currentUser.email, 48));
                }, false);
                img.addEventListener('error', function() {
                    resolve ('//rack.pub/media/fallbackImage.png');
                }, false);            
                img.src = getGravatar(firebase.auth().currentUser.email, 48);
            } else {
                resolve ('//rack.pub/media/fallbackImage.png');
            }
        } else {
            img.addEventListener('load', function() {
                resolve (firebase.auth().currentUser.photoURL);
            }, false);
            img.addEventListener('error', function() {
                resolve ('https://rack.pub/media/fallbackImage.png');
            }, false);      
            img.src = firebase.auth().currentUser.photoURL;
        }
    });
}

Automatically resize images with browser size using CSS

image container

Scaling images using the above trick only works if the container the images are in changes size.

The #icons container uses px values for the width and height. px values don't scale when the browser is resized.

Solutions

Use one of the following approaches:

  1. Define the width and/or height using % values.
  2. Use a series of @media queries to set the width and height to different values based on the current screen size.

Calculate difference between two dates (number of days)?

For beginners like me that will stumble upon this tiny problem, in a simple line, with sample conversion to int:

int totalDays = Convert.ToInt32((DateTime.UtcNow.Date - myDateTime.Date).TotalDays);

This calculates the total days from today (DateTime.UtcNow.Date) to a desired date (myDateTime.Date).

If myDateTime is yesterday, or older date than today, this will give a positive (+) integer result.

On the other side, if the myDateTime is tomorrow or on the future date, this will give a negative (-) integer result due to rules of addition.

Happy coding! ^_^

static and extern global variables in C and C++

Global variables are not extern nor static by default on C and C++. When you declare a variable as static, you are restricting it to the current source file. If you declare it as extern, you are saying that the variable exists, but are defined somewhere else, and if you don't have it defined elsewhere (without the extern keyword) you will get a link error (symbol not found).

Your code will break when you have more source files including that header, on link time you will have multiple references to varGlobal. If you declare it as static, then it will work with multiple sources (I mean, it will compile and link), but each source will have its own varGlobal.

What you can do in C++, that you can't in C, is to declare the variable as const on the header, like this:

const int varGlobal = 7;

And include in multiple sources, without breaking things at link time. The idea is to replace the old C style #define for constants.

If you need a global variable visible on multiple sources and not const, declare it as extern on the header, and then define it, this time without the extern keyword, on a source file:

Header included by multiple files:

extern int varGlobal;

In one of your source files:

int varGlobal = 7;

Round a double to 2 decimal places

In your question, it seems that you want to avoid rounding the numbers as well? I think .format() will round the numbers using half-up, afaik?
so if you want to round, 200.3456 should be 200.35 for a precision of 2. but in your case, if you just want the first 2 and then discard the rest?

You could multiply it by 100 and then cast to an int (or taking the floor of the number), before dividing by 100 again.

200.3456 * 100 = 20034.56;  
(int) 20034.56 = 20034;  
20034/100.0 = 200.34;

You might have issues with really really big numbers close to the boundary though. In which case converting to a string and substring'ing it would work just as easily.

Find a pair of elements from an array whose sum equals a given number

One Solution can be this, but not optimul (The complexity of this code is O(n^2)):

public class FindPairsEqualToSum {

private static int inputSum = 0;

public static List<String> findPairsForSum(int[] inputArray, int sum) {
    List<String> list = new ArrayList<String>();
    List<Integer> inputList = new ArrayList<Integer>();
    for (int i : inputArray) {
        inputList.add(i);
    }
    for (int i : inputArray) {
        int tempInt = sum - i;
        if (inputList.contains(tempInt)) {
            String pair = String.valueOf(i + ", " + tempInt);
            list.add(pair);
        }
    }
    return list;
   }
}

Python add item to the tuple

You need to make the second element a 1-tuple, eg:

a = ('2',)
b = 'z'
new = a + (b,)

Python read next()

You don't need to read the next line, you are iterating through the lines. lines is a list (an array), and for line in lines is iterating over it. Every time you are finished with one you move onto the next line. If you want to skip to the next line just continue out of the current loop.

filne = "D:/testtube/testdkanimfilternode.txt"
f = open(filne, 'r+')

lines = f.readlines() # get all lines as a list (array)

# Iterate over each line, printing each line and then move to the next
for line in lines:
    print line

f.close()

Android: Vertical alignment for multi line EditText (Text area)

Now a day use of gravity start is best choise:

android:gravity="start"

For EditText (textarea):

<EditText
    android:id="@+id/EditText02"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:lines="5"
    android:gravity="start"
    android:inputType="textMultiLine"
/>

How I add Headers to http.get or http.post in Typescript and angular 2?

This way I was able to call MyService

private REST_API_SERVER = 'http://localhost:4040/abc';
public sendGetRequest() {
   var myFormData = { email: '[email protected]', password: '123' };
   const headers = new HttpHeaders();
   headers.append('Content-Type', 'application/json');
   //HTTP POST REQUEST
   this.httpClient
  .post(this.REST_API_SERVER, myFormData, {
    headers: headers,
   })
  .subscribe((data) => {
    console.log("i'm from service............", data, myFormData, headers);
    return data;
  });
}

How do I create a Java string from the contents of a file?

That code will normalize line breaks, which may or may not be what you really want to do.

Here's an alternative which doesn't do that, and which is (IMO) simpler to understand than the NIO code (although it still uses java.nio.charset.Charset):

public static String readFile(String file, String csName)
            throws IOException {
    Charset cs = Charset.forName(csName);
    return readFile(file, cs);
}

public static String readFile(String file, Charset cs)
            throws IOException {
    // No real need to close the BufferedReader/InputStreamReader
    // as they're only wrapping the stream
    FileInputStream stream = new FileInputStream(file);
    try {
        Reader reader = new BufferedReader(new InputStreamReader(stream, cs));
        StringBuilder builder = new StringBuilder();
        char[] buffer = new char[8192];
        int read;
        while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
            builder.append(buffer, 0, read);
        }
        return builder.toString();
    } finally {
        // Potential issue here: if this throws an IOException,
        // it will mask any others. Normally I'd use a utility
        // method which would log exceptions and swallow them
        stream.close();
    }        
}

How to split a string content into an array of strings in PowerShell?

Remove the spaces from the original string and split on semicolon

$address = "[email protected]; [email protected]; [email protected]"
$addresses = $address.replace(' ','').split(';')

Or all in one line:

$addresses = "[email protected]; [email protected]; [email protected]".replace(' ','').split(';')

$addresses becomes:

@('[email protected]','[email protected]','[email protected]')

Effect of NOLOCK hint in SELECT statements

It will be faster because it doesnt have to wait for locks

How to know the size of the string in bytes?

You can use encoding like ASCII to get a character per byte by using the System.Text.Encoding class.

or try this

  System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
  System.Text.ASCIIEncoding.ASCII.GetByteCount(string);

Performing Breadth First Search recursively

Here's a python implementation:

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

def bfs(paths, goal):
    if not paths:
        raise StopIteration

    new_paths = []
    for path in paths:
        if path[-1] == goal:
            yield path

        last = path[-1]
        for neighbor in graph[last]:
            if neighbor not in path:
                new_paths.append(path + [neighbor])
    yield from bfs(new_paths, goal)


for path in bfs([['A']], 'D'):
    print(path)

MySQL SELECT statement for the "length" of the field is greater than 1

select * from [tbl] where [link] is not null and len([link]) > 1

For MySQL user:

LENGTH([link]) > 1

How do I pick 2 random items from a Python set?

Use the random module: http://docs.python.org/library/random.html

import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)

This samples the two values without replacement (so the two values are different).

How to check sbt version?

From within the sbt shell

sbt:venkat> about
[info] This is sbt 1.3.3
...

HRESULT: 0x800A03EC on Worksheet.range

This problem occurs if you are using a backwards compatible sheet (a .xls) instead of a .xlsx

To allow sheets to be opened in pre office 2007 version it can't contain more than 65k rows. You can check the number of rows in your sheet by using ctrl+arrowdown till you hit the bottom. If you try to get a range larger than that number of rows it will create an error

Replace multiple characters in one replace call

I don't know if how much this will help but I wanted to remove <b> and </b> from my string

so I used

mystring.replace('<b>',' ').replace('</b>','');

so basically if you want a limited number of character to be reduced and don't waste time this will be useful.

Python glob multiple filetypes

You can try to make a manual list comparing the extension of existing with those you require.

ext_list = ['gif','jpg','jpeg','png'];
file_list = []
for file in glob.glob('*.*'):
  if file.rsplit('.',1)[1] in ext_list :
    file_list.append(file)

"RangeError: Maximum call stack size exceeded" Why?

You first need to understand Call Stack. Understanding Call stack will also give you clarity to how "function hierarchy and execution order" works in JavaScript Engine.

The call stack is primarily used for function invocation (call). Since there is only one call stack. Hence, all function(s) execution get pushed and popped one at a time, from top to bottom.

It means the call stack is synchronous. When you enter a function, an entry for that function is pushed onto the Call stack and when you exit from the function, that same entry is popped from the Call Stack. So, basically if everything is running smooth, then at the very beginning and at the end, Call Stack will be found empty.

Here is the illustration of Call Stack: enter image description here

Now, if you provide too many arguments or caught inside any unhandled recursive call. You will encounter

RangeError: Maximum call stack size exceeded

which is quite obvious as explained by others. enter image description here enter image description here

Hope this helps !

Blocking device rotation on mobile web pages

seems weird that no one proposed the CSS media query solution:

@media screen and (orientation: portrait) {
  ...
}

and the option to use a specific style sheet:

<link rel="stylesheet" type="text/css" href="css/style_p.css" media="screen and (orientation: portrait)">

MDN: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries#orientation

".addEventListener is not a function" why does this error occur?

document.getElementsByClassName returns an array of elements. so may be you want to target a specific index of them: var comment = document.getElementsByClassName('button')[0]; should get you what you want.

Update #1:

var comments = document.getElementsByClassName('button');
var numComments = comments.length;

function showComment() {
  var place = document.getElementById('textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
}

for (var i = 0; i < numComments; i++) {
  comments[i].addEventListener('click', showComment, false);
}

Update #2: (with removeEventListener incorporated as well)

var comments = document.getElementsByClassName('button');
var numComments = comments.length;

function showComment(e) {
  var place = document.getElementById('textfield');
  var commentBox = document.createElement('textarea');
  place.appendChild(commentBox);
  for (var i = 0; i < numComments; i++) {
    comments[i].removeEventListener('click', showComment, false);
  }
}

for (var i = 0; i < numComments; i++) {
  comments[i].addEventListener('click', showComment, false);
}

Using Mockito's generic "any()" method

Since Java 8 you can use the argument-less any method and the type argument will get inferred by the compiler:

verify(bar).doStuff(any());

Explanation

The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only arguments to methods where used for type parameter inference (most of the time).

In this case the parameter type of doStuff will be the target type for any(), and the return value type of any() will get chosen to match that argument type.

This mechanism was added in Java 8 mainly to be able to compile lambda expressions, but it improves type inferences generally.


Primitive types

This doesn't work with primitive types, unfortunately:

public interface IBar {
    void doPrimitiveStuff(int i);
}

verify(bar).doPrimitiveStuff(any()); // Compiles but throws NullPointerException
verify(bar).doPrimitiveStuff(anyInt()); // This is what you have to do instead

The problem is that the compiler will infer Integer as the return value type of any(). Mockito will not be aware of this (due to type erasure) and return the default value for reference types, which is null. The runtime will try to unbox the return value by calling the intValue method on it before passing it to doStuff, and the exception gets thrown.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

I also had the same problem. I used next way:

1.Added settings.xml file (~/.m2/settings.xml) with next content

<proxies>
   <proxy>
      <active>true</active>
      <protocol>http</protocol>
      <host>qq-proxya</host>
      <port>8080</port>
      <username>user</username>
      <password>passw</password>
      <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts>
    </proxy>
  </proxies>

3. Using cmd go to folder with my project and wrote mvn clean and after that mvn install !

  1. After that updated project in the Eclipse(Alt + F5) or right click on project -> Maven -> Update project

P.S. after that, when I add new dependency to my project I have to compile project using cmd(mvn compile). Because if I do it using eclipse plugin, I get error connecting with proxy connection.

How to find a user's home directory on linux or unix?

Normally you use the statement

String userHome = System.getProperty( "user.home" );

to get the home directory of the user on any platform. See the method documentation for getProperty to see what else you can get.

There may be access problems you might want to avoid by using this workaround (Using a security policy file)

Select all where [first letter starts with B]

SQL Statement:

 SELECT * FROM employee WHERE employeeName LIKE 'A%';

Result:

Number of Records: 4

employeeID  employeeName    employeeName    Address City    PostalCode  Country

1           Alam             Wipro          Delhi   Delhi   11005      India

2           Aditya           Wipro          Delhi   Delhi   11005      India

3           Alok             HCL            Delhi   Delhi   11005      India

4           Ashok            IBM            Delhi   Delhi   11005      India

How to schedule a periodic task in Java?

You should take a look to Quartz it's a java framework wich works with EE and SE editions and allows to define jobs to execute an specific time

Does bootstrap 4 have a built in horizontal divider?

Here are some custom utility classes:

_x000D_
_x000D_
hr.dashed {
    border-top: 2px dashed #999;
}

hr.dotted {
    border-top: 2px dotted #999;
}

hr.solid {
    border-top: 2px solid #999;
}


hr.hr-text {
  position: relative;
    border: none;
    height: 1px;
    background: #999;
}

hr.hr-text::before {
    content: attr(data-content);
    display: inline-block;
    background: #fff;
    font-weight: bold;
    font-size: 0.85rem;
    color: #999;
    border-radius: 30rem;
    padding: 0.2rem 2rem;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}



/*
*
* ==========================================
* FOR DEMO PURPOSES
* ==========================================
*
*/

body {
    min-height: 100vh;
    background-color: #fff; 
    color: #333;
}
.text-uppercase {
  letter-spacing: .1em;
}
_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css">

<div class="container py-5">
    <!-- For Demo Purpose -->
    <header class="py-5 text-center">
        <h1 class="display-4">Bootstrap Divider</h1>
        <p class="lead mb-0">Some divider variants using &lt;hr&gt; element.    </p>
    </header>


    <div class="row">
        <div class="col-lg-8 mx-auto">
            <div class="mb-4">
                <h6 class=" text-uppercase">Dashed</h6>
                <!-- Dashed divider -->
                <hr class="dashed">
            </div>
            <div class="mb-4">
                <h6 class=" text-uppercase">Dotted</h6>
                <!-- Dotted divider -->
                <hr class="dotted">
            </div>
            <div class="mb-4">
                <h6 class="text-uppercase">Solid</h6>
                <!-- Solid divider -->
                <hr class="solid">
            </div>
            <div class="mb-4">
                <h6 class=" text-uppercase">Text content</h6>
                <!-- Gradient divider -->
                <hr data-content="AND" class="hr-text">
            </div>
           
        </div>
    </div>
</div>
_x000D_
_x000D_
_x000D_

How do I convert a Swift Array to a String?

Since no one has mentioned reduce, here it is:

[0, 1, 1, 0].map {"\($0)"}.reduce("") { $0 + $1 } // "0110"

In the spirit of functional programming

How do I find which process is leaking memory?

You can run the top command (to run non-interactively, type top -b -n 1). To see applications which are leaking memory, look at the following columns:

  • RPRVT - resident private address space size
  • RSHRD - resident shared address space size
  • RSIZE - resident memory size
  • VPRVT - private address space size
  • VSIZE - total memory size

Adding blank spaces to layout

<View
    android:layout_width="fill_parent"
    android:layout_height="30dp"
    android:background="#80000000">
</View>

Reload browser window after POST without prompting user to resend POST data

This is an older post, but I do have a better solution. Create a form containing all of your post values as hidden fields and give the form a name such as:

<form name="RefreshForm" method="post" action="http://yoursite/yourscript">
    <input type="hidden" name="postVariable" value="PostData">
</form>

Then all you need to do in your setTimeout is RefreshForm.submit();

Cheers!

How is the AND/OR operator represented as in Regular Expressions?

Not an expert in regex, but you can do ^((part1|part2)|(part1, part2))$. In words: "part 1 or part2 or both"