Programs & Examples On #Printing web page

Print page numbers on pages when printing html

This javascript will add absolute positioned div's with pagenumbers on the right bottom corner and works in all browsers.

A4 height = 297mm = 1123px(96dpi)

<html>
    <head>
        <style type="text/css">
            @page {
              size: A4;
              margin: 0; 
            }

            body {
              margin: 0;
            }
        </style>
    </head>
    <body>
        <script type="text/javascript">
          window.onload = addPageNumbers;

          function addPageNumbers() {
            var totalPages = Math.ceil(document.body.scrollHeight / 1123);  //842px A4 pageheight for 72dpi, 1123px A4 pageheight for 96dpi, 
            for (var i = 1; i <= totalPages; i++) {
              var pageNumberDiv = document.createElement("div");
              var pageNumber = document.createTextNode("Page " + i + " of " + totalPages);
              pageNumberDiv.style.position = "absolute";
              pageNumberDiv.style.top = "calc((" + i + " * (297mm - 0.5px)) - 40px)"; //297mm A4 pageheight; 0,5px unknown needed necessary correction value; additional wanted 40px margin from bottom(own element height included)
              pageNumberDiv.style.height = "16px";
              pageNumberDiv.appendChild(pageNumber);
              document.body.insertBefore(pageNumberDiv, document.getElementById("content"));
              pageNumberDiv.style.left = "calc(100% - (" + pageNumberDiv.offsetWidth + "px + 20px))";
            }
          }
        </script>
        <div id="content">
            Lorem ipsum....
        </div>
    </body>
</html>

How to indent/format a selection of code in Visual Studio Code with Ctrl + Shift + F

On OS X, choose "Document Format", and select all lines that you need format.

Then Option + Shift + F.

Google Maps API - how to get latitude and longitude from Autocomplete without showing the map?

You can use the code below.

<script src="http://maps.googleapis.com/maps/api/js?libraries=places" type="text/javascript"></script>

<script type="text/javascript">
    function initialize() {
        var input = document.getElementById('searchTextField');
        var autocomplete = new google.maps.places.Autocomplete(input);
        google.maps.event.addListener(autocomplete, 'place_changed', function () {
            var place = autocomplete.getPlace();
            document.getElementById('city2').value = place.name;
            document.getElementById('cityLat').value = place.geometry.location.lat();
            document.getElementById('cityLng').value = place.geometry.location.lng();
            //alert("This function is working!");
            //alert(place.name);
           // alert(place.address_components[0].long_name);

        });
    }
    google.maps.event.addDomListener(window, 'load', initialize); 
</script>

and this part is inside your form:

<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on" runat="server" />  
<input type="hidden" id="city2" name="city2" />
<input type="hidden" id="cityLat" name="cityLat" />
<input type="hidden" id="cityLng" name="cityLng" />  

I hope it helps.

How find out which process is using a file in Linux?

@jim's answer is correct -- fuser is what you want.

Additionally (or alternately), you can use lsof to get more information including the username, in case you need permission (without having to run an additional command) to kill the process. (THough of course, if killing the process is what you want, fuser can do that with its -k option. You can have fuser use other signals with the -s option -- check the man page for details.)

For example, with a tail -F /etc/passwd running in one window:

ghoti@pc:~$ lsof | grep passwd
tail      12470    ghoti    3r      REG  251,0     2037 51515911 /etc/passwd

Note that you can also use lsof to find out what processes are using particular sockets. An excellent tool to have in your arsenal.

Getting list of parameter names inside python function

import inspect

def func(a,b,c=5):
    pass

inspect.getargspec(func)  # inspect.signature(func) in Python 3

(['a', 'b', 'c'], None, None, (5,))

What's the difference between HEAD, working tree and index, in Git?

The difference between HEAD (current branch or last committed state on current branch), index (aka. staging area) and working tree (the state of files in checkout) is described in "The Three States" section of the "1.3 Git Basics" chapter of Pro Git book by Scott Chacon (Creative Commons licensed).

Here is the image illustrating it from this chapter:

Local Operations - working directory vs. staging area (index) vs git repository (HEAD)

In the above image "working directory" is the same as "working tree", the "staging area" is an alternate name for git "index", and HEAD points to currently checked out branch, which tip points to last commit in the "git directory (repository)"

Note that git commit -a would stage changes and commit in one step.

Keep overflow div scrolled to bottom unless user scrolls up

$('#yourDivID').animate({ scrollTop: $(document).height() }, "slow");
return false;

This will calculate the ScrollTop Position from the height of #yourDivID using the $(document).height() property so that even if dynamic contents are added to the div the scroller will always be at the bottom position. Hope this helps. But it also has a small bug even if we scroll up and leaves the mouse pointer from the scroller it will automatically come to the bottom position. If somebody could correct that also it will be nice.

Inline instantiation of a constant List

const is for compile-time constants. You could just make it static readonly, but that would only apply to the METRICS variable itself (which should typically be Metrics instead, by .NET naming conventions). It wouldn't make the list immutable - so someone could call METRICS.Add("shouldn't be here");

You may want to use a ReadOnlyCollection<T> to wrap it. For example:

public static readonly IList<String> Metrics = new ReadOnlyCollection<string>
    (new List<String> { 
         SourceFile.LoC, SourceFile.McCabe, SourceFile.NoM,
         SourceFile.NoA, SourceFile.FanOut, SourceFile.FanIn, 
         SourceFile.Par, SourceFile.Ndc, SourceFile.Calls });

ReadOnlyCollection<T> just wraps a potentially-mutable collection, but as nothing else will have access to the List<T> afterwards, you can regard the overall collection as immutable.

(The capitalization here is mostly guesswork - using fuller names would make them clearer, IMO.)

Whether you declare it as IList<string>, IEnumerable<string>, ReadOnlyCollection<string> or something else is up to you... if you expect that it should only be treated as a sequence, then IEnumerable<string> would probably be most appropriate. If the order matters and you want people to be able to access it by index, IList<T> may be appropriate. If you want to make the immutability apparent, declaring it as ReadOnlyCollection<T> could be handy - but inflexible.

Linux command to translate DomainName to IP

Use this

$ dig +short stackoverflow.com

69.59.196.211

or this

$ host stackoverflow.com

stackoverflow.com has address 69.59.196.211
stackoverflow.com mail is handled by 30 alt2.aspmx.l.google.com.
stackoverflow.com mail is handled by 40 aspmx2.googlemail.com.
stackoverflow.com mail is handled by 50 aspmx3.googlemail.com.
stackoverflow.com mail is handled by 10 aspmx.l.google.com.
stackoverflow.com mail is handled by 20 alt1.aspmx.l.google.com.

SQL Server Express CREATE DATABASE permission denied in database 'master'

I know, it is an old question, but no solution worked for me. Here is what I did:

USE master 
GO 
GRANT CREATE TABLE TO PUBLIC

Repeat this with every permission you need, for example GRANT CREATE DATABASE TO PUBLIC, ... You must have the server role "public" (yes, I am captain obvious).

Note 1: GRANT ALL TO PUBLIC is deprecated, does not work anymore in 2017.

Note 2: I tried to build an msi installer using the wix toolset. This toolset calls a powershell file, wich creates the databases, ... Just to give you some background information :)

SQLite Reset Primary Key Field

You can reset by update sequence after deleted rows in your-table

UPDATE SQLITE_SEQUENCE SET SEQ=0 WHERE NAME='table_name';

How to pop an alert message box using PHP?

You could use Javascript:

// This is in the PHP file and sends a Javascript alert to the client
$message = "wrong answer";
echo "<script type='text/javascript'>alert('$message');</script>";

php random x digit number

I usually just use RAND() http://php.net/manual/en/function.rand.php

e.g.

rand ( 10000 , 99999 );

for your 5 digit random number

Print PDF directly from JavaScript

Download the Print.js from http://printjs.crabbly.com/

$http({
    url: "",
    method: "GET",
    headers: {
        "Content-type": "application/pdf"
    },
    responseType: "arraybuffer"
}).success(function (data, status, headers, config) {
    var pdfFile = new Blob([data], {
        type: "application/pdf"
    });
    var pdfUrl = URL.createObjectURL(pdfFile);
    //window.open(pdfUrl);
    printJS(pdfUrl);
    //var printwWindow = $window.open(pdfUrl);
    //printwWindow.print();
}).error(function (data, status, headers, config) {
    alert("Sorry, something went wrong")
});

Regular expressions in C: examples?

It's probably not what you want, but a tool like re2c can compile POSIX(-ish) regular expressions to ANSI C. It's written as a replacement for lex, but this approach allows you to sacrifice flexibility and legibility for the last bit of speed, if you really need it.

Convert varchar to float IF ISNUMERIC

You can't cast to float and keep the string in the same column. You can do like this to get null when isnumeric returns 0.

SELECT CASE ISNUMERIC(QTY) WHEN 1 THEN CAST(QTY AS float) ELSE null END

Correctly Parsing JSON in Swift 3

This is an other way to solve your problem. So please check out below solution. Hope it will help you.

let str = "{\"names\": [\"Bob\", \"Tim\", \"Tina\"]}"
let data = str.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
    let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
    if let names = json["names"] as? [String] {
        print(names)
    }
} catch let error as NSError {
    print("Failed to load: \(error.localizedDescription)")
}

How to delete Certain Characters in a excel 2010 cell

Replace [ with nothing, then ] with nothing.

TypeLoadException says 'no implementation', but it is implemented

The other time you can get this error is if you have an incorrect version of a signed assembly. It's not the normal symptom for this cause, but here was the scenario where I got it

  • an asp.net project contains assembly A and assembly B, B is strongly named

  • assembly A uses Activator.CreateInstance to load assembly C (i.e. there is no reference to C which is built separately)

  • C was built referencing an older version of assembly B than is currently present

hope that helps someone - it took me ages to figure this out.

How to AUTO_INCREMENT in db2?

You're looking for is called an IDENTITY column:

create table student (
   sid integer not null GENERATED ALWAYS AS IDENTITY (START WITH 1 INCREMENT BY 1)
  ,sname varchar(30)
  ,PRIMARY KEY (sid)
);

A sequence is another option for doing this, but you need to determine which one is proper for your particular situation. Read this for more information comparing sequences to identity columns.

Deleting a pointer in C++

int value, *ptr;

value = 8;
ptr = &value;
// ptr points to value, which lives on a stack frame.
// you are not responsible for managing its lifetime.

ptr = new int;
delete ptr;
// yes this is the normal way to manage the lifetime of
// dynamically allocated memory, you new'ed it, you delete it.

ptr = nullptr;
delete ptr;
// this is illogical, essentially you are saying delete nothing.

How to use pip with python 3.4 on windows?

I had the same problem when I install python3.5.3. And finally I find the pip.exe in this folder: ~/python/scripts/pip.exe. Hope that help.

How to change facet labels?

Just extending naught101's answer -- credit goes to him

plot_labeller <- function(variable,value, facetVar1='<name-of-1st-facetting-var>', var1NamesMapping=<pass-list-of-name-mappings-here>, facetVar2='', var2NamesMapping=list() )
{
  #print (variable)
  #print (value)
  if (variable==facetVar1) 
    {
      value <- as.character(value)
      return(var1NamesMapping[value])
    } 
  else if (variable==facetVar2) 
    {
      value <- as.character(value)
      return(var2NamesMapping[value])
    } 
  else 
    {
      return(as.character(value))
    }
}

What you have to do is create a list with name-to-name mapping

clusteringDistance_names <- list(
  '100'="100",
  '200'="200",
  '300'="300",
  '400'="400",
  '600'="500"
)

and redefine plot_labeller() with new default arguments:

plot_labeller <- function(variable,value, facetVar1='clusteringDistance', var1NamesMapping=clusteringDistance_names, facetVar2='', var1NamesMapping=list() )

And then:

ggplot() + 
  facet_grid(clusteringDistance ~ . , labeller=plot_labeller) 

Alternatively you can create a dedicated function for each of the label changes you want to have.

Test a weekly cron job

What about putting it into cron.hourly, waiting until the next run of hourly cron jobs, then removing it? That would run it once within an hour, and in the cron environment. You can also run ./your_script, but that won't have the same environment as under cron.

Aligning textviews on the left and right edges in Android layout

It can be done with LinearLayout (less overhead and more control than the Relative Layout option). Give the second view the remaining space so gravity can work. Tested back to API 16.

Proof

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Aligned left" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="end"
        android:text="Aligned right" />
</LinearLayout> 

If you want to limit the size of the first text view, do this:

Adjust weights as required. Relative layout won't allow you to set a percentage weight like this, only a fixed dp of one of the views

Proof 2

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:text="Aligned left but too long and would squash the other view" />

    <TextView
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:gravity="end"
        android:text="Aligned right" />
</LinearLayout>

pow (x,y) in Java

^ is the bitwise exclusive OR (XOR) operator in Java (and many other languages). It is not used for exponentiation. For that, you must use Math.pow.

Xcode iOS 8 Keyboard types not supported

I too had this problem after updating to the latest Xcode Beta. The settings on the simulator are refreshed, so the laptop (external) keyboard was being detected. If you simply press:

 iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard

then the software keyboard will be displayed once again.

How to require a controller in an angularjs directive

I got lucky and answered this in a comment to the question, but I'm posting a full answer for the sake of completeness and so we can mark this question as "Answered".


It depends on what you want to accomplish by sharing a controller; you can either share the same controller (though have different instances), or you can share the same controller instance.

Share a Controller

Two directives can use the same controller by passing the same method to two directives, like so:

app.controller( 'MyCtrl', function ( $scope ) {
  // do stuff...
});

app.directive( 'directiveOne', function () {
  return {
    controller: 'MyCtrl'
  };
});

app.directive( 'directiveTwo', function () {
  return {
    controller: 'MyCtrl'
  };
});

Each directive will get its own instance of the controller, but this allows you to share the logic between as many components as you want.

