Programs & Examples On #Mochiweb

MochiWeb is an Erlang library for building lightweight HTTP servers.

How to create a sticky navigation bar that becomes fixed to the top after scrolling

Note (2015): Both question and the answer below apply to the old, deprecated version 2.x of Twitter Bootstrap.

This feature of making and element "sticky" is built into the Twitter's Bootstrap and it is called Affix. All you have to do is to add:

<div data-spy="affix" data-offset-top="121">
  ... your navbar ...
</div>

around your tag and do not forget to load the Bootstrap's JS files as described in the manual. Data attribute offset-top tells how many pixels the page is scrolled (from the top) to fix you menu component. Usually it is just the space to the top of the page.

Note: You will have to take care of the missing space when the menu will be fixed. Fixing means cutting it off out of your page layer and pasting in different layer that does not scroll. I am doing the following:

<div style="height: 77px;">
  <div data-spy="affix" data-offset-top="121">
    <div style="position: relative; height: 0; width: 100%;">
      <div style="position: absolute; top: 0; left: 0;">
        ... my menu ...
      </div>
    </div>
  </div>
</div>

where 77px is the height of my affixed component.

Generate a heatmap in MatPlotLib using a scatter data set

Edit: For a better approximation of Alejandro's answer, see below.

I know this is an old question, but wanted to add something to Alejandro's anwser: If you want a nice smoothed image without using py-sphviewer you can instead use np.histogram2d and apply a gaussian filter (from scipy.ndimage.filters) to the heatmap:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from scipy.ndimage.filters import gaussian_filter


def myplot(x, y, s, bins=1000):
    heatmap, xedges, yedges = np.histogram2d(x, y, bins=bins)
    heatmap = gaussian_filter(heatmap, sigma=s)

    extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
    return heatmap.T, extent


fig, axs = plt.subplots(2, 2)

# Generate some test data
x = np.random.randn(1000)
y = np.random.randn(1000)

sigmas = [0, 16, 32, 64]

for ax, s in zip(axs.flatten(), sigmas):
    if s == 0:
        ax.plot(x, y, 'k.', markersize=5)
        ax.set_title("Scatter plot")
    else:
        img, extent = myplot(x, y, s)
        ax.imshow(img, extent=extent, origin='lower', cmap=cm.jet)
        ax.set_title("Smoothing with  $\sigma$ = %d" % s)

plt.show()

Produces:

Output images

The scatter plot and s=16 plotted on top of eachother for Agape Gal'lo (click for better view):

On top of eachother


One difference I noticed with my gaussian filter approach and Alejandro's approach was that his method shows local structures much better than mine. Therefore I implemented a simple nearest neighbour method at pixel level. This method calculates for each pixel the inverse sum of the distances of the n closest points in the data. This method is at a high resolution pretty computationally expensive and I think there's a quicker way, so let me know if you have any improvements.

Update: As I suspected, there's a much faster method using Scipy's scipy.cKDTree. See Gabriel's answer for the implementation.

Anyway, here's my code:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm


def data_coord2view_coord(p, vlen, pmin, pmax):
    dp = pmax - pmin
    dv = (p - pmin) / dp * vlen
    return dv


def nearest_neighbours(xs, ys, reso, n_neighbours):
    im = np.zeros([reso, reso])
    extent = [np.min(xs), np.max(xs), np.min(ys), np.max(ys)]

    xv = data_coord2view_coord(xs, reso, extent[0], extent[1])
    yv = data_coord2view_coord(ys, reso, extent[2], extent[3])
    for x in range(reso):
        for y in range(reso):
            xp = (xv - x)
            yp = (yv - y)

            d = np.sqrt(xp**2 + yp**2)

            im[y][x] = 1 / np.sum(d[np.argpartition(d.ravel(), n_neighbours)[:n_neighbours]])

    return im, extent


n = 1000
xs = np.random.randn(n)
ys = np.random.randn(n)
resolution = 250

fig, axes = plt.subplots(2, 2)

for ax, neighbours in zip(axes.flatten(), [0, 16, 32, 64]):
    if neighbours == 0:
        ax.plot(xs, ys, 'k.', markersize=2)
        ax.set_aspect('equal')
        ax.set_title("Scatter Plot")
    else:
        im, extent = nearest_neighbours(xs, ys, resolution, neighbours)
        ax.imshow(im, origin='lower', extent=extent, cmap=cm.jet)
        ax.set_title("Smoothing over %d neighbours" % neighbours)
        ax.set_xlim(extent[0], extent[1])
        ax.set_ylim(extent[2], extent[3])
plt.show()

Result:

Nearest Neighbour Smoothing

Setting table column width

Try this instead.

<table style="width: 100%">
    <tr>
        <th style="width: 20%">
           column 1
        </th>
        <th style="width: 40%">
           column 2
        </th>
        <th style="width: 40%">
           column 3
        </th>
    </tr>
    <tr>
        <td style="width: 20%">
           value 1
        </td>
        <td style="width: 40%">
           value 2
        </td>
        <td style="width: 40%">
           value 3
        </td>
    </tr>
</table>

How to workaround 'FB is not defined'?

It's pretty strange for FB not to be loaded in your javascript if you have the script tag there correctly. Check that you don't have any javascript blockers, ad blockers, tracking blockers etc installed in your browser that are neutralizing your FB Connect code.

oracle plsql: how to parse XML and insert into table

You can load an XML document into an XMLType, then query it, e.g.:

DECLARE
  x XMLType := XMLType(
    '<?xml version="1.0" ?> 
<person>
   <row>
       <name>Tom</name>
       <Address>
           <State>California</State>
           <City>Los angeles</City>
       </Address>
   </row>
   <row>
       <name>Jim</name>
       <Address>
           <State>California</State>
           <City>Los angeles</City>
       </Address>
   </row>
</person>');
BEGIN
  FOR r IN (
    SELECT ExtractValue(Value(p),'/row/name/text()') as name
          ,ExtractValue(Value(p),'/row/Address/State/text()') as state
          ,ExtractValue(Value(p),'/row/Address/City/text()') as city
    FROM   TABLE(XMLSequence(Extract(x,'/person/row'))) p
    ) LOOP
    -- do whatever you want with r.name, r.state, r.city
  END LOOP;
END;

Can't access to HttpContext.Current

Adding a bit to mitigate the confusion here. Even though Darren Davies' (accepted) answer is more straight forward, I think Andrei's answer is a better approach for MVC applications.

The answer from Andrei means that you can use HttpContext just as you would use System.Web.HttpContext.Current. For example, if you want to do this:

System.Web.HttpContext.Current.User.Identity.Name

you should instead do this:

HttpContext.User.Identity.Name

Both achieve the same result, but (again) in terms of MVC, the latter is more recommended.

Another good and also straight forward information regarding this matter can be found here: Difference between HttpContext.Current and Controller.Context in MVC ASP.NET.

How to directly move camera to current location in Google Maps Android API v2?

Just change moveCamera to animateCamera like below

Googlemap.animateCamera(CameraUpdateFactory.newLatLngZoom(locate, 16F))

how to read all files inside particular folder

You can use the DirectoryInfo.GetFiles method:

FileInfo[] files = DirectoryInfo.GetFiles("*.xml");

Inverse of matrix in R

solve(c) does give the correct inverse. The issue with your code is that you are using the wrong operator for matrix multiplication. You should use solve(c) %*% c to invoke matrix multiplication in R.

R performs element by element multiplication when you invoke solve(c) * c.

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

What is the reason for the error message "System cannot find the path specified"?

You just need to:

Step 1: Go home directory of C:\ with typing cd.. (2 times)

Step 2: It appears now C:\>

Step 3: Type dir Windows\System32\run

That's all, it shows complete files & folder details inside target folder.

enter image description here

Details: I used Windows\System32\com folder as example, you should type your own folder name etc. Windows\System32\run

Volley - POST/GET parameters

For the GET parameters there are two alternatives:

First: As suggested in a comment bellow the question you can just use String and replace the parameters placeholders with their values like:

String uri = String.format("http://somesite.com/some_endpoint.php?param1=%1$s&param2=%2$s",
                           num1,
                           num2);

StringRequest myReq = new StringRequest(Method.GET,
                                        uri,
                                        createMyReqSuccessListener(),
                                        createMyReqErrorListener());
queue.add(myReq);

where num1 and num2 are String variables that contain your values.

Second: If you are using newer external HttpClient (4.2.x for example) you can use URIBuilder to build your Uri. Advantage is that if your uri string already has parameters in it it will be easier to pass it to the URIBuilder and then use ub.setQuery(URLEncodedUtils.format(getGetParams(), "UTF-8")); to add your additional parameters. That way you will not bother to check if "?" is already added to the uri or to miss some & thus eliminating a source for potential errors.

For the POST parameters probably sometimes will be easier than the accepted answer to do it like:

StringRequest myReq = new StringRequest(Method.POST,
                                        "http://somesite.com/some_endpoint.php",
                                        createMyReqSuccessListener(),
                                        createMyReqErrorListener()) {

    protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        params.put("param1", num1);
        params.put("param2", num2);
        return params;
    };
};
queue.add(myReq);

e.g. to just override the getParams() method.

You can find a working example (along with many other basic Volley examples) in the Andorid Volley Examples project.

PHP regular expression - filter number only

You could do something like this if you want only whole numbers.

function make_whole($v){
    $v = floor($v);
    if(is_numeric($v)){
      echo (int)$v;
      // if you want only positive whole numbers
      //echo (int)$v = abs($v);
    }
}

How to show form input fields based on select value?

$('#dbType').change(function(){

   var selection = $(this).val();
   if(selection == 'other')
   {
      $('#otherType').show();
   }
   else
   {
      $('#otherType').hide();
   } 

});

Ways to eliminate switch in code

See the Switch Statements Smell:

Typically, similar switch statements are scattered throughout a program. If you add or remove a clause in one switch, you often have to find and repair the others too.

Both Refactoring and Refactoring to Patterns have approaches to resolve this.

If your (pseudo) code looks like:

class RequestHandler {

    public void handleRequest(int action) {
        switch(action) {
            case LOGIN:
                doLogin();
                break;
            case LOGOUT:
                doLogout();
                break;
            case QUERY:
               doQuery();
               break;
        }
    }
}

This code violates the Open Closed Principle and is fragile to every new type of action code that comes along. To remedy this you could introduce a 'Command' object:

interface Command {
    public void execute();
}

class LoginCommand implements Command {
    public void execute() {
        // do what doLogin() used to do
    }
}

class RequestHandler {
    private Map<Integer, Command> commandMap; // injected in, or obtained from a factory
    public void handleRequest(int action) {
        Command command = commandMap.get(action);
        command.execute();
    }
}

If your (pseudo) code looks like:

class House {
    private int state;

    public void enter() {
        switch (state) {
            case INSIDE:
                throw new Exception("Cannot enter. Already inside");
            case OUTSIDE:
                 state = INSIDE;
                 ...
                 break;
         }
    }
    public void exit() {
        switch (state) {
            case INSIDE:
                state = OUTSIDE;
                ...
                break;
            case OUTSIDE:
                throw new Exception("Cannot leave. Already outside");
        }
    }

Then you could introduce a 'State' object.

// Throw exceptions unless the behavior is overriden by subclasses
abstract class HouseState {
    public HouseState enter() {
        throw new Exception("Cannot enter");
    }
    public HouseState leave() {
        throw new Exception("Cannot leave");
    }
}

class Inside extends HouseState {
    public HouseState leave() {
        return new Outside();
    }
}

class Outside extends HouseState {
    public HouseState enter() {
        return new Inside();
    }
}

class House {
    private HouseState state;
    public void enter() {
        this.state = this.state.enter();
    }
    public void leave() {
        this.state = this.state.leave();
    }
}

Hope this helps.

Convert text into number in MySQL query

You can use SUBSTRING and CONVERT:

SELECT stuff
FROM table
WHERE conditions
ORDER BY CONVERT(SUBSTRING(name_column, 6), SIGNED INTEGER);

Where name_column is the column with the "name-" values. The SUBSTRING removes everything up before the sixth character (i.e. the "name-" prefix) and then the CONVERT converts the left over to a real integer.

UPDATE: Given the changing circumstances in the comments (i.e. the prefix can be anything), you'll have to throw a LOCATE in the mix:

ORDER BY CONVERT(SUBSTRING(name_column, LOCATE('-', name_column) + 1), SIGNED INTEGER);

This of course assumes that the non-numeric prefix doesn't have any hyphens in it but the relevant comment says that:

name can be any sequence of letters

so that should be a safe assumption.

What is the difference between AF_INET and PF_INET in socket programming?

In fact, AF_ and PF_ are the same thing. There are some words on Wikipedia will clear your confusion

The original design concept of the socket interface distinguished between protocol types (families) and the specific address types that each may use. It was envisioned that a protocol family may have several address types. Address types were defined by additional symbolic constants, using the prefix AF_ instead of PF_. The AF_-identifiers are intended for all data structures that specifically deal with the address type and not the protocol family. However, this concept of separation of protocol and address type has not found implementation support and the AF_-constants were simply defined by the corresponding protocol identifier, rendering the distinction between AF_ versus PF_ constants a technical argument of no significant practical consequence. Indeed, much confusion exists in the proper usage of both forms.

Detecting an undefined object property

function isUnset(inp) {
  return (typeof inp === 'undefined')
}

Returns false if variable is set, and true if is undefined.

Then use:

if (isUnset(var)) {
  // initialize variable here
}

Using StringWriter for XML Serialization

One problem with StringWriter is that by default it doesn't let you set the encoding which it advertises - so you can end up with an XML document advertising its encoding as UTF-16, which means you need to encode it as UTF-16 if you write it to a file. I have a small class to help with that though:

public sealed class StringWriterWithEncoding : StringWriter
{
    public override Encoding Encoding { get; }

