Programs & Examples On #Mocha.js

Mocha can refer to: (1) A feature-rich JavaScript test framework running on Node.js and the browser; (2) A Ruby library for mocking and stubbing with built-in support for support for MiniTest and Test::Unit.

How to increase timeout for a single test case in mocha

You might also think about taking a different approach, and replacing the call to the network resource with a stub or mock object. Using Sinon, you can decouple the app from the network service, focusing your development efforts.

How do you install and run Mocha, the Node.js testing module? Getting "mocha: command not found" after install

since npm 5.2.0, there's a new command "npx" included with npm that makes this much simpler, if you run:

npx mocha <args>

Note: the optional args are forwarded to the command being executed (mocha in this case)

this will automatically pick the executable "mocha" command from your locally installed mocha (always add it as a dev dependency to ensure the correct one is always used by you and everyone else).

Be careful though that if you didn't install mocha, this command will automatically fetch and use latest version, which is great for some tools (like scaffolders for example), but might not be the most recommendable for certain dependencies where you might want to pin to a specific version.

You can read more on npx here


Now, if instead of invoking mocha directly, you want to define a custom npm script, an alias that might invoke other npm binaries...

you don't want your library tests to fail depending on the machine setup (mocha as global, global mocha version, etc), the way to use the local mocha that works cross-platform is:

node node_modules/.bin/mocha

npm puts aliases to all the binaries in your dependencies on that special folder. Finally, npm will add node_modules/.bin to the PATH automatically when running an npm script, so in your package.json you can do just:

"scripts": {
  "test": "mocha"
}

and invoke it with

npm test

How to run a single test with Mocha?

For those who are looking to run a single file but they cannot make it work, what worked for me was that I needed to wrap my test cases in a describe suite as below and then use the describe title e.g. 'My Test Description' as pattern.

describe('My Test Description', () => {
  it('test case 1', () => {
    // My test code
  })
  it('test case 2', () => {
  // My test code
  })
})

then run

yarn test -g "My Test Description"

or

npm run test -g "My Test Description"

How can I check that two objects have the same set of property names?

To compare two objects along with all attributes of it, I followed this code and it didn't require tostring() or json compar

_x000D_
_x000D_
if(user1.equals(user2))
{
console.log("Both are equal");
}
_x000D_
_x000D_
_x000D_

e.

Change default timeout for mocha

Adding this for completeness. If you (like me) use a script in your package.json file, just add the --timeout option to mocha:

"scripts": {
  "test": "mocha 'test/**/*.js' --timeout 10000",
  "test-debug": "mocha --debug 'test/**/*.js' --timeout 10000"
},

Then you can run npm run test to run your test suite with the timeout set to 10,000 milliseconds.

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

jus do this import { shallow, mount } from "enzyme";

const store = mockStore({
  startup: { complete: false }
});