Require a Controller

If you want to share the same instance of a controller, then you use require.

require ensures the presence of another directive and then includes its controller as a parameter to the link function. So if you have two directives on one element, your directive can require the presence of the other directive and gain access to its controller methods. A common use case for this is to require ngModel.

^require, with the addition of the caret, checks elements above directive in addition to the current element to try to find the other directive. This allows you to create complex components where "sub-components" can communicate with the parent component through its controller to great effect. Examples could include tabs, where each pane can communicate with the overall tabs to handle switching; an accordion set could ensure only one is open at a time; etc.

In either event, you have to use the two directives together for this to work. require is a way of communicating between components.

Check out the Guide page of directives for more info: http://docs.angularjs.org/guide/directive

How do I open the "front camera" on the Android platform?

To open the back camera:-

val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA)

To open the front camera:-

val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
when {
     Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1 && Build.VERSION.SDK_INT < Build.VERSION_CODES.O -> {
         cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT)  // Tested on API 24 Android version 7.0(Samsung S6)
     }
     Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
         cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", CameraCharacteristics.LENS_FACING_FRONT) // Tested on API 27 Android version 8.0(Nexus 6P)
         cameraIntent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true)
     }
     else -> cameraIntent.putExtra("android.intent.extras.CAMERA_FACING", 1)  // Tested API 21 Android version 5.0.1(Samsung S4)
}
startActivityForResult(cameraIntent, REQUEST_CODE_CAMERA)

I could not make it work for API 28 and above. Also, opening the front camera directly is not possible in some devices(depends on the manufacturer).

How do I copy a range of formula values and paste them to a specific range in another sheet?

You can change

Range("B3:B65536").Copy Destination:=Sheets("DB").Range("B" & lastrow)

to

Range("B3:B65536").Copy 
Sheets("DB").Range("B" & lastrow).PasteSpecial xlPasteValues

BTW, if you have xls file (excel 2003), you would get an error if your lastrow would be greater 3.

Try to use this code instead:

Sub Get_Data()
    Dim lastrowDB As Long, lastrow As Long
    Dim arr1, arr2, i As Integer

    With Sheets("DB")
        lastrowDB = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
    End With

    arr1 = Array("B", "C", "D", "E", "F", "AH", "AI", "AJ", "J", "P", "AF")
    arr2 = Array("B", "A", "C", "P", "D", "E", "G", "F", "H", "I", "J")

    For i = LBound(arr1) To UBound(arr1)
        With Sheets("Sheet1")
             lastrow = Application.Max(3, .Cells(.Rows.Count, arr1(i)).End(xlUp).Row)
             .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
             Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues
        End With
    Next
    Application.CutCopyMode = False
End Sub

Note, above code determines last non empty row on DB sheet in column A (variable lastrowDB). If you need to find lastrow for each destination column in DB sheet, use next modification:

For i = LBound(arr1) To UBound(arr1)
   With Sheets("DB")
       lastrowDB = .Cells(.Rows.Count, arr2(i)).End(xlUp).Row + 1
   End With

   ' NEXT CODE

Next

You could also use next approach instead Copy/PasteSpecial. Replace

.Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Copy
Sheets("DB").Range(arr2(i) & lastrowDB).PasteSpecial xlPasteValues

with

Sheets("DB").Range(arr2(i) & lastrowDB).Resize(lastrow - 2).Value = _
      .Range(.Cells(3, arr1(i)), .Cells(lastrow, arr1(i))).Value

Get the last item in an array

How about something like below:

if ('index.html' === array[array.length - 1]) {  
   //do this 
} else { 
   //do that 
}

If using Underscore or Lodash, you can use _.last(), so something like:

if ('index.html' === _.last(array)) {  
   //do this 
} else { 
   //do that 
}

Or you can create your own last function:

const _last = arr => arr[arr.length - 1];

and use it like:

if ('index.html' === _last(array)) {  
   //do this 
} else { 
   //do that 
}

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

How to change row color in datagridview?

Something like the following... assuming the values in the cells are Integers.

foreach (DataGridViewRow dgvr in myDGV.Rows)
{
  if (dgvr.Cells[7].Value < dgvr.Cells[10].Value)
  {
    dgvr.DefaultCellStyle.ForeColor = Color.Red;
  }
}

untested, so apologies for any error.

If you know the particular row, you can skip the iteration:

if (myDGV.Rows[theRowIndex].Cells[7].Value < myDGV.Rows[theRowIndex].Cells[10].Value)
{
  dgvr.DefaultCellStyle.ForeColor = Color.Red;
}

Using node.js as a simple web server

from w3schools

it is pretty easy to create a node server to serve any file that is requested, and you dont need to install any packages for it

var http = require('http');
var url = require('url');
var fs = require('fs');

http.createServer(function (req, res) {
  var q = url.parse(req.url, true);
  var filename = "." + q.pathname;
  fs.readFile(filename, function(err, data) {
    if (err) {
      res.writeHead(404, {'Content-Type': 'text/html'});
      return res.end("404 Not Found");
    }  
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

http://localhost:8080/file.html

will serve file.html from disk

Node Multer unexpected field

In my case, I had 2 forms in differents views and differents router files. The first router used the name field with view one and its file name was "inputGroupFile02". The second view had another name for file input. For some reason Multer not allows you set differents name in different views, so I dicided to use same name for the file input in both views.

enter image description here

How to force IE to reload javascript?

This should do the trick for ASP.NET. The concept is the same as shown in the PHP example. Since the URL is different everytime the script is loaded, neither browser of proxy should cache the file. I'm used to put my JavaScript code into separate files, and wasted a significant amount of time with Visual Studio until I realized that it wouldn't reload the JavaScript files.

<script src="Scripts/main.js?version=<% =DateTime.Now.Ticks.ToString()%>" type="text/javascript"></script>

Full example:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">

   <script src="Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>  
   <script src="Scripts/main.js?version=<% =DateTime.Now.Ticks.ToString()%>" type="text/javascript"></script>
    <script type="text/javascript">

        $(document).ready(function () {
                                myInit();
                          });

    </script>
</asp:Content>

Obvously, this solution should only be used during the development stage, and should be removed before posting the site.

django order_by query set, ascending and descending

Reserved.objects.filter(client=client_id).order_by('-check_in')

A hyphen "-" in front of "check_in" indicates descending order. Ascending order is implied.

We don't have to add an all() before filter(). That would still work, but you only need to add all() when you want all objects from the root QuerySet.

More on this here: https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters

Are parameters in strings.xml possible?

There is many ways to use it and i recomend you to see this documentation about String Format.

http://developer.android.com/intl/pt-br/reference/java/util/Formatter.html

But, if you need only one variable, you'll need to use %[type] where [type] could be any Flag (see Flag types inside site above). (i.e. "My name is %s" or to set my name UPPERCASE, use this "My name is %S")

<string name="welcome_messages">Hello, %1$S! You have %2$d new message(s) and your quote is %3$.2f%%.</string>

Hello, ANDROID! You have 1 new message(s) and your quote is 80,50%.

How to give credentials in a batch script that copies files to a network location?

You can also map the share to a local drive as follows:

net use X: "\\servername\share" /user:morgan password

Check if a row exists using old mysql_* API

Easiest way to check if a row exists:

$lectureName = mysql_real_escape_string($lectureName);  // SECURITY!
$result = mysql_query("SELECT 1 FROM preditors_assigned WHERE lecture_name='$lectureName' LIMIT 1");
if (mysql_fetch_row($result)) {
    return 'Assigned';
} else {
    return 'Available';
}

No need to mess with arrays and field names.

Excel VBA - select multiple columns not in sequential order

Range("A:B,D:E,G:H").Select can help

Edit note: I just saw you have used different column sequence, I have updated my answer

How to debug stored procedures with print statements?

Before I get to my reiterated answer; I am confessing that the only answer I would accept here is this one by KM. above. I down voted the other answers because none of them actually answered the question asked or they were not adequate. PRINT output does indeed show up in the Message window, but that is not what was asked at all.

Why doesn't the PRINT statement output show during my Stored Procedure execution?
The short version of this answer is that you are sending your sproc's execution over to the SQL server and it isn't going to respond until it is finished with the whole transaction. Here is a better answer located at this external link.

  • For even more opinions/observations focus your attention on this SO post here.
  • Specifically look at this answer of the same post by Phil_factor (Ha ha! Love the SQL humor)
  • Regarding the suggestion of using RAISERROR WITH NOWAIT look at this answer of the same post by JimCarden

Don't do these things

  1. Some people are under the impression that they can just use a GO statement after their PRINT statement, but you CANNOT use the GO statement INSIDE of a sproc. So that solution is out.
  2. I don't recommend SELECT-ing your print statements because it is just going to muddy your result set with nonsense and if your sproc is supposed to be consumed by a program later, then you will have to know which result sets to skip when looping through the results from your data reader. This is just a bad idea, so don't do it.
  3. Another problem with SELECT-ING your print statements is that they don't always show up immediately. I have had different experiences with this for different executions, so don't expect any kind of consistency with this methodology.

Alternative to PRINT inside of a Stored Procedure
Really this is kind of an icky work around in my opinion because the syntax is confusing in the context that it is being used in, but who knows maybe it will be updated in the future by Microsoft. I just don't like the idea of raising an error for the sole purpose of printing out debug info...

It seems like the only way around this issue is to use, as has been explained numerous times already RAISERROR WITH NOWAIT. I am providing an example and pointing out a small problem with this approach:

ALTER
--CREATE 
    PROCEDURE [dbo].[PrintVsRaiseErrorSprocExample]
AS
BEGIN
    SET NOCOUNT ON;

    -- This will print immediately
    RAISERROR ('RE Start', 0, 1) WITH NOWAIT
    SELECT 1;

    -- Five second delay to simulate lengthy execution
    WAITFOR DELAY '00:00:05'

    -- This will print after the five second delay
    RAISERROR ('RE End', 0, 1) WITH NOWAIT
    SELECT 2;
END

GO

EXEC [dbo].[PrintVsRaiseErrorSprocExample]

Both SELECT statement results will only show after the execution is finished and the print statements will show in the order shown above.

Potential problem with this approach
Let's say you have both your PRINT statement and RAISERROR statement one after the other, then they both print. I'm sure this has something to do with buffering, but just be aware that this can happen.

ALTER
--CREATE 
    PROCEDURE [dbo].[PrintVsRaiseErrorSprocExample2]
AS
BEGIN
    SET NOCOUNT ON;

    -- Both the PRINT and RAISERROR statements will show
    PRINT 'P Start';
    RAISERROR ('RE Start', 0, 1) WITH NOWAIT
    SELECT 1;

    WAITFOR DELAY '00:00:05'

    -- Both the PRINT and RAISERROR statements will show
    PRINT 'P End'
    RAISERROR ('RE End', 0, 1) WITH NOWAIT
    SELECT 2;
END

GO

EXEC [dbo].[PrintVsRaiseErrorSprocExample2]

Therefore the work around here is, don't use both PRINT and RAISERROR, just choose one over the other. If you want your output to show during the execution of a sproc then use RAISERROR WITH NOWAIT.

Find something in column A then show the value of B for that row in Excel 2010

Guys Its very interesting to know that many of us face the problem of replication of lookup value while using the Vlookup/Index with Match or Hlookup.... If we have duplicate value in a cell we all know, Vlookup will pick up against the first item would be matching in loopkup array....So here is solution for you all...

e.g.

in Column A we have field called company....

Column A                             Column B            Column C

Company_Name                         Value        
Monster                              25000                              
Naukri                               30000  
WNS                                  80000  
American Express                     40000  
Bank of America                      50000  
Alcatel Lucent                       35000  
Google                               75000  
Microsoft                            60000  
Monster                              35000  
Bank of America                      15000 

Now if you lookup the above dataset, you would see the duplicity is in Company Name at Row No# 10 & 11. So if you put the vlookup, the data will be picking up which comes first..But if you use the below formula, you can make your lookup value Unique and can pick any data easily without having any dispute or facing any problem

Put the formula in C2.........A2&"_"&COUNTIF(A2:$A$2,A2)..........Result will be Monster_1 for first line item and for row no 10 & 11.....Monster_2, Bank of America_2 respectively....Here you go now you have the unique value so now you can pick any data easily now..

Cheers!!! Anil Dhawan

Declaring variables in Excel Cells

You can name cells. This is done by clicking the Name Box (that thing next to the formula bar which says "A1" for example) and typing a name, such as, "myvar". Now you can use that name instead of the cell reference:

= myvar*25

window.open(url, '_blank'); not working on iMac/Safari

Taken from the accepted answers comment by Steve on Dec 20, 2013:

Actually, there's a very easy way to do it: just click off "Block popup windows" in the iMac/Safari browser and it does what I want.

To clarify, when running Safari on Mac OS X El Capitan:

  1. Safari -> Preferences
  2. Security -> Uncheck 'Block pop-up windows'

How to exclude particular class name in CSS selector?

In modern browsers you can do:

.reMode_hover:not(.reMode_selected):hover{}

Consult http://caniuse.com/css-sel3 for compatibility information.

DNS caching in linux

On Linux (and probably most Unix), there is no OS-level DNS caching unless nscd is installed and running. Even then, the DNS caching feature of nscd is disabled by default at least in Debian because it's broken. The practical upshot is that your linux system very very probably does not do any OS-level DNS caching.

You could implement your own cache in your application (like they did for Squid, according to diegows's comment), but I would recommend against it. It's a lot of work, it's easy to get it wrong (nscd got it wrong!!!), it likely won't be as easily tunable as a dedicated DNS cache, and it duplicates functionality that already exists outside your application.

If an end user using your software needs to have DNS caching because the DNS query load is large enough to be a problem or the RTT to the external DNS server is long enough to be a problem, they can install a caching DNS server such as Unbound on the same machine as your application, configured to cache responses and forward misses to the regular DNS resolvers.

How to convert TimeStamp to Date in Java?

DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date fecha = getDateInTimestamp(); 

How to extract elements from a list using indices in Python?

Use Numpy direct array indexing, as in MATLAB, Julia, ...

a = [10, 11, 12, 13, 14, 15];
s = [1, 2, 5] ;

import numpy as np
list(np.array(a)[s])
# [11, 12, 15]

Better yet, just stay with Numpy arrays

a = np.array([10, 11, 12, 13, 14, 15])
a[s]
#array([11, 12, 15])

What is the difference between SQL Server 2012 Express versions?

This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.

Summary compiled from the above document:

    * = contains the feature
                                           SQLEXPR    SQLEXPRWT   SQLEXPRADV
 ----------------------------------------------------------------------------
    > SQL Server Core                         *           *           *
    > SQL Server Management Studio            -           *           *
    > Distributed Replay – Admin Tool         -           *           *
    > LocalDB                                 -           *           *
    > SQL Server Data Tools (SSDT)            -           -           *
    > Full-text and semantic search           -           -           *
    > Specification of language in query      -           -           *
    > some of Reporting services features     -           -           *

What is %timeit in python?

I just wanted to add a very subtle point about %%timeit. Given it runs the "magics" on the cell, you'll get error...

UsageError: Line magic function %%timeit not found

...if there is any code/comment lines above %%timeit. In other words, ensure that %%timeit is the first command in your cell.

I know it's a small point all the experts will say duh to, but just wanted to add my half a cent for the young wizards starting out with magic tricks.

Error: "Input is not proper UTF-8, indicate encoding !" using PHP's simplexml_load_string

When generating mapping files using doctrine I ran into same issue. I fixed it by removing all comments that some fields had in the database.

How to pass a value from one jsp to another jsp page?

Use sessions

On your search.jsp

Put your scard in sessions using session.setAttribute("scard","scard")

//the 1st variable is the string name that you will retrieve in ur next page,and the 2nd variable is the its value,i.e the scard value.

And in your next page you retrieve it using session.getAttribute("scard")

UPDATE

<input type="text" value="<%=session.getAttribute("scard")%>"/>

How do I get bootstrap-datepicker to work with Bootstrap 3?

For anyone else who runs into this...

Version 1.2.0 of this plugin (current as of this post) doesn't quite work in all cases as documented with Bootstrap 3.0, but it does with a minor workaround.

Specifically, if using an input with icon, the HTML markup is of course slightly different as class names have changed:

<div class="input-group" data-datepicker="true">
    <input name="date" type="text" class="form-control" />
    <span class="input-group-addon"><i class="icon-calendar"></i></span>
</div>

It seems because of this, you need to use a selector that points directly to the input element itself NOT the parent container (which is what the auto generated HTML on the demo page suggests).

$('*[data-datepicker="true"] input[type="text"]').datepicker({
    todayBtn: true,
    orientation: "top left",
    autoclose: true,
    todayHighlight: true
});

Having done this you will probably also want to add a listener for clicking/tapping on the icon so it sets focus on the text input when clicked (which is the behaviour when using this plugin with TB 2.x by default).

$(document).on('touch click', '*[data-datepicker="true"] .input-group-addon', function(e){
    $('input[type="text"]', $(this).parent()).focus();
});

NB: I just use a data-datepicker boolean attribute because the class name 'datepicker' is reserved by the plugin and I already use 'date' for styling elements.

How to check how many letters are in a string in java?

A)

String str = "a string";
int length = str.length( ); // length == 8

http://download.oracle.com/javase/7/docs/api/java/lang/String.html#length%28%29

edit

If you want to count the number of a specific type of characters in a String, then a simple method is to iterate through the String checking each index against your test case.

int charCount = 0;
char temp;

for( int i = 0; i < str.length( ); i++ )
{
    temp = str.charAt( i );

    if( temp.TestCase )
        charCount++;
}

where TestCase can be isLetter( ), isDigit( ), etc.

Or if you just want to count everything but spaces, then do a check in the if like temp != ' '

B)

String str = "a string";
char atPos0 = str.charAt( 0 ); // atPos0 == 'a'

http://download.oracle.com/javase/7/docs/api/java/lang/String.html#charAt%28int%29

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

No it doesn't wait and the way you are doing it in that sample is not good practice.

dispatch_async is always asynchronous. It's just that you are enqueueing all the UI blocks to the same queue so the different blocks will run in sequence but parallel with your data processing code.

If you want the update to wait you can use dispatch_sync instead.

// This will wait to finish
dispatch_sync(dispatch_get_main_queue(), ^{
    // Update the UI on the main thread.
});

Another approach would be to nest enqueueing the block. I wouldn't recommend it for multiple levels though.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Background work

    dispatch_async(dispatch_get_main_queue(), ^{
        // Update UI

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // Background work

            dispatch_async(dispatch_get_main_queue(), ^{
                // Update UI
            });
        });
    });
});