    public StringWriterWithEncoding (Encoding encoding)
    {
        Encoding = encoding;
    }    
}

Or if you only need UTF-8 (which is all I often need):

public sealed class Utf8StringWriter : StringWriter
{
    public override Encoding Encoding => Encoding.UTF8;
}

As for why you couldn't save your XML to the database - you'll have to give us more details about what happened when you tried, if you want us to be able to diagnose/fix it.

Write string to text file and ensure it always overwrites the existing content.

Generally, FileMode.Create is what you're looking for.

"Register" an .exe so you can run it from any command line in Windows

it's amazing there's no simple solution for such a simple task on windows, I created this little cmd script that you can use to define aliases on windows (instructions are at the file header itself):

https://gist.github.com/benjamine/5992592

this is pretty much the same approach used by tools like NPM or ruby gems to register global commands.

How do I convert a String to an int in Java?

An alternate solution is to use Apache Commons' NumberUtils:

int num = NumberUtils.toInt("1234");

The Apache utility is nice because if the string is an invalid number format then 0 is always returned. Hence saving you the try catch block.

Apache NumberUtils API Version 3.4

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

jQuery get values of checked checkboxes into array

     var ids = [];

$('input[id="find-table"]:checked').each(function() {
   ids.push(this.value); 
});

This one worked for me!

Jquery onclick on div

Make sure it's within a document ready tagAlternatively, try using .live

$(document).ready(function(){

    $('#content').live('click', function(e) {  
        alert(1);
    });
});

Example:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    $('#content').click(function(e) {  _x000D_
      alert(1);_x000D_
    });_x000D_
});
_x000D_
#content {_x000D_
    padding: 20px;_x000D_
    background: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<div id="content">Hello world</div>
_x000D_
_x000D_
_x000D_

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.

$('#content').on( "click", function() {
    alert(1);
});

Phone validation regex

Adding to @Joe Johnston's answer, this will also accept:

+16444444444,,241119933

(Required for Apple's special character support for dial-ins - https://support.apple.com/kb/PH18551?locale=en_US)

\(?\+[0-9]{1,3}\)? ?-?[0-9]{1,3} ?-?[0-9]{3,5} ?-?[0-9]{4}( ?-?[0-9]{3})? ?([\w\,\@\^]{1,10}\s?\d{1,10})?

Note: Accepts upto 10 digits for extension code

How to get status code from webclient?

You can try this code to get HTTP status code from WebException or from OpenReadCompletedEventArgs.Error. It works in Silverlight too because SL does not have WebExceptionStatus.ProtocolError defined.

HttpStatusCode GetHttpStatusCode(System.Exception err)
{
    if (err is WebException)
    {
        WebException we = (WebException)err;
        if (we.Response is HttpWebResponse)
        {
            HttpWebResponse response = (HttpWebResponse)we.Response;
            return response.StatusCode;
        }
    }
    return 0;
}

How to escape % in String.Format?

To complement the previous stated solution, use:

str = str.replace("%", "%%");

Python: how to print range a-z?

list(string.ascii_lowercase)

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

How to set Toolbar text and back arrow color

If you use AndroidX (as of July 2019) you may add these:

<androidx.appcompat.widget.Toolbar
  android:id="@+id/toolbar"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  app:layout_collapseMode="pin"
  app:theme="@style/ThemeOverlay.MaterialComponents.Dark.ActionBar"
  app:popupTheme="@style/ThemeOverlay.MaterialComponents.Light"/>

NOTE! This was tested to work if your Toolbar is placed directly inside AppBarLayout but not inside CollapsingToolbarLayout

Print range of numbers on same line

Same can be achieved by using stdout.

>>> from sys import stdout
>>> for i in range(1,11):
...     stdout.write(str(i)+' ')
...
1 2 3 4 5 6 7 8 9 10 

Alternatively, same can be done by using reduce() :

>>> xrange = range(1,11)
>>> print reduce(lambda x, y: str(x) + ' '+str(y), xrange)
1 2 3 4 5 6 7 8 9 10
>>>

Validation error: "No validator could be found for type: java.lang.Integer"

As per the javadoc of NotEmpty, Integer is not a valid type for it to check. It's for Strings and collections. If you just want to make sure an Integer has some value, javax.validation.constraints.NotNull is all you need.

public @interface NotEmpty

Asserts that the annotated string, collection, map or array is not null or empty.

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

  • NOLOCK is local to the table (or views etc)
  • READ UNCOMMITTED is per session/connection

As for guidelines... a random search from StackOverflow and the electric interweb...

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

Can someone explain how to implement the jQuery File Upload plugin?

Check out the Image drag and drop uploader with image preview using dropper jquery plugin.

HTML

<div class="target" width="78" height="100"><img /></div>

JS

$(".target").dropper({
    action: "upload.php",

}).on("start.dropper", onStart);
function onStart(e, files){
console.log(files[0]);

    image_preview(files[0].file).then(function(res){
$('.dropper-dropzone').empty();
//$('.dropper-dropzone').css("background-image",res.data);
 $('#imgPreview').remove();        
$('.dropper-dropzone').append('<img id="imgPreview"/><span style="display:none">Drag and drop files or click to select</span>');
var widthImg=$('.dropper-dropzone').attr('width');
        $('#imgPreview').attr({width:widthImg});
    $('#imgPreview').attr({src:res.data});

    })

}

function image_preview(file){
    var def = new $.Deferred();
    var imgURL = '';
    if (file.type.match('image.*')) {
        //create object url support
        var URL = window.URL || window.webkitURL;
        if (URL !== undefined) {
            imgURL = URL.createObjectURL(file);
            URL.revokeObjectURL(file);
            def.resolve({status: 200, message: 'OK', data:imgURL, error: {}});
        }
        //file reader support
        else if(window.File && window.FileReader)
        {
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onloadend = function () {
                imgURL = reader.result;
                def.resolve({status: 200, message: 'OK', data:imgURL, error: {}});
            }
        }
        else {
            def.reject({status: 1001, message: 'File uploader not supported', data:imgURL, error: {}});
        }
    }
    else
        def.reject({status: 1002, message: 'File type not supported', error: {}});
    return def.promise();
}

$('.dropper-dropzone').mouseenter(function() {
 $( '.dropper-dropzone>span' ).css("display", "block");
});

$('.dropper-dropzone').mouseleave(function() {
 $( '.dropper-dropzone>span' ).css("display", "none");
});

CSS

.dropper-dropzone{
    width:78px;
padding:3px;
    height:100px;
position: relative;
}
.dropper-dropzone>img{
    width:78px;
    height:100px;
margin-top=0;
}

.dropper-dropzone>span {
    position: absolute;
    right: 10px;
    top: 20px;
color:#ccc;


}

.dropper .dropper-dropzone{

padding:3px !important    
}

Demo Jsfiddle

bash: pip: command not found

The updated command for installing pip3 is :

sudo apt-get install python3-pip

Can't use WAMP , port 80 is used by IIS 7.5

This happens to me once: I uninstalled the IIS, and the port 80 still was used. Well the problem was that also I had the Report Service of the Sql Server 2012 installed, so I stopped that service and the problems solves.

See Stop Or Uninstall IIS for running Wamp Server (Apache) on default port (:80) question for more details.

Hope this helps some body, as it help to me.

How to detect when a UIScrollView has finished scrolling

Just developed solution to detect when scrolling finished app-wide: https://gist.github.com/k06a/731654e3168277fb1fd0e64abc7d899e

It is based on idea of tracking changes of runloop modes. And perform blocks at least after 0.2 seconds after scrolling.

This is core idea for tracking runloop modes changes iOS10+:

- (void)tick {
    [[NSRunLoop mainRunLoop] performInModes:@[ UITrackingRunLoopMode ] block:^{
        [self tock];
    }];
}

- (void)tock {
    self.runLoopModeWasUITrackingAgain = YES;
    [[NSRunLoop mainRunLoop] performInModes:@[ NSDefaultRunLoopMode ] block:^{
        [self tick];
    }];
}

And solution for low deployment targets like iOS2+:

- (void)tick {
    [[NSRunLoop mainRunLoop] performSelector:@selector(tock) target:self argument:nil order:0 modes:@[ UITrackingRunLoopMode ]];
}

- (void)tock {
    self.runLoopModeWasUITrackingAgain = YES;
    [[NSRunLoop mainRunLoop] performSelector:@selector(tick) target:self argument:nil order:0 modes:@[ NSDefaultRunLoopMode ]];
}

How to convert nanoseconds to seconds using the TimeUnit enum?

This will convert a time to seconds in a double format, which is more precise than an integer value:

double elapsedTimeInSeconds = TimeUnit.MILLISECONDS.convert(elapsedTime, TimeUnit.NANOSECONDS) / 1000.0;

decimal vs double! - Which one should I use and when?

System.Single / float - 7 digits
System.Double / double - 15-16 digits
System.Decimal / decimal - 28-29 significant digits

The way I've been stung by using the wrong type (a good few years ago) is with large amounts:

  • £520,532.52 - 8 digits
  • £1,323,523.12 - 9 digits

You run out at 1 million for a float.

A 15 digit monetary value:

  • £1,234,567,890,123.45

9 trillion with a double. But with division and comparisons it's more complicated (I'm definitely no expert in floating point and irrational numbers - see Marc's point). Mixing decimals and doubles causes issues:

A mathematical or comparison operation that uses a floating-point number might not yield the same result if a decimal number is used because the floating-point number might not exactly approximate the decimal number.

When should I use double instead of decimal? has some similar and more in depth answers.

Using double instead of decimal for monetary applications is a micro-optimization - that's the simplest way I look at it.

TortoiseGit save user authentication / credentials

None of the above answers worked for me using git version 1.8.3.msysgit.0 and TortoiseGit 1.8.4.0.

In my particular situation, I have to connect to the remote git repo over HTTPS, using a full blown e-mail address as username. In this situation, wincred did not appear to work.

Using the email address as a part of the repo URL also did not work, as the software seems to be confused by the double appearance of the '@' character in the URL.

I did manage to overcome the problem using winstore. Here is what I did:

This will copy the git-credential-winstore.exe to a local directory and add two lines to your global .gitconfig. You can verify this by examining your global .gitconfig. This is easiest done via right mouse button on a folder, "TortoiseGit > Settings > Git > Edit global .gitconfig". The file should contain two lines like:

    [credential]
        helper = !'C:\\Users\\yourlogin\\AppData\\Roaming\\GitCredStore\\git-credential-winstore.exe'
  • No other TortoiseGit settings are needed under "Network" or "Credential". In particular: the "Credential helper" pull down menu under "Credential" will have gone blank as a result of these configuration lines, since TortoiseGit does not recognize the new helper. Do not set the pull down menu to another value or the global .gitconfig will be overwritten with an incorrect value! (*)

You are now ready to go:

  • Try to pull from the remote repository. You will notice an authentication popup asking your username and password, the popup should be visually different from the default TortoiseGit popup. This is a good sign and means winstore works. Enter the correct authentication and the pull should succeed.
  • Try the same pull again, and your username and password should no longer be asked.

Done! Enjoy your interactions with the remote repo while winstore takes care of the authentication.

(*) Alternatively, if you don't like the blank selection in the TortoiseGit Credential settings helper pull down menu, you can use the "Advanced" option:

  • Go to "TortoiseGit > Settings > Credential"
  • Select Credential helper "Advanced"
  • Click on the "G" (for global) under Helpers
  • Enter the Helper path as below. Note: a regular Windows path notation (e.g. "C:\Users...") will not work here, you have to replicate the exact line that installing winstore created in the global .gitconf without the "helper =" bit.

    !'C:\\Users\\yourlogin\\AppData\\Roaming\\GitCredStore\\git-credential-winstore.exe'
    
  • Click the "Add New/Save" button

How do you concatenate Lists in C#?

I know this is old but I came upon this post quickly thinking Concat would be my answer. Union worked great for me. Note, it returns only unique values but knowing that I was getting unique values anyway this solution worked for me.

namespace TestProject
{
    public partial class Form1 :Form
    {
        public Form1()
        {
            InitializeComponent();

            List<string> FirstList = new List<string>();
            FirstList.Add("1234");
            FirstList.Add("4567");

            // In my code, I know I would not have this here but I put it in as a demonstration that it will not be in the secondList twice
            FirstList.Add("Three");  

            List<string> secondList = GetList(FirstList);            
            foreach (string item in secondList)
                Console.WriteLine(item);
        }

        private List<String> GetList(List<string> SortBy)
        {
            List<string> list = new List<string>();
            list.Add("One");
            list.Add("Two");
            list.Add("Three");

            list = list.Union(SortBy).ToList();

            return list;
        }
    }
}

The output is:

One
Two
Three
1234
4567

What is the relative performance difference of if/else versus switch statement in Java?

According to Cliff Click in his 2009 Java One talk A Crash Course in Modern Hardware:

Today, performance is dominated by patterns of memory access. Cache misses dominate – memory is the new disk. [Slide 65]

You can get his full slides here.

Cliff gives an example (finishing on Slide 30) showing that even with the CPU doing register-renaming, branch prediction, and speculative execution, it's only able to start 7 operations in 4 clock cycles before having to block due to two cache misses which take 300 clock cycles to return.

So he says to speed up your program you shouldn't be looking at this sort of minor issue, but on larger ones such as whether you're making unnecessary data format conversions, such as converting "SOAP ? XML ? DOM ? SQL ? …" which "passes all the data through the cache".

Convert String to Calendar Object in Java

No new Calendar needs to be created, SimpleDateFormat already uses a Calendar underneath.

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.EN_US);
Date date = sdf.parse("Mon Mar 14 16:02:37 GMT 2011"));// all done
Calendar cal = sdf.getCalendar();

