Programs & Examples On #Dijkstra

Dijkstra's algorithm, conceived by Dutch computer scientist Edsger Dijkstra is a graph search algorithm that solves the single-source shortest path problem for a connected graph with nonnegative edge path costs, producing a shortest path tree. This algorithm is often used in routing and as a subroutine in other graph algorithms.

Negative weights using Dijkstra's Algorithm

Note, that Dijkstra works even for negative weights, if the Graph has no negative cycles, i.e. cycles whose summed up weight is less than zero.

Of course one might ask, why in the example made by templatetypedef Dijkstra fails even though there are no negative cycles, infact not even cycles. That is because he is using another stop criterion, that holds the algorithm as soon as the target node is reached (or all nodes have been settled once, he did not specify that exactly). In a graph without negative weights this works fine.

If one is using the alternative stop criterion, which stops the algorithm when the priority-queue (heap) runs empty (this stop criterion was also used in the question), then dijkstra will find the correct distance even for graphs with negative weights but without negative cycles.

However, in this case, the asymptotic time bound of dijkstra for graphs without negative cycles is lost. This is because a previously settled node can be reinserted into the heap when a better distance is found due to negative weights. This property is called label correcting.

Why doesn't Dijkstra's algorithm work for negative weight edges?

Consider the graph shown below with the source as Vertex A. First try running Dijkstra’s algorithm yourself on it.

enter image description here

When I refer to Dijkstra’s algorithm in my explanation I will be talking about the Dijkstra's Algorithm as implemented below,

Dijkstra’s algorithm

So starting out the values (the distance from the source to the vertex) initially assigned to each vertex are,

initialization

We first extract the vertex in Q = [A,B,C] which has smallest value, i.e. A, after which Q = [B, C]. Note A has a directed edge to B and C, also both of them are in Q, therefore we update both of those values,

first iteration

Now we extract C as (2<5), now Q = [B]. Note that C is connected to nothing, so line16 loop doesn't run.

second iteration

Finally we extract B, after which Q is Phi. Note B has a directed edge to C but C isn't present in Q therefore we again don't enter the for loop in line16,

3rd?

So we end up with the distances as

no change guys

Note how this is wrong as the shortest distance from A to C is 5 + -10 = -5, when you go a to b to c.

So for this graph Dijkstra's Algorithm wrongly computes the distance from A to C.

This happens because Dijkstra's Algorithm does not try to find a shorter path to vertices which are already extracted from Q.

What the line16 loop is doing is taking the vertex u and saying "hey looks like we can go to v from source via u, is that (alt or alternative) distance any better than the current dist[v] we got? If so lets update dist[v]"

Note that in line16 they check all neighbors v (i.e. a directed edge exists from u to v), of u which are still in Q. In line14 they remove visited notes from Q. So if x is a visited neighbour of u, the path source to u to x is not even considered as a possible shorter way from source to v.

In our example above, C was a visited neighbour of B, thus the path A to B to C was not considered, leaving the current shortest path A to C unchanged.

This is actually useful if the edge weights are all positive numbers, because then we wouldn't waste our time considering paths that can't be shorter.

So I say that when running this algorithm if x is extracted from Q before y, then its not possible to find a path - not possible which is shorter. Let me explain this with an example,

As y has just been extracted and x had been extracted before itself, then dist[y] > dist[x] because otherwise y would have been extracted before x. (line 13 min distance first)

And as we already assumed that the edge weights are positive, i.e. length(x,y)>0. So the alternative distance (alt) via y is always sure to be greater, i.e. dist[y] + length(x,y)> dist[x]. So the value of dist[x] would not have been updated even if y was considered as a path to x, thus we conclude that it makes sense to only consider neighbors of y which are still in Q (note comment in line16)

But this thing hinges on our assumption of positive edge length, if length(u,v)<0 then depending on how negative that edge is we might replace the dist[x] after the comparison in line18.

So any dist[x] calculation we make will be incorrect if x is removed before all vertices v - such that x is a neighbour of v with negative edge connecting them - is removed.

Because each of those v vertices is the second last vertex on a potential "better" path from source to x, which is discarded by Dijkstra’s algorithm.

So in the example I gave above, the mistake was because C was removed before B was removed. While that C was a neighbour of B with a negative edge!

Just to clarify, B and C are A's neighbours. B has a single neighbour C and C has no neighbours. length(a,b) is the edge length between the vertices a and b.

How do I increase memory on Tomcat 7 when running as a Windows Service?

//ES/tomcat -> This may not work if you have changed the service name during the installation.

Either run the command without any service name

.\bin\tomcat7w.exe //ES

or with exact service name

.\bin\tomcat7w.exe //ES/YourServiceName

How can I divide one column of a data frame through another?

Hadley Wickham

dplyr

packages is always a saver in case of data wrangling. To add the desired division as a third variable I would use mutate()

d <- mutate(d, new = min / count2.freq)

Have bash script answer interactive prompts

A simple

echo "Y Y N N Y N Y Y N" | ./your_script

This allow you to pass any sequence of "Y" or "N" to your script.

Laravel 5 not finding css files

Simply you can put a back slash in front of your css link

I'm getting the "missing a using directive or assembly reference" and no clue what's going wrong

In some cases, when necessary using has been obviously added and studio can't see this namespace, studio restart can save the day.

Prevent overwriting a file using cmd if exist

Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:

If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"

What is the difference between a "function" and a "procedure"?

Procedures and functions are both subroutines the only difference between them is that a procedure returns multiple (or at least can do) values whereas a function can only return one value (this is why function notation is used in maths as usually only one value is found at one given time) although some programming languages do not follow these rules this is their true definitions

Error in plot.new() : figure margins too large in R

The problem is that the small figure region 2 created by your layout() call is not sufficiently large enough to contain just the default margins, let alone a plot.

More generally, you get this error if the size of the plotting region on the device is not large enough to actually do any plotting. For the OP's case the issue was having too small a plotting device to contain all the subplots and their margins and leave a large enough plotting region to draw in.

RStudio users can encounter this error if the Plot tab is too small to leave enough room to contain the margins, plotting region etc. This is because the physical size of that pane is the size of the graphics device. These are not independent issues; the plot pane in RStudio is just another plotting device, like png(), pdf(), windows(), and X11().

Solutions include:

  1. reducing the size of the margins; this might help especially if you are trying, as in the case of the OP, to draw several plots on the same device.

  2. increasing the physical dimensions of the device, either in the call to the device (e.g. png(), pdf(), etc) or by resizing the window / pane containing the device

  3. reducing the size of text on the plot as that can control the size of margins etc.

Reduce the size of the margins

Before the line causing the problem try:

par(mar = rep(2, 4))

then plot the second image

image(as.matrix(leg),col=cx,axes=T)

You'll need to play around with the size of the margins on the par() call I show to get this right.

Increase the size of the device

You may also need to increase the size of the actual device onto which you are plotting.

A final tip, save the par() defaults before changing them, so change your existing par() call to:

op <- par(oma=c(5,7,1,1))

then at the end of plotting do

par(op)

Insert all data of a datagridview to database at once

I think the best way is by using TableAdapters rather than using Commands objects, its Update method sends all changes mades (Updates,Inserts and Deletes) inside a Dataset or DataTable straight TO the database. Usually when using a DataGridView you bind to a BindingSource which lets you interact with a DataSource such as Datatables or Datasets.

If you work like this, then on your bounded DataGridView you can just do:

this.customersBindingSource.EndEdit();
this.myTableAdapter.Update(this.myDataSet.Customers);

The 'customersBindingSource' is the DataSource of the DataGridView.

The adapter's Update method will update a single data table and execute the correct command (INSERT, UPDATE, or DELETE) based on the RowState of each data row in the table.

From: https://msdn.microsoft.com/en-us/library/ms171933.aspx

So any changes made inside the DatagridView will be reflected on the Database when using the Update method.

More about TableAdapters: https://msdn.microsoft.com/en-us/library/bz9tthwx.aspx

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

Webpack is a bundler. Like Browserfy it looks in the codebase for module requests (require or import) and resolves them recursively. What is more, you can configure Webpack to resolve not just JavaScript-like modules, but CSS, images, HTML, literally everything. What especially makes me excited about Webpack, you can combine both compiled and dynamically loaded modules in the same app. Thus one get a real performance boost, especially over HTTP/1.x. How exactly you you do it I described with examples here http://dsheiko.com/weblog/state-of-javascript-modules-2017/ As an alternative for bundler one can think of Rollup.js (https://rollupjs.org/), which optimizes the code during compilation, but stripping all the found unused chunks.

