Programs & Examples On #Swc

An Adobe SWC file is a package of precompiled Flash symbols and ActionScript code that allows a Flash or Flex developer to distribute classes and assets, or to avoid recompiling symbols and code that will not change.

WCF error - There was no endpoint listening at

You can solve the issue by clearing value of address in endpoint tag in web.config:

<endpoint address="" name="wsHttpEndpoint"  .......           />

How to convert image into byte array and byte array to base64 String in android?

They have wrapped most stuff need to solve your problem, one of the tests looks like this:

String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " ");
String code = "background: url(folder.png);";

StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), true);
embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1));

String result = writer.toString();
assertEquals("background: url(" + folderDataURI + ");", result);

Error 5 : Access Denied when starting windows service

Use LocalSystem Account instead of LocalService Account in Service Installer.

You can do this either from doing below change in design view of your service installer:
Properties of Service Process Installer -> Set Account to LocalSystem.

or by doing below change in in designer.cs file of your service installer:

this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem;

How to Load RSA Private Key From File

You need to convert your private key to PKCS8 format using following command:

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key_file  -nocrypt > pkcs8_key

After this your java program can read it.

How to compare type of an object in Python?

First, avoid all type comparisons. They're very, very rarely necessary. Sometimes, they help to check parameter types in a function -- even that's rare. Wrong type data will raise an exception, and that's all you'll ever need.

All of the basic conversion functions will map as equal to the type function.

type(9) is int
type(2.5) is float
type('x') is str
type(u'x') is unicode
type(2+3j) is complex

There are a few other cases.

isinstance( 'x', basestring )
isinstance( u'u', basestring )
isinstance( 9, int )
isinstance( 2.5, float )
isinstance( (2+3j), complex )

None, BTW, never needs any of this kind of type checking. None is the only instance of NoneType. The None object is a Singleton. Just check for None

variable is None

BTW, do not use the above in general. Use ordinary exceptions and Python's own natural polymorphism.

REST API Token-based Authentication

A pure RESTful API should use the underlying protocol standard features:

  1. For HTTP, the RESTful API should comply with existing HTTP standard headers. Adding a new HTTP header violates the REST principles. Do not re-invent the wheel, use all the standard features in HTTP/1.1 standards - including status response codes, headers, and so on. RESTFul web services should leverage and rely upon the HTTP standards.

  2. RESTful services MUST be STATELESS. Any tricks, such as token based authentication that attempts to remember the state of previous REST requests on the server violates the REST principles. Again, this is a MUST; that is, if you web server saves any request/response context related information on the server in attempt to establish any sort of session on the server, then your web service is NOT Stateless. And if it is NOT stateless it is NOT RESTFul.

Bottom-line: For authentication/authorization purposes you should use HTTP standard authorization header. That is, you should add the HTTP authorization / authentication header in each subsequent request that needs to be authenticated. The REST API should follow the HTTP Authentication Scheme standards.The specifics of how this header should be formatted are defined in the RFC 2616 HTTP 1.1 standards – section 14.8 Authorization of RFC 2616, and in the RFC 2617 HTTP Authentication: Basic and Digest Access Authentication.

I have developed a RESTful service for the Cisco Prime Performance Manager application. Search Google for the REST API document that I wrote for that application for more details about RESTFul API compliance here. In that implementation, I have chosen to use HTTP "Basic" Authorization scheme. - check out version 1.5 or above of that REST API document, and search for authorization in the document.

How to generate java classes from WSDL file

Assuming that you have JAXB installed Go to the following directory C:\Program Files\jaxb\bin open command window here

> xjc -wsdl http://localhost/mywsdl/MyDWsdl.wsdl C:\Users\myname\Desktop

C:\Users\myname\Desktop is the ouput folder you can change that to your preference

http://localhost/mywsdl/MyDWsdl.wsdl is the link to the WSDL

C compiler for Windows?

You could always just use gcc via cygwin.

Postman addon's like in firefox

The feature that I'm missing a lot from postman in Firefox extensions is WebView
(preview when API returns HTML).

Now I'm settled with Fiddler (Inspectors > WebView)

Help with packages in java - import does not work

Just add classpath entry ( I mean your parent directory location) under System Variables and User Variables menu ... Follow : Right Click My Computer>Properties>Advanced>Environment Variables

How to view unallocated free space on a hard disk through terminal

This is an old question, but I wanted to give my answer as well.

Since we're talking about free available space, we should talk about sectors, since no partitioning or sizing of sectors is done.

For us human beings this doesn't make much sense. To have human-readable information we must translate this number into bytes. So, we have a disk already partitioned and we want to know how much space we may use. I personally don't like the parted solution because my brain-memory for commands is already taken. There is also cfdisk, which gives you free space. But I think fdisk is the quickest solution: it's plain and simple, with nothing to install: execute fdisk /dev/sdx and then enter v into the interactive shell. It will gives you the number of sectors still free.

2004-54-0 [17:03:33][root@minimac:~]$> fdisk /dev/sda
Welcome to fdisk (util-linux 2.23.2).
..
Command (m for help): v
Remaining 1713 unallocated 512-byte sectors

We still have 1713 sectors at 512 bytes each. So, because you love terminal (in 2012, who knows now?) we do echo $(((1713*512)/1024))k, which is 1713 sectors multiplied for 512 bytes (divided by 1024 to have KB), which gives 856k.. not even 900 KB.. and I need another disk..

Difference between OData and REST web services

REST stands for REpresentational State Transfer which is a resource based architectural style. Resource based means that data and functionalities are considered as resources.

OData is a web based protocol that defines a set of best practices for building and consuming RESTful web services. OData is a way to create RESTful web services thus an implementation of REST.

How to change sa password in SQL Server 2008 express?

This may help you to reset your sa password for SQL 2008 and 2012

EXEC sp_password NULL, 'yourpassword', 'sa'

How can I count the number of matches for a regex?

If you want to use Java 8 streams and are allergic to while loops, you could try this:

public static int countPattern(String references, Pattern referencePattern) {
    Matcher matcher = referencePattern.matcher(references);
    return Stream.iterate(0, i -> i + 1)
            .filter(i -> !matcher.find())
            .findFirst()
            .get();
}

Disclaimer: this only works for disjoint matches.

Example:

public static void main(String[] args) throws ParseException {
    Pattern referencePattern = Pattern.compile("PASSENGER:\\d+");
    System.out.println(countPattern("[ \"PASSENGER:1\", \"PASSENGER:2\", \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
    System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\" ]", referencePattern));
    System.out.println(countPattern("[ \"AIR:1\", \"AIR:2\", \"FOP:2\", \"PASSENGER:1\" ]", referencePattern));
    System.out.println(countPattern("[  ]", referencePattern));
}

This prints out:

2
0
1
0

This is a solution for disjoint matches with streams:

public static int countPattern(String references, Pattern referencePattern) {
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
            new Iterator<Integer>() {
                Matcher matcher = referencePattern.matcher(references);
                int from = 0;

                @Override
                public boolean hasNext() {
                    return matcher.find(from);
                }

                @Override
                public Integer next() {
                    from = matcher.start() + 1;
                    return 1;
                }
            },
            Spliterator.IMMUTABLE), false).reduce(0, (a, c) -> a + c);
}

How to globally replace a forward slash in a JavaScript string?

This has worked for me in turning "//" into just "/".

str.replace(/\/\//g, '/');

Make div fill remaining space along the main axis in flexbox

Use the flex-grow property to make a flex item consume free space on the main axis.

This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.

A common example is flex-grow: 1 or, using the shorthand property, flex: 1.

Hence, instead of width: 96% on your div, use flex: 1.


You wrote:

So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.

The squashing of the fixed-width div is related to another flex property: flex-shrink

By default, flex items are set to flex-shrink: 1 which enables them to shrink in order to prevent overflow of the container.

To disable this feature use flex-shrink: 0.

For more details see The flex-shrink factor section in the answer here:


Learn more about flex alignment along the main axis here:

Learn more about flex alignment along the cross axis here:

MAMP mysql server won't start. No mysql processes are running

Best way to find the real cause is to check the MAMP error log in MAMP > logs > mysql_error_log.err

I found the ERROR "Do you already have another mysql server running on port: 3306 ?" - which was actually the cause for my MAMP MYSQL not starting.

Port 3306 was already "busy", so I have changed it to 8306 and that solved my issue.

Creating files and directories via Python

import os

path = chap_name

if not os.path.exists(path):
    os.makedirs(path)

filename = img_alt + '.jpg'
with open(os.path.join(path, filename), 'wb') as temp_file:
    temp_file.write(buff)

Key point is to use os.makedirs in place of os.mkdir. It is recursive, i.e. it generates all intermediate directories. See http://docs.python.org/library/os.html

Open the file in binary mode as you are storing binary (jpeg) data.

In response to Edit 2, if img_alt sometimes has '/' in it:

img_alt = os.path.basename(img_alt)

sklearn plot confusion matrix with labels

I found a function that can plot the confusion matrix which generated from sklearn.

import numpy as np


def plot_confusion_matrix(cm,
                          target_names,
                          title='Confusion matrix',
                          cmap=None,
                          normalize=True):
    """
    given a sklearn confusion matrix (cm), make a nice plot

    Arguments
    ---------
    cm:           confusion matrix from sklearn.metrics.confusion_matrix

    target_names: given classification classes such as [0, 1, 2]
                  the class names, for example: ['high', 'medium', 'low']

    title:        the text to display at the top of the matrix

    cmap:         the gradient of the values displayed from matplotlib.pyplot.cm
                  see http://matplotlib.org/examples/color/colormaps_reference.html
                  plt.get_cmap('jet') or plt.cm.Blues

    normalize:    If False, plot the raw numbers
                  If True, plot the proportions

    Usage
    -----
    plot_confusion_matrix(cm           = cm,                  # confusion matrix created by
                                                              # sklearn.metrics.confusion_matrix
                          normalize    = True,                # show proportions
                          target_names = y_labels_vals,       # list of names of the classes
                          title        = best_estimator_name) # title of graph

    Citiation
    ---------
    http://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html

    """
    import matplotlib.pyplot as plt
    import numpy as np
    import itertools

    accuracy = np.trace(cm) / np.sum(cm).astype('float')
    misclass = 1 - accuracy

    if cmap is None:
        cmap = plt.get_cmap('Blues')

    plt.figure(figsize=(8, 6))
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()

    if target_names is not None:
        tick_marks = np.arange(len(target_names))
        plt.xticks(tick_marks, target_names, rotation=45)
        plt.yticks(tick_marks, target_names)

    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]


    thresh = cm.max() / 1.5 if normalize else cm.max() / 2
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        if normalize:
            plt.text(j, i, "{:0.4f}".format(cm[i, j]),
                     horizontalalignment="center",
                     color="white" if cm[i, j] > thresh else "black")
        else:
            plt.text(j, i, "{:,}".format(cm[i, j]),
                     horizontalalignment="center",
                     color="white" if cm[i, j] > thresh else "black")


    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))
    plt.show()

It will look like this enter image description here

decompiling DEX into Java sourcecode

A more complete version of fred's answer:

Manual way

First you need a tool to extract all the (compiled) classes on the DEX to a JAR.
There's one called dex2jar, which is made by a chinese student.

Then, you can use jd-gui to decompile the classes on the JAR to source code.
The resulting source should be quite readable, as dex2jar applies some optimizations.

Automatic way

You can use APKTool. It will automatically extract all the classes (.dex), resources (.asrc), then it will convert binary XML to human-readable XML, and it will also dissassemble the classes for you.
Disassembly will always be more robust than decompiling, especially with
JARs obfuscated with Pro Guard!

Just tell APKTool to decode the APK into a directory, then modify what you want,
and finally encode it back to an APK. That's all.

Important: APKTool dissassembles. It doesn't decompile.
The generated code won't be Java source.
But you should be able to read it, and even edit it if you're familiar with jasmin.
If you want Java source, please go over the Manual way.

jQuery UI Sortable Position

Use update instead of stop

http://api.jqueryui.com/sortable/

update( event, ui )

Type: sortupdate

This event is triggered when the user stopped sorting and the DOM position has changed.

.

stop( event, ui )

Type: sortstop

This event is triggered when sorting has stopped. event Type: Event

Piece of code:

http://jsfiddle.net/7a1836ce/

<script type="text/javascript">

var sortable    = new Object();
sortable.s1     = new Array(1, 2, 3, 4, 5);
sortable.s2     = new Array(1, 2, 3, 4, 5);
sortable.s3     = new Array(1, 2, 3, 4, 5);
sortable.s4     = new Array(1, 2, 3, 4, 5);
sortable.s5     = new Array(1, 2, 3, 4, 5);

sortingExample();

function sortingExample()
{
    // Init vars

    var tDiv    = $('<div></div>');
    var tSel    = '';

    // ul
    for (var tName in sortable)
    {

        // Creating ul list
        tDiv.append(createUl(sortable[tName], tName));
        // Add selector id
        tSel += '#' + tName + ',';

    }

    $('body').append('<div id="divArrayInfo"></div>');
    $('body').append(tDiv);

    // ul sortable params

    $(tSel).sortable({connectWith:tSel,
       start: function(event, ui) 
       {
            ui.item.startPos = ui.item.index();
       },
        update: function(event, ui)
        {
            var a   = ui.item.startPos;
            var b   = ui.item.index();
            var id = this.id;

            // If element moved to another Ul then 'update' will be called twice
            // 1st from sender list
            // 2nd from receiver list
            // Skip call from sender. Just check is element removed or not

            if($('#' + id + ' li').length < sortable[id].length)
            {
                return;
            }

            if(ui.sender === null)
            {
                sortArray(a, b, this.id, this.id);
            }
            else
            {
                sortArray(a, b, $(ui.sender).attr('id'), this.id);
            }

            printArrayInfo();

        }
    }).disableSelection();;

// Add styles

    $('<style>')
    .attr('type', 'text/css')
    .html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
    .appendTo('head');


    printArrayInfo();

}

function printArrayInfo()
{

    var tStr = '';

    for ( tName in sortable)
    {

        tStr += tName + ': ';

        for(var i=0; i < sortable[tName].length; i++)
        {

            // console.log(sortable[tName][i]);
            tStr += sortable[tName][i] + ', ';

        }

        tStr += '<br>';

    }

    $('#divArrayInfo').html(tStr);

}


function createUl(tArray, tId)
{

    var tUl = $('<ul>', {id:tId, class:'sortableClass'})

    for(var i=0; i < tArray.length; i++)
    {

        // Create Li element
        var tLi = $('<li>' + tArray[i] + '</li>');
        tUl.append(tLi);

    }

    return tUl;
}

function sortArray(a, b, idA, idB)
{
    var c;

    c = sortable[idA].splice(a, 1);
    sortable[idB].splice(b, 0, c);      

}
</script>

How do I remove the passphrase for the SSH key without having to create a new key?

Short answer:

$ ssh-keygen -p

This will then prompt you to enter the keyfile location, the old passphrase, and the new passphrase (which can be left blank to have no passphrase).


If you would like to do it all on one line without prompts do:

$ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]

Important: Beware that when executing commands they will typically be logged in your ~/.bash_history file (or similar) in plain text including all arguments provided (i.e. the passphrases in this case). It is, therefore, is recommended that you use the first option unless you have a specific reason to do otherwise.

Notice though that you can still use -f keyfile without having to specify -P nor -N, and that the keyfile defaults to ~/.ssh/id_rsa, so in many cases, it's not even needed.