(I can't comment yet, that's why I created a new answer)

How to open a file / browse dialog using javascript?

Use this.

<script>
  function openFileOption()
{
  document.getElementById("file1").click();
}
</script>
     <input type="file" id="file1" style="display:none">
     <a href="#" onclick="openFileOption();return;">open File Dialog</a>

"document.getElementByClass is not a function"

It should be getElementsByClassName, and not getElementByClass. See this - https://developer.mozilla.org/en/DOM/document.getElementsByClassName.

Note that some browsers/versions may not support this.

best practice to generate random token for forgot password

This answers the 'best random' request:

Adi's answer1 from Security.StackExchange has a solution for this:

Make sure you have OpenSSL support, and you'll never go wrong with this one-liner

$token = bin2hex(openssl_random_pseudo_bytes(16));

1. Adi, Mon Nov 12 2018, Celeritas, "Generating an unguessable token for confirmation e-mails", Sep 20 '13 at 7:06, https://security.stackexchange.com/a/40314/

Get the value of a dropdown in jQuery

_x000D_
_x000D_
$('.leave_response').on('change', function() {_x000D_
    var responseId = $(this).val();_x000D_
    console.log(responseId);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<td>_x000D_
    <select class="leave_response" name="leave">_x000D_
        <option>1</option>_x000D_
        <option>2</option>_x000D_
        <option>3</option>_x000D_
        <option>4</option>_x000D_
    </select>_x000D_
</td>
_x000D_
_x000D_
_x000D_

MySQL query finding values in a comma separated string

You can achieve this by following function.

Run following query to create function.

DELIMITER ||
CREATE FUNCTION `TOTAL_OCCURANCE`(`commastring` TEXT, `findme`     VARCHAR(255)) RETURNS int(11)
NO SQL
-- SANI: First param is for comma separated string and 2nd for string to find.
return ROUND (   
    (
        LENGTH(commastring)
        - LENGTH( REPLACE ( commastring, findme, "") ) 
    ) / LENGTH(findme)        
);

And call this function like this

msyql> select TOTAL_OCCURANCE('A,B,C,A,D,X,B,AB', 'A');

How can I find and run the keytool

To get android key hash code follow these steps (for facebook apps)

  1. Download the openssl for windows here
  2. now unzip to c drive
  3. open cmd prompt
  4. type cd C:\Program Files\Java\jdk1.6.0_26\bin
  5. then type only keytool -export -alias myAlias -keystore C:\Users\<your user name>\.android\myKeyStore | C:\openssl-0.9.8k_WIN32\bin\openssl sha1 -binary | C:\openssl-0.9.8k_WIN32\bin\openssl enc -a -e
  6. Done

To get Certificate fingerprint(MD5) code follow these steps

  1. go to - C:\Program Files\Java\jdk1.6.0_26\bin
  2. inside the bin folder run the jarsigner.exe file
  3. open cmd prompt
  4. type cd C:\Program Files\Java\jdk1.6.0_26\bin
  5. then again type on cmd keytool -list -keystore "C:/Documents and Settings/<your user name>/.android/debug.keystore"
  6. it will ask for Keystore password now. The default is "android" type and enter
  7. Done.

Show Youtube video source into HTML5 video tag?

I have created a realtively small (4.89 KB) javascript library for this exact functionality.

Found on my GitHub here: https://github.com/thelevicole/youtube-to-html5-loader/

It's as simple as:

<video data-yt2html5="https://www.youtube.com/watch?v=ScMzIvxBSi4"></video>

<script src="https://cdn.jsdelivr.net/gh/thelevicole/[email protected]/dist/YouTubeToHtml5.js"></script>
<script>new YouTubeToHtml5();</script>

Working example here: https://jsfiddle.net/thelevicole/5g6dbpx3/1/

What the library does is extract the video ID from the data attribute and makes a request to the https://www.youtube.com/get_video_info?video_id=. It decodes the response which includes streaming information we can use to add a source to the <video> tag.

How to use java.Set

Did you override equals and hashCode in the Block class?

EDIT:

I assumed you mean it doesn't work at runtime... did you mean that or at compile time? If compile time what is the error message? If it crashes at runtime what is the stack trace? If it compiles and runs but doesn't work right then the equals and hashCode are the likely issue.

Get absolute path of initially run script

echo realpath(dirname(__FILE__));

If you place this in an included file, it prints the path to this include. To get the path of the parent script, replace __FILE__ with $_SERVER['PHP_SELF']. But be aware that PHP_SELF is a security risk!

What is the difference between localStorage, sessionStorage, session and cookies?

This is an extremely broad scope question, and a lot of the pros/cons will be contextual to the situation.

In all cases, these storage mechanisms will be specific to an individual browser on an individual computer/device. Any requirement to store data on an ongoing basis across sessions will need to involve your application server side - most likely using a database, but possibly XML or a text/CSV file.

localStorage, sessionStorage, and cookies are all client storage solutions. Session data is held on the server where it remains under your direct control.

localStorage and sessionStorage

localStorage and sessionStorage are relatively new APIs (meaning, not all legacy browsers will support them) and are near identical (both in APIs and capabilities) with the sole exception of persistence. sessionStorage (as the name suggests) is only available for the duration of the browser session (and is deleted when the tab or window is closed) - it does, however, survive page reloads (source DOM Storage guide - Mozilla Developer Network).

Clearly, if the data you are storing needs to be available on an ongoing basis then localStorage is preferable to sessionStorage - although you should note both can be cleared by the user so you should not rely on the continuing existence of data in either case.

localStorage and sessionStorage are perfect for persisting non-sensitive data needed within client scripts between pages (for example: preferences, scores in games). The data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser so should not be relied upon for storage of sensitive or security-related data within applications.

Cookies

This is also true for cookies, these can be trivially tampered with by the user, and data can also be read from them in plain text - so if you are wanting to store sensitive data then the session is really your only option. If you are not using SSL, cookie information can also be intercepted in transit, especially on an open wifi.

On the positive side cookies can have a degree of protection applied from security risks like Cross-Site Scripting (XSS)/Script injection by setting an HTTP only flag which means modern (supporting) browsers will prevent access to the cookies and values from JavaScript (this will also prevent your own, legitimate, JavaScript from accessing them). This is especially important with authentication cookies, which are used to store a token containing details of the user who is logged on - if you have a copy of that cookie then for all intents and purposes you become that user as far as the web application is concerned, and have the same access to data and functionality the user has.

As cookies are used for authentication purposes and persistence of user data, all cookies valid for a page are sent from the browser to the server for every request to the same domain - this includes the original page request, any subsequent Ajax requests, all images, stylesheets, scripts, and fonts. For this reason, cookies should not be used to store large amounts of information. The browser may also impose limits on the size of information that can be stored in cookies. Typically cookies are used to store identifying tokens for authentication, session, and advertising tracking. The tokens are typically not human readable information in and of themselves, but encrypted identifiers linked to your application or database.

localStorage vs. sessionStorage vs. Cookies

In terms of capabilities, cookies, sessionStorage, and localStorage only allow you to store strings - it is possible to implicitly convert primitive values when setting (these will need to be converted back to use them as their type after reading) but not Objects or Arrays (it is possible to JSON serialise them to store them using the APIs). Session storage will generally allow you to store any primitives or objects supported by your Server Side language/framework.

Client-side vs. Server-side

As HTTP is a stateless protocol - web applications have no way of identifying a user from previous visits on returning to the web site - session data usually relies on a cookie token to identify the user for repeat visits (although rarely URL parameters may be used for the same purpose). Data will usually have a sliding expiry time (renewed each time the user visits), and depending on your server/framework data will either be stored in-process (meaning data will be lost if the web server crashes or is restarted) or externally in a state server or database. This is also necessary when using a web-farm (more than one server for a given website).

As session data is completely controlled by your application (server side) it is the best place for anything sensitive or secure in nature.

The obvious disadvantage of server-side data is scalability - server resources are required for each user for the duration of the session, and that any data needed client side must be sent with each request. As the server has no way of knowing if a user navigates to another site or closes their browser, session data must expire after a given time to avoid all server resources being taken up by abandoned sessions. When using session data you should, therefore, be aware of the possibility that data will have expired and been lost, especially on pages with long forms. It will also be lost if the user deletes their cookies or switches browsers/devices.

Some web frameworks/developers use hidden HTML inputs to persist data from one page of a form to another to avoid session expiration.

localStorage, sessionStorage, and cookies are all subject to "same-origin" rules which means browsers should prevent access to the data except the domain that set the information to start with.

For further reading on client storage technologies see Dive Into Html 5.

How to pass in parameters when use resource service?

I think I see your problem, you need to use the @ syntax to define parameters you will pass in this way, also I'm not sure what loginID or password are doing you don't seem to define them anywhere and they are not being used as URL parameters so are they being sent as query parameters?

This is what I can suggest based on what I see so far:

.factory('MagComments', function ($resource) {
    return $resource('http://localhost/dooleystand/ci/api/magCommenct/:id', {
      loginID : organEntity,
      password : organCommpassword,
      id : '@magId'
    });
  })

The @magId string will tell the resource to replace :id with the property magId on the object you pass it as parameters.

I'd suggest reading over the documentation here (I know it's a bit opaque) very carefully and looking at the examples towards the end, this should help a lot.

SQL Server query to find all current database names

For people where "sys.databases" does not work, You can use this aswell;

SELECT DISTINCT TABLE_SCHEMA from INFORMATION_SCHEMA.COLUMNS

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

(server: ubuntu 14)

1.) install nvm (node version manager) https://github.com/creationix/nvm

2.) nvm install node

3.) npm -v (inquire npm version => 3.8.6)

4.) node -v (inquire node version => v6.0.0)

JSON library for C#

The .net framework supports JSON through JavaScriptSerializer. Here is a good example to get you started.

using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace GoogleTranslator.GoogleJSON
{
    public class FooTest
    {
        public void Test()
        {
            const string json = @"{
              ""DisplayFieldName"" : ""ObjectName"", 
              ""FieldAliases"" : {
                ""ObjectName"" : ""ObjectName"", 
                ""ObjectType"" : ""ObjectType""
              }, 
              ""PositionType"" : ""Point"", 
              ""Reference"" : {
                ""Id"" : 1111
              }, 
              ""Objects"" : [
                {
                  ""Attributes"" : {
                    ""ObjectName"" : ""test name"", 
                    ""ObjectType"" : ""test type""
                  }, 
                  ""Position"" : 
                  {
                    ""X"" : 5, 
                    ""Y"" : 7
                  }
                }
              ]
            }";

            var ser = new JavaScriptSerializer();
            ser.Deserialize<Foo>(json);
        }
    }

    public class Foo
    {
        public Foo() { Objects = new List<SubObject>(); }
        public string DisplayFieldName { get; set; }
        public NameTypePair FieldAliases { get; set; }
        public PositionType PositionType { get; set; }
        public Ref Reference { get; set; }
        public List<SubObject> Objects { get; set; }
    }

    public class NameTypePair
    {
        public string ObjectName { get; set; }
        public string ObjectType { get; set; }
    }

    public enum PositionType { None, Point }
    public class Ref
    {
        public int Id { get; set; }
    }

    public class SubObject
    {
        public NameTypePair Attributes { get; set; }
        public Position Position { get; set; }
    }

    public class Position
    {
        public int X { get; set; }
        public int Y { get; set; }
    }
}

How to prevent a jQuery Ajax request from caching in Internet Explorer?

If you set unique parameters, then the cache does not work, for example:

$.ajax({
    url : "my_url",
    data : {
        'uniq_param' : (new Date()).getTime(),
        //other data
    }});

Device not detected in Eclipse when connected with USB cable

ok this is an old thread -
but I spent nearly two days and did not get anywhere
Here is what solved my problem
I had USB debugging enabled ( finding developer options itself was a pain - I think the 7 times tap from google is childish and just plain stupid - rant over )

However HTC syn manager , eclipse ADT and windows computer management were all unable to identify my device

My problem was my phone was set to ONLY USB Charge - this was the problem In 'USB Computer connection' >> Choose the option USB Storage Once you do this - PC will install drivers and your device will get detected by Eclipse as well as in 'Computer Management' under ''Android USB devices '

Now I still dont know a way to access ''USB Computer connection' but at that time I did get the option to change and t worked

For those ( like me earlier ) who dont know how to identify if 'Computer Management' shows their device look for 'Android USB devices ' If its present - then your device is being detected by your PC

Hope this helps some others
shankar

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

If that is all you have changed, you may not have the mysqli driver installed or enabled within your PHP configuration.

Check for its presence using phpinfo(), or in your php.ini file (extension=php_mysqli....).

How do I split a string in Rust?

There's also split_whitespace()

fn main() {
    let words: Vec<&str> = "   foo   bar\t\nbaz   ".split_whitespace().collect();
    println!("{:?}", words);
    // ["foo", "bar", "baz"] 
}

Default values for Vue component props & how to check if a user did not set the prop?

This is an old question, but regarding the second part of the question - how can you check if the user set/didn't set a prop?