describe("==== Testing App ======", () => {
  const setUpFn = props => {
    return mount(
      <Provider store={store}>
        <App />
      </Provider>
    );
  };

  let wrapper;
  beforeEach(() => {
    wrapper = setUpFn();
  });

How to specify test directory for mocha?

Edit : This option is deprecated : https://mochajs.org/#mochaopts


If you want to do it by still just running mocha on the command line, but wanted to run the tests in a folder ./server-tests instead of ./test, create a file at ./test/mocha.opts with just this in the file:

server-tests

If you wanted to run everything in that folder and subdirectories, put this into test/mocha.opts

server-tests
--recursive

mocha.opts are the arguments passed in via the command line, so making the first line just the directory you want to change the tests too will redirect from ./test/

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

What Mocha options are you using?

Maybe it is something to do with reporter (-R) or ui (-ui) being used?

console.log(msg);

works fine during my test runs, though sometimes mixed in a little goofy. Presumably due to the async nature of the test run.

Here are the options (mocha.opts) I'm using:

--require should
-R spec
--ui bdd

Hmm..just tested without any mocha.opts and console.log still works.

Mocha / Chai expect.to.throw not catching thrown errors

One other possible implementation, more cumbersome than the .bind() solution, but one that helps to make the point that expect() requires a function that provides a this context to the covered function, you can use a call(), e.g.,

expect(function() {model.get.call(model, 'z');}).to.throw('...');

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

I got this error when stubbing with sinon.

The fix is to use npm package sinon-as-promised when resolving or rejecting promises with stubs.

Instead of ...

sinon.stub(Database, 'connect').returns(Promise.reject( Error('oops') ))

Use ...

require('sinon-as-promised');
sinon.stub(Database, 'connect').rejects(Error('oops'));

There is also a resolves method (note the s on the end).

See http://clarkdave.net/2016/09/node-v6-6-and-asynchronously-handled-promise-rejections

chai test array equality doesn't work as expected

This is how to use chai to deeply test associative arrays.

I had an issue trying to assert that two associative arrays were equal. I know that these shouldn't really be used in javascript but I was writing unit tests around legacy code which returns a reference to an associative array. :-)

I did it by defining the variable as an object (not array) prior to my function call:

var myAssocArray = {};   // not []
var expectedAssocArray = {};  // not []

expectedAssocArray['myKey'] = 'something';
expectedAssocArray['differentKey'] = 'something else';

// legacy function which returns associate array reference
myFunction(myAssocArray);

assert.deepEqual(myAssocArray, expectedAssocArray,'compare two associative arrays');

Code coverage with Mocha

You need an additional library for code coverage, and you are going to be blown away by how powerful and easy istanbul is. Try the following, after you get your mocha tests to pass:

npm install nyc

Now, simply place the command nyc in front of your existing test command, for example:

{
  "scripts": {
    "test": "nyc mocha"
  }
}

In mocha testing while calling asynchronous function how to avoid the timeout Error: timeout of 2000ms exceeded

A little late but someone can use this in future...You can increase your test timeout by updating scripts in your package.json with the following:

"scripts": { "test": "test --timeout 10000" //Adjust to a value you need }

Run your tests using the command test

Regex match entire words only

If you are doing it in Notepad++

[\w]+ 

Would give you the entire word, and you can add parenthesis to get it as a group. Example: conv1 = Conv2D(64, (3, 3), activation=LeakyReLU(alpha=a), padding='valid', kernel_initializer='he_normal')(inputs). I would like to move LeakyReLU into its own line as a comment, and replace the current activation. In notepad++ this can be done using the follow find command:

([\w]+)( = .+)(LeakyReLU.alpha=a.)(.+)

and the replace command becomes:

\1\2'relu'\4 \n    # \1 = LeakyReLU\(alpha=a\)\(\1\)

The spaces is to keep the right formatting in my code. :)

Control the dashed border stroke length and distance between strokes

Stroke length depends on stroke width. You can increase length by increasing width and hide part of border by inner element.

EDIT: added pointer-events: none; thanks to benJ.

.thin {
    background: #F4FFF3;
    border: 2px dashed #3FA535;  
    position: relative;
}

.thin:after {
    content: '';
    position: absolute;
    left: -1px;
    top: -1px;
    right: -1px;
    bottom: -1px;
    border: 1px solid #F4FFF3;
    pointer-events: none;
}

https://jsfiddle.net/ksf9zoLh/

How do you make Vim unhighlight what you searched for?

I have this in my .vimrc:

nnoremap ; :set invhlsearch<CR>

This way, ; will toggle search highlighting. Normally, the ; key repeats the latest t/T/f/F command, but I never really used that functionality. I find this setting much more useful, because I can change search highlighting on and off very quickly and can easily get a sense of where my search results are, at a glance.

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

ADB error: cannot connect to daemon

I've finally solved a very similar issue!

In my case, the problem was that I had two different SDKs (one from Eclipse and the other from Android Studio), so I was trying to execute the ADB commands in the wrong one.

So it is important that you check the path you are using in your IDE and execute the commands on the same.

Android Studio don't generate R.java for my import project

I found my solution here. In short make sure not only the Eclipse plugin(if you are using eclipse) is updated. Also ensure that the Android SDK Tools, the SDK platform-tools and the SDK Build-tools are updated. After this restart your machine.

Show an image preview before upload

HTML5 comes with File API spec, which allows you to create applications that let the user interact with files locally; That means you can load files and render them in the browser without actually having to upload the files. Part of the File API is the FileReader interface which lets web applications asynchronously read the contents of files .

Here's a quick example that makes use of the FileReader class to read an image as DataURL and renders a thumbnail by setting the src attribute of an image tag to a data URL:

The html code:

<input type="file" id="files" />
<img id="image" />

The JavaScript code:

document.getElementById("files").onchange = function () {
    var reader = new FileReader();

    reader.onload = function (e) {
        // get loaded data and render thumbnail.
        document.getElementById("image").src = e.target.result;
    };

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

Here's a good article on using the File APIs in JavaScript.

The code snippet in the HTML example below filters out images from the user's selection and renders selected files into multiple thumbnail previews:

_x000D_
_x000D_
function handleFileSelect(evt) {_x000D_
    var files = evt.target.files;_x000D_
_x000D_
    // Loop through the FileList and render image files as thumbnails._x000D_
    for (var i = 0, f; f = files[i]; i++) {_x000D_
_x000D_
      // Only process image files._x000D_
      if (!f.type.match('image.*')) {_x000D_
        continue;_x000D_
      }_x000D_
_x000D_
      var reader = new FileReader();_x000D_
_x000D_
      // Closure to capture the file information._x000D_
      reader.onload = (function(theFile) {_x000D_
        return function(e) {_x000D_
          // Render thumbnail._x000D_
          var span = document.createElement('span');_x000D_
          span.innerHTML = _x000D_
          [_x000D_
            '<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', _x000D_
            e.target.result,_x000D_
            '" title="', escape(theFile.name), _x000D_
            '"/>'_x000D_
          ].join('');_x000D_
          _x000D_
          document.getElementById('list').insertBefore(span, null);_x000D_
        };_x000D_
      })(f);_x000D_
_x000D_
      // Read in the image file as a data URL._x000D_
      reader.readAsDataURL(f);_x000D_
    }_x000D_
  }_x000D_
_x000D_
  document.getElementById('files').addEventListener('change', handleFileSelect, false);
_x000D_
<input type="file" id="files" multiple />_x000D_
<output id="list"></output>
_x000D_
_x000D_
_x000D_

Auto-size dynamic text to fill fixed size container

I went with geekMonkey solution, but it's too slow. What he does, is he adjusts the font size to maximum (maxFontPixels) and then checks if it fits inside the container. else it reduces the font size by 1px and checks again. Why not simply check the previous container for the height and submit that value? (yes, I know why, but I now made a solution, that only works on the height and also has a min/max option)

Here is a much quicker solution:

var index_letters_resize;
(index_letters_resize = function() {
  $(".textfill").each(function() {
    var
      $this = $(this),
      height = Math.min( Math.max( parseInt( $this.height() ), 40 ), 150 );
    $this.find(".size-adjust").css({
      fontSize: height
    });
  });
}).call();

$(window).on('resize', function() {
  index_letters_resize();
);

and this would be the HTML:

<div class="textfill">
  <span class="size-adjust">adjusted element</span>
  other variable stuff that defines the container size
</div>

Again: this solution ONLY checks for the height of the container. That's why this function does not has to check, if the element fits inside. But I also implemented a min/max value (40min, 150max) so for me this works perfectly fine (and also works on window resize).

SELECT CONVERT(VARCHAR(10), GETDATE(), 110) what is the meaning of 110 here?

That number indicates Date and Time Styles

You need to look at CAST and CONVERT (Transact-SQL). Here you can find the meaning of all these Date and Time Styles.

Styles with century (e.g. 100, 101 etc) means year will come in yyyy format. While styles without century (e.g. 1,7,10) means year will come in yy format.

You can also refer to SQL Server Date Formats. Here you can find all date formats with examples.

Permanently adding a file path to sys.path in Python

This way worked for me:

adding the path that you like:

export PYTHONPATH=$PYTHONPATH:/path/you/want/to/add

checking: you can run 'export' cmd and check the output or you can check it using this cmd:

python -c "import sys; print(sys.path)"

cannot download, $GOPATH not set

I had to run an application as root (to open a webserver on port 80), this produced the error for me, because the sudo user has a different environment than the normal user, hence GOPATH was not set.

If someone else is having this problem, add -E to the command, this will preserve the user environment.

sudo -E go run main.go

For more infos see discussion here: Google Groups – GOPATH Problem

Create a date from day month and year with T-SQL

Or using just a single dateadd function:

DECLARE @day int, @month int, @year int
SELECT @day = 4, @month = 3, @year = 2011

SELECT dateadd(mm, (@year - 1900) * 12 + @month - 1 , @day - 1)

click command in selenium webdriver does not work

If you know for sure that the element is present, you could try this to simulate the click - if .Click() isn't working

driver.findElement(By.name("submit")).sendKeys(Keys.RETURN);

or

driver.findElement(By.name("submit")).sendKeys(Keys.ENTER);

What is the !! (not not) operator in JavaScript?

!! is similar to using the Boolean constructor, or arguably more like the Boolean function.

_x000D_
_x000D_
console.log(Boolean(null)); // Preffered over the Boolean object_x000D_
_x000D_
console.log(new Boolean(null).valueOf()); // Not recommended for coverting non-boolean values_x000D_
_x000D_
console.log(!!null); // A hacky way to omit calling the Boolean function, but essentially does the same thing. _x000D_
_x000D_
_x000D_
// The context you saw earlier (your example)_x000D_
var vertical;_x000D_
_x000D_
function Example(vertical)_x000D_
{_x000D_
        this.vertical = vertical !== undefined ? !!vertical : _x000D_
        this.vertical; _x000D_
        // Let's break it down: If vertical is strictly not undefined, return the boolean value of vertical and set it to this.vertical. If not, don't set a value for this.vertical (just ignore it and set it back to what it was before; in this case, nothing).   _x000D_
_x000D_
        return this.vertical;_x000D_
}_x000D_
_x000D_
console.log( "\n---------------------" )_x000D_
_x000D_
// vertical is currently undefined_x000D_
_x000D_
console.log(new Example(vertical).vertical); // The falsey or truthy value of this.vertical_x000D_
console.log(!!new Example(vertical).vertical); // Coerced value of this.vertical_x000D_
_x000D_
vertical = 12.5; // set vertical to 12.5, a truthy value._x000D_
console.log(new Example(vertical).vertical); // The falsey or truthy value of this.vertical which happens to be true anyway_x000D_
console.log(!!new Example(vertical).vertical); // Coerced value of this.vertical_x000D_
_x000D_
vertical = -0; // set vertical to -0, a falsey value._x000D_
console.log(new Example(vertical).vertical); // The falsey or truthy value of this.vertical which happens to be false either way_x000D_
console.log(!!new Example(vertical).vertical); // Coerced value of this.vertical
_x000D_
_x000D_
_x000D_

Falsey values in javascript coerce to false, and truthy values coerce to true. Falsey and truthy values can also be used in if statements and will essentially "map" to their corresponding boolean value. However, you will probably not find yourself having to use proper boolean values often, as they mostly differ in output (return values).

Although this may seem similar to casting, realistically this is likely a mere coincidence and is not 'built' or purposely made for and like a boolean cast. So let's not call it that.


Why and how it works

To be concise, it looks something like this: ! ( !null ). Whereas, null is falsey, so !null would be true. Then !true would be false and it would essentially invert back to what it was before, except this time as a proper boolean value (or even vice versa with truthy values like {} or 1).


Going back to your example

Overall, the context that you saw simply adjusts this.vertical depending on whether or not vertical is defined, and if so; it will be set to the resulting boolean value of vertical, otherwise it will not change. In other words, if vertical is defined; this.vertical will be set to the boolean value of it, otherwise, it will stay the same. I guess that in itself is an example of how you would use !!, and what it does.


Vertical I/O Example

Run this example and fiddle around with the vertical value in the input. See what the result coerces to so that you can fully understand your context's code. In the input, enter any valid javascript value. Remember to include the quotations if you are testing out a string. Don't mind the CSS and HTML code too much, simply run this snippet and play around with it. However, you might want to take a look at the non-DOM-related javascript code though (the use of the Example constructor and the vertical variable).

_x000D_
_x000D_
var vertical = document.getElementById("vertical");_x000D_
var p = document.getElementById("result");_x000D_
_x000D_
function Example(vertical)_x000D_
{_x000D_
        this.vertical = vertical !== undefined ? !!vertical : _x000D_
        this.vertical;   _x000D_
_x000D_
        return this.vertical;_x000D_
}_x000D_
_x000D_
document.getElementById("run").onclick = function()_x000D_
{_x000D_
_x000D_
  p.innerHTML = !!( new Example(eval(vertical.value)).vertical );_x000D_
  _x000D_
}
_x000D_
input_x000D_
{_x000D_
  text-align: center;_x000D_
  width: 5em;_x000D_
} _x000D_
_x000D_
button _x000D_
{_x000D_
  margin: 15.5px;_x000D_
  width: 14em;_x000D_
  height: 3.4em;_x000D_
  color: blue;_x000D_
}_x000D_
_x000D_
var _x000D_
{_x000D_
  color: purple;_x000D_
}_x000D_
_x000D_
p {_x000D_
  margin: 15px;_x000D_
}_x000D_
_x000D_
span.comment {_x000D_
  color: brown;_x000D_
}
_x000D_
<!--Vertical I/O Example-->_x000D_
<h4>Vertical Example</h4>_x000D_
<code id="code"><var class="var">var</var> vertical = <input type="text" id="vertical" maxlength="9" />; <span class="comment">// enter any valid javascript value</span></code>_x000D_
<br />_x000D_
<button id="run">Run</button>_x000D_
<p id="result">...</p>
_x000D_
_x000D_
_x000D_

Check if list<t> contains any of another list

Here is a sample to find if there are match elements in another list

List<int> nums1 = new List<int> { 2, 4, 6, 8, 10 };
List<int> nums2 = new List<int> { 1, 3, 6, 9, 12};

if (nums1.Any(x => nums2.Any(y => y == x)))
{
    Console.WriteLine("There are equal elements");
}
else
{
    Console.WriteLine("No Match Found!");
}

Available text color classes in Bootstrap

The text at the navigation bar is normally colored by using one of the two following css classes in the bootstrap.css file.

Firstly, in case of using a default navigation bar (the gray one), the .navbar-default class will be used and the text is colored as dark gray.

.navbar-default .navbar-text {
  color: #777;
}

The other is in case of using an inverse navigation bar (the black one), the text is colored as gray60.

.navbar-inverse .navbar-text {
  color: #999;
}

So, you can change its color as you wish. However, I would recommend you to use a separate css file to change it.

NOTE: you could also use the customizer provided by Twitter Bootstrap, in the Navbar section.

What is the difference between user and kernel modes in operating systems?

I'm going to take a stab in the dark and guess you're talking about Windows. In a nutshell, kernel mode has full access to hardware, but user mode doesn't. For instance, many if not most device drivers are written in kernel mode because they need to control finer details of their hardware.

See also this wikibook.

What is the difference between JavaScript and ECMAScript?

Existing answers paraphrase the main point quite well.

The main point is that ECMAScript is the bare abstract language, without any domain specific extensions, it's useless in itself. The specification defines only the language and the core objects of it.

While JavaScript and ActionScript and other dialects add the domain specific library to it, so you can use it for something meaningful.

There are many ECMAScript engines, some of them are open source, others are proprietary. You can link them into your program then add your native functions to the global object so your program becomes scriptable. Although most often they are used in browsers.

Using psql how do I list extensions installed in a database?

Additionally if you want to know which extensions are available on your server: SELECT * FROM pg_available_extensions

How do I unlock a SQLite database?

I found the documentation of the various states of locking in SQLite to be very helpful. Michael, if you can perform reads but can't perform writes to the database, that means that a process has gotten a RESERVED lock on your database but hasn't executed the write yet. If you're using SQLite3, there's a new lock called PENDING where no more processes are allowed to connect but existing connections can sill perform reads, so if this is the issue you should look at that instead.

The system cannot find the file specified in java

Generally, just stating the name of file inside the File constructor means that the file is located in the same directory as the java file. However, when using IDEs like NetBeans and Eclipse i.e. not the case you have to save the file in the project folder directory. So I think checking that will solve your problem.

Java 8 Streams FlatMap method example

Made up example

Imagine that you want to create the following sequence: 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 etc. (in other words: 1x1, 2x2, 3x3 etc.)

With flatMap it could look like:

IntStream sequence = IntStream.rangeClosed(1, 4)
                          .flatMap(i -> IntStream.iterate(i, identity()).limit(i));
sequence.forEach(System.out::println);

where:

  • IntStream.rangeClosed(1, 4) creates a stream of int from 1 to 4, inclusive
  • IntStream.iterate(i, identity()).limit(i) creates a stream of length i of int i - so applied to i = 4 it creates a stream: 4, 4, 4, 4
  • flatMap "flattens" the stream and "concatenates" it to the original stream

With Java < 8 you would need two nested loops:

List<Integer> list = new ArrayList<>();
for (int i = 1; i <= 4; i++) {
    for (int j = 0; j < i; j++) {
        list.add(i);
    }
}

Real world example

Let's say I have a List<TimeSeries> where each TimeSeries is essentially a Map<LocalDate, Double>. I want to get a list of all dates for which at least one of the time series has a value. flatMap to the rescue:

list.stream().parallel()
    .flatMap(ts -> ts.dates().stream()) // for each TS, stream dates and flatmap
    .distinct()                         // remove duplicates
    .sorted()                           // sort ascending
    .collect(toList());

Not only is it readable, but if you suddenly need to process 100k elements, simply adding parallel() will improve performance without you writing any concurrent code.

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

Leave out quotes when copying from cell

Possible problem in relation to answer from "user3616725":
Im on Windows 8.1 and there seems to be a problem with the linked VBA code from accepted answer from "user3616725":

Sub CopyCellContents()
 ' !!! IMPORTANT !!!:
 ' CREATE A REFERENCE IN THE VBE TO "Microsft Forms 2.0 Library" OR "Microsft Forms 2.0 Object Library"
 ' DO THIS BY (IN VBA EDITOR) CLICKING TOOLS -> REFERENCES & THEN TICKING "Microsoft Forms 2.0 Library" OR "Microsft Forms 2.0 Object Library"
 Dim objData As New DataObject
 Dim strTemp As String
 strTemp = ActiveCell.Value
 objData.SetText (strTemp)
 objData.PutInClipboard
End Sub

Details:
Running above code and pasting clipboard into a cell in Excel I get two symbols composed of squares with a question mark inside, like this: ??. Pasting into Notepad doesn't even show anything.

Solution:
After searching for quite some time I found another VBA script from user "Nepumuk" which makes use of the Windows API. Here's his code that finally worked for me:

Option Explicit

Private Declare Function OpenClipboard Lib "user32.dll" ( _
    ByVal hwnd As Long) As Long
Private Declare Function CloseClipboard Lib "user32.dll" () As Long
Private Declare Function EmptyClipboard Lib "user32.dll" () As Long
Private Declare Function SetClipboardData Lib "user32.dll" ( _
    ByVal wFormat As Long, _
    ByVal hMem As Long) As Long
Private Declare Function GlobalAlloc Lib "kernel32.dll" ( _
    ByVal wFlags As Long, _
    ByVal dwBytes As Long) As Long
Private Declare Function GlobalLock Lib "kernel32.dll" ( _
    ByVal hMem As Long) As Long
Private Declare Function GlobalUnlock Lib "kernel32.dll" ( _
    ByVal hMem As Long) As Long
Private Declare Function GlobalFree Lib "kernel32.dll" ( _
    ByVal hMem As Long) As Long
Private Declare Function lstrcpy Lib "kernel32.dll" ( _
    ByVal lpStr1 As Any, _
    ByVal lpStr2 As Any) As Long

Private Const CF_TEXT As Long = 1&

Private Const GMEM_MOVEABLE As Long = 2

Public Sub Beispiel()
    Call StringToClipboard("Hallo ...")
End Sub

Private Sub StringToClipboard(strText As String)
    Dim lngIdentifier As Long, lngPointer As Long
    lngIdentifier = GlobalAlloc(GMEM_MOVEABLE, Len(strText) + 1)
    lngPointer = GlobalLock(lngIdentifier)
    Call lstrcpy(ByVal lngPointer, strText)
    Call GlobalUnlock(lngIdentifier)
    Call OpenClipboard(0&)
    Call EmptyClipboard
    Call SetClipboardData(CF_TEXT, lngIdentifier)
    Call CloseClipboard
    Call GlobalFree(lngIdentifier)
End Sub

To use it the same way like the first VBA code from above, change the Sub "Beispiel()" from:

Public Sub Beispiel()
    Call StringToClipboard("Hallo ...")
End Sub

To:

Sub CopyCellContents()
    Call StringToClipboard(ActiveCell.Value)
End Sub

And run it via Excel macro menu like suggested from "user3616725" from accepted answer:

Back in Excel, go Tools>Macro>Macros and select the macro called "CopyCellContents" and then choose Options from the dialog. Here you can assign the macro to a shortcut key (eg like Ctrl+c for normal copy) - I used Ctrl+q.

Then, when you want to copy a single cell over to Notepad/wherever, just do Ctrl+q (or whatever you chose) and then do a Ctrl+v or Edit>Paste in your chosen destination.


Edit (21st of November in 2015):
@ comment from "dotctor":
No, this seriously is no new question! In my opinion it is a good addition for the accepted answer as my answer addresses problems that you can face when using the code from the accepted answer. If I would have more reputation, I would have created a comment.
@ comment from "Teepeemm":
Yes, you are right, answers beginning with title "Problem:" are misleading. Changed to: "Possible problem in relation to answer from "user3616725":". As a comment I certainly would have written much more compact.

Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?

The answer is no.

The main purpose of the hash is to scroll to a certain part of the page where you have defined a bookmark. e.g. Scroll to this Part when page loads.

The browse will scroll such that this line is the first visible content in the page, depending on how much content follows below the line.

Yes javascript can acces it, and then a simple ajax call will do the magic

Using moment.js to convert date to string "MM/dd/yyyy"

this also might be relevant to anyone using React -

install react-moment (npm i react-moment)

import Moment from 'react-moment'


<Moment format="MM/DD/YYYY">{yourTimeStamp}</Moment>

(or any other format you'd like)

How to read data from a file in Lua

You should use the I/O Library where you can find all functions at the io table and then use file:read to get the file content.

local open = io.open

local function read_file(path)
    local file = open(path, "rb") -- r read mode and b binary mode
    if not file then return nil end
    local content = file:read "*a" -- *a or *all reads the whole file
    file:close()
    return content
end

local fileContent = read_file("foo.html");
print (fileContent);

How to search for an element in an stl list?

What you can do and what you should do are different matters.

If the list is very short, or you are only ever going to call find once then use the linear approach above.

However linear-search is one of the biggest evils I find in slow code, and consider using an ordered collection (set or multiset if you allow duplicates). If you need to keep a list for other reasons eg using an LRU technique or you need to maintain the insertion order or some other order, create an index for it. You can actually do that using a std::set of the list iterators (or multiset) although you need to maintain this any time your list is modified.

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

You can solve the problem by checking if your date matches a REGEX pattern. If not, then NULL (or something else you prefer).

In my particular case it was necessary because I have >20 DATE columns saved as CHAR, so I don't know from which column the error is coming from.

Returning to your query:

1. Declare a REGEX pattern.
It is usually a very long string which will certainly pollute your code (you may want to reuse it as well).

define REGEX_DATE = "'your regex pattern goes here'"

Don't forget a single quote inside a double quote around your Regex :-)

A comprehensive thread about Regex date validation you'll find here.

2. Use it as the first CASE condition:

To use Regex validation in the SELECT statement, you cannot use REGEXP_LIKE (it's only valid in WHERE. It took me a long time to understand why my code was not working. So it's certainly worth a note.

Instead, use REGEXP_INSTR
For entries not found in the pattern (your case) use REGEXP_INSTR (variable, pattern) = 0 .

    DEFINE REGEX_DATE = "'your regex pattern goes here'"

    SELECT   c.contract_num,
         CASE
            WHEN REGEXP_INSTR(c.event_dt, &REGEX_DATE) = 0 THEN NULL
            WHEN   (  MAX (TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
                    - MIN (TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
                 / COUNT (c.event_occurrence) < 32
            THEN
              'Monthly'
            WHEN       (  MAX (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
                        - MIN (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
                     / COUNT (c.event_occurrence) >= 32
                 AND   (  MAX (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
                        - MIN (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
                     / COUNT (c.event_occurrence) < 91
            THEN
              'Quarterley'
            ELSE
              'Yearly'
         END
FROM     ps_ca_bp_events c
GROUP BY c.contract_num;

How to detect browser using angularjs?

you should use conditional comments

<!--[if IE 9]>
<script type="text/javascript">
    window.isIE9 = true;
</script>
<![endif]-->

You can then check for $window.isIE9 in your controllers.

How to pass form input value to php function

This is pretty basic, just put in the php file you want to use for processing in the element.

For example

<form action="process.php" method="post">

Then in process.php you would get the form values using $_POST['name of the variable]

Setting the correct encoding when piping stdout in Python

An arguable sanitized version of Craig McQueen's answer.

import sys, codecs
class EncodedOut:
    def __init__(self, enc):
        self.enc = enc
        self.stdout = sys.stdout
    def __enter__(self):
        if sys.stdout.encoding is None:
            w = codecs.getwriter(self.enc)
            sys.stdout = w(sys.stdout)
    def __exit__(self, exc_ty, exc_val, tb):
        sys.stdout = self.stdout

Usage:

with EncodedOut('utf-8'):
    print u'ÅÄÖåäö'

Deserialize JSON array(or list) in C#

Download Json.NET from here http://james.newtonking.com/projects/json-net.aspx

name deserializedName = JsonConvert.DeserializeObject<name>(jsonData);

How can I create tests in Android Studio?

As of now (studio 0.61) maintaining proper project structure is enough. No need to create separate test project as in eclipse (see below).

Tests structure

How to break out of a loop in Bash?

while true ; do
    ...
    if [ something ]; then
        break
    fi
done

Playing .mp3 and .wav in Java?

It's been a while since I used it, but JavaLayer is great for MP3 playback

Streaming Audio from A URL in Android using MediaPlayer?

I've had the same error as you have and it turned out that there was nothing wrong with the code. The problem was that the webserver was sending the wrong Content-Type header.

Try wireshark or something similar to see what content-type the webserver is sending.

Best TCP port number range for internal applications

Short answer: use an unassigned user port

Over achiever's answer - Select and deploy a resource discovery solution. Have the server select a private port dynamically. Have the clients use resource discovery.

The risk that that a server will fail because the port it wants to listen on is not available is real; at least it's happened to me. Another service or a client might get there first.

You can almost totally reduce the risk from a client by avoiding the private ports, which are dynamically handed out to clients.

The risk that from another service is minimal if you use a user port. An unassigned port's risk is only that another service happens to be configured (or dyamically) uses that port. But at least that's probably under your control.

The huge doc with all the port assignments, including User Ports, is here: http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt look for the token Unassigned.

Pass parameter from a batch file to a PowerShell script

Let's say you would like to pass the string Dev as a parameter, from your batch file:

powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 Dev"

put inside your powershell script head:

$w = $args[0]       # $w would be set to "Dev"

This if you want to use the built-in variable $args. Otherwise:

 powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 -Environment \"Dev\""

and inside your powershell script head:

param([string]$Environment)

This if you want a named parameter.

You might also be interested in returning the error level:

powershell -command "G:\Karan\PowerShell_Scripts\START_DEV.ps1 Dev; exit $LASTEXITCODE"

The error level will be available inside the batch file as %errorlevel%.

jQuery add blank option to top of list and make selected to existing dropdown

This worked:

$("#theSelectId").prepend("<option value='' selected='selected'></option>");

Firebug Output:

<select id="theSelectId">
  <option selected="selected" value=""/>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

You could also use .prependTo if you wanted to reverse the order:

?$("<option>", { value: '', selected: true }).prependTo("#theSelectId");???????????

how to get current month and year

Like this:

DateTime.Now.ToString("MMMM yyyy")

For more information, see DateTime Format Strings.

How to uncommit my last commit in Git

Just a note - if you're using ZSH and see the error

zsh: no matches found: HEAD^

You need to escape the ^

git reset --soft HEAD\^

jQuery adding 2 numbers from input fields

Ok so your code actually works but what you need to do is replace a and b in your click function with the jquery notation you used before the click. This will ensure you have the correct and most up to date values. so changing your click function to this should work:

$("submit").on("click", function(){
    var sum = $("#a").val().match(/\d+/) + $("#b").val().match(/\d+/);
    alert(sum);         
})

or inlined to:

$("submit").on("click", function(){
    alert($("#a").val().match(/\d+/) + $("#b").val().match(/\d+/));         
})

I'm getting favicon.ico error

I was getting the same fav icon error - 404 (Not Found). I used the following element in the <head> element of my index.html file and it fixed the error:

<link rel="icon" href="data:;base64,iVBORw0KGgo=">

<strong> vs. font-weight:bold & <em> vs. font-style:italic

The <em> element - from W3C (HTML5 reference)

YES! There is a clear difference.

The <em> element represents stress emphasis of its contents. The level of emphasis that a particular piece of content has is given by its number of ancestor <em> elements.

<strong>  =  important content
<em>      =  stress emphasis of its contents

The placement of emphasis changes the meaning of the sentence. The element thus forms an integral part of the content. The precise way in which emphasis is used in this way depends on the language.

Note!

  1. The <em> element also isnt intended to convey importance; for that purpose, the <strong> element is more appropriate.

  2. The <em> element isn't a generic "italics" element. Sometimes, text is intended to stand out from the rest of the paragraph, as if it was in a different mood or voice. For this, the i element is more appropriate.

Reference (examples): See W3C Reference

How to use python numpy.savetxt to write strings and float number to an ASCII file?

The currently accepted answer does not actually address the question, which asks how to save lists that contain both strings and float numbers. For completeness I provide a fully working example, which is based, with some modifications, on the link given in @joris comment.

import numpy as np

names  = np.array(['NAME_1', 'NAME_2', 'NAME_3'])
floats = np.array([ 0.1234 ,  0.5678 ,  0.9123 ])

ab = np.zeros(names.size, dtype=[('var1', 'U6'), ('var2', float)])
ab['var1'] = names
ab['var2'] = floats

np.savetxt('test.txt', ab, fmt="%10s %10.3f")

Update: This example also works properly in Python 3 by using the 'U6' Unicode string dtype, when creating the ab structured array, instead of the 'S6' byte string. The latter dtype would work in Python 2.7, but would write strings like b'NAME_1' in Python 3.

Select all child elements recursively in CSS

The rule is as following :

A B 

B as a descendant of A

A > B 

B as a child of A

So

div.dropdown *

and not

div.dropdown > *

Alter table to modify default value of column

ALTER TABLE *table_name*
MODIFY *column_name* DEFAULT *value*;

worked in Oracle

e.g:

ALTER TABLE MY_TABLE
MODIFY MY_COLUMN DEFAULT 1;

Plotting a python dict in order of key values

Simply pass the sorted items from the dictionary to the plot() function. concentration.items() returns a list of tuples where each tuple contains a key from the dictionary and its corresponding value.

You can take advantage of list unpacking (with *) to pass the sorted data directly to zip, and then again to pass it into plot():

import matplotlib.pyplot as plt

concentration = {
    0: 0.19849878712984576,
    5000: 0.093917341754771386,
    10000: 0.075060643507712022,
    20000: 0.06673074282575861,
    30000: 0.057119318961966224,
    50000: 0.046134834546203485,
    100000: 0.032495766396631424,
    200000: 0.018536317451599615,
    500000: 0.0059499290585381479}

plt.plot(*zip(*sorted(concentration.items())))
plt.show()

sorted() sorts tuples in the order of the tuple's items so you don't need to specify a key function because the tuples returned by dict.item() already begin with the key value.

How to abort a Task like aborting a Thread (Thread.Abort method)?

But can I abort a Task (in .Net 4.0) in the same way not by cancellation mechanism. I want to kill the Task immediately.

Other answerers have told you not to do it. But yes, you can do it. You can supply Thread.Abort() as the delegate to be called by the Task's cancellation mechanism. Here is how you could configure this:

class HardAborter
{
  public bool WasAborted { get; private set; }
  private CancellationTokenSource Canceller { get; set; }
  private Task<object> Worker { get; set; }

  public void Start(Func<object> DoFunc)
  {
    WasAborted = false;

    // start a task with a means to do a hard abort (unsafe!)
    Canceller = new CancellationTokenSource();

    Worker = Task.Factory.StartNew(() => 
      {
        try
        {
          // specify this thread's Abort() as the cancel delegate
          using (Canceller.Token.Register(Thread.CurrentThread.Abort))
          {
            return DoFunc();
          }
        }
        catch (ThreadAbortException)
        {
          WasAborted = true;
          return false;
        }
      }, Canceller.Token);
  }

  public void Abort()
  {
    Canceller.Cancel();
  }

}

disclaimer: don't do this.

Here is an example of what not to do:

 var doNotDoThis = new HardAborter();

 // start a thread writing to the console
 doNotDoThis.Start(() =>
    {
       while (true)
       {
          Thread.Sleep(100);
          Console.Write(".");
       }
       return null;
    });


 // wait a second to see some output and show the WasAborted value as false
 Thread.Sleep(1000);
 Console.WriteLine("WasAborted: " + doNotDoThis.WasAborted);

 // wait another second, abort, and print the time
 Thread.Sleep(1000);
 doNotDoThis.Abort();
 Console.WriteLine("Abort triggered at " + DateTime.Now);

 // wait until the abort finishes and print the time
 while (!doNotDoThis.WasAborted) { Thread.CurrentThread.Join(0); }
 Console.WriteLine("WasAborted: " + doNotDoThis.WasAborted + " at " + DateTime.Now);

 Console.ReadKey();

output from sample code

Task continuation on UI thread

Call the continuation with TaskScheduler.FromCurrentSynchronizationContext():

    Task UITask= task.ContinueWith(() =>
    {
     this.TextBlock1.Text = "Complete"; 
    }, TaskScheduler.FromCurrentSynchronizationContext());

This is suitable only if the current execution context is on the UI thread.

Make div 100% Width of Browser Window

There are new units that you can use:

vw - viewport width

vh - viewport height

#neo_main_container1
{
   width: 100%; //fallback
   width: 100vw;
}

Help / MDN

Opera Mini does not support this, but you can use it in all other modern browsers.

CanIUse

enter image description here

How do I correctly detect orientation change using Phonegap on iOS?

I've found this code to detect if the device is in landscape orientation and in this case add a splash page saying "change orientation to see the site". It's working on iOS, android and windows phones. I think that this is very useful since it's quite elegant and avoid to set a landscape view for the mobile site. The code is working very well. The only thing not completely satisfying is that if someone load the page being in landscape view the splash page doesn't appears.

<script>
(function() {
    'use strict';

    var isMobile = {
        Android: function() {
            return navigator.userAgent.match(/Android/i);
        },
        BlackBerry: function() {
            return navigator.userAgent.match(/BlackBerry/i);
        },
        iOS: function() {
            return navigator.userAgent.match(/iPhone|iPad|iPod/i);
        },
        Opera: function() {
            return navigator.userAgent.match(/Opera Mini/i);
        },
        Windows: function() {
            return navigator.userAgent.match(/IEMobile/i);
        },
        any: function() {
            return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
        }
    };
    if (isMobile.any()) {
        doOnOrientationChange();
        window.addEventListener('resize', doOnOrientationChange, 'false');
    }

    function doOnOrientationChange() {
        var a = document.getElementById('alert');
        var b = document.body;
        var w = b.offsetWidth;
        var h = b.offsetHeight;
        (w / h > 1) ? (a.className = 'show', b.className = 'full-body') : (a.className = 'hide', b.className = '');
    }
})();
</script>

And the HTML: <div id="alert" class="hide"> <div id="content">This site is not thought to be viewed in landscape mode, please turn your device </div> </div>

How to select rows from a DataFrame based on column values

For selecting only specific columns out of multiple columns for a given value in Pandas:

select col_name1, col_name2 from table where column_name = some_value.

Options:

df.loc[df['column_name'] == some_value][[col_name1, col_name2]]

or

df.query['column_name' == 'some_value'][[col_name1, col_name2]]

how to add the missing RANDR extension

I had the same problem with Firefox 30 + Selenium 2.49 + Ubuntu 15.04.

It worked fine with Ubuntu 14 but after upgrade to 15.04 I got same RANDR warning and problem at starting Firefox using Xfvb.

After adding +extension RANDR it worked again.

$ vim /etc/init/xvfb.conf

#!upstart
description "Xvfb Server as a daemon"

start on filesystem and started networking
stop on shutdown

respawn

env XVFB=/usr/bin/Xvfb
env XVFBARGS=":10 -screen 1 1024x768x24 -ac +extension GLX +extension RANDR +render -noreset"
env PIDFILE=/var/run/xvfb.pid

exec start-stop-daemon --start --quiet --make-pidfile --pidfile $PIDFILE --exec $XVFB -- $XVFBARGS >> /var/log/xvfb.log 2>&1

Can you have multiline HTML5 placeholder text in a <textarea>?

React:

If you are using React, you can do it as follows:

placeholder={'Address Line1\nAddress Line2\nCity State, Zip\nCountry'}

Two Decimal places using c#

here is another approach

decimal decimalRounded = Decimal.Parse(Debitvalue.ToString("0.00"));

Time comparison

Java doesn't (yet) have a good built-in Time class (it has one for JDBC queries, but that's not what you want).

One option would be use the JodaTime APIs and its LocalTime class.

Sticking with just the built-in Java APIs, you are stuck with java.util.Date. You can use a SimpleDateFormat to parse the time, then the Date comparison functions to see if it is before or after some other time:

SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date ten = parser.parse("10:00");
Date eighteen = parser.parse("18:00");

try {
    Date userDate = parser.parse(someOtherDate);
    if (userDate.after(ten) && userDate.before(eighteen)) {
        ...
    }
} catch (ParseException e) {
    // Invalid date was entered
}

Or you could just use some string manipulations, perhaps a regular expression to extract just the hour and the minute portions, convert them to numbers and do a numerical comparison:

Pattern p = Pattern.compile("(\d{2}):(\d{2})");
Matcher m = p.matcher(userString);
if (m.matches() ) {
    String hourString = m.group(1);
    String minuteString = m.group(2);
    int hour = Integer.parseInt(hourString);
    int minute = Integer.parseInt(minuteString);

    if (hour >= 10 && hour <= 18) {
        ...
    }
}

It really all depends on what you are trying to accomplish.

How to percent-encode URL parameters in Python?

In Python 3, urllib.quote has been moved to urllib.parse.quote and it does handle unicode by default.

>>> from urllib.parse import quote
>>> quote('/test')
'/test'
>>> quote('/test', safe='')
'%2Ftest'
>>> quote('/El Niño/')
'/El%20Ni%C3%B1o/'

What difference does .AsNoTracking() make?

AsNoTracking() allows the "unique key per record" requirement in EF to be bypassed (not mentioned explicitly by other answers).

This is extremely helpful when reading a View that does not support a unique key because perhaps some fields are nullable or the nature of the view is not logically indexable.

For these cases the "key" can be set to any non-nullable column but then AsNoTracking() must be used with every query else records (duplicate by key) will be skipped.

Build a simple HTTP server in C

I'd suggest looking at the source to something like lighthttpd.

DateTime and CultureInfo

InvariantCulture is similar to en-US, so i would use the correct CultureInfo instead:

var dutchCulture = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCulture);

Demo

And what about when the culture is en-us? Will I have to code for every single language there is out there?

If you want to know how to display the date in another culture like "en-us", you can use date1.ToString(CultureInfo.CreateSpecificCulture("en-US")).

How to remove the underline for anchors(links)?

Use CSS to remove text-decorations.

a {
    text-decoration: none;
}

Differences between fork and exec

Fork creates a copy of a calling process. generally follows the structure enter image description here

int cpid = fork( );

if (cpid = = 0) 
{

  //child code

  exit(0);

}

//parent code

wait(cpid);

// end

(for child process text(code),data,stack is same as calling process) child process executes code in if block.

EXEC replaces the current process with new process's code,data,stack. generally follows the structure enter image description here

int cpid = fork( );

if (cpid = = 0) 
{   
  //child code

  exec(foo);

  exit(0);    
}

//parent code

wait(cpid);

// end

(after exec call unix kernel clears the child process text,data,stack and fills with foo process related text/data) thus child process is with different code (foo's code {not same as parent})

Best HTTP Authorization header type for JWT

The best HTTP header for your client to send an access token (JWT or any other token) is the Authorization header with the Bearer authentication scheme.

This scheme is described by the RFC6750.

Example:

GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIXVCJ9TJV...r7E20RMHrHDcEfxjoYZgeFONFh7HgQ

If you need stronger security protection, you may also consider the following IETF draft: https://tools.ietf.org/html/draft-ietf-oauth-pop-architecture. This draft seems to be a good alternative to the (abandoned?) https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac.

Note that even if this RFC and the above specifications are related to the OAuth2 Framework protocol, they can be used in any other contexts that require a token exchange between a client and a server.

Unlike the custom JWT scheme you mention in your question, the Bearer one is registered at the IANA.

Concerning the Basic and Digest authentication schemes, they are dedicated to authentication using a username and a secret (see RFC7616 and RFC7617) so not applicable in that context.

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

Laravel 5 Clear Views Cache

There is now a php artisan view:clear command for this task since Laravel 5.1

How to get the Enum Index value in C#

By default the underlying type of each element in the enum is integer.

enum Values
{
   A,
   B,
   C
}

You can also specify custom value for each item:

enum Values
{
   A = 10,
   B = 11,
   C = 12
}
int x = (int)Values.A; // x will be 10;

Note: By default, the first enumerator has the value 0.

How to add a char/int to an char array in C?

I think you've forgotten initialize your string "str": You need initialize the string before using strcat. And also you need that tmp were a string, not a single char. Try change this:

char str[1024]; // Only declares size
char tmp = '.';

for

char str[1024] = "Hello World";  //Now you have "Hello World" in str
char tmp[2] = ".";

JQuery to load Javascript file dynamically

I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:

$("#addComment").click(function() {
    if(typeof TinyMCE === "undefined") {
        $.ajax({
            url: "tinymce.js",
            dataType: "script",
            cache: true,
            success: function() {
                TinyMCE.init();
            }
        });
    }
});

The getScript() function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:

http://www.yoursite.com/js/tinymce.js?_=1399055841840

If a user clicks the #addComment link multiple times, tinymce.js will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.

===

Alternatively, in the getScript() documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript() function as follows:

jQuery.cachedScript = function( url, options ) {

    // Allow user to set any option except for dataType, cache, and url
    options = $.extend( options || {}, {
        dataType: "script",
        cache: true,
        url: url
    });

    // Use $.ajax() since it is more flexible than $.getScript
    // Return the jqXHR object so we can chain callbacks
    return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
    console.log( textStatus );
});

===

Or, if you want to disable caching globally, you can do so using ajaxSetup() as follows:

$.ajaxSetup({
    cache: true
});

iPhone UILabel text soft shadow

To keep things up to date: Creating the shadow in Swift is as easy as that:

Import the QuartzCore Framework

import QuartzCore

And set the shadow attributes to your label

titleLabel.shadowColor = UIColor.blackColor()
titleLabel.shadowOffset = CGSizeMake(0.0, 0.0)
titleLabel.layer.shadowRadius = 5.0
titleLabel.layer.shadowOpacity = 0.8
titleLabel.layer.masksToBounds = false
titleLabel.layer.shouldRasterize = true

Android Saving created bitmap to directory on sd card

This answer is an update with a little more consideration for OOM and various other leaks.

Assumes you have a directory intended as the destination and a name String already defined.

    File destination = new File(directory.getPath() + File.separatorChar + filename);

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    source.compress(Bitmap.CompressFormat.PNG, 100, bytes);

    FileOutputStream fo = null;
    try {
        destination.createNewFile();

        fo = new FileOutputStream(destination);
        fo.write(bytes.toByteArray());
    } catch (IOException e) {

    } finally {
        try {
            fo.close();
        } catch (IOException e) {}
    }

What are "named tuples" in Python?

Everyone else has already answered it, but I think I still have something else to add.

Namedtuple could be intuitively deemed as a shortcut to define a class.

See a cumbersome and conventional way to define a class .

class Duck:
    def __init__(self, color, weight):
        self.color = color
        self.weight = weight
red_duck = Duck('red', '10')

    In [50]: red_duck
    Out[50]: <__main__.Duck at 0x1068e4e10>
    In [51]: red_duck.color
    Out[51]: 'red'

As for namedtuple

from collections import namedtuple
Duck = namedtuple('Duck', ['color', 'weight'])
red_duck = Duck('red', '10')

In [54]: red_duck
Out[54]: Duck(color='red', weight='10')
In [55]: red_duck.color
Out[55]: 'red'

UPDATE and REPLACE part of a string

You don't need wildcards in the REPLACE - it just finds the string you enter for the second argument, so the following should work:

UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <=4

If the column to replace is type text or ntext you need to cast it to nvarchar

UPDATE dbo.xxx
SET Value = REPLACE(CAST(Value as nVarchar(4000)), '123', '')
WHERE ID <=4

What is this date format? 2011-08-12T20:17:46.384Z

The T is just a literal to separate the date from the time, and the Z means "zero hour offset" also known as "Zulu time" (UTC). If your strings always have a "Z" you can use:

SimpleDateFormat format = new SimpleDateFormat(
    "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));

Or using Joda Time, you can use ISODateTimeFormat.dateTime().

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

Yeah, the best way is to convert the object notation to a flat key-value string representation, as mentioned in this comment: https://stackoverflow.com/a/39357531/2529199

I wanted to highlight an alternative method using this NPM library: https://www.npmjs.com/package/dot-object which lets you manipulate different objects using dot notation.

I used this pattern to programatically create a nested object property when accepting the key-value as a function variable, as follows:

const dot = require('dot-object');

function(docid, varname, varvalue){
  let doc = dot.dot({
      [varname]: varvalue 
  });

  Mongo.update({_id:docid},{$set:doc});
}

This pattern lets me use nested as well as single-level properties interchangeably, and insert them cleanly into Mongo.

If you need to play around with JS Objects beyond just Mongo, especially on the client-side but have consistency when working with Mongo, this library gives you more options than the earlier mentioned mongo-dot-notation NPM module.

P.S I originally wanted to just mention this as a comment but apparently my S/O rep isn't high enough to post a comment. So, not trying to muscle in on SzybkiSasza's comment, just wanted to highlight providing an alternative module.

Sometimes adding a WCF Service Reference generates an empty reference.cs

When attempting to troubleshoot this problem with svcutil, I received the error referred to in dblood's answer ("referenced type cannot be used since it does not match imported DataContract").

In my case the underlying cause seemed to be an enum type that had the DataContract attribute, but whose members were not marked with the EnumMember attribute. The problem class svcutil pointed at had a property with that enum type.

This would fit better as a comment to dblood's answer, but not enough rep for that...

Display text from .txt file in batch file

Try this: use Find to iterate through all lines with "Current date/time", and write each line to the same file:

for /f "usebackq delims==" %i in (`find "Current date" log.txt`) do (echo %i > log-time.txt)
type log-time.txt

Set delims= to a character not relevant in the date/time lines. Use %%i in batch files.

Explanation (update):

Find extracts all lines from log.txt containing the search string.

For /f loops through each line the command inside (...) generates.

As echo > log-time.txt (single > !) overwrites log-time.txt every time it's executed, only the last matching line remains in log-time.txt

Add Keypair to existing EC2 instance

You can't apply a keypair to a running instance. You can only use the new keypair to launch a new instance.

For recovery, if it's an EBS boot AMI, you can stop it, make a snapshot of the volume. Create a new volume based on it. And be able to use it back to start the old instance, create a new image, or recover data.

Though data at ephemeral storage will be lost.


Due to the popularity of this question and answer, I wanted to capture the information in the link that Rodney posted on his comment.

Credit goes to Eric Hammond for this information.

Fixing Files on the Root EBS Volume of an EC2 Instance

You can examine and edit files on the root EBS volume on an EC2 instance even if you are in what you considered a disastrous situation like:

  • You lost your ssh key or forgot your password
  • You made a mistake editing the /etc/sudoers file and can no longer gain root access with sudo to fix it
  • Your long running instance is hung for some reason, cannot be contacted, and fails to boot properly
  • You need to recover files off of the instance but cannot get to it

On a physical computer sitting at your desk, you could simply boot the system with a CD or USB stick, mount the hard drive, check out and fix the files, then reboot the computer to be back in business.

A remote EC2 instance, however, seems distant and inaccessible when you are in one of these situations. Fortunately, AWS provides us with the power and flexibility to be able to recover a system like this, provided that we are running EBS boot instances and not instance-store.

The approach on EC2 is somewhat similar to the physical solution, but we’re going to move and mount the faulty “hard drive” (root EBS volume) to a different instance, fix it, then move it back.

In some situations, it might simply be easier to start a new EC2 instance and throw away the bad one, but if you really want to fix your files, here is the approach that has worked for many:

Setup

Identify the original instance (A) and volume that contains the broken root EBS volume with the files you want to view and edit.

instance_a=i-XXXXXXXX

volume=$(ec2-describe-instances $instance_a |
  egrep '^BLOCKDEVICE./dev/sda1' | cut -f3)

Identify the second EC2 instance (B) that you will use to fix the files on the original EBS volume. This instance must be running in the same availability zone as instance A so that it can have the EBS volume attached to it. If you don’t have an instance already running, start a temporary one.

instance_b=i-YYYYYYYY

Stop the broken instance A (waiting for it to come to a complete stop), detach the root EBS volume from the instance (waiting for it to be detached), then attach the volume to instance B on an unused device.

ec2-stop-instances $instance_a
ec2-detach-volume $volume
ec2-attach-volume --instance $instance_b --device /dev/sdj $volume

ssh to instance B and mount the volume so that you can access its file system.

ssh ...instance b...

sudo mkdir -p 000 /vol-a
sudo mount /dev/sdj /vol-a

Fix It

At this point your entire root file system from instance A is available for viewing and editing under /vol-a on instance B. For example, you may want to:

  • Put the correct ssh keys in /vol-a/home/ubuntu/.ssh/authorized_keys
  • Edit and fix /vol-a/etc/sudoers
  • Look for error messages in /vol-a/var/log/syslog
  • Copy important files out of /vol-a/…

Note: The uids on the two instances may not be identical, so take care if you are creating, editing, or copying files that belong to non-root users. For example, your mysql user on instance A may have the same UID as your postfix user on instance B which could cause problems if you chown files with one name and then move the volume back to A.

Wrap Up

After you are done and you are happy with the files under /vol-a, unmount the file system (still on instance-B):

sudo umount /vol-a
sudo rmdir /vol-a

Now, back on your system with ec2-api-tools, continue moving the EBS volume back to it’s home on the original instance A and start the instance again:

ec2-detach-volume $volume
ec2-attach-volume --instance $instance_a --device /dev/sda1 $volume
ec2-start-instances $instance_a

Hopefully, you fixed the problem, instance A comes up just fine, and you can accomplish what you originally set out to do. If not, you may need to continue repeating these steps until you have it working.

Note: If you had an Elastic IP address assigned to instance A when you stopped it, you’ll need to reassociate it after starting it up again.

Remember! If your instance B was temporarily started just for this process, don’t forget to terminate it now.

VBA Check if variable is empty

I had a similar issue with an integer that could be legitimately assigned 0 in Access VBA. None of the above solutions worked for me.

At first I just used a boolean var and IF statement:

Dim i as integer, bol as boolean
   If bol = false then
      i = ValueIWantToAssign
      bol = True
   End If

In my case, my integer variable assignment was within a for loop and another IF statement, so I ended up using "Exit For" instead as it was more concise.

Like so:

Dim i as integer
ForLoopStart
   If ConditionIsMet Then
      i = ValueIWantToAssign
   Exit For
   End If
ForLoopEnd

HTML favicon won't show on google chrome

Another reason for Chrome not displaying the favicon is that it still remembers a time when the site in question did not have a favicon or the favicon was incorrectly configured.

You're going to want to completely wipe the favicon cache:

  1. Exit all running Chrome processes.

  2. Delete the Favicons file in your user data folder. For example:

    C:\Users\me\AppData\Local\Google\Chrome\User Data\Default\Favicons
    

This can not be resolved by clearing the browser cache, as it does not affect the Favicons container.

Also note that, contrary to what you might read online, requests to favicon resources are not shown in the Network panel of the DevTools. Under very rare circumstances, one such request may show up there, but it is highly unlikely and the DevTools will not help you solve your favicon woes.

Rounding Bigdecimal values with 2 Decimal Places

Add 0.001 first to the number and then call setScale(2, RoundingMode.ROUND_HALF_UP)

Code example:

public static void main(String[] args) {
    BigDecimal a = new BigDecimal("10.12445").add(new BigDecimal("0.001"));
    BigDecimal b = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println(b);
}

Is it possible to get a list of files under a directory of a website? How?

Any crawler or spider will read your index.htm or equivalent, that is exposed to the web, they will read the source code for that page, and find everything that is associated to that webpage and contains subdirectories. If they find a "contact us" button, there may be is included the path to the webpage or php that deal with the contact-us action, so they now have one more subdirectory/folder name to crawl and dig more. But even so, if that folder has a index.htm or equivalent file, it will not list all the files in such folder.

If by mistake, the programmer never included an index.htm file in such folder, then all the files will be listed on your computer screen, and also for the crawler/spider to keep digging. But, if you created a folder www.yoursite.com/nombresinistro75crazyragazzo19/ and put several files in there, and never published any button or never exposed that folder address anywhere in the net, keeping only in your head, chances are that nobody ever will find that path, with crawler or spider, for more sophisticated it can be.

Except, of course, if they can enter your FTP or access your site control panel.

Is it possible to Turn page programmatically in UIPageViewController?

I could totally be missing something here, but this solution seems a lot simpler than many others proposed.

extension UIPageViewController {
    func goToNextPage(animated: Bool = true, completion: ((Bool) -> Void)? = nil) {
        if let currentViewController = viewControllers?[0] {
            if let nextPage = dataSource?.pageViewController(self, viewControllerAfter: currentViewController) {
                setViewControllers([nextPage], direction: .forward, animated: animated, completion: completion)
            }
        }
    }
}

Executing multiple SQL queries in one statement with PHP

With mysqli you're able to use multiple statements for real using mysqli_multi_query().

Read more on multiple statements in the PHP Docs.

how to add value to combobox item

Instead of adding Reader("Name") you add a new ListItem. ListItem has a Text and a Value property that you can set.

List all kafka topics

to see that topic if we run the list topic command:

$ bin/kafka-topics.sh --list --zookeeper localhost:2181

To check if the data is landing in Kafka:

$ bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic twitterstream --from-beginning

Get IP address of visitors using Flask for Python

If You are using Gunicorn and Nginx environment then the following code template works for you.

addr_ip4 = request.remote_addr

using mailto to send email with an attachment

what about this

<FORM METHOD="post" ACTION="mailto:[email protected]" ENCTYPE="multipart/form-data">
Attachment: <INPUT TYPE="file" NAME="attachedfile" MAXLENGTH=50 ALLOW="text/*" >
 <input type="submit" name="submit" id="submit" value="Email"/>
</FORM>

Storing integer values as constants in Enum manner in java

I found this to be helpful:

http://dan.clarke.name/2011/07/enum-in-java-with-int-conversion/

public enum Difficulty
{
    EASY(0),
    MEDIUM(1),
    HARD(2);

    /**
    * Value for this difficulty
    */
    public final int Value;

    private Difficulty(int value)
    {
        Value = value;
    }

    // Mapping difficulty to difficulty id
    private static final Map<Integer, Difficulty> _map = new HashMap<Integer, Difficulty>();
    static
    {
        for (Difficulty difficulty : Difficulty.values())
            _map.put(difficulty.Value, difficulty);
    }

    /**
    * Get difficulty from value
    * @param value Value
    * @return Difficulty
    */
    public static Difficulty from(int value)
    {
        return _map.get(value);
    }
}

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

I just had this problem also. Tried all the suggestions here, but they didn't help.

I found another thing to check that fixed it for me. In Visual Studio, right-click on the project and open "Properties". Click on the "Compile" (or "Build") tab and then click on "Advanced Compile Options" at the bottom.

Check the dropdown "Target CPU". It should match the "Platform" you are building. That is, if you are building "Any CPU" then "Target CPU" should say "Any CPU". Go through all of your Platforms by making them active and check this setting.

Could not load file or assembly '' or one of its dependencies

  1. Check if you are referencing an assembly which in turn referencing an old version of unity. For example let's say you have an assembly called ServiceLocator.dll which needs an old version of Unity assembly, now when you reference the ServiceLocator you should provide it with the old version of Unity, and that makes the problem.

  2. May be the output folder where all projects build their assemblies, has an old version of unity.

You can use FusLogVw to find out who is loading the old assemblies, just define a path for the log, and run your solution, then check (in FusLogvw) the first line where the Unity assembly is loaded, double click it and see the calling assembly, and here you go.

How to find and replace string?

void replaceAll(std::string & data, const std::string &toSearch, const std::string &replaceStr)
{
    // Get the first occurrence
    size_t pos = data.find(toSearch);
    // Repeat till end is reached
    while( pos != std::string::npos)
    {
        // Replace this occurrence of Sub String
        data.replace(pos, toSearch.size(), replaceStr);
        // Get the next occurrence from the current position
        pos =data.find(toSearch, pos + replaceStr.size());
    }
}

More CPP utilities: https://github.com/Heyshubham/CPP-Utitlities/blob/master/src/MEString.cpp#L60

Where could I buy a valid SSL certificate?

You are really asking a couple of questions here:

1) Why does the price of SSL certificates vary so much

2) Where can I get good, cheap SSL certificates?

The first question is a good one. For example, the type of SSL certificate you buy is important. Many SSL certificates are domain verified only - that is, the company issuing the certificate only validate that you own the domain. They don't validate your identity, so people visiting your site might know that the domain has a SSL certificate, but that doesn't mean the person behing the website isn't a scammer or phisher, for example. This is why the Verisign solution is much more expensive - you are getting a cert that not only secures your site, but validates the identity of the owner of the site (well, that's the claim).

You can read more on this subject here

For your second question, I can personally recommend RapidSSL. I've bought several certificates from them in the past and they are, well, rapid. However, you should always do your research first. A company based in France might be better for you to deal with as you can get support in your local hours, etc.

javac not working in windows command prompt

Try the solutions here: http://techdem.centerkey.com/2009/05/javahome-command-script.html

These are much more robust to change -- like when you upgrade the JDK or JRE, since there is no hard coded path.

The quick solution (if you don't want to read the blog) is

C:\>for /d %i in ("\Program Files\Java\jdk*") do set JAVA_HOME=%i
C:\>set PATH=%PATH%;%JAVA_HOME%

You can then add these lines to a startup/login script.

IntelliJ, can't start simple web application: Unable to ping server at localhost:1099

I had same problem. In "Edit Configurations.." -> "Tomcat Server" I changed JRE from "Default" to my current version with SDK directory address (like C:\Program Files\Java\jdk1.8.0_121\jre)

My Tomcat version is 8.5.31

How to display 3 buttons on the same line in css

You need to float all the buttons to left and make sure its width to fit within outer container.

CSS:

.btn{

   float:left;
}

HTML:

    <button type="submit" class="btn" onClick="return false;" >Save</button>
    <button type="submit" class="btn" onClick="return false;">Publish</button>
    <button class="btn">Back</button>

How is the default max Java heap size determined?

The Xms and Xmx are flag of Java virtual machine (JVM):

  • Xms: initial and minimum JVM heap size
    • Format: -Xms<size>[g|G|m|M|k|K]
    • Default Size:
      • -server mode: 25% of free physical memory, >=8MB and <= 64MB
      • -client mode: 25% of free physical memory, >=8MB and <= 16MB
    • Typical Size:
      • -Xms128M
      • -Xms256M
      • -Xms512M
    • Function/Effect:
      • -> JVM start with allocate Xms size memory
  • Xmx: maximum JVM heap size
    • Format: -Xmx<size>[g|G|m|M|k|K]
    • Default Size:
      • <= R27.2
        • Windows: 75% of total physical memory up to 1GB
        • Linux/Solaris: 50% of available physical memory up to 1GB
      • >= R27.3
        • Windows X64: 75% of total physical memory up to 2GB
        • Linux/Solaris X64: 50% of available physical memory up to 2GB
        • Windows x86: 75% of total physical memory up to 1GB
        • Linux/Solaris X86: 50% of available physical memory up to 1GB
    • Typical Size:
      • -Xmx1g
      • -Xmx2084M
      • -Xmx4g
      • -Xmx6g
      • -Xmx8g
    • Function/Effect:
      • -> JVM allow use maxium of Xmx size memory
        • when exceed Xmx, will java.lang.OutOfMemoryError
          • How to fix OutOfMemoryError ?
            • exceed Xmx value
              • eg: from -Xmx4g to -Xmx8g

More detail

see official doc: -X Command-line Options

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

How about:

public void printMB(uint sizekB)   
{
    double sizeMB = (double) sizekB / 1024;
    Console.WriteLine("Size is " + sizeMB.ToString("0.00") + "MB");
}

E.g. call like

printMB(123456);

Will result in output

"Size is 120,56 MB"

Multi value Dictionary

Here is an implementation of a single key to multi value map in C# which uses a set based key type:

https://github.com/ColmBhandal/CsharpExtras/blob/master/CsharpExtras/Dictionary/MultiValueMapImpl.cs

The dictionary behaves like a regular dictionary from the key type onto a set of the value type, but also provides functionality to directly add a single value of the value type, and in the background handles the creation of an underlying set and/or addition to that set.

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

[contains(text(),'')] only returns true or false. It won't return any element results.

Update a local branch with the changes from a tracked remote branch

You don't use the : syntax - pull always modifies the currently checked-out branch. Thus:

git pull origin my_remote_branch

while you have my_local_branch checked out will do what you want.

Since you already have the tracking branch set, you don't even need to specify - you could just do...

git pull

while you have my_local_branch checked out, and it will update from the tracked branch.

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

If you're using spring boot with starters - this dependency adds both tomcat-embed-el and hibernate-validator dependencies:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

How to test android apps in a real device with Android Studio?

if you are using IOS react native platform and want to debugging real android device you can use following code:

adb reverse tcp:8081 tcp:8081
npm start -- --reset-cache
react-native run-android

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

This is a simple example of JSON parsing by taking example of google map API. This will return City name of given zip code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Net;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        WebClient client = new WebClient();
        string jsonstring;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            jsonstring = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address="+txtzip.Text.Trim());
            dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);

            Response.Write(dynObj.results[0].address_components[1].long_name);
        }
    }
}

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

You can cast your timestamp to a date by suffixing it with ::date. Here, in psql, is a timestamp:

# select '2010-01-01 12:00:00'::timestamp;
      timestamp      
---------------------
 2010-01-01 12:00:00

Now we'll cast it to a date:

wconrad=# select '2010-01-01 12:00:00'::timestamp::date;
    date    
------------
 2010-01-01

On the other hand you can use date_trunc function. The difference between them is that the latter returns the same data type like timestamptz keeping your time zone intact (if you need it).

=> select date_trunc('day', now());
       date_trunc
------------------------
 2015-12-15 00:00:00+02
(1 row)

Process to convert simple Python script into Windows executable

you may want to see if your app can run under IronPython. If so, you can compile it to an exe http://www.codeplex.com/IronPython

How to create a dotted <hr/> tag?

You could just have <hr style="border-top: dotted 1px;" /> . That should work.

Post multipart request with Android SDK

I can recomend Ion library it use 3 dependences and you can find all three jar files at these two sites:
https://github.com/koush/ion#jars (ion and androidasync)

https://code.google.com/p/google-gson/downloads/list (gson)

try {
   Ion.with(this, "http://www.urlthatyouwant.com/post/page")
   .setMultipartParameter("field1", "This is field number 1")
   .setMultipartParameter("field2", "Field 2 is shorter")
   .setMultipartFile("imagefile",
        new File(Environment.getExternalStorageDirectory()+"/testfile.jpg"))
   .asString()
   .setCallback(new FutureCallback<String>() {
        @Override
        public void onCompleted(Exception e, String result) {
             System.out.println(result);
        }});
   } catch(Exception e) {
     // Do something about exceptions
        System.out.println("exception: " + e);
   }

this will run async and the callback will be executed in the UI thread once a response is received I strongly recomned that you go to the https://github.com/koush/ion for futher information

Remove space above and below <p> tag HTML

<p> elements generally have margins and / or padding. You can set those to zero in a stylesheet.

li p {
    margin: 0;
    padding: 0;
}

Semantically speaking, however, it is fairly unusual to have a list of paragraphs.

Mask output of `The following objects are masked from....:` after calling attach() function

It may be "better" to not use attach at all. On the plus side, you can save some typing if you use attach. Let's say your dataset is called mydata and you have variables called v1, v2, and v3. If you don't attach mydata, then you will type mean(mydata$v1) to get the mean of v1. If you do attach mydata, then you will type mean(v1) to get the mean of v1. But, if you don't detach the mydata dataset (every time), you'll get the message about the objects being masked going forward.

Solution 1 (assuming you want to attach):

  1. Use detach every time.
  2. See Dan Tarr's response if you already have the data attached (and it may be in the global environment several times). Then, in the future, use detach every time.

Solution 2

Don't use attach. Instead, include the dataset name every time you refer to a variable. The form is mydata$v1 (name of data set, dollar sign, name of variable).

As for me, I used solution 1 a lot in the past, but I've moved to solution 2. It's a bit more typing in the beginning, but if you are going to use the code multiple times, it just seems cleaner.

How to call a method defined in an AngularJS directive?

If you want to use isolated scopes you can pass a control object using bi-directional binding = of a variable from the controller scope. You can also control also several instances of the same directive on a page with the same control object.

_x000D_
_x000D_
angular.module('directiveControlDemo', [])_x000D_
_x000D_
.controller('MainCtrl', function($scope) {_x000D_
  $scope.focusinControl = {};_x000D_
})_x000D_
_x000D_
.directive('focusin', function factory() {_x000D_
  return {_x000D_
    restrict: 'E',_x000D_
    replace: true,_x000D_
    template: '<div>A:{{internalControl}}</div>',_x000D_
    scope: {_x000D_
      control: '='_x000D_
    },_x000D_
    link: function(scope, element, attrs) {_x000D_
      scope.internalControl = scope.control || {};_x000D_
      scope.internalControl.takenTablets = 0;_x000D_
      scope.internalControl.takeTablet = function() {_x000D_
        scope.internalControl.takenTablets += 1;_x000D_
      }_x000D_
    }_x000D_
  };_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div ng-app="directiveControlDemo">_x000D_
  <div ng-controller="MainCtrl">_x000D_
    <button ng-click="focusinControl.takeTablet()">Call directive function</button>_x000D_
    <p>_x000D_
      <b>In controller scope:</b>_x000D_
      {{focusinControl}}_x000D_
    </p>_x000D_
    <p>_x000D_
      <b>In directive scope:</b>_x000D_
      <focusin control="focusinControl"></focusin>_x000D_
    </p>_x000D_
    <p>_x000D_
      <b>Without control object:</b>_x000D_
      <focusin></focusin>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Getting a timestamp for today at midnight?

Updated Answer in 19 April, 2020

Simply we can do this:

$today = date('Y-m-d 00:00:00');

div inside php echo

You can use the below sample, also you dont need the else clause to print nothing!

 <?php if ( ($cart->count_product) > 0) { ?>
           <div class="my_class">
               <?php print $cart->count_product; ?> 
           </div>
 <?php } ?>

Django: save() vs update() to update the database?

Update only works on updating querysets. If you want to update multiple fields at the same time, say from a dict for a single object instance you can do something like:

obj.__dict__.update(your_dict)
obj.save()

Bear in mind that your dictionary will have to contain the correct mapping where the keys need to be your field names and the values the values you want to insert.

Trim last character from a string

you could also use this:

public static class Extensions
 {

        public static string RemovePrefix(this string o, string prefix)
        {
            if (prefix == null) return o;
            return !o.StartsWith(prefix) ? o : o.Remove(0, prefix.Length);
        }

        public static string RemoveSuffix(this string o, string suffix)
        {
            if(suffix == null) return o;
            return !o.EndsWith(suffix) ? o : o.Remove(o.Length - suffix.Length, suffix.Length);
        }

    }

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

if x is numeric, then add scale_x_continuous(); if x is character/factor, then add scale_x_discrete(). This might solve your problem.

Unstage a deleted file in git

I tried the above solutions and I was still having difficulties. I had other files staged with two files that were deleted accidentally.

To undo the two deleted files I had to unstage all of the files:

git reset HEAD .

At that point I was able to do the checkout of the deleted items:

git checkout -- WorkingFolder/FileName.ext

Finally I was able to restage the rest of the files and continue with my commit.

Setting background-image using jQuery CSS property

You probably want this (to make it like a normal CSS background-image declaration):

$('myObject').css('background-image', 'url(' + imageUrl + ')');

Get an object's class name at runtime

In Angular2, this can help to get components name:

    getName() {
        let comp:any = this.constructor;
        return comp.name;
    }

comp:any is needed because TypeScript compiler will issue errors since Function initially does not have property name.

C non-blocking keyboard input

select() is a bit too low-level for convenience. I suggest you use the ncurses library to put the terminal in cbreak mode and delay mode, then call getch(), which will return ERR if no character is ready:

WINDOW *w = initscr();
cbreak();
nodelay(w, TRUE);

At that point you can call getch without blocking.

What is the --save option for npm install?

Update npm 5:

As of npm 5.0.0, installed modules are added as a dependency by default, so the --save option is no longer needed. The other save options still exist and are listed in the documentation for npm install.

Original answer:

Before version 5, NPM simply installed a package under node_modules by default. When you were trying to install dependencies for your app/module, you would need to first install them, and then add them (along with the appropriate version number) to the dependencies section of your package.json.

The --save option instructed NPM to include the package inside of the dependencies section of your package.json automatically, thus saving you an additional step.

In addition, there are the complementary options --save-dev and --save-optional which save the package under devDependencies and optionalDependencies, respectively. This is useful when installing development-only packages, like grunt or your testing library.

MessageBox with YesNoCancel - No & Cancel triggers same event

dim result as dialogresult
result = MessageBox.Show("message", "caption", MessageBoxButtons.YesNoCancel)
If result = DialogResult.Cancel Then
    MessageBox.Show("Cancel pressed")
ElseIf result = DialogResult.No Then
    MessageBox.Show("No pressed")
ElseIf result = DialogResult.Yes Then
    MessageBox.Show("Yes pressed")
End If

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

I had the same error when initializing Spring on startup, using some different library versions, but everything worked when I got my versions in this order in the classpath (the other libraries in the cp were not important):

  1. asm-3.1.jar
  2. cglib-nodep-2.1_3.jar
  3. asm-attrs-1.5.3.jar

How do I post form data with fetch api?

To add on the good answers above you can also avoid setting explicitly the action in HTML and use an event handler in javascript, using "this" as the form to create the "FormData" object

Html form :

<form id="mainForm" class="" novalidate>
<!--Whatever here...-->
</form>

In your JS :

$("#mainForm").submit(function( event ) {
  event.preventDefault();
  const formData = new URLSearchParams(new FormData(this));
  fetch("http://localhost:8080/your/server",
    {   method: 'POST',
        mode : 'same-origin',
        credentials: 'same-origin' ,
        body : formData
    })
    .then(function(response) {
      return response.text()
    }).then(function(text) {
        //text is the server's response
    });
});

angularjs make a simple countdown

It might help to "How to write the code for countdown watch in AngularJS"

Step 1 : HTML Code-sample

<div ng-app ng-controller="ExampleCtrl">
    <div ng-show="countDown_text > 0">Your password is expired in 180 Seconds.</div>
    <div ng-show="countDown_text > 0">Seconds left {{countDown_text}}</div>
    <div ng-show="countDown_text == 0">Your password is expired!.</div>
</div>

Step 2 : The AngulaJs code-sample

function ExampleCtrl($scope, $timeout) {
  var countDowner, countDown = 10;
  countDowner = function() {
    if (countDown < 0) {
      $("#warning").fadeOut(2000);
      countDown = 0;
      return; // quit
    } else {
      $scope.countDown_text = countDown; // update scope
      countDown--; // -1
      $timeout(countDowner, 1000); // loop it again
    }
  };

  $scope.countDown_text = countDown;
  countDowner()
}

The full example over countdown watch in AngularJs as given below.

<!DOCTYPE html>
<html>

<head>
  <title>AngularJS Example - Single Timer Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
  <script>
    function ExampleCtrl($scope, $timeout) {
      var countDowner, countDown = 10;
      countDowner = function() {
        if (countDown < 0) {
          $("#warning").fadeOut(2000);
          countDown = 0;
          return; // quit
        } else {
          $scope.countDown_text = countDown; // update scope
          countDown--; // -1
          $timeout(countDowner, 1000); // loop it again
        }
      };

      $scope.countDown_text = countDown;
      countDowner()
    }
  </script>
</head>

<body>
  <div ng-app ng-controller="ExampleCtrl">
    <div ng-show="countDown_text > 0">Your password is expired in 180 Seconds.</div>
    <div ng-show="countDown_text > 0">Seconds left {{countDown_text}}</div>
    <div ng-show="countDown_text == 0">Your password is expired!.</div>
  </div>
</body>

</html>

How do you auto format code in Visual Studio?

Select the text you want to automatically indent.

Click Format Selection in Edit, Advanced, or press CTRL+K, CTRL+F. Format Selection applies the smart indenting rules for the language in which you are programming to the selected text.

Step (1) :- CTRL+A

Step (2) :- CTRL+K

Step (3) :- CTRL+F

Mipmap drawables for icons

The Android implementation of mipmaps in 4.3 is exactly the technique from 1983 explained in the Wikipedia article :)

Each bitmap image of the mipmap set is a downsized duplicate of the main texture, but at a certain reduced level of detail. Although the main texture would still be used when the view is sufficient to render it in full detail, the renderer will switch to a suitable mipmap image (...) when the texture is viewed from a distance or at a small size.

Although this is described as a technique for 3D graphics (as it mentions "viewing from a distance"), it applies just as well to 2D (translated as "drawn is a smaller space", i.e. "downscaled").

For a concrete Android example, imagine you have a View with a certain background drawable (in particular, a BitmapDrawable). You now use an animation to scale it to 0.15 of its original size. Normally, this would require downscaling the background bitmap for each frame. This "extreme" downscaling, however, may produce visual artifacts.

You can, however, provide a mipmap, which means that the image is already pre-rendered for a few specific scales (let's say 1.0, 0.5, and 0.25). Whenever the animation "crosses" the 0.5 threshold, instead of continuing to downscale the original, 1.0-sized image, it will switch to the 0.5 image and downscale it, which should provide a better result. And so forth as the animation continues.

This is a bit theoretical, since it's actually done by the renderer. According to the source of the Bitmap class, it's just a hint, and the renderer may or may not honor it.

/**
 * Set a hint for the renderer responsible for drawing this bitmap
 * indicating that it should attempt to use mipmaps when this bitmap
 * is drawn scaled down.
 *
 * If you know that you are going to draw this bitmap at less than
 * 50% of its original size, you may be able to obtain a higher
 * quality by turning this property on.
 * 
 * Note that if the renderer respects this hint it might have to
 * allocate extra memory to hold the mipmap levels for this bitmap.
 *
 * This property is only a suggestion that can be ignored by the
 * renderer. It is not guaranteed to have any effect.
 *
 * @param hasMipMap indicates whether the renderer should attempt
 *                  to use mipmaps
 *
 * @see #hasMipMap()
 */
public final void setHasMipMap(boolean hasMipMap) {
    nativeSetHasMipMap(mNativeBitmap, hasMipMap);
}

I'm not quite sure why this would be especially suitable for application icons, though. Although Android on tablets, as well as some launchers (e.g. GEL), request an icon "one density higher" to show it bigger, this is supposed to be done using the regular mechanism (i.e. drawable-xxxhdpi, &c).

Taking the record with the max date

Since Oracle 12C, you can fetch a specific number of rows with FETCH FIRST ROW ONLY. In your case this implies an ORDER BY, so the performance should be considered.

SELECT A, col_date
FROM TABLENAME t_ext
ORDER BY col_date DESC NULLS LAST
FETCH FIRST 1 ROW ONLY;

The NULLS LAST is just in case you may have null values in your field.

Insert images to XML file

The most common way of doing this is to include the binary as base-64 in an element. However, this is a workaround, and adds a bit of volume to the file.

For example, this is the bytes 00 to 09 (note we needed 16 bytes to encode 10 bytes worth of data):

<xml><image>AAECAwQFBgcICQ==</image></xml>

how you do this encoding varies per architecture. For example, with .NET you might use Convert.ToBase64String, or XmlWriter.WriteBase64.

How to compare data between two table in different databases using Sql Server 2008?

I’d really suggest that people who encounter this problem go and find a third party database comparison tool.

Reason – these tools save a lot of time and make the process less error prone.

I’ve used comparison tools from ApexSQL (Diff and Data Diff) but you can’t go wrong with other tools marc_s and Marina Nastenko already pointed out.

If you’re absolutely sure that you are only going to compare tables once then SQL is fine but if you’re going to need this from time to time you’ll be better off with some 3rd party tool.

If you don’t have budget to buy it then just use it in trial mode to get the job done.

I hope new readers will find this useful even though it’s a late answer…

Use :hover to modify the css of another class?

Provided .wrapper is inside .item, and provided you're either not in IE 6 or .item is an a tag, the CSS you have should work just fine. Do you have evidence to suggest it isn't?

EDIT:

CSS alone can't affect something not contained within it. To make this happen, format your menu like so:

<ul class="menu">
    <li class="menuitem">
        <a href="destination">menu text</a>
        <ul class="menu">
            <li class="menuitem">
                <a href="destination">part of pull-out menu</a>
... etc ...

and your CSS like this:

.menu .menu {
    display: none;
}

.menu .menuitem:hover .menu {
    display: block;
    float: left;
    // likely need to set top & left
}

Recover sa password

The best way is to simply reset the password by connecting with a domain/local admin (so you may need help from your system administrators), but this only works if SQL Server was set up to allow local admins (these are now left off the default admin group during setup).

If you can't use this or other existing methods to recover / reset the SA password, some of which are explained here:

Then you could always backup your important databases, uninstall SQL Server, and install a fresh instance.

You can also search for less scrupulous ways to do it (e.g. there are password crackers that I am not enthusiastic about sharing).

As an aside, the login properties for sa would never say Windows Authentication. This is by design as this is a SQL Authentication account. This does not mean that Windows Authentication is disabled at the instance level (in fact it is not possible to do so), it just doesn't apply for a SQL auth account.

I wrote a tip on using PSExec to connect to an instance using the NT AUTHORITY\SYSTEM account (which works < SQL Server 2012), and a follow-up that shows how to hack the SqlWriter service (which can work on more modern versions):

And some other resources:

How to get primary key of table?

MySQL has a SQL query "SHOW INDEX FROM" which returns the indexes from a table. For eg. - the following query will show all the indexes for the products table:-

SHOW INDEXES FROM products \G

It returns a table with type, column_name, Key_name, etc. and displays output with all indexes and primary keys as -

*************************** 1. row ***************************
        Table: products
   Non_unique: 0
     Key_name: PRIMARY
 Seq_in_index: 1
  Column_name: product_id
    Collation: A
  Cardinality: 0
     Sub_part: NULL
       Packed: NULL
         Null: 
   Index_type: BTREE
      Comment: 
Index_comment: 

To just display primary key from the table use :-

SHOW INDEXES FROM table_name WHERE Key_name = 'PRIMARY'

vector vs. list in STL

Most answers here miss one important detail: what for?

What do you want to keep in the containter?

If it is a collection of ints, then std::list will lose in every scenario, regardless if you can reallocate, you only remove from the front, etc. Lists are slower to traverse, every insertion costs you an interaction with the allocator. It would be extremely hard to prepare an example, where list<int> beats vector<int>. And even then, deque<int> may be better or close, not justyfing the use of lists, which will have greater memory overhead.

However, if you are dealing with large, ugly blobs of data - and few of them - you don't want to overallocate when inserting, and copying due to reallocation would be a disaster - then you may, maybe, be better off with a list<UglyBlob> than vector<UglyBlob>.

Still, if you switch to vector<UglyBlob*> or even vector<shared_ptr<UglyBlob> >, again - list will lag behind.

So, access pattern, target element count etc. still affects the comparison, but in my view - the elements size - cost of copying etc.

How to merge remote master to local branch

git rebase didn't seem to work for me. After git rebase, when I try to push changes to my local branch, I kept getting an error ("hint: Updates were rejected because the tip of your current branch is behind its remote counterpart. Integrate the remote changes (e.g. 'git pull ...') before pushing again.") even after git pull. What finally worked for me was git merge.

git checkout <local_branch>
git merge <master> 

If you are a beginner like me, here is a good article on git merge vs git rebase. https://www.atlassian.com/git/tutorials/merging-vs-rebasing

Can I run Keras model on gpu?

2.0 Compatible Answer: While above mentioned answer explain in detail on how to use GPU on Keras Model, I want to explain how it can be done for Tensorflow Version 2.0.

To know how many GPUs are available, we can use the below code:

print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))

To find out which devices your operations and tensors are assigned to, put tf.debugging.set_log_device_placement(True) as the first statement of your program.

Enabling device placement logging causes any Tensor allocations or operations to be printed. For example, running the below code:

tf.debugging.set_log_device_placement(True)

# Create some tensors
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)

print(c)

gives the Output shown below:

Executing op MatMul in device /job:localhost/replica:0/task:0/device:GPU:0 tf.Tensor( [[22. 28.] [49. 64.]], shape=(2, 2), dtype=float32)

For more information, refer this link

How can I use goto in Javascript?

To achieve goto-like functionality while keeping the call stack clean, I am using this method:

// in other languages:
// tag1:
// doSomething();
// tag2:
// doMoreThings();
// if (someCondition) goto tag1;
// if (otherCondition) goto tag2;

function tag1() {
    doSomething();
    setTimeout(tag2, 0); // optional, alternatively just tag2();
}

function tag2() {
    doMoreThings();
    if (someCondition) {
        setTimeout(tag1, 0); // those 2 lines
        return;              // imitate goto
    }
    if (otherCondition) {
        setTimeout(tag2, 0); // those 2 lines
        return;              // imitate goto
    }
    setTimeout(tag3, 0); // optional, alternatively just tag3();
}

// ...

Please note that this code is slow since the function calls are added to timeouts queue, which is evaluated later, in browser's update loop.

Please also note that you can pass arguments (using setTimeout(func, 0, arg1, args...) in browser newer than IE9, or setTimeout(function(){func(arg1, args...)}, 0) in older browsers.

AFAIK, you shouldn't ever run into a case that requires this method unless you need to pause a non-parallelable loop in an environment without async/await support.

Making the main scrollbar always visible

body { 
    min-height: 101vh; 
} 

works the best for me

Why does NULL = NULL evaluate to false in SQL server

The equality test, for example, in a case statement when clause, can be changed from

XYZ = NULL 

to

XYZ IS NULL

If I want to treat blanks and empty string as equal to NULL I often also use an equality test like:

(NULLIF(ltrim( XYZ ),'') IS NULL)

SameSite warning Chrome 77

Fixed by adding crossorigin to the script tag.

From: https://code.jquery.com/

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>

The integrity and crossorigin attributes are used for Subresource Integrity (SRI) checking. This allows browsers to ensure that resources hosted on third-party servers have not been tampered with. Use of SRI is recommended as a best-practice, whenever libraries are loaded from a third-party source. Read more at srihash.org

Can't clone a github repo on Linux via HTTPS

Make sure you have git 1.7.10 or later, it now prompts for user/password correctly. (You can download the latest version here)

How to import local packages without gopath

To add a "local" package to your project, add a folder (for example "package_name"). And put your implementation files in that folder.

src/github.com/GithubUser/myproject/
 +-- main.go
 +---package_name
       +-- whatever_name1.go
       +-- whatever_name2.go

In your package main do this:

import "github.com/GithubUser/myproject/package_name"

Where package_name is the folder name and it must match the package name used in files whatever_name1.go and whatever_name2.go. In other words all files with a sub-directory should be of the same package.

You can further nest more subdirectories as long as you specify the whole path to the parent folder in the import.

Running Java Program from Command Line Linux

Guys let's understand the syntax of it.

  1. If class file is present in the Current Dir.

    java -cp . fileName

  2. If class file is present within the Dir. Go to the Parent Dir and enter below cmd.

    java -cp . dir1.dir2.dir3.fileName

  3. If there is a dependency on external jars then,

    java -cp .:./jarName1:./jarName2 fileName

    Hope this helps.

Linux command: How to 'find' only text files?

  • bash example to serach text "eth0" in /etc in all text/ascii files

grep eth0 $(find /etc/ -type f -exec file {} \; | egrep -i "text|ascii" | cut -d ':' -f1)

Detach (move) subdirectory into separate Git repository

The original question wants XYZ/ABC/(*files) to become ABC/ABC/(*files). After implementing the accepted answer for my own code, I noticed that it actually changes XYZ/ABC/(*files) into ABC/(*files). The filter-branch man page even says,

The result will contain that directory (and only that) as its project root."

In other words, it promotes the top-level folder "up" one level. That's an important distinction because, for example, in my history I had renamed a top-level folder. By promoting folders "up" one level, git loses continuity at the commit where I did the rename.

I lost contiuity after filter-branch

My answer to the question then is to make 2 copies of the repository and manually delete the folder(s) you want to keep in each. The man page backs me up with this:

[...] avoid using [this command] if a simple single commit would suffice to fix your problem

Installing Tomcat 7 as Service on Windows Server 2008

  1. Edit service.bat – Swap two lines so that they appear in following order: if not “%JAVA_HOME%“ == ““ goto got JdkHome if not “%JRE_HOME%“ == ““ goto got JreHome
  2. Open cmd and run command service.bat install
  3. Open Services and find Apache Tomcat 7.0 Tomcat7. Right click and Properties. Change its startup type to Automatic (with delay).
  4. Reboot machine to verify if the service started automatically

How to create empty data frame with column names specified in R?

Just create a data.frame with 0 length variables

eg

nodata <- data.frame(x= numeric(0), y= integer(0), z = character(0))
str(nodata)

## 'data.frame':    0 obs. of  3 variables:
##  $ x: num 
##  $ y: int 
##  $ z: Factor w/ 0 levels: 

or to create a data.frame with 5 columns named a,b,c,d,e

nodata <- as.data.frame(setNames(replicate(5,numeric(0), simplify = F), letters[1:5]))

How do I get the Date & Time (VBS)

To expound on Numenor's answer you can do something like, Format(Now(),"HH:mm:ss") using these custom date/time formating options


For everyone who is tempted to downvote this answer please be aware that the question was originally tagged VB and vbscript hence my answer, the VB tag was edited out leaving only the vbscript tag. The OP accepted this answer which I take to mean that it gave him the information that he needed.

Can I have two JavaScript onclick events in one element?

This one works:

<input type="button" value="test" onclick="alert('hey'); alert('ho');" />

And this one too:

function Hey()
{
    alert('hey');
}

function Ho()
{
    alert('ho');
}

.

<input type="button" value="test" onclick="Hey(); Ho();" />

So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.

C++ - How to append a char to char*?

char ch = 't';
char chArray[2];
sprintf(chArray, "%c", ch);
char chOutput[10]="tes";
strcat(chOutput, chArray);
cout<<chOutput;

OUTPUT:

test

How to install the Sun Java JDK on Ubuntu 10.10 (Maverick Meerkat)?

It is working fine for me, but with a different command:

root@ubuntu:/usr/bin# sudo apt-get install sun-java6

Error message:

Couldn't find package sun-java6.

root@ubuntu:/usr/bin# sudo apt-get install sun-java*

Bam, it worked.

CSS force new line

Use the display property

a{
    display: block;
}

This will make the link to display in new line

If you want to remove list styling, use

li{
    list-style: none;
}

Wait for async task to finish

How about calling a function from within your callback instead of returning a value in sync_call()?

function sync_call(input) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) {
        value = result;
        use_value(value);
    } );
}

How to create a css rule for all elements except one class?

Wouldn't setting a css rule for all tables, and then a subsequent one for tables where class="dojoxGrid" work? Or am I missing something?

Highest Salary in each department

Here is a way to get maximum values and names on any version of SQL.

Test Data:

CREATE TABLE EmpDetails(DeptID VARCHAR(10), EmpName VARCHAR(10), Salary DECIMAL(8,2))
INSERT INTO EmpDetails VALUES('Engg','Sam',1000)
INSERT INTO EmpDetails VALUES('Engg','Smith',2000)
INSERT INTO EmpDetails VALUES('HR','Denis',1500)
INSERT INTO EmpDetails VALUES('HR','Danny',3000)
INSERT INTO EmpDetails VALUES('IT','David',2000)
INSERT INTO EmpDetails VALUES('IT','John',3000)

Example:

SELECT ed.DeptID
      ,ed.EmpName
      ,ed.Salary
FROM (SELECT DeptID, MAX(Salary) MaxSal
      FROM EmpDetails
      GROUP BY DeptID)AS empmaxsal
INNER JOIN EmpDetails ed
  ON empmaxsal.DeptID = ed.DeptID
 AND empmaxsal.MaxSal = ed.Salary

Not the most elegant, but it works.

What's the effect of adding 'return false' to a click event listener?

I am surprised that no one mentioned onmousedown instead of onclick. The

onclick='return false'

does not catch the browser's default behaviour resulting in (sometimes unwanted) text selection occurring for mousedown but

onmousedown='return false'

does.

In other words, when I click on a button, its text sometimes becomes accidentally selected changing the look of the button, that may be unwanted. That is the default behaviour that we are trying to prevent here. However, the mousedown event is registered before click, so if you only prevent that behaviour inside your click handler, it will not affect the unwanted selection arising from the mousedown event. So the text still gets selected. However, preventing default for the mousedown event will do the job.

See also event.preventDefault() vs. return false

How to sanity check a date in Java

This is working great for me. Approach suggested above by Ben.

private static boolean isDateValid(String s) {
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    try {
        Date d = asDate(s);
        if (sdf.format(d).equals(s)) {
            return true;
        } else {
            return false;
        }
    } catch (ParseException e) {
        return false;
    }
}

Getting all request parameters in Symfony 2

Since you are in a controller, the action method is given a Request parameter.

You can access all POST data with $request->request->all();. This returns a key-value pair array.

When using GET requests you access data using $request->query->all();

Understanding the set() function

After reading the other answers, I still had trouble understanding why the set comes out un-ordered.

Mentioned this to my partner and he came up with this metaphor: take marbles. You put them in a tube a tad wider than marble width : you have a list. A set, however, is a bag. Even though you feed the marbles one-by-one into the bag; when you pour them from a bag back into the tube, they will not be in the same order (because they got all mixed up in a bag).

Find all files with name containing string

grep -R "somestring" | cut -d ":" -f 1

Update Item to Revision vs Revert to Revision

Update your working copy to the selected revision. Useful if you want to have your working copy reflect a time in the past, or if there have been further commits to the repository and you want to update your working copy one step at a time. It is best to update a whole directory in your working copy, not just one file, otherwise your working copy could be inconsistent. This is used to test a specific rev purpose, if your test has done, you can use this command to test another rev or use SVN Update to get HEAD

If you want to undo an earlier change permanently, use Revert to this revision instead.

-- from TSVN help doc

If you Update your working copy to an earlier rev, this is only affect your own working copy, after you do some change, and want to commit, you will fail,TSVN will alert you to update your WC to latest revision first If you Revert to a rev, you can commit to repository.everyone will back to the rev after they do an update.

How do I make an attributed string using Swift?

I did a function that takes array of strings and returns attributed string with the attributes you give.

func createAttributedString(stringArray: [String], attributedPart: Int, attributes: [NSAttributedString.Key: Any]) -> NSMutableAttributedString? {
    let finalString = NSMutableAttributedString()
    for i in 0 ..< stringArray.count {
        var attributedString = NSMutableAttributedString(string: stringArray[i], attributes: nil)
        if i == attributedPart {
            attributedString = NSMutableAttributedString(string: attributedString.string, attributes: attributes)
            finalString.append(attributedString)
        } else {
            finalString.append(attributedString)
        }
    }
    return finalString
}

In the example above you specify what part of string you want to get attributed with attributedPart: Int

And then you give the attributes for it with attributes: [NSAttributedString.Key: Any]

USE EXAMPLE

if let attributedString = createAttributedString(stringArray: ["Hello ", "how ", " are you?"], attributedPart: 2, attributes: [NSAttributedString.Key.foregroundColor: UIColor.systemYellow]) {
      myLabel.attributedText = attributedString
}

Will do:

getContext is not a function

Actually we get this error also when we create canvas in javascript as below.

document.createElement('canvas');

Here point to be noted we have to provide argument name correctly as 'canvas' not anything else.

Thanks

Convert any object to a byte[]

Using Encoding.UTF8.GetBytes is faster than using MemoryStream. Here, I am using NewtonsoftJson to convert input object to JSON string and then getting bytes from JSON string.

byte[] SerializeObject(object value) =>Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value));

Benchmark for @Daniel DiPaolo's version with this version

Method                    |     Mean |     Error |    StdDev |   Median |  Gen 0 | Allocated |
--------------------------|----------|-----------|-----------|----------|--------|-----------| 
ObjectToByteArray         | 4.983 us | 0.1183 us | 0.2622 us | 4.887 us | 0.9460 |    3.9 KB |
ObjectToByteArrayWithJson | 1.548 us | 0.0309 us | 0.0690 us | 1.528 us | 0.3090 |   1.27 KB |

How to get a time zone from a location using latitude and longitude coordinates?

For those of us using Javascript and looking to get a timezone from a zip code via Google APIs, here is one method.

  1. Fetch the lat/lng via geolocation
  2. fetch the timezone by pass that into the timezone API.
    • Using Luxon here for timezone conversion.

Note: my understanding is that zipcodes are not unique across countries, so this is likely best suited for use in the USA.

const googleMapsClient; // instantiate your client here
const zipcode = '90210'
const myDateThatNeedsTZAdjustment; // define your date that needs adjusting
// fetch lat/lng from google api by zipcode
const geocodeResponse = await googleMapsClient.geocode({ address: zipcode }).asPromise();
if (geocodeResponse.json.status === 'OK') {
  lat = geocodeResponse.json.results[0].geometry.location.lat;
  lng = geocodeResponse.json.results[0].geometry.location.lng;
} else {
  console.log('Geocode was not successful for the following reason: ' + status);
}

// prepare lat/lng and timestamp of profile created_at to fetch time zone
const location = `${lat},${lng}`;
const timestamp = new Date().valueOf() / 1000;
const timezoneResponse = await googleMapsClient
  .timezone({ location: location, timestamp: timestamp })
  .asPromise();

const timeZoneId = timezoneResponse.json.timeZoneId;
// adjust by setting timezone
const timezoneAdjustedDate = DateTime.fromJSDate(
  myDateThatNeedsTZAdjustment
).setZone(timeZoneId);

Bootstrap Carousel Full Screen

You can do it without forcing html and body to me 100% height. Use view port height instead. And with mouse wheel control too.

_x000D_
_x000D_
function debounce(func, wait, immediate) {_x000D_
  var timeout;_x000D_
  return function() {_x000D_
    var context = this,_x000D_
      args = arguments;_x000D_
    var later = function() {_x000D_
      timeout = null;_x000D_
      if (!immediate) func.apply(context, args);_x000D_
    };_x000D_
    var callNow = immediate && !timeout;_x000D_
    clearTimeout(timeout);_x000D_
    timeout = setTimeout(later, wait);_x000D_
    if (callNow) func.apply(context, args);_x000D_
  };_x000D_
}_x000D_
_x000D_
var slider = document.getElementById("demo");_x000D_
var onScroll = debounce(function(direction) {_x000D_
  //console.log(direction);_x000D_
  if (direction == false) {_x000D_
   $('.carousel-control-next').click();_x000D_
  } else {_x000D_
   $('.carousel-control-prev').click();_x000D_
  }_x000D_
}, 100, true);_x000D_
_x000D_
slider.addEventListener("wheel", function(e) {_x000D_
  e.preventDefault();_x000D_
  var delta;_x000D_
  if (event.wheelDelta) {_x000D_
    delta = event.wheelDelta;_x000D_
  } else {_x000D_
    delta = -1 * event.deltaY;_x000D_
  }_x000D_
_x000D_
  onScroll(delta >= 0);_x000D_
});
_x000D_
.carousel-item {_x000D_
  height: 100vh;_x000D_
  background: #212121;_x000D_
}_x000D_
_x000D_
.carousel-control-next,_x000D_
.carousel-control-prev {_x000D_
  width: 8% !important;_x000D_
}_x000D_
_x000D_
.carousel-item.active,_x000D_
.carousel-item-left,_x000D_
.carousel-item-right {_x000D_
  display: flex !important;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
.carousel-item h1 {_x000D_
    color: #fff;_x000D_
    font-size: 72px;_x000D_
    padding: 0 10%;_x000D_
 }
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div id="demo" class="carousel slide" data-ride="carousel" data-interval="false">_x000D_
_x000D_
  <!-- The slideshow -->_x000D_
  <div class="carousel-inner">_x000D_
    <div class="carousel-item active">_x000D_
      <h1 class="display-1 text-center">Lorem ipsum dolor sit amet adipisicing</h1>_x000D_
    </div>_x000D_
    <div class="carousel-item">_x000D_
      <h1 class="display-1 text-center">Inventore omnis odio, dolore culpa atque?</h1>_x000D_
    </div>_x000D_
    <div class="carousel-item">_x000D_
     <h1 class="display-1 text-center">Lorem ipsum dolor sit</h1>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <!-- Left and right controls -->_x000D_
  <a class="carousel-control-prev" href="#demo" data-slide="prev">_x000D_
    <span class="carousel-control-prev-icon"></span>_x000D_
  </a>_x000D_
  <a class="carousel-control-next" href="#demo" data-slide="next">_x000D_
    <span class="carousel-control-next-icon"></span>_x000D_
  </a>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

I don't think this is allowed by most browsers for security reasons, in a pure JavaScript context as the question asks.

In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?

  • "Final" denotes that something cannot be changed. You usually want to use this on static variables that will hold the same value throughout the life of your program.
  • "Finally" is used in conjunction with a try/catch block. Anything inside of the "finally" clause will be executed regardless of if the code in the 'try' block throws an exception or not.
  • "Finalize" is called by the JVM before an object is about to be garbage collected.

How to easily consume a web service from PHP

Well, those features are specific to a tool that you are using for development in those languages.

You wouldn't have those tools if (for example) you were using notepad to write code. So, maybe you should ask the question for the tool you are using.

For PHP: http://webservices.xml.com/pub/a/ws/2004/03/24/phpws.html

Kotlin - How to correctly concatenate a String

There are various way to concatenate strings in kotlin Example -

a = "Hello" , b= "World"
  1. Using + operator a+b

  2. Using plus() operator

    a.plus(b)

Note - + is internally converted to .plus() method only

In above 2 methods, a new string object is created as strings are immutable. if we want to modify the existing string, we can use StringBuilder

StringBuilder str = StringBuilder("Hello").append("World")

How to align this span to the right of the div?

If you can modify the HTML: http://jsfiddle.net/8JwhZ/3/

<div class="title">
  <span class="name">Cumulative performance</span>
  <span class="date">20/02/2011</span>
</div>

.title .date { float:right }
.title .name { float:left }

Change Input to Upper Case

This answer has a problem:

style="text-transform: uppercase"

it also converts the place holder word to upper case which is inconvenient

placeholder="first name"

when rendering the input, it writes "first name" placeholder as uppercase

FIRST NAME

so i wrote something better:

onkeypress="this.value = this.value + event.key.toUpperCase(); return false;"

it works good!, but it has some side effects if your javascript code is complex,

hope it helps somebody to give him/her an idea to develop a better solution.

Show "loading" animation on button click

The best loading and blocking that particular div for ajax call until it succeeded is Blockui

go through this link http://www.malsup.com/jquery/block/#element

example usage:

 <span class="no-display smallLoader"><img src="/images/loader-small.png" /></span>

script

jQuery.ajax(
{   
 url: site_path+"/restaurantlist/addtocart",
 type: "POST",
 success: function (data) {
   jQuery("#id").unblock(); 
},
beforeSend:function (data){
    jQuery("#id").block({ 
    message: jQuery(".smallLoader").html(), 
    css: { 
         border: 'none', 
         backgroundColor: 'none'
    },
    overlayCSS: { backgroundColor: '#afafaf' } 
    });

}
});

hope this helps really it is very interactive.

setting min date in jquery datepicker

basically if you already specify the year range there is no need to use mindate and maxdate if only year is required

Spring Boot REST service exception handling

New answer (2016-04-20)

Using Spring Boot 1.3.1.RELEASE

New Step 1 - It is easy and less intrusive to add the following properties to the application.properties:

spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false

Much easier than modifying the existing DispatcherServlet instance (as below)! - JO'

If working with a full RESTful Application, it is very important to disable the automatic mapping of static resources since if you are using Spring Boot's default configuration for handling static resources then the resource handler will be handling the request (it's ordered last and mapped to /** which means that it picks up any requests that haven't been handled by any other handler in the application) so the dispatcher servlet doesn't get a chance to throw an exception.


New Answer (2015-12-04)

Using Spring Boot 1.2.7.RELEASE

New Step 1 - I found a much less intrusive way of setting the "throExceptionIfNoHandlerFound" flag. Replace the DispatcherServlet replacement code below (Step 1) with this in your application initialization class:

@ComponentScan()
@EnableAutoConfiguration
public class MyApplication extends SpringBootServletInitializer {
    private static Logger LOG = LoggerFactory.getLogger(MyApplication.class);
    public static void main(String[] args) {
        ApplicationContext ctx = SpringApplication.run(MyApplication.class, args);
        DispatcherServlet dispatcherServlet = (DispatcherServlet)ctx.getBean("dispatcherServlet");
        dispatcherServlet.setThrowExceptionIfNoHandlerFound(true);
    }

In this case, we're setting the flag on the existing DispatcherServlet, which preserves any auto-configuration by the Spring Boot framework.

One more thing I've found - the @EnableWebMvc annotation is deadly to Spring Boot. Yes, that annotation enables things like being able to catch all the controller exceptions as described below, but it also kills a LOT of the helpful auto-configuration that Spring Boot would normally provide. Use that annotation with extreme caution when you use Spring Boot.


Original Answer:

After a lot more research and following up on the solutions posted here (thanks for the help!) and no small amount of runtime tracing into the Spring code, I finally found a configuration that will handle all Exceptions (not Errors, but read on) including 404s.

Step 1 - tell SpringBoot to stop using MVC for "handler not found" situations. We want Spring to throw an exception instead of returning to the client a view redirect to "/error". To do this, you need to have an entry in one of your configuration classes:

// NEW CODE ABOVE REPLACES THIS! (2015-12-04)
@Configuration
public class MyAppConfig {
    @Bean  // Magic entry 
    public DispatcherServlet dispatcherServlet() {
        DispatcherServlet ds = new DispatcherServlet();
        ds.setThrowExceptionIfNoHandlerFound(true);
        return ds;
    }
}

The downside of this is that it replaces the default dispatcher servlet. This hasn't been a problem for us yet, with no side effects or execution problems showing up. If you're going to do anything else with the dispatcher servlet for other reasons, this is the place to do them.

Step 2 - Now that spring boot will throw an exception when no handler is found, that exception can be handled with any others in a unified exception handler:

@EnableWebMvc
@ControllerAdvice
public class ServiceExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    ResponseEntity<Object> handleControllerException(HttpServletRequest req, Throwable ex) {
        ErrorResponse errorResponse = new ErrorResponse(ex);
        if(ex instanceof ServiceException) {
            errorResponse.setDetails(((ServiceException)ex).getDetails());
        }
        if(ex instanceof ServiceHttpException) {
            return new ResponseEntity<Object>(errorResponse,((ServiceHttpException)ex).getStatus());
        } else {
            return new ResponseEntity<Object>(errorResponse,HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @Override
    protected ResponseEntity<Object> handleNoHandlerFoundException(NoHandlerFoundException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        Map<String,String> responseBody = new HashMap<>();
        responseBody.put("path",request.getContextPath());
        responseBody.put("message","The URL you have reached is not in service at this time (404).");
        return new ResponseEntity<Object>(responseBody,HttpStatus.NOT_FOUND);
    }
    ...
}

Keep in mind that I think the "@EnableWebMvc" annotation is significant here. It seems that none of this works without it. And that's it - your Spring boot app will now catch all exceptions, including 404s, in the above handler class and you may do with them as you please.

One last point - there doesn't seem to be a way to get this to catch thrown Errors. I have a wacky idea of using aspects to catch errors and turn them into Exceptions that the above code can then deal with, but I have not yet had time to actually try implementing that. Hope this helps someone.

Any comments/corrections/enhancements will be appreciated.

Using LINQ to remove elements from a List<T>

To keep the code fluent (if code optimisation is not crucial) and you would need to do some further operations on the list:

authorsList = authorsList.Where(x => x.FirstName != "Bob").<do_some_further_Linq>;

or

authorsList = authorsList.Where(x => !setToRemove.Contains(x)).<do_some_further_Linq>;

How to remove new line characters from data rows in mysql?

UPDATE mytable SET title=TRIM(REPLACE(REPLACE(title, "\n", ""), "\t", ""));

Drawing Circle with OpenGL

#include <Windows.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define window_width  1080  
#define window_height 720 
void drawFilledSun(){
    //static float angle;
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    glTranslatef(0, 0, -10);
    int i, x, y;
    double radius = 0.30;
    //glColor3ub(253, 184, 19);     
    glColor3ub(255, 0, 0);
    double twicePi = 2.0 * 3.142;
    x = 0, y = 0;
    glBegin(GL_TRIANGLE_FAN); //BEGIN CIRCLE
    glVertex2f(x, y); // center of circle
    for (i = 0; i <= 20; i++)   {
        glVertex2f (
            (x + (radius * cos(i * twicePi / 20))), (y + (radius * sin(i * twicePi / 20)))
            );
    }
    glEnd(); //END
}
void DrawCircle(float cx, float cy, float r, int num_segments) {
    glBegin(GL_LINE_LOOP);
    for (int ii = 0; ii < num_segments; ii++)   {
        float theta = 2.0f * 3.1415926f * float(ii) / float(num_segments);//get the current angle 
        float x = r * cosf(theta);//calculate the x component 
        float y = r * sinf(theta);//calculate the y component 
        glVertex2f(x + cx, y + cy);//output vertex 
    }
    glEnd();
}
void main_loop_function() {
    int c;
    drawFilledSun();
    DrawCircle(0, 0, 0.7, 100);
    glutSwapBuffers();
    c = getchar();
}
void GL_Setup(int width, int height) {
    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glEnable(GL_DEPTH_TEST);
    gluPerspective(45, (float)width / height, .1, 100);
    glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitWindowSize(window_width, window_height);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
    glutCreateWindow("GLUT Example!!!");
    glutIdleFunc(main_loop_function);
    GL_Setup(window_width, window_height);
    glutMainLoop();
}

This is what I did. I hope this helps. Two types of circle are here. Filled and unfilled.

Initialising a multidimensional array in Java

You can declare multi dimensional arrays like :

// 4 x 5 String arrays, all Strings are null
// [0] -> [null,null,null,null,null]
// [1] -> [null,null,null,null,null]
// [2] -> [null,null,null,null,null]
// [3] -> [null,null,null,null,null]

String[][] sa1 = new String[4][5];
for(int i = 0; i < sa1.length; i++) {           // sa1.length == 4
    for (int j = 0; j < sa1[i].length; j++) {     //sa1[i].length == 5
        sa1[i][j] = "new String value";
    }
}


// 5 x 0  All String arrays are null
// [null]
// [null]
// [null]
// [null]
// [null]
String[][] sa2 = new String[5][];
for(int i = 0; i < sa2.length; i++) {
    String[] anon = new String[ /* your number here */];
    // or String[] anon = new String[]{"I'm", "a", "new", "array"};
    sa2[i] = anon;
}

// [0] -> ["I'm","in","the", "0th", "array"]
// [1] -> ["I'm", "in", "another"]
String[][] sa3 = new String[][]{ {"I'm","in","the", "0th", "array"},{"I'm", "in", "another"}};

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

xmlns:android

Defines the Android namespace. This attribute should always be set to "http://schemas.android.com/apk/res/android".

refer https://developer.android.com/guide/topics/manifest/manifest-element#nspace

Spring MVC: Complex object as GET @RequestParam

While answers that refer to @ModelAttribute, @RequestParam, @PathParam and the likes are valid, there is a small gotcha I ran into. The resulting method parameter is a proxy that Spring wraps around your DTO. So, if you attempt to use it in a context that requires your own custom type, you may get some unexpected results.

The following will not work:

@GetMapping(produces = APPLICATION_JSON_VALUE)
public ResponseEntity<CustomDto> request(@ModelAttribute CustomDto dto) {
    return ResponseEntity.ok(dto);
}

In my case, attempting to use it in Jackson binding resulted in a com.fasterxml.jackson.databind.exc.InvalidDefinitionException.

You will need to create a new object from the dto.

How do you run a script on login in *nix?

If you wish to run one script and only one script, you can make it that users default shell.

echo "/usr/bin/uptime" >> /etc/shells
vim /etc/passwd  
  * username:x:uid:grp:message:homedir:/usr/bin/uptime

can have interesting effects :) ( its not secure tho, so don't trust it too much. nothing like setting your default shell to be a script that wipes your drive. ... although, .. I can imagine a scenario where that could be amazingly useful )

Generate random array of floats between a range

Why not use a list comprehension?

In Python 2

ran_floats = [random.uniform(low,high) for _ in xrange(size)]

In Python 3, range works like xrange(ref)

ran_floats = [random.uniform(low,high) for _ in range(size)]

jQuery, checkboxes and .is(":checked")

$( "#checkbox" ).change(function() {
    if($(this).is(":checked")){
        alert('hi');
    }

});

Parse usable Street Address, City, State, Zip from a string

After the advice here, I have devised the following function in VB which creates passable, although not always perfect (if a company name and a suite line are given, it combines the suite and city) usable data. Please feel free to comment/refactor/yell at me for breaking one of my own rules, etc.:

Public Function parseAddress(ByVal input As String) As Collection
    input = input.Replace(",", "")
    input = input.Replace("  ", " ")
    Dim splitString() As String = Split(input)
    Dim streetMarker() As String = New String() {"street", "st", "st.", "avenue", "ave", "ave.", "blvd", "blvd.", "highway", "hwy", "hwy.", "box", "road", "rd", "rd.", "lane", "ln", "ln.", "circle", "circ", "circ.", "court", "ct", "ct."}
    Dim address1 As String
    Dim address2 As String = ""
    Dim city As String
    Dim state As String
    Dim zip As String
    Dim streetMarkerIndex As Integer

    zip = splitString(splitString.Length - 1).ToString()
    state = splitString(splitString.Length - 2).ToString()
    streetMarkerIndex = getLastIndexOf(splitString, streetMarker) + 1
    Dim sb As New StringBuilder

    For counter As Integer = streetMarkerIndex To splitString.Length - 3
        sb.Append(splitString(counter) + " ")
    Next counter
    city = RTrim(sb.ToString())
    Dim addressIndex As Integer = 0

    For counter As Integer = 0 To streetMarkerIndex
        If IsNumeric(splitString(counter)) _
            Or splitString(counter).ToString.ToLower = "po" _
            Or splitString(counter).ToString().ToLower().Replace(".", "") = "po" Then
                addressIndex = counter
            Exit For
        End If
    Next counter

    sb = New StringBuilder
    For counter As Integer = addressIndex To streetMarkerIndex - 1
        sb.Append(splitString(counter) + " ")
    Next counter

    address1 = RTrim(sb.ToString())

    sb = New StringBuilder

    If addressIndex = 0 Then
        If splitString(splitString.Length - 2).ToString() <> splitString(streetMarkerIndex + 1) Then
            For counter As Integer = streetMarkerIndex To splitString.Length - 2
                sb.Append(splitString(counter) + " ")
            Next counter
        End If
    Else
        For counter As Integer = 0 To addressIndex - 1
            sb.Append(splitString(counter) + " ")
        Next counter
    End If
    address2 = RTrim(sb.ToString())

    Dim output As New Collection
    output.Add(address1, "Address1")
    output.Add(address2, "Address2")
    output.Add(city, "City")
    output.Add(state, "State")
    output.Add(zip, "Zip")
    Return output
End Function

Private Function getLastIndexOf(ByVal sArray As String(), ByVal checkArray As String()) As Integer
    Dim sourceIndex As Integer = 0
    Dim outputIndex As Integer = 0
    For Each item As String In checkArray
        For Each source As String In sArray
            If source.ToLower = item.ToLower Then
                outputIndex = sourceIndex
                If item.ToLower = "box" Then
                    outputIndex = outputIndex + 1
                End If
            End If
            sourceIndex = sourceIndex + 1
        Next
        sourceIndex = 0
    Next
    Return outputIndex
End Function

Passing the parseAddress function "A. P. Croll & Son 2299 Lewes-Georgetown Hwy, Georgetown, DE 19947" returns:

2299 Lewes-Georgetown Hwy
A. P. Croll & Son  
Georgetown
DE
19947

Angular 2 execute script after template render

ngAfterViewInit() of AppComponent is a lifecycle callback Angular calls after the root component and it's children have been rendered and it should fit for your purpose.

See also https://angular.io/guide/lifecycle-hooks

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

I experienced this error when trying to embed an iframe and then opening the site with Brave. The error went away when I changed to "Shields Down" for the site in question. Obviously, this is not a full solution, since anyone else visiting the site with Brave will run into the same issue. To actually resolve it I would need to do one of the other things listed on this page. But at least I now know where the problem lies.

Curl Command to Repeat URL Request

You could use URL sequence substitution with a dummy query string (if you want to use CURL and save a few keystrokes):

curl http://www.myurl.com/?[1-20]

If you have other query strings in your URL, assign the sequence to a throwaway variable:

curl http://www.myurl.com/?myVar=111&fakeVar=[1-20]

Check out the URL section on the man page: https://curl.haxx.se/docs/manpage.html

Iterator over HashMap in Java

Map<String, Car> carMap = new HashMap<String, Car>(16, (float) 0.75);

// there is no iterator for Maps, but there are methods to do this.

        Set<String> keys = carMap.keySet(); // returns a set containing all the keys
        for(String c : keys)
        {

            System.out.println(c);
        }

        Collection<Car> values = carMap.values(); // returns a Collection with all the objects
        for(Car c : values)
        {
            System.out.println(c.getDiscription());
        }
        /*keySet and the values methods serve as “views” into the Map.
          The elements in the set and collection are merely references to the entries in the map, 
          so any changes made to the elements in the set or collection are reflected in the map, and vice versa.*/

        //////////////////////////////////////////////////////////
        /*The entrySet method returns a Set of Map.Entry objects. 
          Entry is an inner interface in the Map interface.
          Two of the methods specified by Map.Entry are getKey and getValue.
          The getKey method returns the key and getValue returns the value.*/

        Set<Map.Entry<String, Car>> cars = carMap.entrySet(); 
        for(Map.Entry<String, Car> e : cars)
        {
            System.out.println("Keys = " + e.getKey());
            System.out.println("Values = " + e.getValue().getDiscription() + "\n");

        }

What is the best way to test for an empty string with jquery-out-of-the-box?

if((a.trim()=="")||(a=="")||(a==null))
{
    //empty condition
}
else
{
    //working condition
}

How to send Request payload to REST API in java?

I tried with a rest client.

Headers :

  • POST /r/gerrit/rpc/ChangeDetailService HTTP/1.1
  • Host: git.eclipse.org
  • User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0
  • Accept: application/json
  • Accept-Language: null
  • Accept-Encoding: gzip,deflate,sdch
  • accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
  • Content-Type: application/json; charset=UTF-8
  • Content-Length: 73
  • Connection: keep-alive

it works fine. I retrieve 200 OK with a good body.

Why do you set a status code in your request? and multiple declaration "Accept" with Accept:application/json,application/json,application/jsonrequest. just a statement is enough.

Angular2 use [(ngModel)] with [ngModelOptions]="{standalone: true}" to link to a reference to model's property

For me the code:

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

throws error, but I added name attribute to input:

_x000D_
_x000D_
<form (submit)="addTodo()">_x000D_
  <input type="text" [(ngModel)]="text" name="text">_x000D_
</form>
_x000D_
_x000D_
_x000D_

and it started to work.

Hard reset of a single file

To revert to upstream/master do:

git checkout upstream/master -- myfile.txt

Is there a way to have printf() properly print out an array (of floats, say)?

I don't think there is a way to print array for you in printf. "printf" function has no idea how long your array is.

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

What does the clearfix class do in css?

How floats work

When floating elements exist on the page, non-floating elements wrap around the floating elements, similar to how text goes around a picture in a newspaper. From a document perspective (the original purpose of HTML), this is how floats work.

float vs display:inline

Before the invention of display:inline-block, websites use float to set elements beside each other. float is preferred over display:inline since with the latter, you can't set the element's dimensions (width and height) as well as vertical paddings (top and bottom) - which floated elements can do since they're treated as block elements.

Float problems

The main problem is that we're using float against its intended purpose.

Another is that while float allows side-by-side block-level elements, floats do not impart shape to its container. It's like position:absolute, where the element is "taken out of the layout". For instance, when an empty container contains a floating 100px x 100px <div>, the <div> will not impart 100px in height to the container.

Unlike position:absolute, it affects the content that surrounds it. Content after the floated element will "wrap" around the element. It starts by rendering beside it and then below it, like how newspaper text would flow around an image.

Clearfix to the rescue

What clearfix does is to force content after the floats or the container containing the floats to render below it. There are a lot of versions for clear-fix, but it got its name from the version that's commonly being used - the one that uses the CSS property clear.

Examples

Here are several ways to do clearfix , depending on the browser and use case. One only needs to know how to use the clear property in CSS and how floats render in each browser in order to achieve a perfect cross-browser clear-fix.

What you have

Your provided style is a form of clearfix with backwards compatibility. I found an article about this clearfix. It turns out, it's an OLD clearfix - still catering the old browsers. There is a newer, cleaner version of it in the article also. Here's the breakdown:

  • The first clearfix you have appends an invisible pseudo-element, which is styled clear:both, between the target element and the next element. This forces the pseudo-element to render below the target, and the next element below the pseudo-element.

  • The second one appends the style display:inline-block which is not supported by earlier browsers. inline-block is like inline but gives you some properties that block elements, like width, height as well as vertical padding. This was targeted for IE-MAC.

  • This was the reapplication of display:block due to IE-MAC rule above. This rule was "hidden" from IE-MAC.

All in all, these 3 rules keep the .clearfix working cross-browser, with old browsers in mind.