You might want to consider using ssh-agent, which can cache the passphrase for a time. The latest versions of gpg-agent also support the protocol that is used by ssh-agent.

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

CSS:

.blue-icon{
color:blue !important;
}

HTML

<i class="fa fa-wrench blue-icon"></i>

Glyphicons are removed in 4.0, i recommend Font-awesome 4 or newer :)

How to show x and y axes in a MATLAB graph?

Easiest solution:

plot([0,0],[0.0], xData, yData);

This creates an invisible line between the points [0,0] to [0,0] and since Matlab wants to include these points it will shows the axis.

How to remove elements from a generic list while iterating over it?

My approach is that I first create a list of indices, which should get deleted. Afterwards I loop over the indices and remove the items from the initial list. This looks like this:

var messageList = ...;
// Restrict your list to certain criteria
var customMessageList = messageList.FindAll(m => m.UserId == someId);

if (customMessageList != null && customMessageList.Count > 0)
{
    // Create list with positions in origin list
    List<int> positionList = new List<int>();
    foreach (var message in customMessageList)
    {
        var position = messageList.FindIndex(m => m.MessageId == message.MessageId);
        if (position != -1)
            positionList.Add(position);
    }
    // To be able to remove the items in the origin list, we do it backwards
    // so that the order of indices stays the same
    positionList = positionList.OrderByDescending(p => p).ToList();
    foreach (var position in positionList)
    {
        messageList.RemoveAt(position);
    }
}

How to call a MySQL stored procedure from within PHP code?

<?php
    $res = mysql_query('SELECT getTreeNodeName(1) AS result');
    if ($res === false) {
        echo mysql_errno().': '.mysql_error();
    }
    while ($obj = mysql_fetch_object($res)) {
        echo $obj->result;
    }

Blur the edges of an image or background image with CSS

<html>
<head>
<meta charset="utf-8">
<title>test</title>

<style>
#grad1 {
  height: 400px;
  width: 600px;
  background-image: url(t1.jpg);/* Select Image Hare */
}


#gradup {
  height: 100%;
  width: 100%;
  background: radial-gradient(transparent 20%, white 70%); /* Set radial-gradient to faded edges */

}
</style>

</head>

<body>
<h1>Fade Image Edge With Radial Gradient</h1>

<div id="grad1"><div id="gradup"></div></div>

</body>
</html>

Text not wrapping inside a div element

The problem in the jsfiddle is that your dummy text is all one word. If you use your lorem ipsum given in the question, then the text wraps fine.

If you want large words to be broken mid-word and wrap around, add this to your .title css:

word-wrap: break-word;

Trying to detect browser close event

Try following code works for me under Linux chrome environment. Before running make sure jquery is attached to the document.

$(document).ready(function()
{
    $(window).bind("beforeunload", function() { 
        return confirm("Do you really want to close?"); 
    });
});

For simple follow following steps:

  1. open http://jsfiddle.net/
  2. enter something into html, css or javascript box
  3. try to close tab in chrome

It should show following picture:

enter image description here

Show datalist labels but submit the actual value

The solution I use is the following:

<input list="answers" id="answer">
<datalist id="answers">
  <option data-value="42" value="The answer">
</datalist>

Then access the value to be sent to the server using JavaScript like this:

var shownVal = document.getElementById("answer").value;
var value2send = document.querySelector("#answers option[value='"+shownVal+"']").dataset.value;


Hope it helps.

In Angular, I need to search objects in an array

Saw this thread but I wanted to search for IDs that did not match my search. Code to do that:

found = $filter('filter')($scope.fish, {id: '!fish_id'}, false);

How can I determine whether a specific file is open in Windows?

Use Process Explorer from the Sysinternals Suite, the Find Handle or DLL function will let you search for the process with that file open.

Visual Studio can't 'see' my included header files

I encountered this issue, but the solutions provided didn't directly help me, so I'm sharing how I got myself into a similar situation and temporarily resolved it.

I created a new project within an existing solution and copy & pasted the Header and CPP file from another project within that solution that I needed to include in my new project through the IDE. Intellisense displayed an error suggesting it could not resolve the reference to the header file and compiling the code failed with the same error too.

After reading the posts here, I checked the project folder with Windows File Explorer and only the main.cpp file was found. For some reason, my copy and paste of the header file and CPP file were just a reference? (I assume) and did not physically copy the file into the new project file.

I deleted the files from the Project view within Visual Studio and I used File Explorer to copy the files that I needed to the project folder/directory. I then referenced the other solutions posted here to "include files in project" by showing all files and this resolved the problem.

It boiled down to the files not being physically in the Project folder/directory even though they were shown correctly within the IDE.

Please Note I understand duplicating code is not best practice and my situation is purely a learning/hobby project. It's probably in my best interest and anyone else who ended up in a similar situation to use the IDE/project/Solution setup correctly when reusing code from other projects - I'm still learning and I'll figure this out one day!

Setting dynamic scope variables in AngularJs - scope.<some_string>

Using Erik's answer, as a starting point. I found a simpler solution that worked for me.

In my ng-click function I have:

var the_string = 'lifeMeaning';
if ($scope[the_string] === undefined) {
   //Valid in my application for first usage
   $scope[the_string] = true;
} else {
   $scope[the_string] = !$scope[the_string];
}
//$scope.$apply

I've tested it with and without $scope.$apply. Works correctly without it!

How do I execute cmd commands through a batch file?

start cmd /k "your cmd command1"
start cmd /k "your cmd command2"

It works in Windows server2012 while I use these command in one batch file.

Download pdf file using jquery ajax

For those looking a more modern approach, you can use the fetch API. The following example shows how to download a PDF file. It is easily done with the following code.

fetch(url, {
    body: JSON.stringify(data),
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
})
.then(response => response.blob())
.then(response => {
    const blob = new Blob([response], {type: 'application/pdf'});
    const downloadUrl = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = downloadUrl;
    a.download = "file.pdf";
    document.body.appendChild(a);
    a.click();
})

I believe this approach to be much easier to understand than other XMLHttpRequest solutions. Also, it has a similar syntax to the jQuery approach, without the need to add any additional libraries.

Of course, I would advise checking to which browser you are developing, since this new approach won't work on IE. You can find the full browser compatibility list on the following [link][1].

Important: In this example I am sending a JSON request to a server listening on the given url. This url must be set, on my example I am assuming you know this part. Also, consider the headers needed for your request to work. Since I am sending a JSON, I must add the Content-Type header and set it to application/json; charset=utf-8, as to let the server know the type of request it will receive.

docker container ssl certificates

Mount the certs onto the Docker container using -v:

docker run -v /host/path/to/certs:/container/path/to/certs -d IMAGE_ID "update-ca-certificates"

Is it possible to convert char[] to char* in C?

You don't need to declare them as arrays if you want to use use them as pointers. You can simply reference pointers as if they were multi-dimensional arrays. Just create it as a pointer to a pointer and use malloc:

int i;
int M=30, N=25;
int ** buf;
buf = (int**) malloc(M * sizeof(int*));
for(i=0;i<M;i++)
    buf[i] = (int*) malloc(N * sizeof(int));

and then you can reference buf[3][5] or whatever.

How do I get to IIS Manager?

First of all, you need to check that the IIS is installed in your machine, for that you can go to:

Control Panel --> Add or Remove Programs --> Windows Features --> And Check if Internet Information Services is installed with at least the 'Web Administration Tools' Enabled and The 'World Wide Web Service'

If not, check it, and Press Accept to install it.

Once that is done, you need to go to Administrative Tools in Control Panel and the IIS Will be there. Or simply run inetmgr (after Win+R).

Edit: You should have something like this: enter image description here

What is LDAP used for?

Well, there are LDAP servers and the LDAP protocol. Combined, it's a data store, or a database. It's not relational, but it's just a place to store data, and it's optimized to be efficient at reads more than writes. It doesn't support transactions.

Now, it happens to be very popular for storing credentials, but that's by no means its only purpose, and not its original purpose.

Accessing JPEG EXIF rotation data in JavaScript on the client side

I upload expansion code to show photo by android camera on html as normal on some img tag with right rotaion, especially for img tag whose width is wider than height. I know this code is ugly but you don't need to install any other packages. (I used above code to obtain exif rotation value, Thank you.)

function getOrientation(file, callback) {
  var reader = new FileReader();
  reader.onload = function(e) {

    var view = new DataView(e.target.result);
    if (view.getUint16(0, false) != 0xFFD8) return callback(-2);
    var length = view.byteLength, offset = 2;
    while (offset < length) {
      var marker = view.getUint16(offset, false);
      offset += 2;
      if (marker == 0xFFE1) {
        if (view.getUint32(offset += 2, false) != 0x45786966) return callback(-1);
        var little = view.getUint16(offset += 6, false) == 0x4949;
        offset += view.getUint32(offset + 4, little);
        var tags = view.getUint16(offset, little);
        offset += 2;
        for (var i = 0; i < tags; i++)
          if (view.getUint16(offset + (i * 12), little) == 0x0112)
            return callback(view.getUint16(offset + (i * 12) + 8, little));
      }
      else if ((marker & 0xFF00) != 0xFF00) break;
      else offset += view.getUint16(offset, false);
    }
    return callback(-1);
  };
  reader.readAsArrayBuffer(file);
}

var isChanged = false;
function rotate(elem, orientation) {
    if (isIPhone()) return;

    var degree = 0;
    switch (orientation) {
        case 1:
            degree = 0;
            break;
        case 2:
            degree = 0;
            break;
        case 3:
            degree = 180;
            break;
        case 4:
            degree = 180;
            break;
        case 5:
            degree = 90;
            break;
        case 6:
            degree = 90;
            break;
        case 7:
            degree = 270;
            break;
        case 8:
            degree = 270;
            break;
    }
    $(elem).css('transform', 'rotate('+ degree +'deg)')
    if(degree == 90 || degree == 270) {
        if (!isChanged) {
            changeWidthAndHeight(elem)
            isChanged = true
        }
    } else if ($(elem).css('height') > $(elem).css('width')) {
        if (!isChanged) {
            changeWidthAndHeightWithOutMargin(elem)
            isChanged = true
        } else if(degree == 180 || degree == 0) {
            changeWidthAndHeightWithOutMargin(elem)
            if (!isChanged)
                isChanged = true
            else
                isChanged = false
        }
    }
}


function changeWidthAndHeight(elem){
    var e = $(elem)
    var width = e.css('width')
    var height = e.css('height')
    e.css('width', height)
    e.css('height', width)
    e.css('margin-top', ((getPxInt(height) - getPxInt(width))/2).toString() + 'px')
    e.css('margin-left', ((getPxInt(width) - getPxInt(height))/2).toString() + 'px')
}

function changeWidthAndHeightWithOutMargin(elem){
    var e = $(elem)
    var width = e.css('width')
    var height = e.css('height')
    e.css('width', height)
    e.css('height', width)
    e.css('margin-top', '0')
    e.css('margin-left', '0')
}

function getPxInt(pxValue) {
    return parseInt(pxValue.trim("px"))
}

function isIPhone(){
    return (
        (navigator.platform.indexOf("iPhone") != -1) ||
        (navigator.platform.indexOf("iPod") != -1)
    );
}

and then use such as

$("#banner-img").change(function () {
    var reader = new FileReader();
    getOrientation(this.files[0], function(orientation) {
        rotate($('#banner-img-preview'), orientation, 1)
    });

    reader.onload = function (e) {
        $('#banner-img-preview').attr('src', e.target.result)
        $('#banner-img-preview').css('display', 'inherit')

    };

    // read the image file as a data URL.
    reader.readAsDataURL(this.files[0]);

});

Excel to CSV with UTF8 encoding

Assuming an Windows environment, save and work with the file as usual in Excel but then open up the saved Excel file in Gnome Gnumeric (free). Save Gnome Gnumeric's spreadsheet as CSV which - for me anyway - saves it as UTF-8 CSV.

How to display list of repositories from subversion server

If you enable svn via apache and a SVNParentPath directive, you can add a SVNListParentPath On directive to your svn location to get a list of all repositories.

Your apache conf should look similar to this:

<Location /svn>
  DAV svn
  SVNParentPath         "/net/svn/repositories"
  # optional auth stuff     

  SVNListParentPath On    #  <--- Add this line to enable listing of all repos
</Location>

Read text from response

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string strResponse = reader.ReadToEnd();

Compute row average in pandas

I think this is what you are looking for:

df.drop('Region', axis=1).apply(lambda x: x.mean(), axis=1)

How to pass the button value into my onclick event function?

You can get value by using id for that element in onclick function

function dosomething(){
     var buttonValue = document.getElementById('buttonId').value;
}

JS map return object

You're very close already, you just need to return the new object that you want. In this case, the same one except with the launches value incremented by 10:

_x000D_
_x000D_
var rockets = [_x000D_
    { country:'Russia', launches:32 },_x000D_
    { country:'US', launches:23 },_x000D_
    { country:'China', launches:16 },_x000D_
    { country:'Europe(ESA)', launches:7 },_x000D_
    { country:'India', launches:4 },_x000D_
    { country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
var launchOptimistic = rockets.map(function(elem) {_x000D_
  return {_x000D_
    country: elem.country,_x000D_
    launches: elem.launches+10,_x000D_
  } _x000D_
});_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
_x000D_
_x000D_

How do I convert certain columns of a data frame to become factors?

Here's an example:

#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
  a b
1 1 2
2 2 3
3 3 4

#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL

#Convert that column to a factor
> d$a <- factor(d$a)
> d
  a b
1 1 2
2 2 3
3 3 4

#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"

You can also handle this when reading in your data. See the colClasses and stringsAsFactors parameters in e.g. readCSV().

Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.

Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.

how to open *.sdf files?

You can use SQL Compact Query Analyzer

http://sqlcequery.codeplex.com/

SQL Compact Query Analyzer is really snappy. 3 MB download, requires an install but really snappy and works.

How to add button inside input

This is the cleanest way to do in bootstrap v3.

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

how to get data from selected row from datagridview

To get the cell value, you need to read it directly from DataGridView1 using e.RowIndex and e.ColumnIndex properties.

Eg:

Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
   Dim value As Object = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value

   If IsDBNull(value) Then 
      TextBox1.Text = "" ' blank if dbnull values
   Else
      TextBox1.Text = CType(value, String)
   End If
End Sub

Changing CSS style from ASP.NET code

I find that code gets messy fast when C# code is used to modify CSS values. Perhaps a better approach is for your code to dynamically set the class attribute on the div tag and then store any specific CSS settings in the style sheet.

That might not work for your situation, but its a decent default position if you need to change the style on the fly in server side code.

Is there a function to make a copy of a PHP array to another?

Creates a copy of the ArrayObject

<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);

$fruitsArrayObject = new ArrayObject($fruits);
$fruitsArrayObject['pears'] = 4;

// create a copy of the array
$copy = $fruitsArrayObject->getArrayCopy();
print_r($copy);

?>

from https://www.php.net/manual/en/arrayobject.getarraycopy.php

Pythonic way to add datetime.date and datetime.time objects

It's in the python docs.

import datetime
datetime.datetime.combine(datetime.date(2011, 1, 1), 
                          datetime.time(10, 23))

returns

datetime.datetime(2011, 1, 1, 10, 23)

find . -type f -exec chmod 644 {} ;

Piping to xargs is a dirty way of doing that which can be done inside of find.

find . -type d -exec chmod 0755 {} \;
find . -type f -exec chmod 0644 {} \;

You can be even more controlling with other options, such as:

find . -type d -user harry -exec chown daisy {} \;

You can do some very cool things with find and you can do some very dangerous things too. Have a look at "man find", it's long but is worth a quick read. And, as always remember:

  • If you are root it will succeed.
  • If you are in root (/) you are going to have a bad day.
  • Using /path/to/directory can make things a lot safer as you are clearly defining where you want find to run.

Python Image Library fails with message "decoder JPEG not available" - PIL

This is the only way that worked for me. Installing packages and reinstalling PIL didn't work.

On ubuntu, install the required package:

sudo apt-get install libjpeg-dev

(you may also want to install libfreetype6 libfreetype6-dev zlib1g-dev to enable other decoders).

Then replace PIL with pillow:

pip uninstall PIL
pip install pillow

C++ queue - simple example

std::queue<myclass*> my_queue; will do the job.

See here for more information on this container.

Creating an iframe with given HTML dynamically

Do this

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

console.log(frame_win);
...

getIframeWindow is defined here

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

C# Enum - How to Compare Value

use this

if (userProfile.AccountType == AccountType.Retailer)
{
     ...
}

If you want to get int from your AccountType enum and compare it (don't know why) do this:

if((int)userProfile.AccountType == 1)
{ 
     ...
}

Objet reference not set to an instance of an object exception is because your userProfile is null and you are getting property of null. Check in debug why it's not set.

EDIT (thanks to @Rik and @KonradMorawski) :

Maybe you can do some check before:

if(userProfile!=null)
{
}

or

if(userProfile==null)
{
   throw new ArgumentNullException(nameof(userProfile)); // or any other exception
}

How to reload a page using Angularjs?

You need $route defined in your module and change the JS to this.

$scope.backLinkClick = function () {
  window.location.reload(); 
};

that works fine for me.

How to generate a random integer number from within a range

All the answers so far are mathematically wrong. Returning rand() % N does not uniformly give a number in the range [0, N) unless N divides the length of the interval into which rand() returns (i.e. is a power of 2). Furthermore, one has no idea whether the moduli of rand() are independent: it's possible that they go 0, 1, 2, ..., which is uniform but not very random. The only assumption it seems reasonable to make is that rand() puts out a Poisson distribution: any two nonoverlapping subintervals of the same size are equally likely and independent. For a finite set of values, this implies a uniform distribution and also ensures that the values of rand() are nicely scattered.

This means that the only correct way of changing the range of rand() is to divide it into boxes; for example, if RAND_MAX == 11 and you want a range of 1..6, you should assign {0,1} to 1, {2,3} to 2, and so on. These are disjoint, equally-sized intervals and thus are uniformly and independently distributed.

The suggestion to use floating-point division is mathematically plausible but suffers from rounding issues in principle. Perhaps double is high-enough precision to make it work; perhaps not. I don't know and I don't want to have to figure it out; in any case, the answer is system-dependent.

The correct way is to use integer arithmetic. That is, you want something like the following:

#include <stdlib.h> // For random(), RAND_MAX

// Assumes 0 <= max <= RAND_MAX
// Returns in the closed interval [0, max]
long random_at_most(long max) {
  unsigned long
    // max <= RAND_MAX < ULONG_MAX, so this is okay.
    num_bins = (unsigned long) max + 1,
    num_rand = (unsigned long) RAND_MAX + 1,
    bin_size = num_rand / num_bins,
    defect   = num_rand % num_bins;

  long x;
  do {
   x = random();
  }
  // This is carefully written not to overflow
  while (num_rand - defect <= (unsigned long)x);

  // Truncated division is intentional
  return x/bin_size;
}

The loop is necessary to get a perfectly uniform distribution. For example, if you are given random numbers from 0 to 2 and you want only ones from 0 to 1, you just keep pulling until you don't get a 2; it's not hard to check that this gives 0 or 1 with equal probability. This method is also described in the link that nos gave in their answer, though coded differently. I'm using random() rather than rand() as it has a better distribution (as noted by the man page for rand()).

If you want to get random values outside the default range [0, RAND_MAX], then you have to do something tricky. Perhaps the most expedient is to define a function random_extended() that pulls n bits (using random_at_most()) and returns in [0, 2**n), and then apply random_at_most() with random_extended() in place of random() (and 2**n - 1 in place of RAND_MAX) to pull a random value less than 2**n, assuming you have a numerical type that can hold such a value. Finally, of course, you can get values in [min, max] using min + random_at_most(max - min), including negative values.

typedef struct vs struct definitions

The following code creates an anonymous struct with the alias myStruct:

typedef struct{
    int one;
    int two;
} myStruct;

You can't refer it without the alias because you don't specify an identifier for the structure.

How can I change the class of an element with jQuery>

Use jQuery's

$(this).addClass('showhideExtra_up_hover');

and

$(this).addClass('showhideExtra_down_hover');

Java - Convert image to Base64

To begin with, this line of code:

while ((bytesRead = fis.read(byteArray)) != -1)

is equivalent to

while ((bytesRead = fis.read(byteArray, 0, byteArray.length)) != -1)

So it's writing into the byteArray from offset 0, rather than from where you wrote to before.

You need something like this:

int offset = 0;
int bytesRead = 0;

while ((bytesRead = fis.read(byteArray, offset, byteArray.length - offset) != -1) {
    offset += bytesRead;
}

After you have read the data (bytes) in then, you can convert it to Base64.

There are bigger problems though - you're using a fixed size array, so files that are too big won't be converted correctly, and the code is tricker because of it too.

I would ditch the byte array and go with something like this:

ByteArrayOutputStream buffer = new ByteArrayOutputStream();
// commons-io IOUtils
IOUtils.copy(fis, buffer);
byte [] data = buffer.toByteArray();
Base64.encode(data);

Or condense it further as Thilo has with FileUtils.

Auto-Submit Form using JavaScript

A simple solution for a delayed auto submit:

<body onload="setTimeout(function() { document.frm1.submit() }, 5000)">
   <form action="https://www.google.com" name="frm1">
      <input type="hidden" name="q" value="Hello world" />
   </form>
</body>

Get all dates between two dates in SQL Server

I listed dates of 2 Weeks later. You can use variable @period OR function datediff(dd, @date_start, @date_end)

declare @period INT, @date_start datetime, @date_end datetime, @i int;

set @period = 14
set @date_start = convert(date,DATEADD(D, -@period, curent_timestamp))
set @date_end = convert(date,current_timestamp)
set @i = 1

create table #datesList(dts datetime)
insert into #datesList values (@date_start)
while @i <= @period
    Begin
        insert into #datesList values (dateadd(d,@i,@date_start))
        set @i = @i + 1
    end
select cast(dts as DATE) from #datesList
Drop Table #datesList

Angular 2 - Redirect to an external URL and open in a new tab

we can use target = blank to open in new tab

 <a href="https://www.google.co.in/" target="blank">click Here </a>

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

I just add an answear because I spent hours trying to solve the same symptoms (but different issue):

A possible cause is a x86 dll in a 64 bits app pool, the solution is to enable 32 bits apps in the application pool settings.

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

In order to avoid having to fully specify the git push command you could alternatively modify your git config file:

[remote "gerrit"]
    url = https://your.gerrit.repo:44444/repo
    fetch = +refs/heads/master:refs/remotes/origin/master
    push = refs/heads/master:refs/for/master

Now you can simply:

git fetch gerrit
git push gerrit

This is according to Gerrit

SQL time difference between two dates result in hh:mm:ss

declare @StartDate datetime, @EndDate datetime

select @StartDate = '10/01/2012 08:40:18.000',@EndDate='10/04/2012 09:52:48.000'

select convert(varchar(5),DateDiff(s, @startDate, @EndDate)/3600)+':'+convert(varchar(5),DateDiff(s, @startDate, @EndDate)%3600/60)+':'+convert(varchar(5),(DateDiff(s, @startDate, @EndDate)%60)) as [hh:mm:ss]

This query will helpful to you.

Round integers to the nearest 10

This function will round either be order of magnitude (right to left) or by digits the same way that format treats floating point decimal places (left to right:

def intround(n, p):
    ''' rounds an intger. if "p"<0, p is a exponent of 10; if p>0, left to right digits '''
    if p==0: return n
    if p>0:  
        ln=len(str(n))  
        p=p-ln+1 if n<0 else p-ln
    return (n + 5 * 10**(-p-1)) // 10**-p * 10**-p

>>> tgt=5555555
>>> d=2
>>> print('\t{} rounded to {} places:\n\t{} right to left \n\t{} left to right'.format(
        tgt,d,intround(tgt,-d), intround(tgt,d))) 

Prints

5555555 rounded to 2 places:
5555600 right to left 
5600000 left to right

You can also use Decimal class:

import decimal
import sys

def ri(i, prec=6):
    ic=long if sys.version_info.major<3 else int
    with decimal.localcontext() as lct:
        if prec>0:
            lct.prec=prec
        else:
            lct.prec=len(str(decimal.Decimal(i)))+prec  
        n=ic(decimal.Decimal(i)+decimal.Decimal('0'))
    return n

On Python 3 you can reliably use round with negative places and get a rounded integer:

def intround2(n, p):
    ''' will fail with larger floating point numbers on Py2 and require a cast to an int '''
    if p>0:
        return round(n, p-len(str(n))+1)
    else:
        return round(n, p)    

On Python 2, round will fail to return a proper rounder integer on larger numbers because round always returns a float:

>>> round(2**34, -5)
17179900000.0                     # OK
>>> round(2**64, -5)
1.84467440737096e+19              # wrong 

The other 2 functions work on Python 2 and 3

Using request.setAttribute in a JSP page

The reply by Phil Sacre was correct however the session shouldn't be used just for the hell of it. You should only use this for values which really need to live for the lifetime of the session, such as a user login. It's common to see people overuse the session and run into more issues, especially when dealing with a collection or when users return to a page they previously visited only to find they have values still remaining from a previous visit. A smart program minimizes the scope of variables as much as possible, a bad one uses session too much.

How do I remove the space between inline/inline-block elements?

Try this snippet:

span {
    display: inline-block;
    width: 100px;
    background: blue;
    font-size: 30px;
    color: white;
    text-align: center;
    margin-right: -3px;
}

Working demo: http://jsfiddle.net/dGHFV/2784/

Is there a way to provide named parameters in a function call in JavaScript?

Trying Node-6.4.0 ( process.versions.v8 = '5.0.71.60') and Node Chakracore-v7.0.0-pre8 and then Chrome-52 (V8=5.2.361.49), I've noticed that named parameters are almost implemented, but that order has still precedence. I can't find what the ECMA standard says.

>function f(a=1, b=2){ console.log(`a=${a} + b=${b} = ${a+b}`) }

> f()
a=1 + b=2 = 3
> f(a=5)
a=5 + b=2 = 7
> f(a=7, b=10)
a=7 + b=10 = 17

But order is required!! Is it the standard behaviour?

> f(b=10)
a=10 + b=2 = 12

ImageMagick security policy 'PDF' blocking conversion

Alternatively you can use img2pdf to convert images to pdf. Install it on Debian or Ubuntu with:

sudo apt install img2pdf

Convert one or more images to pdf:

img2pdf img.jpg -o output.pdf

It uses a different mechanism than imagemagick to embed the image into the pdf. When possible Img2pdf embeds the image directly into the pdf, without decoding and recoding the image.

Get div to take up 100% body height, minus fixed-height header and footer

The new, modern way to do this is to calculate the vertical height by subtracting the height of both the header and the footer from the vertical-height of the viewport.

//CSS
header { 
  height: 50px;
}
footer { 
  height: 50px;
}
#content { 
  height: calc(100vh - 50px - 50px);
}

jQuery / Javascript code check, if not undefined

I generally like the shorthand version:

if (!!wlocation) { window.location = wlocation; }

Oracle date to string conversion

If your column is of type DATE (as you say), then you don't need to convert it into a string first (in fact you would convert it implicitly to a string first, then explicitly to a date and again explicitly to a string):

SELECT TO_CHAR(COL1, 'mm/dd/yyyy') FROM TABLE1

The date format your seeing for your column is an artifact of the tool your using (TOAD, SQL Developer etc.) and it's language settings.

Edittext change border color with shape.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
     android:shape="rectangle">
     <solid android:color="#ffffff" />
     <stroke android:width="1dip" android:color="#ff9900" />
 </selector>

You have to remove > this from selector root tag, like below

   <selector xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">

As well as move your code to shape from selector.

Moment.js transform to date object

The question is a little obscure. I ll do my best to explain this. First you should understand how to use moment-timezone. According to this answer here TypeError: moment().tz is not a function, you have to import moment from moment-timezone instead of the default moment (ofcourse you will have to npm install moment-timezone first!). For the sake of clarity,

const moment=require('moment-timezone')//import from moment-timezone

Now in order to use the timezone feature, use moment.tz("date_string/moment()","time_zone") (visit https://momentjs.com/timezone/ for more details). This function will return a moment object with a particular time zone. For the sake of clarity,

var newYork= moment.tz("2014-06-01 12:00", "America/New_York");/*this code will consider NewYork as the timezone.*/

Now when you try to convert newYork (the moment object) with moment's toDate() (ISO 8601 format conversion) you will get the time of Greenwich,UK. For more details, go through this article https://www.nhc.noaa.gov/aboututc.shtml, about UTC. However if you just want your local time in this format (New York time, according to this example), just add the method .utc(true) ,with the arg true, to your moment object. For the sake of clarity,

newYork.toDate()//will give you the Greenwich ,UK, time.

newYork.utc(true).toDate()//will give you the local time. according to the moment.tz method arg we specified above, it is 12:00.you can ofcourse change this by using moment()

In short, moment.tz considers the time zone you specify and compares your local time with the time in Greenwich to give you a result. I hope this was useful.

How to output MySQL query results in CSV format?

The following bash script works for me. It optionally also gets the schema for the requested tables.

#!/bin/bash
#
# export mysql data to CSV
#https://stackoverflow.com/questions/356578/how-to-output-mysql-query-results-in-csv-format
#

#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'
red='\033[0;31m'
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'

#
# a colored message 
#   params:
#     1: l_color - the color of the message
#     2: l_msg - the message to display
#
color_msg() {
  local l_color="$1"
  local l_msg="$2"
  echo -e "${l_color}$l_msg${endColor}"
}


#
# error
#
# show the given error message on stderr and exit
#
#   params:
#     1: l_msg - the error message to display
#
error() {
  local l_msg="$1"
  # use ansi red for error
  color_msg $red "Error:" 1>&2
  color_msg $red "\t$l_msg" 1>&2
  usage
}

#
# display usage 
#
usage() {
  echo "usage: $0 [-h|--help]" 1>&2
  echo "               -o  | --output      csvdirectory"    1>&2
  echo "               -d  | --database    database"   1>&2
  echo "               -t  | --tables      tables"     1>&2
  echo "               -p  | --password    password"   1>&2
  echo "               -u  | --user        user"       1>&2
  echo "               -hs | --host        host"       1>&2
  echo "               -gs | --get-schema"             1>&2
  echo "" 1>&2
  echo "     output: output csv directory to export mysql data into" 1>&2
  echo "" 1>&2
  echo "         user: mysql user" 1>&2
  echo "     password: mysql password" 1>&2
  echo "" 1>&2
  echo "     database: target database" 1>&2
  echo "       tables: tables to export" 1>&2
  echo "         host: host of target database" 1>&2
  echo "" 1>&2
  echo "  -h|--help: show help" 1>&2
  exit 1
}

#
# show help 
#
help() {
  echo "$0 Help" 1>&2
  echo "===========" 1>&2
  echo "$0 exports a csv file from a mysql database optionally limiting to a list of tables" 1>&2
  echo "   example: $0 --database=cms --user=scott --password=tiger  --tables=person --output person.csv" 1>&2
  echo "" 1>&2
  usage
}

domysql() {
  mysql --host $host -u$user --password=$password $database
}

getcolumns() {
  local l_table="$1"
  echo "describe $l_table" | domysql | cut -f1 | grep -v "Field" | grep -v "Warning" | paste -sd "," - 2>/dev/null
}

host="localhost"
mysqlfiles="/var/lib/mysql-files/"

# parse command line options
while true; do
  #echo "option $1"
  case "$1" in
    # options without arguments
    -h|--help) usage;;
    -d|--database)     database="$2" ; shift ;;
    -t|--tables)       tables="$2" ; shift ;;
    -o|--output)       csvoutput="$2" ; shift ;;
    -u|--user)         user="$2" ; shift ;;
    -hs|--host)        host="$2" ; shift ;;
    -p|--password)     password="$2" ; shift ;;
    -gs|--get-schema)  option="getschema";; 
    (--) shift; break;;
    (-*) echo "$0: error - unrecognized option $1" 1>&2; usage;;
    (*) break;;
  esac
  shift