Inspecting this within the component, we have this.$options.propsData. If the prop is present here, the user has explicitly set it; default values aren't shown.

This is useful in cases where you can't really compare your value to its default, e.g. if the prop is a function.

Output a NULL cell value in Excel

As you've indicated, you can't output NULL in an excel formula. I think this has to do with the fact that the formula itself causes the cell to not be able to be NULL. "" is the next best thing, but sometimes it's useful to use 0.

--EDIT--

Based on your comment, you might want to check out this link. http://peltiertech.com/WordPress/mind-the-gap-charting-empty-cells/

It goes in depth on the graphing issues and what the various values represent, and how to manipulate their output on a chart.

I'm not familiar with VSTO I'm afraid. So I won't be much help there. But if you are really placing formulas in the cell, then there really is no way. ISBLANK() only tests to see if a cell is blank or not, it doesn't have a way to make it blank. It's possible to write code in VBA (and VSTO I imagine) that would run on a worksheet_change event and update the various values instead of using formulas. But that would be cumbersome and performance would take a hit.

Compare if BigDecimal is greater than zero

It's as simple as:

if (value.compareTo(BigDecimal.ZERO) > 0)

The documentation for compareTo actually specifies that it will return -1, 0 or 1, but the more general Comparable<T>.compareTo method only guarantees less than zero, zero, or greater than zero for the appropriate three cases - so I typically just stick to that comparison.

How to check if Receiver is registered in Android?

You have several options

  1. You can put a flag into your class or activity. Put a boolean variable into your class and look at this flag to know if you have the Receiver registered.

  2. Create a class that extends the Receiver and there you can use:

    1. Singleton pattern for only have one instance of this class in your project.

    2. Implement the methods for know if the Receiver is register.

Java - escape string to prevent SQL injection

From:Source

public String MysqlRealScapeString(String str){
  String data = null;
  if (str != null && str.length() > 0) {
    str = str.replace("\\", "\\\\");
    str = str.replace("'", "\\'");
    str = str.replace("\0", "\\0");
    str = str.replace("\n", "\\n");
    str = str.replace("\r", "\\r");
    str = str.replace("\"", "\\\"");
    str = str.replace("\\x1a", "\\Z");
    data = str;
  }
  return data;
}

Convert String to System.IO.Stream

this is old but for help :

you can also use the stringReader stream

string str = "asasdkopaksdpoadks";
StringReader TheStream = new StringReader( str );

Create dataframe from a matrix

If you change your time column into row names, then you can use as.data.frame(as.table(mat)) for simple cases like this.

Example:

data <- c(0.1, 0.2, 0.3, 0.3, 0.4, 0.5)
dimnames <- list(time=c(0, 0.5, 1), name=c("C_0", "C_1"))
mat <- matrix(data, ncol=2, nrow=3, dimnames=dimnames)
as.data.frame(as.table(mat))
  time name Freq
1    0  C_0  0.1
2  0.5  C_0  0.2
3    1  C_0  0.3
4    0  C_1  0.3
5  0.5  C_1  0.4
6    1  C_1  0.5

In this case time and name are both factors. You may want to convert time back to numeric, or it may not matter.

How to convert text to binary code in JavaScript?

The other answers will work for most cases. But it's worth noting that charCodeAt() and related don't work with UTF-8 strings (that is, they throw errors if there are any characters outside the standard ASCII range). Here's a workaround.

// UTF-8 to binary
var utf8ToBin = function( s ){
    s = unescape( encodeURIComponent( s ) );
    var chr, i = 0, l = s.length, out = '';
    for( ; i < l; i ++ ){
        chr = s.charCodeAt( i ).toString( 2 );
        while( chr.length % 8 != 0 ){ chr = '0' + chr; }
        out += chr;
    }
    return out;
};

// Binary to UTF-8
var binToUtf8 = function( s ){
    var i = 0, l = s.length, chr, out = '';
    for( ; i < l; i += 8 ){
        chr = parseInt( s.substr( i, 8 ), 2 ).toString( 16 );
        out += '%' + ( ( chr.length % 2 == 0 ) ? chr : '0' + chr );
    }
    return decodeURIComponent( out );
};

The escape/unescape() functions are deprecated. If you need polyfills for them, you can check out the more comprehensive UTF-8 encoding example found here: http://jsfiddle.net/47zwb41o

Parse string to DateTime in C#

var dateStr = @"2011-03-21 13:26";
var dateTime = DateTime.ParseExact(dateStr, "yyyy-MM-dd HH:mm", CultureInfo.CurrentCulture);

Check out this link for other format strings!

Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?

I feel like this has been well covered, maybe except for the following:

  • Simple KEY / INDEX (or otherwise called SECONDARY INDEX) do increase performance if selectivity is sufficient. On this matter, the usual recommendation is that if the amount of records in the result set on which an index is applied exceeds 20% of the total amount of records of the parent table, then the index will be ineffective. In practice each architecture will differ but, the idea is still correct.

  • Secondary Indexes (and that is very specific to mysql) should not be seen as completely separate and different objects from the primary key. In fact, both should be used jointly and, once this information known, provide an additional tool to the mysql DBA: in Mysql, indexes embed the primary key. It leads to significant performance improvements, specifically when cleverly building implicit covering indexes such as described there.

  • If you feel like your data should be UNIQUE, use a unique index. You may think it's optional (for instance, working it out at application level) and that a normal index will do, but it actually represents a guarantee for Mysql that each row is unique, which incidentally provides a performance benefit.

  • You can only use FULLTEXT (or otherwise called SEARCH INDEX) with Innodb (In MySQL 5.6.4 and up) and Myisam Engines

  • You can only use FULLTEXT on CHAR, VARCHAR and TEXT column types

  • FULLTEXT index involves a LOT more than just creating an index. There's a bunch of system tables created, a completely separate caching system and some specific rules and optimizations applied. See http://dev.mysql.com/doc/refman/5.7/en/fulltext-restrictions.html and http://dev.mysql.com/doc/refman/5.7/en/innodb-fulltext-index.html

The use of Swift 3 @objc inference in Swift 4 mode is deprecated?

I'm an occasional iOS dev (soon to be more) but I still couldn't find the setting as guided by the other answer (since I did not have that Keychain item the answer shows), so now that I found it I thought I might just add this snapshot with the highlighted locations that you will need to click and find.

  1. Start in the upper left
  2. Choose the project folder icon
  3. Choose your main project name below the project folder icon.
  4. Choose Build Settings on the right side.
  5. Choose your project under TARGETS.
  6. Scroll very far down (or search for the word inference in search text box)

Finding the setting

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

You should use

 SSLContext.getInstance("TLSv1.2"); 

for specific protocol version.

The second exception occured because default socketFactory used fallback SSLv3 protocol for failures.

You can use NoSSLFactory from main answer here for its suppression How to disable SSLv3 in android for HttpsUrlConnection?

Also you should init SSLContext with all your certificates(client and trusted ones if you need them)

But all of that is useless without using

ProviderInstaller.installIfNeeded(getContext())

Here is more information with proper usage scenario https://developer.android.com/training/articles/security-gms-provider.html

Hope it helps.

MSOnline can't be imported on PowerShell (Connect-MsolService error)

After reviewing Microsoft's TechNet article "Azure Active Directory Cmdlets" -> section "Install the Azure AD Module", it seems that this process has been drastically simplified, thankfully.

As of 2016/06/30, in order to successfully execute the PowerShell commands Import-Module MSOnline and Connect-MsolService, you will need to install the following applications (64-bit only):

  1. Applicable Operating Systems: Windows 7 to 10
    Name: "Microsoft Online Services Sign-in Assistant for IT Professionals RTW"
    Version: 7.250.4556.0 (latest)
    Installer URL: https://www.microsoft.com/en-us/download/details.aspx?id=41950
    Installer file name: msoidcli_64.msi
  2. Applicable Operating Systems: Windows 7 to 10
    Name: "Windows Azure Active Directory Module for Windows PowerShell"
    Version: Unknown but the latest installer file's SHA-256 hash is D077CF49077EE133523C1D3AE9A4BF437D220B16D651005BBC12F7BDAD1BF313
    Installer URL: https://technet.microsoft.com/en-us/library/dn975125.aspx
    Installer file name: AdministrationConfig-en.msi
  3. Applicable Operating Systems: Windows 7 only
    Name: "Windows PowerShell 3.0"
    Version: 3.0 (later versions will probably work too)
    Installer URL: https://www.microsoft.com/en-us/download/details.aspx?id=34595
    Installer file name: Windows6.1-KB2506143-x64.msu

 

enter image description here enter image description here enter image description here

CURL to pass SSL certifcate and password

Addition to previous answer make sure that your curl installation supports https.
You can use curl --version to get information about supported protocols.

If your curl supports https follow the previous answer.

curl --cert certificate_path:password https://www.example.com

If it does not support https, you need to install a cURL version that supports https.

SQL: Group by minimum value in one field while selecting distinct rows

This a old question, but this can useful for someone In my case i can't using a sub query because i have a big query and i need using min() on my result, if i use sub query the db need reexecute my big query. i'm using Mysql

select t.* 
    from (select m.*, @g := 0
        from MyTable m --here i have a big query
        order by id, record_date) t
    where (1 = case when @g = 0 or @g <> id then 1 else  0 end )
          and (@g := id) IS NOT NULL

Basically I ordered the result and then put a variable in order to get only the first record in each group.

How to use Google fonts in React.js?

you should see this tutorial: https://scotch.io/@micwanyoike/how-to-add-fonts-to-a-react-project

import WebFont from 'webfontloader';

WebFont.load({
  google: {
    families: ['Titillium Web:300,400,700', 'sans-serif']
  }
});

I just tried this method and I can say that it works very well ;)

phpmyadmin "Not Found" after install on Apache, Ubuntu

Create a link in /var/www/html like this to fix the error:

sudo ln -s /usr/share/phpmyadmin /var/www/html

jump to line X in nano editor

The shortcut is: CTRL+shift+- ("shift+-" results in "_") After typing the shortcut, nano will let you to enter the line you wanna jump to, type in the line number, then press ENTR.

sqlite copy data from one table to another

If you have data already present in both the tables and you want to update a table column values based on some condition then use this

UPDATE Table1 set Name=(select t2.Name from Table2 t2 where t2.id=Table1.id)

How to get substring from string in c#?

Here is example of getting substring from 14 character to end of string. You can modify it to fit your needs

string text = "Retrieves a substring from this instance. The substring starts at a specified character position.";
//get substring where 14 is start index
string substring = text.Substring(14);

How can I use MS Visual Studio for Android Development?

Yes you can:

http://www.gavpugh.com/2011/02/04/vs-android-developing-for-android-in-visual-studio/

enter image description here

In case you get "Unable to locate tools.jar. Expected to find it in C:\Program Files (x86)\Java\jre6\lib\tools.jar" you can add an environment variable JAVA_HOME that points to your Java JDK path, for example c:\sdks\glassfish3\jdk (restart MSVC afterwards)

An even better solution is using WinGDB Mobile Edition in Visual Studio: it lets you create and debug Android projects all inside Visual Studio:

http://ian-ni-lewis.blogspot.com/2011/01/its-like-coming-home-again.html

Download WinGDC for Android from http://www.wingdb.com/wgMobileEdition.htm

Histogram Matplotlib

If you don't want bars you can plot it like this:

import numpy as np
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

bins, edges = np.histogram(x, 50, normed=1)
left,right = edges[:-1],edges[1:]
X = np.array([left,right]).T.flatten()
Y = np.array([bins,bins]).T.flatten()

plt.plot(X,Y)
plt.show()

histogram

How to use glob() to find files recursively?

You'll want to use os.walk to collect filenames that match your criteria. For example:

import os
cfiles = []
for root, dirs, files in os.walk('src'):
  for file in files:
    if file.endswith('.c'):
      cfiles.append(os.path.join(root, file))

How to change max_allowed_packet size

If you want upload big size image or data in database. Just change the data type to 'BIG BLOB'.

Check if a parameter is null or empty in a stored procedure

If you want to use a parameter is Optional so use it.

CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL, @AddressLine1 nvarchar(60) = NULL
    AS
    SELECT *
    FROM AdventureWorks.Person.Address
    WHERE City = ISNULL(@City,City)
    AND AddressLine1 LIKE '%' + ISNULL(@AddressLine1 ,AddressLine1) + '%'
    GO

Javascript : Send JSON Object with Ajax?

