Programs & Examples On #Pasting

Can't compile C program on a Mac after upgrade to Mojave

ln -s /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk '/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.15.sdk' might help you. It fixed my problem.

React Native TextInput that only accepts numeric characters

A kind reminder to those who encountered the problem that "onChangeText" cannot change the TextInput value as expected on iOS: that is actually a bug in ReactNative and had been fixed in version 0.57.1. Refer to: https://github.com/facebook/react-native/issues/18874

Ubuntu: OpenJDK 8 - Unable to locate package

sudo apt-get update
sudo apt-get  install openjdk-8-jdk

this should work

Disable Copy or Paste action for text box?

Try This

 $( "#email,#confirmEmail " ).on( "copy cut paste drop", function() {
                return false;
        });

No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS

I have a solution below and its works for me:

app.controller('LoginController', ['$http', '$scope', function ($scope, $http) {
$scope.login = function (credentials) {
$http({
        method: 'jsonp',
        url: 'http://mywebservice',
        params: {
            format: 'jsonp',
            callback: 'JSON_CALLBACK'
        }
    }).then(function (response) {
        alert(response.data);
    });
  }
}]);

in 'http://mywebservice' there must be need a callback parameter which return JSON_CALLBACK with data.
There is a sample example below which works perfect

$scope.url = "https://angularjs.org/greet.php";
    $http({
        method: 'jsonp',
        url: $scope.url,
        params: {
            format: 'jsonp',
            name: 'Super Hero',
            callback: 'JSON_CALLBACK'
        }
    }).then(function (response) {
        alert(response.data);
    });

example output:

{"name":"Super Hero","salutation":"Apa khabar","greeting":"Apa khabar Super Hero!"}

github markdown colspan

Compromise minimum solution:

| One    | Two | Three | Four    | Five  | Six 
| -
| Span <td colspan=3>triple  <td colspan=2>double

So you can omit closing </td> for speed, ?r can leave for consistency.

Result from http://markdown-here.com/livedemo.html : markdown table with colspan

Works in Jupyter Markdown.

Update:

As of 2019 year all pipes in the second line are compulsory in Jupyter Markdown.

| One    | Two | Three | Four    | Five  | Six
|-|-|-|-|-|-
| Span <td colspan=3>triple  <td colspan=2>double

minimally:

One    | Two | Three | Four    | Five  | Six
-|||||-
Span <td colspan=3>triple  <td colspan=2>double

Expected block end YAML error

I would like to make this answer for meaningful, so the same kind of erroneous user can enjoy without feel any hassle.

Actually, i was getting the same error but for the different reason, in my case I didn't used any kind of quoted, still getting the same error like expected <block end>, but found BlockMappingStart.

I have solved it by fixing, the Alignment issue inside the same .yml file.

If we don't manage the proper 'tab-space(Keyboard key)' for maintaining successor or ancestor then we have to phase such kind of things.

Now i am doing well.

Django: TemplateSyntaxError: Could not parse the remainder

In templates/admin/includes_grappelli/header.html, line 12, you forgot to put admin:password_change between '.

The url Django tag syntax should always be like:

{% url 'your_url_name' %}

Copy from one workbook and paste into another

You copied using Cells.
If so, no need to PasteSpecial since you are copying data at exactly the same format.
Here's your code with some fixes.

Dim x As Workbook, y As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet

Set x = Workbooks.Open("path to copying book")
Set y = Workbooks.Open("path to pasting book")

Set ws1 = x.Sheets("Sheet you want to copy from")
Set ws2 = y.Sheets("Sheet you want to copy to")

ws1.Cells.Copy ws2.cells
y.Close True
x.Close False

If however you really want to paste special, use a dynamic Range("Address") to copy from.
Like this:

ws1.Range("Address").Copy: ws2.Range("A1").PasteSpecial xlPasteValues
y.Close True
x.Close False

Take note of the : colon after the .Copy which is a Statement Separating character.
Using Object.PasteSpecial requires to be executed in a new line.
Hope this gets you going.

VBA paste range

I would try

Sheets("Sheet1").Activate
Set Ticker = Range(Cells(2, 1), Cells(65, 1))
Ticker.Copy

Worksheets("Sheet2").Range("A1").Offset(0,0).Cells.Select
Worksheets("Sheet2").paste

How to Set AllowOverride all

In case you are on Ubuntu, edit the file /etc/apache2/apache2.conf (here we have an example of /var/www):

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
</Directory>

and change it to;

<Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>

then,

sudo service apache2 restart

You may need to also do sudo a2enmod rewrite to enable module rewrite.

How to run Conda?

Open your terminal and type the following command to add anaconda to environment path

for anaconda 2 :

export PATH=~/anaconda2/bin:$PATH

for anaconda 3 :

export PATH=~/anaconda3/bin:$PATH

Then to check the conda version just type,

conda --version

Create an environment using the following command,

conda create --name myenv

Activate the source using,

source activate myenv

Then your anaconda IDE is ready!!!

DateTime fields from SQL Server display incorrectly in Excel

Here's a hack which might be helpful... it puts an apostrophe in front of the time value, so when you right-click on the output in SSMS and say "Copy with Headers", then paste into Excel, it preserves the milliseconds / nanoseconds for datetime2 values. It's a bit ugly that it puts the apostrophe there, but it's better than the frustration of dealing with Excel doing unwanted rounding on the time value. The date is a UK format but you can look at the CONVERT function page in MSDN.

