Programs & Examples On #Measureoverride

how to get param in method post spring mvc?

It also works if you change the content type

    <form method="POST"
    action="http://localhost:8080/cms/customer/create_customer"
    id="frmRegister" name="frmRegister"
    enctype="application/x-www-form-urlencoded">

In the controller also add the header value as follows:

    @RequestMapping(value = "/create_customer", method = RequestMethod.POST, headers = "Content-Type=application/x-www-form-urlencoded")

Converting between strings and ArrayBuffers

I found I had problems with this approach, basically because I was trying to write the output to a file and it was non encoded properly. Since JS seems to use UCS-2 encoding (source, source), we need to stretch this solution a step further, here's my enhanced solution that works to me.

I had no difficulties with generic text, but when it was down to Arab or Korean, the output file didn't have all the chars but instead was showing error characters

File output: ","10k unit":"",Follow:"Õ©íüY‹","Follow %{screen_name}":"%{screen_name}U“’Õ©íü",Tweet:"ĤüÈ","Tweet %{hashtag}":"%{hashtag} ’ĤüÈY‹","Tweet to %{name}":"%{name}U“xĤüÈY‹"},ko:{"%{followers_count} followers":"%{followers_count}…X \Ì","100K+":"100Ì tÁ","10k unit":"Ì è",Follow:"\°","Follow %{screen_name}":"%{screen_name} Ø \°X0",K:"œ",M:"1Ì",Tweet:"¸","Tweet %{hashtag}":"%{hashtag}

Original: ","10k unit":"?",Follow:"??????","Follow %{screen_name}":"%{screen_name}???????",Tweet:"????","Tweet %{hashtag}":"%{hashtag} ???????","Tweet to %{name}":"%{name}?????????"},ko:{"%{followers_count} followers":"%{followers_count}?? ???","100K+":"100? ??","10k unit":"? ??",Follow:"???","Follow %{screen_name}":"%{screen_name} ? ?????",K:"?",M:"??",Tweet:"??","Tweet %{hashtag}":"%{hashtag}

I took the information from dennis' solution and this post I found.

Here's my code:

function encode_utf8(s) {
  return unescape(encodeURIComponent(s));
}

function decode_utf8(s) {
  return decodeURIComponent(escape(s));
}

 function ab2str(buf) {
   var s = String.fromCharCode.apply(null, new Uint8Array(buf));
   return decode_utf8(decode_utf8(s))
 }

function str2ab(str) {
   var s = encode_utf8(str)
   var buf = new ArrayBuffer(s.length); 
   var bufView = new Uint8Array(buf);
   for (var i=0, strLen=s.length; i<strLen; i++) {
     bufView[i] = s.charCodeAt(i);
   }
   return bufView;
 }

This allows me to save the content to a file without encoding problems.

How it works: It basically takes the single 8-byte chunks composing a UTF-8 character and saves them as single characters (therefore an UTF-8 character built in this way, could be composed by 1-4 of these characters). UTF-8 encodes characters in a format that variates from 1 to 4 bytes in length. What we do here is encoding the sting in an URI component and then take this component and translate it in the corresponding 8 byte character. In this way we don't lose the information given by UTF8 characters that are more than 1 byte long.

How to delete Tkinter widgets from a window?

You simply use the destroy() method to delete the specified widgets like this:

lbl = tk.Label(....)

btn = tk.Button(....., command=lambda: lbl.destroy())

Using this you can completely destroy the specific widgets.

How can I build for release/distribution on the Xcode 4?

You can use command line tool to build the release version. Next to your project folder, i.e.

$ ls
...
Foo.xcodeproj
...

Type the following build command:

$ xcodebuild -configuration Release

What is the "assert" function?

C++11 N3337 standard draft

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf

19.3 Assertions

1 The header <cassert>, described in (Table 42), provides a macro for documenting C ++ program assertions and a mechanism for disabling the assertion checks.

2 The contents are the same as the Standard C library header <assert.h>.

C99 N1256 standard draft

http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf

7.2 Diagnostics <assert.h>

1 The header <assert.h> defines the assert macro and refers to another macro, NDEBUG which is not defined by <assert.h>. If NDEBUG is defined as a macro name at the point in the source file where <assert.h> is included, the assert macro is defined simply as

 #define assert(ignore) ((void)0)

The assert macro is redefined according to the current state of NDEBUG each time that <assert.h> is included.

2. The assert macro shall be implemented as a macro, not as an actual function. If the macro definition is suppressed in order to access an actual function, the behavior is undefined.

7.2.1 Program diagnostics

7.2.1.1 The assert macro

Synopsis

1.

#include <assert.h>
void assert(scalar expression);

Description

2 The assert macro puts diagnostic tests into programs; it expands to a void expression. When it is executed, if expression (which shall have a scalar type) is false (that is, compares equal to 0), the assert macro writes information about the particular call that failed (including the text of the argument, the name of the source file, the source line number, and the name of the enclosing function — the latter are respectively the values of the preprocessing macros __FILE__ and __LINE__ and of the identifier __func__) on the standard error stream in an implementation-defined format. 165) It then calls the abort function.

Returns

3 The assert macro returns no value.

How to perform Unwind segue programmatically?

Quoting text from Apple's Technical Note on Unwind Segue: To add an unwind segue that will only be triggered programmatically, control+drag from the scene's view controller icon to its exit icon, then select an unwind action for the new segue from the popup menu.

Link to Technical Note

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

Blocks are the way to go. You can have complex parameters, type safety, and it's a lot simpler and safer than most of the old answers here. For example, you could just write:

[MONBlock performBlock:^{[obj setFrame:SOMETHING];} afterDelay:2];

Blocks allow you to capture arbitrary parameter lists, reference objects and variables.

Backing Implementation (basic):

@interface MONBlock : NSObject

+ (void)performBlock:(void(^)())pBlock afterDelay:(NSTimeInterval)pDelay;

@end

@implementation MONBlock

+ (void)imp_performBlock:(void(^)())pBlock
{
 pBlock();
}

+ (void)performBlock:(void(^)())pBlock afterDelay:(NSTimeInterval)pDelay
{
  [self performSelector:@selector(imp_performBlock:)
             withObject:[pBlock copy]
             afterDelay:pDelay];
}

@end

Example:

int main(int argc, const char * argv[])
{
 @autoreleasepool {
  __block bool didPrint = false;
  int pi = 3; // close enough =p

  [MONBlock performBlock:^{NSLog(@"Hello, World! pi is %i", pi); didPrint = true;} afterDelay:2];

  while (!didPrint) {
   [NSRunLoop.currentRunLoop runUntilDate:[NSDate dateWithTimeInterval:0.1 sinceDate:NSDate.date]];
  }

  NSLog(@"(Bye, World!)");
 }
 return 0;
}

Also see Michael's answer (+1) for another example.

what's data-reactid attribute in html?

That's the HTML data attribute. See this for more detail: http://html5doctor.com/html5-custom-data-attributes/

Basically it's just a container of your custom data while still making the HTML valid. It's data- plus some unique identifier.

How to determine if a type implements an interface with C# reflection

If you have a type or an instance you can easily check if they support a specific interface.

To test if an object implements a certain interface:

if(myObject is IMyInterface) {
  // object myObject implements IMyInterface
}

To test if a type implements a certain interface:

if(typeof(IMyInterface).IsAssignableFrom(typeof(MyType))) {
  // type MyType implements IMyInterface
}

If you got a generic object and want to do a cast as well as a check if the interface you cast to is implemented the code is:

 var myCastedObject = myObject as IMyInterface;

    if(myCastedObject != null) {
      // object myObject implements IMyInterface
    }

Using Html.ActionLink to call action on different controller

What you want is this overload :

//linkText, actionName, controllerName, routeValues, htmlAttributes
<%=Html.ActionLink("Details", "Details", 
    "Product", new {id = item.ID}, null) %>

Node.js - Maximum call stack size exceeded

I found a dirty solution:

/bin/bash -c "ulimit -s 65500; exec /usr/local/bin/node --stack-size=65500 /path/to/app.js"

It just increase call stack limit. I think that this is not suitable for production code, but I needed it for script that run only once.

Undefined variable: $_SESSION

Turned out there was some extra code in the AppModel that was messing things up:

in beforeFind and afterFind:

App::Import("Session");
$session = new CakeSession();
$sim_id = $session->read("Simulation.id");

I don't know why, but that was what the problem was. Removing those lines fixed the issue I was having.

How to hide elements without having them take space on the page?

display:none to hide and set display:block to show.

How to add a "confirm delete" option in ASP.Net Gridview?

Try this:

I used for Update and Delete buttons. It doesn't touch Edit button. You can use auto generated buttons.

  protected void gvOperators_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if(e.Row.RowType != DataControlRowType.DataRow) return;
        var updateButton = (LinkButton)e.Row.Cells[0].Controls[0];
        if (updateButton.Text == "Update")
        {
            updateButton.OnClientClick = "return confirm('Do you really want to update?');";
        }
        var deleteButton = (LinkButton)e.Row.Cells[0].Controls[2];
        if (deleteButton.Text == "Delete")
        {
            deleteButton.OnClientClick = "return confirm('Do you really want to delete?');";
        }

    }

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

WPF button click in C# code

I don't think WPF supports what you are trying to achieve i.e. assigning method to a button using method's name or btn1.Click = "btn1_Click". You will have to use approach suggested in above answers i.e. register button click event with appropriate method btn1.Click += btn1_Click;

Select count(*) from multiple tables

Declare @all int
SET @all = (select COUNT(*) from tab1) + (select count(*) from tab2)
Print @all

or

SELECT (select COUNT(*) from tab1) + (select count(*) from tab2)

Accessing Imap in C#

In the hope that it will be useful to some, you may want to check out my go at it:

S22.Imap

While there are a couple of good and well-documented IMAP libraries for .NET available, none of them are free for personal, let alone commercial use...and I was just not all that satisfied with the mostly abandoned free alternatives I found.

S22.Imap supports IMAP IDLE notifications as well as SSL and partial message fetching. I have put some effort into producing documentation and keeping it up to date, because with the projects I found, documentation was often sparse or non-existent.

Feel free to give it a try and let me know if you run into any issues!

What is the difference between server side cookie and client side cookie?

You probably mean the difference between Http Only cookies and their counter part?

Http Only cookies cannot be accessed (read from or written to) in client side JavaScript, only server side. If the Http Only flag is not set, or the cookie is created in (client side) JavaScript, the cookie can be read from and written to in (client side) JavaScript as well as server side.

Quicksort with Python

def quicksort(items):
    if not len(items) > 1:
        return items
    items, pivot = partition(items)
    return quicksort(items[:pivot]) + [items[pivot]] + quicksort(items[pivot + 1:])


def partition(items):
    i = 1
    pivot = 0
    for j in range(1, len(items)):
        if items[j] <= items[pivot]:
            items[i], items[j] = items[j], items[i]
            i += 1
    items[i - 1], items[pivot] = items[pivot], items[i - 1]
    return items, i - 1

How to run Gulp tasks sequentially one after the other

By default, gulp runs tasks simultaneously, unless they have explicit dependencies. This isn't very useful for tasks like clean, where you don't want to depend, but you need them to run before everything else.

I wrote the run-sequence plugin specifically to fix this issue with gulp. After you install it, use it like this:

var runSequence = require('run-sequence');

gulp.task('develop', function(done) {
    runSequence('clean', 'coffee', function() {
        console.log('Run something else');
        done();
    });
});

You can read the full instructions on the package README — it also supports running some sets of tasks simultaneously.

Please note, this will be (effectively) fixed in the next major release of gulp, as they are completely eliminating the automatic dependency ordering, and providing tools similar to run-sequence to allow you to manually specify run order how you want.

However, that is a major breaking change, so there's no reason to wait when you can use run-sequence today.

How to set transparent background for Image Button in code?

simply use this in your imagebutton layout

android:background="@null"

using

 android:background="@android:color/transparent 

or

 btn.setBackgroundColor(Color.TRANSPARENT);

doesn't give perfect transparency

Error: Specified cast is not valid. (SqlManagerUI)

I had a similar error "Specified cast is not valid" restoring from SQL Server 2012 to SQL Server 2008 R2

First I got the MDF and LDF Names:

RESTORE FILELISTONLY 
FROM  DISK = N'C:\Users\dell laptop\DotNetSandBox\DBBackups\Davincis3.bak' 
GO

Second I restored with a MOVE using those names returned:

RESTORE DATABASE Davincis3 
FROM DISK = 'C:\Users\dell laptop\DotNetSandBox\DBBackups\Davincis3.bak'
WITH 
   MOVE 'JQueryExampleDb' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Davincis3.mdf', 
   MOVE 'JQueryExampleDB_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\Davincis3.ldf', 
REPLACE
GO  

I have no clue as to the name "JQueryExampleDb", but this worked for me.

Nevertheless, backups (and databases) are not backwards compatible with older versions.

jQuery get the name of a select option

In your codethis refers to the select element not to the selected option

to refer the selected option you can do this -

$(this).find('option:selected').attr("name");

Where does Oracle SQL Developer store connections?

SqlDeveloper stores all the connections in a file named

connections.xml

In windows XP you can find the file in location

C:\Documents and Settings\<username>\Application Data\SQL Developer\systemX.X.X.X.X\o.jdeveloper.db.connection.X.X.X.X.X.X.X\connections.xml

In Windows 7 you will find it in location

C:\Users\<username>\AppData\Roaming\SQL Developer\systemX.X.X.X.X\o.jdeveloper.db.connection.X.X.X.X.X.X.X\connections.xml

How to get named excel sheets while exporting from SSRS

You could use -sed- and -grep- to replace or write to the xml header of each file specifying your desired sheet name, e.g., sheetname1, between any occurrence of the tags:

<Sheetnames>?sheetname1?</Sheetnames>

How can I reverse the order of lines in a file?

You can do it with vim stdin and stdout. You can also use ex to be POSIX compliant. vim is just the visual mode for ex. In fact, you can use ex with vim -e or vim -E (improved ex mode). vim is useful because unlike tools like sed it buffers the file for editing, while sed is used for streams. You might be able to use awk, but you would have to manually buffer everything in a variable.

The idea is to do the following:

  1. Read from stdin
  2. For each line move it to line 1 (to reverse). Command is g/^/m0. This means globally, for each line g; match the start of the line, which matches anything ^; move it after address 0, which is line 1 m0.
  3. Print everything. Command is %p. This means for the range of all lines %; print the line p.
  4. Forcefully quit without saving the file. Command is q!. This means quit q; forcefully !.
# Generate a newline delimited sequence of 1 to 10
$ seq 10
1
2
3
4
5
6
7
8
9
10

# Use - to read from stdin.
# vim has a delay and annoying 'Vim: Reading from stdin...' output
# if you use - to read from stdin. Use --not-a-term to hide output.
# --not-a-term requires vim 8.0.1308 (Nov 2017)
# Use -E for improved ex mode. -e would work here too since I'm not
# using any improved ex mode features.
# each of the commands I explained above are specified with a + sign
# and are run sequentially.
$ seq 10 | vim - --not-a-term -Es +'g/^/m0' +'%p' +'q!'
10
9
8
7
6
5
4
3
2
1
# non improved ex mode works here too, -e.
$ seq 10 | vim - --not-a-term -es +'g/^/m0' +'%p' +'q!'

# If you don't have --not-a-term, use /dev/stdin
seq 10 | vim -E +'g/^/m0' +'%p' +'q!' /dev/stdin

# POSIX compliant (maybe)
# POSIX compliant ex doesn't allow using + sign to specify commands.
# It also might not allow running multiple commands sequentially.
# The docs say "Implementations may support more than a single -c"
# If yours does support multiple -c
$ seq 10 | ex -c "execute -c 'g/^/m0' -c '%p' -c 'q!' /dev/stdin

# If not, you can chain them with the bar, |. This is same as shell
# piping. It's more like shell semi-colon, ;.
# The g command consumes the |, so you can use execute to prevent that.
# Not sure if execute and | is POSIX compliant.
seq 10 | ex -c "execute 'g/^/m0' | %p | q!" /dev/stdin