If you need the UI updated to wait then you should use the synchronous versions. It's quite okay to have a background thread wait for the main thread. UI updates should be very quick.

Hide Button After Click (With Existing Form on Page)

Change the button to :

<button onclick="getElementById('hidden-div').style.display = 'block'; this.style.display = 'none'">Check Availability</button>

FIDDLE

Or even better, use a proper event handler by identifying the button :

<button id="show_button">Check Availability</button>

and a script

<script type="text/javascript">
    var button = document.getElementById('show_button')
    button.addEventListener('click',hideshow,false);

    function hideshow() {
        document.getElementById('hidden-div').style.display = 'block'; 
        this.style.display = 'none'
    }   
</script>

FIDDLE

The provided URI scheme 'https' is invalid; expected 'http'. Parameter name: via

Adding this as an answer, just since you can't do much fancy formatting in comments.
I had the same issue, except I was creating and binding my web service client entirely in code.
Reason is the DLL was being uploaded into a system, which prohibited the use of config files.

Here is the code as it needed to be updated to communicate over SSL...

Public Function GetWebserviceClient() As WebWorker.workerSoapClient
    Dim binding = New BasicHttpBinding()
    binding.Name = "WebWorkerSoap"
    binding.CloseTimeout = TimeSpan.FromMinutes(1)
    binding.OpenTimeout = TimeSpan.FromMinutes(1)
    binding.ReceiveTimeout = TimeSpan.FromMinutes(10)
    binding.SendTimeout = TimeSpan.FromMinutes(1)

    '// HERE'S THE IMPORTANT BIT FOR SSL
    binding.Security.Mode = BasicHttpSecurityMode.Transport

    Dim endpoint = New EndpointAddress("https://myurl/worker.asmx")

    Return New WebWorker.workerSoapClient(binding, endpoint)
End Function

How do I concatenate two arrays in C#?

int[] x = new int [] { 1, 2, 3}; int[] y = new int [] { 4, 5 };

int[] z = x.Union(y).ToArray();

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

I found that following these instructions helped with finding what the problem was. For me, that was the killer, not knowing what was broken.

http://mythinkpond.wordpress.com/2011/07/01/tomcat-6-infamous-severe-error-listenerstart-message-how-to-debug-this-error/

Quoting from the link

In Tomcat 6 or above, the default logger is the”java.util.logging” logger and not Log4J. So if you are trying to add a “log4j.properties” file – this will NOT work. The Java utils logger looks for a file called “logging.properties” as stated here: http://tomcat.apache.org/tomcat-6.0-doc/logging.html

So to get to the debugging details create a “logging.properties” file under your”/WEB-INF/classes” folder of your WAR and you’re all set.

And now when you restart your Tomcat, you will see all of your debugging in it’s full glory!!!

Sample logging.properties file:

org.apache.catalina.core.ContainerBase.[Catalina].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].handlers = java.util.logging.ConsoleHandler

JQuery style display value

This will return what you asked, but I wouldnt recommend using css like this. Use external CSS instead of inline css.

$("tr[id='pDetails']").attr("style").split(':')[1];

Renaming column names of a DataFrame in Spark Scala

tow table join not rename the joined key

// method 1: create a new DF
day1 = day1.toDF(day1.columns.map(x => if (x.equals(key)) x else s"${x}_d1"): _*)

// method 2: use withColumnRenamed
for ((x, y) <- day1.columns.filter(!_.equals(key)).map(x => (x, s"${x}_d1"))) {
    day1 = day1.withColumnRenamed(x, y)
}

works!

how to get current location in google map android

//check this condition if (Build.VERSION.SDK_INT < 23 ) 

In some android studio it does not work while Whole code is working, so replace this line by this:

if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) 

& my project is working fine.

Command not found after npm install in zsh

add source /home/YOUUSERNAME/.bash_profile at the beginning of ~/.zshrc

And all missing commands will be detected.

For Mac users : add source /Users/YOUUSERNAME/.bash_profile

How to send a JSON object using html form data

I found a way to pass a JSON message using only a HTML form.

This example is for GraphQL but it will work for any endpoint that is expecting a JSON message.

GrapqhQL by default expects a parameter called operations where you can add your query or mutation in JSON format. In this specific case I am invoking this query which is requesting to get allUsers and return the userId of each user.

{ 
 allUsers 
  { 
  userId 
  }
}

I am using a text input to demonstrate how to use it, but you can change it for a hidden input to hide the query from the user.

<html>
<body>
    <form method="post" action="http://localhost:8080/graphql">
        <input type="text" name="operations" value="{&quot;query&quot;: &quot;{ allUsers { userId } }&quot;, "variables":  {}}"/>
        <input type="submit" />
    </form>
</body>
</html>

In order to make this dynamic you will need JS to transport the values of the text fields to the query string before submitting your form. Anyway I found this approach very interesting. Hope it helps.

How to write a Unit Test?

I provide this post for both IntelliJ and Eclipse.

Eclipse:

For making unit test for your project, please follow these steps (I am using Eclipse in order to write this test):

1- Click on New -> Java Project.

Create Project

2- Write down your project name and click on finish.

Create Project

3- Right click on your project. Then, click on New -> Class.

Create Class

4- Write down your class name and click on finish.

Create Class

Then, complete the class like this:

public class Math {
    int a, b;
    Math(int a, int b) {
        this.a = a;
        this.b = b;
    }
    public int add() {
        return a + b;
    }
}

5- Click on File -> New -> JUnit Test Case.

Create JUnite Test

6- Check setUp() and click on finish. SetUp() will be the place that you initialize your test.

Check SetUp()

7- Click on OK.

Add JUnit

8- Here, I simply add 7 and 10. So, I expect the answer to be 17. Complete your test class like this:

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class MathTest {
    Math math;
    @Before
    public void setUp() throws Exception {
        math = new Math(7, 10);
    }
    @Test
    public void testAdd() {
        Assert.assertEquals(17, math.add());
    }
}

9- Write click on your test class in package explorer and click on Run as -> JUnit Test.

Run JUnit Test

10- This is the result of the test.

Result of The Test

IntelliJ: Note that I used IntelliJ IDEA community 2020.1 for the screenshots. Also, you need to set up your jre before these steps. I am using JDK 11.0.4.

1- Right-click on the main folder of your project-> new -> directory. You should call this 'test'. enter image description here 2- Right-click on the test folder and create the proper package. I suggest creating the same packaging names as the original class. Then, you right-click on the test directory -> mark directory as -> test sources root. enter image description here 3- In the right package in the test directory, you need to create a Java class (I suggest to use Test.java). enter image description here 4- In the created class, type '@Test'. Then, among the options that IntelliJ gives you, select Add 'JUnitx' to classpath. enter image description here enter image description here 5- Write your test method in your test class. The method signature is like:

@Test
public void test<name of original method>(){
...
}

You can do your assertions like below:

Assertions.assertTrue(f.flipEquiv(node1_1, node2_1));

These are the imports that I added:

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

enter image description here

This is the test that I wrote: enter image description here

You can check your methods like below:

Assertions.assertEquals(<Expected>,<actual>);
Assertions.assertTrue(<actual>);
...

For running your unit tests, right-click on the test and click on Run . enter image description here

If your test passes, the result will be like below: enter image description here

I hope it helps. You can see the structure of the project in GitHub https://github.com/m-vahidalizadeh/problem_solving_project.

In Bash, how can I check if a string begins with some value?

I tweaked @markrushakoff's answer to make it a callable function:

function yesNo {
  # Prompts user with $1, returns true if response starts with y or Y or is empty string
  read -e -p "
$1 [Y/n] " YN

  [[ "$YN" == y* || "$YN" == Y* || "$YN" == "" ]]
}

Use it like this:

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n] y
true

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n] Y
true

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n] yes
true

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n]
true

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n] n
false

$ if yesNo "asfd"; then echo "true"; else echo "false"; fi

asfd [Y/n] ddddd
false

Here is a more complex version that provides for a specified default value:

function toLowerCase {
  echo "$1" | tr '[:upper:]' '[:lower:]'
}

function yesNo {
  # $1: user prompt
  # $2: default value (assumed to be Y if not specified)
  # Prompts user with $1, using default value of $2, returns true if response starts with y or Y or is empty string

  local DEFAULT=yes
  if [ "$2" ]; then local DEFAULT="$( toLowerCase "$2" )"; fi
  if [[ "$DEFAULT" == y* ]]; then
    local PROMPT="[Y/n]"
  else
    local PROMPT="[y/N]"
  fi
  read -e -p "
$1 $PROMPT " YN

  YN="$( toLowerCase "$YN" )"
  { [ "$YN" == "" ] && [[ "$PROMPT" = *Y* ]]; } || [[ "$YN" = y* ]]
}

Use it like this:

$ if yesNo "asfd" n; then echo "true"; else echo "false"; fi

asfd [y/N]
false

$ if yesNo "asfd" n; then echo "true"; else echo "false"; fi

asfd [y/N] y
true

$ if yesNo "asfd" y; then echo "true"; else echo "false"; fi

asfd [Y/n] n
false

How do I iterate over an NSArray?