If you`re not using jQuery then please make sure:

var json_upload = "json_name=" + JSON.stringify({name:"John Rambo", time:"2pm"});
var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
xmlhttp.open("POST", "/file.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send(json_upload);

And for the php receiving end:

 $_POST['json_name'] 

JVM option -Xss - What does it do exactly?

If I am not mistaken, this is what tells the JVM how much successive calls it will accept before issuing a StackOverflowError. Not something you wish to change generally.

How to create a Custom Dialog box in android?

Full Screen Custom Alert Dialog Class in Kotlin

  1. Create XML file, same as you would an activity

  2. Create AlertDialog custom class

    class Your_Class(context:Context) : AlertDialog(context){
    
     init {
      requestWindowFeature(Window.FEATURE_NO_TITLE)
      setCancelable(false)
     }
    
     override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.your_Layout)
      val window = this.window
      window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                         WindowManager.LayoutParams.MATCH_PARENT)
    
      //continue custom code here
      //call dismiss() to close
     }
    }
    
  3. Call the dialog within the activity

    val dialog = Your_Class(this)
    //can set some dialog options here
    dialog.show()
    

Note**: If you do not want your dialog to be full screen, delete the following lines

      val window = this.window
      window?.setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                         WindowManager.LayoutParams.MATCH_PARENT)

Then edit the layout_width & layout_height of your top layout within your XML file to be either wrap_content or a fixed DP value.

I generally do not recommend using fixed DP as you would likely want your app to be adaptable to multiple screen sizes, however if you keep your size values small enough you should be fine

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

You can try this command in the Terminal:

git config --global http.sslVerify false

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

In Python 3, the reduce has been removed: Release notes. Nevertheless you can use the functools module

import operator, functools
def product(xs):
    return functools.reduce(operator.mul, xs, 1)

On the other hand, the documentation expresses preference towards for-loop instead of reduce, hence:

def product(xs):
    result = 1
    for i in xs:
        result *= i
    return result

Switch statement equivalent in Windows batch file

Compact form for short commands (no 'echo'):

IF "%ID%"=="0" ( ... & ... & ... ) ELSE ^
IF "%ID%"=="1" ( ... ) ELSE ^
IF "%ID%"=="2" ( ... ) ELSE ^
REM default case...

After ^ must be an immediate line end, no spaces.

How to unsubscribe to a broadcast event in angularJS. How to remove function registered via $on

Register a hook to unsubscribe your listeners when the component is removed:

$scope.$on('$destroy', function () {
   delete $rootScope.$$listeners["youreventname"];
});  

What do hjust and vjust do when making a plot using ggplot?

The value of hjust and vjust are only defined between 0 and 1:

  • 0 means left-justified
  • 1 means right-justified

Source: ggplot2, Hadley Wickham, page 196

(Yes, I know that in most cases you can use it beyond this range, but don't expect it to behave in any specific way. This is outside spec.)

hjust controls horizontal justification and vjust controls vertical justification.

An example should make this clear:

td <- expand.grid(
    hjust=c(0, 0.5, 1),
    vjust=c(0, 0.5, 1),
    angle=c(0, 45, 90),
    text="text"
)

ggplot(td, aes(x=hjust, y=vjust)) + 
    geom_point() +
    geom_text(aes(label=text, angle=angle, hjust=hjust, vjust=vjust)) + 
    facet_grid(~angle) +
    scale_x_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2)) +
    scale_y_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2))

enter image description here


To understand what happens when you change the hjust in axis text, you need to understand that the horizontal alignment for axis text is defined in relation not to the x-axis, but to the entire plot (where this includes the y-axis text). (This is, in my view, unfortunate. It would be much more useful to have the alignment relative to the axis.)

DF <- data.frame(x=LETTERS[1:3],y=1:3)
p <- ggplot(DF, aes(x,y)) + geom_point() + 
    ylab("Very long label for y") +
    theme(axis.title.y=element_text(angle=0))


p1 <- p + theme(axis.title.x=element_text(hjust=0)) + xlab("X-axis at hjust=0")
p2 <- p + theme(axis.title.x=element_text(hjust=0.5)) + xlab("X-axis at hjust=0.5")
p3 <- p + theme(axis.title.x=element_text(hjust=1)) + xlab("X-axis at hjust=1")

library(ggExtra)
align.plots(p1, p2, p3)

enter image description here


To explore what happens with vjust aligment of axis labels:

DF <- data.frame(x=c("a\na","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()

p1 <- p + theme(axis.text.x=element_text(vjust=0, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0")
p2 <- p + theme(axis.text.x=element_text(vjust=0.5, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0.5")
p3 <- p + theme(axis.text.x=element_text(vjust=1, colour="red")) + 
        xlab("X-axis labels aligned with vjust=1")


library(ggExtra)
align.plots(p1, p2, p3)

enter image description here

How to get the ASCII value of a character

You are looking for:

ord()

How do I encode URI parameter values?

Mmhh I know you've already discarded URLEncoder, but despite of what the docs say, I decided to give it a try.

You said:

For example, given an input:

http://google.com/resource?key=value

I expect the output:

http%3a%2f%2fgoogle.com%2fresource%3fkey%3dvalue

So:

C:\oreyes\samples\java\URL>type URLEncodeSample.java
import java.net.*;

public class URLEncodeSample {
    public static void main( String [] args ) throws Throwable {
        System.out.println( URLEncoder.encode( args[0], "UTF-8" ));
    }
}

C:\oreyes\samples\java\URL>javac URLEncodeSample.java

C:\oreyes\samples\java\URL>java URLEncodeSample "http://google.com/resource?key=value"
http%3A%2F%2Fgoogle.com%2Fresource%3Fkey%3Dvalue

As expected.

What would be the problem with this?

how to use #ifdef with an OR condition?

Like this

#if defined(LINUX) || defined(ANDROID)

Add padding to HTML text input field

padding-right should work. Example linked.

http://jsfiddle.net/8Ged8/

How to name and retrieve a stash by name in git?

Late to the party here, but if using VSCode, a quick way to do so is to open the command palette (CTRL / CMD + SHIFT + P) and type "Pop Stash", you'll be able to retrieve your stash by name without the need to use git CLI

How can you use optional parameters in C#?

Another option is to use the params keyword

public void DoSomething(params object[] theObjects)
{
  foreach(object o in theObjects)
  {
    // Something with the Objects…
  }
}

Called like...

DoSomething(this, that, theOther);

Convert date to day name e.g. Mon, Tue, Wed

For other language use day of week to recognize day name

For example for Persian use below code

$dayName = getDayName(date('w', strtotime('2019-11-14')));

    function getDayName($dayOfWeek) {

        switch ($dayOfWeek){
            case 6:
                return '????';
            case 0:
                return '?? ????';
            case 1:
                return '?? ????';
            case 2:
                return '?? ????';
            case 3:
                return '???? ????';
            case 4:
                return '??? ????';
            case 5:
                return '????';
            default:
                return '';
        }

    }

More info : https://www.php.net/manual/en/function.date.php

Regular Expression with wildcards to match any character

The following should work:

ABC: *\([a-zA-Z]+\) *(.+)

Explanation:

ABC:            # match literal characters 'ABC:'
 *              # zero or more spaces
\([a-zA-Z]+\)   # one or more letters inside of parentheses
 *              # zero or more spaces
(.+)            # capture one or more of any character (except newlines)

To get your desired grouping based on the comments below, you can use the following:

(ABC:) *(\([a-zA-Z]+\).+)

Java Hashmap: How to get key from value?

Let the value be maxValue.

Set keySet = map.keySet();

keySet.stream().filter(x->map.get(x)==maxValue).forEach(x-> System.out.println(x));

initialize a numpy array

I realize that this is a bit late, but I did not notice any of the other answers mentioning indexing into the empty array:

big_array = numpy.empty(10, 4)
for i in range(5):
    array_i = numpy.random.random(2, 4)
    big_array[2 * i:2 * (i + 1), :] = array_i

This way, you preallocate the entire result array with numpy.empty and fill in the rows as you go using indexed assignment.

It is perfectly safe to preallocate with empty instead of zeros in the example you gave since you are guaranteeing that the entire array will be filled with the chunks you generate.

Counter exit code 139 when running, but gdb make it through

exit code 139 (people say this means memory fragmentation)

No, it means that your program died with signal 11 (SIGSEGV on Linux and most other UNIXes), also known as segmentation fault.

Could anybody tell me why the run fails but debug doesn't?

Your program exhibits undefined behavior, and can do anything (that includes appearing to work correctly sometimes).

Your first step should be running this program under Valgrind, and fixing all errors it reports.

If after doing the above, the program still crashes, then you should let it dump core (ulimit -c unlimited; ./a.out) and then analyze that core dump with GDB: gdb ./a.out core; then use where command.

Change the bullet color of list

I would recommend you to use background-image instead of default list.

.listStyle {
    list-style: none;
    background: url(image_path.jpg) no-repeat left center;
    padding-left: 30px;
    width: 20px;
    height: 20px;
}

Or, if you don't want to use background-image as bullet, there is an option to do it with pseudo element:

.liststyle{
    list-style: none;
    margin: 0;
    padding: 0;
}
.liststyle:before {
    content: "• ";
    color: red; /* or whatever color you prefer */
    font-size: 20px;/* or whatever the bullet size you prefer */
}

How to modify PATH for Homebrew?

open bash profile in textEdit

open -e .bash_profile

Edit file or paste in front of PATH export PATH=/usr/bin:/usr/sbin:/bin:/sbin:/usr/local/bin:/usr/local/sbin:~/bin

save & close the file

*To open .bash_profile directly open textEdit > file > recent

How to make sure docker's time syncs with that of the host?

docker-compose usage:

Add /etc/localtime:/etc/localtime:ro to the volumes attribute:

version: '3'

services:
  a-service:
      image: service-name
      container_name: container-name
      volumes:
        - /etc/localtime:/etc/localtime:ro

Adding ASP.NET MVC5 Identity Authentication to an existing project

I recommend IdentityServer.This is a .NET Foundation project and covers many issues about authentication and authorization.

Overview

IdentityServer is a .NET/Katana-based framework and hostable component that allows implementing single sign-on and access control for modern web applications and APIs using protocols like OpenID Connect and OAuth2. It supports a wide range of clients like mobile, web, SPAs and desktop applications and is extensible to allow integration in new and existing architectures.

For more information, e.g.

  • support for MembershipReboot and ASP.NET Identity based user stores
  • support for additional Katana authentication middleware (e.g. Google, Twitter, Facebook etc)
  • support for EntityFramework based persistence of configuration
  • support for WS-Federation
  • extensibility

check out the documentation and the demo.

Bootstrap select dropdown list placeholder

Using bootstrap, if you need to also add some values to the option to use for filters or other stuff you can simply add the class "bs-title-option" to the option that you want as a placeholder:

<select class="form-group">
   <option class="bs-title-option" value="myVal">My PlaceHolder</option>
   <option>A</option>
   <option>B</option>
   <option>c</option>
</select>

Bootstrap adds this class to the title attribute.

mysql extract year from date format

SELECT EXTRACT(YEAR FROM subdateshow) FROM tbl_name;

Method call if not null in C#

I have made this generic extension that I use.

public static class ObjectExtensions {
    public static void With<T>(this T value, Action<T> todo) {
        if (value != null) todo(value);
    }
}

Then I use it like below.

string myString = null;
myString.With((value) => Console.WriteLine(value)); // writes nothing
myString = "my value";
myString.With((value) => Console.WriteLine(value)); // Writes `my value`

Creating default object from empty value in PHP?

This is a warning which I faced in PHP 7, the easy fix to this is by initializing the variable before using it

$myObj=new \stdClass();

Once you have intialized it then you can use it for objects

 $myObj->mesg ="Welcome back - ".$c_user;

How to correctly get image from 'Resources' folder in NetBeans

This was a pain, using netBeans IDE 7.2.

  1. You need to remember that Netbeans cleans up the Build folder whenever you rebuild, so
  2. Add a resource folder to the src folder:

    • (project)
      • src
        • project package folder (contains .java files)
        • resources (whatever name you want)
        • images (optional subfolders)
  3. After the clean/build this structure is propogated into the Build folder:

    • (project)
      • build
        • classes
          • project package folder (contains generated .class files)
          • resources (your resources)
          • images (your optional subfolders)

To access the resources:

dlabel = new JLabel(new ImageIcon(getClass().getClassLoader().getResource("resources/images/logo.png")));

and:

if (common.readFile(getClass().getResourceAsStream("/resources/allwise.ini"), buf).equals("OK")) {

worked for me. Note that in one case there is a leading "/" and in the other there isn't. So the root of the path to the resources is the "classes" folder within the build folder.

Double click on the executable jar file in the dist folder. The path to the resources still works.

Bootstrap: how do I change the width of the container?

Use a wrapper selector and create a container that has a 100% width inside of that wrapper to encapsulate the entire page.

<style>#wrapper {width: 1000px;} 
#wrapper .container {max-width: 100%; display: block;}</style>
<body>
<div id="wrapper">
  <div class="container">
    <div class="row">....

Now the maximum width is set to 1000px and you need no less or sass.

Installing tensorflow with anaconda in windows

activate tensorflow

conda install -c conda-forge tensorflow worked for me.

None of the other steps mentioned online helped, I found it here when trying to install an older version.

Eventhough the steps mentioned in the link seems to be for MAC OS X/Linux it worked in windows 7

You can install spyder along with this conda install spyder

Export data from R to Excel

Here is a way to write data from a dataframe into an excel file by different IDs and into different tabs (sheets) by another ID associated to the first level id. Imagine you have a dataframe that has email_address as one column for a number of different users, but each email has a number of 'sub-ids' that have all the data.

data <- tibble(id = c(1,2,3,4,5,6,7,8,9), email_address = c(rep('[email protected]',3), rep('[email protected]', 3), rep('[email protected]', 3)))

So ids 1,2,3 would be associated with [email protected]. The following code splits the data by email and then puts 1,2,3 into different tabs. The important thing is to set append = True when writing the .xlsx file.


temp_dir <- tempdir()

for(i in unique(data$email_address)){
    
  data %>% 
    filter(email_address == i) %>% 
    arrange(id) -> subset_data
  
  for(j in unique(subset_data$id)){
    write.xlsx(subset_data %>% filter(id == j), 
      file = str_c(temp_dir,"/your_filename_", str_extract(i, pattern = "\\b[A-Za-z0- 
       9._%+-]+"),'_', Sys.Date(), '.xlsx'), 
      sheetName = as.character(j), 
      append = TRUE)}
 
  }

The regex gets the name from the email address and puts it into the file-name.

Hope somebody finds this useful. I'm sure there's more elegant ways of doing this but it works.

Btw, here is a way to then send these individual files to the various email addresses in the data.frame. Code goes into second loop [j]

  send.mail(from = "[email protected]",
            to = i,
          subject = paste("Your report for", str_extract(i, pattern = "\\b[A-Za-z0-9._%+-]+"), 'on', Sys.Date()),
          body = "Your email body",
          authenticate = TRUE,
          smtp = list(host.name = "XXX", port = XXX,
                      user.name = Sys.getenv("XXX"), passwd = Sys.getenv("XXX")),
          attach.files = str_c(temp_dir, "/your_filename_", str_extract(i, pattern = "\\b[A-Za-z0-9._%+-]+"),'_', Sys.Date(), '.xlsx'))


Map to String in Java

You can also use google-collections (guava) Joiner class if you want to customize the print format

How to convert Nonetype to int or string?

This can happen if you forget to return a value from a function: it then returns None. Look at all places where you are assigning to that variable, and see if one of them is a function call where the function lacks a return statement.

How to read a text file from server using JavaScript?

You can use hidden frame, load the file in there and parse its contents.

HTML:

<iframe id="frmFile" src="test.txt" onload="LoadFile();" style="display: none;"></iframe>

JavaScript:

<script type="text/javascript">
function LoadFile() {
    var oFrame = document.getElementById("frmFile");
    var strRawContents = oFrame.contentWindow.document.body.childNodes[0].innerHTML;
    while (strRawContents.indexOf("\r") >= 0)
        strRawContents = strRawContents.replace("\r", "");
    var arrLines = strRawContents.split("\n");
    alert("File " + oFrame.src + " has " + arrLines.length + " lines");
    for (var i = 0; i < arrLines.length; i++) {
        var curLine = arrLines[i];
        alert("Line #" + (i + 1) + " is: '" + curLine + "'");
    }
}
</script>

Note: in order for this to work in Chrome browser, you should start it with the --allow-file-access-from-files flag. credit.

Set Canvas size using javascript

function setWidth(width) {
  var canvas = document.getElementById("myCanvas");  
  canvas.width = width;
}

Retrieving data from a POST method in ASP.NET

You need to examine (put a breakpoint on / Quick Watch) the Request object in the Page_Load method of your Test.aspx.cs file.

Get date from input form within PHP

Validate the INPUT.

$time = strtotime($_POST['dateFrom']);
if ($time) {
  $new_date = date('Y-m-d', $time);
  echo $new_date;
} else {
   echo 'Invalid Date: ' . $_POST['dateFrom'];
  // fix it.
}

How to save the output of a console.log(object) to a file?

right click on console.. click save as.. its this simple.. you'll get an output text file

Sorting using Comparator- Descending order (User defined classes)

package com.test;

import java.util.Arrays;

public class Person implements Comparable {

private int age;

private Person(int age) {
    super();
    this.age = age;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}

@Override
public int compareTo(Object o) {
    Person other = (Person)o;
    if (this == other)
        return 0;
    if (this.age < other.age) return 1;
    else if (this.age == other.age) return 0;
    else return -1;

}

public static void main(String[] args) {

    Person[] arr = new Person[4];
    arr[0] = new Person(50);
    arr[1] = new Person(20);
    arr[2] = new Person(10);
    arr[3] = new Person(90);

    Arrays.sort(arr);

    for (int i=0; i < arr.length; i++ ) {
        System.out.println(arr[i].age);
    }
}

}

Here is one way of doing it.

nodemon command is not recognized in terminal for node js server

I was facing the same issue. I had installed nodemon as a dev-dependency and when I tried to start the server it gave the message that

nodemon is not recognized as internal or external command, operable program or batch file

Then I installed it globally and tried to start the server and it worked!

npm install -g nodemon

Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister

I resolved this issue by excluding byte-buddy dependency from springfox

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger2</artifactId>
  <version>2.7.0</version>
  <exclusions>
  <exclusion>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy</artifactId>
  </exclusion>
  </exclusions>
</dependency>

<dependency>
  <groupId>io.springfox</groupId>
  <artifactId>springfox-swagger-ui</artifactId>
  <version>2.7.0</version>
  <exclusions>
  <exclusion>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy</artifactId>
  </exclusion>
</exclusions>
</dependency>

What is the proper way to format a multi-line dict in Python?

Since your keys are strings and since we are talking about readability, I prefer :

mydict = dict(
    key1 = 1,
    key2 = 2,
    key3 = 3
)

How to add (vertical) divider to a horizontal LinearLayout?

I just ran into the same problem today. As the previous answers indicate, the problem stems from the use of a color in the divider tag, rather than a drawable. However, instead of writing my own drawable xml, I prefer to use themed attributes as much as possible. You can use the android:attr/dividerHorizontal and android:attr/dividerVertical to get a predefined drawable instead:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:showDividers="middle"
    android:divider="?android:attr/dividerVertical"
    android:orientation="horizontal">
    <!-- other views -->
</LinearLayout>

The attributes are available in API 11 and above.

Also, as mentioned by bocekm in his answer, the dividerPadding property does NOT add extra padding on either side of a vertical divider, as one might assume. Instead it defines top and bottom padding and thus may truncate the divider if it's too large.

How can I store the result of a system command in a Perl variable?

From Perlfaq8:

You're confusing the purpose of system() and backticks (``). system() runs a command and returns exit status information (as a 16 bit value: the low 7 bits are the signal the process died from, if any, and the high 8 bits are the actual exit value). Backticks (``) run a command and return what it sent to STDOUT.

$exit_status   = system("mail-users");
$output_string = `ls`;

There are many ways to execute external commands from Perl. The most commons with their meanings are:

  • system() : you want to execute a command and don't want to capture its output
  • exec: you don't want to return to the calling perl script
  • backticks : you want to capture the output of the command
  • open: you want to pipe the command (as input or output) to your script

Also see How can I capture STDERR from an external command?

How do I display images from Google Drive on a website?

i supposed you uploaded your photo in your drive all what you need to do is while you are opening your google drive just open your dev tools in chrome and head to your img tag and copy the link beside the src attribute and use it

Typescript import/as vs import/require?

import * as express from "express";

This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.

In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.

Spring Could not Resolve placeholder

If you are using Spring 3.1 and above, you can use something like...

@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
}
}

You can also go by the xml configuration like...

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
  http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  http://www.springframework.org/schema/context 
  http://www.springframework.org/schema/context/spring-context-3.2.xsd">

  <context:property-placeholder location="classpath:foo.properties" />

  </beans>

In earlier versions.

Usage of the backtick character (`) in JavaScript