For AMD, instead of RequireJS one can go with native ES2016 module system, but loaded with System.js (https://github.com/systemjs/systemjs)

Besides, I would point that npm is often used as an automating tool like grunt or gulp. Check out https://docs.npmjs.com/misc/scripts. I personally go now with npm scripts only avoiding other automation tools, though in past I was very much into grunt. With other tools you have to rely on countless plugins for packages, that often are not good written and not being actively maintained. npm knows its packages, so you call to any of locally installed packages by name like:

{
  "scripts": {
    "start": "npm http-server"
  },
  "devDependencies": {
    "http-server": "^0.10.0"
  }
}

Actually you as a rule do not need any plugin if the package supports CLI.

How to get Rails.logger printing to the console/stdout when running rspec?

You can define a method in spec_helper.rb that sends a message both to Rails.logger.info and to puts and use that for debugging:

def log_test(message)
    Rails.logger.info(message)
    puts message
end

Things possible in IntelliJ that aren't possible in Eclipse?

IntelliJ has intellisense and refactoring support from code into jspx documents.

Changing SVG image color with javascript

Your SVG must be inline in your document in order to be styled with CSS. This can be done by writing the SVG markup directly into your HTML code, or by using SVG injection, which replaces the img element with the content from and SVG file with Javascript.

There is an open source library called SVGInject that does this for you. All you have to do is to add the attribute onload="SVGInject(this)" to you <img> tag.

A simple example using SVGInject looks like this:

<html>
  <head>
    <script src="svg-inject.min.js"></script>
  </head>
  <body>
    <img src="image.svg" onload="SVGInject(this)" />
  </body>
</html>

After the image is loaded the onload="SVGInject(this) will trigger the injection and the <img> element will be replaced by the contents of the SVG file provided in the src attribute.

How to determine day of week by passing specific date?

public class TryDateFormats {
    public static void main(String[] args) throws ParseException {
        String month = "08";
        String day = "05";
        String year = "2015";
        String inputDateStr = String.format("%s/%s/%s", day, month, year);
        Date inputDate = new SimpleDateFormat("dd/MM/yyyy").parse(inputDateStr);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(inputDate);
        String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();
        System.out.println(dayOfWeek);
    }
}

how to read a text file using scanner in Java?

I would recommend loading the file as Resource and converting the input stream into string. This would give you the flexibility to load the file anywhere relative to the classpath

Add Insecure Registry to Docker

(Copying answer from question)

To add an insecure docker registry, add the file /etc/docker/daemon.json with the following content:

{
    "insecure-registries" : [ "hostname.cloudapp.net:5000" ]
}

and then restart docker.

How to put a Scanner input into an array... for example a couple of numbers

You can get all the doubles with this code:

List<Double> numbers = new ArrayList<Double>();
while (scan.hasNextDouble()) {
    numbers.add(scan.nextDouble());
}

Set value of input instead of sendKeys() - Selenium WebDriver nodejs

Try to set the element's value using the executeScript method of JavascriptExecutor:

WebDriver driver = new FirefoxDriver();
JavascriptExecutor jse = (JavascriptExecutor)driver;
jse.executeScript("document.getElementById('elementID').setAttribute('value', 'new value for element')");

How can I get the number of records affected by a stored procedure?

@@RowCount will give you the number of records affected by a SQL Statement.

The @@RowCount works only if you issue it immediately afterwards. So if you are trapping errors, you have to do it on the same line. If you split it up, you will miss out on whichever one you put second.

SELECT @NumRowsChanged = @@ROWCOUNT, @ErrorCode = @@ERROR

If you have multiple statements, you will have to capture the number of rows affected for each one and add them up.

SELECT @NumRowsChanged = @NumRowsChanged  + @@ROWCOUNT, @ErrorCode = @@ERROR

How to perform a fade animation on Activity transition?

you can also use this code in your style.xml file so you don't need to write anything else in your activity.java

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowAnimationStyle">@style/AppTheme.WindowTransition</item>
</style>

<!-- Setting window animation -->
<style name="AppTheme.WindowTransition">
    <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
    <item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>

CSS set li indent

padding-left is what controls the indentation of ul not margin-left.

Compare: Here's setting padding-left to 0, notice all the indentation disappears.

_x000D_
_x000D_
ul {
  padding-left: 0;
}
_x000D_
<ul>
  <li>section a
    <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
    </ul>
  </li>
</ul>
<ul>
  <li>section b
    <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
    </ul>
  </li>
</ul>
_x000D_
_x000D_
_x000D_

and here's setting margin-left to 0px. Notice the indentation does NOT change.

_x000D_
_x000D_
ul {
  margin-left: 0;
}
_x000D_
<ul>
  <li>section a
    <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
    </ul>
  </li>
</ul>
<ul>
  <li>section b
    <ul>
      <li>one</li>
      <li>two</li>
      <li>three</li>
    </ul>
  </li>
</ul>
_x000D_
_x000D_
_x000D_

Do you (really) write exception safe code?

EH is good, generally. But C++'s implementation is not very friendly as it's really hard to tell how good your exception catching coverage is. Java for instance makes this easy, the compiler will tend to fail if you don't handle possible exceptions .

SQL Server : converting varchar to INT

This question has got 91,000 views so perhaps many people are looking for a more generic solution to the issue in the title "error converting varchar to INT"

If you are on SQL Server 2012+ one way of handling this invalid data is to use TRY_CAST

SELECT TRY_CAST (userID AS INT)
FROM   audit 

On previous versions you could use

SELECT CASE
         WHEN ISNUMERIC(RTRIM(userID) + '.0e0') = 1
              AND LEN(userID) <= 11
           THEN CAST(userID AS INT)
       END
FROM   audit 

Both return NULL if the value cannot be cast.

In the specific case that you have in your question with known bad values I would use the following however.

CAST(REPLACE(userID COLLATE Latin1_General_Bin, CHAR(0),'') AS INT)

Trying to replace the null character is often problematic except if using a binary collation.

Error when creating a new text file with python?

This works just fine, but instead of

name = input('Enter name of text file: ')+'.txt' 

you should use

name = raw_input('Enter name of text file: ')+'.txt'

along with

open(name,'a') or open(name,'w')

Bulk Insertion in Laravel using eloquent ORM

From Laravel 5.7 with Illuminate\Database\Query\Builder you can use insertUsing method.

$query = [];
foreach($oXML->results->item->item as $oEntry){
    $date = date("Y-m-d H:i:s")
    $query[] = "('{$oEntry->firstname}', '{$oEntry->lastname}', '{$date}')";
}

Builder::insertUsing(['first_name', 'last_name', 'date_added'], implode(', ', $query));

move a virtual machine from one vCenter to another vCenter

Copying the VM files onto an external HDD and then bringing it in to the destination will take a lot longer and requires multiple steps. Using vCenter Converter Standalone Client will do everything for you and is much faster. No external HDD required. Not sure where you got the cloning part from. vCenter Converter Standalone Client is simply copying the VM files by importing and exporting from source to destination, shutdown the source VM, then register the VM at destination and power on. All in one step. Takes about 1 min to set that up vCenter Converter Standalone Client.

How to Find Item in Dictionary Collection?

It's possible to find the element in Dictionary collection by using ContainsKey or TryGetValue as follows:

class Program
{
    protected static Dictionary<string, string> _tags = new Dictionary<string,string>();

    static void Main(string[] args)
    {
        string strValue;

        _tags.Add("101", "C#");
        _tags.Add("102", "ASP.NET");

        if (_tags.ContainsKey("101"))
        {
            strValue = _tags["101"];
            Console.WriteLine(strValue);
        }

        if (_tags.TryGetValue("101", out strValue))
        {
            Console.WriteLine(strValue);
        }
    }
}

jQuery counter to count up to a target number

I ended up creating my own plugin. Here it is in case this helps anyone:

(function($) {
    $.fn.countTo = function(options) {
        // merge the default plugin settings with the custom options
        options = $.extend({}, $.fn.countTo.defaults, options || {});
        
        // how many times to update the value, and how much to increment the value on each update
        var loops = Math.ceil(options.speed / options.refreshInterval),
            increment = (options.to - options.from) / loops;
        
        return $(this).each(function() {
            var _this = this,
                loopCount = 0,
                value = options.from,
                interval = setInterval(updateTimer, options.refreshInterval);
            
            function updateTimer() {
                value += increment;
                loopCount++;
                $(_this).html(value.toFixed(options.decimals));
                
                if (typeof(options.onUpdate) == 'function') {
                    options.onUpdate.call(_this, value);
                }
                
                if (loopCount >= loops) {
                    clearInterval(interval);
                    value = options.to;
                    
                    if (typeof(options.onComplete) == 'function') {
                        options.onComplete.call(_this, value);
                    }
                }
            }
        });
    };
    
    $.fn.countTo.defaults = {
        from: 0,  // the number the element should start at
        to: 100,  // the number the element should end at
        speed: 1000,  // how long it should take to count between the target numbers
        refreshInterval: 100,  // how often the element should be updated
        decimals: 0,  // the number of decimal places to show
        onUpdate: null,  // callback method for every time the element is updated,
        onComplete: null,  // callback method for when the element finishes updating
    };
})(jQuery);

Here's some sample code of how to use it:

<script type="text/javascript"><!--
    jQuery(function($) {
        $('.timer').countTo({
            from: 50,
            to: 2500,
            speed: 1000,
            refreshInterval: 50,
            onComplete: function(value) {
                console.debug(this);
            }
        });
    });
//--></script>

<span class="timer"></span>

View the demo on JSFiddle: http://jsfiddle.net/YWn9t/

Problem in running .net framework 4.0 website on iis 7.0

Go to IIS manager and click on the server name. Then click on the "ISAPI and CGI Restrictions" icon under the IIS header. Change ASP.NET 4.0 from "Not Allowed" to "Allowed".

How can I delete Docker's images?

In Bash:

for i in `sudo docker images|grep \<none\>|awk '{print $3}'`;do sudo docker rmi $i;done

This will remove all images with name "<none>". I found those images redundant.

Cannot set content-type to 'application/json' in jQuery.ajax

I recognized those screens, I'm using CodeFluentEntities, and I've got solution that worked for me as well.

I'm using that construction:

$.ajax({
   url: path,
   type: "POST",
   contentType: "text/plain",
   data: {"some":"some"}
}

as you can see, if I use

contentType: "",

or

contentType: "text/plain", //chrome

Everything works fine.

I'm not 100% sure that it's all that you need, cause I've also changed headers.

Printing 2D array in matrix format

like so:

long[,] arr = new long[4, 4] { { 0, 0, 0, 0 }, { 1, 1, 1, 1 }, { 0, 0, 0, 0 }, { 1, 1, 1, 1 } };

var rowCount = arr.GetLength(0);
var colCount = arr.GetLength(1);
for (int row = 0; row < rowCount; row++)
{
    for (int col = 0; col < colCount; col++)               
        Console.Write(String.Format("{0}\t", arr[row,col]));
    Console.WriteLine();
} 

SQL Server® 2016, 2017 and 2019 Express full download

Download the developer edition. There you can choose Express as license when installing.

enter image description here

Add Favicon to Website

  1. This is not done in PHP. It's part of the <head> tags in a HTML page.
  2. That icon is called a favicon. According to Wikipedia:

    A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.

  3. Adding it is easy. Just add an .ico image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> to the <head> element.
  4. You can easily generate favicons here.

When to use "new" and when not to, in C++?

Take a look at this question and this question for some good answers on C++ object instantiation.

This basic idea is that objects instantiated on the heap (using new) need to be cleaned up manually, those instantiated on the stack (without new) are automatically cleaned up when they go out of scope.

void SomeFunc()
{
    Point p1 = Point(0,0);
} // p1 is automatically freed

void SomeFunc2()
{
    Point *p1 = new Point(0,0);
    delete p1; // p1 is leaked unless it gets deleted
}

How to deny access to a file in .htaccess

Place the below line in your .htaccess file and replace the file name as you wish

RewriteRule ^(test\.php) - [F,L,NC]

How do you clear the focus in javascript?

You can call window.focus();

but moving or losing the focus is bound to interfere with anyone using the tab key to get around the page.

you could listen for keycode 13, and forego the effect if the tab key is pressed.

Installed SSL certificate in certificate store, but it's not in IIS certificate list

had the same problem.

You need to ensure you are installing on the same server as the one you created the "CSR" file from. Otherwise, it won't have the private keys.

If you got your cert, just ask to re-key, it will ask for a new CSR file. I.e. Go Daddy allows you to re-key, just find the cert, and hit "manage"

I am not expert at this stuff, but this managed to work.

Bootstrap table striped: How do I change the stripe background colour?

.table-striped>tbody>tr:nth-child(odd)>td,
.table-striped>tbody>tr:nth-child(odd)>th {
  background-color: #e08283;
  color: white;
}
.table-striped>tbody>tr:nth-child(even)>td,
.table-striped>tbody>tr:nth-child(even)>th {
  background-color: #ECEFF1;
  color: white;
}

Use 'even' for change colour of even rows and use 'odd' for change colour of odd rows.

CSS no text wrap

Just use:

overflow: hidden;
white-space: nowrap;

In your item's divs

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

The best practice is selecting the most appropriate one.

.Net Framework 4.0 Beta 2 has a new IsNullOrWhiteSpace() method for strings which generalizes the IsNullOrEmpty() method to also include other white space besides empty string.

The term “white space” includes all characters that are not visible on screen. For example, space, line break, tab and empty string are white space characters*.

Reference : Here

For performance, IsNullOrWhiteSpace is not ideal but is good. The method calls will result in a small performance penalty. Further, the IsWhiteSpace method itself has some indirections that can be removed if you are not using Unicode data. As always, premature optimization may be evil, but it is also fun.

Reference : Here

Check the source code (Reference Source .NET Framework 4.6.2)

IsNullorEmpty

[Pure]
public static bool IsNullOrEmpty(String value) {
    return (value == null || value.Length == 0);
}

IsNullOrWhiteSpace

[Pure]
public static bool IsNullOrWhiteSpace(String value) {
    if (value == null) return true;

    for(int i = 0; i < value.Length; i++) {
        if(!Char.IsWhiteSpace(value[i])) return false;
    }

    return true;
}

Examples

string nullString = null;
string emptyString = "";
string whitespaceString = "    ";
string nonEmptyString = "abc123";

bool result;

result = String.IsNullOrEmpty(nullString);            // true
result = String.IsNullOrEmpty(emptyString);           // true
result = String.IsNullOrEmpty(whitespaceString);      // false
result = String.IsNullOrEmpty(nonEmptyString);        // false

result = String.IsNullOrWhiteSpace(nullString);       // true
result = String.IsNullOrWhiteSpace(emptyString);      // true
result = String.IsNullOrWhiteSpace(whitespaceString); // true
result = String.IsNullOrWhiteSpace(nonEmptyString);   // false

How to call function of one php file from another php file and pass parameters to it?

files directory:

Project->

-functions.php

-main.php

functions.php

function sum(a,b){
 return a+b;
}
function product(a,b){
return a*b;
}

main.php

require_once "functions.php";
echo "sum of two numbers ". sum(4,2);
echo "<br>"; //  create break line
echo "product of two numbers ".product(2,3);

The Output Is :

sum of two numbers 6 product of two numbers 6

Note: don't write public before function. Public, private, these modifiers can only use when you create class.

Redirect with CodeIgniter

If your directory structure is like this,

site
  application
         controller
                folder_1
                   first_controller.php
                   second_controller.php
                folder_2
                   first_controller.php
                   second_controller.php

And when you are going to redirect it in same controller in which you are working then just write the following code.

 $this->load->helper('url');
    if ($some_value === FALSE/TRUE) //You may give 0/1 as well,its up to your logic
    {
         redirect('same_controller/method', 'refresh');
    }

And if you want to redirect to another control then use the following code.

$this->load->helper('url');
if ($some_value === FALSE/TRUE) //You may give 0/1 as well,its up to your logic
{
     redirect('folder_name/any_controller_name/method', 'refresh');
}

How to tell which row number is clicked in a table?

This would get you the index of the clicked row, starting with one:

_x000D_
_x000D_
$('#thetable').find('tr').click( function(){_x000D_
alert('You clicked row '+ ($(this).index()+1) );_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table id="thetable">_x000D_
   <tr>_x000D_
      <td>1</td><td>1</td><td>1</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
      <td>2</td><td>2</td><td>2</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
      <td>3</td><td>3</td><td>3</td>_x000D_
   </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

If you want to return the number stored in that first cell of each row:

$('#thetable').find('tr').click( function(){
  var row = $(this).find('td:first').text();
  alert('You clicked ' + row);
});

.gitignore is ignored by Git

Mine wasn't working because I've literaly created a text document called .gitignore

Instead, create a text document, open it in Notepad++ then save as .gitignore

Make sure to pick All types (*.*) from the dropdown when you save it.


Or in gitbash, simply use touch .gitignore

Finish all previous activities

You may try Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK. It will totally clears all previous activity(s) and start new activity.

How does MySQL CASE work?

I wanted a simple example of the use of case that I could play with, this doesn't even need a table. This returns odd or even depending whether seconds is odd or even

SELECT CASE MOD(SECOND(NOW()),2) WHEN 0 THEN 'odd' WHEN 1 THEN 'even' END;

TypeScript static classes

Abstract classes have been a first-class citizen of TypeScript since TypeScript 1.6. You cannot instantiate an abstract class.

Here is an example:

export abstract class MyClass {         
    public static myProp = "Hello";

    public static doSomething(): string {
      return "World";
    }
}

const okay = MyClass.doSomething();

//const errors = new MyClass(); // Error

Passing html values into javascript functions

Give the textbox an id of "txtValue" and change the input button declaration to the following:

<input type="button" value="submit" onclick="verifyorder(document.getElementById('txtValue').value)" />

R - " missing value where TRUE/FALSE needed "

Can you change the if condition to this:

if (!is.na(comments[l])) print(comments[l]);

You can only check for NA values with is.na().

How to create .ipa file using Xcode?

In Xcode Version 10.0


  1. Go to Window -> Organizer
  2. Then select your app archive from archives
  3. Then click the "Distribute App" button on right panel

enter image description here

  1. Then follow the below steps

Step 1

enter image description here

Step 2

enter image description here

Step 3

enter image description here

Step 4

enter image description here

Step 5

enter image description here

Step 6 : Finally select the place you want to save the .ipa file

enter image description here

In Xcode Version 9.2


  1. Go to Window -> Organizer
  2. Then select your app archive from archives
  3. Then click the "Upload to App Store" button on right panel
  4. Then follow the following steps

Step 1 enter image description here

Step 2 enter image description here

Step 3 enter image description here

Step 4 Finally select the place you want to save the .ipa file

enter image description here

I can’t find the Android keytool

In fact, eclipse export will call

java -jar android-sdk-windows\tools\lib\sdklib.jar com.android.sdklib.build.ApkBuilderMain

and then call com.android.sdklib.internal.build.SignedJarBuilder.

RegEx: How can I match all numbers greater than 49?

I know there is already a good answer posted, but it won't allow leading zeros. And I don't have enough reputation to leave a comment, so... Here's my solution allowing leading zeros:

First I match the numbers 50 through 99 (with possible leading zeros):

0*[5-9]\d

Then match numbers of 100 and above (also with leading zeros):

0*[1-9]\d{2,}

Add them together with an "or" and wrap it up to match the whole sentence:

^0*([1-9]\d{2,}|[5-9]\d)$

That's it!

Expected linebreaks to be 'LF' but found 'CRLF' linebreak-style

If you are using vscode and you are on Windows i would recommend you to click the option at the bottom-right of the window and set it to LF from CRLF. Because we should not turn off the configuration just for sake of removing errors on Windows

If you don't see LF / CLRF, then right click the status bar and select Editor End of Line.

menu

Aborting a stash pop in Git

Use git reflog to list all changes made in your git history. Copy an action id and type git reset ACTION_ID

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

For other future users who do not want to make their controllers asynchronous, or cannot access the HttpContext, or are using dotnet core (this answer is the first I found on Google trying to do this), the following worked for me:

[HttpPut("{pathId}/{subPathId}"),
public IActionResult Put(int pathId, int subPathId, [FromBody] myViewModel viewModel)
{

    var body = new StreamReader(Request.Body);
    //The modelbinder has already read the stream and need to reset the stream index
    body.BaseStream.Seek(0, SeekOrigin.Begin); 
    var requestBody = body.ReadToEnd();
    //etc, we use this for an audit trail
}

How to grep with a list of words

To find a very long list of words in big files, it can be more efficient to use egrep:

remove the last \n of A
$ tr '\n' '|' < A > A_regex
$ egrep -f A_regex B

pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

My explanation/enquiry is for windows environment.
I am pretty new to python, and this is for someone still novice than me.
I installed the latest pip(python installer package) and downloaded 32 bit/64 bit (open source) compatible binaries from http://www.lfd.uci.edu/~gohlke/pythonlibs/, and it worked.

Steps followed to install pip, though usually pip is installed by default during python installation from www.python.org/downloads/
- Download pip-7.1.0.tar.gz from https://pypi.python.org/pypi/pip.
- Unzip and un-tar the above file.
- In the pip-7.1.0 folder, run: python setup.py install. This installed pip latest version.

Use pip to install(any feasible operation) binary package. Run the pip app to do the work(install file), as below:
\python27\scripts\pip2.7.exe install file_path\file_name --proxy
If you face, wheel(i.e egg) issue, use the compatible binary package file. Hope this helps.

How To Accept a File POST

The ASP.NET Core way is now here:

[HttpPost("UploadFiles")]
public async Task<IActionResult> Post(List<IFormFile> files)
{
    long size = files.Sum(f => f.Length);

    // full path to file in temp location
    var filePath = Path.GetTempFileName();

    foreach (var formFile in files)
    {
        if (formFile.Length > 0)
        {
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }
        }
    }

    // process uploaded files
    // Don't rely on or trust the FileName property without validation.

    return Ok(new { count = files.Count, size, filePath});
}

How to change an Android app's name?

Old question but also now relative to Xamarin Android development:

As Xamarin allows for attributes to be used for adding items into the manifest, you may need to open your MainActivity.cs file and change the Label tag to your application's name:

MainActivity

Note: This attribute will override written android:label= tags in your manifest file as I found out whilst archiving the app ready for release so be sure to change this attribute too.

Static Vs. Dynamic Binding in Java

All answers here are correct but i want to add something which is missing. when you are overriding a static method, it looks like we are overriding it but actually it is not method overriding. Instead it is called method hiding. Static methods cannot be overridden in Java.

Look at below example:

class Animal {
    static void eat() {
        System.out.println("animal is eating...");
    }
}

class Dog extends Animal {

    public static void main(String args[]) {

        Animal a = new Dog();
        a.eat(); // prints >> animal is eating...

    }

    static void eat() {
        System.out.println("dog is eating...");
    }
}

In dynamic binding, method is called depending on the type of reference and not the type of object that the reference variable is holding Here static bindinghappens because method hiding is not a dynamic polymorphism. If you remove static keyword in front of eat() and make it a non static method then it will show you dynamic polymorphism and not method-hiding.

i found the below link to support my answer: https://youtu.be/tNgZpn7AeP0

Add element to a list In Scala

I will try to explain the results of all the commands you tried.

scala> val l = 1.0 :: 5.5 :: Nil
l: List[Double] = List(1.0, 5.5)

First of all, List is a type alias to scala.collection.immutable.List (defined in Predef.scala).

Using the List companion object is more straightforward way to instantiate a List. Ex: List(1.0,5.5)

scala> l
res0: List[Double] = List(1.0, 5.5)

scala> l ::: List(2.2, 3.7)
res1: List[Double] = List(1.0, 5.5, 2.2, 3.7)

::: returns a list resulting from the concatenation of the given list prefix and this list

The original List is NOT modified

scala> List(l) :+ 2.2
res2: List[Any] = List(List(1.0, 5.5), 2.2)

List(l) is a List[List[Double]] Definitely not what you want.

:+ returns a new list consisting of all elements of this list followed by elem.

The type is List[Any] because it is the common superclass between List[Double] and Double

scala> l
res3: List[Double] = List(1.0, 5.5)

l is left unmodified because no method on immutable.List modified the List.

How to remove last n characters from every element in the R vector

The same may be achieved with the stringi package:

library('stringi')
char_array <- c("foo_bar","bar_foo","apple","beer")
a <- data.frame("data"=char_array, "data2"=1:4)
(a$data <- stri_sub(a$data, 1, -4)) # from the first to the last but 4th char
## [1] "foo_" "bar_" "ap"   "b" 

Bootstrap Columns Not Working

While this does not address the OP's question, I had trouble with my bootstrap rows / columns while trying to use them in conjunction with Kendo ListView (even with the bootstrap-kendo css).

Adding the following css fixed the problem for me:

#myListView.k-widget, #catalog-items.k-widget * {
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

Android, How can I Convert String to Date?

From String to Date

String dtStart = "2010-10-15T09:27:37Z";  
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = format.parse(dtStart);  
    System.out.println(date);  
} catch (ParseException e) {
    e.printStackTrace();  
}

From Date to String

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");  
try {  
    Date date = new Date();  
    String dateTime = dateFormat.format(date);
    System.out.println("Current Date Time : " + dateTime); 
} catch (ParseException e) {
    e.printStackTrace();  
}

How to Round to the nearest whole number in C#

You need Math.Round, not Math.Ceiling. Ceiling always "rounds" up, while Round rounds up or down depending on the value after the decimal point.

Convert timestamp in milliseconds to string formatted time in Java

long second = TimeUnit.MILLISECONDS.toSeconds(millis);
long minute = TimeUnit.MILLISECONDS.toMinutes(millis);
long hour = TimeUnit.MILLISECONDS.toHours(millis);
millis -= TimeUnit.SECONDS.toMillis(second);
return String.format("%02d:%02d:%02d:%d", hour, minute, second, millis);

querySelector and querySelectorAll vs getElementsByClassName and getElementById in JavaScript

querySelector and querySelectorAll are a relatively new APIs, whereas getElementById and getElementsByClassName have been with us for a lot longer. That means that what you use will mostly depend on which browsers you need to support.

As for the :, it has a special meaning so you have to escape it if you have to use it as a part of a ID/class name.

Export to csv in jQuery

I recently posted a free software library for this: "html5csv.js" -- GitHub

It is intended to help streamline the creation of small simulator apps in Javascript that might need to import or export csv files, manipulate, display, edit the data, perform various mathematical procedures like fitting, etc.

After loading "html5csv.js" the problem of scanning a table and creating a CSV is a one-liner:

CSV.begin('#PrintDiv').download('MyData.csv').go();

Here is a JSFiddle demo of your example with this code.

Internally, for Firefox/Chrome this is a data URL oriented solution, similar to that proposed by @italo, @lepe, and @adeneo (on another question). For IE

The CSV.begin() call sets up the system to read the data into an internal array. That fetch then occurs. Then the .download() generates a data URL link internally and clicks it with a link-clicker. This pushes a file to the end user.

According to caniuse IE10 doesn't support <a download=...>. So for IE my library calls navigator.msSaveBlob() internally, as suggested by @Manu Sharma

Adobe Reader Command Line Reference

Call this after the print job has returned:

oShell.AppActivate "Adobe Reader"
oShell.SendKeys "%FX"

How to crop an image using PIL?

There is a crop() method:

w, h = yourImage.size
yourImage.crop((0, 30, w, h-30)).save(...)

How can I simulate a click to an anchor tag?

well, you can very quickly test the click dispatch via jQuery like so

$('#link-id').click();

If you're still having problem with click respecting the target, you can always do this

$('#link-id').click( function( event, anchor )
{
  window.open( anchor.href, anchor.target, '' );
  event.preventDefault();
  return false;
});

Compiling C++ on remote Linux machine - "clock skew detected" warning

Replace the watch battery in your computer. I have seen this error message when the coin looking battery on the motherboard was in need of replacement.

SQL Server Insert Example

I hope this will help you

Create table :

create table users (id int,first_name varchar(10),last_name varchar(10));

Insert values into the table :

insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');

RegEx for matching UK Postcodes

I recently posted an answer to this question on UK postcodes for the R language. I discovered that the UK Government's regex pattern is incorrect and fails to properly validate some postcodes. Unfortunately, many of the answers here are based on this incorrect pattern.

I'll outline some of these issues below and provide a revised regular expression that actually works.


Note

My answer (and regular expressions in general):

  • Only validates postcode formats.
  • Does not ensure that a postcode legitimately exists.
    • For this, use an appropriate API! See Ben's answer for more info.

If you don't care about the bad regex and just want to skip to the answer, scroll down to the Answer section.

The Bad Regex

The regular expressions in this section should not be used.

This is the failing regex that the UK government has provided developers (not sure how long this link will be up, but you can see it in their Bulk Data Transfer documentation):

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$

Problems

Problem 1 - Copy/Paste

See regex in use here.

As many developers likely do, they copy/paste code (especially regular expressions) and paste them expecting them to work. While this is great in theory, it fails in this particular case because copy/pasting from this document actually changes one of the characters (a space) into a newline character as shown below:

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))
[0-9][A-Za-z]{2})$