For OS X 10.4.x and previous:

 int i;
 for (i = 0; i < [myArray count]; i++) {
   id myArrayElement = [myArray objectAtIndex:i];
   ...do something useful with myArrayElement
 }

For OS X 10.5.x (or iPhone) and beyond:

for (id myArrayElement in myArray) {
   ...do something useful with myArrayElement
}

Drawing circles with System.Drawing

With this code you can easily draw a circle... C# is great and easy my friend

public partial class Form1 : Form
{


public Form1()
    {
        InitializeComponent();
    }

  private void button1_Click(object sender, EventArgs e)
    {
        Graphics myGraphics = base.CreateGraphics();
        Pen myPen = new Pen(Color.Red);
        SolidBrush mySolidBrush = new SolidBrush(Color.Red);
        myGraphics.DrawEllipse(myPen, 50, 50, 150, 150);
    }
 }

Remove part of string after "."

We can pretend they are filenames and remove extensions:

tools::file_path_sans_ext(a)
# [1] "NM_020506"    "NM_020519"    "NM_001030297" "NM_010281"    "NM_011419"    "NM_053155"

PHP Multiple Checkbox Array

Try this, by for Loop

<form method="post">
<?php
for ($i=1; $i <5 ; $i++) 
{ 
    echo'<input type="checkbox" value="'.$i.'" name="checkbox[]"/>';
} 
?>
<input type="submit" name="submit" class="form-control" value="Submit">  
</form>

<?php 
if(isset($_POST['submit']))
{
    $check=implode(", ", $_POST['checkbox']);
    print_r($check);
}     
?>

Correct way of getting Client's IP Addresses from http.Request

In PHP there are a lot of variables that I should check. Is it the same on Go?

This has nothing to do with Go (or PHP for that matter). It just depends on what the client, proxy, load-balancer, or server is sending. Get the one you need depending on your environment.

http.Request.RemoteAddr contains the remote IP address. It may or may not be your actual client.

And is the request case sensitive? for example x-forwarded-for is the same as X-Forwarded-For and X-FORWARDED-FOR? (from req.Header.Get("X-FORWARDED-FOR"))

No, why not try it yourself? http://play.golang.org/p/YMf_UBvDsH

How to stop creating .DS_Store on Mac?

this file starts to appear when you choose the system shows you the hidden files: $defaults write com.apple.finder AppleShowAllFiles TRUE If you run this command disapear $defaults write com.apple.finder AppleShowAllFiles FALSE Use terminal

Finding all the subsets of a set

a simple bitmasking can do the trick as discussed earlier .... by rgamber

#include<iostream>
#include<cstdio>

#define pf printf
#define sf scanf

using namespace std;

void solve(){

            int t; char arr[99];
            cin >> t;
            int n = t;
            while( t-- )
            {
                for(int l=0; l<n; l++) cin >> arr[l];
                for(int i=0; i<(1<<n); i++)
                {
                    for(int j=0; j<n; j++)
                        if(i & (1 << j))
                        pf("%c", arr[j]);
                    pf("\n");
                }
            }
        }

int main() {
      solve();
      return 0;
}

Converting DateTime format using razor

I was not able to get this working entirely based on the suggestions above. Including the DataTypeAttribute [DataType(DataType.Date)] seemed to solve my issue, see:

Model

[Required]
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
public DateTime RptDate { get; set; }

View

@Html.EditorFor(m => m.CLPosts.RptDate)

HTH

Python: List vs Dict for look up table

set() is exactly what you want. O(1) lookups, and smaller than a dict.

How can I use the $index inside a ng-repeat to enable a class and show a DIV?

The issue here is that ng-repeat creates its own scope, so when you do selected=$index it creates a new a selected property in that scope rather than altering the existing one. To fix this you have two options:

Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:

$scope.selected = {value: 0};

<a ng-click="selected.value = $index">A{{$index}}</a>

See plunker

or

Use the $parent variable to access the correct property. Though less recommended as it increases coupling between scopes

<a ng-click="$parent.selected = $index">A{{$index}}</a>

See plunker

Correct way to read a text file into a buffer in C?

Why don't you just use the array of chars you have? This ought to do it:

   source[i] = getc(fp); 
   i++;

How to make fixed header table inside scrollable div?