Apart from string interpolation, you can also call a function using back-tick.


var sayHello = function () {
    console.log('Hello', arguments);
}

// To call this function using ``

sayHello`some args`; // Check console for the output

// Or
sayHello`
    some args
`;

Check styled component. They use it heavily.

How do I uninstall a Windows service if the files do not exist anymore?

You have at least three options. I have presented them in order of usage preference.

Method 1 - You can use the SC tool (Sc.exe) included in the Resource Kit. (included with Windows 7/8)

Open a Command Prompt and enter

sc delete <service-name>

Tool help snippet follows:

DESCRIPTION:
        SC is a command line program used for communicating with the
        NT Service Controller and services.

delete----------Deletes a service (from the registry).

Method 2 - use delserv

Download and use delserv command line utility. This is a legacy tool developed for Windows 2000. In current Window XP boxes this was superseded by sc described in method 1.

Method 3 - manually delete registry entries (Note that this backfires in Windows 7/8)

Windows services are registered under the following registry key.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

Search for the sub-key with the service name under referred key and delete it. (and you might need to restart to remove completely the service from the Services list)

How to correctly use the extern keyword in C

If each file in your program is first compiled to an object file, then the object files are linked together, you need extern. It tells the compiler "This function exists, but the code for it is somewhere else. Don't panic."

WCF service maxReceivedMessageSize basicHttpBinding issue

When using HTTPS instead of ON the binding, put it IN the binding with the httpsTransport tag:

    <binding name="MyServiceBinding">
      <security defaultAlgorithmSuite="Basic256Rsa15" 
                authenticationMode="MutualCertificate" requireDerivedKeys="true" 
                securityHeaderLayout="Lax" includeTimestamp="true" 
                messageProtectionOrder="SignBeforeEncrypt" 
                messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
                requireSignatureConfirmation="false">
        <localClientSettings detectReplays="true" />
        <localServiceSettings detectReplays="true" />
        <secureConversationBootstrap keyEntropyMode="CombinedEntropy" />
      </security>
      <textMessageEncoding messageVersion="Soap11WSAddressing10">
        <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" 
                      maxArrayLength="2147483647" maxBytesPerRead="4096" 
                      maxNameTableCharCount="16384"/>
      </textMessageEncoding>
      <httpsTransport maxReceivedMessageSize="2147483647" 
                      maxBufferSize="2147483647" maxBufferPoolSize="2147483647" 
                      requireClientCertificate="false" />
    </binding>

Changing .gitconfig location on Windows

If you set HOME to c:\my_configuration_files\, then git will locate .gitconfig there. Editing environment variables is described here. You need to set the HOME variable, then re-open any cmd.exe window. Use the "set" command to verify that HOME indeed points to the right value.

Changing HOME will, of course, also affect other applications. However, from reading git's source code, that appears to be the only way to change the location of these files without the need to adjust the command line. You should also consider Stefan's response: you can set the GIT_CONFIG variable. However, to give it the effect you desire, you need to pass the --global flag to all git invocations (plus any local .git/config files are ignored).

JavaFX Application Icon

If you got Invalid URL or resource not found put your icon.png in the "bin" folder in your workspace.

Java Set retain order?

To retain the order use List or a LinkedHashSet.

How to create a custom navigation drawer in android

The tutorial Android Custom Navigation Drawer (via archive.org) contains a basic and a custom project. The latter shows how to setup a Navigation Drawer as shown in the screenshot:

NavigationDrawerCustom

The source code of the projects (via archive.org) is available for download.


The is also the Navigation Drawer - Live-O project ...

Navigation Drawer - Live-O

The source code of the project is available on GitHub.


The MaterialDrawer library aims to provide the easiest possible implementation of a navigation drawer for your application. It provides a great amount of out of the box customizations and also includes an easy to use header which can be used as AccountSwitcher.

MaterialDrawer library demo


Please note that Android Studio meanwhile has a template project to create a Navigation Drawer Activity as shown in the screenshot.

Navigation Drawer Activity

This repository keeps track of changes being made to the template.

Random "Element is no longer attached to the DOM" StaleElementReferenceException

FirefoxDriver _driver = new FirefoxDriver();

// create webdriverwait
WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10));

// create flag/checker
bool result = false;

// wait for the element.
IWebElement elem = wait.Until(x => x.FindElement(By.Id("Element_ID")));

do
{
    try
    {
        // let the driver look for the element again.
        elem = _driver.FindElement(By.Id("Element_ID"));

        // do your actions.
        elem.SendKeys("text");

        // it will throw an exception if the element is not in the dom or not
        // found but if it didn't, our result will be changed to true.
        result = !result;
    }
    catch (Exception) { }
} while (result != true); // this will continue to look for the element until
                          // it ends throwing exception.

Real world use of JMS/message queues?

We use it to initiate asynchronous processing that we don't want to interrupt or conflict with an existing transaction.

For example, say you've got an expensive and very important piece of logic like "buy stuff", an important part of buy stuff would be 'notify stuff store'. We make the notify call asynchronous so that whatever logic/processing that is involved in the notify call doesn't block or contend with resources with the buy business logic. End result, buy completes, user is happy, we get our money and because the queue is guaranteed delivery the store gets notified as soon as it opens or as soon as there's a new item in the queue.

Unable to Cast from Parent Class to Child Class

As of C# 7.0, you can use the is keyword to do this :

With those class defined :

class Base { /* Define base class */ }
class Derived : Base { /* Define derived class */ }

You can then do somehting like :

void Funtion(Base b)
{
    if (b is Derived d)
    {
        /* Do something with d which is now a variable of type Derived */
    }
}

Which would be equivalent to :

void Funtion(Base b)
{
    Defined d;
    if (b is Derived)
    {
        d = (Defined)b;
        /* Do something with d */
    }
}

You could now call :

Function(new Derived()); // Will execute code defined in if

As well as

Function(new Base()); // Won't execute code defined in if

That way you can be sure that your downcast will be valid and won't throw an exception !

How to check if an alert exists using WebDriver?