How to make this reusable

I use a script I call ved (vim editor like sed) to use vim to edit stdin. Add this to a file called ved in your path:

#!/usr/bin/env sh

vim - --not-a-term -Es "$@" +'%p | q!'

I am using one + command instead of +'%p' +'q!', because vim limits you to 10 commands. So merging them allows the "$@" to have 9 + commands instead of 8.

Then you can do:

seq 10 | ved +'g/^/m0'

If you don't have vim 8, put this in ved instead:

#!/usr/bin/env sh

vim -E "$@" +'%p | q!' /dev/stdin

IntelliJ IDEA "cannot resolve symbol" and "cannot resolve method"

For me, I had to remove the intellij internal sdk and started to use my local sdk. When I started to use the internal, the error was gone.

my sdks

Node.js/Express routing with get params

For Query parameters like domain.com/test?format=json&type=mini format, then you can easily receive it via - req.query.

app.get('/test', function(req, res){
  var format = req.query.format,
      type = req.query.type;
});

Disable same origin policy in Chrome

this is an ever moving target.... today I needed to add another flag to get it to work: --disable-site-isolation-trials

OS X: open /Applications/Google\ Chrome.app --args --user-data-dir="/var/tmp/Chrome_dev_2" --disable-web-security --disable-site-isolation-trials

Regex to match 2 digits, optional decimal, two digits

A previous answer is mostly correct, but it will also match the empty string. The following would solve this.

^([0-9]?[0-9](\.[0-9][0-9]?)?)|([0-9]?[0-9]?(\.[0-9][0-9]?))$

powershell mouse move does not prevent idle mode

I've added a notification that you can easily enable / disable just setting its variable to $true or $false. Also the mouse cursor moves 1 px right and then 1 px left so it basically stays in the same place even after several iterations.

# Lines needed for the notification
[System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
Add-Type -AssemblyName System.Windows.Forms 
$isNotificationOn = $true

$secondsBetweenMouseMoves = 6
$Pos = [System.Windows.Forms.Cursor]::Position
$PosDelta = 1
$logFilename = "previousMouseMoverAction.txt"
$errorLogFilename = "mouseMoverLog.txt"

if (!(Test-Path "$PSScriptRoot\$logFilename")) {
   New-Item -path $PSScriptRoot -name $logFilename -type "file" -value "right"
   Write-Host "Warning: previousMouseMoverAction.txt missing, created a new one."
}

$previousPositionChangeAction = Get-Content -Path $PSScriptRoot\$logFilename

if ($previousPositionChangeAction -eq "left") {
    $PosDelta = 1
    Set-Content -Path $PSScriptRoot\$logFilename -Value 'right'
} else {
    $PosDelta = -1
    Set-Content -Path $PSScriptRoot\$logFilename -Value 'left'
}

for ($i = 0; $i -lt $secondsBetweenMouseMoves; $i++) {
    [System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) + $PosDelta) , $Pos.Y)
    if ($isNotificationOn) {
        # Sending a notification to the user
        $global:balloon = New-Object System.Windows.Forms.NotifyIcon
        $path = (Get-Process -id $pid).Path
        $balloon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($path) 
        $balloon.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::Warning 
        $balloon.BalloonTipText = 'I have just moved your cheese...'
        $balloon.BalloonTipTitle = "Attention, $Env:USERNAME" 
        $balloon.Visible = $true 
        $balloon.ShowBalloonTip(3000)
    }
}

Enums in Javascript with ES6

Is there a problem with this formulation?

I don't see any.

Is there a better way?

I'd collapse the two statements into one:

const Colors = Object.freeze({
    RED:   Symbol("red"),
    BLUE:  Symbol("blue"),
    GREEN: Symbol("green")
});

If you don't like the boilerplate, like the repeated Symbol calls, you can of course also write a helper function makeEnum that creates the same thing from a list of names.

curl: (6) Could not resolve host: application

I was getting this error too. I resolved it by installing: https://git-scm.com/

and running the command from the Git Bash window.

How can I plot data with confidence intervals?

Here is a plotrix solution:

set.seed(0815)
x <- 1:10
F <- runif(10,1,2) 
L <- runif(10,0,1)
U <- runif(10,2,3)

require(plotrix)
plotCI(x, F, ui=U, li=L)

enter image description here

And here is a ggplot solution:

set.seed(0815)
df <- data.frame(x =1:10,
                 F =runif(10,1,2),
                 L =runif(10,0,1),
                 U =runif(10,2,3))

require(ggplot2)
ggplot(df, aes(x = x, y = F)) +
  geom_point(size = 4) +
  geom_errorbar(aes(ymax = U, ymin = L))

enter image description here

UPDATE: Here is a base solution to your edits:

set.seed(1234)
x <- rnorm(20)
df <- data.frame(x = x,
                 y = x + rnorm(20))

plot(y ~ x, data = df)

# model
mod <- lm(y ~ x, data = df)

# predicts + interval
newx <- seq(min(df$x), max(df$x), length.out=100)
preds <- predict(mod, newdata = data.frame(x=newx), 
                 interval = 'confidence')

# plot
plot(y ~ x, data = df, type = 'n')
# add fill
polygon(c(rev(newx), newx), c(rev(preds[ ,3]), preds[ ,2]), col = 'grey80', border = NA)
# model
abline(mod)
# intervals
lines(newx, preds[ ,3], lty = 'dashed', col = 'red')
lines(newx, preds[ ,2], lty = 'dashed', col = 'red')

enter image description here

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

Did not have this problem when I built and ran on my own device. Only had this problem with simulators. I just simply restarted my computer and ran it. It worked.

Why use armeabi-v7a code over armeabi code?

Instead of having a fat APK file, I would like to use just the armeabi files and remove the armeabi-v7a folder.

The opposite is a much better strategy. If you have minSdkVersion to 14 and upload your apk to the play store, you'll notice you'll support the same number of devices whether you support armeabi or not. Therefore, there are no devices with Android 4 or higher which would benefit from armeabi at all.

This is probably why the Android NDK doesn't even support armeabi anymore as per revision r17b. [source]

Android ADB device offline, can't issue commands

I updated many times, until I couldn't update any more, but I never got a prompt on my screen; I just kept getting the device offline.

My problem was that I was running the ADB command from a different directory to what was actually being updated.

The correct updated directory for the ADB exe is:

C:\Program Files (x86)\Android\android-sdk\platform-tools\

Spring Boot application can't resolve the org.springframework.boot package

Maybe there is a problem with the JAR files in the local Maven repository. Try deleting the .m2/repository folder and hit Maven -> Update Project... another time to trigger Maven to download the dependencies again. I tried it and it worked for me.

How can I use pickle to save a dict?

I've found pickling confusing (possibly because I'm thick). I found that this works, though:

myDictionaryString=str(myDictionary)

Which you can then write to a text file. I gave up trying to use pickle as I was getting errors telling me to write integers to a .dat file. I apologise for not using pickle.

Difference between null and empty ("") Java String

You may also understand the difference between null and an empty string this way:

Difference between null and 0/empty string

Original image by R. Sato (@raysato)

AngularJS $resource RESTful example

$resource was meant to retrieve data from an endpoint, manipulate it and send it back. You've got some of that in there, but you're not really leveraging it for what it was made to do.

It's fine to have custom methods on your resource, but you don't want to miss out on the cool features it comes with OOTB.

EDIT: I don't think I explained this well enough originally, but $resource does some funky stuff with returns. Todo.get() and Todo.query() both return the resource object, and pass it into the callback for when the get completes. It does some fancy stuff with promises behind the scenes that mean you can call $save() before the get() callback actually fires, and it will wait. It's probably best just to deal with your resource inside of a promise then() or the callback method.

Standard use

var Todo = $resource('/api/1/todo/:id');

//create a todo
var todo1 = new Todo();
todo1.foo = 'bar';
todo1.something = 123;
todo1.$save();

//get and update a todo
var todo2 = Todo.get({id: 123});
todo2.foo += '!';
todo2.$save();

//which is basically the same as...
Todo.get({id: 123}, function(todo) {
   todo.foo += '!';
   todo.$save();
});

//get a list of todos
Todo.query(function(todos) {
  //do something with todos
  angular.forEach(todos, function(todo) {
     todo.foo += ' something';
     todo.$save();
  });
});

//delete a todo
Todo.$delete({id: 123});

Likewise, in the case of what you posted in the OP, you could get a resource object and then call any of your custom functions on it (theoretically):

var something = src.GetTodo({id: 123});
something.foo = 'hi there';
something.UpdateTodo();

I'd experiment with the OOTB implementation before I went and invented my own however. And if you find you're not using any of the default features of $resource, you should probably just be using $http on it's own.

Update: Angular 1.2 and Promises

As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.

To leverage promises with $resource, you need to use the $promise property on the returned value.

Example using promises

var Todo = $resource('/api/1/todo/:id');

Todo.get({id: 123}).$promise.then(function(todo) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Todo.query().$promise.then(function(todos) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Just keep in mind that the $promise property is a property on the same values it was returning above. So you can get weird:

These are equivalent

var todo = Todo.get({id: 123}, function() {
   $scope.todo = todo;
});

Todo.get({id: 123}, function(todo) {
   $scope.todo = todo;
});

Todo.get({id: 123}).$promise.then(function(todo) {
   $scope.todo = todo;
});

var todo = Todo.get({id: 123});
todo.$promise.then(function() {
   $scope.todo = todo;
});

Why doesn't C++ have a garbage collector?

One of the biggest reasons that C++ doesn't have built in garbage collection is that getting garbage collection to play nice with destructors is really, really hard. As far as I know, nobody really knows how to solve it completely yet. There are alot of issues to deal with:

  • deterministic lifetimes of objects (reference counting gives you this, but GC doesn't. Although it may not be that big of a deal).
  • what happens if a destructor throws when the object is being garbage collected? Most languages ignore this exception, since theres really no catch block to be able to transport it to, but this is probably not an acceptable solution for C++.
  • How to enable/disable it? Naturally it'd probably be a compile time decision but code that is written for GC vs code that is written for NOT GC is going to be very different and probably incompatible. How do you reconcile this?

These are just a few of the problems faced.

NotificationCompat.Builder deprecated in Android O

enter image description here

Here is working code for all android versions as of API LEVEL 26+ with backward compatibility.

 NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext(), "M_CH_ID");

        notificationBuilder.setAutoCancel(true)
                .setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher)
                .setTicker("Hearty365")
                .setPriority(Notification.PRIORITY_MAX) // this is deprecated in API 26 but you can still use for below 26. check below update for 26 API
                .setContentTitle("Default notification")
                .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
                .setContentInfo("Info");

NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1, notificationBuilder.build());

UPDATE for API 26 to set Max priority

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    String NOTIFICATION_CHANNEL_ID = "my_channel_id_01";

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "My Notifications", NotificationManager.IMPORTANCE_MAX);

        // Configure the notification channel.
        notificationChannel.setDescription("Channel description");
        notificationChannel.enableLights(true);
        notificationChannel.setLightColor(Color.RED);
        notificationChannel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
        notificationChannel.enableVibration(true);
        notificationManager.createNotificationChannel(notificationChannel);
    }


    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);

    notificationBuilder.setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_launcher)
            .setTicker("Hearty365")
       //     .setPriority(Notification.PRIORITY_MAX)
            .setContentTitle("Default notification")
            .setContentText("Lorem ipsum dolor sit amet, consectetur adipiscing elit.")
            .setContentInfo("Info");

    notificationManager.notify(/*notification id*/1, notificationBuilder.build());

USB Debugging option greyed out

Finally figured out the solution to the problem, with the help of this post.

When you connect your phone to your PC, using the USB cable, select the mode as PC Software.

Now you should be able to enable USB Debugging.

How do you implement a class in C?

you can take a look at GOBject. it's an OS library that give you a verbose way to do an object.

http://library.gnome.org/devel/gobject/stable/

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)

You can try to set the proxy settings:

File -> Settings -> Appearance -> System Settings -> Http proxy -> Auto Detect

And then provide the proxy URL.

Get human readable version of file size?

A library that has all the functionality that it seems you're looking for is humanize. humanize.naturalsize() seems to do everything you're looking for.

How can I check if a URL exists via PHP?

pretty fast:

function http_response($url){
    $resURL = curl_init(); 
    curl_setopt($resURL, CURLOPT_URL, $url); 
    curl_setopt($resURL, CURLOPT_BINARYTRANSFER, 1); 
    curl_setopt($resURL, CURLOPT_HEADERFUNCTION, 'curlHeaderCallback'); 
    curl_setopt($resURL, CURLOPT_FAILONERROR, 1); 
    curl_exec ($resURL); 
    $intReturnCode = curl_getinfo($resURL, CURLINFO_HTTP_CODE); 
    curl_close ($resURL); 
    if ($intReturnCode != 200 && $intReturnCode != 302 && $intReturnCode != 304) { return 0; } else return 1;
}

echo 'google:';
echo http_response('http://www.google.com');
echo '/ ogogle:';
echo http_response('http://www.ogogle.com');

Check object empty

I have a way, you guys tell me how good it is.

Create a new object of the class and compare it with your object (which you want to check for emptiness).

To be correctly able to do it :

Override the hashCode() and equals() methods of your model class and also of the classes, objects of whose are members of your class, for example :

Person class (primary model class) :

public class Person {

    private int age;
    private String firstName;
    private String lastName;
    private Address address;

    //getters and setters

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((address == null) ? 0 : address.hashCode());
        result = prime * result + age;
        result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
        result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (address == null) {
            if (other.address != null)
                return false;
        } else if (!address.equals(other.address))
            return false;
        if (age != other.age)
            return false;
        if (firstName == null) {
            if (other.firstName != null)
                return false;
        } else if (!firstName.equals(other.firstName))
            return false;
        if (lastName == null) {
            if (other.lastName != null)
                return false;
        } else if (!lastName.equals(other.lastName))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Person [age=" + age + ", firstName=" + firstName + ", lastName=" + lastName + ", address=" + address
                + "]";
    }

}

Address class (used inside Person class) :

public class Address {

    private String line1;
    private String line2;

    //getters and setters

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((line1 == null) ? 0 : line1.hashCode());
        result = prime * result + ((line2 == null) ? 0 : line2.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Address other = (Address) obj;
        if (line1 == null) {
            if (other.line1 != null)
                return false;
        } else if (!line1.equals(other.line1))
            return false;
        if (line2 == null) {
            if (other.line2 != null)
                return false;
        } else if (!line2.equals(other.line2))
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Address [line1=" + line1 + ", line2=" + line2 + "]";
    }

}

Now in the main class :

    Person person1 = new Person();
    person1.setAge(20);

    Person person2 = new Person();

    Person person3 = new Person();

if(person1.equals(person2)) --> this will be false

if(person2.equals(person3)) --> this will be true

I hope this is the best way instead of putting if conditions on each and every member variables.

Let me know !

Scatter plots in Pandas/Pyplot: How to plot by category

It's rather hacky, but you could use one1 as a Float64Index to do everything in one go:

df.set_index('one').sort_index().groupby('key1')['two'].plot(style='--o', legend=True)

enter image description here

Note that as of 0.20.3, sorting the index is necessary, and the legend is a bit wonky.

Selector on background color of TextView

Benoit's solution works, but you really don't need to incur the overhead to draw a shape. Since colors can be drawables, just define a color in a /res/values/colors.xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="semitransparent_white">#77ffffff</color>
</resources>

And then use as such in your selector:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_pressed="true"
        android:drawable="@color/semitransparent_white" />
</selector>

Where does Hive store files in HDFS?

It's also very possible that typing show create table <table_name> in the hive cli will give you the exact location of your hive table.

Should I put input elements inside a label element?

A notable 'gotcha' dictates that you should never include more than one input element inside of a <label> element with an explicit "for" attribute, e.g:

<label for="child-input-1">
  <input type="radio" id="child-input-1"/>
  <span> Associate the following text with the selected radio button: </span>
  <input type="text" id="child-input-2"/>
</label>

While this may be tempting for form features in which a custom text value is secondary to a radio button or checkbox, the click-focus functionality of the label element will immediately throw focus to the element whose id is explicitly defined in its 'for' attribute, making it nearly impossible for the user to click into the contained text field to enter a value.

Personally, I try to avoid label elements with input children. It seems semantically improper for a label element to encompass more than the label itself. If you're nesting inputs in labels in order to achieve a certain aesthetic, you should be using CSS instead.

javascript object max size limit

you have to put this in web.config :

<system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="50000000" />
      </webServices>
    </scripting>
  </system.web.extensions>

How to timeout a thread

Consider using an instance of ExecutorService. Both invokeAll() and invokeAny() methods are available with a timeout parameter.

The current thread will block until the method completes (not sure if this is desirable) either because the task(s) completed normally or the timeout was reached. You can inspect the returned Future(s) to determine what happened.

Multiple INSERT statements vs. single INSERT with multiple VALUES

The issue probably has to do with the time it takes to compile the query.

If you want to speed up the inserts, what you really need to do is wrap them in a transaction:

BEGIN TRAN;
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('6f3f7257-a3d8-4a78-b2e1-c9b767cfe1c1', 'First 0', 'Last 0', 0);
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('32023304-2e55-4768-8e52-1ba589b82c8b', 'First 1', 'Last 1', 1);
...
INSERT INTO T_TESTS (TestId, FirstName, LastName, Age) 
   VALUES ('f34d95a7-90b1-4558-be10-6ceacd53e4c4', 'First 999', 'Last 999', 999);
COMMIT TRAN;

From C#, you might also consider using a table valued parameter. Issuing multiple commands in a single batch, by separating them with semicolons, is another approach that will also help.

How to convert all elements in an array to integer in JavaScript?

The point against parseInt-approach:

There's no need to use lambdas and/or give radix parameter to parseInt, just use parseFloat or Number instead.


Reasons:

  1. It's working:

    var src = "1,2,5,4,3";
    var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3]
    
    var obj = {1: ..., 3: ..., 4: ..., 7: ...};
    var keys= Object.keys(obj); // ["1", "3", "4", "7"]
    var ids = keys.map(parseFloat); // [1, 3, 4, 7]
    
    var arr = ["1", 5, "7", 11];
    var ints= arr.map(parseFloat); // [1, 5, 7, 11]
    ints[1] === "5" // false
    ints[1] === 5   // true
    ints[2] === "7" // false
    ints[2] === 7   // true
    
  2. It's shorter.

  3. It's a tiny bit quickier and takes advantage of cache, when parseInt-approach - doesn't:

      // execution time measure function
      // keep it simple, yeah?
    > var f = (function (arr, c, n, m) {
          var i,t,m,s=n();
          for(i=0;i++<c;)t=arr.map(m);
          return n()-s
      }).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now);
    
    > f(Number) // first launch, just warming-up cache
    > 3971 // nice =)
    
    > f(Number)
    > 3964 // still the same
    
    > f(function(e){return+e})
    > 5132 // yup, just little bit slower
    
    > f(function(e){return+e})
    > 5112 // second run... and ok.
    
    > f(parseFloat)
    > 3727 // little bit quicker than .map(Number)
    
    > f(parseFloat)
    > 3737 // all ok
    
    > f(function(e){return parseInt(e,10)})
    > 21852 // awww, how adorable...
    
    > f(function(e){return parseInt(e)})
    > 22928 // maybe, without '10'?.. nope.
    
    > f(function(e){return parseInt(e)})
    > 22769 // second run... and nothing changes.
    
    > f(Number)
    > 3873 // and again
    > f(parseFloat)
    > 3583 // and again
    > f(function(e){return+e})
    > 4967 // and again
    
    > f(function(e){return parseInt(e,10)})
    > 21649 // dammit 'parseInt'! >_<
    

Notice: In Firefox parseInt works about 4 times faster, but still slower than others. In total: +e < Number < parseFloat < parseInt

How to do 3 table JOIN in UPDATE query?

Alternative way of achieving same result is not to use JOIN keyword at all.

UPDATE TABLE_A, TABLE_B
SET TABLE_A.column_c = TABLE_B.column_c + 1
WHERE TABLE_A.join_col = TABLE_B.join_col

SQL DELETE with INNER JOIN

If the database is InnoDB then it might be a better idea to use foreign keys and cascade on delete, this would do what you want and also result in no redundant data being stored.

For this example however I don't think you need the first s:

DELETE s 
FROM spawnlist AS s 
INNER JOIN npc AS n ON s.npc_templateid = n.idTemplate 
WHERE n.type = "monster";

It might be a better idea to select the rows before deleting so you are sure your deleting what you wish to:

SELECT * FROM spawnlist
INNER JOIN npc ON spawnlist.npc_templateid = npc.idTemplate
WHERE npc.type = "monster";

You can also check the MySQL delete syntax here: http://dev.mysql.com/doc/refman/5.0/en/delete.html

How to retrieve the current version of a MySQL database management system (DBMS)?

With CLI in one line :

mysql --user=root --password=pass --host=localhost db_name --execute='select version()';

or

mysql -uroot -ppass -hlocalhost db_name -e 'select version()';

return something like this :

+-----------+
| version() |
+-----------+
| 5.6.34    |
+-----------+

Making an asynchronous task in Flask

You can also try using multiprocessing.Process with daemon=True; the process.start() method does not block and you can return a response/status immediately to the caller while your expensive function executes in the background.

I experienced similar problem while working with falcon framework and using daemon process helped.

You'd need to do the following:

from multiprocessing import Process

@app.route('/render/<id>', methods=['POST'])
def render_script(id=None):
    ...
    heavy_process = Process(  # Create a daemonic process with heavy "my_func"
        target=my_func,
        daemon=True
    )
    heavy_process.start()
    return Response(
        mimetype='application/json',
        status=200
    )

# Define some heavy function
def my_func():
    time.sleep(10)
    print("Process finished")

You should get a response immediately and, after 10s you should see a printed message in the console.

NOTE: Keep in mind that daemonic processes are not allowed to spawn any child processes.

Swift add icon/image in UITextField

for Swift 3.0 add image on leftside of textField

textField.leftView = UIImageView(image: "small-calendar")
textField.leftView?.frame = CGRect(x: 0, y: 5, width: 20 , height:20)
textField.leftViewMode = .always

Difference between java.lang.RuntimeException and java.lang.Exception

Proper use of RuntimeException?

From Unchecked Exceptions -- The Controversy:

If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

Note that an unchecked exception is one derived from RuntimeException and a checked exception is one derived from Exception.

Why throw a RuntimeException if a client cannot do anything to recover from the exception? The article explains:

Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.

Free easy way to draw graphs and charts in C++?

Cern's ROOT produces some pretty nice stuff, I use it to display Neural Network data a lot.

Call a stored procedure with another in Oracle

To invoke the procedure from the SQLPlus command line, try one of these:

CALL test_sp_1();
EXEC test_sp_1

Changing Underline color

You can also use the box-shadow property to simulate an underline.

Here is a fiddle. The idea is to use two layered box shadows to position the line in the same place as an underline.

a.underline {
    text-decoration: none;
    box-shadow: inset 0 -4px 0 0 rgba(255, 255, 255, 1), inset 0 -5px 0 0 rgba(255, 0, 0, 1);
}

Bash script - variable content as a command to run

In the case where you have multiple variables containing the arguments for a command you're running, and not just a single string, you should not use eval directly, as it will fail in the following case:

function echo_arguments() {
  echo "Argument 1: $1"
  echo "Argument 2: $2"
  echo "Argument 3: $3"
  echo "Argument 4: $4"
}

# Note we are passing 3 arguments to `echo_arguments`, not 4
eval echo_arguments arg1 arg2 "Some arg"

Result:

Argument 1: arg1
Argument 2: arg2
Argument 3: Some
Argument 4: arg

Note that even though "Some arg" was passed as a single argument, eval read it as two.

Instead, you can just use the string as the command itself:

# The regular bash eval works by jamming all its arguments into a string then
# evaluating the string. This function treats its arguments as individual
# arguments to be passed to the command being run.
function eval_command() {
  "$@";
}

Note the difference between the output of eval and the new eval_command function:

eval_command echo_arguments arg1 arg2 "Some arg"

Result:

Argument 1: arg1
Argument 2: arg2
Argument 3: Some arg
Argument 4:

Merge up to a specific commit

Sure, being in master branch all you need to do is:

git merge <commit-id>

where commit-id is hash of the last commit from newbranch that you want to get in your master branch.

You can find out more about any git command by doing git help <command>. It that case it's git help merge. And docs are saying that the last argument for merge command is <commit>..., so you can pass reference to any commit or even multiple commits. Though, I never did the latter myself.

Popup window in winform c#

i am using this method.

add a from that you want to pop up, add all controls you need. in the code you can handle the user input and return result to the caller. for pop up the form just create a new instance of the form and show method.

/* create new form instance. i am overriding constructor to allow the caller form to set the form header */ 
var t = new TextPrompt("Insert your message and click Send button");
// pop up the form
t.Show();
if (t.DialogResult == System.Windows.Forms.DialogResult.OK)
{ 
  MessageBox.Show("RTP", "Message sent to user"); 
}

LIKE vs CONTAINS on SQL Server

Also try changing from this:

    SELECT * FROM table WHERE Contains(Column, "test") > 0;

To this:

    SELECT * FROM table WHERE Contains(Column, '"*test*"') > 0;

The former will find records with values like "this is a test" and "a test-case is the plan".

The latter will also find records with values like "i am testing this" and "this is the greatest".

Declare an array in TypeScript

let arr1: boolean[] = [];

console.log(arr1[1]);

arr1.push(true);

What is JSON and why would I use it?

The difference between JSON and conventional syntax would be as follows (in Javascript)

Conventional

 function Employee(name, Id, Phone, email){

      this.name = name;
      this.Id = Id;
      this.Phone = Phone;
      this.email = email;
  }

  //access or call it as 

var Emp = new Employee("mike","123","9373849784","[email protected]");

With JSON

if we use JSON we can define in different way as

  function Employee(args){

   this.name = args.name;
   this.Id = args.Id;
   this.Phone = args.Phone;
   this.email = args.email;
}

//now access this as...

var Emp = new Employee({'name':'Mike', 'Id':'123', 'Phone':'23792747', 'email':'[email protected]'});

The important thing we have to remember is that, if we have to build the "Employee" class or modal with 100 elements without JSON method we have to parse everything when creating class. But with JSON we can define the objects inline only when a new object for the class is defined.

so this line below is the way of doing things with JSON(just a simple way to define things)

 var Emp = new Employee({'name':'Mike', 'Id':'123', 'Phone':'23792747', 'email':'[email protected]'});

ORA-29283: invalid file operation ORA-06512: at "SYS.UTL_FILE", line 536

I had been facing this problem for two days and I found that the directory you create in Oracle also needs to created first on your physical disk.

I didn't find this point mentioned anywhere i tried to look up the solution to this.

Example

If you created a directory, let's say, 'DB_DIR'.

CREATE OR REPLACE DIRECTORY DB_DIR AS 'E:\DB_WORKS';

Then you need to ensure that DB_WORKS exists in your E:\ drive and also file system level Read/Write permissions are available to the Oracle process.

My understanding of UTL_FILE from my experiences is given below for this kind of operation.

UTL_FILE is an object under SYS user. GRANT EXECUTE ON SYS.UTL_FILE TO PUBLIC; needs to given while logged in as SYS. Otherwise, it will give declaration error in procedure. Anyone can create a directory as shown:- CREATE OR REPLACE DIRECTORY DB_DIR AS 'E:\DBWORKS'; But CREATE DIRECTORY permission should be in place. This can be granted as shown:- GRANT CREATE ALL DIRECTORY TO user; while logged in as SYS user. However, if this needs to be used by another user, grants need to be given to that user otherwise it will throw error. GRANT READ, WRITE, EXECUTE ON DB_DIR TO user; while loggedin as the user who created the directory. Then, compile your package. Before executing the procedure, ensure that the Directory exists physically on your Disk. Otherwise it will throw 'Invalid File Operation' error. (V. IMPORTANT) Ensure that Filesystem level Read/Write permissions are in place for the Oracle process. This is separate from the DB level permissions granted.(V. IMPORTANT) Execute procedure. File should get populated with the result set of your query.

How to set index.html as root file in Nginx?

For me, the try_files directive in the (currently most voted) answer https://stackoverflow.com/a/11957896/608359 led to rewrite cycles,

*173 rewrite or internal redirection cycle while internally redirecting

I had better luck with the index directive. Note that I used a forward slash before the name, which might or might not be what you want.

server {
  listen 443 ssl;
  server_name example.com;

  root /home/dclo/example;
  index /index.html;
  error_page 404 /index.html;

  # ... ssl configuration
}

In this case, I wanted all paths to lead to /index.html, including when returning a 404.

Remove all whitespaces from NSString

I strongly suggest placing this somewhere in your project:

extension String {
    func trim() -> String {
        return self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
    }

    func trim(withSet: NSCharacterSet) -> String {
        return self.stringByTrimmingCharactersInSet(withSet)
    }
}

Typescript empty object for a typed variable

Caveats

Here are two worthy caveats from the comments.

Either you want user to be of type User | {} or Partial<User>, or you need to redefine the User type to allow an empty object. Right now, the compiler is correctly telling you that user is not a User. – jcalz

I don't think this should be considered a proper answer because it creates an inconsistent instance of the type, undermining the whole purpose of TypeScript. In this example, the property Username is left undefined, while the type annotation is saying it can't be undefined. – Ian Liu Rodrigues

Answer

One of the design goals of TypeScript is to "strike a balance between correctness and productivity." If it will be productive for you to do this, use Type Assertions to create empty objects for typed variables.

type User = {
    Username: string;
    Email: string;
}

const user01 = {} as User;
const user02 = <User>{};

user01.Email = "[email protected]";

Here is a working example for you.

Here are type assertions working with suggestion.

Using std::max_element on a vector<double>

min_element and max_element return iterators, not values. So you need *min_element... and *max_element....

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use

This Error comes due to same table exist in 2 database like you have a database for project1 and in which you have table emp and again you have another database like project2 and in which you have table emp then when you try to insert something inside the database with-out your database name then you will get an error like about

Solution for that when you use mysql query then also mention database name along with table name.

OR

Don't Use Reserved key words like KEY as column name

Android: failed to convert @drawable/picture into a drawable

I think I found a way to have it work without restarting Eclipse, or without closing project (it worked for me):

  • rename image file name under res/ in Eclipse -> choose file and press F2 (for me it res/drawable-mdpi/bush-landscape.jpg -> changed to bush.jpg)

  • Build Project (it will still show error)

  • change image where you used it (I changed in Graphical Layout. For me the place was LinearLayout/Background/bush-landscape -> changed "bush-landscape" to "bush")

  • Build Project

How to generate and validate a software license key?

Caveat: you can't prevent users from pirating, but only make it easier for honest users to do the right thing.

Assuming you don't want to do a special build for each user, then:

  • Generate yourself a secret key for the product
  • Take the user's name
  • Concatentate the users name and the secret key and hash with (for example) SHA1
  • Unpack the SHA1 hash as an alphanumeric string. This is the individual user's "Product Key"
  • Within the program, do the same hash, and compare with the product key. If equal, OK.

But, I repeat: this won't prevent piracy


I have recently read that this approach is not cryptographically very sound. But this solution is already weak (as the software itself has to include the secret key somewhere), so I don't think this discovery invalidates the solution as far as it goes.

Just thought I really ought to mention this, though; if you're planning to derive something else from this, beware.

Execute a stored procedure in another stored procedure in SQL server

Suppose you have one stored procedure like this

First stored procedure:

Create  PROCEDURE LoginId
     @UserName nvarchar(200),
     @Password nvarchar(200)