The first thing most developers will do is just erase the newline without thinking twice. Now the regex won't match postcodes with spaces in them (other than the GIR 0AA postcode).

To fix this issue, the newline character should be replaced with the space character:

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$
                                                                                                                                                     ^

Problem 2 - Boundaries

See regex in use here.

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$
^^                     ^ ^                                                                                                                                            ^^

The postcode regex improperly anchors the regex. Anyone using this regex to validate postcodes might be surprised if a value like fooA11 1AA gets through. That's because they've anchored the start of the first option and the end of the second option (independently of one another), as pointed out in the regex above.

What this means is that ^ (asserts position at start of the line) only works on the first option ([Gg][Ii][Rr] 0[Aa]{2}), so the second option will validate any strings that end in a postcode (regardless of what comes before).

Similarly, the first option isn't anchored to the end of the line $, so GIR 0AAfoo is also accepted.

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z]))))[0-9][A-Za-z]{2})$

To fix this issue, both options should be wrapped in another group (or non-capturing group) and the anchors placed around that:

^(([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2}))$
^^                                                                                                                                                                      ^^

Problem 3 - Improper Character Set

See regex in use here.

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$
                                                                                       ^^

The regex is missing a - here to indicate a range of characters. As it stands, if a postcode is in the format ANA NAA (where A represents a letter and N represents a number), and it begins with anything other than A or Z, it will fail.

That means it will match A1A 1AA and Z1A 1AA, but not B1A 1AA.

To fix this issue, the character - should be placed between the A and Z in the respective character set:

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$
                                                                                        ^

Problem 4 - Wrong Optional Character Set

See regex in use here.

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$
                                                                                                                                        ^

I swear they didn't even test this thing before publicizing it on the web. They made the wrong character set optional. They made [0-9] option in the fourth sub-option of option 2 (group 9). This allows the regex to match incorrectly formatted postcodes like AAA 1AA.

To fix this issue, make the next character class optional instead (and subsequently make the set [0-9] match exactly once):

^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([AZa-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?)))) [0-9][A-Za-z]{2})$
                                                                                                                                                ^

Problem 5 - Performance

Performance on this regex is extremely poor. First off, they placed the least likely pattern option to match GIR 0AA at the beginning. How many users will likely have this postcode versus any other postcode; probably never? This means every time the regex is used, it must exhaust this option first before proceeding to the next option. To see how performance is impacted check the number of steps the original regex took (35) against the same regex after having flipped the options (22).

The second issue with performance is due to the way the entire regex is structured. There's no point backtracking over each option if one fails. The way the current regex is structured can greatly be simplified. I provide a fix for this in the Answer section.

Problem 6 - Spaces

See regex in use here

This may not be considered a problem, per se, but it does raise concern for most developers. The spaces in the regex are not optional, which means the users inputting their postcodes must place a space in the postcode. This is an easy fix by simply adding ? after the spaces to render them optional. See the Answer section for a fix.


Answer

1. Fixing the UK Government's Regex

Fixing all the issues outlined in the Problems section and simplifying the pattern yields the following, shorter, more concise pattern. We can also remove most of the groups since we're validating the postcode as a whole (not individual parts):

See regex in use here

^([A-Za-z][A-Ha-hJ-Yj-y]?[0-9][A-Za-z0-9]? ?[0-9][A-Za-z]{2}|[Gg][Ii][Rr] ?0[Aa]{2})$

This can further be shortened by removing all of the ranges from one of the cases (upper or lower case) and using a case-insensitive flag. Note: Some languages don't have one, so use the longer one above. Each language implements the case-insensitivity flag differently.

See regex in use here.

^([A-Z][A-HJ-Y]?[0-9][A-Z0-9]? ?[0-9][A-Z]{2}|GIR ?0A{2})$

Shorter again replacing [0-9] with \d (if your regex engine supports it):

See regex in use here.

^([A-Z][A-HJ-Y]?\d[A-Z\d]? ?\d[A-Z]{2}|GIR ?0A{2})$

2. Simplified Patterns