The following (C# implementation, but similar in Java) allows you to determine if there is an alert without exceptions and without creating the WebDriverWait object.

boolean isDialogPresent(WebDriver driver) {
    IAlert alert = ExpectedConditions.AlertIsPresent().Invoke(driver);
    return (alert != null);
}

What are ODEX files in Android?

ART

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

contains AOT compiled code for methods in the APK.

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

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

it says:

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

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

EOFException - how to handle?

You may come across code that reads from an InputStream and uses the snippet while(in.available()>0) to check for the end of the stream, rather than checking for an EOFException (end of the file).

The problem with this technique, and the Javadoc does echo this, is that it only tells you the number of blocks that can be read without blocking the next caller. In other words, it can return 0 even if there are more bytes to be read. Therefore, the InputStream available() method should never be used to check for the end of the stream.

You must use while (true) and

catch(EOFException e) {
//This isn't problem
} catch (Other e) {
//This is problem
}

Selected tab's color in Bottom Navigation View

In order to set textColor, BottomNavigationView has two style properties you can set directly from the xml:

  • itemTextAppearanceActive
  • itemTextAppearanceInactive

In your layout.xml file:

<com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/bnvMainNavigation"
            style="@style/NavigationView"/>
  

In your styles.xml file:

    <style name="NavigationView" parent="Widget.MaterialComponents.BottomNavigationView">
      <item name="itemTextAppearanceActive">@style/ActiveText</item>
      <item name="itemTextAppearanceInactive">@style/InactiveText</item>
    </style>
    <style name="ActiveText">
      <item name="android:textColor">@color/colorPrimary</item>
    </style>
    <style name="InactiveText">
      <item name="android:textColor">@color/colorBaseBlack</item>
    </style>

SOAP-ERROR: Parsing WSDL: Couldn't load from - but works on WAMP

You cant blame code all the time sometime may be your url is wrong , double check urls

Append an int to a std::string

You cannot cast an int to a char* to get a string. Try this:

std::ostringstream sstream;
sstream << "select logged from login where id = " << ClientID;
std::string query = sstream.str();

stringstream reference

How to get a Color from hexadecimal Color String

For shortened Hex code

int red = colorString.charAt(1) == '0' ? 0 : 255;
int blue = colorString.charAt(2) == '0' ? 0 : 255;
int green = colorString.charAt(3) == '0' ? 0 : 255;
Color.rgb(red, green,blue);

How to define constants in Visual C# like #define in C?

In C#, per MSDN library, we have the "const" keyword that does the work of the "#define" keyword in other languages.

"...when the compiler encounters a constant identifier in C# source code (for example, months), it substitutes the literal value directly into the intermediate language (IL) code that it produces." ( https://msdn.microsoft.com/en-us/library/ms173119.aspx )

Initialize constants at time of declaration since there is no changing them.

public const int cMonths = 12;

How can I multiply and divide using only bit shifting and adding?

To multiply in terms of adding and shifting you want to decompose one of the numbers by powers of two, like so:

21 * 5 = 10101_2 * 101_2             (Initial step)
       = 10101_2 * (1 * 2^2  +  0 * 2^1  +  1 * 2^0)
       = 10101_2 * 2^2 + 10101_2 * 2^0 
       = 10101_2 << 2 + 10101_2 << 0 (Decomposed)
       = 10101_2 * 4 + 10101_2 * 1
       = 10101_2 * 5
       = 21 * 5                      (Same as initial expression)

(_2 means base 2)

As you can see, multiplication can be decomposed into adding and shifting and back again. This is also why multiplication takes longer than bit shifts or adding - it's O(n^2) rather than O(n) in the number of bits. Real computer systems (as opposed to theoretical computer systems) have a finite number of bits, so multiplication takes a constant multiple of time compared to addition and shifting. If I recall correctly, modern processors, if pipelined properly, can do multiplication just about as fast as addition, by messing with the utilization of the ALUs (arithmetic units) in the processor.

Java HTTPS client certificate authentication

I've connected to bank with two-way SSL (client and server certificate) with Spring Boot. So describe here all my steps, hope it helps someone (simplest working solution, I've found):

  1. Generate sertificate request:

    • Generate private key:

      openssl genrsa -des3 -passout pass:MY_PASSWORD -out user.key 2048
      
    • Generate certificate request:

      openssl req -new -key user.key -out user.csr -passin pass:MY_PASSWORD
      

    Keep user.key (and password) and send certificate request user.csr to bank for my sertificate

  2. Receive 2 certificate: my client root certificate clientId.crt and bank root certificate: bank.crt

  3. Create Java keystore (enter key password and set keystore password):

    openssl pkcs12 -export -in clientId.crt -inkey user.key -out keystore.p12 -name clientId -CAfile ca.crt -caname root
    

    Don't pay attention on output: unable to write 'random state'. Java PKCS12 keystore.p12 created.

  4. Add into keystore bank.crt (for simplicity I've used one keystore):

    keytool -import -alias banktestca -file banktestca.crt -keystore keystore.p12 -storepass javaops
    

    Check keystore certificates by:

    keytool -list -keystore keystore.p12
    
  5. Ready for Java code:) I've used Spring Boot RestTemplate with add org.apache.httpcomponents.httpcore dependency:

    @Bean("sslRestTemplate")
    public RestTemplate sslRestTemplate() throws Exception {
      char[] storePassword = appProperties.getSslStorePassword().toCharArray();
      URL keyStore = new URL(appProperties.getSslStore());
    
      SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(keyStore, storePassword)
      // use storePassword twice (with key password do not work)!!
            .loadKeyMaterial(keyStore, storePassword, storePassword) 
            .build();
    
      // Solve "Certificate doesn't match any of the subject alternative names"
      SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    
      CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
      HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
      RestTemplate restTemplate = new RestTemplate(factory);
      // restTemplate.setMessageConverters(List.of(new Jaxb2RootElementHttpMessageConverter()));
      return restTemplate;
    }
    

Can't access Tomcat using IP address

Very strange because the firewall caused the issue.

How do I refresh the page in ASP.NET? (Let it reload itself by code)

You can use 2 ways for solve this problem: 1) After the head tag

<head> 
<meta http-equiv="refresh" content="600">
</head>

2) If your page hasn't head tag you must use Javascript to implement

<script type="text/javascript">
  function RefreshPage()
  {
    window.location.reload()
  }
</script>

My contact:

http://gola.vn

How to remove the URL from the printing page?

In Google Chrome, this can be done by setting the margins to 0, or if it prints funky, then adjusting it just enough to push the unwanted text to the non-printable areas of the page. I tried it and it works :D

enter image description here

The value violated the integrity constraints for the column

It usually happens when Allow Nulls option is unchecked.

Solution:

  1. Look at the name of the column for this error/warning.
  2. Go to SSMS and find the table
  3. Allow Null for that Column
  4. Save the table
  5. Rerun the SSIS

Try these steps. It worked for me.

See this link

Pointer-to-pointer dynamic two-dimensional array

What you describe for the second method only gives you a 1D array:

int *board = new int[10];

This just allocates an array with 10 elements. Perhaps you meant something like this:

int **board = new int*[4];
for (int i = 0; i < 4; i++) {
  board[i] = new int[10];
}

In this case, we allocate 4 int*s and then make each of those point to a dynamically allocated array of 10 ints.

So now we're comparing that with int* board[4];. The major difference is that when you use an array like this, the number of "rows" must be known at compile-time. That's because arrays must have compile-time fixed sizes. You may also have a problem if you want to perhaps return this array of int*s, as the array will be destroyed at the end of its scope.

The method where both the rows and columns are dynamically allocated does require more complicated measures to avoid memory leaks. You must deallocate the memory like so:

for (int i = 0; i < 4; i++) {
  delete[] board[i];
}
delete[] board;

I must recommend using a standard container instead. You might like to use a std::array<int, std::array<int, 10> 4> or perhaps a std::vector<std::vector<int>> which you initialise to the appropriate size.

How to center a (background) image within a div?

try background-position:center;

EDIT: since this question is getting lots of views, its worth adding some extra info:

text-align: center will not work because the background image is not part of the document and is therefore not part of the flow.

background-position:center is shorthand for background-position: center center; (background-position: horizontal vertical);

Import mysql DB with XAMPP in command LINE

In Windows, place the MySQL file (i.e. example.sql) in C:\xampp\mysql\bin.

Open the XAMPP Control Panel, and launch Shell:

cd c:\xampp\mysql\bin
mysql --default-character-set=utf8 -h localhost -u username databasename < example.sql

Note: Using --default-character-set=utf8 can help to prevent encoding issues with special characters if you intend on working with UTF-8.

Afterwards, remove the MySQL file from C:\xampp\mysql\bin.

jQuery: how to get which button was clicked upon form submission?

Here is my solution:

   $('#form').submit(function(e){   
        console.log($('#'+e.originalEvent.submitter.id));
        e.preventDefault();
    });

How to mock location on device?

The above solutions did not work for me because I was testing on an Android device with the latest Google Play Services version which utilizes the FusedLocationProviderClient. After setting the mock location permission in the app manifest and the app as the specified mock location app in the developer settings (as mentioned in the previous answers), I then added the Kotlin code below which successfully mocked the location.

locationProvider = FusedLocationProviderClient(context)
locationProvider.setMockMode(true)

val loc = Location(providerName)
val mockLocation = Location(providerName) // a string
mockLocation.latitude = latitude  // double
mockLocation.longitude = longitude
mockLocation.altitude = loc.altitude
mockLocation.time = System.currentTimeMillis()
mockLocation.accuracy = 1f
mockLocation.elapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    mockLocation.bearingAccuracyDegrees = 0.1f
    mockLocation.verticalAccuracyMeters = 0.1f
    mockLocation.speedAccuracyMetersPerSecond = 0.01f
}
//        locationManager.setTestProviderLocation(providerName, mockLocation)
locationProvider.setMockLocation(mockLocation)

How can I change the default Django date template format?

Just use this:

{{you_date_field|date:'Y-m-d'}}

This will show something like 2016-10-16. You can use the format as you want.

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Resolution

To work around this problem, use one of the following methods:

Symptoms

If you use the Response.End, Response.Redirect, or Server.Transfer method, a ThreadAbortException exception occurs. You can use a try-catch statement to catch this exception.

Cause

The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.

This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.

Status

This behavior is by design.

Properties

Article ID: 312629 - Last Review: August 30, 2012 - Revision: 4.0

Applies to

  • Microsoft ASP.NET 4.5
  • Microsoft ASP.NET 4
  • Microsoft ASP.NET 3.5
  • Microsoft ASP.NET 2.0
  • Microsoft ASP.NET 1.1
  • Microsoft ASP.NET 1.0

Keywords: kbexcepthandling kbprb KB312629

Source: PRB: ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer

How to convert a Java String to an ASCII byte array?

If you happen to need this in Android and want to make it work with anything older than FroYo, you can also use EncodingUtils.getAsciiBytes():

byte[] bytes = EncodingUtils.getAsciiBytes("ASCII Text");

Can an AWS Lambda function call another

Since this question was asked, Amazon has released Step Functions (https://aws.amazon.com/step-functions/).

One of the core principles behind AWS Lambda is that you can focus more on business logic and less on the application logic that ties it all together. Step functions allows you to orchestrate complex interactions between functions without having to write the code to do it.

How do I set a Windows scheduled task to run in the background?

Assuming the application you are attempting to run in the background is CLI based, you can try calling the scheduled jobs using Hidden Start

Also see: http://www.howtogeek.com/howto/windows/hide-flashing-command-line-and-batch-file-windows-on-startup/

How to print a list in Python "nicely"

As other answers have mentioned, pprint is a great module that will do what you want. However if you don't want to import it and just want to print debugging output during development, you can approximate its output.

Some of the other answers work fine for strings, but if you try them with a class object it will give you the error TypeError: sequence item 0: expected string, instance found.

For more complex objects, make sure the class has a __repr__ method that prints the property information you want:

class Foo(object):
    def __init__(self, bar):
        self.bar = bar

    def __repr__(self):
        return "Foo - (%r)" % self.bar

And then when you want to print the output, simply map your list to the str function like this:

l = [Foo(10), Foo(20), Foo("A string"), Foo(2.4)]
print "[%s]" % ",\n ".join(map(str,l))

outputs:

 [Foo - (10),
  Foo - (20),
  Foo - ('A string'),
  Foo - (2.4)]

You can also do things like override the __repr__ method of list to get a form of nested pretty printing:

class my_list(list):
    def __repr__(self):
        return "[%s]" % ",\n ".join(map(str, self))

a = my_list(["first", 2, my_list(["another", "list", "here"]), "last"])
print a

gives

[first,
 2,
 [another,
 list,
 here],
 last]

Unfortunately no second-level indentation but for a quick debug it can be useful.

C# How do I click a button by hitting Enter whilst textbox has focus?

Simply set form "Accept Button" Property to button that you want to hit by Enter key. Or in load event write this.acceptbutton = btnName;

How can I mock an ES6 module import using Jest?

You have to mock the module and set the spy by yourself:

import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency', () => ({
  doSomething: jest.fn()
}))

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    myModule(2);
    expect(dependency.doSomething).toBeCalledWith(4);
  });
});