This is my "crutches" solution by using html and css. There used 2 tables and fixed width of tables and table cell`s

https://jsfiddle.net/babaikawow/s2xyct24/1/

HTML:

  <div class="container">
<table class="table" border = 1; >  <!-- fixed width header -->
                            <thead >
                                <tr>
                                    <th class="tbDataId" >?</th>
                                    <th class="tbDataName">?????????</th>
                                    <th class="tbDataData">????</th>
                                    <th class="tbDataData">?????? ??</th>
                                    <th class="tbDataDiseases">????????1</th>
                                    <th class="tbDataDiseases">????????2</th>
                                    <th class="tbDataDiseases">????????3</th>
                                    <th class="tbDataDiseases">????????4</th>
                                    <th class="tbDataDiseases">????????5</th>  
                                </tr>
                            </thead>  
                        </table> 

                        <div class="scrollTable"> <!-- scrolling block -->
                            <table class="table" border = 1;>
                                 <tbody>
                   <tr>
                      <td class="tbDataId" >?</td>
                                    <td class="tbDataName">?????????</td>
                                    <td class="tbDataData">????</td>
                                    <td class="tbDataData">?????? ??</td>
                                    <td class="tbDataDiseases">????????1</td>
                                    <td class="tbDataDiseases">????????2</td>
                                    <td class="tbDataDiseases">????????3</td>
                                    <td class="tbDataDiseases">????????4</td>
                                    <td class="tbDataDiseases">????????5</td> 
                   </tr>
                    <tr>
                      <td class="tbDataId" >?</td>
                                    <td class="tbDataName">?????????</td>
                                    <td class="tbDataData">????</td>
                                    <td class="tbDataData">?????? ??</td>
                                    <td class="tbDataDiseases">????????1</td>
                                    <td class="tbDataDiseases">????????2</td>
                                    <td class="tbDataDiseases">????????3</td>
                                    <td class="tbDataDiseases">????????4</td>
                                    <td class="tbDataDiseases">????????5</td> 
                   </tr>
                    <tr>
                      <td class="tbDataId" >?</td>
                                    <td class="tbDataName">?????????</td>
                                    <td class="tbDataData">????</td>
                                    <td class="tbDataData">?????? ??</td>
                                    <td class="tbDataDiseases">????????1</td>
                                    <td class="tbDataDiseases">????????2</td>
                                    <td class="tbDataDiseases">????????3</td>
                                    <td class="tbDataDiseases">????????4</td>
                                    <td class="tbDataDiseases">????????5</td> 
                   </tr>
                    <tr>
                      <td class="tbDataId" >?</td>
                                    <td class="tbDataName">?????????</td>
                                    <td class="tbDataData">????</td>
                                    <td class="tbDataData">?????? ??</td>
                                    <td class="tbDataDiseases">????????1</td>
                                    <td class="tbDataDiseases">????????2</td>
                                    <td class="tbDataDiseases">????????3</td>
                                    <td class="tbDataDiseases">????????4</td>
                                    <td class="tbDataDiseases">????????5</td> 
                   </tr>
                    <tr>
                      <td class="tbDataId" >?</td>
                                    <td class="tbDataName">?????????</td>
                                    <td class="tbDataData">????</td>
                                    <td class="tbDataData">?????? ??</td>
                                    <td class="tbDataDiseases">????????1</td>
                                    <td class="tbDataDiseases">????????2</td>
                                    <td class="tbDataDiseases">????????3</td>
                                    <td class="tbDataDiseases">????????4</td>
                                    <td class="tbDataDiseases">????????5</td> 
                   </tr>
                                </tbody>
                            </table>
                        </div> 
</div>

CSS:

*{
  box-sizing: border-box;
}

.container{
 width:1000px;
}
.scrollTable{

    overflow: scroll;
  overflow-x: hidden;
    height: 100px;
} 
table{
margin: 0px!important;
width:983px!important;
border-collapse: collapse; 

}

/*   Styles of the th and td  */

/* Id */
.tbDataId{
    width:5%;
}

/* ????,
?????? ?? */
.tbDataData{
    /*width:170px;*/
    width: 15%;
}

/* ? ? ? */
.tbDataName{
    width: 15%;
}

/*???????? */
.tbDataDiseases{
    width:10%;
}

Angular 2 router.navigate

_x000D_
_x000D_
import { ActivatedRoute } from '@angular/router';_x000D_
_x000D_
export class ClassName {_x000D_
  _x000D_
  private router = ActivatedRoute;_x000D_
_x000D_
    constructor(r: ActivatedRoute) {_x000D_
        this.router =r;_x000D_
    }_x000D_
_x000D_
onSuccess() {_x000D_
     this.router.navigate(['/user_invitation'],_x000D_
         {queryParams: {email: loginEmail, code: userCode}});_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
Get this values:_x000D_
---------------_x000D_
_x000D_
ngOnInit() {_x000D_
    this.route_x000D_
        .queryParams_x000D_
        .subscribe(params => {_x000D_
            let code = params['code'];_x000D_
            let userEmail = params['email'];_x000D_
        });_x000D_
}
_x000D_
_x000D_
_x000D_

Ref: https://angular.io/docs/ts/latest/api/router/index/NavigationExtras-interface.html

Sending a notification from a service in Android

This type of Notification is deprecated as seen from documents:

@java.lang.Deprecated
public Notification(int icon, java.lang.CharSequence tickerText, long when) { /* compiled code */ }

public Notification(android.os.Parcel parcel) { /* compiled code */ }

@java.lang.Deprecated
public void setLatestEventInfo(android.content.Context context, java.lang.CharSequence contentTitle, java.lang.CharSequence contentText, android.app.PendingIntent contentIntent) { /* compiled code */ }

Better way
You can send a notification like this:

// prepare intent which is triggered if the
// notification is selected

Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);

// build notification
// the addAction re-use the same intent to keep the example short
Notification n  = new Notification.Builder(this)
        .setContentTitle("New mail from " + "[email protected]")
        .setContentText("Subject")
        .setSmallIcon(R.drawable.icon)
        .setContentIntent(pIntent)
        .setAutoCancel(true)
        .addAction(R.drawable.icon, "Call", pIntent)
        .addAction(R.drawable.icon, "More", pIntent)
        .addAction(R.drawable.icon, "And more", pIntent).build();


NotificationManager notificationManager = 
  (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

notificationManager.notify(0, n); 

Best way
Code above needs minimum API level 11 (Android 3.0).
If your minimum API level is lower than 11, you should you use support library's NotificationCompat class like this.

So if your minimum target API level is 4+ (Android 1.6+) use this:

    import android.support.v4.app.NotificationCompat;
    -------------
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.mylogo)
                    .setContentTitle("My Notification Title")
                    .setContentText("Something interesting happened");
    int NOTIFICATION_ID = 12345;

    Intent targetIntent = new Intent(this, MyFavoriteActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nManager.notify(NOTIFICATION_ID, builder.build());

Scroll Automatically to the Bottom of the Page

If you want to scroll entire page to the bottom:

var scrollingElement = (document.scrollingElement || document.body);
scrollingElement.scrollTop = scrollingElement.scrollHeight;

See the sample on JSFiddle

If you want to scroll an element to the bottom:

function gotoBottom(id){
   var element = document.getElementById(id);
   element.scrollTop = element.scrollHeight - element.clientHeight;
}

And that's how it works:

enter image description here

Ref: scrollTop, scrollHeight, clientHeight

UPDATE: Latest versions of Chrome (61+) and Firefox does not support scrolling of body, see: https://dev.opera.com/articles/fixing-the-scrolltop-bug/

Android EditText delete(backspace) key event

This question may be old but the answer is really simple using a TextWatcher.

int lastSize=0;
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
    //2. compare the old length of the text with the new one
    //3. if the length is shorter, then backspace was clicked
    if (lastSize > charSequence.length()) {
        //4. Backspace was clicked
        //5. perform action
    }
    //1. get the current length of of the text
    lastSize = charSequence.length();
}

How can I generate a list or array of sequential integers in Java?

This is the shortest I could get using Core Java.

List<Integer> makeSequence(int begin, int end) {
  List<Integer> ret = new ArrayList(end - begin + 1);

  for(int i = begin; i <= end; i++, ret.add(i));

  return ret;  
}

Delete a closed pull request from GitHub

There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.

However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.

Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]

UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact

Get first word of string

const getFirstWord = string => {
    const firstWord = [];
    for (let i = 0; i < string.length; i += 1) {
        if (string[i] === ' ') break;
        firstWord.push(string[i]);
    }
    return firstWord.join('');
};
console.log(getFirstWord('Hello World'));

or simplify it:

const getFirstWord = string => {
    const words = string.split(' ');
    return words[0];
};
console.log(getFirstWord('Hello World'));

Saving awk output to variable

I think the $() syntax is easier to read...

variable=$(ps -ef | grep "port 10 -" | grep -v "grep port 10 -"| awk '{printf "%s", $12}')

But the real issue is probably that $12 should not be qouted with ""

Edited since the question was changed, This returns valid data, but it is not clear what the expected output of ps -ef is and what is expected in variable.

Install apps silently, with granted INSTALL_PACKAGES permission

I made a test app for silent installs, using PackageManager.installPackage method.

I get installPackage method through reflection, and made android.content.pm.IPackageInstallObserver interface in my src folder (because it's hidden in android.content.pm package).

When i run installPackage, i got SecurityException with string indication, that my app has no android.permission.INSTALL_PACKAGES, but it defined in AndroidManifest.xml.

So, i think, it's not possible to use this method.

PS. I tested in on Android SDK 2.3 and 4.0. Maybe it will work with earlier versions.

Assign a class name to <img> tag instead of write it in css file?

I think the Class on img tag is better when You use the same style in different structure on Your site. You have to decide when you write less line of CSS code and HTML is more readable.

Combining a class selector and an attribute selector with jQuery

This code works too:

$("input[reference=12345].myclass").css('border', '#000 solid 1px');

Hibernate JPA Sequence (non-Id)

"I don't want to use a trigger or any other thing other than Hibernate itself to generate the value for my property"

In that case, how about creating an implementation of UserType which generates the required value, and configuring the metadata to use that UserType for persistence of the mySequenceVal property?

In Java, should I escape a single quotation mark (') in String (double quoted)?

It's best practice only to escape the quotes when you need to - if you can get away without escaping it, then do!

The only times you should need to escape are when trying to put " inside a string, or ' in a character:

String quotes = "He said \"Hello, World!\"";
char quote = '\'';

Differences between "java -cp" and "java -jar"?

When using java -cp you are required to provide fully qualified main class name, e.g.

java -cp com.mycompany.MyMain

When using java -jar myjar.jar your jar file must provide the information about main class via manifest.mf contained into the jar file in folder META-INF:

Main-Class: com.mycompany.MyMain

Validate form field only on submit or user input

Erik Aigner,

Please use $dirty(The field has been modified) and $invalid (The field content is not valid).

Please check below examples for angular form validation

1)

Validation example HTML for user enter inputs:

<form  ng-app="myApp"  ng-controller="validateCtrl" name="myForm" novalidate>
  <p>Email:<br>
    <input type="email" name="email" ng-model="email" required>
    <span ng-show="myForm.email.$dirty && myForm.email.$invalid">
      <span ng-show="myForm.email.$error.required">Email is required.</span>
      <span ng-show="myForm.email.$error.email">Invalid email address.</span>
      </span>
  </p>
    </form>

2)

Validation example HTML/Js for user submits :

      <form  ng-app="myApp"  ng-controller="validateCtrl" name="myForm" novalidate form-submit-validation="">
      <p>Email:<br>
        <input type="email" name="email" ng-model="email" required>
        <span ng-show="submitted || myForm.email.$dirty && myForm.email.$invalid">
          <span ng-show="myForm.email.$error.required">Email is required.</span>
          <span ng-show="myForm.email.$error.email">Invalid email address.</span>
          </span>
      </p>
<p>
  <input type="submit">
</p>
</form>

Custom Directive :

app.directive('formSubmitValidation', function () {

        return {
            require: 'form',
            compile: function (tElem, tAttr) {

                tElem.data('augmented', true);

                return function (scope, elem, attr, form) {
                    elem.on('submit', function ($event) {
                        scope.$broadcast('form:submit', form);

                        if (!form.$valid) {
                            $event.preventDefault();
                        }
                        scope.$apply(function () {
                            scope.submitted = true;
                        });


                    });
                }
            }
        };


  })

3)

you don't want use directive use ng-change function like below

  <form  ng-app="myApp"  ng-controller="validateCtrl" name="myForm" novalidate ng-change="submitFun()">
      <p>Email:<br>
        <input type="email" name="email" ng-model="email" required>
        <span ng-show="submitted || myForm.email.$dirty && myForm.email.$invalid">
          <span ng-show="myForm.email.$error.required">Email is required.</span>
          <span ng-show="myForm.email.$error.email">Invalid email address.</span>
          </span>
      </p>
<p>
  <input type="submit">
</p>
</form>

Controller SubmitFun() JS:

 var app = angular.module('example', []);
 app.controller('exampleCntl', function($scope) {
 $scope.submitFun = function($event) {
 $scope.submitted = true;
  if (!$scope.myForm.$valid) 
  {
        $event.preventDefault();
   }
  }

});

Printing tuple with string formatting in Python

Talk is cheap, show you the code:

>>> tup = (10, 20, 30)
>>> i = 50
>>> print '%d      %s'%(i,tup)
50  (10, 20, 30)
>>> print '%s'%(tup,)
(10, 20, 30)
>>> 

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

Essentially it means you don't have the index you are trying to reference. For example:

df = pd.DataFrame()
df['this']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #I haven't yet assigned how long df[data] should be!
print(df)

will give me the error you are referring to, because I haven't told Pandas how long my dataframe is. Whereas if I do the exact same code but I DO assign an index length, I don't get an error:

df = pd.DataFrame(index=[0,1,2,3,4])
df['this']=np.nan
df['is']=np.nan
df['my']=np.nan
df['data']=np.nan
df['data'][0]=5 #since I've properly labelled my index, I don't run into this problem!
print(df)

Hope that answers your question!

AngularJs event to call after content is loaded

According to documentation of $viewContentLoaded, it supposed to work

Emitted every time the ngView content is reloaded.

$viewContentLoaded event is emitted that means to receive this event you need a parent controller like

<div ng-controller="MainCtrl">
  <div ng-view></div>
</div>

From MainCtrl you can listen the event

  $scope.$on('$viewContentLoaded', function(){
    //Here your view content is fully loaded !!
  });

Check the Demo

how to create virtual host on XAMPP

In Your disk drive:\xampp\apache\conf\extra\httpd-vhosts.conf exists an example and you could edit it with your configuration:

 ##<VirtualHost *:80>
 ##ServerAdmin [email protected]
 ##DocumentRoot "C:/xampp/htdocs/dummy-host.example.com"
 ##ServerName dummy-host.example.com
 ##ServerAlias www.dummy-host.example.com
 ##ErrorLog "logs/dummy-host.example.com-error.log"
 ##CustomLog "logs/dummy-host.example.com-access.log" common
 ##</VirtualHost>

It would be like this, as example and don't forget to add VirtualHost for localhost itself to have posibility run phpmyadmin and other project at the same time on the port 80, as example I will show with store.local project:

<VirtualHost *:80>
DocumentRoot "C:/xampp/htdocs"
ServerName localhost
</VirtualHost>

<VirtualHost *:80>
ServerAdmin [email protected]
DocumentRoot "c:/xampp/htdocs/store.local/public"
ServerName www.store.local
ServerAlias store.local
<Directory C:/xampp/htdocs/store.local>
    AllowOverride All
    Require all granted
</Directory>
</VirtualHost>

then as mentioned above you must add in: C:\windows\system32\drivers\hosts to the bottom of the file

127.0.0.1    store.local
127.0.0.1    www.store.local

restart Apache and try in the browser:

store.local or www.store.local

maybe at the first time you must to add like this:

http://store.local or http://www.store.local

to use other ports, you must add follows, before your VirtualHost:

Listen 8081 or another which you prefer

then just use the port for your VirtualHost like this:

<VirtualHost *:8081>
ServerAdmin [email protected]
DocumentRoot "c:/xampp/htdocs/store.local/public"
ServerName store.local
ServerAlias www.store.local
<Directory C:/xampp/htdocs/store.local>
    AllowOverride All
    Require all granted
</Directory>

then restart Apache and try in the browser

store.local:8081 or www.store.local:8081

and only project for which you add the port will running on this port, for example other projects and phpmyadmin will be still running on port 80

Access files stored on Amazon S3 through web browser

You can use a bucket policy to give anonymous users full read access to your objects. Depending on whether you need them to LIST or just perform a GET, you'll want to tweak this. (I.e. permissions for listing the contents of a bucket have the action set to "s3:ListBucket").

http://docs.aws.amazon.com/AmazonS3/latest/dev/AccessPolicyLanguage_UseCases_s3_a.html

Your policy will look something like the following. You can use the S3 console at http://aws.amazon.com/console to upload it.

 {
  "Version":"2008-10-17",
  "Statement":[{
    "Sid":"AddPerm",
      "Effect":"Allow",
      "Principal": {
            "AWS": "*"
         },
      "Action":["s3:GetObject"],
      "Resource":["arn:aws:s3:::bucket/*"
      ]
    }
  ]
}

If you're truly opening up your objects to the world, you'll want to look into setting up CloudWatch rules on your billing so you can shut off permissions to your objects if they become too popular.

Javascript date.getYear() returns 111 in 2011?

In order to comply with boneheaded precedent, getYear() returns the number of years since 1900.

Instead, you should call getFullYear(), which returns the actual year.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

I keep coming back to this post, I've encountered this error several times. It might have to do with importing all my databases after doing a fresh install.

I'm using homebrew. The only thing that used to fix it for me:

sudo mkdir /var/mysql
sudo ln -s /tmp/mysql.sock /var/mysql/mysql.sock

This morning, the issue returned after my machine decided to shut down overnight. The only thing that fixed it now was to upgrade mysql.

brew upgrade mysql

How can I fix the Microsoft Visual Studio error: "package did not load correctly"?

Try devenv /setup on the Visual Studio Command Prompt with administrative rights.

I had the same problem with Visual Studio 2013 Ultimate. I tried the solution by Reza posted here, but it didn't work.

Eventually I couldn't close Visual Studio. It was showing a similar dialog when I tried to close, and it wasn't closing. I tried this: Error message "No exports were found that match the constraint contract name". Neither.

I noticed a message in the Team Explorer window saying "Page 'somenumber' cannot be found". I tried that way, and I found this answer: Page '312e8a59-2712-48a1-863e-0ef4e67961fc' not found using Visual Studio 2012. So I run devenv /setup on the Visual Studio Command Prompt with administrative rights.

It did the job, and everything is fine now.

How to write to error log file in PHP

We all know that PHP save errors in php_errors.log file.

But, that file contains a lot of data.

If we want to log our application data, we need to save it to a custom location.

We can use two parameters in the error_log function to achieve this.

http://php.net/manual/en/function.error-log.php

We can do it using:

error_log(print_r($v, TRUE), 3, '/var/tmp/errors.log');

Where,

print_r($v, TRUE) : logs $v (array/string/object) to log file. 3: Put log message to custom log file specified in the third parameter.

'/var/tmp/errors.log': Custom log file (This path is for Linux, we can specify other depending upon OS).

OR, you can use file_put_contents()

file_put_contents('/var/tmp/e.log', print_r($v, true), FILE_APPEND);

Where:

'/var/tmp/errors.log': Custom log file (This path is for Linux, we can specify other depending upon OS). print_r($v, TRUE) : logs $v (array/string/object) to log file. FILE_APPEND: Constant parameter specifying whether to append to the file if it exists, if file does not exist, new file will be created.

R legend placement in a plot

Edit 2017:

use ggplot and theme(legend.position = ""):

library(ggplot2)
library(reshape2)

set.seed(121)
a=sample(1:100,5)
b=sample(1:100,5)
c=sample(1:100,5)

df = data.frame(number = 1:5,a,b,c)
df_long <- melt(df,id.vars = "number")
ggplot(data=df_long,aes(x = number,y=value, colour=variable)) +geom_line() +
theme(legend.position="bottom")

Original answer 2012: Put the legend on the bottom:

set.seed(121)
a=sample(1:100,5)
b=sample(1:100,5)
c=sample(1:100,5)

dev.off()

layout(rbind(1,2), heights=c(7,1))  # put legend on bottom 1/8th of the chart

plot(a,type='l',ylim=c(min(c(a,b,c)),max(c(a,b,c))))
lines(b,lty=2)
lines(c,lty=3,col='blue')

# setup for no margins on the legend
par(mar=c(0, 0, 0, 0))
# c(bottom, left, top, right)
plot.new()
legend('center','groups',c("A","B","C"), lty = c(1,2,3),
       col=c('black','black','blue'),ncol=3,bty ="n")

enter image description here

How To Include CSS and jQuery in my WordPress plugin?

You can use the following function to enqueue script or style from plugin.

function my_enqueued_assets() {
    wp_enqueue_script('my-js-file', plugin_dir_url(__FILE__) . '/js/script.js', '', time());
    wp_enqueue_style('my-css-file', plugin_dir_url(__FILE__) . '/css/style.css', '', time());
}
add_action('wp_enqueue_scripts', 'my_enqueued_assets');

Looping from 1 to infinity in Python

Using itertools.count:

import itertools
for i in itertools.count(start=1):
    if there_is_a_reason_to_break(i):
        break

In Python 2, range() and xrange() were limited to sys.maxsize. In Python 3 range() can go much higher, though not to infinity:

import sys
for i in range(sys.maxsize**10):  # you could go even higher if you really want
    if there_is_a_reason_to_break(i):
        break

So it's probably best to use count().

client denied by server configuration

in my case,

i'm using macOS Mojave (Apache/2.4.34). There was an issue in virtual host settings at /etc/apache2/extra/httpd-vhosts.conf file. after adding the required directory tag my problem was gone.

Require all granted

Hope the full virtual host setup structure will save you.

<VirtualHost *:80>
    DocumentRoot "/Users/vagabond/Sites/MainProjectFolderName/public/"
    ServerName project.loc

    <Directory /Users/vagabond/Sites/MainProjectFolderName/public/>
        Require all granted
    </Directory>

    ErrorLog "/Users/vagabond/Sites/logs/MainProjectFolderName.loc-error_log"
    CustomLog "/Users/vagabond/Sites/logs/MainProjectFolderName.loc-access_log" common
</VirtualHost>

all you've to do replace the MainProjectFolderName with your exact ProjectFolderName.

PHP: merge two arrays while keeping keys instead of reindexing?

Try array_replace_recursive or array_replace functions

$a = array('userID' => 1, 'username'=> 2);
array (
  userID => 1,
  username => 2
)
$b = array('userID' => 1, 'companyID' => 3);
array (
  'userID' => 1,
  'companyID' => 3
)
$c = array_replace_recursive($a,$b);
array (
  userID => 1,
  username => 2,
  companyID => 3
)

http://php.net/manual/en/function.array-replace-recursive.php

rewrite a folder name using .htaccess

mod_rewrite can only rewrite/redirect requested URIs. So you would need to request /apple/… to get it rewritten to a corresponding /folder1/….

Try this:

RewriteEngine on
RewriteRule ^apple/(.*) folder1/$1

This rule will rewrite every request that starts with the URI path /apple/… internally to /folder1/….


Edit    As you are actually looking for the other way round:

RewriteCond %{THE_REQUEST} ^GET\ /folder1/
RewriteRule ^folder1/(.*) /apple/$1 [L,R=301]

This rule is designed to work together with the other rule above. Requests of /folder1/… will be redirected externally to /apple/… and requests of /apple/… will then be rewritten internally back to /folder1/….

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

How can I check if a Perl module is installed on my system from the command line?

Bravo for @user80168's solution (I'm still counting \'s !) but to avoid all the escaping involved with aliases and shells:

%~/ cat ~/bin/perlmod
perl -le'eval qq{require $ARGV[0]; } 
    ? print ( "Found $ARGV[0] Version: ", eval "$ARGV[0]->VERSION" ) 
    : print "Not installed" ' $1

works reasonably well.

Here might be the simplest and most "modern" approach, using Module::Runtime:

perl -MModule::Runtime=use_module -E '
     say "$ARGV[0] ", use_module($ARGV[0])->VERSION' DBI

This will give a useful error if the module is not installed.

Using -MModule::Runtime requires it to be installed (it is not a core module).

How to create new folder?

You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:

newpath = r'C:\Program Files\arbitrary' 
if not os.path.exists(newpath):
    os.makedirs(newpath)

If you're trying to make an installer: Windows Installer does a lot of work for you.

prevent iphone default keyboard when focusing an <input>

So here is my solution (similar to John Vance's answer):

First go here and get a function to detect mobile browsers.

http://detectmobilebrowsers.com/

They have a lot of different ways to detect if you are on mobile, so find one that works with what you are using.

Your HTML page (pseudo code):

If Mobile Then
    <input id="selling-date" type="date" placeholder="YYYY-MM-DD" max="2999-12-31" min="2010-01-01" value="2015-01-01" />
else
    <input id="selling-date" type="text" class="date-picker" readonly="readonly" placeholder="YYYY-MM-DD" max="2999-12-31" min="2010-01-01" value="2015-01-01" />

JQuery:

$( ".date-picker" ).each(function() {
    var min = $( this ).attr("min");
    var max = $( this ).attr("max");
    $( this ).datepicker({ 
        dateFormat: "yy-mm-dd",  
        minDate: min,  
        maxDate: max  
    });
});

This way you can still use native date selectors in mobile while still setting the min and max dates either way.

The field for non mobile should be read only because if a mobile browser like chrome for ios "requests desktop version" then they can get around the mobile check and you still want to prevent the keyboard from showing up.

However if the field is read only it could look to a user like they cant change the field. You could fix this by changing the CSS to make it look like it isn't read only (ie change border-color to black) but unless you are changing the CSS for all input tags you will find it hard to keep the look consistent across browsers.

To get arround that I just add a calendar image button to the date picker. Just change your JQuery code a bit:

$( ".date-picker" ).each(function() {
    var min = $( this ).attr("min");
    var max = $( this ).attr("max");
    $( this ).datepicker({ 
        dateFormat: "yy-mm-dd",  
        minDate: min,  
        maxDate: max,
        showOn: "both",
        buttonImage: "images/calendar.gif",
        buttonImageOnly: true,
        buttonText: "Select date"
    });
});

Note: you will have to find a suitable image.

At runtime, find all classes in a Java application that extend a base class

I use org.reflections:

Reflections reflections = new Reflections("com.mycompany");    
Set<Class<? extends MyInterface>> classes = reflections.getSubTypesOf(MyInterface.class);

Another example:

public static void main(String[] args) throws IllegalAccessException, InstantiationException {
    Reflections reflections = new Reflections("java.util");
    Set<Class<? extends List>> classes = reflections.getSubTypesOf(java.util.List.class);
    for (Class<? extends List> aClass : classes) {
        System.out.println(aClass.getName());
        if(aClass == ArrayList.class) {
            List list = aClass.newInstance();
            list.add("test");
            System.out.println(list.getClass().getName() + ": " + list.size());
        }
    }
}

Sharing a URL with a query string on Twitter

This can be solved by using https://twitter.com/intent/tweet instead of http://www.twitter.com/share. Using the intent/tweet function, you simply URL encode your entire URL and it works like a charm.

https://dev.twitter.com/web/intents

IntelliJ show JavaDocs tooltip on mouse over

For IntelliJ 13, there is a checkbox in Editor's page in IDE Settings

enter image description here

EDIT: For IntelliJ 14, the option has been moved to Editor > General page. It's the last option in the "Other" group. (For Mac the option is under the menu "IntelliJ Idea" > "Preferences").

EDIT: For IntelliJ 16, it's the second-to-last option in Editor > General > Other.

EDIT: For IntelliJ Ultimate 2016.1, it's been moved to Editor > General > Code Completion. enter image description here

EDIT: For IntelliJ Ultimate 2017.2, aka IntelliJ IDEA 2017.2.3, there are actually two options:

  1. In Editor > General > Other (section) > Show quick documentation on mouse move - delay 500 ms
  • Select this check box to show quick documentation for the symbol at caret. The quick documentation pop-up window appears after the specified delay.
  1. In Editor > General > Code Completion (sub-item) > Autopopup documention in 1000 ms, for explicitly invoked completion
  • Select this check box to have IntelliJ IDEA automatically show a pop-up window with the documentation for the class, method, or field currently highlighted in the lookup list. If this check box is not selected, use Ctrl+Q to show quick documentation for the element at caret.
  • Quick documentation window will automatically pop up with the specified delay in those cases only, when code completion has been invoked explicitly. For the automatic code completion list, documentation window will only show up on pressing Ctrl+Q.

EDIT: For IntelliJ Ultimate 2020.3, the first option is now located under Editor > Code Editing > Quick Documentation > Show quick documentation on mouse move

How to make parent wait for all child processes to finish?

pid_t child_pid, wpid;
int status = 0;

//Father code (before child processes start)

for (int id=0; id<n; id++) {
    if ((child_pid = fork()) == 0) {
        //child code
        exit(0);
    }
}

while ((wpid = wait(&status)) > 0); // this way, the father waits for all the child processes 

//Father code (After all child processes end)

wait waits for a child process to terminate, and returns that child process's pid. On error (eg when there are no child processes), -1 is returned. So, basically, the code keeps waiting for child processes to finish, until the waiting errors out, and then you know they are all finished.

Add a column to a table, if it does not already exist

Here's another variation that worked for me.

IF NOT EXISTS (SELECT 1
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE upper(TABLE_NAME) = 'TABLENAME'
        AND upper(COLUMN_NAME) = 'COLUMNNAME')
BEGIN
    ALTER TABLE [dbo].[Person] ADD Column
END
GO

EDIT: Note that INFORMATION_SCHEMA views may not always be updated, use SYS.COLUMNS instead:

IF NOT EXISTS (SELECT 1 FROM SYS.COLUMNS....

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

ALTER DATABASE test2            --put your database name here
COLLATE Latin1_General_CS_AS    --replace with the collation you need

What is meant by Ems? (Android TextView)

android:ems or setEms(n) sets the width of a TextView to fit a text of n 'M' letters regardless of the actual text extension and text size. See wikipedia Em unit

but only when the layout_width is set to "wrap_content". Other layout_width values override the ems width setting.

Adding an android:textSize attribute determines the physical width of the view to the textSize * length of a text of n 'M's set above.

Python: printing a file to stdout

To improve on @bgporter's answer, with Python-3 you will probably want to operate on bytes instead of needlessly converting things to utf-8:

>>> import shutil
>>> import sys
>>> with open("test.txt", "rb") as f:
...    shutil.copyfileobj(f, sys.stdout.buffer)

How do I select text nodes with jQuery?

$('body').find('*').contents().filter(function () { return this.nodeType === 3; });

What is the best way to determine a session variable is null or empty in C#?

If you know it's a string, you can use the String.IsEmptyOrNull() function.

How do I display a MySQL error in PHP for a long query that depends on the user input?

One useful line of code for you would be:

$sql = "Your SQL statement here";
$result = mysqli_query($this->db_link, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($this->db_link), E_USER_ERROR);

This method is better than die, because you can use it for development AND production. It's the permanent solution.

Is there a Python caching library?

keyring is the best python caching library. You can use

keyring.set_password("service","jsonkey",json_res)

json_res= keyring.get_password("service","jsonkey")

json_res= keyring.core.delete_password("service","jsonkey")

Is there a way since (iOS 7's release) to get the UDID without using iTunes on a PC/Mac?

Have them create a testflightapp.com account.

This is very useful for beta testing - which I'm guessing is what you need the udids for.

You can send them a download link to your app (found in the permissions tap at the bottom of the page) and it will tell them their udid hasn't been validated yet. It will then tell them their udid! They can copy and paste this and text it to you.

How does the data-toggle attribute work? (What's its API?)

The data-* attributes is used to store custom data private to the page or application

So Bootstrap uses these attributes for saving states of objects

W3School data-* description

How do you create a Marker with a custom icon for google maps API v3?

Try

    var marker = new google.maps.Marker({
      position: map.getCenter(),
      icon: 'http://imageshack.us/a/img826/9489/x1my.png',
      map: map
    });

from here

https://developers.google.com/maps/documentation/javascript/examples/marker-symbol-custom

How to move git repository with all branches from bitbucket to github?

It's very simple.

  1. Create a new empty repository in GitHub (without readme or license, you can add them later) and the following screen will show.

  2. In the import code option, paste your Bitbucket repo's URL and voilà!!

Click Import code

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

You should set your RecyclerView LayoutManager to Gridlayout mode. Just change your code when you want to set your RecyclerView LayoutManager:

recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), numberOfColumns));

How to read the RGB value of a given pixel in Python?

It's probably best to use the Python Image Library to do this which I'm afraid is a separate download.

The easiest way to do what you want is via the load() method on the Image object which returns a pixel access object which you can manipulate like an array:

from PIL import Image

im = Image.open('dead_parrot.jpg') # Can be many different formats.
pix = im.load()
print im.size  # Get the width and hight of the image for iterating over
print pix[x,y]  # Get the RGBA Value of the a pixel of an image
pix[x,y] = value  # Set the RGBA Value of the image (tuple)
im.save('alive_parrot.png')  # Save the modified pixels as .png

Alternatively, look at ImageDraw which gives a much richer API for creating images.

Python strftime - date without leading 0?

quite late to the party but %-d works on my end.

datetime.now().strftime('%B %-d, %Y') produces something like "November 5, 2014"

cheers :)

Which Protocols are used for PING?

ICMP means Internet Control Message Protocol and is always coupled with the IP protocol (There's 2 ICMP variants one for IPv4 and one for IPv6.)

echo request and echo response are the two operation codes of ICMP used to implement ping.

Besides the original ping program, ping might simply mean the action of checking if a remote node is responding, this might be done on several layers in a protocol stack - e.g. ARP ping for testing hosts on a local network. The term ping might be used on higher protocol layers and APIs as well, e.g. the act of checking if a database is up, done at the database layer protocol.

ICMP sits on top of IP. What you have below depends on the network you're on, and are not in themselves relevant to the operation of ping.

check if a key exists in a bucket in s3 using boto3

FWIW, here are the very simple functions that I am using

import boto3

def get_resource(config: dict={}):
    """Loads the s3 resource.

    Expects AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY to be in the environment
    or in a config dictionary.
    Looks in the environment first."""

    s3 = boto3.resource('s3',
                        aws_access_key_id=os.environ.get(
                            "AWS_ACCESS_KEY_ID", config.get("AWS_ACCESS_KEY_ID")),
                        aws_secret_access_key=os.environ.get("AWS_SECRET_ACCESS_KEY", config.get("AWS_SECRET_ACCESS_KEY")))
    return s3


def get_bucket(s3, s3_uri: str):
    """Get the bucket from the resource.
    A thin wrapper, use with caution.

    Example usage:

    >> bucket = get_bucket(get_resource(), s3_uri_prod)"""
    return s3.Bucket(s3_uri)


def isfile_s3(bucket, key: str) -> bool:
    """Returns T/F whether the file exists."""
    objs = list(bucket.objects.filter(Prefix=key))
    return len(objs) == 1 and objs[0].key == key


def isdir_s3(bucket, key: str) -> bool:
    """Returns T/F whether the directory exists."""
    objs = list(bucket.objects.filter(Prefix=key))
    return len(objs) > 1

Find files with size in Unix

Assuming you have GNU find:

find . -size +10000k -printf '%s %f\n'

If you want a constant width for the size field, you can do something like:

find . -size +10000k -printf '%10s %f\n'

Note that -size +1000k selects files of at least 10,240,000 bytes (k is 1024, not 1000). You said in a comment that you want files bigger than 1M; if that's 1024*1024 bytes, then this:

find . -size +1M ...

will do the trick -- except that it will also print the size and name of files that are exactly 1024*1024 bytes. If that matters, you could use:

find . -size +1048575c ...

You need to decide just what criterion you want.

Git workflow and rebase vs merge questions

With Git there is no “correct” workflow. Use whatever floats your boat. However, if you constantly get conflicts when merging branches maybe you should coordinate your efforts better with your fellow developer(s)? Sounds like the two of you keep editing the same files. Also, watch out for whitespace and subversion keywords (i.e., “$Id$” and others).

Java String encoding (UTF-8)

This could be complicated way of doing

String newString = new String(oldString);

This shortens the String is the underlying char[] used is much longer.

However more specifically it will be checking that every character can be UTF-8 encoded.

There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?

Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'

String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));

prints

false

How to see if an object is an array without using reflection?

One can access each element of an array separately using the following code:

Object o=...;
if ( o.getClass().isArray() ) {
    for(int i=0; i<Array.getLength(o); i++){
        System.out.println(Array.get(o, i));
    }
}

Notice that it is unnecessary to know what kind of underlying array it is, as this will work for any array.

Call a global variable inside module

Download the bootbox typings

Then add a reference to it inside your .ts file.

How to drop a table if it exists?

Make sure to use cascade constraint at the end to automatically drop all objects that depend on the table (such as views and projections).

drop table if exists tableName cascade;

How to refresh a page with jQuery by passing a parameter to URL

var singleText = "single";
var s = window.location.search;

if (s.indexOf(singleText) == -1) {
    window.location.href += (s.substring(0,1) == "?") ? "&" : "?" + singleText;
}

Comparing boxed Long values 127 and 128

num1 and num2 are Long objects. You should be using equals() to compare them. == comparison might work sometimes because of the way JVM boxes primitives, but don't depend on it.

if (num1.equals(num1))
{
 //code
}

Find (and kill) process locking port 3000 on Mac

TL;DR:

lsof -ti tcp:3000 -sTCP:LISTEN | xargs kill

If you're in a situation where there are both clients and servers using the port, e.g.:

$ lsof -i tcp:3000
COMMAND     PID         USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
node       2043 benjiegillam   21u  IPv4 0xb1b4330c68e5ad61      0t0  TCP localhost:3000->localhost:52557 (ESTABLISHED)
node       2043 benjiegillam   22u  IPv4 0xb1b4330c8d393021      0t0  TCP localhost:3000->localhost:52344 (ESTABLISHED)
node       2043 benjiegillam   25u  IPv4 0xb1b4330c8eaf16c1      0t0  TCP localhost:3000 (LISTEN)
Google    99004 benjiegillam  125u  IPv4 0xb1b4330c8bb05021      0t0  TCP localhost:52557->localhost:3000 (ESTABLISHED)
Google    99004 benjiegillam  216u  IPv4 0xb1b4330c8e5ea6c1      0t0  TCP localhost:52344->localhost:3000 (ESTABLISHED)

then you probably don't want to kill both.

In this situation you can use -sTCP:LISTEN to only show the pid of processes that are listening. Combining this with the -t terse format you can automatically kill the process:

lsof -ti tcp:3000 -sTCP:LISTEN | xargs kill

LINQ Join with Multiple Conditions in On Clause

You can't do it like that. The join clause (and the Join() extension method) supports only equijoins. That's also the reason, why it uses equals and not ==. And even if you could do something like that, it wouldn't work, because join is an inner join, not outer join.

Oracle Error ORA-06512

The variable pCv is of type VARCHAR2 so when you concat the insert you aren't putting it inside single quotes:

 EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('''||pCv||''', '||pSup||', '||pIdM||')';

Additionally the error ORA-06512 raise when you are trying to insert a value too large in a column. Check the definiton of the table M_pNum_GR and the parameters that you are sending. Just for clarify if you try to insert the value 100 on a NUMERIC(2) field the error will raise.

Most efficient way to append arrays in C#?

If you can make an approximation of the number of items that will be there at the end, use the overload of the List constuctor that takes count as a parameter. You will save some expensive List duplications. Otherwise you have to pay for it.

Removing duplicates from a list of lists

Another probably more generic and simpler solution is to create a dictionary keyed by the string version of the objects and getting the values() at the end:

>>> dict([(unicode(a),a) for a in [["A", "A"], ["A", "A"], ["A", "B"]]]).values()
[['A', 'B'], ['A', 'A']]

The catch is that this only works for objects whose string representation is a good-enough unique key (which is true for most native objects).

Set background image on grid in WPF using C#

In order to avoid path problem, you can simply try this, just keep background image in images folder and add this code

<Grid>
  <Grid.Background>
    <ImageBrush Stretch="Fill" ImageSource="..\Images\background.jpg"
                AlignmentY="Top" AlignmentX="Center"/>
  </Grid.Background>
</Grid>

What is the idiomatic Go equivalent of C's ternary operator?

eold's answer is interesting and creative, perhaps even clever.

However, it would be recommended to instead do:

var index int
if val > 0 {
    index = printPositiveAndReturn(val)
} else {
    index = slowlyReturn(-val)  // or slowlyNegate(val)
}

Yes, they both compile down to essentially the same assembly, however this code is much more legible than calling an anonymous function just to return a value that could have been written to the variable in the first place.

Basically, simple and clear code is better than creative code.

Additionally, any code using a map literal is not a good idea, because maps are not lightweight at all in Go. Since Go 1.3, random iteration order for small maps is guaranteed, and to enforce this, it's gotten quite a bit less efficient memory-wise for small maps.

As a result, making and removing numerous small maps is both space-consuming and time-consuming. I had a piece of code that used a small map (two or three keys, are likely, but common use case was only one entry) But the code was dog slow. We're talking at least 3 orders of magnitude slower than the same code rewritten to use a dual slice key[index]=>data[index] map. And likely was more. As some operations that were previously taking a couple of minutes to run, started completing in milliseconds.\

Java RegEx meta character (.) and ordinary dot?

I wanted to match a string that ends with ".*" For this I had to use the following:

"^.*\\.\\*$"

Kinda silly if you think about it :D Heres what it means. At the start of the string there can be any character zero or more times followed by a dot "." followed by a star (*) at the end of the string.

I hope this comes in handy for someone. Thanks for the backslash thing to Fabian.

Why does my Spring Boot App always shutdown immediately after starting?

Maybe it does not fit to your code but i found out if you have a code snippet like this:

@SpringBootApplication
public class SpringBootApacheKafkaApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringBootApacheKafkaApplication.class,args).close();
    }
}

then just remove the close() method. That's fixed my problem! Maybe I can help someone with that

How to add button inside input

This is the cleanest way to do in bootstrap v3.

<div class="form-group">
    <div class="input-group">
        <input type="text" name="search" class="form-control" placeholder="Search">
        <span><button type="submit" class="btn btn-primary"><i class="fa fa-search"></i></button></span>
     </div>
</div>

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

It is not related with Firewall. I had the same issue accessing from office and from mobile. I cleaned the cookies and worked fine. You can read more at https://support.google.com/chromebook/answer/1085581?hl=en

Socket.IO - how do I get a list of connected sockets/clients?

I think we can access the socket object from the server, and you can assign the nickname, and point its socket id,

io.sockets.on('connection',function(socket){ 
    io.sockets.sockets['nickname'] = socket.id;
    client.on("chat", function(data) {      
        var sock_id = io.sockets.sockets['nickname']
        io.sockets.sockets[sock_id].emit("private", "message");
    });    
});

On disconnect please remove the nickname from io.sockets.sockets.

How do you get current active/default Environment profile programmatically in Spring?

Seems there is some demand to be able to access this statically.

How can I get such thing in static methods in non-spring-managed classes? – Aetherus

It's a hack, but you can write your own class to expose it. You must be careful to ensure that nothing will call SpringContext.getEnvironment() before all beans have been created, since there is no guarantee when this component will be instantiated.

@Component
public class SpringContext
{
    private static Environment environment;

    public SpringContext(Environment environment) {
        SpringContext.environment = environment;
    }

    public static Environment getEnvironment() {
        if (environment == null) {
            throw new RuntimeException("Environment has not been set yet");
        }
        return environment;
    }
}

Find if current time falls in a time range

You're very close, the problem is you're comparing a DateTime to a TimeOfDay. What you need to do is add the .TimeOfDay property to the end of your Convert.ToDateTime() functions.

How to parse JSON Array (Not Json Object) in Android

public static void main(String[] args) throws JSONException {
    String str = "[{\"name\":\"name1\",\"url\":\"url1\"},{\"name\":\"name2\",\"url\":\"url2\"}]";

    JSONArray jsonarray = new JSONArray(str);


    for(int i=0; i<jsonarray.length(); i++){
        JSONObject obj = jsonarray.getJSONObject(i);

        String name = obj.getString("name");
        String url = obj.getString("url");

        System.out.println(name);
        System.out.println(url);
    }   
}   

Output:

name1
url1
name2
url2

PHP date time greater than today

You are not comparing dates. You are comparing strings. In the world of string comparisons, 09/17/2015 > 01/02/2016 because 09 > 01. You need to either put your date in a comparable string format or compare DateTime objects which are comparable.

<?php
 $date_now = date("Y-m-d"); // this format is string comparable

if ($date_now > '2016-01-02') {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Or

<?php
 $date_now = new DateTime();
 $date2    = new DateTime("01/02/2016");

if ($date_now > $date2) {
    echo 'greater than';
}else{
    echo 'Less than';
}

Demo

Calculate the center point of multiple latitude/longitude coordinate pairs

Java Version if anyone needs it. Constants defined static to not calculate them twice.

/**************************************************************************************************************
 *   Center of geometry defined by coordinates
 **************************************************************************************************************/
private static double pi = Math.PI / 180;
private static double xpi = 180 / Math.PI;

public static Coordinate center(Coordinate... arr) {
    if (arr.length == 1) {
        return arr[0];
    }
    double x = 0, y = 0, z = 0;

    for (Coordinate c : arr) {
        double latitude = c.lat() * pi, longitude = c.lon() * pi;
        double cl = Math.cos(latitude);//save it as we need it twice
        x += cl * Math.cos(longitude);
        y += cl * Math.sin(longitude);
        z += Math.sin(latitude);
    }

    int total = arr.length;

    x = x / total;
    y = y / total;
    z = z / total;

    double centralLongitude = Math.atan2(y, x);
    double centralSquareRoot = Math.sqrt(x * x + y * y);
    double centralLatitude = Math.atan2(z, centralSquareRoot);

    return new Coordinate(centralLatitude * xpi, centralLongitude * xpi);
}

Difference between View and ViewGroup in Android

A View object is a component of the user interface (UI) like a button or a text box, and it's also called widget.

A ViewGroup object is a layout, that is, a container of other ViewGroup objects (layouts) and View objects (widgets). It's possible to have a layout inside another layout. It's called nested layout but it can increase the time needed to draw the user interface.

The user interface for an app is built using a hierarchy of ViewGroup and View objects. In Android Studio it is possible to use the Component Tree window to visualise this hierarchy.

The Layout Editor in Android Studio can be used to drag and drop View objects (widgets) in the layout. It simplifies the creation of a layout.

How does data binding work in AngularJS?

AngularJs supports Two way data-binding.
Means you can access data View -> Controller & Controller -> View

For Ex.

1)

// If $scope have some value in Controller. 
$scope.name = "Peter";

// HTML
<div> {{ name }} </div>

O/P

Peter

You can bind data in ng-model Like:-
2)

<input ng-model="name" />

<div> {{ name }} </div>

Here in above example whatever input user will give, It will be visible in <div> tag.

If want to bind input from html to controller:-
3)

<form name="myForm" ng-submit="registration()">
   <label> Name </lbel>
   <input ng-model="name" />
</form>

Here if you want to use input name in the controller then,

$scope.name = {};

$scope.registration = function() {
   console.log("You will get the name here ", $scope.name);
};

ng-model binds our view and render it in expression {{ }}.
ng-model is the data which is shown to the user in the view and with which the user interacts.
So it is easy to bind data in AngularJs.

php: catch exception and continue execution, is it possible?

php > 7

use the new interface Throwable

    try {
        // Code that may throw an Exception or Error.
    } catch (Throwable $t) {
        // Handle exception
    }

echo "Script is still running..."; // this script will be executed.

How do you search an amazon s3 bucket?

Fast forward to 2020, and using aws-okta as our 2fa, the following command, while slow as hell to iterate through all of the objects and folders in this particular bucket (+270,000) worked fine.

aws-okta exec dev -- aws s3 ls my-cool-bucket --recursive | grep needle-in-haystax.txt

Fit background image to div

You can use this attributes:

background-size: contain;
background-repeat: no-repeat;

and you code is then like this:

 <div style="text-align:center;background-image: url(/media/img_1_bg.jpg); background-size: contain;
background-repeat: no-repeat;" id="mainpage">

Python: Get HTTP headers from urllib2.urlopen call?

What about sending a HEAD request instead of a normal GET request. The following snipped (copied from a similar question) does exactly that.

>>> import httplib
>>> conn = httplib.HTTPConnection("www.google.com")
>>> conn.request("HEAD", "/index.html")
>>> res = conn.getresponse()
>>> print res.status, res.reason
200 OK
>>> print res.getheaders()
[('content-length', '0'), ('expires', '-1'), ('server', 'gws'), ('cache-control', 'private, max-age=0'), ('date', 'Sat, 20 Sep 2008 06:43:36 GMT'), ('content-type', 'text/html; charset=ISO-8859-1')]

How can I install the Beautiful Soup module on the Mac?

The "normal" way is to:

Another solution is to use easy_install. Go to http://peak.telecommunity.com/DevCenter/EasyInstall), install the package using the instructions on that page, and then type, in a Terminal window:

easy_install BeautifulSoup4
# for older v3:
# easy_install BeautifulSoup

easy_install will take care of downloading, unpacking, building, and installing the package. The advantage to using easy_install is that it knows how to search for many different Python packages, because it queries the PyPI registry. Thus, once you have easy_install on your machine, you install many, many different third-party packages simply by one command at a shell.

80-characters / right margin line in Sublime Text 3

Yes, it is possible both in Sublime Text 2 and 3 (which you should really upgrade to if you haven't already). Select View ? Ruler ? 80 (there are several other options there as well). If you like to actually wrap your text at 80 columns, select View ? Word Wrap Column ? 80. Make sure that View ? Word Wrap is selected.

To make your selections permanent (the default for all opened files or views), open Preferences ? Settings—User and use any of the following rules:

{
    // set vertical rulers in specified columns.
    // Use "rulers": [80] for just one ruler
    // default value is []
    "rulers": [80, 100, 120],

    // turn on word wrap for source and text
    // default value is "auto", which means off for source and on for text
    "word_wrap": true,

    // set word wrapping at this column
    // default value is 0, meaning wrapping occurs at window width
    "wrap_width": 80
}

These settings can also be used in a .sublime-project file to set defaults on a per-project basis, or in a syntax-specific .sublime-settings file if you only want them to apply to files written in a certain language (Python.sublime-settings vs. JavaScript.sublime-settings, for example). Access these settings files by opening a file with the desired syntax, then selecting Preferences ? Settings—More ? Syntax Specific—User.

As always, if you have multiple entries in your settings file, separate them with commas , except for after the last one. The entire content should be enclosed in curly braces { }. Basically, make sure it's valid JSON.

If you'd like a key combo to automatically set the ruler at 80 for a particular view/file, or you are interested in learning how to set the value without using the mouse, please see my answer here.

Finally, as mentioned in another answer, you really should be using a monospace font in order for your code to line up correctly. Other types of fonts have variable-width letters, which means one 80-character line may not appear to be the same length as another 80-character line with different content, and your indentations will look all messed up. Sublime has monospace fonts set by default, but you can of course choose any one you want. Personally, I really like Liberation Mono. It has glyphs to support many different languages and Unicode characters, looks good at a variety of different sizes, and (most importantly for a programming font) clearly differentiates between 0 and O (digit zero and capital letter oh) and 1 and l (digit one and lowercase letter ell), which not all monospace fonts do, unfortunately. Version 2.0 and later of the font are licensed under the open-source SIL Open Font License 1.1 (here is the FAQ).

Removing MySQL 5.7 Completely

You need to remove the /var/lib/mysql folder. Also, purge when you remove the packages (I'm told this helps).

sudo apt-get remove --purge mysql-server mysql-client mysql-common

sudo rm -rf /var/lib/mysql

I was encountering similar issues. The second line got rid of my issues and allowed me to set up MySql from scratch. Hopefully it helps you too!

Hibernate: hbm2ddl.auto=update in production?

I would vote no. Hibernate doesn't seem to understand when datatypes for columns have changed. Examples (using MySQL):

String with @Column(length=50)  ==> varchar(50)
changed to
String with @Column(length=100) ==> still varchar(50), not changed to varchar(100)

@Temporal(TemporalType.TIMESTAMP,TIME,DATE) will not update the DB columns if changed

There are probably other examples as well, such as pushing the length of a String column up over 255 and seeing it convert to text, mediumtext, etc etc.

Granted, I don't think there is really a way to "convert datatypes" with without creating a new column, copying the data and blowing away the old column. But the minute your database has columns which don't reflect the current Hibernate mapping you are living very dangerously...

Flyway is a good option to deal with this problem:

http://flywaydb.org

Check whether specific radio button is checked

I think you're using the wrong approach. You should set the value attribute of your input elements. Check the docs for .val() for examples of setting and returning the .val() of input elements.

ie.

<input type="radio" runat="server" name="testGroup" value="test2" />

return $('input:radio[name=testGroup]:checked').val() == 'test2';

Error:Execution failed for task ':app:processDebugResources'. > java.io.IOException: Could not delete folder "" in android studio

React Native

These steps solved my problem:

  • Renaming of ReactNativeApp/android/build directory to old.build
  • Closing Android Studio
  • Inside ReactNativeApp/android executed this command. gradlew clean
  • Making sure my RAM is 1500mb free
  • Then finally executing the command react-native run-android

** It's quite interesting to close Android Studio. But beleive me these steps solved my problem **

How to get CPU temperature?

You can give the Open Hardware Monitor a go, although it lacks support for the latest processors.

internal sealed class CpuTemperatureReader : IDisposable
{
    private readonly Computer _computer;

    public CpuTemperatureReader()
    {
        _computer = new Computer { CPUEnabled = true };
        _computer.Open();
    }

    public IReadOnlyDictionary<string, float> GetTemperaturesInCelsius()
    {
        var coreAndTemperature = new Dictionary<string, float>();

        foreach (var hardware in _computer.Hardware)
        {
            hardware.Update(); //use hardware.Name to get CPU model
            foreach (var sensor in hardware.Sensors)
            {
                if (sensor.SensorType == SensorType.Temperature && sensor.Value.HasValue)
                    coreAndTemperature.Add(sensor.Name, sensor.Value.Value);
            }
        }

        return coreAndTemperature;
    }

    public void Dispose()
    {
        try
        {
            _computer.Close();
        }
        catch (Exception)
        {
            //ignore closing errors
        }
    }
}

Download the zip from the official source, extract and add a reference to OpenHardwareMonitorLib.dll in your project.

Replace an element into a specific position of a vector

You can do that using at. You can try out the following simple example:

const size_t N = 20;
std::vector<int> vec(N);
try {
    vec.at(N - 1) = 7;
} catch (std::out_of_range ex) {
    std::cout << ex.what() << std::endl;
}
assert(vec.at(N - 1) == 7);

Notice that method at returns an allocator_type::reference, which is that case is a int&. Using at is equivalent to assigning values like vec[i]=....


There is a difference between at and insert as it can be understood with the following example:

const size_t N = 8;
std::vector<int> vec(N);
for (size_t i = 0; i<5; i++){
    vec[i] = i + 1;
}

vec.insert(vec.begin()+2, 10);

If we now print out vec we will get:

1 2 10 3 4 5 0 0 0

If, instead, we did vec.at(2) = 10, or vec[2]=10, we would get

1 2 10 4 5 0 0 0

How do I execute a bash script in Terminal?

Change your directory to where script is located by using cd command

Then type

bash program-name.sh

Specific Time Range Query in SQL Server

select * from table where 
(dtColumn between #3/1/2009# and #3/31/2009#) and 
(hour(dtColumn) between 6 and 22) and 
(weekday(dtColumn, 1) between 2 and 4) 

Change arrow colors in Bootstraps carousel

I know this is an older post, but it helped me out. I've also found that for bootstrap v4 you can also change the arrow color by overriding the controls like this:

.carousel-control-prev-icon {
 background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E") !important;
}

.carousel-control-next-icon {
  background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23fff' viewBox='0 0 8 8'%3E%3Cpath d='M2.75 0l-1.5 1.5 2.5 2.5-2.5 2.5 1.5 1.5 4-4-4-4z'/%3E%3C/svg%3E") !important;
}

Where you change fill='%23fff' the fff at the end to any hexadecimal value that you want. For example:

fill='%23000' for black, fill='%23ff0000' for red and so on. Just a note, I haven't tested this without the !important declaration.

How to download folder from putty using ssh client

I use both PuTTY and Bitvise SSH Client. PuTTY handles screen sessions better, but Bitvise automatically opens up a SFTP window so you can transfer files just like you would with an FTP client.

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I struggled with this as well and found a simple pattern to isolate the test context after a cursory read of the @ComponentScan docs.

/**
* Type-safe alternative to {@link #basePackages} for specifying the packages
* to scan for annotated components. The package of each class specified will be scanned.
* Consider creating a special no-op marker class or interface in each package
* that serves no purpose other than being referenced by this attribute.
*/
Class<?>[] basePackageClasses() default {};

  1. Create a package for your spring tests, ("com.example.test").
  2. Create a marker interface in the package as a context qualifier.
  3. Provide the marker interface reference as a parameter to basePackageClasses.

Example


IsolatedTest.java

package com.example.test;

@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan(basePackageClasses = {TestDomain.class})
@SpringApplicationConfiguration(classes = IsolatedTest.Config.class)
public class IsolatedTest {

     String expected = "Read the documentation on @ComponentScan";
     String actual = "Too lazy when I can just search on Stack Overflow.";

      @Test
      public void testSomething() throws Exception {
          assertEquals(expected, actual);
      }

      @ComponentScan(basePackageClasses = {TestDomain.class})
      public static class Config {
      public static void main(String[] args) {
          SpringApplication.run(Config.class, args);
      }
    }
}

...

TestDomain.java

package com.example.test;

public interface TestDomain {
//noop marker
}

Java 8 stream reverse order

Elegant solution

List<Integer> list = Arrays.asList(1,2,3,4);
list.stream()
    .boxed() // Converts Intstream to Stream<Integer>
    .sorted(Collections.reverseOrder()) // Method on Stream<Integer>
    .forEach(System.out::println);

In Maven how to exclude resources from the generated jar?

To exclude any file from a jar / target directory you can use the <excludes> tag in your pom.xml file.

In the next example, all files with .properties extension will not be included:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <excludes>
                <exclude>*.properties</exclude>
            </excludes>
            <filtering>false</filtering>
        </resource>
    </resources>
</build>

Catch browser's "zoom" event in JavaScript

I'm using this piece of JavaScript to react to Zoom "events".
It polls the window width. (As somewhat suggested on this page (which Ian Elliott linked to): http://novemberborn.net/javascript/page-zoom-ff3 [archive])

Tested with Chrome, Firefox 3.6 and Opera, not IE.

Regards, Magnus

var zoomListeners = [];

(function(){
  // Poll the pixel width of the window; invoke zoom listeners
  // if the width has been changed.
  var lastWidth = 0;
  function pollZoomFireEvent() {
    var widthNow = jQuery(window).width();
    if (lastWidth == widthNow) return;
    lastWidth = widthNow;
    // Length changed, user must have zoomed, invoke listeners.
    for (i = zoomListeners.length - 1; i >= 0; --i) {
      zoomListeners[i]();
    }
  }
  setInterval(pollZoomFireEvent, 100);
})();

What are DDL and DML?

DDL stands for Data Definition Language. DDL is used for defining structure of the table such as create a table or adding a column to table and even drop and truncate table. DML stands for Data Manipulation Language. As the name suggest DML used for manipulating the data of table. There are some commands in DML such as insert and delete.

How to find the number of days between two dates

DECLARE @Firstdate DATE='2016-04-01',
 @LastDate DATE=GETDATE(),/*get today date*/
 @resultDay int=null

SET @resultDay=(SELECT DATEDIFF(d, @Firstdate, @LastDate))
PRINT @resultDay

How do I format a number to a dollar amount in PHP

In php.ini add this (if it is missing):

#windows
extension=php_intl.dll

#linux
extension=php_intl.so

Then do this:

$amount = 123.456;

// for Canadian Dollars
$currency = 'CAD';

// for Canadian English
$locale = 'en_CA';

$fmt = new \NumberFormatter( $locale, \NumberFormatter::CURRENCY );
echo $fmt->formatCurrency($amount, $currency);

.htaccess mod_rewrite - how to exclude directory from rewrite rule

What you could also do is put a .htaccess file containing

RewriteEngine Off

In the folders you want to exclude from being rewritten (by the rules in a .htaccess file that's higher up in the tree). Simple but effective.

Deleting all files from a folder using PHP?

$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
    unlink($v);
}

replace all occurrences in a string

Use the global flag.

str.replace(/\n/g, '<br />');

What's the difference between a word and byte?

A group of 8 bits is called a byte ( with the exception where it is not :) for certain architectures )

A word is a fixed sized group of bits that are handled as a unit by the instruction set and/or hardware of the processor. That means the size of a general purpose register ( which is generally more than a byte ) is a word

In the C, a word is most often called an integer => int

How to fit a smooth curve to my data in R?

In order to get it REALLY smoooth...

x <- 1:10
y <- c(2,4,6,8,7,8,14,16,18,20)
lo <- loess(y~x)
plot(x,y)
xl <- seq(min(x),max(x), (max(x) - min(x))/1000)
lines(xl, predict(lo,xl), col='red', lwd=2)

This style interpolates lots of extra points and gets you a curve that is very smooth. It also appears to be the the approach that ggplot takes. If the standard level of smoothness is fine you can just use.

scatter.smooth(x, y)

SQL Server dynamic PIVOT query?

You can achieve this using dynamic TSQL (remember to use QUOTENAME to avoid SQL injection attacks):

Pivots with Dynamic Columns in SQL Server 2005

SQL Server - Dynamic PIVOT Table - SQL Injection

Obligatory reference to The Curse and Blessings of Dynamic SQL

How to make a radio button unchecked by clicking it?

Here's an example of where it is arguably appropriate to uncheck radio buttons other than by making a new selection. I have a dictionary whose entries can be selected using a variety of indices. Which index to use is selected by means of a set of radio buttons. However, there is also a "random entry" button that the user can use if he or she just wants to browse. Leaving an index in place when the entry has been selected by means of the random entry button would be misleading, so when this button is pressed, I uncheck all of the index selection radio buttons and replace the contents of the index frame with an empty page.

How to compare types

You can compare for exactly the same type using:

class A {
}
var a = new A();
var typeOfa = a.GetType();
if (typeOfa == typeof(A)) {
}

typeof returns the Type object from a given class.

But if you have a type B, that inherits from A, then this comparison is false. And you are looking for IsAssignableFrom.

class B : A {
}
var b = new B();
var typeOfb = b.GetType();

if (typeOfb == typeof(A)) { // false
}

if (typeof(A).IsAssignableFrom(typeOfb)) { // true
}

Does Java have an exponential operator?

To do this with user input:

public static void getPow(){
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter first integer: ");    // 3
    int first = sc.nextInt();
    System.out.println("Enter second integer: ");    // 2
    int second = sc.nextInt();
    System.out.println(first + " to the power of " + second + " is " + 
        (int) Math.pow(first, second));    // outputs 9

How to add Options Menu to Fragment in Android

If you need a menu to refresh a webview inside a specific Fragment, you can use:

Fragment:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    // TODO Add your menu entries here
    inflater.inflate(R.menu.menu, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.exit:
        System.exit(1);
        break;

    case R.id.refresh:
        webView.reload();
        break;
    }
    return true;

}

menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/exit" android:title="Exit" android:icon="@drawable/ic_action_cancel" />
    <item android:id="@+id/refresh" android:title="Refresh" android:icon="@drawable/ic_action_refresh" />
</menu>

javascript regex for special characters

a sleaker way to match special chars:

/\W|_/g

\W Matches any character that is not a word character (alphanumeric & underscore).

Underscore is considered a special character so add boolean to either match a special character or _

Calling a function in jQuery with click()

$("#closeLink").click(closeIt);

Let's say you want to call your function passing some args to it i.e., closeIt(1, false). Then, you should build an anonymous function and call closeIt from it.

$("#closeLink").click(function() {
    closeIt(1, false);
});