done

# checks
if [ "$csvoutput" == "" ]
then
  error "ouput csv directory not set"
fi
if [ "$database" == "" ]
then
  error "mysql database not set"
fi
if [ "$user" == "" ]
then
  error "mysql user not set"
fi
if [ "$password" == "" ]
then
  error "mysql password not set"
fi

color_msg $blue "exporting tables of database $database"
if [ "$tables" = "" ]
then
tables=$(echo "show tables" | domysql)
fi

case $option in
  getschema) 
   rm $csvoutput$database.schema
   for table in $tables
   do
     color_msg $blue "getting schema for $table"
     echo -n "$table:" >> $csvoutput$database.schema
     getcolumns $table >> $csvoutput$database.schema
   done  
   ;;
  *)
for table in $tables
do
  color_msg $blue "exporting table $table"
  cols=$(grep "$table:" $csvoutput$database.schema | cut -f2 -d:)
  if [  "$cols" = "" ]
  then
    cols=$(getcolumns $table)
  fi
  ssh $host rm $mysqlfiles/$table.csv
cat <<EOF | mysql --host $host -u$user --password=$password $database 
SELECT $cols FROM $table INTO OUTFILE '$mysqlfiles$table.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
EOF
  scp $host:$mysqlfiles/$table.csv $csvoutput$table.csv.raw
  (echo "$cols"; cat $csvoutput$table.csv.raw) > $csvoutput$table.csv
  rm $csvoutput$table.csv.raw
done
  ;;
esac

Check element CSS display with JavaScript

If the style was declared inline or with JavaScript, you can just get at the style object:

return element.style.display === 'block';

Otherwise, you'll have to get the computed style, and there are browser inconsistencies. IE uses a simple currentStyle object, but everyone else uses a method:

return element.currentStyle ? element.currentStyle.display :
                              getComputedStyle(element, null).display;

The null was required in Firefox version 3 and below.

How to convert string to integer in PowerShell

You can specify the type of a variable before it to force its type. It's called (dynamic) casting (more information is here):

$string = "1654"
$integer = [int]$string

$string + 1
# Outputs 16541

$integer + 1
# Outputs 1655

As an example, the following snippet adds, to each object in $fileList, an IntVal property with the integer value of the Name property, then sorts $fileList on this new property (the default is ascending), takes the last (highest IntVal) object's IntVal value, increments it and finally creates a folder named after it:

# For testing purposes
#$fileList = @([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })
# OR
#$fileList = New-Object -TypeName System.Collections.ArrayList
#$fileList.AddRange(@([PSCustomObject]@{ Name = "11" }, [PSCustomObject]@{ Name = "2" }, [PSCustomObject]@{ Name = "1" })) | Out-Null

$highest = $fileList |
    Select-Object *, @{ n = "IntVal"; e = { [int]($_.Name) } } |
    Sort-Object IntVal |
    Select-Object -Last 1

$newName = $highest.IntVal + 1

New-Item $newName -ItemType Directory

Sort-Object IntVal is not needed so you can remove it if you prefer.

[int]::MaxValue = 2147483647 so you need to use the [long] type beyond this value ([long]::MaxValue = 9223372036854775807).

How can I insert data into a MySQL database?

Here is OOP:

import MySQLdb


class Database:

    host = 'localhost'
    user = 'root'
    password = '123'
    db = 'test'

    def __init__(self):
        self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db)
        self.cursor = self.connection.cursor()

    def insert(self, query):
        try:
            self.cursor.execute(query)
            self.connection.commit()
        except:
            self.connection.rollback()



    def query(self, query):
        cursor = self.connection.cursor( MySQLdb.cursors.DictCursor )
        cursor.execute(query)

        return cursor.fetchall()

    def __del__(self):
        self.connection.close()


if __name__ == "__main__":

    db = Database()

    #CleanUp Operation
    del_query = "DELETE FROM basic_python_database"
    db.insert(del_query)

    # Data Insert into the table
    query = """
        INSERT INTO basic_python_database
        (`name`, `age`)
        VALUES
        ('Mike', 21),
        ('Michael', 21),
        ('Imran', 21)
        """

    # db.query(query)
    db.insert(query)

    # Data retrieved from the table
    select_query = """
        SELECT * FROM basic_python_database
        WHERE age = 21
        """

    people = db.query(select_query)

    for person in people:
        print "Found %s " % person['name']

How do I syntax check a Bash script without running it?

Time changes everything. Here is a web site which provide online syntax checking for shell script.

I found it is very powerful detecting common errors.

enter image description here

About ShellCheck

ShellCheck is a static analysis and linting tool for sh/bash scripts. It's mainly focused on handling typical beginner and intermediate level syntax errors and pitfalls where the shell just gives a cryptic error message or strange behavior, but it also reports on a few more advanced issues where corner cases can cause delayed failures.

Haskell source code is available on GitHub!

Git ignore file for Xcode projects

A Structure of a standerd .gitignore file for Xcode project >

.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
Icon?
ehthumbs.db
Thumbs.db
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
!default.xcworkspace
xcuserdata
profile
*.moved-aside
DerivedData
.idea/

Python unittest passing arguments

So the doctors here that are saying "You say that hurts? Then don't do that!" are probably right. But if you really want to, here's one way of passing arguments to a unittest test:

import sys
import unittest

class MyTest(unittest.TestCase):
    USERNAME = "jemima"
    PASSWORD = "password"

    def test_logins_or_something(self):
        print('username : {}'.format(self.USERNAME))
        print('password : {}'.format(self.PASSWORD))


if __name__ == "__main__":
    if len(sys.argv) > 1:
        MyTest.USERNAME = sys.argv.pop()
        MyTest.PASSWORD = sys.argv.pop()
    unittest.main()

that will let you run with:

python mytests.py ausername apassword

You need the argv.pops so your command line params don't mess with unittest's own...

[update] The other thing you might want to look into is using environment variables:

import os
import unittest

class MyTest(unittest.TestCase):
    USERNAME = "jemima"
    PASSWORD = "password"

    def test_logins_or_something(self):
        print('username : {}'.format(self.USERNAME))
        print('password : {}'.format(self.PASSWORD))


if __name__ == "__main__":
    MyTest.USERNAME = os.environ.get('TEST_USERNAME', MyTest.USERNAME)            
    MyTest.PASSWORD = os.environ.get('TEST_PASSWORD', MyTest.PASSWORD)
    unittest.main()

That will let you run with:

TEST_USERNAME=ausername TEST_PASSWORD=apassword python mytests.py

and it has the advantage that you're not messing with unittest's own argument parsing. downside is it won't work quite like that on Windows...

Solving Quadratic Equation

give input through your keyboard

a=float(input("enter the 1st number : "))
b=float(input("enter the 2nd number : "))
c=float(input("enter the 3rd number : "))

calculate the discriminant

d = (b**2) - (4*a*c)

possible solution are

sol_1 = (-b-(0.5**d))/(2*a)
sol_2 = (-b+(0.5**d))/(2*a)

print the result

print('The solution are  %0.f,%0.f'%(sol_1,sol_2))

How to find all combinations of coins when given some dollar value

Java solution

import java.util.Arrays;
import java.util.Scanner;


public class nCents {



public static void main(String[] args) {

    Scanner input=new Scanner(System.in);
    int cents=input.nextInt();
    int num_ways [][] =new int [5][cents+1];

    //putting in zeroes to offset
    int getCents[]={0 , 0 , 5 , 10 , 25};
    Arrays.fill(num_ways[0], 0);
    Arrays.fill(num_ways[1], 1);

    int current_cent=0;
    for(int i=2;i<num_ways.length;i++){

        current_cent=getCents[i];

        for(int j=1;j<num_ways[0].length;j++){
            if(j-current_cent>=0){
                if(j-current_cent==0){
                    num_ways[i][j]=num_ways[i-1][j]+1;
                }else{
                    num_ways[i][j]=num_ways[i][j-current_cent]+num_ways[i-1][j];
                }
            }else{
                num_ways[i][j]=num_ways[i-1][j];
            }


        }


    }



    System.out.println(num_ways[num_ways.length-1][num_ways[0].length-1]);

}

}

Angular HttpClient "Http failure during parsing"

You should also check you JSON (not in DevTools, but on a backend). Angular HttpClient having a hard time parsing JSON with \0 characters and DevTools will ignore then, so it's quite hard to spot in Chrome.

Based on this article

open read and close a file in 1 line of code

Using CPython, your file will be closed immediately after the line is executed, because the file object is immediately garbage collected. There are two drawbacks, though:

  1. In Python implementations different from CPython, the file often isn't immediately closed, but rather at a later time, beyond your control.

  2. In Python 3.2 or above, this will throw a ResourceWarning, if enabled.

Better to invest one additional line:

with open('pagehead.section.htm','r') as f:
    output = f.read()

This will ensure that the file is correctly closed under all circumstances.

Spring Boot application in eclipse, the Tomcat connector configured to listen on port XXXX failed to start

Find the process and terminate it. On Windows do a Control+Alt+Delete and then find the "Java(TM) Platform SE Binary" process under the Processes Tab. For example: enter image description here

On Ubuntu, you can use "ps aux | grep java" to find the process and "kill -9 PID_NUMBER" to kill the process.

OR

If you're using a Spring boot application, go to application.properties and add this:

server.port = 8081

Possible reason for NGINX 499 error codes

One of the reasons for this behaviour could be you are using http for uwsgi instead of socket. Use the below command if you are using uwsgi directly.

uwsgi --socket :8080 --module app-name.wsgi

Same command in .ini file is

chdir = /path/to/app/folder
socket = :8080
module = app-name.wsgi

How do I run a terminal inside of Vim?

I use this now, you may can try. VimShell

AngularJS Folder Structure

I like this entry about angularjs structure

It's written by one of the angularjs developers, so should give you a good insight

Here's an excerpt:

root-app-folder
+-- index.html
+-- scripts
¦   +-- controllers
¦   ¦   +-- main.js
¦   ¦   +-- ...
¦   +-- directives
¦   ¦   +-- myDirective.js
¦   ¦   +-- ...
¦   +-- filters
¦   ¦   +-- myFilter.js
¦   ¦   +-- ...
¦   +-- services
¦   ¦   +-- myService.js
¦   ¦   +-- ...
¦   +-- vendor
¦   ¦   +-- angular.js
¦   ¦   +-- angular.min.js
¦   ¦   +-- es5-shim.min.js
¦   ¦   +-- json3.min.js
¦   +-- app.js
+-- styles
¦   +-- ...
+-- views
    +-- main.html
    +-- ...

Java: Simplest way to get last word in a string

Here is a way to do it using String's built-in regex capabilities:

String lastWord = sentence.replaceAll("^.*?(\\w+)\\W*$", "$1");

The idea is to match the whole string from ^ to $, capture the last sequence of \w+ in a capturing group 1, and replace the whole sentence with it using $1.

Demo.

How to call a Python function from Node.js

I'm on node 10 and child process 1.0.2. The data from python is a byte array and has to be converted. Just another quick example of making a http request in python.

node

const process = spawn("python", ["services/request.py", "https://www.google.com"])

return new Promise((resolve, reject) =>{
    process.stdout.on("data", data =>{
        resolve(data.toString()); // <------------ by default converts to utf-8
    })
    process.stderr.on("data", reject)
})

request.py

import urllib.request
import sys

def karl_morrison_is_a_pedant():   
    response = urllib.request.urlopen(sys.argv[1])
    html = response.read()
    print(html)
    sys.stdout.flush()

karl_morrison_is_a_pedant()

p.s. not a contrived example since node's http module doesn't load a few requests I need to make

Batch Files - Error Handling

Other than ERRORLEVEL, batch files have no error handling. You'd want to look at a more powerful scripting language. I've been moving code to PowerShell.

The ability to easily use .Net assemblies and methods was one of the major reasons I started with PowerShell. The improved error handling was another. The fact that Microsoft is now requiring all of its server programs (Exchange, SQL Server etc) to be PowerShell drivable was pure icing on the cake.

Right now, it looks like any time invested in learning and using PowerShell will be time well spent.

Build Android Studio app via command line

Android Studio automatically creates a Gradle wrapper in the root of your project, which is how it invokes Gradle. The wrapper is basically a script that calls through to the actual Gradle binary and allows you to keep Gradle up to date, which makes using version control easier. To run a Gradle command, you can simply use the gradlew script found in the root of your project (or gradlew.bat on Windows) followed by the name of the task you want to run. For instance, to build a debug version of your Android application, you can run ./gradlew assembleDebug from the root of your repository. In a default project setup, the resulting apk can then be found in app/build/outputs/apk/app-debug.apk. On a *nix machine, you can also just run find . -name '*.apk' to find it, if it's not there.

Why is my power operator (^) not working?

There is no way to use the ^ (Bitwise XOR) operator to calculate the power of a number. Therefore, in order to calculate the power of a number we have two options, either we use a while loop or the pow() function.

1. Using a while loop.

#include <stdio.h>

int main() {

    int base, expo;
    long long result = 1;

    printf("Enter a base no.: ");
    scanf("%d", &base);

    printf("Enter an exponent: ");
    scanf("%d", &expo);

    while (expo != 0) {
        result *= base;
        --expo;
    }

    printf("Answer = %lld", result);
    return 0;
}    
             

2. Using the pow() function

#include <math.h>
#include <stdio.h>

int main() {

    double base, exp, result;

    printf("Enter a base number: ");
    scanf("%lf", &base);

    printf("Enter an exponent: ");
    scanf("%lf", &exp);

    // calculate the power of our input numbers
    result = pow(base, exp);

    printf("%.1lf^%.1lf = %.2lf", base, exp, result);

    return 0;
}
     

Laravel: Validation unique on update

an even simpler solution tested with version 5.2

in your model

// validator rules
public static $rules = array(
    ...
    'email_address' => 'email|required|unique:users,id'
);

Import Script from a Parent Directory

You don't import scripts in Python you import modules. Some python modules are also scripts that you can run directly (they do some useful work at a module-level).

In general it is preferable to use absolute imports rather than relative imports.

toplevel_package/
+-- __init__.py
+-- moduleA.py
+-- subpackage
    +-- __init__.py
    +-- moduleB.py

In moduleB:

from toplevel_package import moduleA