SELECT CONVERT(VARCHAR(23), sm.MilestoneDate, 103) AS MilestoneDate, '''' + CONVERT(VARCHAR(23), sm.MilestoneDate, 114) AS MilestoneTime FROM SomeTable sm

Apache giving 403 forbidden errors

You can try disabling selinux and try once again using the following command

setenforce 0

How can I add a vertical scrollbar to my div automatically?

To show vertical scroll bar in your div you need to add

height: 100px;   
overflow-y : scroll;

or

height: 100px; 
overflow-y : auto;

Excel VBA Automation Error: The object invoked has disconnected from its clients

The error in the below line of code (as mentioned by the requestor-William) is due to the following reason:

fromBook.Sheets("Report").Copy Before:=newBook.Sheets("Sheet1")

The destination sheet you are trying to copy to is closed. (Here newbook.Sheets("Sheet1")). Add the below statement just before copying to destination.

Application.Workbooks.Open ("YOUR SHEET NAME")

This will solve the problem!!

Spring Data JPA Update @Query not updating?

I finally understood what was going on.

When creating an integration test on a statement saving an object, it is recommended to flush the entity manager so as to avoid any false negative, that is, to avoid a test running fine but whose operation would fail when run in production. Indeed, the test may run fine simply because the first level cache is not flushed and no writing hits the database. To avoid this false negative integration test use an explicit flush in the test body. Note that the production code should never need to use any explicit flush as it is the role of the ORM to decide when to flush.

When creating an integration test on an update statement, it may be necessary to clear the entity manager so as to reload the first level cache. Indeed, an update statement completely bypasses the first level cache and writes directly to the database. The first level cache is then out of sync and reflects the old value of the updated object. To avoid this stale state of the object, use an explicit clear in the test body. Note that the production code should never need to use any explicit clear as it is the role of the ORM to decide when to clear.

My test now works just fine.

Excel VBA Check if directory exists error

To be certain that a folder exists (and not a file) I use this function:

Public Function FolderExists(strFolderPath As String) As Boolean
    On Error Resume Next
    FolderExists = ((GetAttr(strFolderPath) And vbDirectory) = vbDirectory)
    On Error GoTo 0
End Function

It works both, with \ at the end and without.

modal View controllers - how to display and dismiss

Radu Simionescu - awesome work! and below Your solution for Swift lovers:

@IBAction func showSecondControlerAndCloseCurrentOne(sender: UIButton) {
    let secondViewController = storyboard?.instantiateViewControllerWithIdentifier("ConrollerStoryboardID") as UIViewControllerClass // change it as You need it
    var presentingVC = self.presentingViewController
    self.dismissViewControllerAnimated(false, completion: { () -> Void   in
        presentingVC!.presentViewController(secondViewController, animated: true, completion: nil)
    })
}

How to pass multiple values to single parameter in stored procedure

I think, below procedure help you to what you are looking for.

 CREATE PROCEDURE [dbo].[FindEmployeeRecord]
        @EmployeeID nvarchar(Max)
    AS
    BEGIN
    DECLARE @sqLQuery VARCHAR(MAX)
    Declare @AnswersTempTable Table
    (  
        EmpId int,         
        EmployeeName nvarchar (250),       
        EmployeeAddress nvarchar (250),  
        PostalCode nvarchar (50),
        TelephoneNo nvarchar (50),
        Email nvarchar (250),
        status nvarchar (50),  
        Sex nvarchar (50) 
    )

    Set @sqlQuery =
    'select e.EmpId,e.EmployeeName,e.Email,e.Sex,ed.EmployeeAddress,ed.PostalCode,ed.TelephoneNo,ed.status
    from Employee e
    join EmployeeDetail ed on e.Empid = ed.iEmpID
    where Convert(nvarchar(Max),e.EmpId) in ('+@EmployeeId+')
    order by EmpId'
    Insert into @AnswersTempTable
    exec (@sqlQuery)
    select * from @AnswersTempTable
    END

New Line Issue when copying data from SQL Server 2012 to Excel

This sometimes happens with Excel when you've recently used "Text to Columns."

Try exiting out of excel, reopening, and pasting again. That usually works for me, but I've heard you sometimes have to restart your computer altogether.

PHP Array to CSV

I know this is old, I had a case where I needed the array key to be included in the CSV also, so I updated the script by Jesse Q to do that. I used a string as output, as implode can't add new line (new line is something I added, and should really be there).

Please note, this only works with single value arrays (key, value). but could easily be updated to handle multi-dimensional (key, array()).

function arrayToCsv( array &$fields, $delimiter = ',', $enclosure = '"', $encloseAll = false, $nullToMysqlNull = false ) {
    $delimiter_esc = preg_quote($delimiter, '/');
    $enclosure_esc = preg_quote($enclosure, '/');

    $output = '';
    foreach ( $fields as $key => $field ) {
        if ($field === null && $nullToMysqlNull) {
            $output = '';
            continue;
        }

        // Enclose fields containing $delimiter, $enclosure or whitespace
        if ( $encloseAll || preg_match( "/(?:${delimiter_esc}|${enclosure_esc}|\s)/", $field ) ) {
            $output .= $key;
            $output .= $delimiter;
            $output .= $enclosure . str_replace($enclosure, $enclosure . $enclosure,     $field) . $enclosure;
            $output .= PHP_EOL;
        }
        else {
            $output .= $key;
            $output .= $delimiter;
            $output .= $field;
            $output .= PHP_EOL;
        }
    }

    return  $output ;
}

JQuery: detect change in input field

Use $.on() to bind your chosen event to the input, don't use the shortcuts like $.keydown() etc because as of jQuery 1.7 $.on() is the preferred method to attach event handlers (see here: http://api.jquery.com/on/ and http://api.jquery.com/bind/).

$.keydown() is just a shortcut to $.bind('keydown'), and $.bind() is what $.on() replaces (among others).

To answer your question, as far as I'm aware, unless you need to fire an event on keydown specifically, the change event should do the trick for you.

$('element').on('change', function(){
    console.log('change');
});

To respond to the below comment, the javascript change event is documented here: https://developer.mozilla.org/en-US/docs/Web/Events/change

And here is a working example of the change event working on an input element, using jQuery: http://jsfiddle.net/p1m4xh08/

How to add color to Github's README.md file

Based on @AlecRust idea, I did an implementation of png text service.

The demo is here:

http://lingtalfi.com/services/pngtext?color=cc0000&size=10&text=Hello%20World

There are four parameters:

  • text: the string to display
  • font: not use because I only have Arial.ttf anyway on this demo.
  • fontSize: an integer (defaults to 12)
  • color: a 6 chars hexadecimal code

Please do not use this service directly (except for testing), but use the class I created that provides the service:

https://github.com/lingtalfi/WebBox/blob/master/Image/PngTextUtil.php

class PngTextUtil
{
    /**
     * Displays a png text.
     *
     * Note: this method is meant to be used as a webservice.
     *
     * Options:
     * ------------
     * - font: string = arial/Arial.ttf
     *          The font to use.
     *          If the path starts with a slash, it's an absolute path to the font file.
     *          Else if the path doesn't start with a slash, it's a relative path to the font directory provided
     *          by this class (the WebBox/assets/fonts directory in this repository).
     * - fontSize: int = 12
     *          The font size.
     * - color: string = 000000
     *          The color of the text in hexadecimal format (6 chars).
     *          This can optionally be prefixed with a pound symbol (#).
     *
     *
     *
     *
     *
     *
     * @param string $text
     * @param array $options
     * @throws \Bat\Exception\BatException
     * @throws WebBoxException
     */
    public static function displayPngText(string $text, array $options = []): void
    {
        if (false === extension_loaded("gd")) {
            throw new WebBoxException("The gd extension is not loaded!");
        }
        header("Content-type: image/png");
        $font = $options['font'] ?? "arial/Arial.ttf";
        $fontsize = $options['fontSize'] ?? 12;
        $hexColor = $options['color'] ?? "000000";
        if ('/' !== substr($font, 0, 1)) {
            $fontDir = __DIR__ . "/../assets/fonts";
            $font = $fontDir . "/" . $font;
        }
        $rgbColors = ConvertTool::convertHexColorToRgb($hexColor);
        //--------------------------------------------
        // GET THE TEXT BOX DIMENSIONS
        //--------------------------------------------
        $charWidth = $fontsize;
        $charFactor = 1;
        $textLen = mb_strlen($text);
        $imageWidth = $textLen * $charWidth * $charFactor;
        $imageHeight = $fontsize;
        $logoimg = imagecreatetruecolor($imageWidth, $imageHeight);
        imagealphablending($logoimg, false);
        imagesavealpha($logoimg, true);
        $col = imagecolorallocatealpha($logoimg, 255, 255, 255, 127);
        imagefill($logoimg, 0, 0, $col);
        $white = imagecolorallocate($logoimg, $rgbColors[0], $rgbColors[1], $rgbColors[2]); //for font color
        $x = 0;
        $y = $fontsize;
        $angle = 0;
        $bbox = imagettftext($logoimg, $fontsize, $angle, $x, $y, $white, $font, $text); //fill text in your image
        $boxWidth = $bbox[4] - $bbox[0];
        $boxHeight = $bbox[7] - $bbox[1];
        imagedestroy($logoimg);
        //--------------------------------------------
        // CREATE THE PNG
        //--------------------------------------------
        $imageWidth = abs($boxWidth);
        $imageHeight = abs($boxHeight);
        $logoimg = imagecreatetruecolor($imageWidth, $imageHeight);
        imagealphablending($logoimg, false);
        imagesavealpha($logoimg, true);
        $col = imagecolorallocatealpha($logoimg, 255, 255, 255, 127);
        imagefill($logoimg, 0, 0, $col);
        $white = imagecolorallocate($logoimg, $rgbColors[0], $rgbColors[1], $rgbColors[2]); //for font color
        $x = 0;
        $y = $fontsize;
        $angle = 0;
        imagettftext($logoimg, $fontsize, $angle, $x, $y, $white, $font, $text); //fill text in your image
        imagepng($logoimg); //save your image at new location $target
        imagedestroy($logoimg);
    }
}

Note: if you don't use the universe framework, you will need to replace this line:

$rgbColors = ConvertTool::convertHexColorToRgb($hexColor);

With this code:

$rgbColors = sscanf($hexColor, "%02x%02x%02x");

In which case your hex color must be exactly 6 chars long (don't put the hash symbol (#) in front of it).

Note: in the end, I did not use this service, because I found that the font was ugly and worse: it was not possible to select the text. But for the sake of this discussion I thought this code was worth sharing...

Filter Excel pivot table using VBA

Configure the pivot table so that it is like this:

enter image description here

Your code can simply work on range("B1") now and the pivot table will be filtered to you required SavedFamilyCode

Sub FilterPivotTable()
Application.ScreenUpdating = False
    ActiveSheet.Range("B1") = "K123224"
Application.ScreenUpdating = True
End Sub

Hexadecimal value 0x00 is a invalid character

Without your actual data or source, it will be hard for us to diagnose what is going wrong. However, I can make a few suggestions:

  • Unicode NUL (0x00) is illegal in all versions of XML and validating parsers must reject input that contains it.
  • Despite the above; real-world non-validated XML can contain any kind of garbage ill-formed bytes imaginable.
  • XML 1.1 allows zero-width and nonprinting control characters (except NUL), so you cannot look at an XML 1.1 file in a text editor and tell what characters it contains.

Given what you wrote, I suspect whatever converts the database data to XML is broken; it's propagating non-XML characters.

Create some database entries with non-XML characters (NULs, DELs, control characters, et al.) and run your XML converter on it. Output the XML to a file and look at it in a hex editor. If this contains non-XML characters, your converter is broken. Fix it or, if you cannot, create a preprocessor that rejects output with such characters.

If the converter output looks good, the problem is in your XML consumer; it's inserting non-XML characters somewhere. You will have to break your consumption process into separate steps, examine the output at each step, and narrow down what is introducing the bad characters.

Check file encoding (for UTF-16)

Update: I just ran into an example of this myself! What was happening is that the producer was encoding the XML as UTF16 and the consumer was expecting UTF8. Since UTF16 uses 0x00 as the high byte for all ASCII characters and UTF8 doesn't, the consumer was seeing every second byte as a NUL. In my case I could change encoding, but suggested all XML payloads start with a BOM.

Best way to encode Degree Celsius symbol into web page?

If using Java-JSP, What worked for me is to paste below in JSP page

<%@ page contentType="text/html; charset=UTF-8" %>

How to make the Facebook Like Box responsive?

NOTE: Colin's solution didn't work for me. Facebook may have changed their markup. Using * should be more future-proof.

Wrap the Like box with a div:

<div id="likebox-wrapper">
    <iframe src="..."></iframe> <!-- likebox code -->
</div>

and add this to your css file:

#likebox-wrapper * {
   width: 100% !important;
}

Detecting value change of input[type=text] in jQuery

Try this.. credits to https://stackoverflow.com/users/1169519/teemu

for answering my question here: https://stackoverflow.com/questions/24651811/jquery-keyup-doesnt-work-with-keycode-filtering?noredirect=1#comment38213480_24651811

This solution helped me to progress on my project.

$("#your_textbox").on("input propertychange",function(){

   // Do your thing here.
});

Note: propertychange for lower versions of IE.

fast way to copy formatting in excel

Remember that when you write:

MyArray = Range("A1:A5000")

you are really writing

MyArray = Range("A1:A5000").Value

You can also use names:

MyArray = Names("MyWSTable").RefersToRange.Value

But Value is not the only property of Range. I have used:

MyArray = Range("A1:A5000").NumberFormat

I doubt

MyArray = Range("A1:A5000").Font

would work but I would expect

MyArray = Range("A1:A5000").Font.Bold

to work.

I do not know what formats you want to copy so you will have to try.

However, I must add that when you copy and paste a large range, it is not as much slower than doing it via an array as we all thought.

Post Edit information

Having posted the above I tried by own advice. My experiments with copying Font.Color and Font.Bold to an array have failed.

Of the following statements, the second would fail with a type mismatch:

  ValueArray = .Range("A1:T5000").Value
  ColourArray = .Range("A1:T5000").Font.Color

ValueArray must be of type variant. I tried both variant and long for ColourArray without success.

I filled ColourArray with values and tried the following statement:

  .Range("A1:T5000").Font.Color = ColourArray

The entire range would be coloured according to the first element of ColourArray and then Excel looped consuming about 45% of the processor time until I terminated it with the Task Manager.

There is a time penalty associated with switching between worksheets but recent questions about macro duration have caused everyone to review our belief that working via arrays was substantially quicker.

I constructed an experiment that broadly reflects your requirement. I filled worksheet Time1 with 5000 rows of 20 cells which were selectively formatted as: bold, italic, underline, subscript, bordered, red, green, blue, brown, yellow and gray-80%.

With version 1, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" using copy.

With version 2, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" by copying the value and the colour via an array.

With version 3, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" by copying the formula and the colour via an array.

Version 1 took an average of 12.43 seconds, version 2 took an average of 1.47 seconds while version 3 took an average of 1.83 seconds. Version 1 copied formulae and all formatting, version 2 copied values and colour while version 3 copied formulae and colour. With versions 1 and 2 you could add bold and italic, say, and still have some time in hand. However, I am not sure it would be worth the bother given that copying 21,300 values only takes 12 seconds.

** Code for Version 1**

I do not think this code includes anything that needs an explanation. Respond with a comment if I am wrong and I will fix.

Sub SelectionCopyAndPaste()

  Dim ColDestCrnt As Integer
  Dim ColSrcCrnt As Integer
  Dim NumSelect As Long
  Dim RowDestCrnt As Integer
  Dim RowSrcCrnt As Integer
  Dim StartTime As Single

  Application.ScreenUpdating = False
  Application.Calculation = xlCalculationManual
  NumSelect = 1
  ColDestCrnt = 1
  RowDestCrnt = 1
  With Sheets("Time2")
    .Range("A1:T715").EntireRow.Delete
  End With
  StartTime = Timer
  Do While True
    ColSrcCrnt = (NumSelect Mod 20) + 1
    RowSrcCrnt = (NumSelect - ColSrcCrnt) / 20 + 1
    If RowSrcCrnt > 5000 Then
      Exit Do
    End If
    Sheets("Time1").Cells(RowSrcCrnt, ColSrcCrnt).Copy _
                 Destination:=Sheets("Time2").Cells(RowDestCrnt, ColDestCrnt)
    If ColDestCrnt = 20 Then
      ColDestCrnt = 1
      RowDestCrnt = RowDestCrnt + 1
    Else
     ColDestCrnt = ColDestCrnt + 1
    End If
    NumSelect = NumSelect + 7
  Loop
  Debug.Print Timer - StartTime
  ' Average 12.43 secs
  Application.Calculation = xlCalculationAutomatic

End Sub

** Code for Versions 2 and 3**

The User type definition must be placed before any subroutine in the module. The code works through the source worksheet copying values or formulae and colours to the next element of the array. Once selection has been completed, it copies the collected information to the destination worksheet. This avoids switching between worksheets more than is essential.

Type ValueDtl
  Value As String
  Colour As Long
End Type

Sub SelectionViaArray()

  Dim ColDestCrnt As Integer
  Dim ColSrcCrnt As Integer
  Dim InxVLCrnt As Integer
  Dim InxVLCrntMax As Integer
  Dim NumSelect As Long
  Dim RowDestCrnt As Integer
  Dim RowSrcCrnt As Integer
  Dim StartTime As Single
  Dim ValueList() As ValueDtl

  Application.ScreenUpdating = False
  Application.Calculation = xlCalculationManual

  ' I have sized the array to more than I expect to require because ReDim
  ' Preserve is expensive.  However, I will resize if I fill the array.
  ' For my experiment I know exactly how many elements I need but that
  ' might not be true for you.
  ReDim ValueList(1 To 25000)

  NumSelect = 1
  ColDestCrnt = 1
  RowDestCrnt = 1
  InxVLCrntMax = 0      ' Last used element in ValueList.
  With Sheets("Time2")
    .Range("A1:T715").EntireRow.Delete
  End With
  StartTime = Timer
  With Sheets("Time1")
    Do While True
      ColSrcCrnt = (NumSelect Mod 20) + 1
      RowSrcCrnt = (NumSelect - ColSrcCrnt) / 20 + 1
      If RowSrcCrnt > 5000 Then
        Exit Do
      End If
      InxVLCrntMax = InxVLCrntMax + 1
      If InxVLCrntMax > UBound(ValueList) Then
        ' Resize array if it has been filled 
        ReDim Preserve ValueList(1 To UBound(ValueList) + 1000)
      End If
      With .Cells(RowSrcCrnt, ColSrcCrnt)
        ValueList(InxVLCrntMax).Value = .Value              ' Version 2
        ValueList(InxVLCrntMax).Value = .Formula            ' Version 3
        ValueList(InxVLCrntMax).Colour = .Font.Color
      End With
      NumSelect = NumSelect + 7
    Loop
  End With
  With Sheets("Time2")
    For InxVLCrnt = 1 To InxVLCrntMax
      With .Cells(RowDestCrnt, ColDestCrnt)
        .Value = ValueList(InxVLCrnt).Value                 ' Version 2
        .Formula = ValueList(InxVLCrnt).Value               ' Version 3
        .Font.Color = ValueList(InxVLCrnt).Colour
      End With
      If ColDestCrnt = 20 Then
        ColDestCrnt = 1
        RowDestCrnt = RowDestCrnt + 1
      Else
       ColDestCrnt = ColDestCrnt + 1
      End If
    Next
  End With
  Debug.Print Timer - StartTime
  ' Version 2 average 1.47 secs
  ' Version 3 average 1.83 secs
  Application.Calculation = xlCalculationAutomatic

End Sub

Copy an entire worksheet to a new worksheet in Excel 2010

' Assume that the code name the worksheet is Sheet1

' Copy the sheet using code name and put in the end.
' Note: Using the code name lets the user rename the worksheet without breaking the VBA code
Sheet1.Copy After:=Sheets(Sheets.Count)

' Rename the copied sheet keeping the same name and appending a string " copied"
ActiveSheet.Name = Sheet1.Name & " copied"

How do I sort a table in Excel if it has cell references in it?

Put a dollar sign in front of the row and/or column of the cell you want to remain constant.

Fixed it for me!

How to detect when a youtube video finishes playing?

What you may want to do is include a script on all pages that does the following ... 1. find the youtube-iframe : searching for it by width and height by title or by finding www.youtube.com in its source. You can do that by ... - looping through the window.frames by a for-in loop and then filter out by the properties

  1. inject jscript in the iframe of the current page adding the onYoutubePlayerReady must-include-function http://shazwazza.com/post/Injecting-JavaScript-into-other-frames.aspx

  2. Add the event listeners etc..

Hope this helps

Copying and pasting data using VBA code

Use the PasteSpecial method:

sht.Columns("A:G").Copy
Range("A1").PasteSpecial Paste:=xlPasteValues

BUT your big problem is that you're changing your ActiveSheet to "Data" and not changing it back. You don't need to do the Activate and Select, as per my code (this assumes your button is on the sheet you want to copy to).

CUDA incompatible with my gcc version

If you encounter this error, please read the log file:

$ cat /var/log/cuda-installer.log 
[INFO]: Driver installation detected by command: apt list --installed | grep -e nvidia-driver-[0-9][0-9][0-9] -e nvidia-[0-9][0-9][0-9]
[INFO]: Cleaning up window
[INFO]: Complete
[INFO]: Checking compiler version...
[INFO]: gcc location: /usr/bin/gcc

[INFO]: gcc version: gcc version 9.2.1 20191008 (Ubuntu 9.2.1-9ubuntu2) 

[ERROR]: unsupported compiler version: 9.2.1. Use --override to override this check.

Just follow the suggestion in the log file:

sudo sh cuda_<version>_linux.run --override

Job done :)

I just installed CUDA 10.2 with gcc 9.2 on Kubuntu 19.10 using the --override option.

How to import data from one sheet to another

Saw this thread while looking for something else and I know it is super old, but I wanted to add my 2 cents.

NEVER USE VLOOKUP. It's one of the worst performing formulas in excel. Use index match instead. It even works without sorting data, unless you have a -1 or 1 in the end of the match formula (explained more below)

Here is a link with the appropriate formulas.

The Sheet 2 formula would be this: =IF(A2="","",INDEX(Sheet1!B:B,MATCH($A2,Sheet1!$A:$A,0)))

  • IF(A2="","", means if A2 is blank, return a blank value
  • INDEX(Sheet1!B:B, is saying INDEX B:B where B:B is the data you want to return. IE the name column.
  • Match(A2, is saying to Match A2 which is the ID you want to return the Name for.
  • Sheet1!A:A, is saying you want to match A2 to the ID column in the previous sheet
  • ,0)) is specifying you want an exact value. 0 means return an exact match to A2, -1 means return smallest value greater than or equal to A2, 1 means return the largest value that is less than or equal to A2. Keep in mind -1 and 1 have to be sorted.

More information on the Index/Match formula

Other fun facts: $ means absolute in a formula. So if you specify $B$1 when filling a formula down or over keeps that same value. If you over $B1, the B remains the same across the formula, but if you fill down, the 1 increases with the row count. Likewise, if you used B$1, filling to the right will increment the B, but keep the reference of row 1.

I also included the use of indirect in the second section. What indirect does is allow you to use the text of another cell in a formula. Since I created a named range sheet1!A:A = ID, sheet1!B:B = Name, and sheet1!C:C=Price, I can use the column name to have the exact same formula, but it uses the column heading to change the search criteria.

Good luck! Hope this helps.

How do I load a file into the python console?

You can just use an import statement:

from file import *

So, for example, if you had a file named my_script.py you'd load it like so:

from my_script import *

a href link for entire div in HTML/CSS

This can be done in many ways. a. Using nested inside a tag.

<a href="link1.html">
   <div> Something in the div </div>
 </a>

b. Using the Inline JavaScript Method

<div onclick="javascript:window.location.href='link1.html' "> 
  Some Text 
</div>

c. Using jQuery inside tag

HTML:

<div class="demo" > Some text here </div>

jQuery:

$(".demo").click( function() {
  window.location.href="link1.html";
 });

Android: java.lang.SecurityException: Permission Denial: start Intent

I solved this exception by changing the target sdk version from 19 onwards kitkat version AndroidManifest.xml.

<uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

Delete newline in Vim

As other answers mentioned, (upper case) J and search + replace for \n can be used generally to strip newline characters and to concatenate lines.

But in order to get rid of the trailing newline character in the last line, you need to do this in Vim:

:set noendofline binary
:w

How to detect Ctrl+V, Ctrl+C using JavaScript?

Short solution for preventing user from using context menu, copy and cut in jQuery:

jQuery(document).bind("cut copy contextmenu",function(e){
    e.preventDefault();
});

Also disabling text selection in CSS might come handy:

.noselect {  
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
     user-select: none;
}

How to access SVG elements with Javascript

In case you use jQuery you need to wait for $(window).load, because the embedded SVG document might not be yet loaded at $(document).ready

$(window).load(function () {

    //alert("Document loaded, including graphics and embedded documents (like SVG)");
    var a = document.getElementById("alphasvg");

    //get the inner DOM of alpha.svg
    var svgDoc = a.contentDocument;

    //get the inner element by id
    var delta = svgDoc.getElementById("delta");
    delta.addEventListener("mousedown", function(){ alert('hello world!')}, false);
});

Turning off auto indent when pasting text into vim

Please read this article: Toggle auto-indenting for code paste

Some people like the visual feedback shown in the status line by the following alternative for your vimrc:

nnoremap <F2> :set invpaste paste?<CR>
set pastetoggle=<F2>
set showmode

Excel VBA App stops spontaneously with message "Code execution has been halted"

I have found a 2nd solution.

  1. Press "Debug" button in the popup.
  2. Press Ctrl+Pause|Break twice.
  3. Hit the play button to continue.
  4. Save the file after completion.

Hope this helps someone.

How can I convert an HTML table to CSV?

This is based on atomicules' answer but more succinct and also processes th (header) cells as well as td cells. I also added the strip method to get rid of the extra whitespaces.

CSV.open("output.csv", 'w') do |csv|
  doc.xpath('//table//tr').each do |row|
    csv << row.xpath('th|td').map {|cell| cell.text.strip}
  end
end

Wrapping the code inside the CSV block ensures that the file will be closed properly.


If you just want the text and don't need to write it to a file, you can use this:

doc.xpath('//table//tr').inject('') do |result, row|
  result << row.xpath('th|td').map {|cell| cell.text.strip}.to_csv
end

Disable pasting text into HTML form

Don't do it. Don't mess with the user's browser. By Copy + Pasting into an E-Mail confirmation field, the user accepts responsibility over what they type. If they are dumb enough to copy + paste a faulty address (it has happened to me) then it's their own damn fault.

If you want to make sure that the E-Mail confirmation works out, have the user check their E-Mail while your site waits ("Please open your webmail program in a new window"). Show the E-Mail address in big fat letters ("The confirmation E-Mail was sent to.... made an error? CLick here to change).

Even better, if you can, let the user have some kind of limited access without confirming. That way, they can log in straight away and you improve your chances to keep in touch with the visitor even if the confirmation mail is blocked due to other reasons (e.g. spam filters).

#pragma once vs include guards?

I think the first thing you should do is check to see if this is really going to make a difference, ie. you should first test the performance. One of the searches in google threw up this.

In the results page, the columns are sligthly off for me, but it's clear that at least up to VC6 microsoft was not implementing the include guard optimisations that the other tools were using. Where the include guard was internal it took 50 times as long compared with where the include guard was external (external include guards are at least as good as #pragma). But let's consider the possible affect of this:

According to the tables presented, the time to open the include and check it is 50 times that of a #pragma equivalent. But the actual time to do so was measured at 1 microsecond per file back in 1999!

So, how many duplicate headers will a single TU have? This depends on your style, but if we say that an average TU has 100 duplicates then in 1999 we're potentially paying 100 microseconds per TU. With HDD improvements this is probably significantly lower by now, but even then with precompiled headers and correct dependency tracking the total cumulative cost of this for a project is almost certainly an insigificant part of your build time.

Now, on the flip side, as unlikely as it may be, if you ever move to a compiler that doesn't support #pragma once then consider how much time will it take to update your entire source base to have include guards rather than #pragma?

There is no reason that Microsoft could not implement an include guard optimisation in the same way that GCC and every other compiler does (actually can anybody confirm if their more recent versions implement this?). IMHO, #pragma once does very little other than limit your choice of alternative compiler.

Java properties UTF-8 encoding in Eclipse

This seems to work only for some characters ... including special characters for German, Portuguese, French. However, I ran into trouble with Russian, Hindi and Mandarin characters. These are not converted to Properties format 'native2ascii', instead get saved with ?? ?? ??
The only way I could get my app to display these characters correctly is by putting them in the properties file translated to UTF-8 format - as \u0915 instead of ?, or \u044F instead of ?. Any advice?

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

I've recently found that command prompt has support for context menu via the right mouse click. You can find more details here: http://www.askdavetaylor.com/copy_paste_within_microsoft_windows_command_prompt.html

Return multiple values from a function in swift

Update Swift 4.1

Here we create a struct to implement the Tuple usage and validate the OTP text length. That needs to be of 2 fields for this example.

struct ValidateOTP {
var code: String
var isValid: Bool }

func validateTheOTP() -> ValidateOTP {
    let otpCode = String(format: "%@%@", txtOtpField1.text!, txtOtpField2.text!)
    if otpCode.length < 2 {
        return ValidateOTP(code: otpCode, isValid: false)
    } else {
        return ValidateOTP(code: otpCode, isValid: true)
    }
}

Usage:

let isValidOTP = validateTheOTP()
    if isValidOTP.isValid { print(" valid OTP") } else {   self.alert(msg: "Please fill the valid OTP", buttons: ["Ok"], handler: nil)
    }

Hope it helps!

Thanks

Latex - Change margins of only a few pages

A slight modification of this to change the \voffset works for me:

\newenvironment{changemargin}[1]{
  \begin{list}{}{
    \setlength{\voffset}{#1}
  }
  \item[]}{\end{list}}

And then put your figures in a \begin{changemargin}{-1cm}...\end{changemargin} environment.

Allow click on twitter bootstrap dropdown toggle link?

Since there is not really an answer that works (selected answer disables dropdown), or overrides using javascript, here goes.

This is all html and css fix (uses two <a> tags):

<ul class="nav">
 <li class="dropdown dropdown-li">
    <a class="dropdown-link" href="http://google.com">Dropdown</a>
    <a class="dropdown-caret dropdown-toggle"><b class="caret"></b></a>
    <ul class="dropdown-menu">
        <li><a href="#">Link 1</a></li>
        <li><a href="#">Link 2</a></li>
    </ul>
 </li>
</ul>

Now here's the CSS you need.

.dropdown-li {
    display:inline-block !important;
}
.dropdown-link {
    display:inline-block !important; 
    padding-right:4px !important;
}
.dropdown-caret {
    display:inline-block !important; 
    padding-left:4px !important;
}

Assuming you will want the both <a> tags to highlight on hover of either one, you will also need to override bootstrap, you might play around with the following:

.nav > li:hover {
    background-color: #f67a47; /*hover background color*/
}
.nav > li:hover > a {
    color: white; /*hover text color*/
}
.nav > li:hover > ul > a {
    color: black; /*dropdown item text color*/
}

What is two way binding?

McGarnagle has a great answer, and you'll want to be accepting his, but I thought I'd mention (since you asked) how databinding works.

It's generally implemented by firing events whenever a change is made to the data, which then causes listeners (e.g. the UI) to be updated.

Two-way binding works by doing this twice, with a bit of care taken to ensure that you don't wind up stuck in an event loop (where the update from the event causes another event to be fired).

I was gonna put this in a comment, but it was getting pretty long...

AngularJS - Multiple ng-view in single template

It is possible to have multiple or nested views. But not by ng-view.

The primary routing module in angular does not support multiple views. But you can use ui-router. This is a third party module which you can get via Github, angular-ui/ui-router, https://github.com/angular-ui/ui-router . Also a new version of ngRouter (ngNewRouter) currently, is being developed. It is not stable at the moment. So I provide you a simple start up example with ui-router. Using it you can name views and specify which templates and controllers should be used for rendering them. Using $stateProvider you should specify how view placeholders should be rendered for specific state.

<body ng-app="main">
    <script type="text/javascript">
    angular.module('main', ['ui.router'])
    .config(['$locationProvider', '$stateProvider', function ($locationProvider, $stateProvider) {
        $stateProvider
        .state('home', {
            url: '/',
            views: {
                'header': {
                    templateUrl: '/app/header.html'
                },
                'content': {
                    templateUrl: '/app/content.html'
                }
            }
        });
    }]);
    </script>
    <a ui-sref="home">home</a>
    <div ui-view="header">header</div>
    <div ui-view="content">content</div>
    <div ui-view="bottom">footer</div>
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/angular-ui-router/release/angular-ui-router.js">
</body>

You need referencing angularjs, and angular-ui.router for this sample.

$ bower install angular-ui-router

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

You can see some reports in SSMS:

Right-click the instance name / reports / standard / top sessions

You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.

You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.

This article looks promising.

Some stackoverflow goodness from Mr. Ozar.

edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.

Get all column names of a DataTable into string array using (LINQ/Predicate)

I'd suggest using such extension method:

public static class DataColumnCollectionExtensions
{
    public static IEnumerable<DataColumn> AsEnumerable(this DataColumnCollection source)
    {
        return source.Cast<DataColumn>();
    }
}

And therefore:

string[] columnNames = dataTable.Columns.AsEnumerable().Select(column => column.Name).ToArray();

You may also implement one more extension method for DataTable class to reduce code:

public static class DataTableExtensions
{
    public static IEnumerable<DataColumn> GetColumns(this DataTable source)
    {
        return source.Columns.AsEnumerable();
    }
}

And use it as follows:

string[] columnNames = dataTable.GetColumns().Select(column => column.Name).ToArray();

Difference Between One-to-Many, Many-to-One and Many-to-Many?

1) The circles are Entities/POJOs/Beans

2) deg is an abbreviation for degree as in graphs (number of edges)

PK=Primary key, FK=Foreign key

Note the contradiction between the degree and the name of the side. Many corresponds to degree=1 while One corresponds to degree >1.

Illustration of one-to-many many-to-one

How to drop all stored procedures at once in SQL Server database?

ANSI compliant, without cursor

DECLARE @SQL national character varying(MAX) 
SET @SQL= ''

SELECT @SQL= @SQL+ N'DROP PROCEDURE "' + REPLACE(SPECIFIC_SCHEMA, N'"', N'""') + N'"."' + REPLACE(SPECIFIC_NAME, N'"', N'""') + N'"; '
FROM INFORMATION_SCHEMA.ROUTINES 

WHERE (1=1) 
AND ROUTINE_TYPE = 'PROCEDURE' 
AND ROUTINE_NAME NOT IN 
(
     'dt_adduserobject'
    ,'dt_droppropertiesbyid'
    ,'dt_dropuserobjectbyid'
    ,'dt_generateansiname'
    ,'dt_getobjwithprop'
    ,'dt_getobjwithprop_u'
    ,'dt_getpropertiesbyid'
    ,'dt_getpropertiesbyid_u'
    ,'dt_setpropertybyid'
    ,'dt_setpropertybyid_u'
    ,'dt_verstamp006'
    ,'dt_verstamp007'

    ,'sp_helpdiagrams'
    ,'sp_creatediagram'
    ,'sp_alterdiagram'
    ,'sp_renamediagram'
    ,'sp_dropdiagram'

    ,'sp_helpdiagramdefinition'
    ,'fn_diagramobjects'
    ,'sp_upgraddiagrams'
) 


ORDER BY SPECIFIC_NAME 


-- PRINT @SQL
EXEC(@SQL) 

Without cursor, non-ansi compliant:

DECLARE @sql NVARCHAR(MAX) = N''
, @lineFeed NVARCHAR(2) = CHAR(13) + CHAR(10) ;

SELECT @sql = @sql + N'DROP PROCEDURE ' + QUOTENAME(SPECIFIC_SCHEMA) + N'.' + QUOTENAME(SPECIFIC_NAME) + N';' + @lineFeed
FROM INFORMATION_SCHEMA.ROUTINES 
WHERE ROUTINE_TYPE = 'PROCEDURE' 
-- AND SPECIFIC_NAME LIKE 'sp[_]RPT[_]%'


AND ROUTINE_NAME NOT IN 
( 
    SELECT name FROM sys.procedures WHERE is_ms_shipped <> 0 
) 


ORDER BY SPECIFIC_NAME 


-- PRINT @sql 
EXECUTE(@sql)

Mapping US zip code to time zone

If you want, you can also get a feel for the timezone by asking the browser Josh Fraser has a nice write up on it here

var rightNow = new Date();
var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
var temp = jan1.toGMTString();
var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);

The second thing that you need to know is whether the location observes daylight savings time (DST) or not. Since DST is always observed during the summer, we can compare the time offset between two dates in January, to the time offset between two dates in June. If the offsets are different, then we know that the location observes DST. If the offsets are the same, then we know that the location DOES NOT observe DST.

var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
temp = june1.toGMTString();
var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
var dst;
if (std_time_offset == daylight_time_offset) {
    dst = "0"; // daylight savings time is NOT observed
} else {
    dst = "1"; // daylight savings time is observed
}

All credit for this goes to Josh Fraser.

This might help you with customers outside the US, and it might complement your zip approach.

Here is a SO questions that touch on getting the timezone from javascript

Configure WAMP server to send email

You need a SMTP server to send your mail. If you have one available which does not require SMTP authentification (maybe your ISP's?) just edit the 'SMTP' ([mail function]) setting in your php.ini file.

If this is no option because your SMTP server requires authentification you won't be able to use the internal mail() function and have to use some 3rd party class which supports smtp auth. e.g. http://pear.php.net/package/Mail/

How can I check if a MySQL table exists with PHP?

It was already posted but here it is with PDO (same query)...

$connection = new PDO ( "mysql:host=host_db; dbname=name_db", user_db, pass_db );

if ($connection->query ("DESCRIBE table_name"  )) {
    echo "exist";
} else {
    echo "doesn't exist";
}

Works like a charm for me....

And here's another approach (i think it is slower)...

if ($connection->query ( "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'db_name' AND table_name ='tbl_name'" )->fetch ()) {
    echo "exist";
} else {
    echo "doesn't exist";
}

You can also play with this query:

SHOW TABLE STATUS FROM db_name LIKE 'tbl_name'

I think this was suggested to use in the mysql page.

How does the Java 'for each' loop work?

As defined in JLS for-each loop can have two forms:

  1. If the type of Expression is a subtype of Iterable then translation is as:

    List<String> someList = new ArrayList<String>();
    someList.add("Apple");
    someList.add("Ball");
    for (String item : someList) {
        System.out.println(item);
    }
    
    // IS TRANSLATED TO:
    
    for(Iterator<String> stringIterator = someList.iterator(); stringIterator.hasNext(); ) {
        String item = stringIterator.next();
        System.out.println(item);
    }
    
  2. If the Expression necessarily has an array type T[] then:

    String[] someArray = new String[2];
    someArray[0] = "Apple";
    someArray[1] = "Ball";
    
    for(String item2 : someArray) {
        System.out.println(item2);
    }
    
    // IS TRANSLATED TO:
    for (int i = 0; i < someArray.length; i++) {
        String item2 = someArray[i];
        System.out.println(item2);
    }
    

Java 8 has introduced streams which perform generally better. We can use them as:

someList.stream().forEach(System.out::println);
Arrays.stream(someArray).forEach(System.out::println);

ImportError: No Module named simplejson

Sometimes there is permission errors. Try:

sudo pip install simplejson

Hope it helps.

How to convert Django Model object to dict with its fields and values?

@Zags solution was gorgeous!

I would add, though, a condition for datefields in order to make it JSON friendly.

Bonus Round

If you want a django model that has a better python command-line display, have your models child class the following:

from django.db import models
from django.db.models.fields.related import ManyToManyField

class PrintableModel(models.Model):
    def __repr__(self):
        return str(self.to_dict())

    def to_dict(self):
        opts = self._meta
        data = {}
        for f in opts.concrete_fields + opts.many_to_many:
            if isinstance(f, ManyToManyField):
                if self.pk is None:
                    data[f.name] = []
                else:
                    data[f.name] = list(f.value_from_object(self).values_list('pk', flat=True))
            elif isinstance(f, DateTimeField):
                if f.value_from_object(self) is not None:
                    data[f.name] = f.value_from_object(self).timestamp()
            else:
                data[f.name] = None
            else:
                data[f.name] = f.value_from_object(self)
        return data

    class Meta:
        abstract = True

So, for example, if we define our models as such:

class OtherModel(PrintableModel): pass

class SomeModel(PrintableModel):
    value = models.IntegerField()
    value2 = models.IntegerField(editable=False)
    created = models.DateTimeField(auto_now_add=True)
    reference1 = models.ForeignKey(OtherModel, related_name="ref1")
    reference2 = models.ManyToManyField(OtherModel, related_name="ref2")

Calling SomeModel.objects.first() now gives output like this:

{'created': 1426552454.926738,
'value': 1, 'value2': 2, 'reference1': 1, u'id': 1, 'reference2': [1]}

Minimum and maximum value of z-index?

Out of experience, I think the correct maximum z-index is 2147483638.

Calling one method from another within same class in Python

To call the method, you need to qualify function with self.. In addition to that, if you want to pass a filename, add a filename parameter (or other name you want).

class MyHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        srcpath = event.src_path
        print (srcpath, 'has been ',event.event_type)
        print (datetime.datetime.now())
        filename = srcpath[12:]
        self.dropbox_fn(filename) # <----

    def dropbox_fn(self, filename):  # <-----
        print('In dropbox_fn:', filename)

How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

First, what you are looking for is a column or bar diagram, not really a histogram. A histogram is made from a frequency distribution of a continuous variable that is separated into bins. Here you have a column against separate labels.

To make a bar diagram with matplotlib, use the matplotlib.pyplot.bar() method. Have a look at this page of the matplotlib documentation that explains very well with examples and source code how to do it.

If it is possible though, I would just suggest that for a simple task like this if you could avoid writing code that would be better. If you have any spreadsheet program this should be a piece of cake because that's exactly what they are for, and you won't have to 'reinvent the wheel'. The following is the plot of your data in Excel:

Bar diagram plot in Excel

I just copied your data from the question, used the text import wizard to put it in two columns, then I inserted a column diagram.

What is the difference between char * const and const char *?

Rule of thumb: read the definition from right to left!


const int *foo;

Means "foo points (*) to an int that cannot change (const)".
To the programmer this means "I will not change the value of what foo points to".

  • *foo = 123; or foo[0] = 123; would be invalid.
  • foo = &bar; is allowed.

int *const foo;

Means "foo cannot change (const) and points (*) to an int".
To the programmer this means "I will not change the memory address that foo refers to".

  • *foo = 123; or foo[0] = 123; is allowed.
  • foo = &bar; would be invalid.

const int *const foo;

Means "foo cannot change (const) and points (*) to an int that cannot change (const)".
To the programmer this means "I will not change the value of what foo points to, nor will I change the address that foo refers to".

  • *foo = 123; or foo[0] = 123; would be invalid.
  • foo = &bar; would be invalid.

Modulo operator in Python

Same thing you'd expect from normal modulo .. e.g. 7 % 4 = 3, 7.3 % 4.0 = 3.3

Beware of floating point accuracy issues.

What is the iOS 5.0 user agent string?

I use the following to detect different mobile devices, viewport and screen. Works quite well for me, might be helpful to others:

var pixelRatio = window.devicePixelRatio || 1;

var viewport = {
    width: window.innerWidth,
    height: window.innerHeight
};

var screen = {
    width: window.screen.availWidth * pixelRatio,
    height: window.screen.availHeight * pixelRatio
};

var iPhone = /iPhone/i.test(navigator.userAgent);
var iPhone4 = (iPhone && pixelRatio == 2);
var iPhone5 = /iPhone OS 5_0/i.test(navigator.userAgent);
var iPad = /iPad/i.test(navigator.userAgent);
var android = /android/i.test(navigator.userAgent);
var webos = /hpwos/i.test(navigator.userAgent);
var iOS = iPhone || iPad;
var mobile = iOS || android || webos;

window.devicePixelRatio is the ratio between physical pixels and device-independent pixels (dips) on the device. window.devicePixelRatio = physical pixels / dips.

More info here.

From Arraylist to Array

One approach would be to add the Second for Loop where the printing is being done inside the first for loop. Like this:

static String[] SENTENCE; 

public static void main(String []args) throws Exception{

   Scanner sentence = new Scanner(new File("assets/blah.txt"));
   ArrayList<String> sentenceList = new ArrayList<String>();

   while (sentence.hasNextLine())
   {
       sentenceList.add(sentence.nextLine());
   }

   sentence.close();

   String[] sentenceArray = sentenceList.toArray(new String[sentenceList.size()]);
  // System.out.println(sentenceArray.length);
   for (int r=0;r<sentenceArray.length;r++)
   {
       SENTENCE = sentenceArray[r].split("(?<=[.!?])\\s*"); //split sentences and store in array 

       for (int i=0;i<SENTENCE.length;i++)
       {
           System.out.println("Sentence " + (i+1) + ": " + SENTENCE[i]);
       }
   }    

}

When creating a service with sc.exe how to pass in context parameters?

If you tried all of the above and still can't pass args to your service, if your service was written in C/C++, here's what could be the problem: when you start your service through "sc start arg1 arg2...", SC calls your service's ServiceMain function directly with those args. But when Windows start your service (at boot time, for example), it's your service's main function (_tmain) that's called, with params from the registry's "binPath".

What is the default value for Guid?

The default value for a GUID is empty. (eg: 00000000-0000-0000-0000-000000000000)

This can be invoked using Guid.Empty or new Guid()

If you want a new GUID, you use Guid.NewGuid()

Have nginx access_log and error_log log to STDOUT and STDERR of master process

Syntax: error_log file | stderr | syslog:server=address[,parameter=value] | memory:size [debug | info | notice | warn | error | crit | alert | emerg];
Default:    
error_log logs/error.log error;
Context:    main, http, stream, server, location

http://nginx.org/en/docs/ngx_core_module.html#error_log

Don't use: /dev/stderr This will break your setup if you're going to use systemd-nspawn.

What does ON [PRIMARY] mean?

ON [PRIMARY] will create the structures on the "Primary" filegroup. In this case the primary key index and the table will be placed on the "Primary" filegroup within the database.

Transport security has blocked a cleartext HTTP

Transport security is available on iOS 9.0 or later. You may have this warning when trying to call a WS inside your application:

Application Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.

Adding the following to your Info.plist will disable ATS:

<key>NSAppTransportSecurity</key>
<dict>
     <key>NSAllowsArbitraryLoads</key><true/>
</dict>

Query to get only numbers from a string

This UDF will work for all types of strings:

CREATE FUNCTION udf_getNumbersFromString (@string varchar(max))
RETURNS varchar(max)
AS
BEGIN
    WHILE  @String like '%[^0-9]%'
    SET    @String = REPLACE(@String, SUBSTRING(@String, PATINDEX('%[^0-9]%', @String), 1), '')
    RETURN @String
END

Convert Unix timestamp to a date string

Python:

python -c "from datetime import datetime; print(datetime.fromtimestamp($TIMESTAMP))"

SSL: CERTIFICATE_VERIFY_FAILED with Python3

On Debian 9 I had to:

$ sudo update-ca-certificates --fresh
$ export SSL_CERT_DIR=/etc/ssl/certs

I'm not sure why, but this enviroment variable was never set.

JUnit 4 compare Sets

Apache commons to the rescue again.

assertTrue(CollectionUtils.isEqualCollection(coll1, coll2));

Works like a charm. I don't know why but I found that with collections the following assertEquals(coll1, coll2) doesn't always work. In the case where it failed for me I had two collections backed by Sets. Neither hamcrest nor junit would say the collections were equal even though I knew for sure that they were. Using CollectionUtils it works perfectly.

Difference between float and decimal data type

This is what I found when I had this doubt.

mysql> create table numbers (a decimal(10,2), b float);
mysql> insert into numbers values (100, 100);
mysql> select @a := (a/3), @b := (b/3), @a * 3, @b * 3 from numbers \G
*************************** 1. row ***************************
  @a := (a/3): 33.333333333
  @b := (b/3): 33.333333333333
@a + @a + @a: 99.999999999000000000000000000000
@b + @b + @b: 100

The decimal did exactly what's supposed to do on this cases, it truncated the rest, thus losing the 1/3 part.

So for sums the decimal is better, but for divisions the float is better, up to some point, of course. I mean, using DECIMAL will not give you a "fail proof arithmetic" in any means.

Hope this helps.

How do I assign ls to an array in Linux Bash?

It would be this

array=($(ls -d */))

EDIT: See Gordon Davisson's solution for a more general answer (i.e. if your filenames contain special characters). This answer is merely a syntax correction.

Why am I getting an error "Object literal may only specify known properties"?

As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.

Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash is incorrect and should have been callbackOnLocationHash (note the mis-spelling of "Location").

This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.

Example:

interface TextOptions {
    alignment?: string;
    color?: string;
    padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'

But I meant to do that

There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes

Type-checking only some properties

Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v or v as T) do not check for extra properties, so you can use them in place of a type annotation:

interface Options {
    x?: string;
    y?: number;
}

// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;

These properties and maybe more

Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking

Before

interface Model {
  name: string;
}
function createModel(x: Model) { ... }

// Error
createModel({name: 'hello', length: 100});

After

interface Model {
  name: string;
  [others: string]: any;
}
function createModel(x: Model) { ... }

// OK
createModel({name: 'hello', length: 100});

This is a dog or a cat or a horse, not sure yet

interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }

let x: Animal;
if(...) {
  x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
  x = { move: 'catwalk', meow: 'mrar' };
} else {
  x = { move: 'gallop', neigh: 'wilbur' };
}

Two good solutions come to mind here

Specify a closed set for x

// Removes all errors
let x: Dog|Cat|Horse;

or Type assert each thing

// For each initialization
  x = { move: 'doggy paddle', woof: 'bark' } as Dog;

This type is sometimes open and sometimes not

A clean solution to the "data model" problem using intersection types:

interface DataModelOptions {
  name?: string;
  id?: number;
}
interface UserProperties {
  [key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
 /* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
 /* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });

See also https://github.com/Microsoft/TypeScript/issues/3755

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

Long ago it was impossible to reliably get the list of processes locking a file because Windows simply did not track that information. To support the Restart Manager API, that information is now tracked.

I put together code that takes the path of a file and returns a List<Process> of all processes that are locking that file.

using System.Runtime.InteropServices;
using System.Diagnostics;
using System;
using System.Collections.Generic;

static public class FileUtil
{
    [StructLayout(LayoutKind.Sequential)]
    struct RM_UNIQUE_PROCESS
    {
        public int dwProcessId;
        public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
    }

    const int RmRebootReasonNone = 0;
    const int CCH_RM_MAX_APP_NAME = 255;
    const int CCH_RM_MAX_SVC_NAME = 63;

    enum RM_APP_TYPE
    {
        RmUnknownApp = 0,
        RmMainWindow = 1,
        RmOtherWindow = 2,
        RmService = 3,
        RmExplorer = 4,
        RmConsole = 5,
        RmCritical = 1000
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct RM_PROCESS_INFO
    {
        public RM_UNIQUE_PROCESS Process;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
        public string strAppName;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
        public string strServiceShortName;

        public RM_APP_TYPE ApplicationType;
        public uint AppStatus;
        public uint TSSessionId;
        [MarshalAs(UnmanagedType.Bool)]
        public bool bRestartable;
    }

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
    static extern int RmRegisterResources(uint pSessionHandle,
                                          UInt32 nFiles,
                                          string[] rgsFilenames,
                                          UInt32 nApplications,
                                          [In] RM_UNIQUE_PROCESS[] rgApplications,
                                          UInt32 nServices,
                                          string[] rgsServiceNames);

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
    static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);

    [DllImport("rstrtmgr.dll")]
    static extern int RmEndSession(uint pSessionHandle);

    [DllImport("rstrtmgr.dll")]
    static extern int RmGetList(uint dwSessionHandle,
                                out uint pnProcInfoNeeded,
                                ref uint pnProcInfo,
                                [In, Out] RM_PROCESS_INFO[] rgAffectedApps,
                                ref uint lpdwRebootReasons);

    /// <summary>
    /// Find out what process(es) have a lock on the specified file.
    /// </summary>
    /// <param name="path">Path of the file.</param>
    /// <returns>Processes locking the file</returns>
    /// <remarks>See also:
    /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
    /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
    /// 
    /// </remarks>
    static public List<Process> WhoIsLocking(string path)
    {
        uint handle;
        string key = Guid.NewGuid().ToString();
        List<Process> processes = new List<Process>();

        int res = RmStartSession(out handle, 0, key);
        if (res != 0) throw new Exception("Could not begin restart session.  Unable to determine file locker.");

        try
        {
            const int ERROR_MORE_DATA = 234;
            uint pnProcInfoNeeded = 0,
                 pnProcInfo = 0,
                 lpdwRebootReasons = RmRebootReasonNone;

            string[] resources = new string[] { path }; // Just checking on one resource.

            res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);

            if (res != 0) throw new Exception("Could not register resource.");                                    

            //Note: there's a race condition here -- the first call to RmGetList() returns
            //      the total number of process. However, when we call RmGetList() again to get
            //      the actual processes this number may have increased.
            res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);

            if (res == ERROR_MORE_DATA)
            {
                // Create an array to store the process results
                RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
                pnProcInfo = pnProcInfoNeeded;

                // Get the list
                res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
                if (res == 0)
                {
                    processes = new List<Process>((int)pnProcInfo);

                    // Enumerate all of the results and add them to the 
                    // list to be returned
                    for (int i = 0; i < pnProcInfo; i++)
                    {
                        try
                        {
                            processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
                        }
                        // catch the error -- in case the process is no longer running
                        catch (ArgumentException) { }
                    }
                }
                else throw new Exception("Could not list processes locking resource.");                    
            }
            else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result.");                    
        }
        finally
        {
            RmEndSession(handle);
        }

        return processes;
    }
}

Using from Limited Permission (e.g. IIS)

This call accesses the registry. If the process does not have permission to do so, you will get ERROR_WRITE_FAULT, meaning An operation was unable to read or write to the registry. You could selectively grant permission to your restricted account to the necessary part of the registry. It is more secure though to have your limited access process set a flag (e.g. in the database or the file system, or by using an interprocess communication mechanism such as queue or named pipe) and have a second process call the Restart Manager API.

Granting other-than-minimal permissions to the IIS user is a security risk.

Android list view inside a scroll view

The answer is simple and I am surprised it has yet to be answered here.

Use a Header View or/and Footer View on the list itself. Don't mix a ScrollView with a ListView or anything that can scroll. It's meant to be used with headers and footers :)

Essentially, take all the content above your ListView, put it in another .xml file as a layout and then in code inflate it and add it to the list as a header view.

i.e.

View header = getLayoutInflater().inflate(R.layout.header, null);
View footer = getLayoutInflater().inflate(R.layout.footer, null);
listView.addHeaderView(header);
listView.addFooterView(footer);

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

How can I change the version of npm using nvm?

By looking at www.npmjs.com/install.sh I found there is a way to install a specific version by setting an environment-variable

export npm_install="2.14.14"

Then run the download-script as described at npmjs.com:

curl -L https://www.npmjs.com/install.sh | sh

If you omit setting the npm_install variable, then it will install the the version they have marked as latest

Center Triangle at Bottom of Div

You could also use a CSS "calc" to get the same effect instead of using the negative margin or transform properties (in case you want to use those properties for anything else).

.hero:after,
.hero:after {
    z-index: -1;
    position: absolute;
    top: 98.1%;
    left: calc(50% - 25px);
    content: '';
    width: 0;
    height: 0;
    border-top: solid 50px #e15915;
    border-left: solid 50px transparent;
    border-right: solid 50px transparent;
}

How do I make this file.sh executable via double click?

You can just tell Finder to open the .sh file in Terminal:

  1. Select the file
  2. Get Info (cmd-i) on it
  3. In the "Open with" section, choose "Other…" in the popup menu
  4. Choose Terminal as the application

This will have the exact same effect as renaming it to .command except… you don't have to rename it :)

Axios get access to response header fields

In case you're using Laravel 8 for the back-end side with CORS properly configured, add this line to config/cors.php:

'exposed_headers' => ['Authorization'],

Cannot lower case button text in android studio

in XML Code
add this line android:textAllCaps="false" like bellow code

 <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button_1_name"
        android:id="@+id/button2"
        android:layout_marginTop="140dp"
        android:layout_below="@+id/textView"
        android:layout_centerHorizontal="true"
       ** android:textAllCaps="false" ** />

or

in Java code (programmatically)
add this line to your button setAllCaps(false)

Button btn = (Button) findViewById(R.id.button2);
btn.setAllCaps(false);

Integer ASCII value to character in BASH using printf

If you want to save the ASCII value of the character: (I did this in BASH and it worked)

{
char="A"

testing=$( printf "%d" "'${char}" )

echo $testing}

output: 65

Bypass invalid SSL certificate errors when calling web services in .Net

The approach I used when faced with this problem was to add the signer of the temporary certificate to the trusted authorities list on the computer in question.

I normally do testing with certificates created with CACERT, and adding them to my trusted authorities list worked swimmingly.

Doing it this way means you don't have to add any custom code to your application and it properly simulates what will happen when your application is deployed. As such, I think this is a superior solution to turning off the check programmatically.

How to set selected value of jquery select2?

you can use this code :

$("#programid").val(["number:2", "number:3"]).trigger("change");

where 2 in "number:2" and 3 in "number:3" are id field in object array

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

No problems with my terminal. The above answers helped me looking in the right directions but it didn't work for me until I added 'ignore':

fix_encoding = lambda s: s.decode('utf8', 'ignore')

As indicated in the comment below, this may lead to undesired results. OTOH it also may just do the trick well enough to get things working and you don't care about losing some characters.

PHP Get name of current directory

echo basename(__DIR__); will return the current directory name only
echo basename(__FILE__); will return the current file name only

How to install a Python module via its setup.py in Windows?

setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").

From the command line, you can type

python setup.py --help

...to get a list of commands. What you are looking to do is...

python setup.py install

How to do SELECT MAX in Django?

See this. Your code would be something like the following:

from django.db.models import Max
# Generates a "SELECT MAX..." query
Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}

You can also use this on existing querysets:

from django.db.models import Max
args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset
args.aggregate(Max('rating')) # {'rating__max': 5}

If you need the model instance that contains this max value, then the code you posted is probably the best way to do it:

arg = args.order_by('-rating')[0]

Note that this will error if the queryset is empty, i.e. if no arguments match the query (because the [0] part will raise an IndexError). If you want to avoid that behavior and instead simply return None in that case, use .first():

arg = args.order_by('-rating').first() # may return None

Absolute Positioning & Text Alignment

The div doesn't take up all the available horizontal space when absolutely positioned. Explicitly setting the width to 100% will solve the problem:

HTML

<div id="my-div">I want to be centered</div>?

CSS

#my-div {
   position: absolute;
   bottom: 15px;
   text-align: center;
   width: 100%;
}

?

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

The error in question may also be caused by disabled JarScanner in tomcat/conf/context.xml.

See also Upgrade from Tomcat 8.0.39 to 8.0.41 results in 'failed to scan' errors.

<JarScanner scanManifest="false"/> allows to avoid both problems.

What's the difference between interface and @interface in java?

interface:

In general, an interface exposes a contract without exposing the underlying implementation details. In Object Oriented Programming, interfaces define abstract types that expose behavior, but contain no logic. Implementation is defined by the class or type that implements the interface.

@interface : (Annotation type)

Take the below example, which has a lot of comments:

public class Generation3List extends Generation2List {

   // Author: John Doe
   // Date: 3/17/2002
   // Current revision: 6
   // Last modified: 4/12/2004
   // By: Jane Doe
   // Reviewers: Alice, Bill, Cindy

   // class code goes here

}

Instead of this, you can declare an annotation type

 @interface ClassPreamble {
   String author();
   String date();
   int currentRevision() default 1;
   String lastModified() default "N/A";
   String lastModifiedBy() default "N/A";
   // Note use of array
   String[] reviewers();
}

which can then annotate a class as follows:

@ClassPreamble (
   author = "John Doe",
   date = "3/17/2002",
   currentRevision = 6,
   lastModified = "4/12/2004",
   lastModifiedBy = "Jane Doe",
   // Note array notation
   reviewers = {"Alice", "Bob", "Cindy"}
)
public class Generation3List extends Generation2List {

// class code goes here

}

PS: Many annotations replace comments in code.

Reference: http://docs.oracle.com/javase/tutorial/java/annotations/declaring.html

Check synchronously if file/directory exists in Node.js

The path module does not provide a synchronous version of path.exists so you have to trick around with the fs module.

Fastest thing I can imagine is using fs.realpathSync which will throw an error that you have to catch, so you need to make your own wrapper function with a try/catch.

Visual Studio: ContextSwitchDeadlock

The above solution is good in some scenarios but there is another scenario where this happens when you are unit testing and you try to "Debug Selected Tests" from the Test Explorer when you solution is not set to Debug.

In this case you need to change your solution from Release or whatever it is set to to Debug in this case. If this is the problem then changing "ContextSwitchDeadlock" won't really help you.

I missed this myself because the error message was so nasty I didn't check the obvious thing which was the Debug setting!

Uploading/Displaying Images in MVC 4

Here is a short tutorial:

Model:

namespace ImageUploadApp.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Image
    {
        public int ID { get; set; }
        public string ImagePath { get; set; }
    }
}

View:

  1. Create:

    @model ImageUploadApp.Models.Image
    @{
        ViewBag.Title = "Create";
    }
    <h2>Create</h2>
    @using (Html.BeginForm("Create", "Image", null, FormMethod.Post, 
                                  new { enctype = "multipart/form-data" })) {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)
        <fieldset>
            <legend>Image</legend>
            <div class="editor-label">
                @Html.LabelFor(model => model.ImagePath)
            </div>
            <div class="editor-field">
                <input id="ImagePath" title="Upload a product image" 
                                      type="file" name="file" />
            </div>
            <p><input type="submit" value="Create" /></p>
        </fieldset>
    }
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>
    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }
    
  2. Index (for display):

    @model IEnumerable<ImageUploadApp.Models.Image>
    
    @{
        ViewBag.Title = "Index";
    }
    
    <h2>Index</h2>
    
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.ImagePath)
            </th>
        </tr>
    
    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.ImagePath)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
                @Html.ActionLink("Details", "Details", new { id=item.ID }) |
                @Ajax.ActionLink("Delete", "Delete", new {id = item.ID} })
            </td>
        </tr>
    }
    
    </table>
    
  3. Controller (Create)

    public ActionResult Create(Image img, HttpPostedFileBase file)
    {
        if (ModelState.IsValid)
        {
            if (file != null)
            {
                file.SaveAs(HttpContext.Server.MapPath("~/Images/") 
                                                      + file.FileName);
                img.ImagePath = file.FileName;
            }  
            db.Image.Add(img);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(img);
    }
    

Hope this will help :)

Auto start node.js server on boot

This isn't something to configure in node.js at all, this is purely OS responsibility (Windows in your case). The most reliable way to achieve this is through a Windows Service.

There's this super easy module that installs a node script as a windows service, it's called node-windows (npm, github, documentation). I've used before and worked like a charm.

var Service = require('node-windows').Service;

// Create a new service object
var svc = new Service({
  name:'Hello World',
  description: 'The nodejs.org example web server.',
  script: 'C:\\path\\to\\helloworld.js'
});

// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
  svc.start();
});

svc.install();

p.s.

I found the thing so useful that I built an even easier to use wrapper around it (npm, github).

Installing it:

npm install -g qckwinsvc

Installing your service:

> qckwinsvc
prompt: Service name: [name for your service]
prompt: Service description: [description for it]
prompt: Node script path: [path of your node script]
Service installed

Uninstalling your service:

> qckwinsvc --uninstall
prompt: Service name: [name of your service]
prompt: Node script path: [path of your node script]
Service stopped
Service uninstalled

How to customize message box

You can't restyle the default MessageBox as that's dependant on the current Windows OS theme, however you can easily create your own MessageBox. Just add a new form (i.e. MyNewMessageBox) to your project with these settings:

FormBorderStyle    FixedToolWindow
ShowInTaskBar      False
StartPosition      CenterScreen

To show it use myNewMessageBoxInstance.ShowDialog();. And add a label and buttons to your form, such as OK and Cancel and set their DialogResults appropriately, i.e. add a button to MyNewMessageBox and call it btnOK. Set the DialogResult property in the property window to DialogResult.OK. When that button is pressed it would return the OK result:

MyNewMessageBox myNewMessageBoxInstance = new MyNewMessageBox();
DialogResult result = myNewMessageBoxInstance.ShowDialog();
if (result == DialogResult.OK)
{
    // etc
}

It would be advisable to add your own Show method that takes the text and other options you require:

public DialogResult Show(string text, Color foreColour)
{
     lblText.Text = text;
     lblText.ForeColor = foreColour;
     return this.ShowDialog();
}

Converting java date to Sql timestamp

You can cut off the milliseconds using a Calendar:

java.util.Date utilDate = new java.util.Date();
Calendar cal = Calendar.getInstance();
cal.setTime(utilDate);
cal.set(Calendar.MILLISECOND, 0);
System.out.println(new java.sql.Timestamp(utilDate.getTime()));
System.out.println(new java.sql.Timestamp(cal.getTimeInMillis()));

Output:

2014-04-04 10:10:17.78
2014-04-04 10:10:17.0

Finding child element of parent pure javascript

Just adding another idea you could use a child selector to get immediate children

document.querySelectorAll(".parent > .child1");

should return all the immediate children with class .child1

DateTime's representation in milliseconds?

There are ToUnixTime() and ToUnixTimeMs() methods in DateTimeExtensions class

DateTime.UtcNow.ToUnixTimeMs()

Difference between webdriver.Dispose(), .Close() and .Quit()

This is a good question I have seen people use Close() when they shouldn't. I looked in the source code for the Selenium Client & WebDriver C# Bindings and found the following.

  1. webDriver.Close() - Close the browser window that the driver has focus of
  2. webDriver.Quit() - Calls Dispose()
  3. webDriver.Dispose() Closes all browser windows and safely ends the session

The code below will dispose the driver object, ends the session and closes all browsers opened during a test whether the test fails or passes.

public IWebDriver Driver;

[SetUp]
public void SetupTest()
{
    Driver = WebDriverFactory.GetDriver();
}

[TearDown]
public void TearDown()
{
    if (Driver != null)
      Driver.Quit();
}

In summary ensure that Quit() or Dispose() is called before exiting the program, and don't use the Close() method unless you're sure of what you're doing.

Note
I found this question when try to figure out a related problem why my VM's were running out of harddrive space. Turns out an exception was causing Quit() or Dispose() to not be called every run which then caused the appData folder to fill the hard drive. So we were using the Quit() method correctly but the code was unreachable. Summary make sure all code paths will clean up your unmanaged objects by using exception safe patterns or implement IDisposable

Also
In the case of RemoteDriver calling Quit() or Dispose() will also close the session on the Selenium Server. If the session isn't closed the log files for that session remain in memory.

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

Update 2015-06

Based on antoinepairet's comment/example:

Using uib-collapse attribute provides animations: http://plnkr.co/edit/omyoOxYnCdWJP8ANmTc6?p=preview

<nav class="navbar navbar-default" role="navigation">
    <div class="navbar-header">

        <!-- note the ng-init and ng-click here: -->
        <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Brand</a>
    </div>

    <div class="collapse navbar-collapse" uib-collapse="navCollapsed">
        <ul class="nav navbar-nav">
        ...
        </ul>
    </div>
</nav>

Ancient..

I see that the question is framed around BS2, but I thought I'd pitch in with a solution for Bootstrap 3 using ng-class solution based on suggestions in ui.bootstrap issue 394:

The only variation from the official bootstrap example is the addition of ng- attributes noted by comments, below:

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">

    <!-- note the ng-init and ng-click here: -->
    <button type="button" class="navbar-toggle" ng-init="navCollapsed = true" ng-click="navCollapsed = !navCollapsed">
      <span class="sr-only">Toggle navigation</span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
  </div>

  <!-- note the ng-class here -->
  <div class="collapse navbar-collapse" ng-class="{'in':!navCollapsed}">

    <ul class="nav navbar-nav">
    ...

Here is an updated working example: http://plnkr.co/edit/OlCCnbGlYWeO7Nxwfj5G?p=preview (hat tip Lars)

This seems to works for me in simple use cases, but you'll note in the example that the second dropdown is cut off… good luck!

Switch statement fall-through...should it be allowed?

It is powerful and dangerous. The biggest problem with fall-through is that it's not explicit. For example, if you come across frequently-edited code that has a switch with fall-throughs, how do you know that's intentional and not a bug?

Anywhere I use it, I ensure that it's properly commented:

switch($var) {
    case 'first':
        // Fall-through
    case 'second':
        i++;
        break;
 }

Convert Array to Object

If you like oneliners, and IE8 is not a problem anymore (as it should be)

['a','b','c'].reduce((m,e,i) => Object.assign(m, {[i]: e}), {});

Go ahead and try it on the browser console

It coult be more verbose like this:

['a','b','c'].reduce(function(memo,elm,idx) {
    return Object.assign(memo, {[idx]: elm});
}, {});

But still rules out IE8. If IE8 is a must, then you can use lodash/underscore like that:

_.reduce(['a','b','c'], function(memo,elm,idx) {
    return Object.assign(memo, {[idx]: elm});
}, {})

Convert Xml to DataTable

You can use this code(Recommended)

 MemoryStream objMS = new MemoryStream();
 DataTable oDT = new DataTable();//Your DataTable which you want to convert
 oDT.WriteXml(objMS);
 objMS.Position = 0;
 XPathDocument result = new XPathDocument(objMS);

This is another way but first ex. is recommended

StringWriter objSW = new StringWriter();
DataTable oDt = new DataTable();//Your DataTable which you want to convert
oDt.WriteXml(objSW);
string result = objSW.ToString();

How can I move all the files from one folder to another using the command line?

Be sure to use quotes if there are spaces in the file path:

move "C:\Users\MyName\My Old Folder\*" "C:\Users\MyName\My New Folder"

That will move the contents of C:\Users\MyName\My Old Folder\ to C:\Users\MyName\My New Folder

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

Look at ?par for the various graphics parameters.

In general cex controls size, col controls colour. If you want to control the colour of a label, the par is col.lab, the colour of the axis annotations col.axis, the colour of the main text, col.main etc. The names are quite intuitive, once you know where to begin.

For example

x <- 1:10
y <- 1:10

plot(x , y,xlab="x axis", ylab="y axis",  pch=19, col.axis = 'blue', col.lab = 'red', cex.axis = 1.5, cex.lab = 2)

enter image description here

If you need to change the colour / style of the surrounding box and axis lines, then look at ?axis or ?box, and you will find that you will be using the same parameter names within calls to box and axis.

You have a lot of control to make things however you wish.

eg

plot(x , y,xlab="x axis", ylab="y axis",  pch=19,  cex.lab = 2, axes = F,col.lab = 'red')
box(col = 'lightblue')
axis(1, col = 'blue', col.axis = 'purple', col.ticks = 'darkred', cex.axis = 1.5, font = 2, family = 'serif')
axis(2, col = 'maroon', col.axis = 'pink', col.ticks = 'limegreen', cex.axis = 0.9, font =3, family = 'mono')

enter image description here

Which is seriously ugly, but shows part of what you can control

Find first element in a sequence that matches a predicate

J.F. Sebastian's answer is most elegant but requires python 2.6 as fortran pointed out.

For Python version < 2.6, here's the best I can come up with:

from itertools import repeat,ifilter,chain
chain(ifilter(predicate,seq),repeat(None)).next()

Alternatively if you needed a list later (list handles the StopIteration), or you needed more than just the first but still not all, you can do it with islice:

from itertools import islice,ifilter
list(islice(ifilter(predicate,seq),1))

UPDATE: Although I am personally using a predefined function called first() that catches a StopIteration and returns None, Here's a possible improvement over the above example: avoid using filter / ifilter:

from itertools import islice,chain
chain((x for x in seq if predicate(x)),repeat(None)).next()

Java ArrayList - how can I tell if two lists are equal, order not mattering?

If you don't hope to sort the collections and you need the result that ["A" "B" "C"] is not equals to ["B" "B" "A" "C"],

l1.containsAll(l2)&&l2.containsAll(l1)

is not enough, you propably need to check the size too :

    List<String> l1 =Arrays.asList("A","A","B","C");
    List<String> l2 =Arrays.asList("A","B","C");
    List<String> l3 =Arrays.asList("A","B","C");

    System.out.println(l1.containsAll(l2)&&l2.containsAll(l1));//cautions, this will be true
    System.out.println(isListEqualsWithoutOrder(l1,l2));//false as expected

    System.out.println(l3.containsAll(l2)&&l2.containsAll(l3));//true as expected
    System.out.println(isListEqualsWithoutOrder(l2,l3));//true as expected


    public static boolean isListEqualsWithoutOrder(List<String> l1, List<String> l2) {
        return l1.size()==l2.size() && l1.containsAll(l2)&&l2.containsAll(l1);
}

Why is Maven downloading the maven-metadata.xml every time?

Maven does this because your dependency is in a SNAPSHOT version and maven has no way to detect any changes made to that snapshot version in the repository. Release your artifact and change the version in pom.xml to that version and maven will no longer fetch the metadata file.

Make a link use POST instead of GET

Another working example, using similar approach posted : create a html form, use javascript to simulate the post. This does 2 things : post data to a new page and open it in a new window/tab.

HTML

<form name='myForm' target="_blank" action='newpage.html' method='post'>
<input type="hidden" name="thisIsTheParameterName" value="testDataToBePosted"/>
</form>

JavaScript

document.forms["myForm"].submit();

What are ODEX files in Android?

ART

According to the docs: http://web.archive.org/web/20170909233829/https://source.android.com/devices/tech/dalvik/configure an .odex file:

contains AOT compiled code for methods in the APK.

Furthermore, they appear to be regular shared libraries, since if you get any app, and check:

file /data/app/com.android.appname-*/oat/arm64/base.odex

it says:

base.odex: ELF shared object, 64-bit LSB arm64, stripped

and aarch64-linux-gnu-objdump -d base.odex seems to work and give some meaningful disassembly (but also some rubbish sections).

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

Go to "Target" -> "Build Phases", select your target, select the “Build Phases” tab, click “Add Build Phase”, and select “Add Copy Files”. Change the destination to “Products Directory”. Drag your file into the “Add files” section.

Checking if a website is up via Python

I use requests for this, then it is easy and clean. Instead of print function you can define and call new function (notify via email etc.). Try-except block is essential, because if host is unreachable then it will rise a lot of exceptions so you need to catch them all.

import requests

URL = "https://api.github.com"

try:
    response = requests.head(URL)
except Exception as e:
    print(f"NOT OK: {str(e)}")
else:
    if response.status_code == 200:
        print("OK")
    else:
        print(f"NOT OK: HTTP response code {response.status_code}")

Javascript Array Alert

If you want to see the array as an array, you can say

alert(JSON.stringify(aCustomers));

instead of all those document.writes.

http://jsfiddle.net/5b2eb/

However, if you want to display them cleanly, one per line, in your popup, do this:

alert(aCustomers.join("\n"));

http://jsfiddle.net/5b2eb/1/

Where can I find my Facebook application id and secret key?

From 2018:

Go to Settings -> Basic -> App Secret (type your password and you're ready to go).

How to return a file using Web API?

I've been wondering if there was a simple way to download a file in a more ... "generic" way. I came up with this.

It's a simple ActionResult that will allow you to download a file from a controller call that returns an IHttpActionResult. The file is stored in the byte[] Content. You can turn it into a stream if needs be.

I used this to return files stored in a database's varbinary column.

    public class FileHttpActionResult : IHttpActionResult
    {
        public HttpRequestMessage Request { get; set; }

        public string FileName { get; set; }
        public string MediaType { get; set; }
        public HttpStatusCode StatusCode { get; set; }

        public byte[] Content { get; set; }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            HttpResponseMessage response = new HttpResponseMessage(StatusCode);

            response.StatusCode = StatusCode;
            response.Content = new StreamContent(new MemoryStream(Content));
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = FileName;
            response.Content.Headers.ContentType = new MediaTypeHeaderValue(MediaType);

            return Task.FromResult(response);
        }
    }

What is the difference between background and background-color

background is shorthand property for the following:

 - background-color
 - background-image
 - background-repeat
 - background-attachment
 - background-position

You can detailed info on every property here

Properties order

In most of browser implementation (i think maybe older browser could present issues) the order of the properties does not matter, except for:

  • background-origin and background-clip: when both of this properties are present, the first one refer to -origin and the second to -clip.

    Example:

    background: content-box green padding-box;
    

    Is equivalent to:

    background-origin: content-box;
    background-color: green;
    background-clip: padding-box;
    
  • background-size must always follow background-position and the properties must be separated by /

  • if background-position is composed by two numbers, the first one is the horizontal value and the second the vertical value.

How to animate the change of image in an UIImageView?

In the words of Michael Scott, keep it simple stupid. Here is a simple way to do this in Swift 3 and Swift 4:

UIView.transition(with: imageView,
                  duration: 0.75,
                  options: .transitionCrossDissolve,
                  animations: { self.imageView.image = toImage },
                  completion: nil)

Injecting $scope into an angular service function()

The $scope that you see being injected into controllers is not some service (like the rest of the injectable stuff), but is a Scope object. Many scope objects can be created (usually prototypically inheriting from a parent scope). The root of all scopes is the $rootScope and you can create a new child-scope using the $new() method of any scope (including the $rootScope).

The purpose of a Scope is to "glue together" the presentation and the business logic of your app. It does not make much sense to pass a $scope into a service.

Services are singleton objects used (among other things) to share data (e.g. among several controllers) and generally encapsulate reusable pieces of code (since they can be injected and offer their "services" in any part of your app that needs them: controllers, directives, filters, other services etc).

I am sure, various approaches would work for you. One is this:
Since the StudentService is in charge of dealing with student data, you can have the StudentService keep an array of students and let it "share" it with whoever might be interested (e.g. your $scope). This makes even more sense, if there are other views/controllers/filters/services that need to have access to that info (if there aren't any right now, don't be surprised if they start popping up soon).
Every time a new student is added (using the service's save() method), the service's own array of students will be updated and every other object sharing that array will get automatically updated as well.

Based on the approach described above, your code could look like this:

angular.
  module('cfd', []).

  factory('StudentService', ['$http', '$q', function ($http, $q) {
    var path = 'data/people/students.json';
    var students = [];

    // In the real app, instead of just updating the students array
    // (which will be probably already done from the controller)
    // this method should send the student data to the server and
    // wait for a response.
    // This method returns a promise to emulate what would happen 
    // when actually communicating with the server.
    var save = function (student) {
      if (student.id === null) {
        students.push(student);
      } else {
        for (var i = 0; i < students.length; i++) {
          if (students[i].id === student.id) {
            students[i] = student;
            break;
          }
        }
      }

      return $q.resolve(student);
    };

    // Populate the students array with students from the server.
    $http.get(path).then(function (response) {
      response.data.forEach(function (student) {
        students.push(student);
      });
    });

    return {
      students: students,
      save: save
    };     
  }]).

  controller('someCtrl', ['$scope', 'StudentService', 
    function ($scope, StudentService) {
      $scope.students = StudentService.students;
      $scope.saveStudent = function (student) {
        // Do some $scope-specific stuff...

        // Do the actual saving using the StudentService.
        // Once the operation is completed, the $scope's `students`
        // array will be automatically updated, since it references
        // the StudentService's `students` array.
        StudentService.save(student).then(function () {
          // Do some more $scope-specific stuff, 
          // e.g. show a notification.
        }, function (err) {
          // Handle the error.
        });
      };
    }
]);

One thing you should be careful about when using this approach is to never re-assign the service's array, because then any other components (e.g. scopes) will be still referencing the original array and your app will break.
E.g. to clear the array in StudentService:

/* DON'T DO THAT   */  
var clear = function () { students = []; }

/* DO THIS INSTEAD */  
var clear = function () { students.splice(0, students.length); }

See, also, this short demo.


LITTLE UPDATE:

A few words to avoid the confusion that may arise while talking about using a service, but not creating it with the service() function.

Quoting the docs on $provide:

An Angular service is a singleton object created by a service factory. These service factories are functions which, in turn, are created by a service provider. The service providers are constructor functions. When instantiated they must contain a property called $get, which holds the service factory function.
[...]
...the $provide service has additional helper methods to register services without specifying a provider:

  • provider(provider) - registers a service provider with the $injector
  • constant(obj) - registers a value/object that can be accessed by providers and services.
  • value(obj) - registers a value/object that can only be accessed by services, not providers.
  • factory(fn) - registers a service factory function, fn, that will be wrapped in a service provider object, whose $get property will contain the given factory function.
  • service(class) - registers a constructor function, class that will be wrapped in a service provider object, whose $get property will instantiate a new object using the given constructor function.

Basically, what it says is that every Angular service is registered using $provide.provider(), but there are "shortcut" methods for simpler services (two of which are service() and factory()).
It all "boils down" to a service, so it doesn't make much difference which method you use (as long as the requirements for your service can be covered by that method).

BTW, provider vs service vs factory is one of the most confusing concepts for Angular new-comers, but fortunately there are plenty of resources (here on SO) to make things easier. (Just search around.)

(I hope that clears it up - let me know if it doesn't.)

How to set JAVA_HOME for multiple Tomcat instances?

In UNIX I had this problem, I edited catalina.sh manually and entered

export JAVA_HOME=/usr/lib/jvm/java-6-sun-1.6.0.24
echo "Using JAVA_HOME:       $JAVA_HOME"

as the first 2 lines. I tried setting the JAVA_HOME in /etc/profile but it did not help.

This worked finally.

Find if a textbox is disabled or not using jquery

.prop('disabled') will return a Boolean:

var isDisabled = $('textbox').prop('disabled');

Here's the fiddle: http://jsfiddle.net/unhjM/

setTimeout or setInterval?

I find the setTimeout method easier to use if you want to cancel the timeout:

function myTimeoutFunction() {
   doStuff();
   if (stillrunning) {
      setTimeout(myTimeoutFunction, 1000);
   }
}

myTimeoutFunction();

Also, if something would go wrong in the function it will just stop repeating at the first time error, instead of repeating the error every second.

Creating a textarea with auto-resize

I know I'm late to this party but the simplest solution I've come across is to split your text area content on new line characters and update the rows for the textarea element.

<textarea id="my-text-area"></textarea>

<script>
  $(function() {
    const txtArea = $('#my-text-area')
    const val = txtArea.val()
    const rowLength = val.split('\n')
    txtArea.attr('rows', rowLength)
  })
</script>

HTML Text with tags to formatted text in an Excel cell

Nice! Very slick.

I was disappointed that Excel doesn't let us paste to a merged cell and also pastes results containing a break into successive rows below the "target" cell though, as that meant it simply doesn't work for me. I tried a few tweaks (unmerge/remerge, etc.) but then Excel dropped anything below a break, so that was a dead end.

Ultimately, I came up with a routine that'll handle simple tags and not use the "native" Unicode converter that is causing the issue with merged fields. Hope others find this useful:

Public Sub AddHTMLFormattedText(rngA As Range, strHTML As String, Optional blnShowBadHTMLWarning As Boolean = False)
    ' Adds converts text formatted with basic HTML tags to formatted text in an Excel cell
    ' NOTE: Font Sizes not handled perfectly per HTML standard, but I find this method more useful!

    Dim strActualText As String, intSrcPos As Integer, intDestPos As Integer, intDestSrcEquiv() As Integer
    Dim varyTags As Variant, varTag As Variant, varEndTag As Variant, blnTagMatch As Boolean
    Dim intCtr As Integer
    Dim intStartPos As Integer, intEndPos As Integer, intActualStartPos As Integer, intActualEndPos As Integer
    Dim intFontSizeStartPos As Integer, intFontSizeEndPos As Integer, intFontSize As Integer

    varyTags = Array("<b>", "</b>", "<i>", "</i>", "<u>", "</u>", "<sub>", "</sub>", "<sup>", "</sup>")

    ' Remove unhandled/unneeded tags, convert <br> and <p> tags to line feeds
    strHTML = Trim(strHTML)
    strHTML = Replace(strHTML, "<html>", "")
    strHTML = Replace(strHTML, "</html>", "")
    strHTML = Replace(strHTML, "<p>", "")
    While LCase(Right$(strHTML, 4)) = "</p>" Or LCase(Right$(strHTML, 4)) = "<br>"
        strHTML = Left$(strHTML, Len(strHTML) - 4)
        strHTML = Trim(strHTML)
    Wend
    strHTML = Replace(strHTML, "<br>", vbLf)
    strHTML = Replace(strHTML, "</p>", vbLf)

    strHTML = Trim(strHTML)

    ReDim intDestSrcEquiv(1 To Len(strHTML))
    strActualText = ""
    intSrcPos = 1
    intDestPos = 1
    Do While intSrcPos <= Len(strHTML)
        blnTagMatch = False
        For Each varTag In varyTags
            If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
                blnTagMatch = True
                intSrcPos = intSrcPos + Len(varTag)
                If intSrcPos > Len(strHTML) Then Exit Do
                Exit For
            End If
        Next
        If blnTagMatch = False Then
            varTag = "<font size"
            If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
                blnTagMatch = True
                intEndPos = InStr(intSrcPos, strHTML, ">")
                intSrcPos = intEndPos + 1
                If intSrcPos > Len(strHTML) Then Exit Do
            Else
                varTag = "</font>"
                If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
                    blnTagMatch = True
                    intSrcPos = intSrcPos + Len(varTag)
                    If intSrcPos > Len(strHTML) Then Exit Do
                End If
            End If
        End If
        If blnTagMatch = False Then
            strActualText = strActualText & Mid$(strHTML, intSrcPos, 1)
            intDestSrcEquiv(intSrcPos) = intDestPos
            intDestPos = intDestPos + 1
            intSrcPos = intSrcPos + 1
        End If
    Loop

    ' Clear any bold/underline/italic/superscript/subscript formatting from cell
    rngA.Font.Bold = False
    rngA.Font.Underline = False
    rngA.Font.Italic = False
    rngA.Font.Subscript = False
    rngA.Font.Superscript = False

    rngA.Value = strActualText

    ' Now start applying Formats!"
    ' Start with Font Size first
    intSrcPos = 1
    intDestPos = 1
    Do While intSrcPos <= Len(strHTML)
        varTag = "<font size"
        If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
            intFontSizeStartPos = InStr(intSrcPos, strHTML, """") + 1
            intFontSizeEndPos = InStr(intFontSizeStartPos, strHTML, """") - 1
            If intFontSizeEndPos - intFontSizeStartPos <= 3 And intFontSizeEndPos - intFontSizeStartPos > 0 Then
                Debug.Print Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
                If Mid$(strHTML, intFontSizeStartPos, 1) = "+" Then
                    intFontSizeStartPos = intFontSizeStartPos + 1
                    intFontSize = 11 + 2 * Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
                ElseIf Mid$(strHTML, intFontSizeStartPos, 1) = "-" Then
                    intFontSizeStartPos = intFontSizeStartPos + 1
                    intFontSize = 11 - 2 * Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
                Else
                    intFontSize = Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
                End If
            Else
                ' Error!
                GoTo HTML_Err
            End If
            intEndPos = InStr(intSrcPos, strHTML, ">")
            intSrcPos = intEndPos + 1
            intStartPos = intSrcPos
            If intSrcPos > Len(strHTML) Then Exit Do
            While intDestSrcEquiv(intStartPos) = 0 And intStartPos < Len(strHTML)
                intStartPos = intStartPos + 1
            Wend
            If intStartPos >= Len(strHTML) Then GoTo HTML_Err ' HTML is bad!
            varEndTag = "</font>"
            intEndPos = InStr(intSrcPos, LCase(strHTML), varEndTag)
            If intEndPos = 0 Then GoTo HTML_Err ' HTML is bad!
            While intDestSrcEquiv(intEndPos) = 0 And intEndPos > intSrcPos
                intEndPos = intEndPos - 1
            Wend
            If intEndPos > intSrcPos Then
                intActualStartPos = intDestSrcEquiv(intStartPos)
                intActualEndPos = intDestSrcEquiv(intEndPos)
                rngA.Characters(intActualStartPos, intActualEndPos - intActualStartPos + 1) _
                    .Font.Size = intFontSize
            End If
        End If
        intSrcPos = intSrcPos + 1
    Loop

    'Now do remaining tags
    intSrcPos = 1
    intDestPos = 1
    Do While intSrcPos <= Len(strHTML)
        If intDestSrcEquiv(intSrcPos) = 0 Then
            ' This must be a Tag!
            For intCtr = 0 To UBound(varyTags) Step 2
                varTag = varyTags(intCtr)
                intStartPos = intSrcPos + Len(varTag)
                While intDestSrcEquiv(intStartPos) = 0 And intStartPos < Len(strHTML)
                    intStartPos = intStartPos + 1
                Wend
                If intStartPos >= Len(strHTML) Then GoTo HTML_Err ' HTML is bad!
                If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
                    varEndTag = varyTags(intCtr + 1)
                    intEndPos = InStr(intSrcPos, LCase(strHTML), varEndTag)
                    If intEndPos = 0 Then GoTo HTML_Err ' HTML is bad!
                    While intDestSrcEquiv(intEndPos) = 0 And intEndPos > intSrcPos
                        intEndPos = intEndPos - 1
                    Wend
                    If intEndPos > intSrcPos Then
                        intActualStartPos = intDestSrcEquiv(intStartPos)
                        intActualEndPos = intDestSrcEquiv(intEndPos)
                        With rngA.Characters(intActualStartPos, intActualEndPos - intActualStartPos + 1).Font
                            If varTag = "<b>" Then
                                .Bold = True
                            ElseIf varTag = "<i>" Then
                                .Italic = True
                            ElseIf varTag = "<u>" Then
                                .Underline = True
                            ElseIf varTag = "<sup>" Then
                                .Superscript = True
                            ElseIf varTag = "<sub>" Then
                                .Subscript = True
                            End If
                        End With
                    End If
                    intSrcPos = intSrcPos + Len(varTag) - 1
                    Exit For
                End If
            Next
        End If
        intSrcPos = intSrcPos + 1
        intDestPos = intDestPos + 1
    Loop
Exit_Sub:
    Exit Sub
HTML_Err:
    ' There was an error with the Tags. Show warning if requested.
    If blnShowBadHTMLWarning Then
        MsgBox "There was an error with the Tags in the HTML file. Could not apply formatting."
    End If
End Sub

Note this doesn't care about tag nesting, instead only requiring a close tag for every open tag, and assuming the close tag nearest the opening tag applies to the opening tag. Properly nested tags will work fine, while improperly nested tags will not be rejected and may or may not work.

How to fix apt-get: command not found on AWS EC2?

I guess you are actually using Amazon Linux AMI 2013.03.1 instead of Ubuntu Server 12.x reason why you don't have apt-get tool installed.

INSERT IF NOT EXISTS ELSE UPDATE?

You should use the INSERT OR IGNORE command followed by an UPDATE command: In the following example name is a primary key:

INSERT OR IGNORE INTO my_table (name, age) VALUES ('Karen', 34)
UPDATE my_table SET age = 34 WHERE name='Karen'

The first command will insert the record. If the record exists, it will ignore the error caused by the conflict with an existing primary key.

The second command will update the record (which now definitely exists)

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.

The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.

If this issue is causing serious problems, here are a few things I would suggest:

  • Revert back to JDK 1.7.0_25 until a fix is added to the JDK.

  • Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.

  • Try the JDK early releases as they come out. One of them might fix your problem.

Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.

What's in an Eclipse .classpath/.project file?

This eclipse documentation has details on the markups in .project file: The project description file

It describes the .project file as:

When a project is created in the workspace, a project description file is automatically generated that describes the project. The purpose of this file is to make the project self-describing, so that a project that is zipped up or released to a server can be correctly recreated in another workspace. This file is always called ".project"

How do I change selected value of select2 dropdown with JqGrid?

you can simply use the get/set method for set the value

$("#select").select2("val"); //get the value
$("#select").select2("val", "CA"); //set the value

or you can do this:

$('#select').val("E").change(); // you must enter the Value instead of the string

Write HTML string in JSON

You should escape the forward slash too, here is the correct JSON:

[{
"id": "services.html",
"img": "img/SolutionInnerbananer.jpg",
"html": "<h2class=\"fg-white\">AboutUs<\/h2><pclass=\"fg-white\">developing and supporting complex IT solutions.Touchingmillions of lives world wide by bringing in innovative technology <\/p>"
}]

Java String declaration

There is a small difference between both.

Second declaration assignates the reference associated to the constant SOMEto the variable str

First declaration creates a new String having for value the value of the constant SOME and assignates its reference to the variable str.

In the first case, a second String has been created having the same value that SOME which implies more inititialization time. As a consequence, you should avoid it. Furthermore, at compile time, all constants SOMEare transformed into the same instance, which uses far less memory.

As a consequence, always prefer second syntax.

How do I search for an object by its ObjectId in the mongo console?

Once you opened the mongo CLI, connected and authorized on the right database.

The following example shows how to find the document with the _id=568c28fffc4be30d44d0398e from a collection called “products”:

db.products.find({"_id": ObjectId("568c28fffc4be30d44d0398e")})

Assign variable in if condition statement, good practice or not?

you could do something like so:

if (value = /* sic */ some_function()){
  use_value(value)
}

Difference between "git add -A" and "git add ."

In Git 2.x:

  • If you are located directly at the working directory, then git add -A and git add . work without the difference.

  • If you are in any subdirectory of the working directory, git add -A will add all files from the entire working directory, and git add . will add files from your current directory.

And that's all.

Why are exclamation marks used in Ruby methods?

From themomorohoax.com:

A bang can used in the below ways, in order of my personal preference.

1) An active record method raises an error if the method does not do what it says it will.

2) An active record method saves the record or a method saves an object (e.g. strip!)

3) A method does something “extra”, like posts to someplace, or does some action.

The point is: only use a bang when you’ve really thought about whether it’s necessary, to save other developers the annoyance of having to check why you are using a bang.

The bang provides two cues to other developers.

1) that it’s not necessary to save the object after calling the method.

2) when you call the method, the db is going to be changed.

http://www.themomorohoax.com/2009/02/11/when-to-use-a-bang-exclamation-point-after-rails-methods

SQL Logic Operator Precedence: And and Or

Query to show a 3-variable boolean expression truth table :

;WITH cteData AS
(SELECT 0 AS A, 0 AS B, 0 AS C
UNION ALL SELECT 0,0,1
UNION ALL SELECT 0,1,0
UNION ALL SELECT 0,1,1
UNION ALL SELECT 1,0,0
UNION ALL SELECT 1,0,1
UNION ALL SELECT 1,1,0
UNION ALL SELECT 1,1,1
)
SELECT cteData.*,
    CASE WHEN

(A=1) OR (B=1) AND (C=1)

    THEN 'True' ELSE 'False' END AS Result
FROM cteData

Results for (A=1) OR (B=1) AND (C=1) :

A   B   C   Result
0   0   0   False
0   0   1   False
0   1   0   False
0   1   1   True
1   0   0   True
1   0   1   True
1   1   0   True
1   1   1   True

Results for (A=1) OR ( (B=1) AND (C=1) ) are the same.

Results for ( (A=1) OR (B=1) ) AND (C=1) :

A   B   C   Result
0   0   0   False
0   0   1   False
0   1   0   False
0   1   1   True
1   0   0   False
1   0   1   True
1   1   0   False
1   1   1   True

How to validate a file upload field using Javascript/jquery

In Firefox at least, the DOM inspector is telling me that the File input elements have a property called files. You should be able to check its length.

document.getElementById('myFileInput').files.length

Non-alphanumeric list order from os.listdir()

From the documentation:

The list is in arbitrary order, and does not include the special entries '.' and '..' even if they are present in the directory.

This means that the order is probably OS/filesystem dependent, has no particularly meaningful order, and is therefore not guaranteed to be anything in particular. As many answers mentioned: if preferred, the retrieved list can be sorted.

Cheers :)

How to check if any flags of a flag combination are set?

There are a lot of answers on here but I think the most idiomatic way to do this with Flags would be Letters.AB.HasFlag(letter) or (Letters.A | Letters.B).HasFlag(letter) if you didn't already have Letters.AB. letter.HasFlag(Letters.AB) only works if it has both.

How to access form methods and controls from a class in C#?

Another solution would be to pass the textbox (or control you want to modify) into the method that will manipulate it as a parameter.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        TestClass test = new TestClass();
        test.ModifyText(textBox1);
    }
}

public class TestClass
{
    public void ModifyText(TextBox textBox)
    {
        textBox.Text = "New text";
    }
}

Access HTTP response as string in Go

The method you're using to read the http body response returns a byte slice:

func ReadAll(r io.Reader) ([]byte, error)

official documentation

You can convert []byte to a string by using

body, err := ioutil.ReadAll(resp.Body)
bodyString := string(body)

How to use andWhere and orWhere in Doctrine?

$q->where("a = 1")
  ->andWhere("b = 1 OR b = 2")
  ->andWhere("c = 2 OR c = 2")
  ;

How to always show the vertical scrollbar in a browser?

Tried to do the solution with:

body {
  overflow-y: scroll;
}

But I ended up with two scrollbars in Firefox in this case. So I recommend to use it on the html element like this:

html {
  overflow-y: scroll;
}

Get Bitmap attached to ImageView

This will get you a Bitmap from the ImageView. Though, it is not the same bitmap object that you've set. It is a new one.

imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();

=== EDIT ===

 imageView.setDrawingCacheEnabled(true);
 imageView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), 
                   MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
 imageView.layout(0, 0, 
                  imageView.getMeasuredWidth(), imageView.getMeasuredHeight()); 
 imageView.buildDrawingCache(true);
 Bitmap bitmap = Bitmap.createBitmap(imageView.getDrawingCache());
 imageView.setDrawingCacheEnabled(false);

How to match "any character" in regular expression?

There are lots of sophisticated regex testing and development tools, but if you just want a simple test harness in Java, here's one for you to play with:

    String[] tests = {
        "AAA123",
        "ABCDEFGH123",
        "XXXX123",
        "XYZ123ABC",
        "123123",
        "X123",
        "123",
    };
    for (String test : tests) {
        System.out.println(test + " " +test.matches(".+123"));
    }

Now you can easily add new testcases and try new patterns. Have fun exploring regex.

See also

What is the proper way to re-throw an exception in C#?

The first preserves the original stack trace of the exception, the second one replaces it with the current location.

Therefore the first is BY FAR the better.

Search an array for matching attribute

In this case i would use the ECMAscript 5 Array.filter. The following solution requires array.filter() that doesn't exist in all versions of IE.

Shims can be found here: MDN Array.filter or ES5-shim

var result = restaurants.filter(function (chain) {
    return chain.restaurant.food === "chicken";
})[0].restaurant.name;

How to deep watch an array in angularjs?

There are performance consequences to deep-diving an object in your $watch. Sometimes (for example, when changes are only pushes and pops), you might want to $watch an easily calculated value, such as array.length.

add onclick function to a submit button

I have this code:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<SCRIPT type=text/javascript>_x000D_
function deshabilitarBoton() {     _x000D_
    document.getElementById("boton").style.display = 'none';_x000D_
    document.getElementById("envio").innerHTML ="<br><img src='img/loading.gif' width='16' height='16' border='0'>Generando...";     _x000D_
    return true;_x000D_
} _x000D_
</SCRIPT>_x000D_
<title>untitled</title>_x000D_
</head>_x000D_
<body>_x000D_
<form name="form" action="ok.do" method="post" >_x000D_
<table>_x000D_
<tr>_x000D_
<td>Fecha inicio:</td>_x000D_
<td><input type="TEXT" name="fecha_inicio" id="fecha_inicio"  /></td>_x000D_
</tr>_x000D_
</table>_x000D_
<div id="boton">_x000D_
   <input type="submit" name="event" value="Enviar" class="button" onclick="return deshabilitarBoton()" />_x000D_
</div>_x000D_
<div id="envio">_x000D_
</div>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Does JavaScript guarantee object property order?

In modern browsers you can use the Map data structure instead of a object.

Developer mozilla > Map

A Map object can iterate its elements in insertion order...

How to write new line character to a file in Java

    PrintWriter out = null; // for writting in file    
    String newLine = System.getProperty("line.separator"); // taking new line 
    out.print("1st Line"+newLine); // print with new line
    out.print("2n Line"+newLine);  // print with new line
    out.close();

Script for rebuilding and reindexing the fragmented index?

The real answer, in 2016 and 2017, is: Use Ola Hallengren's scripts:

https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html

That is all any of us need to know or bother with, at this point in our mutual evolution.

How do I use properly CASE..WHEN in MySQL

CASE case_value
    WHEN when_value THEN statements
    [WHEN when_value THEN statements]
    ELSE statements
END 

Or:

CASE
WHEN <search_condition> THEN statements
[WHEN <search_condition> THEN statements] 
ELSE statements
END 

here CASE is an expression in 2nd scenario search_condition will evaluate and if no search_condition is equal then execute else

SELECT
   CASE course_enrollment_settings.base_price
    WHEN course_enrollment_settings.base_price = 0      THEN 1

should be

SELECT
   CASE 
    WHEN course_enrollment_settings.base_price = 0      THEN 1

How to install plugin for Eclipse from .zip

Seen here. You can unzip and

enter image description here enter image description here

Clicking Local will prefix your location fith file:/C:/etc/folder

You can Click archive instead and select your zip, as suggested in the second popular question. It will prefix with jar://path.zip but it is not accepted by Eclipse itself. So, I used the plain folder solution.

How can I select all children of an element except the last child?

When IE9 comes, it will be easier. A lot of the time though, you can switch the problem to one requiring :first-child and style the opposite side of the element (IE7+).

Multiple ping script in Python

import subprocess,os,threading,time
from queue import Queue
lock=threading.Lock()
_start=time.time()
def check(n):
    with open(os.devnull, "wb") as limbo:
                ip="192.168.21.{0}".format(n)
                result=subprocess.Popen(["ping", "-n", "1", "-w", "300", ip],stdout=limbo, stderr=limbo).wait()
                with lock:                    
                    if not result:
                        print (ip, "active")                    
                    else:
                        pass                        

def threader():
    while True:
        worker=q.get()
        check(worker)
        q.task_done()
q=Queue()

for x in range(255):
    t=threading.Thread(target=threader)
    t.daemon=True
    t.start()
for worker in range(1,255):
    q.put(worker)
q.join()
print("Process completed in: ",time.time()-_start)

I think this will be better one.

How can I install Python's pip3 on my Mac?

I solved the same problem with these commands:

curl -O https://bootstrap.pypa.io/get-pip.py
sudo python3 get-pip.py

python pandas: apply a function with arguments to a series

Series.apply(func, convert_dtype=True, args=(), **kwds)

args : tuple

x = my_series.apply(my_function, args = (arg1,))

Using the RUN instruction in a Dockerfile with 'source' does not work

If you're just trying to use pip to install something into the virtualenv, you can modify the PATH env to look in the virtualenv's bin folder first

ENV PATH="/path/to/venv/bin:${PATH}"

Then any pip install commands that follow in the Dockerfile will find /path/to/venv/bin/pip first and use that, which will install into that virtualenv and not the system python.

Global javascript variable inside document.ready

like this: put intro outside your document ready, Good discussion here: http://forum.jquery.com/topic/how-do-i-declare-a-global-variable-in-jquery @thecodeparadox is awesomely fast :P anyways!

 var intro;

$(document).ready(function() {



    if ($('.intro_check').is(':checked')) {
        intro = true;
        $('.intro').wrap('<div class="disabled"></div>');
    };

    $('.intro_check').change(function(){
        if(this.checked) {
            intro = false;
            $('.enabled').removeClass('enabled').addClass('disabled');
        } else {
            intro = true;
            if($('.intro').exists()) {
                $('.disabled').removeClass('disabled').addClass('enabled'); 
            } else {
                $('.intro').wrap('<div class="disabled"></div>');
            }
        }
    });
});

How to find/identify large commits in git history?

I was unable to make use of the most popular answer because the --batch-check command-line switch to Git 1.8.3 (that I have to use) does not accept any arguments. The ensuing steps have been tried on CentOS 6.5 with Bash 4.1.2

Key Concepts

In Git, the term blob implies the contents of a file. Note that a commit might change the contents of a file or pathname. Thus, the same file could refer to a different blob depending on the commit. A certain file could be the biggest in the directory hierarchy in one commit, while not in another. Therefore, the question of finding large commits instead of large files, puts matters in the correct perspective.

For The Impatient

Command to print the list of blobs in descending order of size is:

git cat-file --batch-check < <(git rev-list --all --objects  | \
awk '{print $1}')  | grep blob  | sort -n -r -k 3

Sample output:

3a51a45e12d4aedcad53d3a0d4cf42079c62958e blob 305971200
7c357f2c2a7b33f939f9b7125b155adbd7890be2 blob 289163620

To remove such blobs, use the BFG Repo Cleaner, as mentioned in other answers. Given a file blobs.txt that just contains the blob hashes, for example:

3a51a45e12d4aedcad53d3a0d4cf42079c62958e
7c357f2c2a7b33f939f9b7125b155adbd7890be2

Do:

java -jar bfg.jar -bi blobs.txt <repo_dir>

The question is about finding the commits, which is more work than finding blobs. To know, please read on.

Further Work

Given a commit hash, a command that prints hashes of all objects associated with it, including blobs, is:

git ls-tree -r --full-tree <commit_hash>

So, if we have such outputs available for all commits in the repo, then given a blob hash, the bunch of commits are the ones that match any of the outputs. This idea is encoded in the following script:

#!/bin/bash
DB_DIR='trees-db'

find_commit() {
    cd ${DB_DIR}
    for f in *; do
        if grep -q $1 ${f}; then
            echo ${f}
        fi
    done
    cd - > /dev/null
}

create_db() {
    local tfile='/tmp/commits.txt'
    mkdir -p ${DB_DIR} && cd ${DB_DIR}
    git rev-list --all > ${tfile}

    while read commit_hash; do
        if [[ ! -e ${commit_hash} ]]; then
            git ls-tree -r --full-tree ${commit_hash} > ${commit_hash}
        fi
    done < ${tfile}
    cd - > /dev/null
    rm -f ${tfile}
}

create_db

while read id; do
    find_commit ${id};
done

If the contents are saved in a file named find-commits.sh then a typical invocation will be as under:

cat blobs.txt | find-commits.sh

As earlier, the file blobs.txt lists blob hashes, one per line. The create_db() function saves a cache of all commit listings in a sub-directory in the current directory.

Some stats from my experiments on a system with two Intel(R) Xeon(R) CPU E5-2620 2.00GHz processors presented by the OS as 24 virtual cores:

  • Total number of commits in the repo = almost 11,000
  • File creation speed = 126 files/s. The script creates a single file per commit. This occurs only when the cache is being created for the first time.
  • Cache creation overhead = 87 s.
  • Average search speed = 522 commits/s. The cache optimization resulted in 80% reduction in running time.

Note that the script is single threaded. Therefore, only one core would be used at any one time.

How to set the focus for a particular field in a Bootstrap modal, once it appears

A little cleaner and more modular solution might be:

$(document).ready(function(){
    $('.modal').success(function() { 
        $('input:text:visible:first').focus();
    });  
});

Or using your ID as an example instead:

$(document).ready(function(){
    $('#modal-content').modal('show').success(function() {
        $('input:text:visible:first').focus();
    });  
});

Hope that helps..

Jquery get input array field

You need to use the starts with selector

var elems = $( "[name^='pages_title']" );

But a better solution is to add a class to the elements and reference the class. The reason it is a faster look up.

php $_GET and undefined index

Actually none of the proposed answers, although a good practice, would remove the warning.

For the sake of correctness, I'd do the following:

function getParameter($param, $defaultValue) {
    if (array_key_exists($param, $_GET)) {
        $value=$_GET[$param];
        return isSet($value)?$value:$defaultValue;
    }
    return $defaultValue;
}

This way, I check the _GET array for the key to exist without triggering the Warning. It's not a good idea to disable the warnings because a lot of times they are at least interesting to take a look.

To use the function you just do:

$myvar = getParameter("getparamer", "defaultValue")

so if the parameter exists, you get the value, and if it doesnt, you get the defaultValue.

Get request URL in JSP which is forwarded by Servlet

Try this instead:

String scheme = req.getScheme();             
String serverName = req.getServerName(); 
int serverPort = req.getServerPort();    
String uri = (String) req.getAttribute("javax.servlet.forward.request_uri");
String prmstr = (String) req.getAttribute("javax.servlet.forward.query_string");
String url = scheme + "://" +serverName + ":" + serverPort + uri + "?" + prmstr;

Note: You can't get HREF anchor from your url. Example, if you have url "toc.html#top" then you can get only "toc.html"

Note: req.getAttribute("javax.servlet.forward.request_uri") work only in JSP. if you run this in controller before JSP then result is null

You can use code for both variant:

public static String getCurrentUrl(HttpServletRequest req) {
    String url = getCurrentUrlWithoutParams(req);
    String prmstr = getCurrentUrlParams(req);
    url += "?" + prmstr;
    return url;
}

public static String getCurrentUrlParams(HttpServletRequest request) {
    return StringUtil.safeString(request.getQueryString());
}

public static String getCurrentUrlWithoutParams(HttpServletRequest request) {
    String uri = (String) request.getAttribute("javax.servlet.forward.request_uri");
    if (uri == null) {
        return request.getRequestURL().toString();
    }
    String scheme = request.getScheme();
    String serverName = request.getServerName();
    int serverPort = request.getServerPort();
    String url = scheme + "://" + serverName + ":" + serverPort + uri;
    return url;
}

Redirecting output to $null in PowerShell, but ensuring the variable remains set

Warning messages should be written using the Write-Warning cmdlet, which allows the warning messages to be suppressed with the -WarningAction parameter or the $WarningPreference automatic variable. A function needs to use CmdletBinding to implement this feature.

function WarningTest {
    [CmdletBinding()]
    param($n)

    Write-Warning "This is a warning message for: $n."
    "Parameter n = $n"
}

$a = WarningTest 'test one' -WarningAction SilentlyContinue

# To turn off warnings for multiple commads,
# use the WarningPreference variable
$WarningPreference = 'SilentlyContinue'
$b = WarningTest 'test two'
$c = WarningTest 'test three'
# Turn messages back on.
$WarningPreference = 'Continue'
$c = WarningTest 'test four'

To make it shorter at the command prompt, you can use -wa 0:

PS> WarningTest 'parameter alias test' -wa 0

Write-Error, Write-Verbose and Write-Debug offer similar functionality for their corresponding types of messages.

LD_LIBRARY_PATH vs LIBRARY_PATH

Since I link with gcc why ld is being called, as the error message suggests?

gcc calls ld internally when it is in linking mode.

Is there a way to check which CSS styles are being used or not used on a web page?

I'm using CSS Dig. It is made for chrome, but I think it is a great tool!

How to best display in Terminal a MySQL SELECT returning too many fields?

Just to complement the answer that I thought best, I also use less -SFX but in a different way: I like to ad it to my .my.cnf file in my home folder, an example cnf file looks like this:

[client]
user=root
password=MyPwD
[mysql]
pager='less -SFX'

The good thing about having it this way, is that less is only used when the output of a query is actually more than one page long, here is the explanation of all the flags:

  • -S: Single line, don't skip line when line is wider than screen, instead allow to scroll to the right.
  • -F: Quit if one screen, if content doesn't need scrolling then just send to stdout.
  • -X: No init, disables any output "less" might have configured to output every time it loads.

Note: in the .my.cnf file don't put the pager command below the [client] keyword; although it might work with mysql well, mysqldump will complain about not recognizing it.

How to change to an older version of Node.js

On windows 7 I used the general 'Uninstall Node.js' (just started typing in the search bottom left ,main menu field) followed by clicking the link to the older version which complies with the project, for instance: Windows 64-bit Installer: https://nodejs.org/dist/v4.4.6/node-v4.4.6-x64.msi

Phone mask with jQuery and Masked Input Plugin

The best way to do this is using the change event like this:

$("#phone")
.mask("(99) 9999?9-9999")
.on("change", function() {

    var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );

    if( last.length == 3 ) {
        var move = $(this).val().substr( $(this).val().indexOf("-") - 1, 1 );
        var lastfour = move + last;
        var first = $(this).val().substr( 0, 9 ); // Change 9 to 8 if you prefer mask without space: (99)9999?9-9999

        $(this).val( first + '-' + lastfour );
    }
})
.change(); // Trigger the event change to adjust the mask when the value comes setted. Useful on edit forms.

How to check for changes on remote (origin) Git repository

git remote update && git status 

Found this on the answer to Check if pull needed in Git

git remote update to bring your remote refs up to date. Then you can do one of several things, such as:

  1. git status -uno will tell you whether the branch you are tracking is ahead, behind or has diverged. If it says nothing, the local and remote are the same.

  2. git show-branch *master will show you the commits in all of the branches whose names end in master (eg master and origin/master).

If you use -v with git remote update you can see which branches got updated, so you don't really need any further commands.

Newline in string attribute

May be you can use the attribute xml:space="preserve" for preserving whitespace in the source XAML

<TextBlock xml:space="preserve">
Stuff on line 1
Stuff on line 2
</TextBlock>

Group by multiple field names in java 8

The groupingBy method has the first parameter is Function<T,K> where:

@param <T> the type of the input elements

@param <K> the type of the keys

If we replace lambda with the anonymous class in your code, we can see some kind of that:

people.stream().collect(Collectors.groupingBy(new Function<Person, int>() {
            @Override
            public int apply(Person person) {
                return person.getAge();
            }
        }));

Just now change output parameter<K>. In this case, for example, I used a pair class from org.apache.commons.lang3.tuple for grouping by name and age, but you may create your own class for filtering groups as you need.

people.stream().collect(Collectors.groupingBy(new Function<Person, Pair<Integer, String>>() {
                @Override
                public YourFilter apply(Person person) {
                    return Pair.of(person.getAge(), person.getName());
                }
            }));

Finally, after replacing with lambda back, code looks like that:

Map<Pair<Integer,String>, List<Person>> peopleByAgeAndName = people.collect(Collectors.groupingBy(p -> Pair.of(person.getAge(), person.getName()), Collectors.mapping((Person p) -> p, toList())));

Finding an item in a List<> using C#

item = objects.Find(obj => obj.property==myValue);

warning: control reaches end of non-void function [-Wreturn-type]

You can also use EXIT_SUCCESS instead of return 0;. The macro EXIT_SUCCESS is actually defined as zero, but makes your program more readable.

How to parse JSON data with jQuery / JavaScript?

Use that code.

     $.ajax({

            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "Your URL",
            data: "{}",
            dataType: "json",
            success: function (data) {
                alert(data);
            },
            error: function (result) {
                alert("Error");
            }
        });

SELECT COUNT in LINQ to SQL C#

You should be able to do the count on the purch variable:

purch.Count();

e.g.

var purch = from purchase in myBlaContext.purchases
select purchase;

purch.Count();

jQuery get the location of an element relative to window

TL;DR

headroom_by_jQuery = $('#id').offset().top - $(window).scrollTop();

headroom_by_DOM = $('#id')[0].getBoundingClientRect().top;   // if no iframe

.getBoundingClientRect() appears to be universal. .offset() and .scrollTop() have been supported since jQuery 1.2. Thanks @user372551 and @prograhammer. To use DOM in an iframe see @ImranAnsari's solution.

Distinct pair of values SQL

If you just want a count of the distinct pairs.

The simplest way to do that is as follows SELECT COUNT(DISTINCT a,b) FROM pairs

The previous solutions would list all the pairs and then you'd have to do a second query to count them.

Delete specific values from column with where condition?

You can also use REPLACE():

UPDATE Table
   SET Column = REPLACE(Column, 'Test123', 'Test')

VBA Excel sort range by specific column

Try this code:

Dim lastrow As Long
lastrow = Cells(Rows.Count, 2).End(xlUp).Row
Range("A3:D" & lastrow).Sort key1:=Range("B3:B" & lastrow), _
   order1:=xlAscending, Header:=xlNo

Datatable select with multiple conditions

Yes, the DataTable.Select method supports boolean operators in the same way that you would use them in a "real" SQL statement:

DataRow[] results = table.Select("A = 'foo' AND B = 'bar' AND C = 'baz'");

See DataColumn.Expression in MSDN for the syntax supported by DataTable's Select method.

Java path..Error of jvm.cfg

I was facing the same issue after upgrading my java version.I had more than one jdk installation. I have manually uninstalled the old jdk version . Then it worked for me.

Open Redis port for remote connections

  1. Open $REDIS_HOME/redis.conf and uncomment requirepass -YOUR-PASSWORD-HERE- and write down your password in the specified lines.

  2. Login to redis using redis-cli and verify your password in the database using auth -YOUR-PASSWORD-HERE- command.

  3. Disable protected mode by changing its string in $REDIS_HOME/redis.conf to protected-mode no.

  4. Search for all bind ports values and comment all of them. Just add bind 0.0.0.0 to $REDIS_HOME/redis.conf file.

  5. Disable your firewall or open redis port.

  6. Start redis using ./redis-server $REDIS_HOME/redis.conf.

  7. Check the configuration via ./redis-cli -h -YOUR-IP- -a -YOUR-PASSWORD-HERE-.

  8. Check the configuration via ./redis-cli -h -YOUR-IP- ping.

How to do a non-greedy match in grep?

grep

For non-greedy match in grep you could use a negated character class. In other words, try to avoid wildcards.

For example, to fetch all links to jpeg files from the page content, you'd use:

grep -o '"[^" ]\+.jpg"'

To deal with multiple line, pipe the input through xargs first. For performance, use ripgrep.

How to randomly select rows in SQL?

In order to shuffle the SQL result set, you need to use a database-specific function call.

Note that sorting a large result set using a RANDOM function might turn out to be very slow, so make sure you do that on small result sets.

If you have to shuffle a large result set and limit it afterward, then it's better to use something like the Oracle SAMPLE(N) or the TABLESAMPLE in SQL Server or PostgreSQL instead of a random function in the ORDER BY clause.

So, assuming we have the following database table:

Song database table

And the following rows in the song table:

| id | artist                          | title                              |
|----|---------------------------------|------------------------------------|
| 1  | Miyagi & ???????? ft. ??? ????? | I Got Love                         |
| 2  | HAIM                            | Don't Save Me (Cyril Hahn Remix)   |
| 3  | 2Pac ft. DMX                    | Rise Of A Champion (GalilHD Remix) |
| 4  | Ed Sheeran & Passenger          | No Diggity (Kygo Remix)            |
| 5  | JP Cooper ft. Mali-Koa          | All This Love                      |

Oracle

On Oracle, you need to use the DBMS_RANDOM.VALUE function, as illustrated by the following example:

SELECT
    artist||' - '||title AS song
FROM song
ORDER BY DBMS_RANDOM.VALUE

When running the aforementioned SQL query on Oracle, we are going to get the following result set:

| song                                              |
|---------------------------------------------------|
| JP Cooper ft. Mali-Koa - All This Love            |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| Miyagi & ???????? ft. ??? ????? - I Got Love      |

Notice that the songs are being listed in random order, thanks to the DBMS_RANDOM.VALUE function call used by the ORDER BY clause.

SQL Server

On SQL Server, you need to use the NEWID function, as illustrated by the following example:

SELECT
    CONCAT(CONCAT(artist, ' - '), title) AS song
FROM song
ORDER BY NEWID()

When running the aforementioned SQL query on SQL Server, we are going to get the following result set:

| song                                              |
|---------------------------------------------------|
| Miyagi & ???????? ft. ??? ????? - I Got Love      |
| JP Cooper ft. Mali-Koa - All This Love            |
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |

Notice that the songs are being listed in random order, thanks to the NEWID function call used by the ORDER BY clause.

PostgreSQL

On PostgreSQL, you need to use the random function, as illustrated by the following example:

SELECT
    artist||' - '||title AS song
FROM song
ORDER BY random()

When running the aforementioned SQL query on PostgreSQL, we are going to get the following result set:

| song                                              |
|---------------------------------------------------|
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| JP Cooper ft. Mali-Koa - All This Love            |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Miyagi & ???????? ft. ??? ????? - I Got Love      |

Notice that the songs are being listed in random order, thanks to the random function call used by the ORDER BY clause.

MySQL

On MySQL, you need to use the RAND function, as illustrated by the following example:

SELECT
  CONCAT(CONCAT(artist, ' - '), title) AS song
FROM song
ORDER BY RAND()

When running the aforementioned SQL query on MySQL, we are going to get the following result set:

| song                                              |
|---------------------------------------------------|
| HAIM - Don't Save Me (Cyril Hahn Remix)           |
| Ed Sheeran & Passenger - No Diggity (Kygo Remix)  |
| Miyagi & ???????? ft. ??? ????? - I Got Love      |
| 2Pac ft. DMX - Rise Of A Champion (GalilHD Remix) |
| JP Cooper ft. Mali-Koa - All This Love            |

Notice that the songs are being listed in random order, thanks to the RAND function call used by the ORDER BY clause.

Is there a CSS selector for the first direct child only?

What you posted literally means "Find any divs that are inside of section divs and are the first child of their parent." The sub contains one tag that matches that description.

It is unclear to me whether you want both children of the main div or not. If so, use this:

div.section > div

If you only want the header, use this:

div.section > div:first-child

Using the > changes the description to: "Find any divs that are the direct descendents of section divs" which is what you want.

Please note that all major browsers support this method, except IE6. If IE6 support is mission-critical, you will have to add classes to the child divs and use that, instead. Otherwise, it's not worth caring about.

#1071 - Specified key was too long; max key length is 767 bytes

My fix to this very same issue was to add an option as a 3rd argument: charset

queryInterface.createTable(
  tableName,
  { /*... columns*/ },
  { charset: 'utf8' } 
)

Otherwise sequelize would create tables as utf8mb4.

using stored procedure in entity framework

Simple. Just instantiate your entity, set it to an object and pass it to your view in your controller.

enter image description here

Entity

VehicleInfoEntities db = new VehicleInfoEntities();

Stored Procedure

dbo.prcGetMakes()

or

you can add any parameters in your stored procedure inside the brackets ()

dbo.prcGetMakes("BMW")

Controller

public class HomeController : Controller
{
    VehicleInfoEntities db = new VehicleInfoEntities();

    public ActionResult Index()
    {
        var makes = db.prcGetMakes(null);

        return View(makes);
    }
}

hadoop No FileSystem for scheme: file

Another possible cause (though the OPs question doesn't itself suffer from this) is if you create a configuration instance that does not load the defaults:

Configuration config = new Configuration(false);

If you don't load the defaults then you won't get the default settings for things like the FileSystem implementations which leads to identical errors like this when trying to access HDFS. Switching to the parameterless constructor of passing in true to load defaults may resolve this.

Additionally if you are adding custom configuration locations (e.g. on the file system) to the Configuration object be careful of which overload of addResource() you use. For example if you use addResource(String) then Hadoop assumes that the string is a class path resource, if you need to specify a local file try the following:

File configFile = new File("example/config.xml");
config.addResource(new Path("file://" + configFile.getAbsolutePath()));

tkinter: how to use after method

I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.

Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None))

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

This is a bug in pycharm. PyCharm seems to be expecting the referenced module to be included in an __all__ = [] statement.

For proper coding etiquette, should you include the __all__ statement from your modules? ..this is actually the question we hear young Spock answering while he was being tested, to which he responded: "It is morally praiseworthy but not morally obligatory."

To get around it, you can simply disable that (extremely non-critical) (highly useful) inspection globally, or suppress it for the specific function or statement.

To do so:

  • put the caret over the erroring text ('choice', from your example above)
  • Bring up the intention menu (alt-enter by default, mine is set to alt-backspace)
  • hit the right arrow to open the submenu, and select the relevant action

PyCharm has its share of small bugs like this, but in my opinion its benefits far outweigh its drawbacks. If you'd like to try another good IDE, there's also Spyder/Spyderlib.

I know this is quite a bit after you asked your question, but I hope this helps (you, or someone else).

Edited: Originally, I thought that this was specific to checking __all__, but it looks like it's the more general 'Unresolved References' check, which can be very useful. It's probably best to use statement-level disabling of the feature, either by using the menu as mentioned above, or by specifying # noinspection PyUnresolvedReferences on the line preceding the statement.

Not able to change TextField Border Color

The new way to do it is to use enabledBorder like this:

new TextField(
  decoration: new InputDecoration(
    enabledBorder: const OutlineInputBorder(
      borderSide: const BorderSide(color: Colors.grey, width: 0.0),
    ),
    focusedBorder: ...
    border: ...
  ),
)

Only mkdir if it does not exist

mkdir -p

-p, --parents no error if existing, make parent directories as needed

SQL Query to add a new column after an existing column in SQL Server 2005

According to my research there is no way to do this exactly the way you want. You can manually re-create the table and copy the data, or SSMS can (and will) do this for you (when you drag and drop a column to a different order, it does this). In fact it souldn't matter what order the columns are... As an alternative solution you can select the data you want in the order you desired. For example, instead of using asterisk (*) in select, specify the column names in some order... Lets say MyTable has col1, col2, col3, colNew columns.

Instead of:

SELECT * FROM MyTable

You can use:

SELECT col1, colNew, col2, col3 FROM MyTable

jQuery: select an element's class and id at the same time?

Just to add that the answer that Alex provided worked for me, and not the one that is highlighted as an answer.

This one didn't work for me

$('#country.save') 

But this one did:

$('#country .save') 

so my conclusion is to use the space. Now I don't know if it's to the new version of jQuery that I'm using (1.5.1), but anyway hope this helps to anyone with similar problem that I've had.

edit: Full credit for explanation (in the comment to Alex's answer) goes to Felix Kling who says:

The space is the descendant selector, i.e. A B means "Match all elements that match B which are a descendant of elements matching A". AB means "select all element that match A and B". So it really depends on what you want to achieve. #country.save and #country .save are not equivalent.

How to mark a method as obsolete or deprecated?

With ObsoleteAttribute you can to show the deprecated method. Obsolete attribute has three constructor:

  1. [Obsolete]: is a no parameter constructor and is a default using this attribute.
  2. [Obsolete(string message)]: in this format you can get message of why this method is deprecated.
  3. [Obsolete(string message, bool error)]: in this format message is very explicit but error means, in compilation time, compiler must be showing error and cause to fail compiling or not.

enter image description here

How to make rectangular image appear circular with CSS

I've been researching this very same problem and couldn't find a decent solution other than having the div with the image as background and the img tag inside of it with visibility none or something like this.

One thing I might add is that you should add a background-size: cover to the div, so that your image fills the background by clipping it's excess.

Using node.js as a simple web server

Node.js webserver from scratch


No 3rd-party frameworks; Allows query string; Adds trailing slash; Handles 404


Create a public_html subfolder and place all of your content in it.


Gist: https://gist.github.com/veganaize/fc3b9aa393ca688a284c54caf43a3fc3

var fs = require('fs');

require('http').createServer(function(request, response) {
  var path = 'public_html'+ request.url.slice(0,
      (request.url.indexOf('?')+1 || request.url.length+1) - 1);
      
  fs.stat(path, function(bad_path, path_stat) {
    if (bad_path) respond(404);
    else if (path_stat.isDirectory() && path.slice(-1) !== '/') {
      response.setHeader('Location', path.slice(11)+'/');
      respond(301);
    } else fs.readFile(path.slice(-1)==='/' ? path+'index.html' : path,
          function(bad_file, file_content) {
      if (bad_file) respond(404);
      else respond(200, file_content);
    });
  });
 
  function respond(status, content) {
    response.statusCode = status;
    response.end(content);
  }
}).listen(80, function(){console.log('Server running on port 80...')});

adding multiple entries to a HashMap at once in one statement

Another approach may be writing special function to extract all elements values from one string by regular-expression:

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
    public static void main (String[] args){
        HashMap<String,Integer> hashMapStringInteger = createHashMapStringIntegerInOneStat("'one' => '1', 'two' => '2' , 'three'=>'3'  ");

        System.out.println(hashMapStringInteger); // {one=1, two=2, three=3}
    }

    private static HashMap<String, Integer> createHashMapStringIntegerInOneStat(String str) {
        HashMap<String, Integer> returnVar = new HashMap<String, Integer>();

        String currentStr = str;
        Pattern pattern1 = Pattern.compile("^\\s*'([^']*)'\\s*=\\s*>\\s*'([^']*)'\\s*,?\\s*(.*)$");

        // Parse all elements in the given string.
        boolean thereIsMore = true;
        while (thereIsMore){
            Matcher matcher = pattern1.matcher(currentStr);
            if (matcher.find()) {
                returnVar.put(matcher.group(1),Integer.valueOf(matcher.group(2)));
                currentStr = matcher.group(3);
            }
            else{
                thereIsMore = false;
            }
        }

        // Validate that all elements in the given string were parsed properly
        if (currentStr.length() > 0){
            System.out.println("WARNING: Problematic string format. given String: " + str);
        }

        return returnVar;
    }
}

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

As pointed out by @Jayan in another post, the solution was to do the following

import jenkins.model.*
jenkins = Jenkins.instance

Then I was able to do the rest of my scripting the way it was.

Open a PDF using VBA in Excel

Use Shell "program file path file path you want to open".

Example:

Shell "c:\windows\system32\mspaint.exe c:users\admin\x.jpg"

How to convert this var string to URL in Swift

in swift 4 to convert to url use URL

let fileUrl = URL.init(fileURLWithPath: filePath)

or

let fileUrl = URL(fileURLWithPath: filePath)

“Unable to find manifest signing certificate in the certificate store” - even when add new key

Assuming this is a personal certificate created by windows on the system you copied your project from, you can use the certificate manager on the system where the project is now and import the certificate. Start the certificate manager (certmgr) and select the personal certificates then right click below the list of existing certificates and select import from the tasks. Use the browse to find the .pfx in the project (the .pfx from the previous system that you copied over with the project). It should be in the sub-directory with the same name as the project directory. I am familiar with C# and VS, so if that is not your environment maybe the .pfx will be elsewhere or maybe this suggestion does not apply. After the import you should get a status message. If you succeeded, the compile certificate error should be gone.certmgr screen

Insert text into textarea with jQuery

this one allow you "inject" a piece of text to textbox, inject means: appends the text where cursor is.

function inyectarTexto(elemento,valor){
 var elemento_dom=document.getElementsByName(elemento)[0];
 if(document.selection){
  elemento_dom.focus();
  sel=document.selection.createRange();
  sel.text=valor;
  return;
 }if(elemento_dom.selectionStart||elemento_dom.selectionStart=="0"){
  var t_start=elemento_dom.selectionStart;
  var t_end=elemento_dom.selectionEnd;
  var val_start=elemento_dom.value.substring(0,t_start);
  var val_end=elemento_dom.value.substring(t_end,elemento_dom.value.length);
  elemento_dom.value=val_start+valor+val_end;
 }else{
  elemento_dom.value+=valor;
 }
}

And you can use it like this:

<a href="javascript:void(0);" onclick="inyectarTexto('nametField','hello world');" >Say hello world to text</a>

Funny and have more sence when we have "Insert Tag into Text" functionality.

works in all browsers.

How do I write a Python dictionary to a csv file?

Your code was very close to working.

Try using a regular csv.writer rather than a DictWriter. The latter is mainly used for writing a list of dictionaries.

Here's some code that writes each key/value pair on a separate row:

import csv

somedict = dict(raymond='red', rachel='blue', matthew='green')
with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerows(somedict.items())

If instead you want all the keys on one row and all the values on the next, that is also easy:

with open('mycsvfile.csv','wb') as f:
    w = csv.writer(f)
    w.writerow(somedict.keys())
    w.writerow(somedict.values())

Pro tip: When developing code like this, set the writer to w = csv.writer(sys.stderr) so you can more easily see what is being generated. When the logic is perfected, switch back to w = csv.writer(f).

Can lambda functions be templated?

I am aware that this question is about C++11. However, for those who googled and landed on this page, templated lambdas are now supported in C++14 and go by the name Generic Lambdas.

[info] Most of the popular compilers support this feature now. Microsoft Visual Studio 2015 supports. Clang supports. GCC supports.

C#: easiest way to populate a ListBox from a List

This also could be easiest way to add items in ListBox.

for (int i = 0; i < MyList.Count; i++)
{
        listBox1.Items.Add(MyList.ElementAt(i));
}

Further improvisation of this code can add items at runtime.

Declare a constant array

From Effective Go:

Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.

Slices and arrays are always evaluated during runtime:

var TestSlice = []float32 {.03, .02}
var TestArray = [2]float32 {.03, .02}
var TestArray2 = [...]float32 {.03, .02}

[...] tells the compiler to figure out the length of the array itself. Slices wrap arrays and are easier to work with in most cases. Instead of using constants, just make the variables unaccessible to other packages by using a lower case first letter:

var ThisIsPublic = [2]float32 {.03, .02}
var thisIsPrivate = [2]float32 {.03, .02}

thisIsPrivate is available only in the package it is defined. If you need read access from outside, you can write a simple getter function (see Getters in golang).

How to remove responsive features in Twitter Bootstrap 3?

This is explained in the official Bootstrap 3 release docs:

Steps to disable responsive views

To disable responsive features, follow these steps. See it in action in the modified template below.

  1. Remove (or just don't add) the viewport <meta> mentioned in the CSS docs
  2. Remove the max-width on the .container for all grid tiers with max-width: none !important; and set a regular width like width: 970px;. Be sure that this comes after the default Bootstrap CSS. You can optionally avoid the !important with media queries or some selector-fu.
  3. If using navbars, undo all the navbar collapsing and expanding behavior (this is too much to show here, so peep the example).
  4. For grid layouts, make use of .col-xs-* classes in addition to or in place of the medium/large ones. Don't worry, the extra-small device grid scales up to all resolutions, so you're set there.

You'll still need Respond.js for IE8 (since our media queries are still there and need to be picked up). This just disables the "mobile site" of Bootstrap.

See also the example on GetBootstrap.com/examples/non-responsive/

Laravel 5 – Remove Public from URL

Laravel 5.5

After having installed Laravel for the first time, I faced the renowned "public folder problem" and I came up with this solution that, in my personal opinion, is "cleaner" then the others I found on the Web.


Achievements

  • Don't have public word in the URI
  • Protect the .env file against curious people

Everything can be done just editing the .htaccess using mod_rewrite and four simple rules.


Steps

  1. Move the .htaccess file in public/.htaccess in the main root
  2. Edit it as below

I commented everything, so it should be clear (I hope) also to those who have never used mod_rewrite (not that I'm an expert, all the opposite). Also, to understand the rules, it must be clear that, in Laravel, if Bill connects to https://example.com, https://example.com/index.php is loaded. This file just contains the command header("refresh: 5; https://example.com/public/"), which sends the request to https://example.com/public/index.php. This second index.php is responsible to load the controller and other stuff.

# IfModule prevents the server error if the app is moved in an environment which doesn’t support mod_rewrite
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # RULES ORIGINALLY IN public/.htaccess ---
    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
#    RewriteCond %{REQUEST_FILENAME} !-d
#    RewriteCond %{REQUEST_FILENAME} !-f
#    RewriteRule ^ index.php [L]

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
    # --- END

    # PERSONAL RULES ---
    # All the requests on port 80 are redirected on HTTPS
    RewriteCond %{SERVER_PORT} ^80$
    RewriteRule .* https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

    # When .env file is requested, server redirects to 404
    RewriteRule ^\.env$ - [R=404,L,NC]

    # If the REQUEST_URI is empty (means: http://example.com), it loads /public/index.php
    # N.B.: REQUEST_URI is *never* actually empty, it contains a slash that must be set as match as below
    # .* means: anything can go here at least 0 times (= accepts any sequence of characters, including an empty string)
    RewriteCond %{REQUEST_URI} ^/$
    RewriteRule ^(.*) /public/index.php [L]

    # If the current request is asking for a REQUEST_FILENAME that:
    # a) !== existent directory
    # b) !== existent file
    # => if URI !== css||js||images/whatever => server loads /public/index.php, which is responsible to load the app and the related controller
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule !^(css|js|images|media)/(.*)$ /public/index.php [L,NC]

    # If the current request is asking for a REQUEST_FILENAME that:
    # a) !== existent directory
    # b) !== existent file
    # => if URI == css||js||images[=$1]/whatever[=$2] => server loads the resource at public/$1/$2
    # If R flag is added, the server not only loads the resource at public/$1/$2 but redirects to it
    # e.g.: bamboo.jpg resides in example.com/public/media/bamboo.jpg
    #       Client asks for example.com/media/bamboo.jpg
    #       Without R flag: the URI remains example.com/media/bamboo.jpg and loads the image
    #       With R flag: the server redirects the client to example.com/public/media/bamboo.jpg and loads the image
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(css|js|images|media)/(.*)$ /public/$1/$2 [L,NC]
    # --- END

</IfModule>

The following rule (originally in public/.htaccess) can be deleted. The same rule, in fact, is explicited in a more detailed way in the last two rules.

# Handle Front Controller...
#    RewriteCond %{REQUEST_FILENAME} !-d
#    RewriteCond %{REQUEST_FILENAME} !-f
#    RewriteRule ^ index.php [L]

EDIT: I missed Abhinav Saraswat's solution and his answer should be the accepted one. Just one, simple and clear rule that redirects all the traffic to the public folder without modifying any file.

How to hide the border for specified rows of a table?

Add programatically noborder class to specific row to hide it

<style>
     .noborder
      {
        border:none;
      }
    </style>

<table>

    <tr>
       <th>heading1</th>
       <th>heading2</th>
    </tr>


    <tr>
       <td>content1</td>
       <td>content2</td>
    </tr>
    /*no border for this row */
    <tr class="noborder">
       <td>content1</td>
       <td>content2</td>
    </tr>

</table>

Is it possible to output a SELECT statement from a PL/SQL block?

From an anonymous block? I'd like to now more about the situation where you think that to be required, because with subquery factoring clauses and inline views it's pretty rare that you need to resort to PL/SQL for anything other than the most complex situations.

If you can use a named procedure then use pipelined functions. Here's an example pulled from the documentation:

CREATE PACKAGE pkg1 AS
  TYPE numset_t IS TABLE OF NUMBER;
  FUNCTION f1(x NUMBER) RETURN numset_t PIPELINED;
END pkg1;
/

CREATE PACKAGE BODY pkg1 AS
-- FUNCTION f1 returns a collection of elements (1,2,3,... x)
FUNCTION f1(x NUMBER) RETURN numset_t PIPELINED IS
  BEGIN
    FOR i IN 1..x LOOP
      PIPE ROW(i);
    END LOOP;
    RETURN;
  END;
END pkg1;
/

-- pipelined function is used in FROM clause of SELECT statement
SELECT * FROM TABLE(pkg1.f1(5));

How can one change the timestamp of an old commit in Git?

There are already many great answers, but when I want to change date for multiple commits in one day or in one month, I don't find a proper answer. So I create a new script for this with explaintion, hope it will help someone:

#!/bin/bash

# change GIT_AUTHOR_DATE for commit at Thu Sep 14 13:39:41 2017 +0800
# you can change the data_match to change all commits at any date, one day or one month
# you can also do the same for GIT_COMMITTER_DATE

git filter-branch --force --env-filter '

date_match="^Thu, 14 Sep 2017 13+"              

# GIT_AUTHOR_DATE will be @1505367581 +0800, Git internal format 
author_data=$GIT_AUTHOR_DATE;                   
author_data=${author_data#@}                  
author_data=${author_data% +0800}                # author_data is 1505367581     

oneday=$((24*60*60))

# author_data_str will be "Thu, 14 Sep 2017 13:39:41 +0800", RFC2822 format
author_data_str=`date -R -d @$author_data`      

if [[ $author_data_str =~ $date_match ]];
then
    # remove one day from author_data
    new_data_sec=$(($author_data-$oneday))
    # change to git internal format based on new_data_sec
    new_data="@$new_data_sec +0800"             
    export GIT_AUTHOR_DATE="$new_data"
fi
' --tag-name-filter cat -- --branches --tags

The date will be changed:

AuthorDate: Wed Sep 13 13:39:41 2017 +0800

Set Culture in an ASP.Net MVC app

What is the best place is your question. The best place is inside the Controller.Initialize method. MSDN writes that it is called after the constructor and before the action method. In contrary of overriding OnActionExecuting, placing your code in the Initialize method allow you to benefit of having all custom data annotation and attribute on your classes and on your properties to be localized.

For example, my localization logic come from an class that is injected to my custom controller. I have access to this object since Initialize is called after the constructor. I can do the Thread's culture assignation and not having every error message displayed correctly.

 public BaseController(IRunningContext runningContext){/*...*/}

 protected override void Initialize(RequestContext requestContext)
 {
     base.Initialize(requestContext);
     var culture = runningContext.GetCulture();
     Thread.CurrentThread.CurrentUICulture = culture;
     Thread.CurrentThread.CurrentCulture = culture;
 }

Even if your logic is not inside a class like the example I provided, you have access to the RequestContext which allow you to have the URL and HttpContext and the RouteData which you can do basically any parsing possible.

Get HTML inside iframe using jQuery

Try this code:

$('#iframe').contents().find("html").html();

This will return all the html in your iframe. Instead of .find("html") you can use any selector you want eg: .find('body'),.find('div#mydiv').

How to print the full NumPy array, without truncation?

Using a context manager as Paul Price sugggested

import numpy as np


class fullprint:
    'context manager for printing full numpy arrays'

    def __init__(self, **kwargs):
        kwargs.setdefault('threshold', np.inf)
        self.opt = kwargs

    def __enter__(self):
        self._opt = np.get_printoptions()
        np.set_printoptions(**self.opt)

    def __exit__(self, type, value, traceback):
        np.set_printoptions(**self._opt)


if __name__ == '__main__': 
    a = np.arange(1001)

    with fullprint():
        print(a)

    print(a)

    with fullprint(threshold=None, edgeitems=10):
        print(a)

Android Studio: Where is the Compiler Error Output Window?

For Android Studio 3.1, select the icon below the Build one in the Build window.

Android Studio 3.1 raw log toggle button

By Android Studio 3.3 (possibly in 3.2.1), the icon has changed, though the location is the same:

Android Studio 3.3 raw log toggle button

The build window should open when you run a build action (e.g. from the Build menu). If you don't see it, you can try the "Build" button along the bottom of the window (also visible in the above screenshots), or through the menus View ? Tool Windows ? Build.

How do I use boolean variables in Perl?

I came across a tutorial which have a well explaination about What values are true and false in Perl. It state that:

Following scalar values are considered false:

  • undef - the undefined value
  • 0 the number 0, even if you write it as 000 or 0.0
  • '' the empty string.
  • '0' the string that contains a single 0 digit.

All other scalar values, including the following are true:

  • 1 any non-0 number
  • ' ' the string with a space in it
  • '00' two or more 0 characters in a string
  • "0\n" a 0 followed by a newline
  • 'true'
  • 'false' yes, even the string 'false' evaluates to true.

There is another good tutorial which explain about Perl true and false.

Create table variable in MySQL

MYSQL 8 does, in a way:

MYSQL 8 supports JSON tables, so you could load your results into a JSON variable and select from that variable using the JSON_TABLE() command.

Overriding fields or properties in subclasses

I'd go with option 3, but have an abstract setMyInt method that subclasses are forced to implement. This way you won't have the problem of a derived class forgetting to set it in the constructor.

abstract class Base 
{
 protected int myInt;
 protected abstract void setMyInt();
}

class Derived : Base 
{
 override protected void setMyInt()
 {
   myInt = 3;
 }
}

By the way, with option one, if you don't specify set; in your abstract base class property, the derived class won't have to implement it.

abstract class Father
{
    abstract public int MyInt { get; }
}

class Son : Father
{
    public override int MyInt
    {
        get { return 1; }
    }
}

Loop timer in JavaScript

I believe you are looking for setInterval()

Difference between PACKETS and FRAMES

A packet is a general term for a formatted unit of data carried by a network. It is not necessarily connected to a specific OSI model layer.

For example, in the Ethernet protocol on the physical layer (layer 1), the unit of data is called an "Ethernet packet", which has an Ethernet frame (layer 2) as its payload. But the unit of data of the Network layer (layer 3) is also called a "packet".

A frame is also a unit of data transmission. In computer networking the term is only used in the context of the Data link layer (layer 2).

Another semantical difference between packet and frame is that a frame envelops your payload with a header and a trailer, just like a painting in a frame, while a packet usually only has a header.

But in the end they mean roughly the same thing and the distinction is used to avoid confusion and repetition when talking about the different layers.

'innerText' works in IE, but not in Firefox

As per Prakash K's answer Firefox does not support the innerText property. So you can simply test whether the user agent supports this property and proceed accordingly as below:

function changeText(elem, changeVal) {
    if (typeof elem.textContent !== "undefined") {
        elem.textContent = changeVal;
    } else {
        elem.innerText = changeVal;
    }
}

How to start working with GTest and CMake

Yours and VladLosevs' solutions are probably better than mine. If you want a brute-force solution, however, try this:

SET(CMAKE_EXE_LINKER_FLAGS /NODEFAULTLIB:\"msvcprtd.lib;MSVCRTD.lib\")

FOREACH(flag_var
    CMAKE_CXX_FLAGS CMAKE_CXX_FLAGS_DEBUG CMAKE_CXX_FLAGS_RELEASE
    CMAKE_CXX_FLAGS_MINSIZEREL CMAKE_CXX_FLAGS_RELWITHDEBINFO)
    if(${flag_var} MATCHES "/MD")
        string(REGEX REPLACE "/MD" "/MT" ${flag_var} "${${flag_var}}")
    endif(${flag_var} MATCHES "/MD")
ENDFOREACH(flag_var)

Installation failed with message Invalid File

Please follow the below steps File > Settings > Build,Execution,Deployment > Instant Run > Un-check (Enable Instant Run to hot swap code)

this is working for me

thanks

Hide a EditText & make it visible by clicking a menu

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.waist2height); {
        final EditText edit = (EditText)findViewById(R.id.editText);          
        final RadioButton rb1 = (RadioButton) findViewById(R.id.radioCM);
        final RadioButton rb2 = (RadioButton) findViewById(R.id.radioFT);                       
        if(rb1.isChecked()){    
            edit.setVisibility(View.VISIBLE);              
        }
        else if(rb2.isChecked()){               
            edit.setVisibility(View.INVISIBLE);
        }
}

Where and how is the _ViewStart.cshtml layout file linked?

From ScottGu's blog:

Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

Also see this.


In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

Wikipedia

There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

You need to let Gson know additional type of your response as below

import com.google.common.reflect.TypeToken;
import java.lang.reflect.Type;


Type collectionType = new TypeToken<List<UserSite>>(){}.getType();
List<UserSite> userSites  = gson.fromJson( response.getBody() , collectionType);

Cannot resolve symbol 'AppCompatActivity'

I'll tell you how did i solved this problem in eclipse. Download zip file from this link.https://github.com/dandar3/android-support-v7-appcompat then extract this file,open project, in lib folder you will see one jar file named "android-support-v7-appcompat" , add this jar file into your project. Thats it. enter image description here

Jenkins vs Travis-CI. Which one would you use for a Open Source project?

Travis-ci and Jenkins, while both are tools for continuous integration are very different.

Travis is a hosted service (free for open source) while you have to host, install and configure Jenkins.

Travis does not have jobs as in Jenkins. The commands to run to test the code are taken from a file named .travis.yml which sits along your project code. This makes it easy to have different test code per branch since each branch can have its own version of the .travis.yml file.

You can have a similar feature with Jenkins if you use one of the following plugins:

  • Travis YML Plugin - warning: does not seem to be popular, probably not feature complete in comparison to the real Travis.
  • Jervis - a modification of Jenkins to make it read create jobs from a .jervis.yml file found at the root of project code. If .jervis.yml does not exist, it will fall back to using .travis.yml file instead.

There are other hosted services you might also consider for continuous integration (non exhaustive list):


How to choose ?

You might want to stay with Jenkins because you are familiar with it or don't want to depend on 3rd party for your continuous integration system. Else I would drop Jenkins and go with one of the free hosted CI services as they save you a lot of trouble (host, install, configure, prepare jobs)

Depending on where your code repository is hosted I would make the following choices:

  • in-house ? Jenkins or gitlab-ci
  • Github.com ? Travis-CI

To setup Travis-CI on a github project, all you have to do is:

  • add a .travis.yml file at the root of your project
  • create an account at travis-ci.com and activate your project

The features you get are:

  • Travis will run your tests for every push made on your repo
  • Travis will run your tests on every pull request contributors will make

How do I revert to a previous package in Anaconda?

I know it was not available at the time, but now you could also use Anaconda navigator to install a specific version of packages in the environments tab.

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

When to use "new" and when not to, in C++?

Take a look at this question and this question for some good answers on C++ object instantiation.

This basic idea is that objects instantiated on the heap (using new) need to be cleaned up manually, those instantiated on the stack (without new) are automatically cleaned up when they go out of scope.

void SomeFunc()
{
    Point p1 = Point(0,0);
} // p1 is automatically freed

void SomeFunc2()
{
    Point *p1 = new Point(0,0);
    delete p1; // p1 is leaked unless it gets deleted
}

JavaScript to get rows count of a HTML table

You can use the .rows property and check it's .length, like this:

var rowCount = document.getElementById('myTableID').rows.length;

Adding click event handler to iframe

iframe doesn't have onclick event but we can implement this by using iframe's onload event and javascript like this...

function iframeclick() {
document.getElementById("theiframe").contentWindow.document.body.onclick = function() {
        document.getElementById("theiframe").contentWindow.location.reload();
    }
}


<iframe id="theiframe" src="youriframe.html" style="width: 100px; height: 100px;" onload="iframeclick()"></iframe>

I hope it will helpful to you....

Why does Java have transient fields?

Simply put, the transient java keyword protect fields from the been Serialize as their non-transient fields counter parts.

In this code snippet our abstract class BaseJob implement Serializable interface, we extends from BaseJob but we need not serialize the remote and local data sources; serialize only organizationName and isSynced fields.

public abstract class BaseJob implements Serializable{
   public void ShouldRetryRun(){}
}

public class SyncOrganizationJob extends BaseJob {

   public String organizationName;
   public Boolean isSynced

   @Inject transient RemoteDataSource remoteDataSource;
   @Inject transient LocalDaoSource localDataSource;

   public SyncOrganizationJob(String organizationName) {
     super(new 
         Params(BACKGROUND).groupBy(GROUP).requireNetwork().persist());

      this.organizationName = organizationName;
      this.isSynced=isSynced;

   }
}