Without ensuring specific alphabetic characters, the following can be used (keep in mind the simplifications from 1. Fixing the UK Government's Regex have also been applied here):

See regex in use here.

^([A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}|GIR ?0A{2})$

And even further if you don't care about the special case GIR 0AA:

^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$

3. Complicated Patterns

I would not suggest over-verification of a postcode as new Areas, Districts and Sub-districts may appear at any point in time. What I will suggest potentially doing, is added support for edge-cases. Some special cases exist and are outlined in this Wikipedia article.

Here are complex regexes that include the subsections of 3. (3.1, 3.2, 3.3).

In relation to the patterns in 1. Fixing the UK Government's Regex:

See regex in use here

^(([A-Z][A-HJ-Y]?\d[A-Z\d]?|ASCN|STHL|TDCU|BBND|[BFS]IQQ|PCRN|TKCA) ?\d[A-Z]{2}|BFPO ?\d{1,4}|(KY\d|MSR|VG|AI)[ -]?\d{4}|[A-Z]{2} ?\d{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1)$

And in relation to 2. Simplified Patterns:

See regex in use here

^(([A-Z]{1,2}\d[A-Z\d]?|ASCN|STHL|TDCU|BBND|[BFS]IQQ|PCRN|TKCA) ?\d[A-Z]{2}|BFPO ?\d{1,4}|(KY\d|MSR|VG|AI)[ -]?\d{4}|[A-Z]{2} ?\d{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1)$

3.1 British Overseas Territories

The Wikipedia article currently states (some formats slightly simplified):

  • AI-1111: Anguila
  • ASCN 1ZZ: Ascension Island
  • STHL 1ZZ: Saint Helena
  • TDCU 1ZZ: Tristan da Cunha
  • BBND 1ZZ: British Indian Ocean Territory
  • BIQQ 1ZZ: British Antarctic Territory
  • FIQQ 1ZZ: Falkland Islands
  • GX11 1ZZ: Gibraltar
  • PCRN 1ZZ: Pitcairn Islands
  • SIQQ 1ZZ: South Georgia and the South Sandwich Islands
  • TKCA 1ZZ: Turks and Caicos Islands
  • BFPO 11: Akrotiri and Dhekelia
  • ZZ 11 & GE CX: Bermuda (according to this document)
  • KY1-1111: Cayman Islands (according to this document)
  • VG1111: British Virgin Islands (according to this document)
  • MSR 1111: Montserrat (according to this document)

An all-encompassing regex to match only the British Overseas Territories might look like this:

See regex in use here.

^((ASCN|STHL|TDCU|BBND|[BFS]IQQ|GX\d{2}|PCRN|TKCA) ?\d[A-Z]{2}|(KY\d|MSR|VG|AI)[ -]?\d{4}|(BFPO|[A-Z]{2}) ?\d{2}|GE ?CX)$

3.2 British Forces Post Office

Although they've been recently changed it to better align with the British postcode system to BF# (where # represents a number), they're considered optional alternative postcodes. These postcodes follow(ed) the format of BFPO, followed by 1-4 digits:

See regex in use here

^BFPO ?\d{1,4}$

3.3 Santa?

There's another special case with Santa (as mentioned in other answers): SAN TA1 is a valid postcode. A regex for this is very simply:

^SAN ?TA1$

Get Value of Row in Datatable c#

for (int i=0; i<dt_pattern.Rows.Count; i++)
{
    DataRow dr = dt_pattern.Rows[i];
}

In the loop, you can now reference row i+1 (assuming there is an i+1)

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

Invoke-Command error "Parameter set cannot be resolved using the specified named parameters"

I was solving same problem recently. I was designing a write cmdlet for my Subtitle module. I had six different user stories:

  • Subtitle only
  • Subtitle and path (original file name is used)
  • Subtitle and new file name (original path is used)
  • Subtitle and name suffix is used (original path and modified name is used).
  • Subtile, new path and new file name is is used.
  • Subtitle, new path and suffix is used.

I end up in the big frustration because I though that 4 parameters will be enough. Like most of the times, the frustration was pointless because it was my fault. I didn't know enough about parameter sets.

After some research in documentation, I realized where is the problem. With knowledge how the parameter sets should be used, I developed a general and simple approach how to solve this problem. A pencil and a sheet of paper is required but a spreadsheet editor is better:

  1. Write down all intended ways how the cmdlet should be used => user stories.
  2. Keep adding parameters with meaningful names and mark the use of the parameters until you have a unique collection set => no repetitive combination of parameters.
  3. Implement parameter sets into your code.
  4. Prepare tests for all possible user stories.
  5. Run tests (big surprise, right?). IDEs doesn't checks parameter sets collision, tests could save lots of trouble later one.

Example:

Unique parameter binding resolution approach.

The practical example could be seen over here.

BTW: The parameter uniqueness within parameter sets is the reason why the ParameterSetName property doesn't support [String[]]. It doesn't really make any sense.

How to Remove Array Element and Then Re-Index Array?

array_splice($array, array_search(array_value, $array), 1);

Equivalent of *Nix 'which' command in PowerShell?

If you want a comamnd that both accepts input from pipeline or as paramater, you should try this:

function which($name) {
    if ($name) { $input = $name }
    Get-Command $input | Select-Object -ExpandProperty Path
}

copy-paste the command to your profile (notepad $profile).

Examples:

? echo clang.exe | which
C:\Program Files\LLVM\bin\clang.exe

? which clang.exe
C:\Program Files\LLVM\bin\clang.exe

How can you print a variable name in python?

You can't, as there are no variables in Python but only names.

For example:

> a = [1,2,3]
> b = a
> a is b
True

Which of those two is now the correct variable? There's no difference between a and b.

There's been a similar question before.

How to remove white space characters from a string in SQL Server

There may be 2 spaces after the text, please confirm. You can use LTRIM and RTRIM functions also right?

LTRIM(RTRIM(ProductAlternateKey))

Maybe the extra space isn't ordinary spaces (ASCII 32, soft space)? Maybe they are "hard space", ASCII 160?

ltrim(rtrim(replace(ProductAlternateKey, char(160), char(32))))

Installing MySQL Python on Mac OS X

It's time to be a big boy and install from source. Try this:

1) Download the MySQL-python-1.X.X.tar.gz file(by default will go to your Downloads directory)

2) Open a Terminal window and cd to the Downloads directory.

3) Unzip the file you downloaded:

~/Downloads$ tar xfvz MySQL-python-1.X.X.tar.gz

That will create a directory inside your Downloads directory called MySQL-python

4) cd into the newly created directory.

5) Typically, you just open the file called README or INSTALL and follow the instructions--but generally to install a python module all you do is:

$ sudo python setup.py install

If you care to look, there should be a file called setup.py inside your newly created MySQL-python directory, and you are invoking that program to install the module.

Also note that this:

export PATH=$PATH:/usr/local/mysql/bin

is not permanent if you did that on the command line. You need to put that line in a file called .bashrc in your home directory (~/ or equivalently /Users/YOUR_USER_NAME). To see if .bashrc already exists(it's a hidden file), issue the command:

$ ls -al 

and look for .bashrc. If .bashrc doesn't exist, then create it.

What does ON [PRIMARY] mean?

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

How can I count all the lines of code in a directory recursively?

The tool Tokei displays statistics about code in a directory. Tokei will show the number of files, total lines within those files and code, comments, and blanks grouped by language. Tokei is also available on Mac, Linux, and Windows.

An example of the output of Tokei is as follows:

$ tokei
-------------------------------------------------------------------------------
 Language            Files        Lines         Code     Comments       Blanks
-------------------------------------------------------------------------------
 CSS                     2           12           12            0            0
 JavaScript              1          435          404            0           31
 JSON                    3          178          178            0            0
 Markdown                1            9            9            0            0
 Rust                   10          408          259           84           65
 TOML                    3           69           41           17           11
 YAML                    1           30           25            0            5
-------------------------------------------------------------------------------
 Total                  21         1141          928          101          112
-------------------------------------------------------------------------------

Tokei can be installed by following the instructions on the README file in the repository.

How to open a new form from another form

You could try adding a bool so the algorithm would know when the button was activated. When it's clicked, the bool checks true, the new form shows and the last gets closed.

It's important to know that forms consume some ram (at least a little bit), so it's a good idea to close those you're not gonna use, instead of just hiding it. Makes the difference in big projects.

Grouping into interval of 5 minutes within a time range

You should rather use GROUP BY UNIX_TIMESTAMP(time_stamp) DIV 300 instead of round(../300) because of the rounding I found that some records are counted into two grouped result sets.

Can RDP clients launch remote applications and not desktops

This is called RemoteApp. To use it you need to install Terminal Services, which is now called Remote Desktop Services.

https://social.technet.microsoft.com/wiki/contents/articles/10817.publishing-remoteapps-in-windows-server-2012.aspx

Regular expression to match standard 10 digit phone number

Adding up an example using above mentioned solutions on jsfiddle. I have modified the code a bit as per my clients requirement. Hope this also helps someone.

/^\s*(?:\+?(\d{1,3}))?[- (]*(\d{3})[- )]*(\d{3})[- ]*(\d{4})(?: *[x/#]{1}(\d+))?\s*$/

See Example Here

Windows.history.back() + location.reload() jquery

Try these ...

Option1

window.location=document.referrer;

Option2

window.location.reload(history.back());

This application has no explicit mapping for /error

this can happen if you forget the @RestController annotation on top of your controller class import import org.springframework.web.bind.annotation.RestController;

and add the annotation as below

refer the simple example below

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;


@RestController
public class HelloController {
@RequestMapping("/")
    public String index() {
        return "Greetings from Spring Boot!";
    }

}

How to convert unix timestamp to calendar date moment.js

Moment.js provides Localized formats which can be used.

Here is an example:

const moment = require('moment');

const timestamp = 1519482900000;
const formatted = moment(timestamp).format('L');

console.log(formatted); // "02/24/2018"

What is the path for the startup folder in windows 2008 server

In Server 2008 the startup folder for individual users is here:

C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

For All Users it's here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup

Hope that helps

How do I do logging in C# without using 3rd party libraries?

You can write directly to an event log. Check the following links:
http://support.microsoft.com/kb/307024
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx

And here's the sample from MSDN:

using System;
using System.Diagnostics;
using System.Threading;

class MySample{

    public static void Main(){

        // Create the source, if it does not already exist.
        if(!EventLog.SourceExists("MySource"))
        {
             //An event log source should not be created and immediately used.
             //There is a latency time to enable the source, it should be created
             //prior to executing the application that uses the source.
             //Execute this sample a second time to use the new source.
            EventLog.CreateEventSource("MySource", "MyNewLog");
            Console.WriteLine("CreatedEventSource");
            Console.WriteLine("Exiting, execute the application a second time to use the source.");
            // The source is created.  Exit the application to allow it to be registered.
            return;
        }

        // Create an EventLog instance and assign its source.
        EventLog myLog = new EventLog();
        myLog.Source = "MySource";

        // Write an informational entry to the event log.    
        myLog.WriteEntry("Writing to event log.");

    }
}

How do I view the SQLite database on an Android device?

Although this doesn't view the database on your device directly, I've published a simple shell script for dumping databases to your local machine:

https://github.com/Pixplicity/dbdump

It performs two distinct methods described here:

  1. First, it tries to make the file accessible for other users, and attempting to pull it from the device.
  2. If that fails, it streams the contents of the file over the terminal to the local machine. It performs an additional trick to remove \r characters that some devices output to the shell.

From here you can use a variety of CLI or GUI SQLite applications, such as sqlite3 or sqlitebrowser, to browse the contents of the database.

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

I fixed this problem today.

  • Change your output directory to your WEB-INF/classes folder. (Project/Properties/Java Build Path, Default output folder)
  • Assigne the module dependencies. (Project/Properties/Java EE Module Dependencies) they will be copied to the WEB-INF/lib folder where Eclipse looks for the tag lib definitions too.

I hope it helps.

Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

For ChromeDriver the below worked for me:

string chromeDriverDirectory = "C:\\temp\\2.37";
 var options = new ChromeOptions();
 options.AddArgument("-no-sandbox");
 driver = new ChromeDriver(chromeDriverDirectory, options, 
 TimeSpan.FromMinutes(2));

Selenium version 3.11, ChromeDriver 2.37

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

As already pointed out, b += 1 updates b in-place, while a = a + 1 computes a + 1 and then assigns the name a to the result (now a does not refer to a row of A anymore).

To understand the += operator properly though, we need also to understand the concept of mutable versus immutable objects. Consider what happens when we leave out the .reshape:

C = np.arange(12)
for c in C:
    c += 1
print(C)  # [ 0  1  2  3  4  5  6  7  8  9 10 11]

We see that C is not updated, meaning that c += 1 and c = c + 1 are equivalent. This is because now C is a 1D array (C.ndim == 1), and so when iterating over C, each integer element is pulled out and assigned to c.

Now in Python, integers are immutable, meaning that in-place updates are not allowed, effectively transforming c += 1 into c = c + 1, where c now refers to a new integer, not coupled to C in any way. When you loop over the reshaped arrays, whole rows (np.ndarray's) are assigned to b (and a) at a time, which are mutable objects, meaning that you are allowed to stick in new integers at will, which happens when you do a += 1.

It should be mentioned that though + and += are meant to be related as described above (and very much usually are), any type can implement them any way it wants by defining the __add__ and __iadd__ methods, respectively.

Pass multiple arguments into std::thread

You literally just pass them in std::thread(func1,a,b,c,d); that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate is called. You could std::join or std::detach it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach .

This is how it should be done.

std::thread t(func1,a,b,c,d);
t.join();  

You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.

Get device token for push notification

If you are still not getting device token, try putting following code so to register your device for push notification.

It will also work on ios8 or more.

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 80000

    if ([UIApplication respondsToSelector:@selector(registerUserNotificationSettings:)]) {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeAlert|UIUserNotificationTypeSound
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         UIRemoteNotificationTypeBadge |
         UIRemoteNotificationTypeAlert |
         UIRemoteNotificationTypeSound];

    }
#else
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     UIRemoteNotificationTypeBadge |
     UIRemoteNotificationTypeAlert |
     UIRemoteNotificationTypeSound];

#endif

What is "export default" in JavaScript?

export default function(){} can be used when the function doesn't have a name. There can only be one default export in a file. The alternative is a named export.

This page describes export default in detail as well as other details about modules that I found very helpful.

Convert .class to .java

I used the http://www.javadecompilers.com but in some classes it gives you the message "could not load this classes..."

INSTEAD download Android Studio, navigate to the folder containing the java class file and double click it. The code will show in the right pane and I guess you can copy it an save it as a java file from there

Kill process by name?

If you have to consider the Windows case in order to be cross-platform, then try the following:

os.system('taskkill /f /im exampleProcess.exe')

How to check for an empty object in an AngularJS view

please try this way with filter

angular.module('myApp')
    .filter('isEmpty', function () {
        var bar;
        return function (obj) {
            for (bar in obj) {
                if (obj.hasOwnProperty(bar)) {
                    return false;
                }
            }
            return true;
        };
    });

usage:

 <p ng-hide="items | isEmpty">Some Content</p>

Via from : Checking if object is empty, works with ng-show but not from controller?

How to read request body in an asp.net core webapi controller?

Writing an extension method is the most efficient way in my opinion

 public static string PeekBody(this HttpRequest request)
        {
            try
            {
                request.EnableBuffering();
                var buffer = new byte[Convert.ToInt32(request.ContentLength)];
                request.Body.Read(buffer, 0, buffer.Length);
                return Encoding.UTF8.GetString(buffer);
            }
            finally
            {
                request.Body.Position = 0;
            }
        }

You can use Request.Body.Peeker Nuget Package as well (source code)

//Return string
var request = HttpContext.Request.PeekBody();

//Return in expected type
LoginRequest request = HttpContext.Request.PeekBody<LoginRequest>();

//Return in expected type asynchronously
LoginRequest request = await HttpContext.Request.PeekBodyAsync<LoginRequest>();

Trying to fire the onload event on script tag

I faced a similar problem, trying to test if jQuery is already present on a page, and if not force it's load, and then execute a function. I tried with @David Hellsing workaround, but with no chance for my needs. In fact, the onload instruction was immediately evaluated, and then the $ usage inside this function was not yet possible (yes, the huggly "$ is not a function." ^^).

So, I referred to this article : https://developer.mozilla.org/fr/docs/Web/Events/load and attached a event listener to my script object.

var script = document.createElement('script');
script.type = "text/javascript";
script.addEventListener("load", function(event) {
    console.log("script loaded :)");
    onjqloaded();
});
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);

For my needs, it works fine now. Hope this can help others :)

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