AS
BEGIN
    DECLARE  @loginID  int

    SELECT @loginID = LoginId 
    FROM UserLogin 
    WHERE UserName = @UserName AND Password = @Password

    return @loginID
END

Now you want to call this procedure from another stored procedure like as below

Second stored procedure

Create  PROCEDURE Emprecord
         @UserName nvarchar(200),
         @Password nvarchar(200),
         @Email nvarchar(200),
         @IsAdmin bit,
         @EmpName nvarchar(200),
         @EmpLastName nvarchar(200),
         @EmpAddress nvarchar(200),
         @EmpContactNo nvarchar(150),
         @EmpCompanyName nvarchar(200)

    AS
    BEGIN
        INSERT INTO UserLogin VALUES(@UserName,@Password,@Email,@IsAdmin)

        DECLARE @EmpLoginid int

        **exec @EmpLoginid= LoginId @UserName,@Password**

        INSERT INTO tblEmployee VALUES(@EmpName,@EmpLastName,@EmpAddress,@EmpContactNo,@EmpCompanyName,@EmpLoginid)
    END

As you seen above, we can call one stored procedure from another

SQL Inner join 2 tables with multiple column conditions and update

UPDATE T1,T2 
INNER JOIN T1 ON  T1.Brands = T2.Brands
SET 
T1.Inci = T2.Inci
WHERE
    T1.Category= T2.Category
AND
    T1.Date = T2.Date

How to add New Column with Value to the Existing DataTable?

Without For loop:

Dim newColumn As New Data.DataColumn("Foo", GetType(System.String))     
newColumn.DefaultValue = "Your DropDownList value" 
table.Columns.Add(newColumn) 

C#:

System.Data.DataColumn newColumn = new System.Data.DataColumn("Foo", typeof(System.String));
newColumn.DefaultValue = "Your DropDownList value";
table.Columns.Add(newColumn);

Delete specified file from document directory

You can double protect your file removal with NSFileManager.defaultManager().isDeletableFileAtPath(PathName) As of now you MUST use do{}catch{} as the old error methods no longer work. isDeletableFileAtPath() is not a "throws" (i.e. "public func removeItemAtPath(path: String) throws") so it does not need the do...catch

let killFile = NSFileManager.defaultManager()

            if (killFile.isDeletableFileAtPath(PathName)){


                do {
                  try killFile.removeItemAtPath(arrayDictionaryFilePath)
                }
                catch let error as NSError {
                    error.description
                }
            }

How to set up ES cluster?

I tried the steps that @KannarKK suggested on ES 2.0.2, however, I could not bring the cluster up and running. Evidently, I figured out something, as I had set tcp port number on Master, on the Slave configuration discovery.zen.ping.unicast.hosts needs Master's port number along with IP address ( tcp port number ) for discovery. So when I try following configuration it works for me.

Node 1

cluster.name: mycluster
node.name: "node1"
node.master: true
node.data: true
http.port : 9200
tcp.port : 9300
discovery.zen.ping.multicast.enabled: false
# I think unicast.host on master is redundant.
discovery.zen.ping.unicast.hosts: ["node1.example.com"]

Node 2

cluster.name: mycluster
node.name: "node2"
node.master: false
node.data: true
http.port : 9201
tcp.port : 9301
discovery.zen.ping.multicast.enabled: false
# The port number of Node 1
discovery.zen.ping.unicast.hosts: ["node1.example.com:9300"]

how to remove multiple columns in r dataframe?

Adding answer as this was the top hit when searching for "drop multiple columns in r":

The general version of the single column removal, e.g df$column1 <- NULL, is to use list(NULL):

df[ ,c('column1', 'column2')] <- list(NULL)

This also works for position index as well:

df[ ,c(1,2)] <- list(NULL)

This is a more general drop and as some comments have mentioned, removing by indices isn't recommended. Plus the familiar negative subset (used in other answers) doesn't work for columns given as strings:

> iris[ ,-c("Species")]
Error in -"Species" : invalid argument to unary operator

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

Adding my two cents, based on a performance issue I observed.

If simple queries are getting parellelized unnecessarily, it can bring more problems than solving one. However, before adding MAXDOP into the query as "knee-jerk" fix, there are some server settings to check.

In Jeremiah Peschka - Five SQL Server Settings to Change, MAXDOP and "COST THRESHOLD FOR PARALLELISM" (CTFP) are mentioned as important settings to check.

Note: Paul White mentioned max server memory aslo as a setting to check, in a response to Performance problem after migration from SQL Server 2005 to 2012. A good kb article to read is Using large amounts of memory can result in an inefficient plan in SQL Server

Jonathan Kehayias - Tuning ‘cost threshold for parallelism’ from the Plan Cache helps to find out good value for CTFP.

Why is cost threshold for parallelism ignored?

Aaron Bertrand - Six reasons you should be nervous about parallelism has a discussion about some scenario where MAXDOP is the solution.

Parallelism-Inhibiting Components are mentioned in Paul White - Forcing a Parallel Query Execution Plan

How to Check whether Session is Expired or not in asp.net

I use the @Adi-lester answer and add some methods.

Method to verify if Session is Alive

public static void SessionIsAlive(HttpSessionStateBase Session)
{
    if (Session.Contents.Count == 0)
    {
        Response.Redirect("Timeout.html"); 
    }
    else
    {
        InitializeControls();
    }
}

Create session var in Page Load

protected void Page_Load(object sender, EventArgs e)
{
    Session["user_id"] = 1;
}

Create SaveData method (but you can use it in all methods)

protected void SaveData()
{
    // Verify if Session is Alive
    SessionIsAlive(Session);

    //Save Data Process
    // bla
    // bla
    // bla
}

Handler vs AsyncTask vs Thread

In my opinion threads aren't the most efficient way of doing socket connections but they do provide the most functionality in terms of running threads. I say that because from experience, running threads for a long time causes devices to be very hot and resource intensive. Even a simple while(true) will heat a phone in minutes. If you say that UI interaction is not important, perhaps an AsyncTask is good because they are designed for long-term processes. This is just my opinion on it.

UPDATE

Please disregard my above answer! I answered this question back in 2011 when I was far less experienced in Android than I am now. My answer above is misleading and is considered wrong. I'm leaving it there because many people commented on it below correcting me, and I've learned my lesson.

There are far better other answers on this thread, but I will at least give me more proper answer. There is nothing wrong with using a regular Java Thread; however, you should really be careful about how you implement it because doing it wrong can be very processor intensive (most notable symptom can be your device heating up). AsyncTasks are pretty ideal for most tasks that you want to run in the background (common examples are disk I/O, network calls, and database calls). However, AsyncTasks shouldn't be used for particularly long processes that may need to continue after the user has closed your app or put their device to standby. I would say for most cases, anything that doesn't belong in the UI thread, can be taken care of in an AsyncTask.

Left align and right align within div in Bootstrap

2021 Update...

Bootstrap 5 (beta)

For aligning within a flexbox div or row...

  • ml-auto is now ms-auto
  • mr-auto is now me-auto

Bootstrap 4+

  • pull-right is now float-right
  • text-right is the same as 3.x, and works for inline elements
  • both float-* and text-* are responsive for different alignment at different widths (ie: float-sm-right)

The flexbox utils (eg:justify-content-between) can also be used for alignment:

<div class="d-flex justify-content-between">
      <div>
         left
      </div>
      <div>
         right
      </div>
 </div>

or, auto-margins (eg:ml-auto) in any flexbox container (row,navbar,card,d-flex,etc...)

<div class="d-flex">
      <div>
         left
      </div>
      <div class="ml-auto">
         right
      </div>
 </div>

Bootstrap 4 Align Demo
Bootstrap 4 Right Align Examples(float, flexbox, text-right, etc...)


Bootstrap 3

Use the pull-right class..

<div class="container">
  <div class="row">
    <div class="col-md-6">Total cost</div>
    <div class="col-md-6"><span class="pull-right">$42</span></div>
  </div>
</div>

Bootstrap 3 Demo

You can also use the text-right class like this:

  <div class="row">
    <div class="col-md-6">Total cost</div>
    <div class="col-md-6 text-right">$42</div>
  </div>

Bootstrap 3 Demo 2

How to get input from user at runtime

declare
a number;
b number;
begin
a:= :a;
b:= :b;
if a>b then
dbms_output.put_line('Large number is '||a);
else
dbms_output.put_line('Large number is '||b);
end if;
end;

How to get the scroll bar with CSS overflow on iOS

Solution given by Chris Barr here

function isTouchDevice(){
    try{
        document.createEvent("TouchEvent");
        return true;
    }catch(e){
        return false;
    }
}

function touchScroll(id){
    if(isTouchDevice()){ //if touch events exist...
        var el=document.getElementById(id);
        var scrollStartPos=0;

        document.getElementById(id).addEventListener("touchstart", function(event) {
            scrollStartPos=this.scrollTop+event.touches[0].pageY;
            event.preventDefault();
        },false);

        document.getElementById(id).addEventListener("touchmove", function(event) {
            this.scrollTop=scrollStartPos-event.touches[0].pageY;
            event.preventDefault();
        },false);
    }
}

Works fine for me. Remove event.preventDefault if you need to use some clicks...

How do I view the SSIS packages in SQL Server Management Studio?

The wizard likely created the package as a file. Do a search on your system for files with an extension of .dtsx. This is the actual "SSIS Package" file.

As for loading it in Management Studio, you don't actually view it through there. If you have SQL Server 2005 loaded on your machine, look in the program group. You should find an application with the same icon as Visual Studio called "SQL Server Business Intelligence Development Studio". It's basically a stripped down version of VS 2005 which allows you to create SSIS packages.

Create a blank solution and add your .dtsx file to that to edit/view it.

How can javascript upload a blob?

I tried all the solutions above and in addition, those in related answers as well. Solutions including but not limited to passing the blob manually to a HTMLInputElement's file property, calling all the readAs* methods on FileReader, using a File instance as second argument for a FormData.append call, trying to get the blob data as a string by getting the values at URL.createObjectURL(myBlob) which turned out nasty and crashed my machine.

Now, if you happen to attempt those or more and still find you're unable to upload your blob, it could mean the problem is server-side. In my case, my blob exceeded the http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize and post_max_size limit in PHP.INI so the file was leaving the front end form but getting rejected by the server. You could either increase this value directly in PHP.INI or via .htaccess

Is it possible to create a temporary table in a View and drop it after select?

Not possible but if you try CTE, this would be the code:

ALTER VIEW [dbo].[VW_PuntosDeControlDeExpediente]
AS
    WITH TEMP (RefLocal, IdPuntoControl, Descripcion) 
    AS 
    (
        SELECT 
              EX.RefLocal
            , PV.IdPuntoControl
            , PV.Descripcion
        FROM [dbo].[PuntosDeControl] AS PV
        INNER JOIN [dbo].[Vertidos] AS VR ON VR.IdVertido = PV.IdVertido
        INNER JOIN [dbo].[ExpedientesMF] AS MF ON MF.IdExpedienteMF = VR.IdExpedienteMF
        INNER JOIN [dbo].[Expedientes] AS EX ON EX.IdExpediente = MF.IdExpediente
    )
    SELECT 
          Q1.[RefLocal]
        ,    [IdPuntoControl] = ( SELECT MAX(IdPuntoControl) FROM TEMP WHERE [RefLocal] = Q1.[RefLocal] AND [Descripcion] = Q1.[Descripcion] )
        , Q1.[Descripcion]
    FROM TEMP AS Q1
    GROUP BY Q1.[RefLocal], Q1.[Descripcion]
GO

changing permission for files and folder recursively using shell command in mac

The issue is that the * is getting interpreted by your shell and is expanding to a file named TEST_FILE that happens to be in your current working directory, so you're telling find to execute the command named TEST_FILE which doesn't exist. I'm not sure what you're trying to accomplish with that *, you should just remove it.

Furthermore, you should use the idiom -exec program '{}' \+ instead of -exec program '{}' \; so that find doesn't fork a new process for each file. With ;, a new process is forked for each file, whereas with +, it only forks one process and passes all of the files on a single command line, which for simple programs like chmod is much more efficient.

Lastly, chmod can do recursive changes on its own with the -R flag, so unless you need to search for specific files, just do this:

chmod -R 777 /Users/Test/Desktop/PATH

bootstrap 3 - how do I place the brand in the center of the navbar?

Another option is to use nav-justified..

<nav class="navbar navbar-default" role="navigation">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </button>    
  </div>
  <div class="navbar-collapse collapse">
    <ul class="nav nav-justified">
      <li><a href="#" class="navbar-brand">Brand</a></li>
    </ul>
  </div>
</nav>

CSS

.navbar-brand {
    float:none;
}

Bootply

Alternate example

Difference between except: and except Exception as e: in Python

except:

accepts all exceptions, whereas

except Exception as e:

only accepts exceptions that you're meant to catch.

Here's an example of one that you're not meant to catch:

>>> try:
...     input()
... except:
...     pass
... 
>>> try:
...     input()
... except Exception as e:
...     pass
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
KeyboardInterrupt

The first one silenced the KeyboardInterrupt!

Here's a quick list:

issubclass(BaseException, BaseException)
#>>> True
issubclass(BaseException, Exception)
#>>> False


issubclass(KeyboardInterrupt, BaseException)
#>>> True
issubclass(KeyboardInterrupt, Exception)
#>>> False


issubclass(SystemExit, BaseException)
#>>> True
issubclass(SystemExit, Exception)
#>>> False

If you want to catch any of those, it's best to do

except BaseException:

to point out that you know what you're doing.


All exceptions stem from BaseException, and those you're meant to catch day-to-day (those that'll be thrown for the programmer) inherit too from Exception.

Set JavaScript variable = null, or leave undefined?

Generally speak I defined null as it indicates a human set the value and undefined to indicate no setting has taken place.

What is the purpose of mvnw and mvnw.cmd files?