Java for loop multiple variables

  1. It is cards.length(), not cards.length (length is a method of java.lang.String, not an attribute).

  2. It is System.out (capital 's'), not system.out. See java.lang.System.

  3. It is

    for(int a = 0, b = 1; a<cards.length()-1; b=a+1, a++){
    

    not

    for(int a = 0, b = 1; a<cards.length-1; b=a+1; a++;){
    
  4. Syntactically, it is if(rank == cards.substring(a,b)){, not if(rank===cards.substring(a,b){ (double equals, not triple equals; missing closing parenthesis), but to compare if two Strings are equal you need to use equals(): if(rank.equals(cards.substring(a,b))){

You should probably consider downloading Eclipse, which is an integrated development environment (not only) for Java development. Eclipse shows you the errors while you type and also provides help in fixing these. This makes it much easier to get started with Java development.

How to read from a text file using VBScript?

Use first the method OpenTextFile, and then...

either read the file at once with the method ReadAll:

Set file = fso.OpenTextFile("C:\test.txt", 1)
content = file.ReadAll

or line by line with the method ReadLine:

Set dict = CreateObject("Scripting.Dictionary")
Set file = fso.OpenTextFile ("c:\test.txt", 1)
row = 0
Do Until file.AtEndOfStream
  line = file.Readline
  dict.Add row, line
  row = row + 1
Loop

file.Close

'Loop over it
For Each line in dict.Items
  WScript.Echo line
Next

How to use environment variables in docker compose

As far as I know, this is a work-in-progress. They want to do it, but it's not released yet. See 1377 (the "new" 495 that was mentioned by @Andy).

I ended up implementing the "generate .yml as part of CI" approach as proposed by @Thomas.

What does it mean to write to stdout in C?

It depends.

When you commit to sending output to stdout, you're basically leaving it up to the user to decide where that output should go.

If you use printf(...) (or the equivalent fprintf(stdout, ...)), you're sending the output to stdout, but where that actually ends up can depend on how I invoke your program.

If I launch your program from my console like this, I'll see output on my console:

$ prog
Hello, World! # <-- output is here on my console

However, I might launch the program like this, producing no output on the console:

$ prog > hello.txt

but I would now have a file "hello.txt" with the text "Hello, World!" inside, thanks to the shell's redirection feature.

Who knows – I might even hook up some other device and the output could go there. The point is that when you decide to print to stdout (e.g. by using printf()), then you won't exactly know where it will go until you see how the process is launched or used.

Create Directory When Writing To File In Node.js

first taking the full path including directory and extracting the directory

//Just for the sake of example
cwd=process.cwd()
filendir=path.resolve(cwd,'_site/assets/text','node.txt')

// Extracting directory name
mkdir=path.dirname(filendir)

Now make the directory, add option recursive:true as stated by @David Weldon

fs.mkdirSync(mkdir,{recursive:true})

Then make the file

data='Some random text'
fs.writeFileSync(filendir,data)

Change font color and background in html on mouseover

You'd better use CSS for this:

td{
    background-color:black;
    color:white;
}
td:hover{
    background-color:white;
    color:black;
}

If you want to use these styles for only a specific set of elements, you should give your td a class (or an ID, if it's the only element which'll have that style).

Example :

HTML

<td class="whiteHover"></td>

CSS

.whiteHover{
    /* Same style as above */
}

Here's a reference on MDN for :hover pseudo class.

How do I make Visual Studio pause after executing a console application in debug mode?

In Boost.Test there is the --auto_start_dbg parameter for breaking into the debugger when a test fails (on an exception or on an assertion failure). For some reason it doesn't work for me.

See http://www.boost.org/doc/libs/1_40_0/libs/test/doc/html/utf/usage-recommendations/dot-net-specific.html

For this reason I have created my custom test_observer that will break into the debugger when there is an assertion failure or an exception. This is enabled on debug builds when we are running under a debugger.

In one of the source files of my unit test EXE file I have added this code:

#ifdef _DEBUG

#include <boost/test/framework.hpp>
#include <boost/test/test_observer.hpp>

struct BoostUnitTestCrtBreakpointInDebug: boost::unit_test::test_observer
{
    BoostUnitTestCrtBreakpointInDebug()
    {
        boost::unit_test::framework::register_observer(*this);
    }

    virtual ~BoostUnitTestCrtBreakpointInDebug()
    {
        boost::unit_test::framework::deregister_observer(*this);
    }

    virtual void assertion_result( bool passed /* passed */ )
    {
        if (!passed)
            BreakIfInDebugger();
    }

    virtual void exception_caught( boost::execution_exception const& )
    {
        BreakIfInDebugger();
    }

    void BreakIfInDebugger()
    {
        if (IsDebuggerPresent())
        {
            /**
             * Hello, I know you are here staring at the debugger :)
             *
             * If you got here then there is an exception in your unit
             * test code. Walk the call stack to find the actual cause.
             */
            _CrtDbgBreak();
        }
    }
};

BOOST_GLOBAL_FIXTURE(BoostUnitTestCrtBreakpointInDebug);

#endif

Java ArrayList Index

Read more about Array and ArrayList

List<String> aList = new ArrayList<String>();
aList.add("apple");   
aList.add("banana");   
aList.add("orange");   
String result = alist.get(1);  //this will retrieve banana

Note: Index starts from 0 i.e. Zero

Spring Boot Program cannot find main class

In case if someone is using Gradle for the build then fix will be by adding the following lines in build.gradle file

apply plugin: 'application'

mainClassName = "com.example.demo.DemoApplication"

Shell script to capture Process ID and kill it if exist

You probably wanted to write

`ps -ef | grep syncapp | awk '{print $2}'`

but I will endorse @PaulR's answer - killall -9 syncapp is a much better alternative.

Is it possible to specify a different ssh port when using rsync?

A bit offtopic but might help someone. If you need to pass password and port I suggest using sshpass package. Command line command would look like this: sshpass -p "password" rsync -avzh -e 'ssh -p PORT312' [email protected]:/dir_on_host/

jQuery/JavaScript: accessing contents of an iframe

If the <iframe> is from the same domain, the elements are easily accessible as

$("#iFrame").contents().find("#someDiv").removeClass("hidden");

Reference

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

If uploading an image, try reducing the image quality, which is the second parameter of the Bitmap. This was the solution in my case. Previously it was 90, then I tried with 60 (as it is in the code below now).

Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
finalBitmap.compress(Bitmap.CompressFormat.JPEG,60,baos);
byte[] b = baos.toByteArray();

Exception in thread "main" java.util.NoSuchElementException

Reimeus is right, you see this because of in.close in your chooseCave(). Also, this is wrong.

if (playAgain == "yes") {
      play = true;
}

You should use equals instead of "==".

if (playAgain.equals("yes")) {
      play = true;
}

Use images instead of radio buttons

  • Wrap radio and image in <label>
  • Hide radio button (Don't use display:none or visibility:hidden since such will impact accessibility)
  • Target the image next to the hidden radio using Adjacent sibling selector +

_x000D_
_x000D_
/* HIDE RADIO */
[type=radio] { 
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}

/* IMAGE STYLES */
[type=radio] + img {
  cursor: pointer;
}

/* CHECKED STYLES */
[type=radio]:checked + img {
  outline: 2px solid #f00;
}
_x000D_
<label>
  <input type="radio" name="test" value="small" checked>
  <img src="http://placehold.it/40x60/0bf/fff&text=A">
</label>

<label>
  <input type="radio" name="test" value="big">
  <img src="http://placehold.it/40x60/b0f/fff&text=B">
</label>
_x000D_
_x000D_
_x000D_

Don't forget to add a class to your labels and in CSS use that class instead.


Custom styles and animations

Here's an advanced version using the <i> element and the :after pseudo:

CSS custom radio and checkbox

_x000D_
_x000D_
body{color:#444;font:100%/1.4 sans-serif;}


/* CUSTOM RADIO & CHECKBOXES
   http://stackoverflow.com/a/17541916/383904 */
.rad,
.ckb{
  cursor: pointer;
  user-select: none;
  -webkit-user-select: none;
  -webkit-touch-callout: none;
}
.rad > input,
.ckb > input{ /* HIDE ORG RADIO & CHECKBOX */
  position: absolute;
  opacity: 0;
  width: 0;
  height: 0;
}
/* RADIO & CHECKBOX STYLES */
/* DEFAULT <i> STYLE */
.rad > i,
.ckb > i{ 
  display: inline-block;
  vertical-align: middle;
  width:  16px;
  height: 16px;
  border-radius: 50%;
  transition: 0.2s;
  box-shadow: inset 0 0 0 8px #fff;
  border: 1px solid gray;
  background: gray;
}
/* CHECKBOX OVERWRITE STYLES */
.ckb > i {
  width: 25px;
  border-radius: 3px;
}
.rad:hover > i{ /* HOVER <i> STYLE */
  box-shadow: inset 0 0 0 3px #fff;
  background: gray;
}
.rad > input:checked + i{ /* (RADIO CHECKED) <i> STYLE */
  box-shadow: inset 0 0 0 3px #fff;
  background: orange;
}
/* CHECKBOX */
.ckb > input + i:after{
  content: "";
  display: block;
  height: 12px;
  width:  12px;
  margin: 2px;
  border-radius: inherit;
  transition: inherit;
  background: gray;
}
.ckb > input:checked + i:after{ /* (RADIO CHECKED) <i> STYLE */
  margin-left: 11px;
  background:  orange;
}
_x000D_
<label class="rad">
  <input type="radio" name="rad1" value="a">
  <i></i> Radio 1
</label>
<label class="rad">
  <input type="radio" name="rad1" value="b" checked>
  <i></i> Radio 2
</label>

<br>

<label class="ckb">
  <input type="checkbox" name="ckb1" value="a" checked>
  <i></i> Checkbox 1
</label>
<label class="ckb">
  <input type="checkbox" name="ckb2" value="b">
  <i></i> Checkbox 2
</label>
_x000D_
_x000D_
_x000D_

What is the difference between `git merge` and `git merge --no-ff`?

The --no-ff flag prevents git merge from executing a "fast-forward" if it detects that your current HEAD is an ancestor of the commit you're trying to merge. A fast-forward is when, instead of constructing a merge commit, git just moves your branch pointer to point at the incoming commit. This commonly occurs when doing a git pull without any local changes.

However, occasionally you want to prevent this behavior from happening, typically because you want to maintain a specific branch topology (e.g. you're merging in a topic branch and you want to ensure it looks that way when reading history). In order to do that, you can pass the --no-ff flag and git merge will always construct a merge instead of fast-forwarding.

Similarly, if you want to execute a git pull or use git merge in order to explicitly fast-forward, and you want to bail out if it can't fast-forward, then you can use the --ff-only flag. This way you can regularly do something like git pull --ff-only without thinking, and then if it errors out you can go back and decide if you want to merge or rebase.

jQuery - Call ajax every 10 seconds

setInterval(function()
{ 
    $.ajax({
      type:"post",
      url:"myurl.html",
      datatype:"html",
      success:function(data)
      {
          //do something with response data
      }
    });
}, 10000);//time in milliseconds 

Deserialize Java 8 LocalDateTime with JacksonMapper

You used wrong letter case for year in line:

@JsonFormat(pattern = "YYYY-MM-dd HH:mm")

Should be:

@JsonFormat(pattern = "yyyy-MM-dd HH:mm")

With this change everything is working as expected.

Why does Firebug say toFixed() is not a function?

toFixed isn't a method of non-numeric variable types. In other words, Low and High can't be fixed because when you get the value of something in Javascript, it automatically is set to a string type. Using parseFloat() (or parseInt() with a radix, if it's an integer) will allow you to convert different variable types to numbers which will enable the toFixed() function to work.

var Low  = parseFloat($SliderValFrom.val()),
    High = parseFloat($SliderValTo.val());

Keeping ASP.NET Session Open / Alive

you can just write this code in you java script file thats it.

$(document).ready(function () {
        var delay = (20-1)*60*1000;
        window.setInterval(function () {
            var url = 'put the url of some Dummy page';
            $.get(url);                
        }, delay);
});

The (20-1)*60*1000 is refresh time, it will refresh the session timeout. Refresh timeout is calculated as default time out of iis = 20 minutes, means 20 × 60000 = 1200000 milliseconds - 60000 millisecond (One minutes before session expires ) is 1140000.

document.getElementById('btnid').disabled is not working in firefox and chrome

Another alternative :

document.formname.elementname.disabled=true

Work on FF and IE ! :)

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

This works for me:

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

ALLOWED_HOSTS = ['localhost', '127.0.0.1']

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

The following example Web.config file will configure IIS to deny access for HTTP requests where the length of the "Content-type" header is greater than 100 bytes.

  <configuration>
   <system.webServer>
      <security>
         <requestFiltering>
            <requestLimits>
               <headerLimits>
                  <add header="Content-type" sizeLimit="100" />
               </headerLimits>
            </requestLimits>
         </requestFiltering>
      </security>
   </system.webServer>
</configuration>

Source: http://www.iis.net/configreference/system.webserver/security/requestfiltering/requestlimits

How to detect if a browser is Chrome using jQuery?

Although it is not Jquery , I use jquery myself but for browser detection I have used the script on this page a few times. It detects all major browsers, and then some. The work is pretty much all done for you.

jQuery checkbox change and click event

Checkbox click and checking for the value in the same event loop is the problem.

Try this:

$('#checkbox1').click(function() {
    var self = this;
    setTimeout(function() {

        if (!self.checked) {
            var ans = confirm("Are you sure?");
            self.checked = ans;
            $('#textbox1').val(ans.toString());
        }
    }, 0);
});

Demo: http://jsfiddle.net/mrchief/JsUWv/6/

How do I find out what version of WordPress is running?

Because I can not comment to @Michelle 's answer, I post my trick here.

Instead of checking the version on meta tag that usually is removed by a customized theme.

Check the rss feed by append /feed to almost any link from that site, then search for some keywords (wordpress, generator), you will have a better chance.

<lastBuildDate>Fri, 29 May 2015 10:08:40 +0000</lastBuildDate>
<sy:updatePeriod>hourly</sy:updatePeriod>
<sy:updateFrequency>1</sy:updateFrequency>
<generator>http://wordpress.org/?v=4.2.2</generator>

Aligning a button to the center

You should use something like this:

<div style="text-align:center">  
    <input type="submit" />  
</div>  

Or you could use something like this. By giving the element a width and specifying auto for the left and right margins the element will center itself in its parent.

<input type="submit" style="width: 300px; margin: 0 auto;" />

Extract month and year from a zoo::yearmon object

For large vectors:

y = as.POSIXlt(date1)$year + 1900    # x$year : years since 1900
m = as.POSIXlt(date1)$mon + 1        # x$mon : 0–11