http://en.wikipedia.org/wiki/Visual_C++

You are using Visual C++ 2012 which is v110. v120 means Visual C++ 2013.

So either you change the project settings to use toolset v110, or you install Visual Studio 2013 on this machine and use VS2013 to compile it.

Differences between C++ string == and compare()?

One thing that is not covered here is that it depends if we compare string to c string, c string to string or string to string.

A major difference is that for comparing two strings size equality is checked before doing the compare and that makes the == operator faster than a compare.

here is the compare as i see it on g++ Debian 7

// operator ==
  /**
   *  @brief  Test equivalence of two strings.
   *  @param __lhs  First string.
   *  @param __rhs  Second string.
   *  @return  True if @a __lhs.compare(@a __rhs) == 0.  False otherwise.
   */
  template<typename _CharT, typename _Traits, typename _Alloc>
    inline bool
    operator==(const basic_string<_CharT, _Traits, _Alloc>& __lhs,
           const basic_string<_CharT, _Traits, _Alloc>& __rhs)
    { return __lhs.compare(__rhs) == 0; }

  template<typename _CharT>
    inline
    typename __gnu_cxx::__enable_if<__is_char<_CharT>::__value, bool>::__type
    operator==(const basic_string<_CharT>& __lhs,
           const basic_string<_CharT>& __rhs)
    { return (__lhs.size() == __rhs.size()
          && !std::char_traits<_CharT>::compare(__lhs.data(), __rhs.data(),
                            __lhs.size())); }

  /**
   *  @brief  Test equivalence of C string and string.
   *  @param __lhs  C string.
   *  @param __rhs  String.
   *  @return  True if @a __rhs.compare(@a __lhs) == 0.  False otherwise.
   */
  template<typename _CharT, typename _Traits, typename _Alloc>
    inline bool
    operator==(const _CharT* __lhs,
           const basic_string<_CharT, _Traits, _Alloc>& __rhs)
    { return __rhs.compare(__lhs) == 0; }

  /**
   *  @brief  Test equivalence of string and C string.
   *  @param __lhs  String.
   *  @param __rhs  C string.
   *  @return  True if @a __lhs.compare(@a __rhs) == 0.  False otherwise.
   */
  template<typename _CharT, typename _Traits, typename _Alloc>
    inline bool
    operator==(const basic_string<_CharT, _Traits, _Alloc>& __lhs,
           const _CharT* __rhs)
    { return __lhs.compare(__rhs) == 0; }

Node.js check if path is file or directory

Here's a function that I use. Nobody is making use of promisify and await/async feature in this post so I thought I would share.

const promisify = require('util').promisify;
const lstat = promisify(require('fs').lstat);

async function isDirectory (path) {
  try {
    return (await lstat(path)).isDirectory();
  }
  catch (e) {
    return false;
  }
}

Note : I don't use require('fs').promises; because it has been experimental for one year now, better not rely on it.

Reference — What does this symbol mean in PHP?

Spaceship Operator <=> (Added in PHP 7)

Examples for <=> Spaceship operator (PHP 7, Source: PHP Manual):

Integers, Floats, Strings, Arrays & objects for Three-way comparison of variables.

// Integers
echo 10 <=> 10; // 0
echo 10 <=> 20; // -1
echo 20 <=> 10; // 1

// Floats
echo 1.5 <=> 1.5; // 0
echo 1.5 <=> 2.5; // -1
echo 2.5 <=> 1.5; // 1

// Strings
echo "a" <=> "a"; // 0
echo "a" <=> "b"; // -1
echo "b" <=> "a"; // 1
// Comparison is case-sensitive
echo "B" <=> "a"; // -1

echo "a" <=> "aa"; // -1
echo "zz" <=> "aa"; // 1

// Arrays
echo [] <=> []; // 0
echo [1, 2, 3] <=> [1, 2, 3]; // 0
echo [1, 2, 3] <=> []; // 1
echo [1, 2, 3] <=> [1, 2, 1]; // 1
echo [1, 2, 3] <=> [1, 2, 4]; // -1

// Objects
$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "b"]; 
echo $a <=> $b; // 0

$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "c"]; 
echo $a <=> $b; // -1

$a = (object) ["a" => "c"]; 
$b = (object) ["a" => "b"]; 
echo $a <=> $b; // 1

// only values are compared
$a = (object) ["a" => "b"]; 
$b = (object) ["b" => "b"]; 
echo $a <=> $b; // 1

How to compress an image via Javascript in the browser?

For JPG Image compression you can use the best compression technique called JIC (Javascript Image Compression)This will definitely help you -->https://github.com/brunobar79/J-I-C

Why can't I display a pound (£) symbol in HTML?

Or for other code equivalents try:

&#163;
&pound;

How to open the command prompt and insert commands using Java?

You can use any on process for dynamic path on command prompt

Process p = Runtime.getRuntime().exec("cmd.exe /c start dir ");
Process p = Runtime.getRuntime().exec("cmd.exe /c start cd \"E:\\rakhee\\Obligation Extractions\" && dir");
Process p = Runtime.getRuntime().exec("cmd.exe /c start cd \"E:\\oxyzen-workspace\\BrightleafDesktop\\Obligation Extractions\" && dir");

Working Copy Locked

To anyone still having this issue (Error: Working copy '{DIR}' locked.), I have your solution:

I found that when one of TortoiseSVN windows crash, it leaves a TSVNCache.exe that still has a few handles to your working copy and that is causing the Lock issues you are seeing (and also prevents Clean Up from doing it's job).

So to resolve this:

Either

1a) Use Process Explorer or similar to delete the handles owned by TSVNCache.exe

1b) ..Or even easier, just use Task Manager to kill TSVNCache.exe

Then

2) Right click -> TortoiseSVN -> Clean up. Only "Clean up working copy status" needs to be checked.

From there, happy updating/committing. You can reproduce Lock behavior by doing SVN Update and then quickly killing it's TortoiseProc.exe process before Update finishes.

How to include *.so library in Android Studio?

Solution 1 : Creation of a JniLibs folder

Create a folder called “jniLibs” into your app and the folders containing your *.so inside. The "jniLibs" folder needs to be created in the same folder as your "Java" or "Assets" folders.

Solution 2 : Modification of the build.gradle file

If you don’t want to create a new folder and keep your *.so files into the libs folder, it is possible !

In that case, just add your *.so files into the libs folder (please respect the same architecture as the solution 1 : libs/armeabi/.so for instance) and modify the build.gradle file of your app to add the source directory of the jniLibs.

sourceSets {
    main {
        jniLibs.srcDirs = ["libs"]
    }
}

You will have more explanations, with screenshots to help you here ( Step 6 ):

http://blog.guillaumeagis.eu/setup-andengine-with-android-studio/

EDIT It had to be jniLibs.srcDirs, not jni.srcDirs - edited the code. The directory can be a [relative] path that points outside of the project directory.

Custom height Bootstrap's navbar

For Bootstrap 4, there are now spacing utilities so it's easier to change the height via padding on the nav links. This can be responsively applied only at specific breakpoints (ie: py-md-3). For example, on larger (md) screens, this nav is 120px high, then shrinks to normal height for the mobile menu. No extra CSS is needed..

<nav class="navbar navbar-fixed-top navbar-inverse bg-primary navbar-toggleable-md py-md-3">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNav" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
    </button>
    <a class="navbar-brand" href="#">Brand</a>
    <div class="navbar-collapse collapse" id="navbarNav">
        <ul class="navbar-nav">
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Home</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Link</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Link</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">More</a></li>
            <li class="nav-item py-md-3"><a href="#" class="nav-link">Options</a></li>
        </ul>
    </div>
</nav>

Bootstrap 4 Navbar Height Demo

JavaScript ES6 promise for loop

Based on the excellent answer by trincot, I wrote a reusable function that accepts a handler to run over each item in an array. The function itself returns a promise that allows you to wait until the loop has finished and the handler function that you pass may also return a promise.

loop(items, handler) : Promise

It took me some time to get it right, but I believe the following code will be usable in a lot of promise-looping situations.

Copy-paste ready code:

// SEE https://stackoverflow.com/a/46295049/286685
const loop = (arr, fn, busy, err, i=0) => {
  const body = (ok,er) => {
    try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}
    catch(e) {er(e)}
  }
  const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)
  const run  = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()
  return busy ? run(busy,err) : new Promise(run)
}

Usage

To use it, call it with the array to loop over as the first argument and the handler function as the second. Do not pass parameters for the third, fourth and fifth arguments, they are used internally.

_x000D_
_x000D_
const loop = (arr, fn, busy, err, i=0) => {_x000D_
  const body = (ok,er) => {_x000D_
    try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
    catch(e) {er(e)}_x000D_
  }_x000D_
  const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
  const run  = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
  return busy ? run(busy,err) : new Promise(run)_x000D_
}_x000D_
_x000D_
const items = ['one', 'two', 'three']_x000D_
_x000D_
loop(items, item => {_x000D_
  console.info(item)_x000D_
})_x000D_
.then(() => console.info('Done!'))
_x000D_
_x000D_
_x000D_

Advanced use cases

Let's look at the handler function, nested loops and error handling.

handler(current, index, all)

The handler gets passed 3 arguments. The current item, the index of the current item and the complete array being looped over. If the handler function needs to do async work, it can return a promise and the loop function will wait for the promise to resolve before starting the next iteration. You can nest loop invocations and all works as expected.

_x000D_
_x000D_
const loop = (arr, fn, busy, err, i=0) => {_x000D_
  const body = (ok,er) => {_x000D_
    try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
    catch(e) {er(e)}_x000D_
  }_x000D_
  const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
  const run  = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
  return busy ? run(busy,err) : new Promise(run)_x000D_
}_x000D_
_x000D_
const tests = [_x000D_
  [],_x000D_
  ['one', 'two'],_x000D_
  ['A', 'B', 'C']_x000D_
]_x000D_
_x000D_
loop(tests, (test, idx, all) => new Promise((testNext, testFailed) => {_x000D_
  console.info('Performing test ' + idx)_x000D_
  return loop(test, (testCase) => {_x000D_
    console.info(testCase)_x000D_
  })_x000D_
  .then(testNext)_x000D_
  .catch(testFailed)_x000D_
}))_x000D_
.then(() => console.info('All tests done'))
_x000D_
_x000D_
_x000D_

Error handling

Many promise-looping examples I looked at break down when an exception occurs. Getting this function to do the right thing was pretty tricky, but as far as I can tell it is working now. Make sure to add a catch handler to any inner loops and invoke the rejection function when it happens. E.g.:

_x000D_
_x000D_
const loop = (arr, fn, busy, err, i=0) => {_x000D_
  const body = (ok,er) => {_x000D_
    try {const r = fn(arr[i], i, arr); r && r.then ? r.then(ok).catch(er) : ok(r)}_x000D_
    catch(e) {er(e)}_x000D_
  }_x000D_
  const next = (ok,er) => () => loop(arr, fn, ok, er, ++i)_x000D_
  const run  = (ok,er) => i < arr.length ? new Promise(body).then(next(ok,er)).catch(er) : ok()_x000D_
  return busy ? run(busy,err) : new Promise(run)_x000D_
}_x000D_
_x000D_
const tests = [_x000D_
  [],_x000D_
  ['one', 'two'],_x000D_
  ['A', 'B', 'C']_x000D_
]_x000D_
_x000D_
loop(tests, (test, idx, all) => new Promise((testNext, testFailed) => {_x000D_
  console.info('Performing test ' + idx)_x000D_
  loop(test, (testCase) => {_x000D_
    if (idx == 2) throw new Error()_x000D_
    console.info(testCase)_x000D_
  })_x000D_
  .then(testNext)_x000D_
  .catch(testFailed)  //  <--- DON'T FORGET!!_x000D_
}))_x000D_
.then(() => console.error('Oops, test should have failed'))_x000D_
.catch(e => console.info('Succesfully caught error: ', e))_x000D_
.then(() => console.info('All tests done'))
_x000D_
_x000D_
_x000D_