The Maven Wrapper is an excellent choice for projects that need a specific version of Maven (or for users that don't want to install Maven at all). Instead of installing many versions of it in the operating system, we can just use the project-specific wrapper script.

mvnw: it's an executable Unix shell script used in place of a fully installed Maven

mvnw.cmd: it's for Windows environment


Use Cases

The wrapper should work with different operating systems such as:

  • Linux
  • OSX
  • Windows
  • Solaris

After that, we can run our goals like this for the Unix system:

./mvnw clean install

And the following command for Batch:

./mvnw.cmd clean install

If we don't have the specified Maven in the wrapper properties, it'll be downloaded and installed in the folder $USER_HOME/.m2/wrapper/dists of the system.


Maven Wrapper plugin

Maven Wrapper plugin to make auto installation in a simple Spring Boot project.

First, we need to go in the main folder of the project and run this command:

mvn -N io.takari:maven:wrapper

We can also specify the version of Maven:

mvn -N io.takari:maven:wrapper -Dmaven=3.5.2

The option -N means –non-recursive so that the wrapper will only be applied to the main project of the current directory, not in any submodules.


Source 1 (further reading): https://www.baeldung.com/maven-wrapper

Static Classes In Java

Yes there is a static nested class in java. When you declare a nested class static, it automatically becomes a stand alone class which can be instantiated without having to instantiate the outer class it belongs to.

Example:

public class A
{

 public static class B
 {
 }
}

Because class B is declared static you can explicitly instantiate as:

B b = new B();

Note if class B wasn't declared static to make it stand alone, an instance object call would've looked like this:

A a= new A();
B b = a.new B();

Homebrew refusing to link OpenSSL

None of these solutions worked for me on OS X El Capitan 10.11.6. Probably because OS X has a native version of openssl that it believes is superior, and as such, does not like tampering.

So, I took the high road and started fresh...


Manually install and symlink

cd /usr/local/src  
  • If you're getting "No such file or directory", make it:

    cd /usr/local && mkdir src && cd src

Download openssl:

curl --remote-name https://www.openssl.org/source/openssl-1.0.2h.tar.gz

Extract and cd in:

tar -xzvf openssl-1.0.2h.tar.gz
cd openssl-1.0.2h

Compile and install:

./configure darwin64-x86_64-cc --prefix=/usr/local/openssl-1.0.2h shared
make depend
make
make install

Now symlink OS X's openssl to your new and updated openssl:

ln -s /usr/local/openssl-1.0.2h/bin/openssl /usr/local/bin/openssl

Close terminal, open a new session, and verify OS X is using your new openssl:

openssl version -a

Python debugging tips

Getting a stack trace from a running Python application

There are several tricks here. These include

  • Breaking into an interpreter/printing a stack trace by sending a signal
  • Getting a stack trace out of an unprepared Python process
  • Running the interpreter with flags to make it useful for debugging

Why does an onclick property set with setAttribute fail to work in IE?

Did you try:

    execBtn.setAttribute("onclick", function() { runCommand() });

Filtering DataSet

You can use DataTable.Select:

var strExpr = "CostumerID = 1 AND OrderCount > 2";
var strSort = "OrderCount DESC";

// Use the Select method to find all rows matching the filter.
foundRows = ds.Table[0].Select(strExpr, strSort);  

Or you can use DataView:

ds.Tables[0].DefaultView.RowFilter = strExpr;  

UPDATE I'm not sure why you want to have a DataSet returned. But I'd go with the following solution:

var dv = ds.Tables[0].DefaultView;
dv.RowFilter = strExpr;
var newDS = new DataSet();
var newDT = dv.ToTable();
newDS.Tables.Add(newDT);

How to use a FolderBrowserDialog from a WPF application

I realize this is an old question, but here is an approach which might be slightly more elegant (and may or may not have been available before)...

using System;
using System.Windows;
using System.Windows.Forms;

// ...

/// <summary>
///     Utilities for easier integration with WinForms.
/// </summary>
public static class WinFormsCompatibility {

    /// <summary>
    ///     Gets a handle of the given <paramref name="window"/> and wraps it into <see cref="IWin32Window"/>,
    ///     so it can be consumed by WinForms code, such as <see cref="FolderBrowserDialog"/>.
    /// </summary>
    /// <param name="window">
    ///     The WPF window whose handle to get.
    /// </param>
    /// <returns>
    ///     The handle of <paramref name="window"/> is returned as <see cref="IWin32Window.Handle"/>.
    /// </returns>
    public static IWin32Window GetIWin32Window(this Window window) {
        return new Win32Window(new System.Windows.Interop.WindowInteropHelper(window).Handle);
    }

    /// <summary>
    ///     Implementation detail of <see cref="GetIWin32Window"/>.
    /// </summary>
    class Win32Window : IWin32Window { // NOTE: This is System.Windows.Forms.IWin32Window, not System.Windows.Interop.IWin32Window!

        public Win32Window(IntPtr handle) {
            Handle = handle; // C# 6 "read-only" automatic property.
        }

        public IntPtr Handle { get; }

    }

}

Then, from your WPF window, you can simply...

public partial class MainWindow : Window {

    void Button_Click(object sender, RoutedEventArgs e) {
        using (var dialog = new FolderBrowserDialog()) {
            if (dialog.ShowDialog(this.GetIWin32Window()) == System.Windows.Forms.DialogResult.OK) {
                // Use dialog.SelectedPath.
            }
        }
    }

}

Actually, does it matter?

I'm not sure if it matters in this case, but generally, you should tell Windows what is your window hierarchy, so if a parent window is clicked while child window is modal, Windows can provide a visual (and possibly audible) clue to the user.

Also, it ensures the "right" window is on top when there are multiple modal windows (not that I'm advocating such UI design). I've seen UIs designed by a certain multi-billion dollar corporation (which shell remain unnamed), that hanged simply because one modal dialog got "stuck" underneath another, and user had no clue it was even there, let alone how to close it.

Why javascript getTime() is not a function?

To use this function/method,you need an instance of the class Date .

This method is always used in conjunction with a Date object.

See the code below :

var d = new Date();
d.getTime();

Link : http://www.w3schools.com/jsref/jsref_getTime.asp

Python Set Comprehension

You can get clean and clear solutions by building the appropriate predicates as helper functions. In other words, use the Python set-builder notation the same way you would write the answer with regular mathematics set-notation.

The whole idea behind set comprehensions is to let us write and reason in code the same way we do mathematics by hand.

With an appropriate predicate in hand, problem 1 simplifies to:

 low_primes = {x for x in range(1, 100) if is_prime(x)}

And problem 2 simplifies to:

 low_prime_pairs = {(x, x+2) for x in range(1,100,2) if is_prime(x) and is_prime(x+2)}

Note how this code is a direct translation of the problem specification, "A Prime Pair is a pair of consecutive odd numbers that are both prime."

P.S. I'm trying to give you the correct problem solving technique without actually giving away the answer to the homework problem.

exec failed because the name not a valid identifier?

As was in my case if your sql is generated by concatenating or uses converts then sql at execute need to be prefixed with letter N as below

e.g.

Exec N'Select bla..' 

the N defines string literal is unicode.

How to use clock() in C++

On Windows at least, the only practically accurate measurement mechanism is QueryPerformanceCounter (QPC). std::chrono is implemented using it (since VS2015, if you use that), but it is not accurate to the same degree as using QueryPerformanceCounter directly. In particular it's claim to report at 1 nanosecond granularity is absolutely not correct. So, if you're measuring something that takes a very short amount of time (and your case might just be such a case), then you should use QPC, or the equivalent for your OS. I came up against this when measuring cache latencies, and I jotted down some notes that you might find useful, here; https://github.com/jarlostensen/notesandcomments/blob/master/stdchronovsqcp.md

Console app arguments, how arguments are passed to Main method

Read MSDN.

it also contains a link to the args.

short answer: no, the main does not get override. when visual studio (actually the compiler) builds your exe it must declare a starting point for the assmebly, that point is the main function.

if you meant how to literary pass args then you can either run you're app from the command line with them (e.g. appname.exe param1 param2) or in the project setup, enter them (in the command line arguments in the Debug tab)

in the main you will need to read those args for example:

for (int i = 0; i < args.Length; i++)
{
    string flag = args.GetValue(i).ToString();
    if (flag == "bla") 
    {
        Bla();
    }
}

Pie chart with jQuery

A few others that have not been mentioned:

For mini pies, lines and bars, Peity is brilliant, simple, tiny, fast, uses really elegant markup.

I'm not sure of it's relationship with Flot (given its name), but Flotr2 is pretty good, certainly does better pies than Flot.

Bluff produces nice-looking line graphs, but I had a bit of trouble with its pies.

Not what I was after, but another commercial product (much like Highcharts) is TeeChart.

Testing javascript with Mocha - how can I use console.log to debug a test?

Use the debug lib.

import debug from 'debug'
const log = debug('server');

Use it:

log('holi')

then run:

DEBUG=server npm test

And that's it!

JavaScript variable number of arguments to function

Use the arguments object when inside the function to have access to all arguments passed in.

Windows command to convert Unix line endings?

Based on Endoro's answer but to keep the blanks, try this:

@echo off
setlocal enabledelayedexpansion
(for /f "tokens=* delims=:" %%i in ('findstr /n "^" file.unix') do (
        set line=%%i
        set line=!line:*:=!
        echo(!line!
        ))>file.dos

What does the Java assert keyword do, and when should it be used?

A real world example, from a Stack-class (from Assertion in Java Articles)

public int pop() {
   // precondition
   assert !isEmpty() : "Stack is empty";
   return stack[--num];
}

Objective-C declared @property attributes (nonatomic, copy, strong, weak)

This link has the break down

http://clang.llvm.org/docs/AutomaticReferenceCounting.html#ownership.spelling.property

assign implies __unsafe_unretained ownership.

copy implies __strong ownership, as well as the usual behavior of copy semantics on the setter.

retain implies __strong ownership.

strong implies __strong ownership.

unsafe_unretained implies __unsafe_unretained ownership.

weak implies __weak ownership.

Resize UIImage and change the size of UIImageView

This is the Swift equivalent for Rajneesh071's answer, using extensions

UIImage {
  func scaleToSize(aSize :CGSize) -> UIImage {
    if (CGSizeEqualToSize(self.size, aSize)) {
      return self
    }

    UIGraphicsBeginImageContextWithOptions(aSize, false, 0.0)
    self.drawInRect(CGRectMake(0.0, 0.0, aSize.width, aSize.height))
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
  }
}

Usage:

let image = UIImage(named: "Icon")
item.icon = image?.scaleToSize(CGSize(width: 30.0, height: 30.0))

add an onclick event to a div

Assign the onclick like this:

divTag.onclick = printWorking;

The onclick property will not take a string when assigned. Instead, it takes a function reference (in this case, printWorking).
The onclick attribute can be a string when assigned in HTML, e.g. <div onclick="func()"></div>, but this is generally not recommended.

Copy table to a different database on a different SQL Server

Microsoft SQL Server Database Publishing Wizard will generate all the necessary insert statements, and optionally schema information as well if you need that:

http://www.microsoft.com/downloads/details.aspx?familyid=56E5B1C5-BF17-42E0-A410-371A838E570A

How do you change the document font in LaTeX?

For a different approach, I would suggest using the XeTeX or LuaTex system. They allow you to access system fonts (TrueType, OpenType, etc) and set font features. In a typical LaTeX document, you just need to include this in your headers:

\usepackage{fontspec}
\defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase}
\setmainfont{Times}
\setmonofont{Lucida Sans Typewriter}

It's the fontspec package that allows for \setmainfont and \setmonofont. The ability to choose a multitude of font features is beyond my expertise, but I would suggest looking up some examples and seeing if this would suit your needs.

Just don't forget to replace your favorite latex compiler by the appropriate one (xelatex or lualatex).

How to make program go back to the top of the code instead of closing

write a for or while loop and put all of your code inside of it? Goto type programming is a thing of the past.

https://wiki.python.org/moin/ForLoop

Hide header in stack navigator React navigation

if you want remove the header from all screen goto app.js and add this code to Stack.Navigator

screenOptions={ { headerShown: false } }

How do I load an url in iframe with Jquery

Just in case anyone still stumbles upon this old question:

The code was theoretically almost correct in a sense, the problem was the use of $('this') instead of $(this), therefore telling jQuery to look for a tag.

$(document).ready(function(){
  $("#frame").click(function () { 
    $(this).load("http://www.google.com/");
  });
});

The script itself woudln't work as it is right now though because the load() function itself is an AJAX function, and google does not seem to specifically allow the use of loading this page with AJAX, but this method should be easy to use in order to load pages from your own domain by using relative paths.

<> And Not In VB.NET

The C# and VB.NET compilers often generate different IL for operations that are apparently equivalent in both languages. It just so happens that C# does the "expected" thing when you write stringvar == null, but VB.NET does not. To get the same effect in VB.NET you have to force true reference equality with the Is operator.

Using sed, Insert a line above or below the pattern?

To append after the pattern: (-i is for in place replace). line1 and line2 are the lines you want to append(or prepend)

sed -i '/pattern/a \
line1 \
line2' inputfile

Output:

#cat inputfile
 pattern
 line1 line2 

To prepend the lines before:

sed -i '/pattern/i \
line1 \
line2' inputfile

Output:

#cat inputfile
 line1 line2 
 pattern

How to add a response header on nginx when using proxy_pass?

There is a module called HttpHeadersMoreModule that gives you more control over headers. It does not come with Nginx and requires additional installation. With it, you can do something like this:

location ... {
  more_set_headers "Server: my_server";
}

That will "set the Server output header to the custom value for any status code and any content type". It will replace headers that are already set or add them if unset.

Change URL without refresh the page

When you use a function ...

<p onclick="update_url('/en/step2');">Link</p>

<script>
function update_url(url) {
    history.pushState(null, null, url);
}
</script>

How to uncompress a tar.gz in another directory

You can use the option -C (or --directory if you prefer long options) to give the target directory of your choice in case you are using the Gnu version of tar. The directory should exist:

mkdir foo
tar -xzf bar.tar.gz -C foo

If you are not using a tar capable of extracting to a specific directory, you can simply cd into your target directory prior to calling tar; then you will have to give a complete path to your archive, of course. You can do this in a scoping subshell to avoid influencing the surrounding script:

mkdir foo
(cd foo; tar -xzf ../bar.tar.gz)  # instead of ../ you can use an absolute path as well

Or, if neither an absolute path nor a relative path to the archive file is suitable, you also can use this to name the archive outside of the scoping subshell:

TARGET_PATH=a/very/complex/path/which/might/even/be/absolute
mkdir -p "$TARGET_PATH"
(cd "$TARGET_PATH"; tar -xzf -) < bar.tar.gz

Visual Studio Post Build Event - Copy to Relative Directory Location

Here is what you want to put in the project's Post-build event command line:

copy /Y "$(TargetDir)$(ProjectName).dll" "$(SolutionDir)lib\$(ProjectName).dll"

EDIT: Or if your target name is different than the Project Name.

copy /Y "$(TargetDir)$(TargetName).dll" "$(SolutionDir)lib\$(TargetName).dll"

Where to find Java JDK Source Code?

Yes!! Got it!

I downloaded the Java Developer Kit (JDK) from sun.com for Linux. There was src.zip in. But first I uninstalled all Java packages with synaptic.

Get all validation errors from Angular 2 FormGroup

Based on the @MixerOID response, here is my final solution as a component (maybe I create a library). I also support FormArray's:

import {Component, ElementRef, Input, OnInit} from '@angular/core';
import {FormArray, FormGroup, ValidationErrors} from '@angular/forms';
import {TranslateService} from '@ngx-translate/core';

interface AllValidationErrors {
  controlName: string;
  errorName: string;
  errorValue: any;
}

@Component({
  selector: 'app-form-errors',
  templateUrl: './form-errors.component.html',
  styleUrls: ['./form-errors.component.scss']
})
export class FormErrorsComponent implements OnInit {

  @Input() form: FormGroup;
  @Input() formRef: ElementRef;
  @Input() messages: Array<any>;

  private errors: AllValidationErrors[];

  constructor(
    private translateService: TranslateService
  ) {
    this.errors = [];
    this.messages = [];
  }

  ngOnInit() {
    this.form.valueChanges.subscribe(() => {
      this.errors = [];
      this.calculateErrors(this.form);
    });

    this.calculateErrors(this.form);
  }

  calculateErrors(form: FormGroup | FormArray) {
    Object.keys(form.controls).forEach(field => {
      const control = form.get(field);
      if (control instanceof FormGroup || control instanceof FormArray) {
        this.errors = this.errors.concat(this.calculateErrors(control));
        return;
      }

      const controlErrors: ValidationErrors = control.errors;
      if (controlErrors !== null) {
        Object.keys(controlErrors).forEach(keyError => {
          this.errors.push({
            controlName: field,
            errorName: keyError,
            errorValue: controlErrors[keyError]
          });
        });
      }
    });

    // This removes duplicates
    this.errors = this.errors.filter((error, index, self) => self.findIndex(t => {
      return t.controlName === error.controlName && t.errorName === error.errorName;
    }) === index);
    return this.errors;
  }

  getErrorMessage(error) {
    switch (error.errorName) {
      case 'required':
        return this.translateService.instant('mustFill') + ' ' + this.messages[error.controlName];
      default:
        return 'unknown error ' + error.errorName;
    }
  }
}

And the HTML:

<div *ngIf="formRef.submitted">
  <div *ngFor="let error of errors" class="text-danger">
    {{getErrorMessage(error)}}
  </div>
</div>

Usage:

<app-form-errors [form]="languageForm"
                 [formRef]="formRef"
                 [messages]="{language: 'Language'}">
</app-form-errors>

Send push to Android by C# using FCM (Firebase Cloud Messaging)

Based on Teste's code .. I can confirm the following works. I can't say whether or not this is "good" code, but it certainly works and could get you back up and running quickly if you ended up with GCM to FCM server problems!

public AndroidFCMPushNotificationStatus SendNotification(string serverApiKey, string senderId, string deviceId, string message)
{
    AndroidFCMPushNotificationStatus result = new AndroidFCMPushNotificationStatus();

    try
    {
        result.Successful = false;
        result.Error = null;

        var value = message;
        WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
        tRequest.Method = "post";
        tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
        tRequest.Headers.Add(string.Format("Authorization: key={0}", serverApiKey));
        tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));

        string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message=" + value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + "";

        Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
        tRequest.ContentLength = byteArray.Length;

        using (Stream dataStream = tRequest.GetRequestStream())
        {
            dataStream.Write(byteArray, 0, byteArray.Length);

            using (WebResponse tResponse = tRequest.GetResponse())
            {
                using (Stream dataStreamResponse = tResponse.GetResponseStream())
                {
                    using (StreamReader tReader = new StreamReader(dataStreamResponse))
                    {
                        String sResponseFromServer = tReader.ReadToEnd();
                        result.Response = sResponseFromServer;
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        result.Successful = false;
        result.Response = null;
        result.Error = ex;
    }

    return result;
}


public class AndroidFCMPushNotificationStatus
{
    public bool Successful
    {
        get;
        set;
    }

    public string Response
    {
        get;
        set;
    }
    public Exception Error
    {
        get;
        set;
    }
}

Display animated GIF in iOS

You can use SwiftGif from this link

Usage:

imageView.loadGif(name: "jeremy")

jQuery: Get height of hidden element in jQuery

Following Nick Craver's solution, setting the element's visibility allows it to get accurate dimensions. I've used this solution very very often. However, having to reset the styles manually, I've come to find this cumbersome, given that modifying the element's initial positioning/display in my css through development, I often forget to update the related javascript code. The following code doesn't reset the styles per say, but removes the inline styles added by javascript:

$("#myDiv")
.css({
    position:   'absolute',
    visibility: 'hidden',
    display:    'block'
});

optionHeight = $("#myDiv").height();
optionWidth = $("#myDiv").width();

$("#myDiv").attr('style', '');

The only assumption here is that there can't be other inline styles or else they will be removed aswell. The benefit here, however, is that the element's styles are returned to what they were in the css stylesheet. As a consequence, you can write this up as a function where an element is passed through, and a height or width is returned.

Another issue I've found of setting the styles inline via js is that when dealing with transitions through css3, you become forced to adapt your style rules' weights to be stronger than an inline style, which can be frustrating sometimes.

Mockito: Mock private field initialization

In case you use Spring Test try org.springframework.test.util.ReflectionTestUtils

 ReflectionTestUtils.setField(testObject, "person", mockedPerson);

load external URL into modal jquery ui dialog

_x000D_
_x000D_
if you are using **Bootstrap** this is solution, _x000D_
_x000D_
$(document).ready(function(e) {_x000D_
    $('.bootpopup').click(function(){_x000D_
  var frametarget = $(this).attr('href');_x000D_
  targetmodal = '#myModal'; _x000D_
        $('#modeliframe').attr("src", frametarget );   _x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>_x000D_
<!-- Button trigger modal -->_x000D_
<a  href="http://twitter.github.io/bootstrap/" title="Edit Transaction" class="btn btn-primary btn-lg bootpopup" data-toggle="modal" data-target="#myModal">_x000D_
  Launch demo modal_x000D_
</a>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
         <iframe src="" id="modeliframe" style="zoom:0.60" frameborder="0" height="250" width="99.6%"></iframe>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        <button type="button" class="btn btn-primary">Save changes</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Creating a byte array from a stream

public static byte[] ToByteArray(Stream stream)
    {
        if (stream is MemoryStream)
        {
            return ((MemoryStream)stream).ToArray();
        }
        else
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }            
    }

Difference between JE/JNE and JZ/JNZ

From the Intel's manual - Instruction Set Reference, the JE and JZ have the same opcode (74 for rel8 / 0F 84 for rel 16/32) also JNE and JNZ (75 for rel8 / 0F 85 for rel 16/32) share opcodes.

JE and JZ they both check for the ZF (or zero flag), although the manual differs slightly in the descriptions of the first JE rel8 and JZ rel8 ZF usage, but basically they are the same.

Here is an extract from the manual's pages 464, 465 and 467.

 Op Code    | mnemonic  | Description
 -----------|-----------|-----------------------------------------------  
 74 cb      | JE rel8   | Jump short if equal (ZF=1).
 74 cb      | JZ rel8   | Jump short if zero (ZF ? 1).

 0F 84 cw   | JE rel16  | Jump near if equal (ZF=1). Not supported in 64-bit mode.
 0F 84 cw   | JZ rel16  | Jump near if 0 (ZF=1). Not supported in 64-bit mode.

 0F 84 cd   | JE rel32  | Jump near if equal (ZF=1).
 0F 84 cd   | JZ rel32  | Jump near if 0 (ZF=1).

 75 cb      | JNE rel8  | Jump short if not equal (ZF=0).
 75 cb      | JNZ rel8  | Jump short if not zero (ZF=0).

 0F 85 cd   | JNE rel32 | Jump near if not equal (ZF=0).
 0F 85 cd   | JNZ rel32 | Jump near if not zero (ZF=0).

How to change the current URL in javascript?

This is more robust:

mi = location.href.split(/(\d+)/);
no = mi.length - 2;
os = mi[no];
mi[no]++;
if ((mi[no] + '').length < os.length) mi[no] = os.match(/0+/) + mi[no];
location.href = mi.join('');

When the URL has multiple numbers, it will change the last one:

http://mywebsite.com/8815/1.html

It supports numbers with leading zeros:

http://mywebsite.com/0001.html

Example

Javascript: Unicode string to hex

Here is my take: these functions convert a UTF8 string to a proper HEX without the extra zeroes padding. A real UTF8 string has characters with 1, 2, 3 and 4 bytes length.

While working on this I found a couple key things that solved my problems:

  1. str.split('') doesn't handle multi-byte characters like emojis correctly. The proper/modern way to handle this is with Array.from(str)
  2. encodeURIComponent() and decodeURIComponent() are great tools to convert between string and hex. They are pretty standard, they handle UTF8 correctly.
  3. (Most) ASCII characters (codes 0 - 127) don't get URI encoded, so they need to handled separately. But c.charCodeAt(0).toString(16) works perfectly for those
    function utf8ToHex(str) {
      return Array.from(str).map(c => 
        c.charCodeAt(0) < 128 ? c.charCodeAt(0).toString(16) : 
        encodeURIComponent(c).replace(/\%/g,'').toLowerCase()
      ).join('');
    },
    function hexToUtf8: function(hex) {
      return decodeURIComponent('%' + hex.match(/.{1,2}/g).join('%'));
    }

Demo: https://jsfiddle.net/lyquix/k2tjbrvq/

Java HTTP Client Request with defined timeout

HttpParams is deprecated in the new Apache HTTPClient library. Using the code provided by Laz leads to deprecation warnings.

I suggest to use RequestConfig instead on your HttpGet or HttpPost instance:

final RequestConfig params = RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(3000).build();
httpPost.setConfig(params);

ImportError: No module named 'bottle' - PyCharm

The settings are changed for PyCharm 5+.

  • Go to File > Default Settings
  • In left sidebar, click Default Project > Project Interpreter
  • At bottom of window, click + to install or - to uninstall.
  • If we click +, a new window opens where we can decrease the results by entering the package name/keyword.
  • Install the package.
  • Go to File > Invalidate caches/restart and click Invalidate and Restart to apply changes and restart PyCharm.

    Settings

    Install package

Typescript: Type 'string | undefined' is not assignable to type 'string'

if you want to have nullable property change your interface to this:

interface Person {
  name?:string | null,
  age?:string | null,
  gender?:string | null,
  occupation?:string | null,
 }

if being undefined is not the case you can remove question marks (?) from in front of the property names.

Where and how is the _ViewStart.cshtml layout file linked?

From ScottGu's blog:

Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

Also see this.


In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

Wikipedia

There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

How to get the file path from URI?

File myFile = new File(uri.toString());
myFile.getAbsolutePath()

should return u the correct path

EDIT

As @Tron suggested the working code is

File myFile = new File(uri.getPath());
myFile.getAbsolutePath()

PHP - Extracting a property from an array of objects

function extract_ids($cats){
    $res = array();
    foreach($cats as $k=>$v) {
        $res[]= $v->id;
    }
    return $res
}

and use it in one line:

$ids = extract_ids($cats);

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

I ran into this issue calling a .Net assembly from a C++ client via COM. It turns out that one of the assemblies the .Net assembly depended on could not be found. I wrestled for a while trying to figure out what was wrong with the 1st assembly, but it was actually one of the 1st assembly's dependencies. I received two different errors when calling CoCreateInstance() from the C++ client. The first was: REGDB_E_CLASSNOTREG Class not registered And the second try was: 0x80131040 : The located assembly's manifest definition does not match the assembly reference.

So check that your assembly's references are present. I discovered this by browsing the 1st assembly with dotPeek and noticing one of it's references was missing. Placing the correct version of the dependency in the folder resolved both errors.

How to check if an email address exists without sending an email?

I think you cannot, there are so many scenarios where even sending an e-mail can fail. Eg. mail server on the user side is temporarily down, mailbox exists but is full so message cannot be delivered, etc.

That's probably why so many sites validate a registration after the user confirmed they have received the confirmation e-mail.

c++ compile error: ISO C++ forbids comparison between pointer and integer

You must remember to use single quotes for char constants. So use

if (answer == 'y') return true;

Rather than

if (answer == "y") return true;

I tested this and it works

SQL How to correctly set a date variable value and use it?

Your syntax is fine, it will return rows where LastAdDate lies within the last 6 months;

select cast('01-jan-1970' as datetime) as LastAdDate into #PubAdvTransData 
    union select GETDATE()
    union select NULL
    union select '01-feb-2010'

DECLARE @sp_Date DATETIME = DateAdd(m, -6, GETDATE())

SELECT * FROM #PubAdvTransData pat
     WHERE (pat.LastAdDate > @sp_Date)

>2010-02-01 00:00:00.000
>2010-04-29 21:12:29.920

Are you sure LastAdDate is of type DATETIME?

C compiling - "undefined reference to"?

As stated by a few others, this is a linking error. The section of code where this function is being called doesn't know what this function is. It either needs to be declared in a header file an defined in its own source file, or defined or declared in the same source file, above where it's being called.

Edit: In older versions of C, C89/C90, function declarations weren't actually required. So, you could just add the definition anywhere in the file in which you're using the function, even after the call and the compiler would infer the declaration. For example,

int main()
{
  int a = func();
}

int func()
{
   return 1;
}

However, this isn't good practice today and most languages, C++ for example, won't allow it. One way to get away with defining the function in the same source file in which you're using it, is to declare it at the beginning of the file. So, the previous example would look like this instead.

int func();

int main()
{
   int a = func();
}

int func()
{
  return 1;
}

Closing a Userform with Unload Me doesn't work

As specified by the top answer, I used the following in the code behind the button control.

Private Sub btnClose_Click()
    Unload Me
End Sub

In doing so, it will not attempt to unload a control, but rather will unload the user form where the button control resides. The "Me" keyword refers to the user form object even when called from a control on the user form. If you are getting errors with this technique, there are a couple of possible reasons.

  1. You could be entering the code in the wrong place (such as a separate module)

  2. You might be using an older version of Office. I'm using Office 2013. I've noticed that VBA changes over time.

From my experience, the use of the the DoCmd.... method is more specific to the macro features in MS Access, but not commonly used in Excel VBA.

Under normal (out of the box) conditions, the code above should work just fine.

Can't access RabbitMQ web management interface after fresh install

Something that just happened to me and caused me some headaches:

I have set up a new Linux RabbitMQ server and used a shell script to set up my own custom users (not guest!).

The script had several of those "code" blocks:

rabbitmqctl add_user test test
rabbitmqctl set_user_tags test administrator
rabbitmqctl set_permissions -p / test ".*" ".*" ".*"

Very similar to the one in Gabriele's answer, so I take his code and don't need to redact passwords.

Still I was not able to log in in the management console. Then I noticed that I had created the setup script in Windows (CR+LF line ending) and converted the file to Linux (LF only), then reran the setup script on my Linux server.

... and was still not able to log in, because it took another 15 minutes until I realized that calling add_user over and over again would not fix the broken passwords (which probably ended with a CR character). I had to call change_password for every user to fix my earlier mistake:

rabbitmqctl change_password test test

(Another solution would have been to delete all users and then call the script again)

How to use the read command in Bash?

Do you need the pipe?

echo -ne "$MENU"
read NUMBER

Django. Override save for model

Query the database for an existing record with the same PK. Compare the file sizes and checksums of the new and existing images to see if they're the same.

How can I get a specific field of a csv file?

import csv

def read_cell(x, y):
    with open('file.csv', 'r') as f:
        reader = csv.reader(f)
        y_count = 0
        for n in reader:
            if y_count == y:
                cell = n[x]
                return cell
            y_count += 1

print (read_cell(4, 8)) 

This example prints cell 4, 8 in Python 3.

Webdriver and proxy server for firefox

In case if you have an autoconfig URL -

        FirefoxProfile firefoxProfile = new FirefoxProfile();
        firefoxProfile.setPreference("network.proxy.type", 2);
        firefoxProfile.setPreference("network.proxy.autoconfig_url", "http://www.etc.com/wpad.dat");
        firefoxProfile.setPreference("network.proxy.no_proxies_on", "localhost");
        WebDriver driver = new FirefoxDriver(firefoxProfile);

Angular 2 ngfor first, last, index loop

Here is how its done in Angular 6

<li *ngFor="let user of userObservable ; first as isFirst">
   <span *ngIf="isFirst">default</span>
</li>

Note the change from let first = first to first as isFirst

Fast Bitmap Blur For Android SDK

Thanks @Yahel for the code. Posting the same method with alpha channel blurring support as it took me some time to make it work correctly so it may save someone's time:

/**
 * Stack Blur v1.0 from
 * http://www.quasimondo.com/StackBlurForCanvas/StackBlurDemo.html
 * Java Author: Mario Klingemann <mario at quasimondo.com>
 * http://incubator.quasimondo.com
 * <p/>
 * created Feburary 29, 2004
 * Android port : Yahel Bouaziz <yahel at kayenko.com>
 * http://www.kayenko.com
 * ported april 5th, 2012
 * <p/>
 * This is a compromise between Gaussian Blur and Box blur
 * It creates much better looking blurs than Box Blur, but is
 * 7x faster than my Gaussian Blur implementation.
 * <p/>
 * I called it Stack Blur because this describes best how this
 * filter works internally: it creates a kind of moving stack
 * of colors whilst scanning through the image. Thereby it
 * just has to add one new block of color to the right side
 * of the stack and remove the leftmost color. The remaining
 * colors on the topmost layer of the stack are either added on
 * or reduced by one, depending on if they are on the right or
 * on the left side of the stack.
 * <p/>
 * If you are using this algorithm in your code please add
 * the following line:
 * Stack Blur Algorithm by Mario Klingemann <[email protected]>
 */

public static Bitmap fastblur(Bitmap sentBitmap, float scale, int radius) {

    int width = Math.round(sentBitmap.getWidth() * scale);
    int height = Math.round(sentBitmap.getHeight() * scale);
    sentBitmap = Bitmap.createScaledBitmap(sentBitmap, width, height, false);

    Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

    if (radius < 1) {
        return (null);
    }

    int w = bitmap.getWidth();
    int h = bitmap.getHeight();

    int[] pix = new int[w * h];
    Log.e("pix", w + " " + h + " " + pix.length);
    bitmap.getPixels(pix, 0, w, 0, 0, w, h);

    int wm = w - 1;
    int hm = h - 1;
    int wh = w * h;
    int div = radius + radius + 1;

    int r[] = new int[wh];
    int g[] = new int[wh];
    int b[] = new int[wh];
    int a[] = new int[wh];
    int rsum, gsum, bsum, asum, x, y, i, p, yp, yi, yw;
    int vmin[] = new int[Math.max(w, h)];

    int divsum = (div + 1) >> 1;
    divsum *= divsum;
    int dv[] = new int[256 * divsum];
    for (i = 0; i < 256 * divsum; i++) {
        dv[i] = (i / divsum);
    }

    yw = yi = 0;

    int[][] stack = new int[div][4];
    int stackpointer;
    int stackstart;
    int[] sir;
    int rbs;
    int r1 = radius + 1;
    int routsum, goutsum, boutsum, aoutsum;
    int rinsum, ginsum, binsum, ainsum;

    for (y = 0; y < h; y++) {
        rinsum = ginsum = binsum = ainsum = routsum = goutsum = boutsum = aoutsum = rsum = gsum = bsum = asum = 0;
        for (i = -radius; i <= radius; i++) {
            p = pix[yi + Math.min(wm, Math.max(i, 0))];
            sir = stack[i + radius];
            sir[0] = (p & 0xff0000) >> 16;
            sir[1] = (p & 0x00ff00) >> 8;
            sir[2] = (p & 0x0000ff);
            sir[3] = 0xff & (p >> 24);

            rbs = r1 - Math.abs(i);
            rsum += sir[0] * rbs;
            gsum += sir[1] * rbs;
            bsum += sir[2] * rbs;
            asum += sir[3] * rbs;
            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
                ainsum += sir[3];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
                aoutsum += sir[3];
            }
        }
        stackpointer = radius;

        for (x = 0; x < w; x++) {

            r[yi] = dv[rsum];
            g[yi] = dv[gsum];
            b[yi] = dv[bsum];
            a[yi] = dv[asum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;
            asum -= aoutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];
            aoutsum -= sir[3];

            if (y == 0) {
                vmin[x] = Math.min(x + radius + 1, wm);
            }
            p = pix[yw + vmin[x]];

            sir[0] = (p & 0xff0000) >> 16;
            sir[1] = (p & 0x00ff00) >> 8;
            sir[2] = (p & 0x0000ff);
            sir[3] = 0xff & (p >> 24);

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];
            ainsum += sir[3];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;
            asum += ainsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[(stackpointer) % div];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];
            aoutsum += sir[3];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];
            ainsum -= sir[3];

            yi++;
        }
        yw += w;
    }
    for (x = 0; x < w; x++) {
        rinsum = ginsum = binsum = ainsum = routsum = goutsum = boutsum = aoutsum = rsum = gsum = bsum = asum = 0;
        yp = -radius * w;
        for (i = -radius; i <= radius; i++) {
            yi = Math.max(0, yp) + x;

            sir = stack[i + radius];

            sir[0] = r[yi];
            sir[1] = g[yi];
            sir[2] = b[yi];
            sir[3] = a[yi];

            rbs = r1 - Math.abs(i);

            rsum += r[yi] * rbs;
            gsum += g[yi] * rbs;
            bsum += b[yi] * rbs;
            asum += a[yi] * rbs;

            if (i > 0) {
                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];
                ainsum += sir[3];
            } else {
                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];
                aoutsum += sir[3];
            }

            if (i < hm) {
                yp += w;
            }
        }
        yi = x;
        stackpointer = radius;
        for (y = 0; y < h; y++) {
            pix[yi] = (dv[asum] << 24) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

            rsum -= routsum;
            gsum -= goutsum;
            bsum -= boutsum;
            asum -= aoutsum;

            stackstart = stackpointer - radius + div;
            sir = stack[stackstart % div];

            routsum -= sir[0];
            goutsum -= sir[1];
            boutsum -= sir[2];
            aoutsum -= sir[3];

            if (x == 0) {
                vmin[y] = Math.min(y + r1, hm) * w;
            }
            p = x + vmin[y];


            sir[0] = r[p];
            sir[1] = g[p];
            sir[2] = b[p];
            sir[3] = a[p];

            rinsum += sir[0];
            ginsum += sir[1];
            binsum += sir[2];
            ainsum += sir[3];

            rsum += rinsum;
            gsum += ginsum;
            bsum += binsum;
            asum += ainsum;

            stackpointer = (stackpointer + 1) % div;
            sir = stack[stackpointer];

            routsum += sir[0];
            goutsum += sir[1];
            boutsum += sir[2];
            aoutsum += sir[3];

            rinsum -= sir[0];
            ginsum -= sir[1];
            binsum -= sir[2];
            ainsum -= sir[3];

            yi += w;
        }
    }

    Log.e("pix", w + " " + h + " " + pix.length);
    bitmap.setPixels(pix, 0, w, 0, 0, w, h);

    return (bitmap);
}

Custom CSS Scrollbar for Firefox

Since Firefox 64, is possible to use new specs for a simple Scrollbar styling (not as complete as in Chrome with vendor prefixes).

In this example is possible to see a solution that combine different rules to address both Firefox and Chrome with a similar (not equal) final result (example use your original Chrome rules):

The key rules are:

For Firefox

.scroller {
  overflow-y: scroll;
  scrollbar-color: #0A4C95 #C2D2E4;
}

For Chrome

.scroller::-webkit-scrollbar {
    width: 15px;
    height: 15px;
}

.scroller::-webkit-scrollbar-track-piece  {
    background-color: #C2D2E4;
}

.scroller::-webkit-scrollbar-thumb:vertical {
    height: 30px;
    background-color: #0A4C95;
}

Please note that respect to your solution, is possible to use also simpler Chrome rules as the following:

.scroller::-webkit-scrollbar-track  {
    background-color: #C2D2E4;
}

.scroller::-webkit-scrollbar-thumb {
    height: 30px;
    background-color: #0A4C95;
}

Finally, in order to hide arrows in scrollbars also in Firefox, currently is necessary to set it as "thin" with the following rule scrollbar-width: thin;

Is it possible to create a 'link to a folder' in a SharePoint document library?

The simplest way is to use the following pattern:

http://[server]/[site]/[ListName]/[Folder]/[SubFolder]

To place a shortcut to a document library:

  1. Upload it as *.url file. However, by default, this file type is not allowed.
  2. Go to you Document Library settings > Advanced Settings > Allow management of content types. Add the "Link to document" content type to a document library and paste the link

Selected tab's color in Bottom Navigation View

If you want to change icons' and texts' colors programmatically:

ColorStateList iconsColorStates = new ColorStateList(
            new int[][]{
                    new int[]{-android.R.attr.state_checked},
                    new int[]{android.R.attr.state_checked}
            },
            new int[]{
                    Color.parseColor("#123456"),
                    Color.parseColor("#654321")
            });

    ColorStateList textColorStates = new ColorStateList(
            new int[][]{
                    new int[]{-android.R.attr.state_checked},
                    new int[]{android.R.attr.state_checked}
            },
            new int[]{
                    Color.parseColor("#123456"),
                    Color.parseColor("#654321")
            });

    navigation.setItemIconTintList(iconsColorStates);
    navigation.setItemTextColor(textColorStates);

Show "Open File" Dialog

My comments on Renaud Bompuis's answer messed up.

Actually, you can use late binding, and the reference to the 11.0 object library is not required.

The following code will work without any references:

 Dim f    As Object 
 Set f = Application.FileDialog(3) 
 f.AllowMultiSelect = True 
 f.Show 

 MsgBox "file choosen = " & f.SelectedItems.Count 

Note that the above works well in the runtime also.

org.hibernate.QueryException: could not resolve property: filename

Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity).