If you'd like to run moduleB.py as a script then make sure that parent directory for toplevel_package is in your sys.path.

Keystore change passwords

Changing keystore password

$ keytool -storepasswd -keystore keystorename
Enter keystore password:  <old password>
New keystore password: <new password>
Re-enter new keystore password: <new password>

Changing keystore alias password

$keytool -keypasswd -keystore keystorename -alias aliasname
Enter keystore password:  
New key password for <aliasname>: 
Re-enter new key password for <aliasname>:

Note:

**Keystorename**: name of your keystore(with path if you are indifferent folder) 
**aliasname**: alias name you used when creating (if name has space you can use \) 
for example: $keytool -keypasswd -keystore keystorename -alias stop\ watch

Using jquery to get all checked checkboxes with a certain class name

I'm not sure if it helps for your particular case, and I'm not sure if in your case, the checkboxes you want to include only are all part of a single form or div or table, but you can always select all checkboxes inside a specific element. For example:

<ul id="selective">
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
</ul>

Then, using the following jQuery, it ONLY goes through the checkboxes within that UL with id="selective":

$('#selective input:checkbox').each(function () {
 var sThisVal = (this.checked ? $(this).val() : "");
});

what is numeric(18, 0) in sql server 2008 r2

This page explains it pretty well.

As a numeric the allowable range that can be stored in that field is -10^38 +1 to 10^38 - 1.

The first number in parentheses is the total number of digits that will be stored. Counting both sides of the decimal. In this case 18. So you could have a number with 18 digits before the decimal 18 digits after the decimal or some combination in between.

The second number in parentheses is the total number of digits to be stored after the decimal. Since in this case the number is 0 that basically means only integers can be stored in this field.

So the range that can be stored in this particular field is -(10^18 - 1) to (10^18 - 1)

Or -999999999999999999 to 999999999999999999 Integers only

nano error: Error opening terminal: xterm-256color

I can confirm this is a terminfo issue. This is what worked for me. SSH in to the remote machine and run

 sudo apt-get install ncurses-term

Boom. Problem solved.

How to handle errors with boto3?

Following @armod's update about exceptions being added right on client objects. I'll show how you can see all exceptions defined for your client class.

Exceptions are generated dynamically when you create your client with session.create_client() or boto3.client(). Internally it calls method botocore.errorfactory.ClientExceptionsFactory._create_client_exceptions() and fills client.exceptions field with constructed exception classes.

All class names are available in client.exceptions._code_to_exception dictionary, so you can list all types with following snippet:

client = boto3.client('s3')

for ex_code in client.exceptions._code_to_exception:
    print(ex_code)

Hope it helps.

Which is the correct C# infinite loop, for (;;) or while (true)?

The C# compiler will transform both

for(;;)
{
    // ...
}

and

while (true)
{
    // ...
}

into

{
    :label
    // ...
    goto label;
}

The CIL for both is the same. Most people find while(true) to be easier to read and understand. for(;;) is rather cryptic.

Source:

I messed a little more with .NET Reflector, and I compiled both loops with the "Optimize Code" on in Visual Studio.

Both loops compile into (with .NET Reflector):

Label_0000:
    goto Label_0000;

Raptors should attack soon.

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

Might be an overkill in this case, but if the opportunity shows moment.js is just awesome!

Moment.js is a javascript datetime library, to use it for such scenario, you'd do:

moment(yourdate).fromNow()

http://momentjs.com/docs/#/displaying/fromnow/

2018 addendum: Luxon is a new modern library and might be worth a look!

nodejs mongodb object id to string

try this: objectId.str;

see doc.

Select the values of one property on all objects of an array in PowerShell

Caution, member enumeration only works if the collection itself has no member of the same name. So if you had an array of FileInfo objects, you couldn't get an array of file lengths by using

 $files.length # evaluates to array length

And before you say "well obviously", consider this. If you had an array of objects with a capacity property then

 $objarr.capacity

would work fine UNLESS $objarr were actually not an [Array] but, for example, an [ArrayList]. So before using member enumeration you might have to look inside the black box containing your collection.

(Note to moderators: this should be a comment on rageandqq's answer but I don't yet have enough reputation.)

Where is NuGet.Config file located in Visual Studio project?

I have created an answer for this post that might help: https://stackoverflow.com/a/63816822/2399164

Summary:

I am a little late to the game but I believe I found a simple solution to this problem...

  1. Create a "NuGet.Config" file in the same directory as your .sln
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
    <add key="{{CUSTOM NAME}}" value="{{CUSTOM SOURCE}}" />
  </packageSources>
  <packageRestore>
    <add key="enabled" value="True" />
    <add key="automatic" value="True" />
  </packageRestore>
  <bindingRedirects>
    <add key="skip" value="False" />
  </bindingRedirects>
  <packageManagement>
    <add key="format" value="0" />
    <add key="disabled" value="False" />
  </packageManagement>
</configuration>
  1. That is it! Create your "Dockerfile" here as well

  2. Run docker build with your Dockerfile and all will get resolved

What's the environment variable for the path to the desktop?

Quite old topic. But I want to give my 2 cents...

I've slightly modified tomasz86 solution, to look in the old style "Shell Folders" instead of "User Shell Folders", so i don't need to expand the envvar %userprofile%

Also there is no dependency from powershell/vbscript/etc....

for /f "usebackq tokens=2,3*" %%A in (`REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" /v "Desktop"`) do if %%A==REG_SZ  set desktopdir=%%B
echo %desktopdir%

Hope it helps.

Java 8 method references: provide a Supplier capable of supplying a parameterized result

It appears that you can throw only RuntimeException from the method orElseThrow. Otherwise you will get an error message like MyException cannot be converted to java.lang.RuntimeException

Update:- This was an issue with an older version of JDK. I don't see this issue with the latest versions.

Center an element in Bootstrap 4 Navbar

make new style

.container {
    position: relative;
}
.center-nav {
    position: absolute;
    left: 0;
    right: 0;
    margin: 0 auto;
    width: auto;
    max-width: 200px;
    text-align: center;
}
.center-nav li{
  text-align: center;
  width:100%;
}

Replace website name UL with below

<ul class="nav navbar-nav center-nav">
        <li class="nav-item"><a class="nav-link" href="#">Website Name</a></li>
 </ul>

Hope this helps..

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

The default shell for the RUN instruction is ["/bin/sh", "-c"].

RUN "source file"      # translates to: RUN /bin/sh -c "source file"

Using SHELL instruction, you can change default shell for subsequent RUN instructions in Dockerfile:

SHELL ["/bin/bash", "-c"] 

Now, default shell has changed and you don't need to explicitly define it in every RUN instruction

RUN "source file"    # now translates to: RUN /bin/bash -c "source file"

Additional Note: You could also add --login option which would start a login shell. This means ~/.bachrc for example would be read and you don't need to source it explicitly before your command

MySql : Grant read only options?

Note for MySQL 8 it's different

You need to do it in two steps:

CREATE USER 'readonly_user'@'localhost' IDENTIFIED BY 'some_strong_password';
GRANT SELECT, SHOW VIEW ON *.* TO 'readonly_user'@'localhost';
flush privileges;

Python Iterate Dictionary by Index

You can iterate over keys and get values by keys:

for key in dict.iterkeys():
    print key, dict[key]

You can iterate over keys and corresponding values:

for key, value in dict.iteritems():
    print key, value

You can use enumerate if you want indexes (remember that dictionaries don't have an order):

>>> for index, key in enumerate(dict):
...     print index, key
... 
0 orange
1 mango
2 apple
>>> 

What MySQL data type should be used for Latitude/Longitude with 8 decimal places?

in laravel used decimal column type for migration

$table->decimal('latitude', 10, 8);
$table->decimal('longitude', 11, 8);

for more information see available column type

With block equivalent in C#?

As the Visual C# Program Manager linked above says, there are limited situations where the With statement is more efficient, the example he gives when it is being used as a shorthand to repeatedly access a complex expression.

Using an extension method and generics you can create something that is vaguely equivalent to a With statement, by adding something like this:

    public static T With<T>(this T item, Action<T> action)
    {
        action(item);
        return item;
    }

Taking a simple example of how it could be used, using lambda syntax you can then use it to change something like this:

    updateRoleFamily.RoleFamilyDescription = roleFamilyDescription;
    updateRoleFamily.RoleFamilyCode = roleFamilyCode;

To this:

    updateRoleFamily.With(rf =>
          {
              rf.RoleFamilyDescription = roleFamilyDescription;
              rf.RoleFamilyCode = roleFamilyCode;
          });

On an example like this, the only advantage is perhaps a nicer layout, but with a more complex reference and more properties, it could well give you more readable code.

How to clear mysql screen console in windows?

This is not possible on Windows.

There is an open bug for this issue: Bug #58680: Windows Clear Screen Command

Is it possible to pass a flag to Gulp to have it run tasks in different ways?

There's a very simple way to do on/off flags without parsing the arguments. gulpfile.js is just a file that's executed like any other, so you can do:

var flags = {
  production: false
};

gulp.task('production', function () {
  flags.production = true;
});

And use something like gulp-if to conditionally execute a step

gulp.task('build', function () {
  gulp.src('*.html')
    .pipe(gulp_if(flags.production, minify_html()))
    .pipe(gulp.dest('build/'));
});

Executing gulp build will produce a nice html, while gulp production build will minify it.

How do I get an Excel range using row and column numbers in VSTO / C#?

you can retrieve value like this

string str = (string)(range.Cells[row, col] as Excel.Range).Value2 ;

select entire used range

Excel.Range range = xlWorkSheet.UsedRange;

source :

http://csharp.net-informations.com/excel/csharp-read-excel.htm

flaming

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

This is a warning spit out by build tools for two reasons.
1. One of the plugin is relying on Task instead of TaskProvider, there is nothing much we can do.
2. You have configured usage of task, where as it supports TaskProvider.

WARNING: API 'variant.getGenerateBuildConfig()' is obsolete and has been replaced with 'variant.getGenerateBuildConfigProvider()'.
It will be removed at the end of 2019.
For more information, see https://d.android.com/r/tools/task-configuration-avoidance

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'.
It will be removed at the end of 2019.
For more information, see https://d.android.com/r/tools/task-configuration-avoidance

WARNING: API 'variant.getMergeResources()' is obsolete and has been replaced with 'variant.getMergeResourcesProvider()'.
It will be removed at the end of 2019.
For more information, see https://d.android.com/r/tools/task-configuration-avoidance

Look out for snippets as below & update.

android {
    <library|application>Variants.all { variant ->
        /* Disable Generating Build config */
        // variant.generateBuildConfig.enabled = true // <- Deprecated
        variant.generateBuildConfigProvider.configure {
            it.enabled = true // Replacement
        }
    }
}

Similarly, find usages of 'variant.getJavaCompile()' or 'variant.javaCompile', 'variant.getMergeResources()' or 'variant.mergeResources'. Replace as above.

More information at Task Configuration Avoidance

Grep to find item in Perl array

In addition to what eugene and stevenl posted, you might encounter problems with using both <> and <STDIN> in one script: <> iterates through (=concatenating) all files given as command line arguments.

However, should a user ever forget to specify a file on the command line, it will read from STDIN, and your code will wait forever on input

Declare and initialize a Dictionary in Typescript

I agree with thomaux that the initialization type checking error is a TypeScript bug. However, I still wanted to find a way to declare and initialize a Dictionary in a single statement with correct type checking. This implementation is longer, however it adds additional functionality such as a containsKey(key: string) and remove(key: string) method. I suspect that this could be simplified once generics are available in the 0.9 release.

First we declare the base Dictionary class and Interface. The interface is required for the indexer because classes cannot implement them.

interface IDictionary {
    add(key: string, value: any): void;
    remove(key: string): void;
    containsKey(key: string): bool;
    keys(): string[];
    values(): any[];
}

class Dictionary {

    _keys: string[] = new string[];
    _values: any[] = new any[];

    constructor(init: { key: string; value: any; }[]) {

        for (var x = 0; x < init.length; x++) {
            this[init[x].key] = init[x].value;
            this._keys.push(init[x].key);
            this._values.push(init[x].value);
        }
    }

    add(key: string, value: any) {
        this[key] = value;
        this._keys.push(key);
        this._values.push(value);
    }

    remove(key: string) {
        var index = this._keys.indexOf(key, 0);
        this._keys.splice(index, 1);
        this._values.splice(index, 1);

        delete this[key];
    }

    keys(): string[] {
        return this._keys;
    }

    values(): any[] {
        return this._values;
    }

    containsKey(key: string) {
        if (typeof this[key] === "undefined") {
            return false;
        }

        return true;
    }

    toLookup(): IDictionary {
        return this;
    }
}

Now we declare the Person specific type and Dictionary/Dictionary interface. In the PersonDictionary note how we override values() and toLookup() to return the correct types.

interface IPerson {
    firstName: string;
    lastName: string;
}

interface IPersonDictionary extends IDictionary {
    [index: string]: IPerson;
    values(): IPerson[];
}

class PersonDictionary extends Dictionary {
    constructor(init: { key: string; value: IPerson; }[]) {
        super(init);
    }

    values(): IPerson[]{
        return this._values;
    }

    toLookup(): IPersonDictionary {
        return this;
    }
}

And here is a simple initialization and usage example:

var persons = new PersonDictionary([
    { key: "p1", value: { firstName: "F1", lastName: "L2" } },
    { key: "p2", value: { firstName: "F2", lastName: "L2" } },
    { key: "p3", value: { firstName: "F3", lastName: "L3" } }
]).toLookup();


alert(persons["p1"].firstName + " " + persons["p1"].lastName);
// alert: F1 L2

persons.remove("p2");

if (!persons.containsKey("p2")) {
    alert("Key no longer exists");
    // alert: Key no longer exists
}

alert(persons.keys().join(", "));
// alert: p1, p3

How to run a Maven project from Eclipse?

Your Maven project doesn't seem to be configured as a Eclipse Java project, that is the Java nature is missing (the little 'J' in the project icon).

To enable this, the <packaging> element in your pom.xml should be jar (or similar).

Then, right-click the project and select Maven > Update Project Configuration

For this to work, you need to have m2eclipse installed. But since you had the _ New ... > New Maven Project_ wizard, I assume you have m2eclipse installed.

Threading pool similar to the multiprocessing Pool?

If you don't mind executing other's code, here's mine:

Note: There is lot of extra code you may want to remove [added for better clarificaiton and demonstration how it works]

Note: Python naming conventions were used for method names and variable names instead of camelCase.

Working procedure:

  1. MultiThread class will initiate with no of instances of threads by sharing lock, work queue, exit flag and results.
  2. SingleThread will be started by MultiThread once it creates all instances.
  3. We can add works using MultiThread (It will take care of locking).
  4. SingleThreads will process work queue using a lock in middle.
  5. Once your work is done, you can destroy all threads with shared boolean value.
  6. Here, work can be anything. It can automatically import (uncomment import line) and process module using given arguments.
  7. Results will be added to results and we can get using get_results

Code:

import threading
import queue


class SingleThread(threading.Thread):
    def __init__(self, name, work_queue, lock, exit_flag, results):
        threading.Thread.__init__(self)
        self.name = name
        self.work_queue = work_queue
        self.lock = lock
        self.exit_flag = exit_flag
        self.results = results

    def run(self):
        # print("Coming %s with parameters %s", self.name, self.exit_flag)
        while not self.exit_flag:
            # print(self.exit_flag)
            self.lock.acquire()
            if not self.work_queue.empty():
                work = self.work_queue.get()
                module, operation, args, kwargs = work.module, work.operation, work.args, work.kwargs
                self.lock.release()
                print("Processing : " + operation + " with parameters " + str(args) + " and " + str(kwargs) + " by " + self.name + "\n")
                # module = __import__(module_name)
                result = str(getattr(module, operation)(*args, **kwargs))
                print("Result : " + result + " for operation " + operation + " and input " + str(args) + " " + str(kwargs))
                self.results.append(result)
            else:
                self.lock.release()
        # process_work_queue(self.work_queue)

class MultiThread:
    def __init__(self, no_of_threads):
        self.exit_flag = bool_instance()
        self.queue_lock = threading.Lock()
        self.threads = []
        self.work_queue = queue.Queue()
        self.results = []
        for index in range(0, no_of_threads):
            thread = SingleThread("Thread" + str(index+1), self.work_queue, self.queue_lock, self.exit_flag, self.results)
            thread.start()
            self.threads.append(thread)

    def add_work(self, work):
        self.queue_lock.acquire()
        self.work_queue._put(work)
        self.queue_lock.release()

    def destroy(self):
        self.exit_flag.value = True
        for thread in self.threads:
            thread.join()

    def get_results(self):
        return self.results


class Work:
    def __init__(self, module, operation, args, kwargs={}):
        self.module = module
        self.operation = operation
        self.args = args
        self.kwargs = kwargs


class SimpleOperations:
    def sum(self, *args):
        return sum([int(arg) for arg in args])

    @staticmethod
    def mul(a, b, c=0):
        return int(a) * int(b) + int(c)


class bool_instance:
    def __init__(self, value=False):
        self.value = value

    def __setattr__(self, key, value):
        if key != "value":
            raise AttributeError("Only value can be set!")
        if not isinstance(value, bool):
            raise AttributeError("Only True/False can be set!")
        self.__dict__[key] = value
        # super.__setattr__(key, bool(value))

    def __bool__(self):
        return self.value

if __name__ == "__main__":
    multi_thread = MultiThread(5)
    multi_thread.add_work(Work(SimpleOperations(), "mul", [2, 3], {"c":4}))
    while True:
        data_input = input()
        if data_input == "":
            pass
        elif data_input == "break":
            break
        else:
            work = data_input.split()
            multi_thread.add_work(Work(SimpleOperations(), work[0], work[1:], {}))
    multi_thread.destroy()
    print(multi_thread.get_results())

Node.js: Python not found exception due to node-sass and node-gyp

My answer might not apply to everyone. Node version: v10.16.0 NPM: 6.9.0

I was having a lot of trouble using node-sass and node-sass-middleware. They are interesting packages because they are widely used (millions of downloads weekly), but their githubs show a limited dependencies and coverage. I was updating an older platform I'd been working on.

What I ended up having to do was:

1) Manually Delete node_modules