UPDATE: NPM package

Since writing this answer, I turned the above code in an NPM package.

for-async

Install

npm install --save for-async

Import

var forAsync = require('for-async');  // Common JS, or
import forAsync from 'for-async';

Usage (async)

var arr = ['some', 'cool', 'array'];
forAsync(arr, function(item, idx){
  return new Promise(function(resolve){
    setTimeout(function(){
      console.info(item, idx);
      // Logs 3 lines: `some 0`, `cool 1`, `array 2`
      resolve(); // <-- signals that this iteration is complete
    }, 25); // delay 25 ms to make async
  })
})

See the package readme for more details.

HTTPS setup in Amazon EC2

You can also use Amazon API Gateway. Put your application behind API Gateway. Please check this FAQ

if else in a list comprehension

Make a list from items in an iterable

It seems best to first generalize all the possible forms rather than giving specific answers to questions. Otherwise, the reader won't know how the answer was determined. Here are a few generalized forms I thought up before I got a headache trying to decide if a final else' clause could be used in the last form.

[expression1(item)                                        for item in iterable]

[expression1(item) if conditional1                        for item in iterable]

[expression1(item) if conditional1 else expression2(item) for item in iterable]

[expression1(item) if conditional1 else expression2(item) for item in iterable if conditional2]

The value of item doesn't need to be used in any of the conditional clauses. A conditional3 can be used as a switch to either add or not add a value to the output list.

For example, to create a new list that eliminates empty strings or whitespace strings from the original list of strings:

newlist = [s for s in firstlist if s.strip()]

Order a MySQL table by two columns

ORDER BY article_rating ASC , article_time DESC

DESC at the end will sort by both columns descending. You have to specify ASC if you want it otherwise

Sublime Text 2 multiple line edit

I was facing the same problem on Linux, what I did was to select all the content (ctrl-A) and then press ctrl+shift+L, It gives you a cursor on each line and then you can add similar content to each column.

Also you can perform other operations like cut, copy and paste column wise.

PS :- If you want to select a rectangular set of data from text, you can also press shift and hold Right Mouse button and then select data in a rectangular fashion. Then press CTRL+SHIFT+L to get the cursor on each line.

How does facebook, gmail send the real time notification?

Update

As I continue to recieve upvotes on this, I think it is reasonable to remember that this answer is 4 years old. Web has grown in a really fast pace, so please be mindful about this answer.


I had the same issue recently and researched about the subject.

The solution given is called long polling, and to correctly use it you must be sure that your AJAX request has a "large" timeout and to always make this request after the current ends (timeout, error or success).

Long Polling - Client

Here, to keep code short, I will use jQuery:

function pollTask() { 

    $.ajax({

        url: '/api/Polling',
        async: true,            // by default, it's async, but...
        dataType: 'json',       // or the dataType you are working with
        timeout: 10000,          // IMPORTANT! this is a 10 seconds timeout
        cache: false

    }).done(function (eventList) {  

       // Handle your data here
       var data;
       for (var eventName in eventList) {

            data = eventList[eventName];
            dispatcher.handle(eventName, data); // handle the `eventName` with `data`

       }

    }).always(pollTask);

}

It is important to remember that (from jQuery docs):

In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period.

Long Polling - Server

It is not in any specific language, but it would be something like this:

function handleRequest () {  

     while (!anythingHappened() || hasTimedOut()) { sleep(2); }

     return events();

} 

Here, hasTimedOut will make sure your code does not wait forever, and anythingHappened, will check if any event happend. The sleep is for releasing your thread to do other stuff while nothing happens. The events will return a dictionary of events (or any other data structure you may prefer) in JSON format (or any other you prefer).

It surely solves the problem, but, if you are concerned about scalability and perfomance as I was when researching, you might consider another solution I found.

Solution

Use sockets!

On client side, to avoid any compatibility issues, use socket.io. It tries to use socket directly, and have fallbacks to other solutions when sockets are not available.

On server side, create a server using NodeJS (example here). The client will subscribe to this channel (observer) created with the server. Whenever a notification has to be sent, it is published in this channel and the subscriptor (client) gets notified.

If you don't like this solution, try APE (Ajax Push Engine).

Hope I helped.

What is this Javascript "require"?

Alright, so let's first start with making the distinction between Javascript in a web browser, and Javascript on a server (CommonJS and Node).

Javascript is a language traditionally confined to a web browser with a limited global context defined mostly by what came to be known as the Document Object Model (DOM) level 0 (the Netscape Navigator Javascript API).

Server-side Javascript eliminates that restriction and allows Javascript to call into various pieces of native code (like the Postgres library) and open sockets.

Now require() is a special function call defined as part of the CommonJS spec. In node, it resolves libraries and modules in the Node search path, now usually defined as node_modules in the same directory (or the directory of the invoked javascript file) or the system-wide search path.

To try to answer the rest of your question, we need to use a proxy between the code running in the the browser and the database server.

Since we are discussing Node and you are already familiar with how to run a query from there, it would make sense to use Node as that proxy.

As a simple example, we're going to make a URL that returns a few facts about a Beatle, given a name, as JSON.

/* your connection code */

var express = require('express');
var app = express.createServer();
app.get('/beatles/:name', function(req, res) {
    var name = req.params.name || '';
    name = name.replace(/[^a-zA_Z]/, '');
    if (!name.length) {
        res.send({});
    } else {
        var query = client.query('SELECT * FROM BEATLES WHERE name =\''+name+'\' LIMIT 1');
        var data = {};
        query.on('row', function(row) {
            data = row;
            res.send(data);
        });
    };
});
app.listen(80, '127.0.0.1');

How to Convert datetime value to yyyymmddhhmmss in SQL server?

This seems to work:

declare @d datetime
set @d = '2014-04-17 13:55:12'

select replace(convert(varchar(8), @d, 112)+convert(varchar(8), @d, 114), ':','') 

Result:

20140417135512

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

Changing width property of a :before css selector using JQuery

One option is to use an attribute on the image, and modify that using jQuery. Then take that value in CSS:

HTML (note I'm assuming .cloumn is a div but it could be anything):

<div class="column" bf-width=100 >
    <img src="..." />
</div>

jQuery:

// General use:
$('.column').attr('bf-width', 100);
// With your image, along the lines of:
$('.column').attr('bf-width', $('img').width());

And then in order to use that value in CSS:

.column:before {
    content: attr(data-content) 'px';
    /* ... */
}

This will grab the attribute value from .column, and apply it on the before.

Sources: CSS attr (note the examples with before), jQuery attr.

How to replicate background-attachment fixed on iOS

It looks to me like the background images aren't actually background images...the site has the background images and the quotes in sibling divs with the children of the div containing the images having been assigned position: fixed; The quotes div is also given a transparent background.

wrapper div{
   image wrapper div{
       div for individual image{ <--- Fixed position
          image <--- relative position
       }
   }
   quote wrapper div{
       div for individual quote{
          quote
       }
   }
 }

XSLT - How to select XML Attribute by Attribute?

I would do it by creating a variable that points to the nodes that have the proper value in Value1 then referring to t

<xsl:variable name="myVarANode" select="root//DataSet/Data[@Value1='2']" />
<xsl:value-of select="$myVarANode/@Value2"/>

Everyone else's answers are right too - more right in fact since I didn't notice the extra slash in your XPATH that would mess things up. Still, this will also work , and might work for different things, so keep this method in your toolbox.

Easiest way to convert month name to month number in JS ? (Jan = 01)

Just for fun I did this:

function getMonthFromString(mon){
   return new Date(Date.parse(mon +" 1, 2012")).getMonth()+1
}

Bonus: it also supports full month names :-D Or the new improved version that simply returns -1 - change it to throw the exception if you want (instead of returning -1):

function getMonthFromString(mon){

   var d = Date.parse(mon + "1, 2012");
   if(!isNaN(d)){
      return new Date(d).getMonth() + 1;
   }
   return -1;
 }

Sry for all the edits - getting ahead of myself

How to insert a newline in front of a pattern?

In sed, you can't add newlines in the output stream easily. You need to use a continuation line, which is awkward, but it works:

$ sed 's/regexp/\
&/'

Example:

$ echo foo | sed 's/.*/\
&/'

foo

See here for details. If you want something slightly less awkward you could try using perl -pe with match groups instead of sed:

$ echo foo | perl -pe 's/(.*)/\n$1/'

foo

$1 refers to the first matched group in the regular expression, where groups are in parentheses.

How to move child element from one parent to another using jQuery

Based on the answers provided, I decided to make a quick plugin to do this:

(function($){
    $.fn.moveTo = function(selector){
        return this.each(function(){
            var cl = $(this).clone();
            $(cl).appendTo(selector);
            $(this).remove();
        });
    };
})(jQuery);

Usage:

$('#nodeToMove').moveTo('#newParent');

Step out of current function with GDB

You can use the finish command.

finish: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated as fin.

(See 5.2 Continuing and Stepping.)

How to get file path from OpenFileDialog and FolderBrowserDialog?

Your choofdlog holds a FileName and FileNames (for multi-selection) containing the file paths, after the ShowDialog() returns.

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

In case it helps anyone I will post what worked for me.

I had to plug my S3 into a direct USB port of my PC for it to prompt me to accept the RSA signature. I had my S3 plugged into a hub before then.

Now the S3 is detected when using both the direct USB port of the PC and via the hub.

NOTE - You may need to also run adb devices from the command line to get your S3 to re-request permission.

D:\apps\android-sdk-windows\platform-tools>adb devices
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
9283759342847566        unauthorized

...accept signature on phone...

D:\apps\android-sdk-windows\platform-tools>adb devices
List of devices attached
9283759342847566        device

Javascript String to int conversion

If you are sure id.substring(indexPos) is a number, you can do it like so:

var number = Number(id.substring(indexPos)) + 1;

Otherwise I suggest checking if the Number function evaluates correctly.

Postgres ERROR: could not open file for reading: Permission denied

I had the issue when I was trying to export data from a remote server into the local disk. I hadn't realised that SQL copy actually is executed on the server and that it tries to write to a server folder. Instead the correct thing to do was to use \copy which is the psql command and it writes to the local file system as I expected. http://www.postgresql.org/message-id/CAFjNrYsE4Za_KWzmfgN1_-MG7GTw_vpMRxPk=OEjAiLqLskxdA@mail.gmail.com

Perhaps that might be useful to someone else too.

Which is the fastest algorithm to find prime numbers?

I will let you decide if it's the fastest or not.

using System;
namespace PrimeNumbers
{

public static class Program
{
    static int primesCount = 0;


    public static void Main()
    {
        DateTime startingTime = DateTime.Now;

        RangePrime(1,1000000);   

        DateTime endingTime = DateTime.Now;

        TimeSpan span = endingTime - startingTime;

        Console.WriteLine("span = {0}", span.TotalSeconds);

    }


    public static void RangePrime(int start, int end)
    {
        for (int i = start; i != end+1; i++)
        {
            bool isPrime = IsPrime(i);
            if(isPrime)
            {
                primesCount++;
                Console.WriteLine("number = {0}", i);
            }
        }
        Console.WriteLine("primes count = {0}",primesCount);
    }



    public static bool IsPrime(int ToCheck)
    {

        if (ToCheck == 2) return true;
        if (ToCheck < 2) return false;


        if (IsOdd(ToCheck))
        {
            for (int i = 3; i <= (ToCheck / 3); i += 2)
            {
                if (ToCheck % i == 0) return false;
            }
            return true;
        }
        else return false; // even numbers(excluding 2) are composite
    }

    public static bool IsOdd(int ToCheck)
    {
        return ((ToCheck % 2 != 0) ? true : false);
    }
}
}

It takes approximately 82 seconds to find and print prime numbers within a range of 1 to 1,000,000, on my Core 2 Duo laptop with a 2.40 GHz processor. And it found 78,498 prime numbers.

Are there any naming convention guidelines for REST APIs?

I don't think the camel case is the issue in that example, but I imagine a more RESTful naming convention for the above example would be:

api.service.com/helloWorld/userId/x

rather then making userId a query parameter (which is perfectly legal) my example denotes that resource in, IMO, a more RESTful way.

How to remove Firefox's dotted outline on BUTTONS as well as links?

This works on firefox v-27.0

 .buttonClassName:focus {
  outline:none;
}

Should MySQL have its timezone set to UTC?

This is a working example:

jdbc:mysql://localhost:3306/database?useUnicode=yes&characterEncoding=UTF-8&serverTimezone=Europe/Moscow

Converting from Integer, to BigInteger

The method you want is BigInteger#valueOf(long val).

E.g.,

BigInteger bi = BigInteger.valueOf(myInteger.intValue());

Making a String first is unnecessary and undesired.

Change image size via parent div

Apply 100% width and height to your image:

<div style="height:42px;width:42px">
  <img src="http://someimage.jpg" style="width:100%; height:100%">
</div>

This way it will same size of its parent.

Show loading image while $.ajax is performed

You can add ajax start and complete event, this is work for when you click on button event

 $(document).bind("ajaxSend", function () {
            $(":button").html('<i class="fa fa-spinner fa-spin"></i> Loading');
            $(":button").attr('disabled', 'disabled');
        }).bind("ajaxComplete", function () {
            $(":button").html('<i class="fa fa-check"></i> Show');
            $(":button").removeAttr('disabled', 'disabled');
        });

What's the best way to determine which version of Oracle client I'm running?

You can use the v$session_connect_info view against the current session ID (SID from the USERENV namespace in SYS_CONTEXT).

e.g.

SELECT
  DISTINCT
  s.client_version
FROM
  v$session_connect_info s
WHERE
  s.sid = SYS_CONTEXT('USERENV', 'SID');

Select statement to find duplicates on certain fields

This is a fun solution with SQL Server 2005 that I like. I'm going to assume that by "for every record except for the first one", you mean that there is another "id" column that we can use to identify which row is "first".

SELECT id
    , field1
    , field2
    , field3
FROM
(
    SELECT id
        , field1
        , field2
        , field3
        , RANK() OVER (PARTITION BY field1, field2, field3 ORDER BY id ASC) AS [rank]
    FROM table_name
) a
WHERE [rank] > 1

How do I print colored output with Python 3?

It is very simple with colorama, just do this:

import colorama
from colorama import Fore, Style
print(Fore.BLUE + "Hello World")

And here is the running result in Python3 REPL:

And call this to reset the color settings:

print(Style.RESET_ALL)

To avoid printing an empty line write this:

print(f"{Fore.BLUE}Hello World{Style.RESET_ALL}")

Python creating a dictionary of lists

You can use defaultdict:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = ['1', '2']
>>> for i in a:
...   for j in range(int(i), int(i) + 2):
...     d[j].append(i)
...
>>> d
defaultdict(<type 'list'>, {1: ['1'], 2: ['1', '2'], 3: ['2']})
>>> d.items()
[(1, ['1']), (2, ['1', '2']), (3, ['2'])]

How to switch activity without animation in Android?

Here is a one-liner solution that works for as low as minSdkVersion 14 which you should insert in you res/styles.xml:

<item name="android:windowAnimationStyle">@null</item>

like so:

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        ...
        <item name="android:windowAnimationStyle">@null</item>
    </style>
    ...
</resources>

Cheers!

Merge DLL into EXE?

I Found The Solution Below are the Stpes:-

  1. Download ILMerge.msi and Install it on your Machine.
  2. Open Command Prompt
  3. type cd C:\Program Files (x86)\Microsoft\ILMerge Preess Enter
  4. C:\Program Files (x86)\Microsoft\ILMerge>ILMerge.exe /target:winexe /targetplatform:"v4,C:\Windows\Microsoft.NET\Framework\v4.0.30319" /out:NewExeName.exe SourceExeName.exe DllName.dll

For Multiple Dll :-

C:\Program Files (x86)\Microsoft\ILMerge>ILMerge.exe /target:winexe /targetplatform:"v4,C:\Windows\Microsoft.NET\Framework\v4.0.30319" /out:NewExeName.exe SourceExeName.exe DllName1.dll DllName2.dll DllName3.dll

Open images? Python

if location == a2:
    img = Image.open("picture.jpg")
    Img.show

Make sure the name of the image is in parantheses this should work

MySQL Error 1215: Cannot add foreign key constraint

Another reason: if you use ON DELETE SET NULL all columns that are used in the foreign key must allow null values. Someone else found this out in this question.

From my understanding it wouldn't be a problem regarding data integrity, but it seems that MySQL just doesn't support this feature (in 5.7).

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

How can I clear the Scanner buffer in Java?

Try this:

in.nextLine();

This advances the Scanner to the next line.

Getting byte array through input type = file

[Edit]

As noted in comments above, while still on some UA implementations, readAsBinaryString method didn't made its way to the specs and should not be used in production. Instead, use readAsArrayBuffer and loop through it's buffer to get back the binary string :

_x000D_
_x000D_
document.querySelector('input').addEventListener('change', function() {_x000D_
_x000D_
  var reader = new FileReader();_x000D_
  reader.onload = function() {_x000D_
_x000D_
    var arrayBuffer = this.result,_x000D_
      array = new Uint8Array(arrayBuffer),_x000D_
      binaryString = String.fromCharCode.apply(null, array);_x000D_
_x000D_
    console.log(binaryString);_x000D_
_x000D_
  }_x000D_
  reader.readAsArrayBuffer(this.files[0]);_x000D_
_x000D_
}, false);
_x000D_
<input type="file" />_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

For a more robust way to convert your arrayBuffer in binary string, you can refer to this answer.


[old answer] (modified)

Yes, the file API does provide a way to convert your File, in the <input type="file"/> to a binary string, thanks to the FileReader Object and its method readAsBinaryString.
[But don't use it in production !]

_x000D_
_x000D_
document.querySelector('input').addEventListener('change', function(){_x000D_
    var reader = new FileReader();_x000D_
    reader.onload = function(){_x000D_
        var binaryString = this.result;_x000D_
        document.querySelector('#result').innerHTML = binaryString;_x000D_
        }_x000D_
    reader.readAsBinaryString(this.files[0]);_x000D_
  }, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

If you want an array buffer, then you can use the readAsArrayBuffer() method :

_x000D_
_x000D_
document.querySelector('input').addEventListener('change', function(){_x000D_
    var reader = new FileReader();_x000D_
    reader.onload = function(){_x000D_
        var arrayBuffer = this.result;_x000D_
      console.log(arrayBuffer);_x000D_
        document.querySelector('#result').innerHTML = arrayBuffer + '  '+arrayBuffer.byteLength;_x000D_
        }_x000D_
    reader.readAsArrayBuffer(this.files[0]);_x000D_
  }, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

Load data from txt with pandas

I usually take a look at the data first or just try to import it and do data.head(), if you see that the columns are separated with \t then you should specify sep="\t" otherwise, sep = " ".

import pandas as pd     
data = pd.read_csv('data.txt', sep=" ", header=None)

Display a RecyclerView in Fragment

Make sure that you have the correct layout, and that the RecyclerView id is inside the layout. Otherwise, you will be getting this error. I had the same problem, then I noticed the layout was wrong.

    public class ColorsFragment extends Fragment {

         public ColorsFragment() {}

         @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container,
             Bundle savedInstanceState) {

==> make sure you are getting the correct layout here. R.layout...

             View rootView = inflater.inflate(R.layout.fragment_colors, container, false); 

Git clone particular version of remote repository

If that version you need to obtain is either a branch or a tag then:

git clone -b branch_or_tag_name repo_address_or_path

Change Schema Name Of Table In SQL

Your Code is:

FROM
 dbo.Employees
TO
 exe.Employees

I tried with this query.

ALTER SCHEMA exe TRANSFER dbo.Employees

Just write create schema exe and execute it

HTML Canvas Full Screen

A - How To Calculate Full Screen Width & Height

Here is the functions;

canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

Check this out

B - How To Make Full Screen Stable With Resize

Here is the resize method for the resize event;

function resizeCanvas() {
    canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

    WIDTH = canvas.width;
    HEIGHT = canvas.height;

    clearScreen();
}

C - How To Get Rid Of Scroll Bars

Simply;

<style>
    html, body {
        overflow: hidden;
    }
</style>

D - Demo Code

_x000D_
_x000D_
<html>_x000D_
 <head>_x000D_
  <title>Full Screen Canvas Example</title>_x000D_
  <style>_x000D_
   html, body {_x000D_
    overflow: hidden;_x000D_
   }_x000D_
  </style>_x000D_
 </head>_x000D_
 <body onresize="resizeCanvas()">_x000D_
  <canvas id="mainCanvas">_x000D_
  </canvas>_x000D_
  <script>_x000D_
   (function () {_x000D_
    canvas = document.getElementById('mainCanvas');_x000D_
    ctx = canvas.getContext("2d");_x000D_
    _x000D_
    canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;_x000D_
    canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;_x000D_
    WIDTH = canvas.width;_x000D_
    HEIGHT = canvas.height;_x000D_
    _x000D_
    clearScreen();_x000D_
   })();_x000D_
   _x000D_
   function resizeCanvas() {_x000D_
    canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;_x000D_
    canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;_x000D_
    _x000D_
    WIDTH = canvas.width;_x000D_
    HEIGHT = canvas.height;_x000D_
    _x000D_
    clearScreen();_x000D_
   }_x000D_
   _x000D_
   function clearScreen() {_x000D_
    var grd = ctx.createLinearGradient(0,0,0,180);_x000D_
    grd.addColorStop(0,"#6666ff");_x000D_
    grd.addColorStop(1,"#aaaacc");_x000D_
_x000D_
    ctx.fillStyle = grd;_x000D_
    ctx.fillRect(  0, 0, WIDTH, HEIGHT );_x000D_
   }_x000D_
  </script>_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to install gdb (debugger) in Mac OSX El Capitan?

On my Mac OS X El Capitan, I use homebrew to install gdb:

brew install gdb

Then I follow the instruction here: https://sourceware.org/gdb/wiki/BuildingOnDarwin, in the section 2.1. Method for Mac OS X 10.5 (Leopard) and later.

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

Sounds like you want a simple imagemap, I'd recommend to not make it more complex than it needs to be. Here's an article on how to improve imagemaps with svg. It's very easy to do clickable regions in svg itself, just add some <a> elements around the shapes you want to have clickable.

A couple of options if you need something more advanced:

Creating a system overlay window (always on top)

It uses permission "android.permission.SYSTEM_ALERT_WINDOW" full tutorial on this link : http://androidsrc.net/facebook-chat-like-floating-chat-heads/

Invariant Violation: _registerComponent(...): Target container is not a DOM element

When you got:

Error: Uncaught Error: Target container is not a DOM element.

You can use DOMContentLoaded event or move your <script ...></script> tag in the bottom of your body.

The DOMContentLoaded event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.

document.addEventListener("DOMContentLoaded", function(event) {
  ReactDOM.render(<App />, document.getElementById('root'));
})

Best Way to do Columns in HTML/CSS

You might also try.

_x000D_
_x000D_
.col{_x000D_
  float: left;_x000D_
}_x000D_
.col + .col{_x000D_
  float: left;_x000D_
  margin-left: 20px;_x000D_
}_x000D_
_x000D_
/* or */_x000D_
_x000D_
.col:not(:nth-child(1)){_x000D_
  float:left;_x000D_
  margin-left: 20px;_x000D_
}_x000D_
_x000D_
 
_x000D_
<div class="row">_x000D_
  <div class="col">column</div>_x000D_
  <div class="col">column</div>_x000D_
  <div class="col">column</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

ref: http://codepen.io/co0kie/pen/gPKNWX?editors=1100

How to POST using HTTPclient content type = application/x-www-form-urlencoded

 var params= new Dictionary<string, string>();
 var url ="Please enter URLhere"; 
 params.Add("key1", "value1");
 params.Add("key2", "value2");

 using (HttpClient client = new HttpClient())
  {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = client.PostAsync(url, new FormUrlEncodedContent(dict)).Result;
              var tokne= response.Content.ReadAsStringAsync().Result;
}

//Get response as expected

How to SHUTDOWN Tomcat in Ubuntu?

Van, in your case where tomcat won't shutdown normally, i would use

ps ax | grep java

to find the java process number. If that command returns something, then run

sudo kill -9 pid

where pid is the process number. The -9 option means 'just kill it', and normally you don't need this sort of thing, but since in your situation the process won't stop normally, you need it.

The output of the first command should look like

38678 s002  U      0:02.62 /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home/bin/java -Djava.util.logging.config.file=/usr/share/apache-tomcat-6.0.26/conf/logging.properties -Xms2048m -Xmx2048m -XX:PermSize=256m -XX:MaxPermSize=512m -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=8086 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Djava.rmi.server.hostname=xxxx -Djava.endorsed.dirs=/usr/share/apache-tomcat-6.0.26/endorsed -classpath /usr/share/apache-tomcat-6.0.26/bin/bootstrap.jar -Dcatalina.base=/usr/share/apache-tomcat-6.0.26 -Dcatalina.home=/usr/share/apache-tomcat-6.0.26 -Djava.io.tmpdir=/usr/share/apache-tomcat-6.0.26/temp org.apache.catalina.startup.Bootstrap start

38678 is the process number. Be aware that there might be other java processes running that you might not want to kill. Also, this output is from a mac, so on ubuntu will look slightly different.

Eclipse "Server Locations" section disabled and need to change to use Tomcat installation

If your server is not loaded with heavy configuration, the best solution would be to delete the tomcat and set it again.
It will be much easier then doing try and error for 7-10 times! enter image description here

How do you calculate program run time in python?

You might want to take a look at the timeit module:

http://docs.python.org/library/timeit.html

or the profile module:

http://docs.python.org/library/profile.html

There are some additionally some nice tutorials here:

http://www.doughellmann.com/PyMOTW/profile/index.html

http://www.doughellmann.com/PyMOTW/timeit/index.html

And the time module also might come in handy, although I prefer the later two recommendations for benchmarking and profiling code performance:

http://docs.python.org/library/time.html

How to download an entire directory and subdirectories using wget?

This link just gave me the best answer:

$ wget --no-clobber --convert-links --random-wait -r -p --level 1 -E -e robots=off -U mozilla http://base.site/dir/

Worked like a charm.

Read all contacts' phone numbers in android

Code to get contact name (Ascending order) and number

For more reference: show contact in listview

Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" ASC");
        while (phones.moveToNext())
        {
            String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
            String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));


        }
        phones.close();

document.getElementById replacement in angular4 / typescript?

  element: HTMLElement;

  constructor() {}

  fakeClick(){
    this.element = document.getElementById('ButtonX') as HTMLElement;
    this.element.click();
  }

Android Studio emulator does not come with Play Store for API 23

I've had to do this recently on the API 23 emulator, and followed this guide. It works for API 23 emulator, so you shouldn't have a problem.

Note: All credit goes to the author of the linked blog post (pyoor). I'm just posting it here in case the link breaks for any reason.

....

Download the GAPPS Package

Next we need to pull down the appropriate Google Apps package that matches our Android AVD version. In this case we’ll be using the 'gapps-lp-20141109-signed.zip' package. You can download that file from BasketBuild here.

[pyoor@localhost]$ md5sum gapps-lp-20141109-signed.zip
367ce76d6b7772c92810720b8b0c931e gapps-lp-20141109-signed.zip

In order to install Google Play, we’ll need to push the following 4 APKs to our AVD (located in ./system/priv-app/):

GmsCore.apk, GoogleServicesFramework.apk, GoogleLoginService.apk, Phonesky.apk

[pyoor@localhost]$ unzip -j gapps-lp-20141109-signed.zip \
system/priv-app/GoogleServicesFramework/GoogleServicesFramework.apk \
system/priv-app/GoogleLoginService/GoogleLoginService.apk \
system/priv-app/Phonesky/Phonesky.apk \
system/priv-app/GmsCore/GmsCore.apk -d ./

Push APKs to the Emulator

With our APKs extracted, let’s launch our AVD using the following command.

[pyoor@localhost tools]$ ./emulator @<YOUR_DEVICE_NAME> -no-boot-anim

This may take several minutes the first time as the AVD is created. Once started, we need to remount the AVDs system partition as read/write so that we can push our packages onto the device.

[pyoor@localhost]$ cd ~/android-sdk/platform-tools/
[pyoor@localhost platform-tools]$ ./adb remount

Next, push the APKs to our AVD:

[pyoor@localhost platform-tools]$ ./adb push GmsCore.apk /system/priv-app/
[pyoor@localhost platform-tools]$ ./adb push GoogleServicesFramework.apk /system/priv-app/
[pyoor@localhost platform-tools]$ ./adb push GoogleLoginService.apk /system/priv-app/
[pyoor@localhost platform-tools]$ ./adb push Phonesky.apk /system/priv-app

Profit!

And finally, reboot the emualator using the following commands:

[pyoor@localhost platform-tools]$ ./adb shell stop && ./adb shell start

Once the emulator restarts, we should see the Google Play package appear within the menu launcher. After associating a Google account with this AVD we now have a fully working version of Google Play running under our emulator.

Spring Boot Remove Whitelabel Error Page

server.error.whitelabel.enabled=false

Include the above line to the Resources folders application.properties

More Error Issue resolve please refer http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-customize-the-whitelabel-error-page

How to send POST request?

You can't achieve POST requests using urllib (only for GET), instead try using requests module, e.g.:

Example 1.0:

import requests

base_url="www.server.com"
final_url="/{0}/friendly/{1}/url".format(base_url,any_value_here)

payload = {'number': 2, 'value': 1}
response = requests.post(final_url, data=payload)

print(response.text) #TEXT/HTML
print(response.status_code, response.reason) #HTTP

Example 1.2:

>>> import requests

>>> payload = {'key1': 'value1', 'key2': 'value2'}

>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)
{
  ...
  "form": {
    "key2": "value2",
    "key1": "value1"
  },
  ...
}

Example 1.3:

>>> import json

>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}