Make sure you refer to the property as fileName in the Criteria query, not filename.

Specifically, Hibernate will call the getter method of the filename property when executing that Criteria query, so it will look for a method called getFilename(). But the property is called FileName and the getter getFileName().

So, change the projection like so:

criteria.setProjection(Projections.property("fileName"));

"’" showing on page instead of " ' "

If someone gets this error on WordPress website, you need to change wp-config db charset:

define('DB_CHARSET', 'utf8mb4_unicode_ci');

instead of:

define('DB_CHARSET', 'utf8mb4');

Declare and initialize a Dictionary in Typescript

Here is a more general Dictionary implementation inspired by this from @dmck

    interface IDictionary<T> {
      add(key: string, value: T): void;
      remove(key: string): void;
      containsKey(key: string): boolean;
      keys(): string[];
      values(): T[];
    }

    class Dictionary<T> implements IDictionary<T> {

      _keys: string[] = [];
      _values: T[] = [];

      constructor(init?: { key: string; value: T; }[]) {
        if (init) {
          for (var x = 0; x < init.length; x++) {
            this[init[x].key] = init[x].value;
            this._keys.push(init[x].key);
            this._values.push(init[x].value);
          }
        }
      }

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

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

        delete this[key];
      }

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

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

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

        return true;
      }

      toLookup(): IDictionary<T> {
        return this;
      }
    }