2) Manually Delete package-lock.json

3) sudo npm install node-sass --unsafe-perm=true --allow-root

4) sudo npm install node-sass-middleware --unsafe-perm=true --allow-root

I had the following help, thanks!

Pre-built binaries not found for [email protected] and [email protected]

Error: EACCES: permission denied when trying to install ESLint using npm

Regular Expression to select everything before and up to a particular text

Up to and including txt you would need to change your regex like so:

^(.*?\\.txt)

Load HTML page dynamically into div with jQuery

Try with this one:

$(document).ready(function(){
  $('a').click(function(e){
     e.preventDefault();
     $("#content").load($(this).attr('href'));
  });
});

and make sure to call this library first:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">
</script>

$(window).height() vs $(document).height

Well you seem to have mistaken them both for what they do.

$(window).height() gets you an unit-less pixel value of the height of the (browser) window aka viewport. With respect to the web browsers the viewport here is visible portion of the canvas(which often is smaller than the document being rendered).

$(document).height() returns an unit-less pixel value of the height of the document being rendered. However, if the actual document’s body height is less than the viewport height then it will return the viewport height instead.

Hope that clears things a little.

Easy interview question got harder: given numbers 1..100, find the missing number(s) given exactly k are missing

For different values of k, the approach will be different so there won't be a generic answer in terms of k. For example, for k=1 one can take advantage of the sum of natural numbers, but for k = n/2, one has to use some kind of bitset. The same way for k=n-1, one can simply compare the only number in the bag with the rest.

Best TCP port number range for internal applications

I decided to download the assigned port numbers from IANA, filter out the used ports, and sort each "Unassigned" range in order of most ports available, descending. This did not work, since the csv file has ranges marked as "Unassigned" that overlap other port number reservations. I manually expanded the ranges of assigned port numbers, leaving me with a list of all assigned port numbers. I then sorted that list and generated my own list of unassigned ranges.

Since this stackoverflow.com page ranked very high in my search about the topic, I figured I'd post the largest ranges here for anyone else who is interested. These are for both TCP and UDP where the number of ports in the range is at least 500.

Total   Start   End
829     29170   29998
815     38866   39680
710     41798   42507
681     43442   44122
661     46337   46997
643     35358   36000
609     36866   37474
596     38204   38799
592     33657   34248
571     30261   30831
563     41231   41793
542     21011   21552
528     28590   29117
521     14415   14935
510     26490   26999

Source (via the CSV download button):

http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml

Git credential helper - update password

None of these answers ended up working for my Git credential issue. Here is what did work if anyone needs it (I'm using Git 1.9 on Windows 8.1).

To update your credentials, go to Control PanelCredential ManagerGeneric Credentials. Find the credentials related to your Git account and edit them to use the updated password.

Reference: How to update your Git credentials on Windows

Note that to use the Windows Credential Manager for Git you need to configure the credential helper like so:

git config --global credential.helper wincred

If you have multiple GitHub accounts that you use for different repositories, then you should configure credentials to use the full repository path (rather than just the domain, which is the default):

git config --global credential.useHttpPath true

JAX-RS — How to return JSON and HTTP status code together?

I'm not using JAX-RS, but I've got a similar scenario where I use:

response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());

HTML Submit-button: Different value / button-text?

It's possible using the button element.

<button name="name" value="value" type="submit">Sök</button>

From the W3C page on button:

Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content.

Java FileWriter how to write to next Line

.newLine() is the best if your system property line.separator is proper . and sometime you don't want to change the property runtime . So alternative solution is appending \n

Xcode 6.1 - How to uninstall command line tools?

If you installed the command line tools separately, delete them using:

sudo rm -rf /Library/Developer/CommandLineTools

Docker - Cannot remove dead container

The best way to get rid of dead container processes is to restart your docker service. I was unable to remove a container as it was stuck in restarting status, I just restarted the docker service and it worked for me.

How to check postgres user and password?

You may change the pg_hba.conf and then reload the postgresql. something in the pg_hba.conf may be like below:

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust

then you change your user to postgresql, you may login successfully.

su postgresql

WCF named pipe minimal example

I just found this excellent little tutorial. broken link (Cached version)

I also followed Microsoft's tutorial which is nice, but I only needed pipes as well.

As you can see, you don't need configuration files and all that messy stuff.

By the way, he uses both HTTP and pipes. Just remove all code lines related to HTTP, and you'll get a pure pipe example.

AngularJS: How to set a variable inside of a template?

Use ngInit: https://docs.angularjs.org/api/ng/directive/ngInit

<div ng-repeat="day in forecast_days" ng-init="f = forecast[day.iso]">
  {{$index}} - {{day.iso}} - {{day.name}}
  Temperature: {{f.temperature}}<br>
  Humidity: {{f.humidity}}<br>
  ...
</div>

Example: http://jsfiddle.net/coma/UV4qF/

How to copy directory recursively in python and overwrite all?

My simple answer.

def get_files_tree(src="src_path"):
    req_files = []
    for r, d, files in os.walk(src):
        for file in files:
            src_file = os.path.join(r, file)
            src_file = src_file.replace('\\', '/')
            if src_file.endswith('.db'):
                continue
            req_files.append(src_file)

    return req_files
def copy_tree_force(src_path="",dest_path=""):
    """
    make sure that all the paths has correct slash characters.
    """
    for cf in get_files_tree(src=src_path):
        df= cf.replace(src_path, dest_path)
        if not os.path.exists(os.path.dirname(df)):
            os.makedirs(os.path.dirname(df))
        shutil.copy2(cf, df)

How to decode encrypted wordpress admin password?

just edit wp_user table with your phpmyadmin, and choose MD5 on Function field then input your new password, save it (go button). enter image description here

ImportError: No module named requests

My answer is basically the same as @pi-k. In my case my program worked locally but failed to build on QA servers. (I suspect devops had older versions of the package blocked and my version must have been too out-of-date) I just decided to upgrade everything

$ pip install pip-review
$ pip-review --local --interactive

How to use Chrome's network debugger with redirects

Just update of @bfncs answer

I think around Chrome 43 the behavior was changed a little. You still need to enable Preserve log to see, but now redirect shown under Other tab, when loaded document is shown under Doc.

This always confuse me, because I have a lot of networks requests and filter it by type XHR, Doc, JS etc. But in case of redirect the Doc tab is empty, so I have to guess.

How to exit in Node.js

To exit

let exitCode = 1;
process.exit(exitCode)

Useful exit codes

1 - Catchall for general errors
2 - Misuse of shell builtins (according to Bash documentation)
126 - Command invoked cannot execute
127 - “command not found”
128 - Invalid argument to exit
128+n - Fatal error signal “n”
130 - Script terminated by Control-C
255\* - Exit status out of range

Segmentation Fault - C

Your scanf("%s", s); is commented out. That means s is uninitialized, so when this line ln = strlen(s); executes, you get a seg fault.

It always helps to initialize a pointer to NULL, and then test for null before using the pointer.

How to stop a function

def player(game_over):
    do something here
    game_over = check_winner() #Here we tell check_winner to run and tell us what game_over should be, either true or false
    if not game_over: 
        computer(game_over)  #We are only going to do this if check_winner comes back as False

def check_winner(): 
    check something
    #here needs to be an if / then statement deciding if the game is over, return True if over, false if not
    if score == 100:
        return True
    else:
        return False

def computer(game_over):
    do something here
    game_over = check_winner() #Here we tell check_winner to run and tell us what game_over should be, either true or false
    if not game_over:
        player(game_over) #We are only going to do this if check_winner comes back as False

game_over = False   #We need a variable to hold wether the game is over or not, we'll start it out being false.
player(game_over)   #Start your loops, sending in the status of game_over

Above is a pretty simple example... I made up a statement for check_winner using score = 100 to denote the game being over.

You will want to use similar method of passing score into check_winner, using game_over = check_winner(score). Then you can create a score at the beginning of your program and pass it through to computer and player just like game_over is being handled.

How to read a file from jar in Java?

Ah, this is one of my favorite subjects. There are essentially two ways you can load a resource through the classpath:

Class.getResourceAsStream(resource)

and

ClassLoader.getResourceAsStream(resource)

(there are other ways which involve getting a URL for the resource in a similar fashion, then opening a connection to it, but these are the two direct ways).

The first method actually delegates to the second, after mangling the resource name. There are essentially two kinds of resource names: absolute (e.g. "/path/to/resource/resource") and relative (e.g. "resource"). Absolute paths start with "/".

Here's an example which should illustrate. Consider a class com.example.A. Consider two resources, one located at /com/example/nested, the other at /top, in the classpath. The following program shows nine possible ways to access the two resources:

package com.example;

public class A {

    public static void main(String args[]) {

        // Class.getResourceAsStream
        Object resource = A.class.getResourceAsStream("nested");
        System.out.println("1: A.class nested=" + resource);

        resource = A.class.getResourceAsStream("/com/example/nested");
        System.out.println("2: A.class /com/example/nested=" + resource);

        resource = A.class.getResourceAsStream("top");
        System.out.println("3: A.class top=" + resource);

        resource = A.class.getResourceAsStream("/top");
        System.out.println("4: A.class /top=" + resource);

        // ClassLoader.getResourceAsStream
        ClassLoader cl = A.class.getClassLoader();
        resource = cl.getResourceAsStream("nested");        
        System.out.println("5: cl nested=" + resource);

        resource = cl.getResourceAsStream("/com/example/nested");
        System.out.println("6: cl /com/example/nested=" + resource);
        resource = cl.getResourceAsStream("com/example/nested");
        System.out.println("7: cl com/example/nested=" + resource);

        resource = cl.getResourceAsStream("top");
        System.out.println("8: cl top=" + resource);

        resource = cl.getResourceAsStream("/top");
        System.out.println("9: cl /top=" + resource);
    }

}

The output from the program is:

1: A.class nested=java.io.BufferedInputStream@19821f
2: A.class /com/example/nested=java.io.BufferedInputStream@addbf1
3: A.class top=null
4: A.class /top=java.io.BufferedInputStream@42e816
5: cl nested=null
6: cl /com/example/nested=null
7: cl com/example/nested=java.io.BufferedInputStream@9304b1
8: cl top=java.io.BufferedInputStream@190d11
9: cl /top=null

Mostly things do what you'd expect. Case-3 fails because class relative resolving is with respect to the Class, so "top" means "/com/example/top", but "/top" means what it says.

Case-5 fails because classloader relative resolving is with respect to the classloader. But, unexpectedly Case-6 also fails: one might expect "/com/example/nested" to resolve properly. To access a nested resource through the classloader you need to use Case-7, i.e. the nested path is relative to the root of the classloader. Likewise Case-9 fails, but Case-8 passes.

Remember: for java.lang.Class, getResourceAsStream() does delegate to the classloader:

     public InputStream getResourceAsStream(String name) {
        name = resolveName(name);
        ClassLoader cl = getClassLoader0();
        if (cl==null) {
            // A system class.
            return ClassLoader.getSystemResourceAsStream(name);
        }
        return cl.getResourceAsStream(name);
    }

so it is the behavior of resolveName() that is important.

Finally, since it is the behavior of the classloader that loaded the class that essentially controls getResourceAsStream(), and the classloader is often a custom loader, then the resource-loading rules may be even more complex. e.g. for Web-Applications, load from WEB-INF/classes or WEB-INF/lib in the context of the web application, but not from other web-applications which are isolated. Also, well-behaved classloaders delegate to parents, so that duplicateed resources in the classpath may not be accessible using this mechanism.

How to jQuery clone() and change id?

I have created a generalised solution. The function below will change ids and names of cloned object. In most cases, you will need the row number so Just add "data-row-id" attribute to the object.