>>> r = requests.post(url, data=json.dumps(payload))

React Native Change Default iOS Simulator Device

You can create an alias at your ~/.bash_profile file:

alias rn-ios="react-native run-ios --simulator \"iPhone 5s (10.0)\""

And then run react-native using the created alias:

$ rn-ios

Canvas width and height in HTML5

Thank you very much! Finally I solved the blurred pixels problem with this code:

<canvas id="graph" width=326 height=240 style='width:326px;height:240px'></canvas>

With the addition of the 'half-pixel' does the trick to unblur lines.

How to change resolution (DPI) of an image?

This article talks about modifying the EXIF data without the re-saving/re-compressing (and thus loss of information -- it actually uses a "trick"; there may be more direct libraries) required by the SetResolution approach. This was found on a quick google search, but I wanted to point out that all you need to do is modify the stored EXIF data.

Also: .NET lib for EXIF modification and another SO question. Google owns when you know good search terms.

Stop Chrome Caching My JS Files

You can open an incognito window instead. Switching to an incognito window worked for me when disabling the cache in a normal chrome window still didn't reload a JavaScript file I had changed since the last cache.

https://www.quora.com/Does-incognito-mode-on-Chrome-use-the-cache-that-was-previously-stored

How to check is Apache2 is stopped in Ubuntu?

In the command line type service apache2 status then hit enter. The result should say:

Apache2 is running (pid xxxx)

pandas: find percentile stats of a given column

You can even give multiple columns with null values and get multiple quantile values (I use 95 percentile for outlier treatment)

my_df[['field_A','field_B']].dropna().quantile([0.0, .5, .90, .95])

Form Google Maps URL that searches for a specific places near specific coordinates

Yeah, I had the same question for a long time and I found the perfect one. Here are some parameters from it.

https://maps.google.com/?parameter=value



q=

Used to specify the search query in Google maps search.
eg :

https://maps.google.com/?q=newyork or
https://maps.google.com/?q=51.03841,-114.01679

near=

Used to specify the location instead of putting it into q. Also has the added effect of allowing you to increase the AddressDetails Accuracy value by being more precise. Mostly only useful if q is a business or suchlike.

z=

Zoom level. Can be set 19 normally, but in certain cases can go up to 23.

ll=

Latitude and longitude of the map centre point. Must be in that order. Requires decimal format. Interestingly, you can use this without q, in which case it doesn’t show a marker.

sll=

Similar to ll, only this sets the lat/long of the centre point for a business search. Requires the same input criteria as ll.

t=

Sets the kind of map shown. Can be set to:

m – normal  map
k – satellite
h – hybrid
p – terrain

saddr=

Sets the starting point for directions searches. You can also add text into this in brackets to bold it in the directions sidebar.

daddr=

Sets the end point for directions searches, and again will bold any text added in brackets.You can also add "+to:" which will set via points. These can be added multiple times.

via=

Allows you to insert via points in directions. Must be in CSV format. For example, via=1,5 addresses 1 and 5 will be via points without entries in the sidebar. The start point (which is set as 0), and 2, 3 and 4 will all show full addresses.

doflg=

Changes the units used to measure distance (will default to the standard unit in country of origin). Change to ptk for metric or ptm for imperial.

msa=

Does stuff with My Maps. Set to 0 show defined My Maps, b to turn the My Maps sidebar on, 1 to show the My Maps tab on its own, or 2 to go to the new My Map creator form.

reference : http://moz.com/ugc/everything-you-never-wanted-to-know-about-google-maps-parameters

How to call two methods on button's onclick method in HTML or JavaScript?

The modern event handling method:

element.addEventListener('click', startDragDrop, false);
element.addEventListener('click', spyOnUser, false);

The first argument is the event, the second is the function and the third specifies whether to allow event bubbling.

From QuirksMode:

W3C’s DOM Level 2 Event specification pays careful attention to the problems of the traditional model. It offers a simple way to register as many event handlers as you like for the same event on one element.

The key to the W3C event registration model is the method addEventListener(). You give it three arguments: the event type, the function to be executed and a boolean (true or false) that I’ll explain later on. To register our well known doSomething() function to the onclick of an element you do:

Full details here: http://www.quirksmode.org/js/events_advanced.html

Using jQuery

if you're using jQuery, there is a nice API for event handling:

$('#myElement').bind('click', function() { doStuff(); });
$('#myElement').bind('click', function() { doMoreStuff(); });
$('#myElement').bind('click', doEvenMoreStuff);

Full details here: http://api.jquery.com/category/events/

How to part DATE and TIME from DATETIME in MySQL

per the mysql documentation, the DATE() function will pull the date part of a datetime feild, and TIME() for the time portion. so I would try:

select DATE(dateTimeField) as Date, TIME(dateTimeField) as Time, col2, col3, FROM Table1 ...

How to schedule a function to run every hour on Flask?

You could try using APScheduler's BackgroundScheduler to integrate interval job into your Flask app. Below is the example that uses blueprint and app factory (init.py) :

from datetime import datetime

# import BackgroundScheduler
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask

from webapp.models.main import db 
from webapp.controllers.main import main_blueprint    

# define the job
def hello_job():
    print('Hello Job! The time is: %s' % datetime.now())

def create_app(object_name):
    app = Flask(__name__)
    app.config.from_object(object_name)
    db.init_app(app)
    app.register_blueprint(main_blueprint)
    # init BackgroundScheduler job
    scheduler = BackgroundScheduler()
    # in your case you could change seconds to hours
    scheduler.add_job(hello_job, trigger='interval', seconds=3)
    scheduler.start()

    try:
        # To keep the main thread alive
        return app
    except:
        # shutdown if app occurs except 
        scheduler.shutdown()

Hope it helps :)

Ref :

  1. https://github.com/agronholm/apscheduler/blob/master/examples/schedulers/background.py

error: expected unqualified-id before ‘.’ token //(struct)

The struct's name is ReducedForm; you need to make an object (instance of the struct or class) and use that. Do this:

ReducedForm MyReducedForm;
MyReducedForm.iSimplifiedNumerator = iNumerator/iGreatCommDivisor;
MyReducedForm.iSimplifiedDenominator = iDenominator/iGreatCommDivisor;

Cannot open output file, permission denied

FOR LINUX OS... go to file where u r created file.then usually ......project_name/bin/Debug/project_name.executable here for this executable file you wont be having execute permission then the execute permission.Either by right click if you are unable to change permission then use use open terminal(command promt) to change permission. first go to that executable file using 'cd' command then use "chmod u+x" then permission is going to change.then go to c::b open and execute you will get output.

only thing for all file u need to do it.

Remove rows with all or some NAs (missing values) in data.frame

We can also use the subset function for this.

finalData<-subset(data,!(is.na(data["mmul"]) | is.na(data["rnor"])))

This will give only those rows that do not have NA in both mmul and rnor

Is there a macro to conditionally copy rows to another worksheet?

Here's another solution that uses some of VBA's built in date functions and stores all the date data in an array for comparison, which may give better performance if you get a lot of data:

Public Sub MoveData(MonthNum As Integer, FromSheet As Worksheet, ToSheet As Worksheet)
    Const DateCol = "A" 'column where dates are store
    Const DestCol = "A" 'destination column where dates are stored. We use this column to find the last populated row in ToSheet
    Const FirstRow = 2 'first row where date data is stored
    'Copy range of values to Dates array
    Dates = FromSheet.Range(DateCol & CStr(FirstRow) & ":" & DateCol & CStr(FromSheet.Range(DateCol & CStr(FromSheet.Rows.Count)).End(xlUp).Row)).Value
    Dim i As Integer
    For i = LBound(Dates) To UBound(Dates)
        If IsDate(Dates(i, 1)) Then
            If Month(CDate(Dates(i, 1))) = MonthNum Then
                Dim CurrRow As Long
                'get the current row number in the worksheet
                CurrRow = FirstRow + i - 1
                Dim DestRow As Long
                'get the destination row
                DestRow = ToSheet.Range(DestCol & CStr(ToSheet.Rows.Count)).End(xlUp).Row + 1
                'copy row CurrRow in FromSheet to row DestRow in ToSheet
                FromSheet.Range(CStr(CurrRow) & ":" & CStr(CurrRow)).Copy ToSheet.Range(DestCol & CStr(DestRow))
            End If
        End If
    Next i
End Sub

Ant is using wrong java version

This is rather an old question, but I will add my notes for future references.

I had a similar issue and fixed it by changing the order of the exports in the PATH variable.

For example I was using a method of concatenating strings to my PATH by doing (this is just an example):

$> export PATH='$PATH:'$JAVA_HOME

If my variable PATH already had a java in it, the last value would be meaningless, thus the order would matter. To solve this I started inverting it by adding my variable first, then adding the PATH.

Following this idea I inverted the order that ANT_HOME was being exported. Adding JAVA_HOME before ANT_HOME.

This could be just a coincidence, but it worked for me.

In Python, how do I index a list with another list?

I wasn't happy with any of these approaches, so I came up with a Flexlist class that allows for flexible indexing, either by integer, slice or index-list:

class Flexlist(list):
    def __getitem__(self, keys):
        if isinstance(keys, (int, slice)): return list.__getitem__(self, keys)
        return [self[k] for k in keys]

Which, for your example, you would use as:

L = Flexlist(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])
Idx = [0, 3, 7]
T = L[ Idx ]

print(T)  # ['a', 'd', 'h']

Is it safe to expose Firebase apiKey to the public?

After reading this and after I did some research about the possibilities, I came up with a slightly different approach to restrict data usage by unauthorised users:

I save my users in my DB too (and save the profile data in there). So i just set the db rules like this:

".read": "auth != null && root.child('/userdata/'+auth.uid+'/userRole').exists()",
".write": "auth != null && root.child('/userdata/'+auth.uid+'/userRole').exists()"

This way only a previous saved user can add new users in the DB so there is no way anyone without an account can do operations on DB. also adding new users is posible only if the user has a special role and edit only by admin or by that user itself (something like this):

"userdata": {
  "$userId": {
    ".write": "$userId === auth.uid || root.child('/userdata/'+auth.uid+'/userRole').val() === 'superadmin'",
   ...

Visual Studio 2010 always thinks project is out of date, but nothing has changed

Most build systems use data time stamps to determine when rebuilds should happen - the date/time stamp of any output files is checked against the last modified time of the dependencies - if any of the dependencies are fresher, then the target is rebuilt.

This can cause problems if any of the dependencies somehow get an invalid data time stamp as it's difficult for the time stamp of any build output to ever exceed the timestamp of a file supposedly created in the future :P

Removing duplicate elements from an array in Swift

You can use directly a set collection to remove duplicate, then cast it back to an array

var myArray = [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6]
var mySet = Set<Int>(myArray)

myArray = Array(mySet) // [2, 4, 60, 6, 15, 24, 1]

Then you can order your array as you want

myArray.sort{$0 < $1} // [1, 2, 4, 6, 15, 24, 60]

Changing image sizes proportionally using CSS?

If you don't want to stretch the image, fit it into div container without overflow and center it by adjusting it's margin if needed.

  1. The image will not get cropped
  2. The aspect ratio will also remain the same.

HTML:

<div id="app">
    <div id="container">
      <img src="#" alt="something">
    </div>
    <div id="container">
      <img src="#" alt="something">
    </div>
    <div id="container">
      <img src="#" alt="something">
    </div>
</div>

CSS:

div#container {
    height: 200px;
    width: 200px;
    border: 1px solid black;
    margin: 4px;
}
img {
    max-width: 100%;
    max-height: 100%;
    display: block;
    margin: 0 auto;
}

How to "git clone" including submodules?

I think you can go with 3 steps:

git clone
git submodule init
git submodule update

LaTeX package for syntax highlighting of code in various languages

I recommend Pygments. It accepts a piece of code in any language and outputs syntax highlighted LaTeX code. It uses fancyvrb and color packages to produce its output. I personally prefer it to the listing package. I think fancyvrb creates much prettier results.