How do I declare and initialize an array in Java?

I find it is helpful if you understand each part:

Type[] name = new Type[5];

Type[] is the type of the variable called name ("name" is called the identifier). The literal "Type" is the base type, and the brackets mean this is the array type of that base. Array types are in turn types of their own, which allows you to make multidimensional arrays like Type[][] (the array type of Type[]). The keyword new says to allocate memory for the new array. The number between the bracket says how large the new array will be and how much memory to allocate. For instance, if Java knows that the base type Type takes 32 bytes, and you want an array of size 5, it needs to internally allocate 32 * 5 = 160 bytes.

You can also create arrays with the values already there, such as

int[] name = {1, 2, 3, 4, 5};

which not only creates the empty space but fills it with those values. Java can tell that the primitives are integers and that there are 5 of them, so the size of the array can be determined implicitly.

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

You can always just export the registry, change the setting, then export the registry again and do a diff.

String, StringBuffer, and StringBuilder

Difference between String and the other two classes is that String is immutable and the other two are mutable classes.

But why we have two classes for same purpose?

Reason is that StringBuffer is Thread safe and StringBuilder is not. StringBuilder is a new class on StringBuffer Api and it was introduced in JDK5 and is always recommended if you are working in a Single threaded environment as it is much Faster

For complete Details you can read http://www.codingeek.com/java/stringbuilder-and-stringbuffer-a-way-to-create-mutable-strings-in-java/

Java Singleton and Synchronization

What is the best way to implement Singleton in Java, in a multithreaded environment?

Refer to this post for best way to implement Singleton.

What is an efficient way to implement a singleton pattern in Java?

What happens when multiple threads try to access getInstance() method at the same time?

It depends on the way you have implemented the method.If you use double locking without volatile variable, you may get partially constructed Singleton object.

Refer to this question for more details:

Why is volatile used in this example of double checked locking

Can we make singleton's getInstance() synchronized?

Is synchronization really needed, when using Singleton classes?

Not required if you implement the Singleton in below ways

  1. static intitalization
  2. enum
  3. LazyInitalaization with Initialization-on-demand_holder_idiom

Refer to this question fore more details

Java Singleton Design Pattern : Questions

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

GCM with PHP (Google Cloud Messaging)

Also you can try this piece of code, source:

<?php
    define("GOOGLE_API_KEY", "AIzaSyCJiVkatisdQ44rEM353PFGbia29mBVscA");
    define("GOOGLE_GCM_URL", "https://android.googleapis.com/gcm/send");

    function send_gcm_notify($reg_id, $message) {
        $fields = array(
            'registration_ids'  => array( $reg_id ),
            'data'              => array( "message" => $message ),
        );

        $headers = array(
            'Authorization: key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, GOOGLE_GCM_URL);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

        $result = curl_exec($ch);
        if ($result === FALSE) {
            die('Problem occurred: ' . curl_error($ch));
        }

        curl_close($ch);
        echo $result;
    }

    $reg_id = "APA91bHuSGES.....nn5pWrrSz0dV63pg";
    $msg = "Google Cloud Messaging working well";

    send_gcm_notify($reg_id, $msg);

Java: How to Indent XML Generated by Transformer

I used the Xerces (Apache) library instead of messing with Transformer. Once you add the library add the code below.

OutputFormat format = new OutputFormat(document);
format.setLineWidth(65);
format.setIndenting(true);
format.setIndent(2);
Writer outxml = new FileWriter(new File("out.xml"));
XMLSerializer serializer = new XMLSerializer(outxml, format);
serializer.serialize(document);

In VBA get rid of the case sensitivity when comparing words?

There is a statement you can issue at the module level:

Option Compare Text

This makes all "text comparisons" case insensitive. This means the following code will show the message "this is true":

Option Compare Text

Sub testCase()
  If "UPPERcase" = "upperCASE" Then
    MsgBox "this is true: option Compare Text has been set!"
  End If
End Sub

See for example http://www.ozgrid.com/VBA/vba-case-sensitive.htm . I'm not sure it will completely solve the problem for all instances (such as the Application.Match function) but it will take care of all the if a=b statements. As for Application.Match - you may want to convert the arguments to either upper case or lower case using the LCase function.

With android studio no jvm found, JAVA_HOME has been set

Though, the question is asked long back, I see this same issue recently after installing Android Studio 2.1.0v, and JDK 7.80 on my PC Windows 10, 32 bit OS. I got this error.

No JVM installation found. Please install a 32 bit JDK. If you already have a JDK installed define a JAVA_HOME variable in Computer > System Properties > System Settings > Environment Variables.

I tried different ways to fix this nothing worked. But As per System Requirements in this Android developer website link.

Its solved after installing JDK 8(jdk-8u101-windows-i586.exe) JDK download site link.

Hope it helps somebody.

Delete a closed pull request from GitHub

This is the reply I received from Github when I asked them to delete a pull request:

"Thanks for getting in touch! Pull requests can't be deleted through the UI at the moment and we'll only delete pull requests when they contain sensitive information like passwords or other credentials."

Create a new Ruby on Rails application using MySQL instead of SQLite

rails new <project_name> -d mysql

OR

rails new projectname

Changes in config/database.yml

development:
  adapter: mysql2
  database: db_name_name
  username: root
  password:
  host: localhost
  socket: /tmp/mysql.sock

Setting action for back button in navigation controller

For a form that requires user input like this, I would recommend invoking it as a "modal" instead of part of your navigation stack. That way they have to take care of business on the form, then you can validate it and dismiss it using a custom button. You can even design a nav bar that looks the same as the rest of your app but gives you more control.

Border around specific rows in a table?

How about tr {outline: thin solid black;}? Works for me on tr or tbody elements, and appears to be compatible with the most browsers, including IE 8+ but not before.

how to create insert new nodes in JsonNode?

I've recently found even more interesting way to create any ValueNode or ContainerNode (Jackson v2.3).

ObjectNode node = JsonNodeFactory.instance.objectNode();

How to pass variable number of arguments to a PHP function

For those looking for a way to do this with $object->method:

call_user_func_array(array($object, 'method_name'), $array);

I was successful with this in a construct function that calls a variable method_name with variable parameters.

MySQL - ERROR 1045 - Access denied

If you actually have set a root password and you've just lost/forgotten it:

  1. Stop MySQL
  2. Restart it manually with the skip-grant-tables option: mysqld_safe --skip-grant-tables

  3. Now, open a new terminal window and run the MySQL client: mysql -u root

  4. Reset the root password manually with this MySQL command: UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root'; If you are using MySQL 5.7 (check using mysql --version in the Terminal) then the command is:

    UPDATE mysql.user SET authentication_string=PASSWORD('password')  WHERE  User='root';
    
  5. Flush the privileges with this MySQL command: FLUSH PRIVILEGES;

From http://www.tech-faq.com/reset-mysql-password.shtml

(Maybe this isn't what you need, Abs, but I figure it could be useful for people stumbling across this question in the future)

Execute Insert command and return inserted Id in Sql

Change the query to

"INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) VALUES(@na,@occ); SELECT SCOPE_IDENTITY()"

This will return the last inserted ID which you can then get with ExecuteScalar

On design patterns: When should I use the singleton?

A Singleton candidate must satisfy three requirements:

  • controls concurrent access to a shared resource.
  • access to the resource will be requested from multiple, disparate parts of the system.
  • there can be only one object.

If your proposed Singleton has only one or two of these requirements, a redesign is almost always the correct option.

For example, a printer spooler is unlikely to be called from more than one place (the Print menu), so you can use mutexes to solve the concurrent access problem.

A simple logger is the most obvious example of a possibly-valid Singleton, but this can change with more complex logging schemes.

ASP.net vs PHP (What to choose)

You can have great success and great performance either way. MSDN runs off of ASP.NET so you know it can perform well. PHP runs a lot of the top websites in the world. The same can be said of the databases as well. You really need to choose based upon your skills, the skills of your team, possible specific features that you need/want that one does better than the other, and even the servers that you want to run this site.

If I were building it, I would lean towards PHP because probably everything you want to do has been done before (with code examples how) and because hosting is so much easier to get (and cheaper because you don't have the licensing issues to deal with compared to Windows hosting). For the same reason, I would choose MySQL as well. It is a great database platform and the price is right.

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

Just default the variable to the expected type:

(number=1) => ...
(number=1.0) => ...
(string='str') ...

How do I add indices to MySQL tables?

It's worth noting that multiple field indexes can drastically improve your query performance. So in the above example we assume ProductID is the only field to lookup but were the query to say ProductID = 1 AND Category = 7 then a multiple column index helps. This is achieved with the following:

ALTER TABLE `table` ADD INDEX `index_name` (`col1`,`col2`)

Additionally the index should match the order of the query fields. In my extended example the index should be (ProductID,Category) not the other way around.

How to use Servlets and Ajax?

Indeed, the keyword is "ajax": Asynchronous JavaScript and XML. However, last years it's more than often Asynchronous JavaScript and JSON. Basically, you let JS execute an asynchronous HTTP request and update the HTML DOM tree based on the response data.

Since it's pretty a tedious work to make it to work across all browsers (especially Internet Explorer versus others), there are plenty of JavaScript libraries out which simplifies this in single functions and covers as many as possible browser-specific bugs/quirks under the hoods, such as jQuery, Prototype, Mootools. Since jQuery is most popular these days, I'll use it in the below examples.

Kickoff example returning String as plain text

Create a /some.jsp like below (note: the code snippets in this answer doesn't expect the JSP file being placed in a subfolder, if you do so, alter servlet URL accordingly from "someservlet" to "${pageContext.request.contextPath}/someservlet"; it's merely omitted from the code snippets for brevity):

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>SO question 4112686</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).on("click", "#somebutton", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
                $.get("someservlet", function(responseText) {   // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response text...
                    $("#somediv").text(responseText);           // Locate HTML DOM element with ID "somediv" and set its text content with the response text.
                });
            });
        </script>
    </head>
    <body>
        <button id="somebutton">press here</button>
        <div id="somediv"></div>
    </body>
</html>

Create a servlet with a doGet() method which look like this:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String text = "some text";

    response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
    response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
    response.getWriter().write(text);       // Write response body.
}