function renameCloneIdsAndNames( objClone ) {

    if( !objClone.attr( 'data-row-id' ) ) {
        console.error( 'Cloned object must have \'data-row-id\' attribute.' );
    }

    if( objClone.attr( 'id' ) ) {
        objClone.attr( 'id', objClone.attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );
    }

    objClone.attr( 'data-row-id', objClone.attr( 'data-row-id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );

    objClone.find( '[id]' ).each( function() {

        var strNewId = $( this ).attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } );

        $( this ).attr( 'id', strNewId );

        if( $( this ).attr( 'name' ) ) {
            var strNewName  = $( this ).attr( 'name' ).replace( /\[\d+\]/g, function( strName ) {
                strName = strName.replace( /[\[\]']+/g, '' );
                var intNumber = parseInt( strName ) + 1;
                return '[' + intNumber + ']'
            } );
            $( this ).attr( 'name', strNewName );
        }
    });

    return objClone;
}

VBA, if a string contains a certain letter

Try:

If myString like "*A*" Then

Specify the date format in XMLGregorianCalendar

This is an easy way for any format. Just change it to required format string

XMLGregorianCalendar gregFmt = DatatypeFactory.newInstance().newXMLGregorianCalendar(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date()));
System.out.println(gregFmt);

How to extract numbers from string in c?

#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
void main(int argc,char *argv[])
{
char *str ="ab234cid*(s349*(20kd", *ptr = str;
while (*ptr) { // While there are more characters to process...
    if ( isdigit(*ptr) ) {
        // Found a number
        int val = (int)strtol(ptr,&ptr, 10); // Read number
        printf("%d\n", val); // and print it.
    } else {
        // Otherwise, move on to the next character.
        ptr++;
    }
}

}

What's the advantage of a Java enum versus a class with public static final fields?

The biggest advantage is enum Singletons are easy to write and thread-safe :

public enum EasySingleton{
    INSTANCE;
}

and

/**
* Singleton pattern example with Double checked Locking
*/
public class DoubleCheckedLockingSingleton{
     private volatile DoubleCheckedLockingSingleton INSTANCE;

     private DoubleCheckedLockingSingleton(){}

     public DoubleCheckedLockingSingleton getInstance(){
         if(INSTANCE == null){
            synchronized(DoubleCheckedLockingSingleton.class){
                //double checking Singleton instance
                if(INSTANCE == null){
                    INSTANCE = new DoubleCheckedLockingSingleton();
                }
            }
         }
         return INSTANCE;
     }
}

both are similar and it handled Serialization by themselves by implementing

//readResolve to prevent another instance of Singleton
    private Object readResolve(){
        return INSTANCE;
    }

more

Change hash without reload in jQuery

The accepted answer didn't work for me as my page jumped slightly on click, messing up my scroll animation.

I decided to update the entire URL using window.history.replaceState rather than using the window.location.hash method. Thus circumventing the hashChange event fired by the browser.

// Only fire when URL has anchor
$('a[href*="#"]:not([href="#"])').on('click', function(event) {

    // Prevent default anchor handling (which causes the page-jumping)
    event.preventDefault();

    if ( location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname ) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

        if ( target.length ) {    
            // Smooth scrolling to anchor
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);

            // Update URL
            window.history.replaceState("", document.title, window.location.href.replace(location.hash, "") + this.hash);
        }
    }
});

How to perform a fade animation on Activity transition?

Just re-posting answer by oleynikd because it's simple and neat

Bundle bundle = ActivityOptionsCompat.makeCustomAnimation(getContext(),
    android.R.anim.fade_in, android.R.anim.fade_out).toBundle(); 
startActivity(intent, bundle);

Construct a manual legend for a complicated plot

You need to map attributes to aesthetics (colours within the aes statement) to produce a legend.

cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h, fill = "BAR"),colour="#333333")+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols) + scale_fill_manual(name="Bar",values=cols) +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here

I understand where Roland is coming from, but since this is only 3 attributes, and complications arise from superimposing bars and error bars this may be reasonable to leave the data in wide format like it is. It could be slightly reduced in complexity by using geom_pointrange.


To change the background color for the error bars legend in the original, add + theme(legend.key = element_rect(fill = "white",colour = "white")) to the plot specification. To merge different legends, you typically need to have a consistent mapping for all elements, but it is currently producing an artifact of a black background for me. I thought guide = guide_legend(fill = NULL,colour = NULL) would set the background to null for the legend, but it did not. Perhaps worth another question.

ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols, guide = guide_legend(fill = NULL,colour = NULL)) + 
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here


To get rid of the black background in the legend, you need to use the override.aes argument to the guide_legend. The purpose of this is to let you specify a particular aspect of the legend which may not be being assigned correctly.

ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols, 
                      guide = guide_legend(override.aes=aes(fill=NA))) + 
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here

Remove duplicate elements from array in Ruby

You can return the intersection.

a = [1,1,2,3]
a & a

This will also delete duplicates.

How to subscribe to an event on a service in Angular2?

Using alpha 28, I accomplished programmatically subscribing to event emitters by way of the eventEmitter.toRx().subscribe(..) method. As it is not intuitive, it may perhaps change in a future release.

Why does multiplication repeats the number several times?

Use integers instead of strings.

make sure to cast your string to ints

price = int('1') * 9

The actual example code you posted will return 9 not 111111111

How to execute a program or call a system command from Python

After some research, I have the following code which works very well for me. It basically prints both stdout and stderr in real time.

stdout_result = 1
stderr_result = 1


def stdout_thread(pipe):
    global stdout_result
    while True:
        out = pipe.stdout.read(1)
        stdout_result = pipe.poll()
        if out == '' and stdout_result is not None:
            break

        if out != '':
            sys.stdout.write(out)
            sys.stdout.flush()


def stderr_thread(pipe):
    global stderr_result
    while True:
        err = pipe.stderr.read(1)
        stderr_result = pipe.poll()
        if err == '' and stderr_result is not None:
            break

        if err != '':
            sys.stdout.write(err)
            sys.stdout.flush()


def exec_command(command, cwd=None):
    if cwd is not None:
        print '[' + ' '.join(command) + '] in ' + cwd
    else:
        print '[' + ' '.join(command) + ']'

    p = subprocess.Popen(
        command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd
    )

    out_thread = threading.Thread(name='stdout_thread', target=stdout_thread, args=(p,))
    err_thread = threading.Thread(name='stderr_thread', target=stderr_thread, args=(p,))

    err_thread.start()
    out_thread.start()

    out_thread.join()
    err_thread.join()

    return stdout_result + stderr_result

Is it possible to import modules from all files in a directory, using a wildcard?

I've used them a few times (in particular for building massive objects splitting the data over many files (e.g. AST nodes)), in order to build them I made a tiny script (which I've just added to npm so everyone else can use it).

Usage (currently you'll need to use babel to use the export file):

$ npm install -g folder-module
$ folder-module my-cool-module/

Generates a file containing:

export {default as foo} from "./module/foo.js"
export {default as default} from "./module/default.js"
export {default as bar} from "./module/bar.js"
...etc

Then you can just consume the file:

import * as myCoolModule from "my-cool-module.js"
myCoolModule.foo()

Split array into chunks of N length

Maybe this code helps:

_x000D_
_x000D_
var chunk_size = 10;_x000D_
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];_x000D_
var groups = arr.map( function(e,i){ _x000D_
     return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; _x000D_
}).filter(function(e){ return e; });_x000D_
console.log({arr, groups})
_x000D_
_x000D_
_x000D_

ToList()-- does it create a new list?

A new list is created but the items in it are references to the orginal items (just like in the original list). Changes to the list itself are independent, but to the items will find the change in both lists.

Getting reference to the top-most view/window in iOS application

If your application only works in portrait orientation, this is enough:

[[[UIApplication sharedApplication] keyWindow] addSubview:yourView]

And your view will not be shown over keyboard and status bar.

If you want to get a topmost view that over keyboard or status bar, or you want the topmost view can rotate correctly with devices, please try this framework:

https://github.com/HarrisonXi/TopmostView

It supports iOS7/8/9.

Request Permission for Camera and Library in iOS 10 - Info.plist

Use the plist settings mentioned above and the appropriate accessor (AVCaptureDevice or PHPhotoLibrary), but also alert them and send them to settings if you really need this, like so:

Swift 4.0 and 4.1

func proceedWithCameraAccess(identifier: String){
    // handler in .requestAccess is needed to process user's answer to our request
    AVCaptureDevice.requestAccess(for: .video) { success in
      if success { // if request is granted (success is true)
        DispatchQueue.main.async {
          self.performSegue(withIdentifier: identifier, sender: nil)
        }
      } else { // if request is denied (success is false)
        // Create Alert
        let alert = UIAlertController(title: "Camera", message: "Camera access is absolutely necessary to use this app", preferredStyle: .alert)

        // Add "OK" Button to alert, pressing it will bring you to the settings app
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
          UIApplication.shared.open(URL(string: UIApplicationOpenSettingsURLString)!)
        }))
        // Show the alert with animation
        self.present(alert, animated: true)
      }
    }
  }

How are cookies passed in the HTTP protocol?

create example script as resp :

#!/bin/bash

http_code=200
mime=text/html

echo -e "HTTP/1.1 $http_code OK\r"
echo "Content-type: $mime"
echo
echo "Set-Cookie: name=F"

then make executable and execute like this.

./resp | nc -l -p 12346

open browser and browse URL: http://localhost:1236 you will see Cookie value which is sent by Browser

    [aaa@bbbbbbbb ]$ ./resp | nc -l -p 12346
    GET / HTTP/1.1
    Host: xxx.xxx.xxx.xxx:12346
    Connection: keep-alive
    Cache-Control: max-age=0
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
    Upgrade-Insecure-Requests: 1
    User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36
    Accept-Encoding: gzip, deflate, sdch
    Accept-Language: en-US,en;q=0.8,ru;q=0.6
    Cookie: name=F

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

Tensor.get_shape() from this post.

From documentation:

c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
print(c.get_shape())
==> TensorShape([Dimension(2), Dimension(3)])

Shell Script: Execute a python program from within a shell script

Save the following program as print.py:

#!/usr/bin/python3
print('Hello World')

Then in the terminal type:

chmod +x print.py
./print.py

Detect Windows version in .net

I used this when I had to determine various Microsoft Operating System versions:

string getOSInfo()
{
   //Get Operating system information.
   OperatingSystem os = Environment.OSVersion;
   //Get version information about the os.
   Version vs = os.Version;

   //Variable to hold our return value
   string operatingSystem = "";

   if (os.Platform == PlatformID.Win32Windows)
   {
       //This is a pre-NT version of Windows
       switch (vs.Minor)
       {
           case 0:
               operatingSystem = "95";
               break;
           case 10:
               if (vs.Revision.ToString() == "2222A")
                   operatingSystem = "98SE";
               else
                   operatingSystem = "98";
               break;
           case 90:
               operatingSystem = "Me";
               break;
           default:
               break;
       }
   }
   else if (os.Platform == PlatformID.Win32NT)
   {
       switch (vs.Major)
       {
           case 3:
               operatingSystem = "NT 3.51";
               break;
           case 4:
               operatingSystem = "NT 4.0";
               break;
           case 5:
               if (vs.Minor == 0)
                   operatingSystem = "2000";
               else
                   operatingSystem = "XP";
               break;
           case 6:
               if (vs.Minor == 0)
                   operatingSystem = "Vista";
               else if (vs.Minor == 1)
                   operatingSystem = "7";
               else if (vs.Minor == 2)
                   operatingSystem = "8";
               else
                   operatingSystem = "8.1";
               break;
           case 10:
               operatingSystem = "10";
               break;
           default:
               break;
       }
   }
   //Make sure we actually got something in our OS check
   //We don't want to just return " Service Pack 2" or " 32-bit"
   //That information is useless without the OS version.
   if (operatingSystem != "")
   {
       //Got something.  Let's prepend "Windows" and get more info.
       operatingSystem = "Windows " + operatingSystem;
       //See if there's a service pack installed.
       if (os.ServicePack != "")
       {
           //Append it to the OS name.  i.e. "Windows XP Service Pack 3"
           operatingSystem += " " + os.ServicePack;
       }
       //Append the OS architecture.  i.e. "Windows XP Service Pack 3 32-bit"
       //operatingSystem += " " + getOSArchitecture().ToString() + "-bit";
   }
   //Return the information we've gathered.
   return operatingSystem;
}

Source: here

How to specify the JDK version in android studio?

You can use cmd + ; for Mac or Ctrl + Alt + Shift + S for Windows/Linux to pull up the Project Structure dialog. In there, you can set the JDK location as well as the Android SDK location.

Project Structure Dialog

To get your JDK location, run /usr/libexec/java_home -v 1.7 in terminal. Send 1.7 for Java 7 or 1.8 for Java 8.

How to see tomcat is running or not

open your browser,check whether Tomcat homepage is visible by below command.

http://ipaddress:portnumber

also check this

Simulate Keypress With jQuery

This works:

var event = jQuery.Event('keypress');
event.which = 13; 
event.keyCode = 13; //keycode to trigger this for simulating enter
jQuery(this).trigger(event); 

Docker: unable to prepare context: unable to evaluate symlinks in Dockerfile path: GetFileAttributesEx

Most importantly make sure your file name is Dockerfile if you use another name it won't work(at least it did not for me.)

Also if you are in the same dir where the Dockerfile is use a . i.e. docker build -t Myubuntu1:v1 . or use the absolute path i.e docker build -t Myubuntu1:v1 /Users/<username>/Desktop/Docker

How do I get the command-line for an Eclipse run configuration?

Scan your workspace .metadata directory for files called *.launch. I forget which plugin directory exactly holds these records, but it might even be the most basic org.eclipse.plugins.core one.

invalid command code ., despite escaping periods, using sed

If you are on a OS X, this probably has nothing to do with the sed command. On the OSX version of sed, the -i option expects an extension argument so your command is actually parsed as the extension argument and the file path is interpreted as the command code.

Try adding the -e argument explicitly and giving '' as argument to -i:

find ./ -type f -exec sed -i '' -e "s/192.168.20.1/new.domain.com/" {} \;

See this.

How to get current local date and time in Kotlin

My utils method for get current date time using Calendar when our minSdkVersion < 26.

fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
    val formatter = SimpleDateFormat(format, locale)
    return formatter.format(this)
}

fun getCurrentDateTime(): Date {
    return Calendar.getInstance().time
}

Using

import ...getCurrentDateTime
import ...toString
...
...
val date = getCurrentDateTime()
val dateInString = date.toString("yyyy/MM/dd HH:mm:ss")

data.map is not a function

The SIMPLEST answer is to put "data" into a pair of square brackets (i.e. [data]):

     $.getJSON("json/products.json").done(function (data) {

         var allProducts = [data].map(function (item) {
             return new getData(item);
         });

     });

Here, [data] is an array, and the ".map" method can be used on it. It works for me! enter image description here

How to execute an .SQL script file using c#

This works for me:

public void updatedatabase()
{

    SqlConnection conn = new SqlConnection("Data Source=" + txtserver.Text.Trim() + ";Initial Catalog=" + txtdatabase.Text.Trim() + ";User ID=" + txtuserid.Text.Trim() + ";Password=" + txtpwd.Text.Trim() + "");
    try
    {

        conn.Open();

        string script = File.ReadAllText(Server.MapPath("~/Script/DatingDemo.sql"));

        // split script on GO command
        IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
        foreach (string commandString in commandStrings)
        {
            if (commandString.Trim() != "")
            {
                new SqlCommand(commandString, conn).ExecuteNonQuery();
            }
        }
        lblmsg.Text = "Database updated successfully.";

    }
    catch (SqlException er)
    {
        lblmsg.Text = er.Message;
        lblmsg.ForeColor = Color.Red;
    }
    finally
    {
        conn.Close();
    }
}

How do you UrlEncode without using System.Web?

System.Net.WebUtility.HtmlDecode

How do I get the HTTP status code with jQuery?

I have had major issues with ajax + jQuery v3 getting both the response status code and data from JSON APIs. jQuery.ajax only decodes JSON data if the status is a successful one, and it also swaps around the ordering of the callback parameters depending on the status code. Ugghhh.

The best way to combat this is to call the .always chain method and do a bit of cleaning up. Here is my code.

$.ajax({
        ...
    }).always(function(data, textStatus, xhr) {
        var responseCode = null;
        if (textStatus === "error") {
            // data variable is actually xhr
            responseCode = data.status;
            if (data.responseText) {
                try {
                    data = JSON.parse(data.responseText);
                } catch (e) {
                    // Ignore
                }
            }
        } else {
            responseCode = xhr.status;
        }

        console.log("Response code", responseCode);
        console.log("JSON Data", data);
    });