Map this servlet on an URL pattern of /someservlet or /someservlet/* as below (obviously, the URL pattern is free to your choice, but you'd need to alter the someservlet URL in JS code examples over all place accordingly):

package com.example;

@WebServlet("/someservlet/*")
public class SomeServlet extends HttpServlet {
    // ...
}

Or, when you're not on a Servlet 3.0 compatible container yet (Tomcat 7, Glassfish 3, JBoss AS 6, etc or newer), then map it in web.xml the old fashioned way (see also our Servlets wiki page):

<servlet>
    <servlet-name>someservlet</servlet-name>
    <servlet-class>com.example.SomeServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>someservlet</servlet-name>
    <url-pattern>/someservlet/*</url-pattern>
</servlet-mapping>

Now open the http://localhost:8080/context/test.jsp in the browser and press the button. You'll see that the content of the div get updated with the servlet response.

Returning List<String> as JSON

With JSON instead of plaintext as response format you can even get some steps further. It allows for more dynamics. First, you'd like to have a tool to convert between Java objects and JSON strings. There are plenty of them as well (see the bottom of this page for an overview). My personal favourite is Google Gson. Download and put its JAR file in /WEB-INF/lib folder of your webapplication.

Here's an example which displays List<String> as <ul><li>. The servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<String> list = new ArrayList<>();
    list.add("item1");
    list.add("item2");
    list.add("item3");
    String json = new Gson().toJson(list);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

The JS code:

$(document).on("click", "#somebutton", function() {  // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {    // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $ul = $("<ul>").appendTo($("#somediv")); // Create HTML <ul> element and append it to HTML DOM element with ID "somediv".
        $.each(responseJson, function(index, item) { // Iterate over the JSON array.
            $("<li>").text(item).appendTo($ul);      // Create HTML <li> element, set its text content with currently iterated item and append it to the <ul>.
        });
    });
});

Do note that jQuery automatically parses the response as JSON and gives you directly a JSON object (responseJson) as function argument when you set the response content type to application/json. If you forget to set it or rely on a default of text/plain or text/html, then the responseJson argument wouldn't give you a JSON object, but a plain vanilla string and you'd need to manually fiddle around with JSON.parse() afterwards, which is thus totally unnecessary if you set the content type right in first place.

Returning Map<String, String> as JSON

Here's another example which displays Map<String, String> as <option>:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Map<String, String> options = new LinkedHashMap<>();
    options.put("value1", "label1");
    options.put("value2", "label2");
    options.put("value3", "label3");
    String json = new Gson().toJson(options);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

And the JSP:

$(document).on("click", "#somebutton", function() {               // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {                 // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $select = $("#someselect");                           // Locate HTML DOM element with ID "someselect".
        $select.find("option").remove();                          // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
        $.each(responseJson, function(key, value) {               // Iterate over the JSON object.
            $("<option>").val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
        });
    });
});

with

<select id="someselect"></select>

Returning List<Entity> as JSON

Here's an example which displays List<Product> in a <table> where the Product class has the properties Long id, String name and BigDecimal price. The servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<Product> products = someProductService.list();
    String json = new Gson().toJson(products);

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

The JS code:

$(document).on("click", "#somebutton", function() {        // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseJson) {          // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
        var $table = $("<table>").appendTo($("#somediv")); // Create HTML <table> element and append it to HTML DOM element with ID "somediv".
        $.each(responseJson, function(index, product) {    // Iterate over the JSON array.
            $("<tr>").appendTo($table)                     // Create HTML <tr> element, set its text content with currently iterated item and append it to the <table>.
                .append($("<td>").text(product.id))        // Create HTML <td> element, set its text content with id of currently iterated product and append it to the <tr>.
                .append($("<td>").text(product.name))      // Create HTML <td> element, set its text content with name of currently iterated product and append it to the <tr>.
                .append($("<td>").text(product.price));    // Create HTML <td> element, set its text content with price of currently iterated product and append it to the <tr>.
        });
    });
});

Returning List<Entity> as XML

Here's an example which does effectively the same as previous example, but then with XML instead of JSON. When using JSP as XML output generator you'll see that it's less tedious to code the table and all. JSTL is this way much more helpful as you can actually use it to iterate over the results and perform server side data formatting. The servlet:

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<Product> products = someProductService.list();

    request.setAttribute("products", products);
    request.getRequestDispatcher("/WEB-INF/xml/products.jsp").forward(request, response);
}

The JSP code (note: if you put the <table> in a <jsp:include>, it may be reusable elsewhere in a non-ajax response):

<?xml version="1.0" encoding="UTF-8"?>
<%@page contentType="application/xml" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<data>
    <table>
        <c:forEach items="${products}" var="product">
            <tr>
                <td>${product.id}</td>
                <td><c:out value="${product.name}" /></td>
                <td><fmt:formatNumber value="${product.price}" type="currency" currencyCode="USD" /></td>
            </tr>
        </c:forEach>
    </table>
</data>

The JS code:

$(document).on("click", "#somebutton", function() {             // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
    $.get("someservlet", function(responseXml) {                // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response XML...
        $("#somediv").html($(responseXml).find("data").html()); // Parse XML, find <data> element and append its HTML to HTML DOM element with ID "somediv".
    });
});

You'll by now probably realize why XML is so much more powerful than JSON for the particular purpose of updating a HTML document using Ajax. JSON is funny, but after all generally only useful for so-called "public web services". MVC frameworks like JSF use XML under the covers for their ajax magic.

Ajaxifying an existing form

You can use jQuery $.serialize() to easily ajaxify existing POST forms without fiddling around with collecting and passing the individual form input parameters. Assuming an existing form which works perfectly fine without JavaScript/jQuery (and thus degrades gracefully when enduser has JavaScript disabled):

<form id="someform" action="someservlet" method="post">
    <input type="text" name="foo" />
    <input type="text" name="bar" />
    <input type="text" name="baz" />
    <input type="submit" name="submit" value="Submit" />
</form>

You can progressively enhance it with ajax as below:

$(document).on("submit", "#someform", function(event) {
    var $form = $(this);

    $.post($form.attr("action"), $form.serialize(), function(response) {
        // ...
    });

    event.preventDefault(); // Important! Prevents submitting the form.
});

You can in the servlet distinguish between normal requests and ajax requests as below:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String foo = request.getParameter("foo");
    String bar = request.getParameter("bar");
    String baz = request.getParameter("baz");

    boolean ajax = "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));

    // ...

    if (ajax) {
        // Handle ajax (JSON or XML) response.
    } else {
        // Handle regular (JSP) response.
    }
}

The jQuery Form plugin does less or more the same as above jQuery example, but it has additional transparent support for multipart/form-data forms as required by file uploads.

Manually sending request parameters to servlet

If you don't have a form at all, but just wanted to interact with the servlet "in the background" whereby you'd like to POST some data, then you can use jQuery $.param() to easily convert a JSON object to an URL-encoded query string.

var params = {
    foo: "fooValue",
    bar: "barValue",
    baz: "bazValue"
};

$.post("someservlet", $.param(params), function(response) {
    // ...
});

The same doPost() method as shown here above can be reused. Do note that above syntax also works with $.get() in jQuery and doGet() in servlet.

Manually sending JSON object to servlet

If you however intend to send the JSON object as a whole instead of as individual request parameters for some reason, then you'd need to serialize it to a string using JSON.stringify() (not part of jQuery) and instruct jQuery to set request content type to application/json instead of (default) application/x-www-form-urlencoded. This can't be done via $.post() convenience function, but needs to be done via $.ajax() as below.

var data = {
    foo: "fooValue",
    bar: "barValue",
    baz: "bazValue"
};

$.ajax({
    type: "POST",
    url: "someservlet",
    contentType: "application/json", // NOT dataType!
    data: JSON.stringify(data),
    success: function(response) {
        // ...
    }
});

Do note that a lot of starters mix contentType with dataType. The contentType represents the type of the request body. The dataType represents the (expected) type of the response body, which is usually unnecessary as jQuery already autodetects it based on response's Content-Type header.

Then, in order to process the JSON object in the servlet which isn't being sent as individual request parameters but as a whole JSON string the above way, you only need to manually parse the request body using a JSON tool instead of using getParameter() the usual way. Namely, servlets don't support application/json formatted requests, but only application/x-www-form-urlencoded or multipart/form-data formatted requests. Gson also supports parsing a JSON string into a JSON object.

JsonObject data = new Gson().fromJson(request.getReader(), JsonObject.class);
String foo = data.get("foo").getAsString();
String bar = data.get("bar").getAsString();
String baz = data.get("baz").getAsString();
// ...

Do note that this all is more clumsy than just using $.param(). Normally, you want to use JSON.stringify() only if the target service is e.g. a JAX-RS (RESTful) service which is for some reason only capable of consuming JSON strings and not regular request parameters.

Sending a redirect from servlet

Important to realize and understand is that any sendRedirect() and forward() call by the servlet on an ajax request would only forward or redirect the ajax request itself and not the main document/window where the ajax request originated. JavaScript/jQuery would in such case only retrieve the redirected/forwarded response as responseText variable in the callback function. If it represents a whole HTML page and not an ajax-specific XML or JSON response, then all you could do is to replace the current document with it.

document.open();
document.write(responseText);
document.close();

Note that this doesn't change the URL as enduser sees in browser's address bar. So there are issues with bookmarkability. Therefore, it's much better to just return an "instruction" for JavaScript/jQuery to perform a redirect instead of returning the whole content of the redirected page. E.g. by returning a boolean, or an URL.

String redirectURL = "http://example.com";

Map<String, String> data = new HashMap<>();
data.put("redirect", redirectURL);
String json = new Gson().toJson(data);

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
function(responseJson) {
    if (responseJson.redirect) {
        window.location = responseJson.redirect;
        return;
    }

    // ...
}

See also:

How to count days between two dates in PHP?

Here is the raw way to do it

$startTimeStamp = strtotime("2011/07/01");
$endTimeStamp = strtotime("2011/07/17");

$timeDiff = abs($endTimeStamp - $startTimeStamp);

$numberDays = $timeDiff/86400;  // 86400 seconds in one day

// and you might want to convert to integer
$numberDays = intval($numberDays);

How to set and reference a variable in a Jenkinsfile

A complete example for scripted pipepline:

       stage('Build'){
            withEnv(["GOPATH=/ws","PATH=/ws/bin:${env.PATH}"]) {
                sh 'bash build.sh'
            }
        }

How to add a JAR in NetBeans

Right click 'libraries' in the project list, then click add.

CSV file written with Python has blank lines between each row

with open(destPath+'\\'+csvXML, 'a+') as csvFile:
    writer = csv.writer(csvFile, delimiter=';', lineterminator='\r')
    writer.writerows(xmlList)

The "lineterminator='\r'" permit to pass to next row, without empty row between two.

Create a custom View by inflating a layout?

In practice, I have found that you need to be a bit careful, especially if you are using a bit of xml repeatedly. Suppose, for example, that you have a table that you wish to create a table row for each entry in a list. You've set up some xml:

In my_table_row.xml:

<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android" 
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent" android:id="@+id/myTableRow">
    <ImageButton android:src="@android:drawable/ic_menu_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/rowButton"/>
    <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:text="TextView" android:id="@+id/rowText"></TextView>
</TableRow>

Then you want to create it once per row with some code. It assume that you have defined a parent TableLayout myTable to attach the Rows to.

for (int i=0; i<numRows; i++) {
    /*
     * 1. Make the row and attach it to myTable. For some reason this doesn't seem
     * to return the TableRow as you might expect from the xml, so you need to
     * receive the View it returns and then find the TableRow and other items, as
     * per step 2.
     */
    LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v =  inflater.inflate(R.layout.my_table_row, myTable, true);

    // 2. Get all the things that we need to refer to to alter in any way.
    TableRow    tr        = (TableRow)    v.findViewById(R.id.profileTableRow);
    ImageButton rowButton = (ImageButton) v.findViewById(R.id.rowButton);
    TextView    rowText   = (TextView)    v.findViewById(R.id.rowText);

    // 3. Configure them out as you need to
    rowText.setText("Text for this row");
    rowButton.setId(i); // So that when it is clicked we know which one has been clicked!
    rowButton.setOnClickListener(this); // See note below ...           

    /*
     * To ensure that when finding views by id on the next time round this
     * loop (or later) gie lots of spurious, unique, ids.
     */
    rowText.setId(1000+i);
    tr.setId(3000+i);
}

For a clear simple example on handling rowButton.setOnClickListener(this), see Onclicklistener for a programatically created button.

Add text at the end of each line

If you'd like to add text at the end of each line in-place (in the same file), you can use -i parameter, for example:

sed -i'.bak' 's/$/:80/' foo.txt

However -i option is non-standard Unix extension and may not be available on all operating systems.

So you can consider using ex (which is equivalent to vi -e/vim -e):

ex +"%s/$/:80/g" -cwq foo.txt

which will add :80 to each line, but sometimes it can append it to blank lines.

So better method is to check if the line actually contain any number, and then append it, for example:

ex  +"g/[0-9]/s/$/:80/g" -cwq foo.txt

If the file has more complex format, consider using proper regex, instead of [0-9].