How do I connect to mongodb with node.js (and authenticate)?

I'm using Mongoose to connect to mongodb. Install mongoose npm using following command

npm install mongoose

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/database_name', function(err){
    if(err){
        console.log('database not connected');
    }
});
var Schema = mongoose.Schema;
var userschema = new Schema ({});
var user = mongoose.model('collection_name', userschema);

we can use the queries like this

user.find({},function(err,data){
         if(err){
         console.log(err);
         }
        console.log(data);
    });

read input separated by whitespace(s) or newline...?

std::getline( stream, where to?, delimiter ie

std::string in;
std::getline(std::cin, in, ' '); //will split on space

or you can read in a line, then tokenize it based on whichever delimiter you wish.

How to execute a bash command stored as a string with quotes and asterisk

To eliminate the need for the cmd variable, you can do this:

eval 'mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'

SQL Server dynamic PIVOT query?

The below code provides the results which replaces NULL to zero in the output.

Table creation and data insertion:

create table test_table
 (
 date nvarchar(10),
 category char(3),
 amount money
 )

 insert into test_table values ('1/1/2012','ABC',1000.00)
 insert into test_table values ('2/1/2012','DEF',500.00)
 insert into test_table values ('2/1/2012','GHI',800.00)
 insert into test_table values ('2/10/2012','DEF',700.00)
 insert into test_table values ('3/1/2012','ABC',1100.00)

Query to generate the exact results which also replaces NULL with zeros:

DECLARE @DynamicPivotQuery AS NVARCHAR(MAX),
@PivotColumnNames AS NVARCHAR(MAX),
@PivotSelectColumnNames AS NVARCHAR(MAX)

--Get distinct values of the PIVOT Column
SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat

--Get distinct values of the PIVOT Column with isnull
SELECT @PivotSelectColumnNames 
= ISNULL(@PivotSelectColumnNames + ',','')
+ 'ISNULL(' + QUOTENAME(category) + ', 0) AS '
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat

--Prepare the PIVOT query using the dynamic 
SET @DynamicPivotQuery = 
N'SELECT date, ' + @PivotSelectColumnNames + '
FROM test_table
pivot(sum(amount) for category in (' + @PivotColumnNames + ')) as pvt';

--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery

OUTPUT :

enter image description here

Storing SHA1 hash values in MySQL

I would use VARCHAR for variable length data, but not with fixed length data. Because a SHA-1 value is always 160 bit long, the VARCHAR would just waste an additional byte for the length of the fixed-length field.

And I also wouldn’t store the value the SHA1 is returning. Because it uses just 4 bit per character and thus would need 160/4 = 40 characters. But if you use 8 bit per character, you would only need a 160/8 = 20 character long field.

So I recommend you to use BINARY(20) and the UNHEX function to convert the SHA1 value to binary.

I compared storage requirements for BINARY(20) and CHAR(40).

CREATE TABLE `binary` (
    `id` int unsigned auto_increment primary key,
    `password` binary(20) not null
);
CREATE TABLE `char` (
    `id` int unsigned auto_increment primary key,
    `password` char(40) not null
);

With million of records binary(20) takes 44.56M, while char(40) takes 64.57M. InnoDB engine.

Git keeps prompting me for a password

Step 1: check your current configuration

cat .git/config

You will get:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = https://github.com/path_to_your_git.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[user]
    name = your_username
    email = your_email
[branch "master-staging"]
    remote = origin
    merge = refs/heads/master-staging

Step 2: remove your remote origin

git remote rm origin

Step 3: add remote origin back with your username and password

git remote add origin https://your_git_username:[email protected]/path_to_your_git.git

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

Main was missing in the entry point configuration. enter image description here

jQuery: Slide left and slide right

This code works well :

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <script>
            $(document).ready(function(){
            var options = {};
            $("#c").hide();
            $("#d").hide();
            $("#a").click(function(){
                 $("#c").toggle( "slide", options, 500 );
                 $("#d").hide();
            });
            $("#b").click(function(){
                 $("#d").toggle( "slide", options, 500 );
                 $("#c").hide();
                });
            });
        </script>
        <style>
            nav{
            float:left;
            max-width:300px;
            width:300px;
            margin-top:100px;
            }
            article{
            margin-top:100px; 
            height:100px;
            }
            #c,#d{
            padding:10px;
            border:1px solid olive;
            margin-left:100px;
            margin-top:100px;
            background-color:blue;
            }
            button{
            border:2px solid blue;
            background-color:white;
            color:black;
            padding:10px;
            }
        </style>
    </head>
    <body>
        <header>
            <center>hi</center>
        </header>
        <nav>
            <button id="a">Register 1</button>
            <br>
            <br>
            <br>
            <br>
            <button id="b">Register 2</button>
         </nav>

        <article id="c">
            <form>
                <label>User name:</label>
                <input type="text" name="123" value="something"/>
                <br>
                <br>
                <label>Password:</label>
                <input type="text" name="456" value="something"/>
            </form>
        </article>
        <article id="d">
            <p>Hi</p>
        </article>
    </body>
</html>

Reference:W3schools.com and jqueryui.com

Note:This is a example code don't forget to add all the script tags in order to achieve proper functioning of the code.

General error: 1364 Field 'user_id' doesn't have a default value

There are two solutions for this issue.

First, is to create fields with default values set in datatable. It could be empty string, which is fine for MySQL server running in strict mode.

Second, if you started to get this error just recently, after MySQL/MariaDB upgrade, like I did, and in case you already have large project with a lot to fix, all you need to do is to edit MySQL/MariaDB configuration file (for example /etc/my.cnf) and disable strict mode for tables:

[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION

This error started to happen quite recently, due to new strict mode enabled by default. Removing STRICT_TRANS_TABLES from sql_mode configuration key, makes it work as before.

Using variables in Nginx location rules

You can't. Nginx doesn't really support variables in config files, and its developers mock everyone who ask for this feature to be added:

"[Variables] are rather costly compared to plain static configuration. [A] macro expansion and "include" directives should be used [with] e.g. sed + make or any other common template mechanism." http://nginx.org/en/docs/faq/variables_in_config.html

You should either write or download a little tool that will allow you to generate config files from placeholder config files.

Update The code below still works, but I've wrapped it all up into a small PHP program/library called Configurator also on Packagist, which allows easy generation of nginx/php-fpm etc config files, from templates and various forms of config data.

e.g. my nginx source config file looks like this:

location  / {
    try_files $uri /routing.php?$args;
    fastcgi_pass   unix:%phpfpm.socket%/php-fpm-www.sock;
    include       %mysite.root.directory%/conf/fastcgi.conf;
}

And then I have a config file with the variables defined:

phpfpm.socket=/var/run/php-fpm.socket
mysite.root.directory=/home/mysite

And then I generate the actual config file using that. It looks like you're a Python guy, so a PHP based example may not help you, but for anyone else who does use PHP:

<?php

require_once('path.php');

$filesToGenerate = array(
    'conf/nginx.conf' => 'autogen/nginx.conf',
    'conf/mysite.nginx.conf' => 'autogen/mysite.nginx.conf',
    'conf/mysite.php-fpm.conf' => 'autogen/mysite.php-fpm.conf',
    'conf/my.cnf' => 'autogen/my.cnf',
);

$environment = 'amazonec2';

if ($argc >= 2){
    $environmentRequired = $argv[1];

    $allowedVars = array(
        'amazonec2',
        'macports',
    );

    if (in_array($environmentRequired, $allowedVars) == true){
        $environment = $environmentRequired;
    }
}
else{
    echo "Defaulting to [".$environment."] environment";
}

$config = getConfigForEnvironment($environment);

foreach($filesToGenerate as $inputFilename => $outputFilename){
    generateConfigFile(PATH_TO_ROOT.$inputFilename, PATH_TO_ROOT.$outputFilename, $config);
}


function    getConfigForEnvironment($environment){
    $config = parse_ini_file(PATH_TO_ROOT."conf/deployConfig.ini", TRUE);
    $configWithMarkers = array();
    foreach($config[$environment] as $key => $value){
        $configWithMarkers['%'.$key.'%'] = $value;
    }

    return  $configWithMarkers;
}


function    generateConfigFile($inputFilename, $outputFilename, $config){

    $lines = file($inputFilename);

    if($lines === FALSE){
        echo "Failed to read [".$inputFilename."] for reading.";
        exit(-1);
    }

    $fileHandle = fopen($outputFilename, "w");

    if($fileHandle === FALSE){
        echo "Failed to read [".$outputFilename."] for writing.";
        exit(-1);
    }

    $search = array_keys($config);
    $replace = array_values($config);

    foreach($lines as $line){
        $line = str_replace($search, $replace, $line);
        fwrite($fileHandle, $line);
    }

    fclose($fileHandle);
}

?>

And then deployConfig.ini looks something like:

[global]

;global variables go here.

[amazonec2]
nginx.log.directory = /var/log/nginx
nginx.root.directory = /usr/share/nginx
nginx.conf.directory = /etc/nginx
nginx.run.directory  = /var/run
nginx.user           = nginx

[macports]
nginx.log.directory = /opt/local/var/log/nginx
nginx.root.directory = /opt/local/share/nginx
nginx.conf.directory = /opt/local/etc/nginx
nginx.run.directory  = /opt/local/var/run
nginx.user           = _www

Is there a way to access the "previous row" value in a SELECT statement?

Oracle, PostgreSQL, SQL Server and many more RDBMS engines have analytic functions called LAG and LEAD that do this very thing.

In SQL Server prior to 2012 you'd need to do the following:

SELECT  value - (
        SELECT  TOP 1 value
        FROM    mytable m2
        WHERE   m2.col1 < m1.col1 OR (m2.col1 = m1.col1 AND m2.pk < m1.pk)
        ORDER BY 
                col1, pk
        )
FROM mytable m1
ORDER BY
      col1, pk

, where COL1 is the column you are ordering by.

Having an index on (COL1, PK) will greatly improve this query.

document.getElementById vs jQuery $()

All the answers above are correct. In case you want to see it in action, don't forget you have Console in a browser where you can see the actual result crystal clear :

I have an HTML :

<div id="contents"></div>

Go to console (cntrl+shift+c) and use these commands to see your result clearly

document.getElementById('contents')
>>> div#contents

$('#contents')
>>> [div#contents,
 context: document,
 selector: "#contents",
 jquery: "1.10.1",
 constructor: function,
 init: function …]

As we can see, in the first case we got the tag itself (that is, strictly speaking, an HTMLDivElement object). In the latter we actually don’t have a plain object, but an array of objects. And as mentioned by other answers above, you can use the following command:

$('#contents')[0]
>>> div#contents

How to POST JSON request using Apache HttpClient?

Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)

Once you've generated your JSON, you can use something like the code below to POST it

StringRequestEntity requestEntity = new StringRequestEntity(
    JSON_STRING,
    "application/json",
    "UTF-8");

PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);

int statusCode = httpClient.executeMethod(postMethod);

Edit

Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:

StringEntity requestEntity = new StringEntity(
    JSON_STRING,
    ContentType.APPLICATION_JSON);

HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);

HttpResponse rawResponse = httpclient.execute(postMethod);

How to find unused/dead code in java projects

Eclipse can show/highlight code that can't be reached. JUnit can show you code coverage, but you'd need some tests and have to decide if the relevant test is missing or the code is really unused.

Regular expression for a hexadecimal number?

If you're using Perl or PHP, you can replace

[0-9a-fA-F]

with:

[[:xdigit:]]

IOError: [Errno 13] Permission denied

I had a similar problem. I was attempting to have a file written every time a user visits a website.

The problem ended up being twofold.

1: the permissions were not set correctly

2: I attempted to use
f = open(r"newfile.txt","w+") (Wrong)

After changing the file to 777 (all users can read/write)
chmod 777 /var/www/path/to/file
and changing the path to an absolute path, my problem was solved
f = open(r"/var/www/path/to/file/newfile.txt","w+") (Right)

What regular expression will match valid international phone numbers?

This is a further optimisation.

\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|
2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|
4[987654310]|3[9643210]|2[70]|7|1)
\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*\d\W*(\d{1,2})$

(i) allows for valid international prefixes
(ii) followed by 9 or 10 digits, with any type or placing of delimeters (except between the last two digits)

This will match:
+1-234-567-8901
+61-234-567-89-01
+46-234 5678901
+1 (234) 56 89 901
+1 (234) 56-89 901
+46.234.567.8901
+1/234/567/8901

When is assembly faster than C?

I have read all the answers (more than 30) and didn't find a simple reason: assembler is faster than C if you have read and practiced the Intel® 64 and IA-32 Architectures Optimization Reference Manual, so the reason why assembly may be slower is that people who write such slower assembly didn't read the Optimization Manual.

In the good old days of Intel 80286, each instruction was executed at a fixed count of CPU cycles, but since Pentium Pro, released in 1995, Intel processors became superscalar, utilizing Complex Pipelining: Out-of-Order Execution & Register Renaming. Before that, on Pentium, produced 1993, there were U and V pipelines: dual pipe lines that could execute two simple instructions at one clock cycle if they didn't depend on one another; but this was nothing to compare of what is Out-of-Order Execution & Register Renaming appeared in Pentium Pro, and almost left unchanged nowadays.

To explain in a few words, fastest code is where instructions do not depend on previous results, e.g. you should always clear whole registers (by movzx) to remove dependency from previous values of the registers you are working with, so they may renamed internally by the CPU to allow instruction execute in parallel or in different order.

Or, on some processors, false dependency may exist that may also slow things down, like false dependency on Pentium 4 for inc/dec, so you may with to use add eax, 1 instead or inc eax to remove dependency on previous state of the flags.

You can read more on Out-of-Order Execution & Register Renaming if time permits, there is plenty information available in the Internet.

There are also other important issues like branch prediction, number of load and store units, number of gates that execute micro-ops, memory cache coherence protocols, etc., but the most important thing to consider is namely the Out-of-Order Execution.

Most people are simply not aware about the Out-of-Order Execution, so they write their assembly programs like for 80286, expecting their instruction will take a fixed time to execute regardless of context; while C compilers are aware of the Out-of-Order Execution and generate the code correctly. That's why the code of such unaware people is slower, but if you will become aware, your code will be faster.

How Spring Security Filter Chain works

UsernamePasswordAuthenticationFilter is only used for /login, and latter filters are not?

No, UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter, and this contains a RequestMatcher, that means you can define your own processing url, this filter only handle the RequestMatcher matches the request url, the default processing url is /login.

Later filters can still handle the request, if the UsernamePasswordAuthenticationFilter executes chain.doFilter(request, response);.

More details about core fitlers

Does the form-login namespace element auto-configure these filters?

UsernamePasswordAuthenticationFilter is created by <form-login>, these are Standard Filter Aliases and Ordering

Does every request (authenticated or not) reach FilterSecurityInterceptor for non-login url?

It depends on whether the before fitlers are successful, but FilterSecurityInterceptor is the last fitler normally.

Does configuring two http elements create two springSecurityFitlerChains?

Yes, every fitlerChain has a RequestMatcher, if the RequestMatcher matches the request, the request will be handled by the fitlers in the fitler chain.

The default RequestMatcher matches all request if you don't config the pattern, or you can config the specific url (<http pattern="/rest/**").

If you want to konw more about the fitlers, I think you can check source code in spring security. doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)