Programs & Examples On #Bank

Is there an API to get bank transaction and bank balance?

Also check out the open financial exchange (ofx) http://www.ofx.net/

This is what apps like quicken, ms money etc use.

Add / remove input field dynamically with jQuery

you can do it as follow:

 $("#addButton").click(function () {

    if(counter>10){
            alert("Only 10 textboxes allow");
            return false;
    }   

    var newTextBoxDiv = $(document.createElement('div'))
         .attr("id", 'TextBoxDiv' + counter);

    newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
          '<input type="text" name="textbox' + counter + 
          '" id="textbox' + counter + '" value="" >');

    newTextBoxDiv.appendTo("#TextBoxesGroup");


    counter++;
     });

     $("#removeButton").click(function () {
    if(counter==1){
          alert("No more textbox to remove");
          return false;
       }   

    counter--;

        $("#TextBoxDiv" + counter).remove();

     });

refer live demo http://www.mkyong.com/jquery/how-to-add-remove-textbox-dynamically-with-jquery/

Javascript array declaration: new Array(), new Array(3), ['a', 'b', 'c'] create arrays that behave differently

Arrays have numerical indexes. So,

a = new Array();
a['a1']='foo';
a['a2']='bar';

and

b = new Array(2);
b['b1']='foo';
b['b2']='bar';

are not adding elements to the array, but adding .a1 and .a2 properties to the a object (arrays are objects too). As further evidence, if you did this:

a = new Array();
a['a1']='foo';
a['a2']='bar';
console.log(a.length);   // outputs zero because there are no items in the array

Your third option:

c=['c1','c2','c3'];

is assigning the variable c an array with three elements. Those three elements can be accessed as: c[0], c[1] and c[2]. In other words, c[0] === 'c1' and c.length === 3.

Javascript does not use its array functionality for what other languages call associative arrays where you can use any type of key in the array. You can implement most of the functionality of an associative array by just using an object in javascript where each item is just a property like this.

a = {};
a['a1']='foo';
a['a2']='bar';

It is generally a mistake to use an array for this purpose as it just confuses people reading your code and leads to false assumptions about how the code works.

db.collection is not a function when using MongoClient v3.0

I have MongoDB shell version v3.6.4, below code use mongoclient, It's good for me:

var MongoClient = require('mongodb').MongoClient,
assert = require('assert');
var url = 'mongodb://localhost:27017/video';
MongoClient.connect(url,{ useNewUrlParser: true }, function(err, client) 
{
assert.equal(null, err);
console.log("Successfully connected to server");
var db = client.db('video');
// Find some documents in our collection
db.collection('movies').find({}).toArray(function(err, docs) {
// Print the documents returned
docs.forEach(function(doc) {
console.log(doc.title);
});
// Close the DB
client.close();
});
// Declare success
console.log("Called find()");
 });

Which ORM should I use for Node.js and MySQL?

First off, please note that I haven't used either of them (but have used Node.js).

Both libraries are documented quite well and have a stable API. However, persistence.js seems to be used in more projects. I don't know if all of them still use it, though.

The developer of sequelize sometimes blogs about it at blog.depold.com. When you'd like to use primary keys as foreign keys, you'll need the patch that's described in this blog post. If you'd like help for persistence.js there is a google group devoted to it.

From the examples I gather that sequelize is a bit more JavaScript-like (more sugar) than persistance.js but has support for fewer datastores (only MySQL, while persistance.js can even use in-browser stores).

I think that sequelize might be the way to go for you, as you only need MySQL support. However, if you need some convenient features (for instance search) or want to use a different database later on you'd need to use persistence.js.

Correct way to use get_or_create?

Following @Tobu answer and @mipadi comment, in a more pythonic way, if not interested in the created flag, I would use:

customer.source, _ = Source.objects.get_or_create(name="Website")

How to set upload_max_filesize in .htaccess?

If your web server is running php5, I believe you must use php5_value. This resolved the same error I received when using php_value.

How can I run another application within a panel of my C# program?

If you want to run notepad inside your app you would probably be better of with a text editor component. There's obviously a basic text box that comes with WinForms, but I suspect more advanced components that offer Notepad functionality (or better) can be found on the interweb.

Tracking the script execution time in PHP

I created an ExecutionTime class out of phihag answer that you can use out of box:

class ExecutionTime
{
     private $startTime;
     private $endTime;

     public function start(){
         $this->startTime = getrusage();
     }

     public function end(){
         $this->endTime = getrusage();
     }

     private function runTime($ru, $rus, $index) {
         return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
     -  ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
     }    

     public function __toString(){
         return "This process used " . $this->runTime($this->endTime, $this->startTime, "utime") .
        " ms for its computations\nIt spent " . $this->runTime($this->endTime, $this->startTime, "stime") .
        " ms in system calls\n";
     }
 }

usage:

$executionTime = new ExecutionTime();
$executionTime->start();
// code
$executionTime->end();
echo $executionTime;

Note: In PHP 5, the getrusage function only works in Unix-oid systems. Since PHP 7, it also works on Windows.

How to validate a date?

I recommend to use moment.js. Only providing date to moment will validate it, no need to pass the dateFormat.

var date = moment("2016-10-19");

And then date.isValid() gives desired result.

Se post HERE

Iterate over a Javascript associative array in sorted order

You can use the keys function from the underscore.js library to get the keys, then the sort() array method to sort them:

var sortedKeys = _.keys(dict).sort();

The keys function in the underscore's source code:

// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
    if (obj !== Object(obj)) throw new TypeError('Invalid object');
    var keys = [];
    for (var key in obj) if (_.has(obj, key)) keys.push(key);
    return keys;
};    

// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
    return hasOwnProperty.call(obj, key);
};

C read file line by line

FILE* filePointer;
int bufferLength = 255;
char buffer[bufferLength];

filePointer = fopen("file.txt", "r");

while(fgets(buffer, bufferLength, filePointer)) {
    printf("%s\n", buffer);
}

fclose(filePointer);

Difference between Ctrl+Shift+F and Ctrl+I in Eclipse

Ctrl+Shift+F formats the selected line(s) or the whole source code if you haven't selected any line(s) as per the formatter specified in your Eclipse, while Ctrl+I gives proper indent to the selected line(s) or the current line if you haven't selected any line(s).

When is std::weak_ptr useful?

std::weak_ptr is a very good way to solve the dangling pointer problem. By just using raw pointers it is impossible to know if the referenced data has been deallocated or not. Instead, by letting a std::shared_ptr manage the data, and supplying std::weak_ptr to users of the data, the users can check validity of the data by calling expired() or lock().

You could not do this with std::shared_ptr alone, because all std::shared_ptr instances share the ownership of the data which is not removed before all instances of std::shared_ptr are removed. Here is an example of how to check for dangling pointer using lock():

#include <iostream>
#include <memory>

int main()
{
    // OLD, problem with dangling pointer
    // PROBLEM: ref will point to undefined data!

    int* ptr = new int(10);
    int* ref = ptr;
    delete ptr;

    // NEW
    // SOLUTION: check expired() or lock() to determine if pointer is valid

    // empty definition
    std::shared_ptr<int> sptr;

    // takes ownership of pointer
    sptr.reset(new int);
    *sptr = 10;

    // get pointer to data without taking ownership
    std::weak_ptr<int> weak1 = sptr;

    // deletes managed object, acquires new pointer
    sptr.reset(new int);
    *sptr = 5;

    // get pointer to new data without taking ownership
    std::weak_ptr<int> weak2 = sptr;

    // weak1 is expired!
    if(auto tmp = weak1.lock())
        std::cout << *tmp << '\n';
    else
        std::cout << "weak1 is expired\n";

    // weak2 points to new data (5)
    if(auto tmp = weak2.lock())
        std::cout << *tmp << '\n';
    else
        std::cout << "weak2 is expired\n";
}

How to validate phone numbers using regex

Java generates REGEX for valid phone numbers

Another alternative is to let Java generate a REGEX that macthes all variations of phone numbers read from a list. This means that the list called validPhoneNumbersFormat, seen below in code context, is deciding which phone number format is valid.

Note: This type of algorithm would work for any language handling regular expressions.

Code snippet that generates the REGEX:

Set<String> regexSet = uniqueValidPhoneNumbersFormats.stream()
        .map(s -> s.replaceAll("\\+", "\\\\+"))
        .map(s -> s.replaceAll("\\d", "\\\\d"))
        .map(s -> s.replaceAll("\\.", "\\\\."))
        .map(s -> s.replaceAll("([\\(\\)])", "\\\\$1"))
        .collect(Collectors.toSet());

String regex = String.join("|", regexSet);

Code snippet in context:

public class TestBench {

    public static void main(String[] args) {
        List<String> validPhoneNumbersFormat = Arrays.asList(
                "1-234-567-8901",
                "1-234-567-8901 x1234",
                "1-234-567-8901 ext1234",
                "1 (234) 567-8901",
                "1.234.567.8901",
                "1/234/567/8901",
                "12345678901",
                "+12345678901",
                "(234) 567-8901 ext. 123",
                "+1 234-567-8901 ext. 123",
                "1 (234) 567-8901 ext. 123",
                "00 1 234-567-8901 ext. 123",
                "+210-998-234-01234",
                "210-998-234-01234",
                "+21099823401234",
                "+210-(998)-(234)-(01234)",
                "(+351) 282 43 50 50",
                "90191919908",
                "555-8909",
                "001 6867684",
                "001 6867684x1",
                "1 (234) 567-8901",
                "1-234-567-8901 x1234",
                "1-234-567-8901 ext1234",
                "1-234 567.89/01 ext.1234",
                "1(234)5678901x1234",
                "(123)8575973",
                "(0055)(123)8575973"
        );

        Set<String> uniqueValidPhoneNumbersFormats = new LinkedHashSet<>(validPhoneNumbersFormat);

        List<String> invalidPhoneNumbers = Arrays.asList(
                "+210-99A-234-01234",       // FAIL
                "+210-999-234-0\"\"234",    // FAIL
                "+210-999-234-02;4",        // FAIL
                "-210+998-234-01234",       // FAIL
                "+210-998)-(234-(01234"     // FAIL
        );
        List<String> invalidAndValidPhoneNumbers = new ArrayList<>();
        invalidAndValidPhoneNumbers.addAll(invalidPhoneNumbers);
        invalidAndValidPhoneNumbers.addAll(uniqueValidPhoneNumbersFormats);

        Set<String> regexSet = uniqueValidPhoneNumbersFormats.stream()
                .map(s -> s.replaceAll("\\+", "\\\\+"))
                .map(s -> s.replaceAll("\\d", "\\\\d"))
                .map(s -> s.replaceAll("\\.", "\\\\."))
                .map(s -> s.replaceAll("([\\(\\)])", "\\\\$1"))
                .collect(Collectors.toSet());

        String regex = String.join("|", regexSet);

        List<String> result = new ArrayList<>();
        Pattern pattern = Pattern.compile(regex);
        for (String phoneNumber : invalidAndValidPhoneNumbers) {
            Matcher matcher = pattern.matcher(phoneNumber);
            if(matcher.matches()) {
                result.add(matcher.group());
            }
        }

        // Output:
        if(uniqueValidPhoneNumbersFormats.size() == result.size()) {
            System.out.println("All valid numbers was matched!\n");
        }    
        result.forEach(System.out::println); 
    }

}

Output:

All valid numbers was matched!

1-234-567-8901
1-234-567-8901 x1234
1-234-567-8901 ext1234
...
...
...

convert strtotime to date time format in php

FORMAT DATE STRTOTIME OR TIME STRING TO DATE FORMAT
$unixtime = 1307595105;
function formatdate($unixtime) 
{ 
        return $time = date("m/d/Y h:i:s",$unixtime);
} 

ORA-12154: TNS:could not resolve the connect identifier specified (PLSQL Developer)

Just wanted to add -- apparently this can also be caused by installing Instant Client for 10, then realizing you want the full install and installing it again in a parallel directory. I don't know why this broke it.

Fill remaining vertical space - only CSS

Flexbox solution

_x000D_
_x000D_
html, body {_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  width: 300px;_x000D_
  height: 100%;_x000D_
}_x000D_
_x000D_
.first {_x000D_
  height: 50px;_x000D_
}_x000D_
_x000D_
.second {_x000D_
  flex-grow: 1;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="first" style="background:#b2efd8">First</div>_x000D_
  <div class="second" style="background:#80c7cd">Second</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to match hyphens with Regular Expression?

It’s less confusing to always use an escaped hyphen, so that it doesn't have to be positionally dependent. That’s a \- inside the bracketed character class.

But there’s something else to consider. Some of those enumerated characters should possibly be written differently. In some circumstances, they definitely should.

This comparison of regex flavors says that C? can use some of the simpler Unicode properties. If you’re dealing with Unicode, you should probably use the general category \p{L} for all possible letters, and maybe \p{Nd} for decimal numbers. Also, if you want to accomodate all that dash punctuation, not just HYPHEN-MINUS, you should use the \p{Pd} property. You might also want to write that sequence of whitespace characters simply as \s, assuming that’s not too general for you.

All together, that works out to apattern of [\p{L}\p{Nd}\p{Pd}!$*] to match any one character from that set.

I’d likely use that anyway, even if I didn’t plan on dealing with the full Unicode set, because it’s a good habit to get into, and because these things often grow beyond their original parameters. Now when you lift it to use in other code, it will still work correctly. If you hard-code all the characters, it won’t.

if statement checks for null but still throws a NullPointerException

The | and & check both the sides everytime.

if (str == null | str.length() == 0)

here we have high possibility to get NullPointerException

Logical || and && check the right hand side only if necessary.

but with logical operator

no chance to get NPE because it will not check RHS

Error "The input device is not a TTY"

For those who struggle with this error and git bash on Windows, just use PowerShell where -it works perfectly.

How to include clean target in Makefile?

By the way it is written, clean rule is invoked only if it is explicitly called:

make clean

I think it is better, than make clean every time. If you want to do this by your way, try this:

CXX = g++ -O2 -Wall

all: clean code1 code2

code1: code1.cc utilities.cc
   $(CXX) $^ -o $@

code2: code2.cc utilities.cc
   $(CXX) $^ -o $@

clean: 
    rm ...
    echo Clean done

make an html svg object also a clickable link

Would like to take credit for this but I found a solution here:

https://teamtreehouse.com/forum/how-do-you-make-a-svg-clickable

add the following to the css for the anchor:

a.svg {
  position: relative;
  display: inline-block; 
}
a.svg:after {
  content: ""; 
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left:0;
}


<a href="#" class="svg">
  <object data="random.svg" type="image/svg+xml">
    <img src="random.jpg" />
  </object>
</a>

Link works on the svg and on the fallback.

Stored procedure with default parameters

I'd do this one of two ways. Since you're setting your start and end dates in your t-sql code, i wouldn't ask for parameters in the stored proc

Option 1

Create Procedure [Test] AS
    DECLARE @StartDate varchar(10)
    DECLARE @EndDate varchar(10)
    Set @StartDate = '201620' --Define start YearWeek
    Set @EndDate  = (SELECT CAST(DATEPART(YEAR,getdate()) AS varchar(4)) + CAST(DATEPART(WEEK,getdate())-1 AS varchar(2)))

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Option 2

Create Procedure [Test] @StartDate varchar(10),@EndDate varchar(10) AS

SELECT 
*
FROM
    (SELECT DISTINCT [YEAR],[WeekOfYear] FROM [dbo].[DimDate] WHERE [Year]+[WeekOfYear] BETWEEN @StartDate AND @EndDate ) dimd
    LEFT JOIN [Schema].[Table1] qad ON (qad.[Year]+qad.[Week of the Year]) = (dimd.[Year]+dimd.WeekOfYear)

Then run exec test '2016-01-01','2016-01-25'

Turn a string into a valid filename?

Though you have to be careful. It is not clearly said in your intro, if you are looking only at latine language. Some words can become meaningless or another meaning if you sanitize them with ascii characters only.

imagine you have "forêt poésie" (forest poetry), your sanitization might give "fort-posie" (strong + something meaningless)

Worse if you have to deal with chinese characters.

"???" your system might end up doing "---" which is doomed to fail after a while and not very helpful. So if you deal with only files I would encourage to either call them a generic chain that you control or to keep the characters as it is. For URIs, about the same.

How to detect when keyboard is shown and hidden

Swift 4 - dd 20 october 2017

override func viewDidLoad() {
    [..]

    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear(_:)), name: Notification.Name.UIKeyboardWillHide, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(_:)), name: Notification.Name.UIKeyboardWillShow, object: nil)
}

@objc func keyboardWillAppear(_ notification: NSNotification) {
    if let userInfo = notification.userInfo, 
       let keyboardFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue).cgRectValue {
           let inset = keyboardFrame.height // if scrollView is not aligned to bottom of screen, subtract offset
           scrollView.contentInset.bottom = inset
           scrollView.scrollIndicatorInsets.bottom = inset
    }
}

@objc func keyboardWillDisappear(_ notification: NSNotification) {
    scrollView.contentInset.bottom = 0
    scrollView.scrollIndicatorInsets.bottom = 0
}

deinit {
    NotificationCenter.default.removeObserver(self)
}

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

This looks like a Json array list.Therefore its best to use ArrayList to handle the data. In your api end point add array list like this

 @GET("places/")
Call<ArrayList<Place>> getNearbyPlaces(@Query("latitude") String latitude, @Query("longitude") String longitude);

Using a dispatch_once singleton model in Swift

Per the Apple documentation, it has been repeated many times that the easiest way to do this in Swift is with a static type property:

class Singleton {
    static let sharedInstance = Singleton()
}

However, if you're looking for a way to perform additional setup beyond a simple constructor call, the secret is to use an immediately invoked closure:

class Singleton {
    static let sharedInstance: Singleton = {
        let instance = Singleton()
        // setup code
        return instance
    }()
}

This is guaranteed to be thread-safe and lazily initialized only once.

Getting "conflicting types for function" in C, why?

A C Function-Declaration Backgrounder

In C, function declarations don't work like they do in other languages: The C compiler itself doesn't search backward and forward in the file to find the function's declaration from the place you call it, and it doesn't scan the file multiple times to figure out the relationships either: The compiler only scans forward in the file exactly once, from top to bottom. Connecting function calls to function declarations is part of the linker's job, and is only done after the file is compiled down to raw assembly instructions.

This means that as the compiler scans forward through the file, the very first time the compiler encounters the name of a function, one of two things have to be the case: It either is seeing the function declaration itself, in which case the compiler knows exactly what the function is and what types it takes as arguments and what types it returns — or it's a call to the function, and the compiler has to guess how the function will eventually be declared.

(There's a third option, where the name is used in a function prototype, but we'll ignore that for now, since if you're seeing this problem in the first place, you're probably not using prototypes.)

History Lesson

In the earliest days of C, the fact that the compiler had to guess types wasn't really an issue: All of the types were more-or-less the same — pretty much everything was either an int or a pointer, and they were the same size. (In fact, in B, the language that preceded C, there were no types at all; everything was just an int or pointer and its type was determined solely by how you used it!) So the compiler could safely guess the behavior of any function just based on the number of parameters that were passed: If you passed two parameters, the compiler would push two things onto the call stack, and presumably the callee would have two arguments declared, and that would all line up. If you passed only one parameter but the function expected two, it would still sort-of work, and the second argument would just be ignored/garbage. If you passed three parameters and the function expected two, it would also still sort-of work, and the third parameter would be ignored and stomped on by the function's local variables. (Some old C code still expects these mismatched-argument rules will work, too.)

But having the compiler let you pass anything to anything isn't really a good way to design a programming language. It worked well in the early days because the early C programmers were mostly wizards, and they knew not to pass the wrong type to functions, and even if they did get the types wrong, there were always tools like lint that could do deeper double-checking of your C code and warn you about such things.

Fast-forward to today, and we're not quite in the same boat. C has grown up, and a lot of people are programming in it who aren't wizards, and to accommodate them (and to accommodate everyone else who regularly used lint anyway), the compilers have taken on many of the abilities that were previously part of lint — especially the part where they check your code to ensure it's type-safe. Early C compilers would let you write int foo = "hello"; and it would just blithely assign the pointer to the integer, and it was up to you to make sure you weren't doing anything stupid. Modern C compilers complain loudly when you get your types wrong, and that's a good thing.

Type Conflicts

So what's all this got to do with the mysterious conflicting-type error on the line of the function declaration? As I said above, C compilers still have to either know or guess what a name means the first time they see that name as they scan forward through the file: They can know what it means it if it's an actual function declaration itself (or a function "prototype," more on that shortly), but if it's just a call to the function, they have to guess. And, sadly, the guess is often wrong.

When the compiler saw your call to do_something(), it looked at how it was invoked, and it concluded that do_something() would eventually be declared like this:

int do_something(char arg1[], char arg2[])
{
    ...
}

Why did it conclude that? Because that's how you called it! (Some C compilers may conclude that it was int do_something(int arg1, int arg2), or simply int do_something(...), both of which are even farther from what you want, but the important point is that regardless of how the compiler guesses the types, it guesses them differently from what your actual function uses.)

Later on, as the compiler scans forward in the file, it sees your actual declaration of char *do_something(char *, char *). That function declaration isn't even close to the declaration that the compiler guessed, which means that the line where the compiler compiled the call was compiled wrong, and the program is just not going to work. So it rightly prints an error telling you that your code isn't going to work as written.

You might be wondering, "Why does it assume I'm returning an int?" Well, it assumes that type because there's no information to the contrary: printf() can take in any type in its variable arguments, so without a better answer, int is as good a guess as any. (Many early C compilers always assumed int for every unspecified type, and assumed you meant ... for the arguments for every function declared f() — not void — which is why many modern code standards recommend always putting void in for the arguments if there really aren't supposed to be any.)

The Fix

There are two common fixes for the function-declaration error.

The first solution, which is recommended by many other answers here, is to put a prototype in the source code above the place where the function is first called. A prototype looks just like the function's declaration, but it has a semicolon where the body should be:

char *do_something(char *dest, const char *src);

By putting the prototype first, the compiler then knows what the function will eventually look like, so it doesn't have to guess. By convention, programmers often put prototypes at the top of the file, just under the #include statements, to ensure that they'll always be defined before any potential usages of them.

The other solution, which also shows up in some real-world code, is to simply reorder your functions so that the function declarations are always before anything that calls them! You could move the entire char *do_something(char *dest, const char *src) { ... } function above the first call to it, and the compiler then would know exactly what the function looks like and wouldn't have to guess.

In practice, most people use function prototypes, because you can also take function prototypes and move them into header (.h) files so that code in other .c files can call those functions. But either solution works, and many codebases use both.

C99 and C11

It is useful to note that the rules are slightly different in the newer versions of the C standard. In the earlier versions (C89 and K&R), the compiler really would guess the types at function-call time (and K&R-era compilers often wouldn't even warn you if they were wrong). C99 and C11 both require that the function declaration/prototype must precede the first call, and it's an error if it doesn't. But many modern C compilers — mainly for backward compatibility with earlier code — will only warn about a missing prototype and not consider it an error.

Why is Node.js single threaded?

Node.js was created explicitly as an experiment in async processing. The theory was that doing async processing on a single thread could provide more performance and scalability under typical web loads than the typical thread-based implementation.

And you know what? In my opinion that theory's been borne out. A node.js app that isn't doing CPU intensive stuff can run thousands more concurrent connections than Apache or IIS or other thread-based servers.

The single threaded, async nature does make things complicated. But do you honestly think it's more complicated than threading? One race condition can ruin your entire month! Or empty out your thread pool due to some setting somewhere and watch your response time slow to a crawl! Not to mention deadlocks, priority inversions, and all the other gyrations that go with multithreading.

In the end, I don't think it's universally better or worse; it's different, and sometimes it's better and sometimes it's not. Use the right tool for the job.

Python 2: AttributeError: 'list' object has no attribute 'strip'

What you want to do is -

strtemp = ";".join(l)

The first line adds a ; to the end of MySpace so that while splitting, it does not give out MySpaceApple This will join l into one string and then you can just-

l1 = strtemp.split(";")

This works because strtemp is a string which has .split()

C# Linq Where Date Between 2 Dates

If you have date interval filter condition and you need to select all records which falls partly into this filter range. Assumption: records has ValidFrom and ValidTo property.

DateTime intervalDateFrom = new DateTime(1990, 01, 01);
DateTime intervalDateTo = new DateTime(2000, 01, 01);

var itemsFiltered = allItems.Where(x=> 
    (x.ValidFrom >= intervalDateFrom && x.ValidFrom <= intervalDateTo) ||
    (x.ValidTo >= intervalDateFrom && x.ValidTo <= intervalDateTo) ||
    (intervalDateFrom >= x.ValidFrom && intervalDateFrom <= x.ValidTo) ||
    (intervalDateTo >= x.ValidFrom && intervalDateTo <= x.ValidTo)
);

How to implement a ViewPager with different Fragments / Layouts

Code for adding fragment

public Fragment getItem(int position) {

    switch (position){
        case 0:
            return new Fragment1();

        case 1:
            return new Fragment2();

        case 2:
            return new Fragment3();

        case 3:
            return new Fragment4();

        default:
            break;
    }

    return null;
}

Create an xml file for each fragment say for Fragment1, use fragment_one.xml as layout file, use the below code in Fragment1 java file.

public class Fragment1 extends Fragment {

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

        View view = inflater.inflate(R.layout.fragment_one, container, false);

        return view;

    }
}

Later you can make necessary corrections.. It worked for me.

Remove the legend on a matplotlib figure

As of matplotlib v1.4.0rc4, a remove method has been added to the legend object.

Usage:

ax.get_legend().remove()

or

legend = ax.legend(...)
...
legend.remove()

See here for the commit where this was introduced.

'tsc command not found' in compiling typescript

This answer is specific for iTermV2 on MAC

  1. First of all, I needed to instal as sudo (admin) during NPM install

    sudo npm install -g typescript

  2. NPM installs the libraries under /usr/local/Cellar/node/<your latest version>/lib/node_modules/typescript folder and symlinks at /usr/local/Cellar/node/<your latest version>/bin/tsc

hence I went ~/.zshrc ( .bashrc, if you use bash)and added /usr/local/Cellar/node/<your latest version>/bin to the $PATH.

  1. reload the shell profile via source ~/.zshrc (.bashrc in your case)

How to playback MKV video in web browser?

You can use this following code. work just on chrome browser.

_x000D_
_x000D_
 function failed(e) {_x000D_
   // video playback failed - show a message saying why_x000D_
   switch (e.target.error.code) {_x000D_
     case e.target.error.MEDIA_ERR_ABORTED:_x000D_
       alert('You aborted the video playback.');_x000D_
       break;_x000D_
     case e.target.error.MEDIA_ERR_NETWORK:_x000D_
       alert('A network error caused the video download to fail part-way.');_x000D_
       break;_x000D_
     case e.target.error.MEDIA_ERR_DECODE:_x000D_
       alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');_x000D_
       break;_x000D_
     case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:_x000D_
       alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');_x000D_
       break;_x000D_
     default:_x000D_
       alert('An unknown error occurred.');_x000D_
       break;_x000D_
   }_x000D_
 }
_x000D_
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">_x000D_
_x000D_
<head>_x000D_
 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />_x000D_
 <meta name="author" content="Amin Developer!" />_x000D_
_x000D_
 <title>Untitled 1</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<p><video src="http://jell.yfish.us/media/Jellyfish-3-Mbps.mkv" type='video/x-matroska; codecs="theora, vorbis"' autoplay controls onerror="failed(event)" ></video></p>_x000D_
<p><a href="YOU mkv FILE LINK GOES HERE TO DOWNLOAD">Download the video file</a>.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Creating pdf files at runtime in c#

Well, free and not-for-free, I use WebSuperGoo ABCpdf .NET component, that I just love it!

not-for-free because you need to pay for it.

for free because even if you have to pay, they have a trial version and you can request a free license if you do not mind that, in your site show "This site uses WebSuperGoo ABCpdf .NET component" with a link to their website.

I did that and I got a free license (version 5 in that time) so, I can say that it works (even if the website is no longer online) - I still have and use the component ~:)

A wonderful thing that I love with this is that you can do everything that you can thing off with this, create PDF forms and dynamically fill them and send to user by mail or have them to download it, create a pdf from scratch, convert HTML pages into PDF, etc etc etc, please read the documentation, it is a wonderful component.

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

Manually map column names with class properties

Taken from the Dapper Tests which is currently on Dapper 1.42.

// custom mapping
var map = new CustomPropertyTypeMap(typeof(TypeWithMapping), 
                                    (type, columnName) => type.GetProperties().FirstOrDefault(prop => GetDescriptionFromAttribute(prop) == columnName));
Dapper.SqlMapper.SetTypeMap(typeof(TypeWithMapping), map);

Helper class to get name off the Description attribute (I personally have used Column like @kalebs example)

static string GetDescriptionFromAttribute(MemberInfo member)
{
   if (member == null) return null;

   var attrib = (DescriptionAttribute)Attribute.GetCustomAttribute(member, typeof(DescriptionAttribute), false);
   return attrib == null ? null : attrib.Description;
}

Class

public class TypeWithMapping
{
   [Description("B")]
   public string A { get; set; }

   [Description("A")]
   public string B { get; set; }
}

How to deep watch an array in angularjs?

This solution worked very well for me, i'm doing this in a directive:

scope.$watch(attrs.testWatch, function() {.....}, true);

the true works pretty well and react for all the chnages (add, delete, or modify a field).

Here is a working plunker for play with it.

Deeply Watching an Array in AngularJS

I hope this can be useful for you. If you have any questions, feel free for ask, I'll try to help :)

failed to open stream: No such file or directory in

you can use:

define("PATH_ROOT", dirname(__FILE__));
include_once PATH_ROOT . "/PoliticalForum/headerSite.php";

How to force DNS refresh for a website?

So if the issue is you just created a website and your clients or any given ISP DNS is cached and doesn't show new site yet. Yes all the other stuff applies ipconfig reset browser etc. BUT here's an Idea and something I do from time to time. You can set an alternate network ISP's DNS in the tcpip properties on the NIC properties. So if your ISP is say telstra and it hasn't propagated or updated you can specify an alternate service providers dns there. if that isp dns is updated before your native one hey presto you will see new site.But there is lots of other tricks you can do to determine propagation and get mail to work prior to the DNS updating. drop me a line if any one wants to chat.

How to timeout a thread

I think the answer mainly depends on the task itself.

  • Is it doing one task over and over again?
  • Is it necessary that the timeout interrupts a currently running task immediately after it expires?

If the first answer is yes and the second is no, you could keep it as simple as this:

public class Main {

    private static final class TimeoutTask extends Thread {
        private final long _timeoutMs;
        private Runnable _runnable;

        private TimeoutTask(long timeoutMs, Runnable runnable) {
            _timeoutMs = timeoutMs;
            _runnable = runnable;
        }

        @Override
        public void run() {
            long start = System.currentTimeMillis();
            while (System.currentTimeMillis() < (start + _timeoutMs)) {
                _runnable.run();
            }
            System.out.println("execution took " + (System.currentTimeMillis() - start) +" ms");
        }

    }

    public static void main(String[] args) throws Exception {
        new TimeoutTask(2000L, new Runnable() {

            @Override
            public void run() {
                System.out.println("doing something ...");
                try {
                    // pretend it's taking somewhat longer than it really does
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}

If this isn't an option, please narrow your requirements - or show some code.

std::enable_if to conditionally compile a member function

From this post:

Default template arguments are not part of the signature of a template

But one can do something like this:

#include <iostream>

struct Foo {
    template < class T,
               class std::enable_if < !std::is_integral<T>::value, int >::type = 0 >
    void f(const T& value)
    {
        std::cout << "Not int" << std::endl;
    }

    template<class T,
             class std::enable_if<std::is_integral<T>::value, int>::type = 0>
    void f(const T& value)
    {
        std::cout << "Int" << std::endl;
    }
};

int main()
{
    Foo foo;
    foo.f(1);
    foo.f(1.1);

    // Output:
    // Int
    // Not int
}

SQL - using alias in Group By

At least in PostgreSQL you can use the column number in the resultset in your GROUP BY clause:

SELECT 
 itemName as ItemName,
 substring(itemName, 1,1) as FirstLetter,
 Count(itemName)
FROM table1
GROUP BY 1, 2

Of course this starts to be a pain if you are doing this interactively and you edit the query to change the number or order of columns in the result. But still.

List comprehension vs. lambda + filter

My take

def filter_list(list, key, value, limit=None):
    return [i for i in list if i[key] == value][:limit]

Solving sslv3 alert handshake failure when trying to use a client certificate

Not a definite answer but too much to fit in comments:

I hypothesize they gave you a cert that either has a wrong issuer (although their server could use a more specific alert code for that) or a wrong subject. We know the cert matches your privatekey -- because both curl and openssl client paired them without complaining about a mismatch; but we don't actually know it matches their desired CA(s) -- because your curl uses openssl and openssl SSL client does NOT enforce that a configured client cert matches certreq.CAs.

Do openssl x509 <clientcert.pem -noout -subject -issuer and the same on the cert from the test P12 that works. Do openssl s_client (or check the one you did) and look under Acceptable client certificate CA names; the name there or one of them should match (exactly!) the issuer(s) of your certs. If not, that's most likely your problem and you need to check with them you submitted your CSR to the correct place and in the correct way. Perhaps they have different regimes in different regions, or business lines, or test vs prod, or active vs pending, etc.

If the issuer of your cert does match desiredCAs, compare its subject to the working (test-P12) one: are they in similar format? are there any components in the working one not present in yours? If they allow it, try generating and submitting a new CSR with a subject name exactly the same as the test-P12 one, or as close as you can get, and see if that produces a cert that works better. (You don't have to generate a new key to do this, but if you choose to, keep track of which certs match which keys so you don't get them mixed up.) If that doesn't help look at the certificate extensions with openssl x509 <cert -noout -text for any difference(s) that might reasonably be related to subject authorization, like KeyUsage, ExtendedKeyUsage, maybe Policy, maybe Constraints, maybe even something nonstandard.

If all else fails, ask the server operator(s) what their logs say about the problem, or if you have access look at the logs yourself.

"No such file or directory" error when executing a binary

Well another possible cause of this can be simple line break at end of each line and shebang line If you have been coding in windows IDE its possible that windows has added its own line break at the end of each line and when you try to run it on linux the line break cause problems

How to position the form in the center screen?

Simply set location relative to null after calling pack on the JFrame, that's it.

e.g.,

  JFrame frame = new JFrame("FooRendererTest");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().add(mainPanel); // or whatever...
  frame.pack();
  frame.setLocationRelativeTo(null);  // *** this will center your app ***
  frame.setVisible(true);

How can I get the URL of the current tab from a Google Chrome extension?

This Solution is already TESTED.

set permissions for API in manifest.json

"permissions": [ ...
   "tabs",
    "activeTab",
    "<all_urls>"
]

On first load call function. https://developer.chrome.com/extensions/tabs#event-onActivated

chrome.tabs.onActivated.addListener((activeInfo) => {  
  sendCurrentUrl()
})

On change call function. https://developer.chrome.com/extensions/tabs#event-onSelectionChanged

chrome.tabs.onSelectionChanged.addListener(() => {
  sendCurrentUrl()
})

the function to get the URL

function sendCurrentUrl() {
  chrome.tabs.getSelected(null, function(tab) {
    var tablink = tab.url
    console.log(tablink)
  })

"Are you missing an assembly reference?" compile error - Visual Studio

While creating new Blank UWP project in Visual Studio 2017 Community, this error came up.

enter image description here

After the suggested remedy (restoring NuGet cache) the reference resurfaced in the Project.

Regular expression to match a dot

A . in regex is a metacharacter, it is used to match any character. To match a literal dot, you need to escape it, so \.

How can I embed a YouTube video on GitHub wiki pages?

It's not possible to embed videos directly, but you can put an image which links to a YouTube video:

[![IMAGE ALT TEXT HERE](https://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg)](https://www.youtube.com/watch?v=YOUTUBE_VIDEO_ID_HERE)

How to count the number of occurrences of a character in an Oracle varchar value?

I justed faced very similar problem... BUT RegExp_Count couldn't resolved it. How many times string '16,124,3,3,1,0,' contains ',3,'? As we see 2 times, but RegExp_Count returns just 1. Same thing is with ''bbaaaacc' and when looking in it 'aa' - should be 3 times and RegExp_Count returns just 2.

select REGEXP_COUNT('336,14,3,3,11,0,' , ',3,') from dual;
select REGEXP_COUNT('bbaaaacc' , 'aa') from dual;

I lost some time to research solution on web. Couldn't' find... so i wrote my own function that returns TRUE number of occurance. Hope it will be usefull.

CREATE OR REPLACE FUNCTION EXPRESSION_COUNT( pEXPRESSION VARCHAR2, pPHRASE VARCHAR2 ) RETURN NUMBER AS
  vRET NUMBER := 0;
  vPHRASE_LENGTH NUMBER := 0;
  vCOUNTER NUMBER := 0;
  vEXPRESSION VARCHAR2(4000);
  vTEMP VARCHAR2(4000);
BEGIN
  vEXPRESSION := pEXPRESSION;
  vPHRASE_LENGTH := LENGTH( pPHRASE );
  LOOP
    vCOUNTER := vCOUNTER + 1;
    vTEMP := SUBSTR( vEXPRESSION, 1, vPHRASE_LENGTH);
    IF (vTEMP = pPHRASE) THEN        
        vRET := vRET + 1;
    END IF;
    vEXPRESSION := SUBSTR( vEXPRESSION, 2, LENGTH( vEXPRESSION ) - 1);
  EXIT WHEN ( LENGTH( vEXPRESSION ) = 0 ) OR (vEXPRESSION IS NULL);
  END LOOP;
  RETURN vRET;
END;

What does it mean when MySQL is in the state "Sending data"?

In this state:

The thread is reading and processing rows for a SELECT statement, and sending data to the client.

Because operations occurring during this this state tend to perform large amounts of disk access (reads).

That's why it takes more time to complete and so is the longest-running state over the lifetime of a given query.

Convert a SQL Server datetime to a shorter date format

The shortest date format of mm/dd/yy can be obtained with:

Select Convert(varchar(8),getdate(),1)

Which comes first in a 2D array, rows or columns?

The best way to remember if rows or columns come first would be writing a comment and mentioning it.

Java does not store a 2D Array as a table with specified rows and columns, it stores it as an array of arrays, like many other answers explain. So you can decide, if the first or second dimension is your row. You just have to read the array depending on that.

So, since I get confused by this all the time myself, I always write a comment that tells me, which dimension of the 2d Array is my row, and which is my column.

Linux configure/make, --prefix?

In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198

Is it possible in Java to access private fields via reflection

Yes.

  Field f = Test.class.getDeclaredField("str");
  f.setAccessible(true);//Very important, this allows the setting to work.
  String value = (String) f.get(object);

Then you use the field object to get the value on an instance of the class.

Note that get method is often confusing for people. You have the field, but you don't have an instance of the object. You have to pass that to the get method

Change color of Label in C#

You can try this with Color.FromArgb:

Random rnd = new Random();
lbl.ForeColor = Color.FromArgb(rnd.Next(255), rnd.Next(255), rnd.Next(255));

Xcode build failure "Undefined symbols for architecture x86_64"

in my case I had to add

    target 'SomeTargetTests' do
        inherit! :search_paths
    end
to my podfile and then delete the /Pods directory and run `pod install`

(Xcode 10.1)

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

Uninstall your application from the emulator or device. Run the app again. (OnCreate() is not executed when the database already exists)

Fast query runs slow in SSRS

Couple of things you can do, without executing the actual report just run the sproc from within the data tab of reporting services. Does it still take time? Another option is to use SQL Profiler and determine what is coming in and out of the database system.

Another thing you can do to test it, so to recreate a simple report without any parameters. Run the report and see if it makes a difference. It could be that your RS report is corrupted or badly formed that may cause the rendering to be really slow.

phpmyadmin logs out after 1440 secs

It worked for me after I

  • changed the $cfg['LoginCookieValidity'] in (phpmyadmin folder)/libraries/config.default.php to 999999999.

  • checked the php.ini used by the phpmyadmin by php5 -i | grep php.ini.

  • went to the php.ini file whose path I got from the grep command output and changed the session.gc_maxlifetime value to 999999999.

  • restarted the server. In my case it was sudo service apache2 restart.

Done. Logged in phpmyadmin and checked the cookie validity in Settings -> Features -> General -> Login cookie validity. It was 999999999. Also there was no warning "Your PHP parameter session.gc_maxlifetime is lower that cookie validity ...". The warning showed after I logged in phpmyadmin before I changed the php.ini file.

Check the version of php used by the phpmyadmin. You should change the ini file of the php that is used by the phpmyadmin. I have php5 and php(i.e 7) both installed. But my phpmyadmin uses php5. So I had to search for ini file of php5.

How to create a self-signed certificate with OpenSSL

This is the script I use on local boxes to set the SAN (subjectAltName) in self-signed certificates.

This script takes the domain name (example.com) and generates the SAN for *.example.com and example.com in the same certificate. The sections below are commented. Name the script (e.g. generate-ssl.sh) and give it executable permissions. The files will be written to the same directory as the script.

Chrome 58 an onward requires SAN to be set in self-signed certificates.

#!/usr/bin/env bash

# Set the TLD domain we want to use
BASE_DOMAIN="example.com"

# Days for the cert to live
DAYS=1095

# A blank passphrase
PASSPHRASE=""

# Generated configuration file
CONFIG_FILE="config.txt"

cat > $CONFIG_FILE <<-EOF
[req]
default_bits = 2048
prompt = no
default_md = sha256
x509_extensions = v3_req
distinguished_name = dn

[dn]
C = CA
ST = BC
L = Vancouver
O = Example Corp
OU = Testing Domain
emailAddress = webmaster@$BASE_DOMAIN
CN = $BASE_DOMAIN

[v3_req]
subjectAltName = @alt_names

[alt_names]
DNS.1 = *.$BASE_DOMAIN
DNS.2 = $BASE_DOMAIN
EOF

# The file name can be anything
FILE_NAME="$BASE_DOMAIN"

# Remove previous keys
echo "Removing existing certs like $FILE_NAME.*"
chmod 770 $FILE_NAME.*
rm $FILE_NAME.*

echo "Generating certs for $BASE_DOMAIN"

# Generate our Private Key, CSR and Certificate
# Use SHA-2 as SHA-1 is unsupported from Jan 1, 2017

openssl req -new -x509 -newkey rsa:2048 -sha256 -nodes -keyout "$FILE_NAME.key" -days $DAYS -out "$FILE_NAME.crt" -passin pass:$PASSPHRASE -config "$CONFIG_FILE"

# OPTIONAL - write an info to see the details of the generated crt
openssl x509 -noout -fingerprint -text < "$FILE_NAME.crt" > "$FILE_NAME.info"

# Protect the key
chmod 400 "$FILE_NAME.key"

This script also writes an information file, so you can inspect the new certificate and verify the SAN is set properly.

                ...
                28:dd:b8:1e:34:b5:b1:44:1a:60:6d:e3:3c:5a:c4:
                da:3d
            Exponent: 65537 (0x10001)
    X509v3 extensions:
        X509v3 Subject Alternative Name: 
            DNS:*.example.com, DNS:example.com
Signature Algorithm: sha256WithRSAEncryption
     3b:35:5a:d6:9e:92:4f:fc:f4:f4:87:78:cd:c7:8d:cd:8c:cc:
     ...

If you are using Apache, then you can reference the above certificate in your configuration file like so:

<VirtualHost _default_:443>
    ServerName example.com
    ServerAlias www.example.com
    DocumentRoot /var/www/htdocs

    SSLEngine on
    SSLCertificateFile path/to/your/example.com.crt
    SSLCertificateKeyFile path/to/your/example.com.key
</VirtualHost>

Remember to restart your Apache (or Nginx, or IIS) server for the new certificate to take effect.

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

When you use an async function like

async () => {
    try {
        const response = await fetch(`https://www.reddit.com/r/${subreddit}.json`);
        const json = await response.json();
        setPosts(json.data.children.map(it => it.data));
    } catch (e) {
        console.error(e);
    }
}

it returns a promise and useEffect doesn't expect the callback function to return Promise, rather it expects that nothing is returned or a function is returned.

As a workaround for the warning you can use a self invoking async function.

useEffect(() => {
    (async function() {
        try {
            const response = await fetch(
                `https://www.reddit.com/r/${subreddit}.json`
            );
            const json = await response.json();
            setPosts(json.data.children.map(it => it.data));
        } catch (e) {
            console.error(e);
        }
    })();
}, []);

or to make it more cleaner you could define a function and then call it

useEffect(() => {
    async function fetchData() {
        try {
            const response = await fetch(
                `https://www.reddit.com/r/${subreddit}.json`
            );
            const json = await response.json();
            setPosts(json.data.children.map(it => it.data));
        } catch (e) {
            console.error(e);
        }
    };
    fetchData();
}, []);

the second solution will make it easier to read and will help you write code to cancel previous requests if a new one is fired or save the latest request response in state

Working codesandbox

How to convert a DataTable to a string in C#?

You could use something like this:

Private Sub PrintTableOrView(ByVal table As DataTable, ByVal label As String)
    Dim sw As System.IO.StringWriter
    Dim output As String

    Console.WriteLine(label)

    ' Loop through each row in the table. '
    For Each row As DataRow In table.Rows
        sw = New System.IO.StringWriter
        ' Loop through each column. '
        For Each col As DataColumn In table.Columns
            ' Output the value of each column's data.
            sw.Write(row(col).ToString() & ", ")
        Next
        output = sw.ToString
        ' Trim off the trailing ", ", so the output looks correct. '
        If output.Length > 2 Then
            output = output.Substring(0, output.Length - 2)
        End If
        ' Display the row in the console window. '
        Console.WriteLine(output)
    Next
    Console.WriteLine()
End Sub

Is there a naming convention for git repositories?

Maybe it is just my Java and C background showing, but I prefer CamelCase (CapCase) over punctuation in the name. My workgroup uses such names, probably to match the names of the app or service the repository contains.

How to prevent Browser cache on Angular 2 site?

In each html template I just add the following meta tags at the top:

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

In my understanding each template is free standing therefore it does not inherit meta no caching rules setup in the index.html file.

Difference between java HH:mm and hh:mm on SimpleDateFormat

Please take a look here

HH is hour in a day (starting from 0 to 23)

hh are hours in am/pm format

kk is hour in day (starting from 1 to 24)

mm is minute in hour

ss are the seconds in a minute

Run Command Prompt Commands

this is all you have to do run shell commands from C#

string strCmdText;
strCmdText= "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);

EDIT:

This is to hide the cmd window.

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
process.StartInfo = startInfo;
process.Start();

EDIT: 2

Important is that the argument begins with /C otherwise it won't work. How Scott Ferguson said: it "Carries out the command specified by the string and then terminates."

how to rename an index in a cluster?

Just in case someone still needs it. The successful, not official, way to rename indexes are:

  1. Close indexes that need to be renamed
  2. Rename indexes' folders in all data directories of master and data nodes.
  3. Reopen old closed indexes (I use kofp plugin). Old indexes will be reopened but stay unassigned. New indexes will appear in closed state
  4. Reopen new indexes
  5. Delete old indexes

If you happen to get this error "dangled index directory name is", remove index folder in all master nodes (not data nodes), and restart one of the data nodes.

Getting a count of rows in a datatable that meet certain criteria

If the data is stored in a database it will be faster to send the query to the database instead of getting all data and query it in memory.

A third way to do it will be linq to datasets, but i doubt any of these 3 methods differ much in performance.

How do I convert a number to a letter in Java?

public static void main(String[] args)
 {
     int rem,n=702,quo;
     String s=" ";
     while(n>0)
     {
         rem=(n-1)%26;
         quo=(n-1)/26;
         s=(char)(rem+97)+s;
         if(quo==1)
         {
            s=(char)(97)+s;
            break;
         }
         else
         n=(n-1)/26;
     }
     System.out.print(s);
 }
}
////We can also write the code like the below one. There is no much difference but it may help to understand the concept for some people.


public static void main(String[] args)
 {
     int rem,n=52,quo;
     String s=" ";
     while(n>0)
     {
         rem=n%26;
         quo=n/26;
         if(rem==0)
             rem=26;
         s=(char)(rem+96)+s;
         if((quo==1 || quo==0) && n>26)
         {
             n=n/26;
            s=(char)(n+96)+s;
            break;
         }
         else
             n=n/26-1; 
     }
     System.out.print(s);
 }

How to make certain text not selectable with CSS

Use a simple background image for the textarea suffice.

Or

<div onselectstart="return false">your text</div>

writing a batch file that opens a chrome URL

assuming chrome is his default browser: start http://url.site.you.com/path/to/joke should open that url in his browser.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 2: ordinal not in range(128)

The main reason for the error is that the default encoding assumed by python is ASCII. Hence, if the string data to be encoded by encode('utf8') contains character that is outside of ASCII range e.g. for a string like 'hgvcj???387', python would throw error because the string is not in the expected encoding format.

If you are using python version earlier than version 3.5, a reliable fix would be to set the default encoding assumed by python to utf8:

import sys
reload(sys)
sys.setdefaultencoding('utf8')
name = school_name.encode('utf8')

This way python would be able to anticipate characters within a string that fall outside of ASCII range.

However, if you are using python version 3.5 or above, reload() function is not available, so you would have to fix it using decode e.g.

name = school_name.decode('utf8').encode('utf8')

Pro JavaScript programmer interview questions (with answers)

Ask them how they ensure their pages continue to be usable when the user has JavaScript turned off or JavaScript isn't available.

There's no One True Answer, but you're fishing for an answer talking about some strategies for Progressive Enhancement.

Progressive Enhancement consists of the following core principles:

  • basic content should be accessible to all browsers
  • basic functionality should be accessible to all browsers
  • sparse, semantic markup contains all content
  • enhanced layout is provided by externally linked CSS
  • enhanced behavior is provided by [[Unobtrusive JavaScript|unobtrusive]], externally linked JavaScript
  • end user browser preferences are respected

How to get character for a given ascii value

Simply Try this:

int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("data is: {0}", Convert.ToChar(n));

How to make the background image to fit into the whole page without repeating using plain css?

Depending on what kind of image you have, it might be better to rework the design so that the main image fades to a set solid color or repeatable pattern. If you center the image in the page and have the solid color as the backgroud.

See http://www.webdesignerwall.com/trends/80-large-background-websites/ for examples of sites using large or scalable backgrounds.

How can I use a JavaScript variable as a PHP variable?

You seem to be confusing client-side and server side code. When the button is clicked you need to send (post, get) the variables to the server where the php can be executed. You can either submit the page or use an ajax call to submit just the data. -don

How can you test if an object has a specific property?

I've been using the following which returns the property value, as it would be accessed via $thing.$prop, if the "property" would be to exist and not throw a random exception. If the property "doesn't exist" (or has a null value) then $null is returned: this approach functions in/is useful for strict mode, because, well, Gonna Catch 'em All.

I find this approach useful because it allows PS Custom Objects, normal .NET objects, PS HashTables, and .NET collections like Dictionary to be treated as "duck-typed equivalent", which I find is a fairly good fit for PowerShell.

Of course, this does not meet the strict definition of "has a property".. which this question may be explicitly limited to. If accepting the larger definition of "property" assumed here, the method can be trivially modified to return a boolean.

Function Get-PropOrNull {
    param($thing, [string]$prop)
    Try {
        $thing.$prop
    } Catch {
    }
}

Examples:

Get-PropOrNull (Get-Date) "Date"                   # => Monday, February 05, 2018 12:00:00 AM
Get-PropOrNull (Get-Date) "flub"                   # => $null
Get-PropOrNull (@{x="HashTable"}) "x"              # => "HashTable"
Get-PropOrNull ([PSCustomObject]@{x="Custom"}) "x" # => "Custom"
$oldDict = New-Object "System.Collections.HashTable"
$oldDict["x"] = "OldDict"
Get-PropOrNull $d "x"                              # => "OldDict"

And, this behavior might not [always] be desired.. ie. it's not possible to distinguish between x.Count and x["Count"].

PHP: date function to get month of the current date

$unixtime = strtotime($test);
echo date('m', $unixtime); //month
echo date('d', $unixtime); 
echo date('y', $unixtime );

vertical-align: middle doesn't work

You must wrap your element in a table-cell, within a table using display.

Like this:

<div>
  <span class='twoline'>Two line text</span>
  <span class='float'>Float right</span>
</div>

and

.float {
    display: table-cell;
    vertical-align: middle;
    text-align: right;
}
.twoline {
    width: 50px;
    display: table-cell;
}
div {
    display: table;
    border: solid 1px blue;
    width: 500px;
    height: 100px;
}

Shown here: http://jsfiddle.net/e8ESb/7/

CSS Float: Floating an image to the left of the text

_x000D_
_x000D_
.post-container{_x000D_
    margin: 20px 20px 0 0;  _x000D_
    border:5px solid #333;_x000D_
    width:600px;_x000D_
    overflow:hidden;_x000D_
}_x000D_
_x000D_
.post-thumb img {_x000D_
    float: left;_x000D_
    clear:left;_x000D_
    width:50px;_x000D_
    height:50px;_x000D_
    border:1px solid red;_x000D_
}_x000D_
_x000D_
.post-title {_x000D_
     float:left;   _x000D_
    margin-left:10px;_x000D_
}_x000D_
_x000D_
.post-content {_x000D_
    float:right;_x000D_
}
_x000D_
<div class="post-container">                _x000D_
   <div class="post-thumb"><img src="thumb.jpg" /></div>_x000D_
   <div class="post-title">Post title</div>_x000D_
   <div class="post-content"><p>post description description description etc etc etc</p></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle

Get a list of dates between two dates

We had a similar problem with BIRT reports in that we wanted to report on those days that had no data. Since there were no entries for those dates, the easiest solution for us was to create a simple table that stored all dates and use that to get ranges or join to get zero values for that date.

We have a job that runs every month to ensure that the table is populated 5 years out into the future. The table is created thus:

create table all_dates (
    dt date primary key
);

No doubt there are magical tricky ways to do this with different DBMS' but we always opt for the simplest solution. The storage requirements for the table are minimal and it makes the queries so much simpler and portable. This sort of solution is almost always better from a performance point-of-view since it doesn't require per-row calculations on the data.

The other option (and we've used this before) is to ensure there's an entry in the table for every date. We swept the table periodically and added zero entries for dates and/or times that didn't exist. This may not be an option in your case, it depends on the data stored.

If you really think it's a hassle to keep the all_dates table populated, a stored procedure is the way to go which will return a dataset containing those dates. This will almost certainly be slower since you have to calculate the range every time it's called rather than just pulling pre-calculated data from a table.

But, to be honest, you could populate the table out for 1000 years without any serious data storage problems - 365,000 16-byte (for example) dates plus an index duplicating the date plus 20% overhead for safety, I'd roughly estimate at about 14M [365,000 * 16 * 2 * 1.2 = 14,016,000 bytes]), a minuscule table in the scheme of things.

Permutation of array

Here is one using arrays and Java 8+

import java.util.Arrays;
import java.util.stream.IntStream;

public class HelloWorld {

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 5};
        permutation(arr, new int[]{});
    }

    static void permutation(int[] arr, int[] prefix) {
        if (arr.length == 0) {
            System.out.println(Arrays.toString(prefix));
        }
        for (int i = 0; i < arr.length; i++) {
            int i2 = i;
            int[] pre = IntStream.concat(Arrays.stream(prefix), IntStream.of(arr[i])).toArray();
            int[] post = IntStream.range(0, arr.length).filter(i1 -> i1 != i2).map(v -> arr[v]).toArray();
            permutation(post, pre);
        }
    }
}

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

Getting a map() to return a list in Python 3.x

In addition to above answers in Python 3, we may simply create a list of result values from a map as

li = []
for x in map(chr,[66,53,0,94]):
    li.append(x)

print (li)
>>>['B', '5', '\x00', '^']

We may generalize by another example where I was struck, operations on map can also be handled in similar fashion like in regex problem, we can write function to obtain list of items to map and get result set at the same time. Ex.

b = 'Strings: 1,072, Another String: 474 '
li = []
for x in map(int,map(int, re.findall('\d+', b))):
    li.append(x)

print (li)
>>>[1, 72, 474]

Why is PHP session_destroy() not working?

session_destroy() is effective after the page load is complete. So in the second upload, the session is terminated. But with unset() you can also log out from within the page.

OpenCV - Apply mask to a color image

Answer given by Abid Rahman K is not completely correct. I also tried it and found very helpful but got stuck.

This is how I copy image with a given mask.

x, y = np.where(mask!=0)
pts = zip(x, y)
# Assuming dst and src are of same sizes
for pt in pts:
   dst[pt] = src[pt]

This is a bit slow but gives correct results.

EDIT:

Pythonic way.

idx = (mask!=0)
dst[idx] = src[idx]

How do you pass view parameters when navigating from an action in JSF2?

The unintuitive thing about passing parameters in JSF is that you do not decide what to send (in the action), but rather what you wish to receive (in the target page).

When you do an action that ends with a redirect, the target page metadata is loaded and all required parameters are read and appended to the url as params.

Note that this is exactly the same mechanism as with any other JSF binding: you cannot read inputText's value from one place and have it write somewhere else. The value expression defined in viewParam is used both for reading (before the redirect) and for writing (after the redirect).

With your bean you just do:

@ManagedBean
@RequestScoped
public class MyBean {

private int id;

public String submit() {
    //Does stuff
    id = setID();
    return "success?faces-redirect=true&includeViewParams=true";
}

// setter and getter for id

If the receiving side has:

    <f:metadata>
        <f:viewParam name="id" value="#{myBean.id}" />
    </f:metadata>

It will do exactly what you want.

Making a mocked method return an argument that was passed to it

This is a bit old, but I came here because I had the same issue. I'm using JUnit but this time in a Kotlin app with mockk. I'm posting a sample here for reference and comparison with the Java counterpart:

@Test
fun demo() {
  // mock a sample function
  val aMock: (String) -> (String) = mockk()

  // make it return the same as the argument on every invocation
  every {
    aMock.invoke(any())
  } answers {
    firstArg()
  }

  // test it
  assertEquals("senko", aMock.invoke("senko"))
  assertEquals("senko1", aMock.invoke("senko1"))
  assertNotEquals("not a senko", aMock.invoke("senko"))
}

How to convert string to XML using C#

Use LoadXml Method of XmlDocument;

string xml = "<head><body><Inner> welcome </head> </Inner> <Outer> Bye</Outer></body></head>";
xDoc.LoadXml(xml);

How to generate an MD5 file hash in JavaScript?

As a contemporary alternative, there is a standard now for client side cryptography. This has the advantage of being optimised by the browser itself.

Taken from the example in the documentation:

async function sha256(message) {

    // encode as UTF-8
    const msgBuffer = new TextEncoder('utf-8').encode(message);

    // hash the message
    const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);

    // convert ArrayBuffer to Array
    const hashArray = Array.from(new Uint8Array(hashBuffer));

    // convert bytes to hex string
    const hashHex = hashArray.map(b => ('00' + b.toString(16)).slice(-2)).join('');
    return hashHex;
}

sha256('abc').then(hash => console.log(hash));

(async function() {
    const hash = await sha256('abc');
}());

MD5 is likely unsupported, however the likes of SHA-256, SHA-384, and SHA-512 are.

And those will likely be able to be calculated server side also.

Here's some documentation on usage: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest

And cross browser compatibility: https://caniuse.com/#feat=cryptography

How to get Maven project version to the bash command line

I've recently developed the Release Candidate Maven plugin that solves this exact problem so that you don't have to resort to any hacky shell scripts and parsing the output of the maven-help-plugin.

For example, to print the version of your Maven project to a terminal, run:

mvn com.smartcodeltd:release-candidate-maven-plugin:LATEST:version

which gives output similar to maven-help-plugin:

[INFO] Detected version: '1.0.0-SNAPSHOT'
1.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

However, you can also specify an arbitrary output format (so that the version could be picked up from the log by a CI server such as TeamCity):

mvn com.smartcodeltd:release-candidate-maven-plugin:LATEST:version \
   -DoutputTemplate="##teamcity[setParameter name='env.PROJECT_VERSION' value='{{ version }}']"

Which results in:

[INFO] Detected version: '1.0.0-SNAPSHOT'
##teamcity[setParameter name='env.PROJECT_VERSION' value='1.0.0-SNAPSHOT']
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------

To save the output to a file (so that a CI server such as Jenkins could use it):

mvn com.smartcodeltd:release-candidate-maven-plugin:LATEST:version \
   -DoutputTemplate="PROJECT_VERSION={{ version }}" \
   -DoutputUri="file://\${project.basedir}/version.properties"

The resulting version.properties file will look as follows:

PROJECT_VERSION=1.0.0-SNAPSHOT

On top of all the above, Release Candidate also allows you to set the version of your project (which is something you'd probably do on your CI server) based on the API version you've defined in your POM.

If you'd like to see an example of Release Candidate being used as part of the Maven lifecycle, have a look at the pom.xml of my other open-source project - Build Monitor for Jenkins.

In c, in bool, true == 1 and false == 0?

More accurately anything that is not 0 is true.

So 1 is true, but so is 2, 3 ... etc.

Environment variable to control java.io.tmpdir?

Hmmm -- since this is handled by the JVM, I delved into the OpenJDK VM source code a little bit, thinking that maybe what's done by OpenJDK mimics what's done by Java 6 and prior. It isn't reassuring that there's a way to do this other than on Windows.

On Windows, OpenJDK's get_temp_directory() function makes a Win32 API call to GetTempPath(); this is how on Windows, Java reflects the value of the TMP environment variable.

On Linux and Solaris, the same get_temp_directory() functions return a static value of /tmp/.

I don't know if the actual JDK6 follows these exact conventions, but by the behavior on each of the listed platforms, it seems like they do.

Split an NSString to access one particular piece

Its working fine

NSString *dateString = @"10/10/2010";//Date 
NSArray* dateArray = [dateString componentsSeparatedByString: @"/"];
NSString* dayString = [dateArray objectAtIndex: 0];

Where is Java's Array indexOf?

Unlike in C# where you have the Array.IndexOf method, and JavaScript where you have the indexOf method, Java's API (the Array and Arrays classes in particular) have no such method.

This method indexOf (together with its complement lastIndexOf) is defined in the java.util.List interface. Note that indexOf and lastIndexOf are not overloaded and only take an Object as a parameter.

If your array is sorted, you are in luck because the Arrays class defines a series of overloads of the binarySearch method that will find the index of the element you are looking for with best possible performance (O(log n) instead of O(n), the latter being what you can expect from a sequential search done by indexOf). There are four considerations:

  1. The array must be sorted either in natural order or in the order of a Comparator that you provide as an argument, or at the very least all elements that are "less than" the key must come before that element in the array and all elements that are "greater than" the key must come after that element in the array;

  2. The test you normally do with indexOf to determine if a key is in the array (verify if the return value is not -1) does not hold with binarySearch. You need to verify that the return value is not less than zero since the value returned will indicate the key is not present but the index at which it would be expected if it did exist;

  3. If your array contains multiple elements that are equal to the key, what you get from binarySearch is undefined; this is different from indexOf that will return the first occurrence and lastIndexOf that will return the last occurrence.

  4. An array of booleans might appear to be sorted if it first contains all falses and then all trues, but this doesn't count. There is no override of the binarySearch method that accepts an array of booleans and you'll have to do something clever there if you want O(log n) performance when detecting where the first true appears in an array, for instance using an array of Booleans and the constants Boolean.FALSE and Boolean.TRUE.

If your array is not sorted and not primitive type, you can use List's indexOf and lastIndexOf methods by invoking the asList method of java.util.Arrays. This method will return an AbstractList interface wrapper around your array. It involves minimal overhead since it does not create a copy of the array. As mentioned, this method is not overloaded so this will only work on arrays of reference types.

If your array is not sorted and the type of the array is primitive, you are out of luck with the Java API. Write your own for loop, or your own static utility method, which will certainly have performance advantages over the asList approach that involves some overhead of an object instantiation. In case you're concerned that writing a brute force for loop that iterates over all of the elements of the array is not an elegant solution, accept that that is exactly what the Java API is doing when you call indexOf. You can make something like this:

public static int indexOfIntArray(int[] array, int key) {
    int returnvalue = -1;
    for (int i = 0; i < array.length; ++i) {
        if (key == array[i]) {
            returnvalue = i;
            break;
        }
    }
    return returnvalue;
}

If you want to avoid writing your own method here, consider using one from a development framework like Guava. There you can find an implementation of indexOf and lastIndexOf.

Unable to open debugger port in IntelliJ

I once have this problem too. My solution is to work around this problem by kill the application which is using the port. Here is a article to teach us how to check which application is using which port, find it and kill/close it.

Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE environment variable to

I'm using Android Data Binding and I have the same problem today.

To solve it, change:

classpath "com.android.databinding:dataBinder:1.0-rc0"

To:

classpath "com.android.databinding:dataBinder:1.0-rc1"

1.0-rc0 still could be found on jcenter now, I don't know why it couldn't be use.

Disable sorting for a particular column in jQuery DataTables

set class "no-sort" in th of the table then add css .no-sort { pointer-events: none !important; cursor: default !important;background-image: none !important; } by this it will hide the arrow updown and disble event in the head.

How change default SVN username and password to commit changes?

For Windows (7), the same folder is located at,

%APPDATA%\Subversion\auth

Type in the above in the Run(Win key + R) dialog box and hit Enter,

To check the existing username open the below file as a text file,

%APPDATA%\Subversion\auth\svn.simple\xxxxxxxxxx

How to create strings containing double quotes in Excel formulas?

Concatenate " as a ceparate cell:

    A |   B   | C | D
1   " | text  | " | =CONCATENATE(A1; B1; C1);

D1 displays "text"

Google Chrome forcing download of "f.txt" file

Seems related to https://groups.google.com/forum/#!msg/google-caja-discuss/ite6K5c8mqs/Ayqw72XJ9G8J.

The so-called "Rosetta Flash" vulnerability is that allowing arbitrary yet identifier-like text at the beginning of a JSONP response is sufficient for it to be interpreted as a Flash file executing in that origin. See for more information: http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/

JSONP responses from the proxy servlet now: * are prefixed with "/**/", which still allows them to execute as JSONP but removes requester control over the first bytes of the response. * have the response header Content-Disposition: attachment.

Apache Spark: map vs mapPartitions?

Imp. TIP :

Whenever you have heavyweight initialization that should be done once for many RDD elements rather than once per RDD element, and if this initialization, such as creation of objects from a third-party library, cannot be serialized (so that Spark can transmit it across the cluster to the worker nodes), use mapPartitions() instead of map(). mapPartitions() provides for the initialization to be done once per worker task/thread/partition instead of once per RDD data element for example : see below.

val newRd = myRdd.mapPartitions(partition => {
  val connection = new DbConnection /*creates a db connection per partition*/

  val newPartition = partition.map(record => {
    readMatchingFromDB(record, connection)
  }).toList // consumes the iterator, thus calls readMatchingFromDB 

  connection.close() // close dbconnection here
  newPartition.iterator // create a new iterator
})

Q2. does flatMap behave like map or like mapPartitions?

Yes. please see example 2 of flatmap.. its self explanatory.

Q1. What's the difference between an RDD's map and mapPartitions

map works the function being utilized at a per element level while mapPartitions exercises the function at the partition level.

Example Scenario : if we have 100K elements in a particular RDD partition then we will fire off the function being used by the mapping transformation 100K times when we use map.

Conversely, if we use mapPartitions then we will only call the particular function one time, but we will pass in all 100K records and get back all responses in one function call.

There will be performance gain since map works on a particular function so many times, especially if the function is doing something expensive each time that it wouldn't need to do if we passed in all the elements at once(in case of mappartitions).

map

Applies a transformation function on each item of the RDD and returns the result as a new RDD.

Listing Variants

def map[U: ClassTag](f: T => U): RDD[U]

Example :

val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)
 val b = a.map(_.length)
 val c = a.zip(b)
 c.collect
 res0: Array[(String, Int)] = Array((dog,3), (salmon,6), (salmon,6), (rat,3), (elephant,8)) 

mapPartitions

This is a specialized map that is called only once for each partition. The entire content of the respective partitions is available as a sequential stream of values via the input argument (Iterarator[T]). The custom function must return yet another Iterator[U]. The combined result iterators are automatically converted into a new RDD. Please note, that the tuples (3,4) and (6,7) are missing from the following result due to the partitioning we chose.

preservesPartitioning indicates whether the input function preserves the partitioner, which should be false unless this is a pair RDD and the input function doesn't modify the keys.

Listing Variants

def mapPartitions[U: ClassTag](f: Iterator[T] => Iterator[U], preservesPartitioning: Boolean = false): RDD[U]

Example 1

val a = sc.parallelize(1 to 9, 3)
 def myfunc[T](iter: Iterator[T]) : Iterator[(T, T)] = {
   var res = List[(T, T)]()
   var pre = iter.next
   while (iter.hasNext)
   {
     val cur = iter.next;
     res .::= (pre, cur)
     pre = cur;
   }
   res.iterator
 }
 a.mapPartitions(myfunc).collect
 res0: Array[(Int, Int)] = Array((2,3), (1,2), (5,6), (4,5), (8,9), (7,8)) 

Example 2

val x = sc.parallelize(List(1, 2, 3, 4, 5, 6, 7, 8, 9,10), 3)
 def myfunc(iter: Iterator[Int]) : Iterator[Int] = {
   var res = List[Int]()
   while (iter.hasNext) {
     val cur = iter.next;
     res = res ::: List.fill(scala.util.Random.nextInt(10))(cur)
   }
   res.iterator
 }
 x.mapPartitions(myfunc).collect
 // some of the number are not outputted at all. This is because the random number generated for it is zero.
 res8: Array[Int] = Array(1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 5, 7, 7, 7, 9, 9, 10) 

The above program can also be written using flatMap as follows.

Example 2 using flatmap

val x  = sc.parallelize(1 to 10, 3)
 x.flatMap(List.fill(scala.util.Random.nextInt(10))(_)).collect

 res1: Array[Int] = Array(1, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10) 

Conclusion :

mapPartitions transformation is faster than map since it calls your function once/partition, not once/element..

Further reading : foreach Vs foreachPartitions When to use What?

Understanding the map function

map isn't particularly pythonic. I would recommend using list comprehensions instead:

map(f, iterable)

is basically equivalent to:

[f(x) for x in iterable]

map on its own can't do a Cartesian product, because the length of its output list is always the same as its input list. You can trivially do a Cartesian product with a list comprehension though:

[(a, b) for a in iterable_a for b in iterable_b]

The syntax is a little confusing -- that's basically equivalent to:

result = []
for a in iterable_a:
    for b in iterable_b:
        result.append((a, b))

How to redirect to Index from another controller?

You can use the overloads method RedirectToAction(string actionName, string controllerName);

Example:

RedirectToAction(nameof(HomeController.Index), "Home");

adb doesn't show nexus 5 device

What you need to do is this:

Settings | About Phone

Scroll to the bottom to build number. Tap on build number about 7 times. Each time you will get a popup message saying you are x steps away from being a developer

When you get to the final step you will get a message saying now you are a developer

Go back into settings and you will see a new setting Developer options there you will see a lot of options for developers. Enable USB debugging

Re-connect you phone to the usb, and you should see you device under adb devices.

I hope this answer helps someone else.

Trigger 404 in Spring-MVC controller?

While the marked answer is correct there is a way of achieving this without exceptions. The service is returning Optional<T> of the searched object and this is mapped to HttpStatus.OK if found and to 404 if empty.

@Controller
public class SomeController {

    @RequestMapping.....
    public ResponseEntity<Object> handleCall() {
        return  service.find(param).map(result -> new ResponseEntity<>(result, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }
}

@Service
public class Service{

    public Optional<Object> find(String param){
        if(!found()){
            return Optional.empty();
        }
        ...
        return Optional.of(data); 
    }

}

Combating AngularJS executing controller twice

My issue was really difficult to track down. In the end, the problem was occurring when the web page had missing images. The src was missing a Url. This was happening on an MVC 5 Web Controller. To fix the issue, I included transparent images when no real image is available.

<img alt="" class="logo" src="">

Choose Git merge strategy for specific files ("ours", "mine", "theirs")

Even though this question is answered, providing an example as to what "theirs" and "ours" means in the case of git rebase vs merge. See this link

Git Rebase
theirs is actually the current branch in the case of rebase. So the below set of commands are actually accepting your current branch changes over the remote branch.

# see current branch
$ git branch
... 
* branch-a
# rebase preferring current branch changes during conflicts
$ git rebase -X theirs branch-b

Git Merge
For merge, the meaning of theirs and ours is reversed. So, to get the same effect during a merge, i.e., keep your current branch changes (ours) over the remote branch being merged (theirs).

# assuming branch-a is our current version
$ git merge -X ours branch-b  # <- ours: branch-a, theirs: branch-b

python JSON object must be str, bytes or bytearray, not 'dict

json.dumps() is used to decode JSON data

import json

# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
    'int': int_data,
    'str': str_data,
    'float': float_data,
    'list': list_data,
    'nested list': nested_list
}

# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4))  # the json data will be indented

output:

String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
    1,
    1.5,
    [
        "normal string",
        1,
        1.5
    ]
]
Dictionary : {
    "int": 1,
    "str": "normal string",
    "float": 1.5,
    "list": [
        "normal string",
        1,
        1.5
    ],
    "nested list": [
        1,
        1.5,
        [
            "normal string",
            1,
            1.5
        ]
    ]
}
  • Python Object to JSON Data Conversion
|                 Python                 |  JSON  |
|:--------------------------------------:|:------:|
|                  dict                  | object |
|               list, tuple              |  array |
|                   str                  | string |
| int, float, int- & float-derived Enums | number |
|                  True                  |  true  |
|                  False                 |  false |
|                  None                  |  null  |

json.loads() is used to convert JSON data into Python data.

import json

# initialize different JSON data
arrayJson = '[1, 1.5, ["normal string", 1, 1.5]]'
objectJson = '{"a":1, "b":1.5 , "c":["normal string", 1, 1.5]}'

# convert them to Python Data
list_data = json.loads(arrayJson)
dictionary = json.loads(objectJson)

print('arrayJson to list_data :\n', list_data)
print('\nAccessing the list data :')
print('list_data[2:] =', list_data[2:])
print('list_data[:1] =', list_data[:1])

print('\nobjectJson to dictionary :\n', dictionary)
print('\nAccessing the dictionary :')
print('dictionary[\'a\'] =', dictionary['a'])
print('dictionary[\'c\'] =', dictionary['c'])

output:

arrayJson to list_data :
 [1, 1.5, ['normal string', 1, 1.5]]

Accessing the list data :
list_data[2:] = [['normal string', 1, 1.5]]
list_data[:1] = [1]

objectJson to dictionary :
 {'a': 1, 'b': 1.5, 'c': ['normal string', 1, 1.5]}

Accessing the dictionary :
dictionary['a'] = 1
dictionary['c'] = ['normal string', 1, 1.5]
  • JSON Data to Python Object Conversion
|      JSON     | Python |
|:-------------:|:------:|
|     object    |  dict  |
|     array     |  list  |
|     string    |   str  |
|  number (int) |   int  |
| number (real) |  float |
|      true     |  True  |
|     false     |  False |

Explaining the 'find -mtime' command

+1 means 2 days ago. It's rounded.

Put byte array to JSON and vice versa

Here is a good example of base64 encoding byte arrays. It gets more complicated when you throw unicode characters in the mix to send things like PDF documents. After encoding a byte array the encoded string can be used as a JSON property value.

Apache commons offers good utilities:

 byte[] bytes = getByteArr();
 String base64String = Base64.encodeBase64String(bytes);
 byte[] backToBytes = Base64.decodeBase64(base64String);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Base64_encoding_and_decoding

Java server side example:

public String getUnsecureContentBase64(String url)
        throws ClientProtocolException, IOException {

            //getUnsecureContent will generate some byte[]
    byte[] result = getUnsecureContent(url);

            // use apache org.apache.commons.codec.binary.Base64
            // if you're sending back as a http request result you may have to
            // org.apache.commons.httpclient.util.URIUtil.encodeQuery
    return Base64.encodeBase64String(result);
}

JavaScript decode:

//decode URL encoding if encoded before returning result
var uriEncodedString = decodeURIComponent(response);

var byteArr = base64DecToArr(uriEncodedString);

//from mozilla
function b64ToUint6 (nChr) {

  return nChr > 64 && nChr < 91 ?
      nChr - 65
    : nChr > 96 && nChr < 123 ?
      nChr - 71
    : nChr > 47 && nChr < 58 ?
      nChr + 4
    : nChr === 43 ?
      62
    : nChr === 47 ?
      63
    :
      0;

}

function base64DecToArr (sBase64, nBlocksSize) {

  var
    sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
    nOutLen = nBlocksSize ? Math.ceil((nInLen * 3 + 1 >> 2) / nBlocksSize) * nBlocksSize : nInLen * 3 + 1 >> 2, taBytes = new Uint8Array(nOutLen);

  for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
    nMod4 = nInIdx & 3;
    nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
    if (nMod4 === 3 || nInLen - nInIdx === 1) {
      for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
        taBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
      }
      nUint24 = 0;

    }
  }

  return taBytes;
}

iOS 7 UIBarButton back button arrow color

I had to use both:

[[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] 
                     setTitleTextAttributes:[NSDictionary 
               dictionaryWithObjectsAndKeys:[UIColor whiteColor], UITextAttributeTextColor,nil] 
                                   forState:UIControlStateNormal];

[[self.navigationController.navigationBar.subviews lastObject] setTintColor:[UIColor whiteColor]];

And works for me, thank you for everyone!

Convert float64 column to int64 in Pandas

You can need to pass in the string 'int64':

>>> import pandas as pd
>>> df = pd.DataFrame({'a': [1.0, 2.0]})  # some test dataframe

>>> df['a'].astype('int64')
0    1
1    2
Name: a, dtype: int64

There are some alternative ways to specify 64-bit integers:

>>> df['a'].astype('i8')      # integer with 8 bytes (64 bit)
0    1
1    2
Name: a, dtype: int64

>>> import numpy as np
>>> df['a'].astype(np.int64)  # native numpy 64 bit integer
0    1
1    2
Name: a, dtype: int64

Or use np.int64 directly on your column (but it returns a numpy.array):

>>> np.int64(df['a'])
array([1, 2], dtype=int64)

if else condition in blade file (laravel 5.3)

I think you are putting one too many curly brackets. Try this

 @if($user->status=='waiting')
            <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{!! $user->travel_id !!}" data-toggle="modal" data-target="#myModal">Approve/Reject</a> </td>
            @else
            <td>{!! $user->status !!}</td>
        @endif

Access Enum value using EL with JSTL

So to get my problem fully resolved I needed to do the following:

<% pageContext.setAttribute("old", Status.OLD); %>

Then I was able to do:

<c:when test="${someModel.status == old}"/>...</c:when>

which worked as expected.

Java: get all variable names in a class

As mentioned by few users, below code can help find all the fields in a given class.

TestClass testObject= new TestClass().getClass();
Method[] methods = testObject.getMethods();
for (Method method:methods)
{
    String name=method.getName();
    if(name.startsWith("get"))
    {
        System.out.println(name.substring(3));
    }else if(name.startsWith("is"))
    {
        System.out.println(name.substring(2));
    }
}

However a more interesting approach is below:

With the help of Jackson library, I was able to find all class properties of type String/integer/double, and respective values in a Map class. (without using reflections api!)

TestClass testObject = new TestClass();
com.fasterxml.jackson.databind.ObjectMapper m = new com.fasterxml.jackson.databind.ObjectMapper();

Map<String,Object> props = m.convertValue(testObject, Map.class);

for(Map.Entry<String, Object> entry : props.entrySet()){
    if(entry.getValue() instanceof String || entry.getValue() instanceof Integer || entry.getValue() instanceof Double){
        System.out.println(entry.getKey() + "-->" + entry.getValue());
    }
}

How to change the text on the action bar

getSupportActionBar().setTitle("title");

Rails: Default sort order for a rails model?

A quick update to Michael's excellent answer above.

For Rails 4.0+ you need to put your sort in a block like this:

class Book < ActiveRecord::Base
  default_scope { order('created_at DESC') }
end

Notice that the order statement is placed in a block denoted by the curly braces.

They changed it because it was too easy to pass in something dynamic (like the current time). This removes the problem because the block is evaluated at runtime. If you don't use a block you'll get this error:

Support for calling #default_scope without a block is removed. For example instead of default_scope where(color: 'red'), please use default_scope { where(color: 'red') }. (Alternatively you can just redefine self.default_scope.)

As @Dan mentions in his comment below, you can do a more rubyish syntax like this:

class Book < ActiveRecord::Base
  default_scope { order(created_at: :desc) }
end

or with multiple columns:

class Book < ActiveRecord::Base
  default_scope { order({begin_date: :desc}, :name) }
end

Thanks @Dan!

Transparent background in JPEG image

Just wanted to add that GIF "transparency" is more like missing pixels. If you use GIF then you will see jagged edges where the background and the rest of the image meet. Using PNG, you can smoothly "composite" images together, which is what you really want. Plus PNG supports highly quality images.

Don't use "Paint". There are many high quality art applications for doing art work. I think even the cell phone apps (Pixlr is pretty good and free!) and web-based image editting apps are better. I use Gimp - free for all platforms.

While a JPEG can't be made transparent in and of itself, if your goal is to reduce the size of very large image areas for the web that need to contain transparent image areas, then there is a solution. It's a bit too complicated to post details, but Google it. Basically, you create your image with transparency and then split out the alpha channel (Gimp can do this easily) as a simple 8-bit greyscale PNG. Then you export the color data as a JPG. Now your web page uses a CANVAS tag to load the JPG as image data and applies the 8-bit greyscale PNG as the Canvas's alpha channel. The browser's Canvas does the work of making the image transparent. The JPEG stores the color info (better compressed than PNG) and the PNG is reduced to 8-bit alpha so its considerably smaller. I've saved a few hundred K per image using this technique. A few people have proposed file formats that embed PNG transparency info into a JPEG's extended information fields, but these proposal's don't have wide support as of yet.

Get human readable version of file size?

Addressing the above "too small a task to require a library" issue by a straightforward implementation:

def sizeof_fmt(num, suffix='B'):
    for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)

Supports:

  • all currently known binary prefixes
  • negative and positive numbers
  • numbers larger than 1000 Yobibytes
  • arbitrary units (maybe you like to count in Gibibits!)

Example:

>>> sizeof_fmt(168963795964)
'157.4GiB'

by Fred Cirera

Maven in Eclipse: step by step installation

I have also come across the same issue and figuredout the issue here is the solution.

Lot of people assumes Eclipse and maven intergration is tough but its very eassy.

1) download the maven and unzip it in to your favorite directory.

Ex : C:\satyam\DEV_TOOLS\apache-maven-3.1.1

2) Set the environment variable for Maven(Hope every one knows where to go to set this)

In the system variable: Variable_name = M2_HOME Variable_Value =C:\satyam\DEV_TOOLS\apache-maven-3.1.1

Next in the same System Variable you will find the variable name called Path: just edit the path variable and add M2_HOME details like with the existing values.

%M2_HOME%/bin;

so in the second step now you are done setting the Maven stuff to your system.you need to cross check it whether your setting is correct or not, go to command prompt and type mvn--version it should disply the path of your Maven

3) Open the eclipse and go to Install new software and type M2E Plugin install and restart the Eclipse

with the above 3 steps you are done with Maven and Maven Plugin with eclipse

4) Maven is used .m2 folder to download all the jars, it will find in Ex: C:\Users\tempsakat.m2

under this folder one settings.xml file and one repository folder will be there

5) go to Windwo - preferences of your Eclipse and type Maven then select UserSettings from left menu then give the path of the settings.xml here .

now you are done...

Can I stretch text using CSS?

CSS font-stretch is now supported in all major browsers (except iOS Safari and Opera Mini). It is not easy to find a common font-family that supports expanding fonts, but it is easy to find fonts that support condensing, for example:

font-stretch: condense;
font-family: sans-serif, "Helvetica Neue", "Lucida Grande", Arial;

LaTeX "\indent" creating paragraph indentation / tabbing package requirement?

This is kind of a hack but the best solution that I have found is to use a description tag with no \item. This will produce an error from the latex compiler; however, the error does not prevent the pdf from being generated.

\begin{description} 
     <YOUR TEXT HERE> 
\end{description}
  • This only worked on windows latex compiler

How do I go about adding an image into a java project with eclipse?

Place the image in a source folder, not a regular folder. That is: right-click on project -> New -> Source Folder. Place the image in that source folder. Then:

InputStream input = classLoader.getResourceAsStream("image.jpg");

Note that the path is omitted. That's because the image is directly in the root of the path. You can add folders under your source folder to break it down further if you like. Or you can put the image under your existing source folder (usually called src).

Transparent scrollbar with css

Try this one, it works fine for me.

In CSS:

::-webkit-scrollbar
{
    width: 0px;
}
::-webkit-scrollbar-track-piece
{
    background-color: transparent;
    -webkit-border-radius: 6px;
}

and here is the working demo: https://jsfiddle.net/qpvnecz5/

Why are Python lambdas useful?

I'm just beginning Python and ran head first into Lambda- which took me a while to figure out.

Note that this isn't a condemnation of anything. Everybody has a different set of things that don't come easily.

Is lambda one of those 'interesting' language items that in real life should be forgotten?

No.

I'm sure there are some edge cases where it might be needed, but given the obscurity of it,

It's not obscure. The past 2 teams I've worked on, everybody used this feature all the time.

the potential of it being redefined in future releases (my assumption based on the various definitions of it)

I've seen no serious proposals to redefine it in Python, beyond fixing the closure semantics a few years ago.

and the reduced coding clarity - should it be avoided?

It's not less clear, if you're using it right. On the contrary, having more language constructs available increases clarity.

This reminds me of overflowing (buffer overflow) of C types - pointing to the top variable and overloading to set the other field values...sort of a techie showmanship but maintenance coder nightmare..

Lambda is like buffer overflow? Wow. I can't imagine how you're using lambda if you think it's a "maintenance nightmare".

Detecting when Iframe content has loaded (Cross browser)

See this blog post. It uses jQuery, but it should help you even if you are not using it.

Basically you add this to your document.ready()

$('iframe').load(function() {
    RunAfterIFrameLoaded();
});

Proper way to set response status and JSON content in a REST API made with nodejs and express

The standard way to get full HttpResponse that includes following properties

  1. body //contains your data
  2. headers
  3. ok
  4. status
  5. statusText
  6. type
  7. url

On backend, do this

router.post('/signup', (req, res, next) => {
    // res object have its own statusMessage property so utilize this
    res.statusText = 'Your have signed-up succesfully'
    return res.status(200).send('You are doing a great job')
})

On Frontend e.g. in Angular, just do:

let url = `http://example.com/signup`
this.http.post(url, { profile: data }, {
    observe: 'response' // remember to add this, you'll get pure HttpResponse
}).subscribe(response => {
    console.log(response)
})

Pylint "unresolved import" error in Visual Studio Code

None of the previous answers worked for me. Adding both of the lines below to my settings.json file did, however.

"python.analysis.disabled": [
    "unresolved-import"
],
"python.linting.pylintArgs": ["--load-plugin","pylint_protobuf"]

The first line really just hides the linting error. Certainly not a permanent solution, but de-clutters the screen.

This answer gave me the second line: VS Code PyLint Error E0602 (undefined variable) with ProtoBuf compiled Python Structure

Maybe someone who understands Python more than me can explain that one more.

How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

My favorite datetime parser is DateTime::Format::ISO8601 Once you've got that working, you'll have a DateTime object, easily convertable to epoch seconds with epoch()

How to assign a NULL value to a pointer in python?

All objects in python are implemented via references so the distinction between objects and pointers to objects does not exist in source code.

The python equivalent of NULL is called None (good info here). As all objects in python are implemented via references, you can re-write your struct to look like this:

class Node:
    def __init__(self): #object initializer to set attributes (fields)
        self.val = 0
        self.right = None
        self.left = None

And then it works pretty much like you would expect:

node = Node()
node.val = some_val #always use . as everything is a reference and -> is not used
node.left = Node()

Note that unlike in NULL in C, None is not a "pointer to nowhere": it is actually the only instance of class NoneType. Therefore, as None is a regular object, you can test for it just like any other object:

if node.left == None:
   print("The left node is None/Null.")

Although since None is a singleton instance, it is considered more idiomatic to use is and compare for reference equality:

if node.left is None:
   print("The left node is None/Null.")

CSS vertical alignment text inside li

line-height is how you vertically align text. It is pretty standard and I don't consider it a "hack". Just add line-height: 100px to your ul.catBlock li and it will be fine.

In this case you may have to add it to ul.catBlock li a instead since all of the text inside the li is also inside of an a. I have seen some weird things happen when you do this, so try both and see which one works.

Javascript replace all "%20" with a space

If you want to use jQuery you can use .replaceAll()

How to check if String is null

You can use the null coalescing double question marks to test for nulls in a string or other nullable value type:

textBox1.Text = s ?? "Is null";

The operator '??' asks if the value of 's' is null and if not it returns 's'; if it is null it returns the value on the right of the operator.

More info here: https://msdn.microsoft.com/en-us/library/ms173224.aspx

And also worth noting there's a null-conditional operator ?. and ?[ introduced in C# 6.0 (and VB) in VS2015

textBox1.Text = customer?.orders?[0].description ?? "n/a";

This returns "n/a" if description is null, or if the order is null, or if the customer is null, else it returns the value of description.

More info here: https://msdn.microsoft.com/en-us/library/dn986595.aspx

What is referencedColumnName used for in JPA?

Quoting API on referencedColumnName:

The name of the column referenced by this foreign key column.

Default (only applies if single join column is being used): The same name as the primary key column of the referenced table.

Q/A

Where this would be used?

When there is a composite PK in referenced table, then you need to specify column name you are referencing.

What's the difference between align-content and align-items?

align-content

align-content controls the cross-axis (i.e. vertical direction if the flex-direction is row, and horizontal if the flex-direction is column) positioning of multiple lines relative to each other.

(Think lines of a paragraph being vertically spread out, stacked toward the top, stacked toward the bottom. This is under a flex-direction row paradigm).

align-items

align-items controls the cross-axis of an individual line of flex elements.

(Think how an individual line of a paragraph is aligned, if it contains some normal text and some taller text like math equations. In that case, will it be the bottom, top, or center of each type of text in a line that will be aligned?)

How to check for empty array in vba macro

As you are dealing with a string array, have you considered Join?

If Len(Join(FileNamesList)) > 0 Then

How do you make an element "flash" in jQuery

Like fadein / fadeout you could use animate css / delay

$(this).stop(true, true).animate({opacity: 0.1}, 100).delay(100).animate({opacity: 1}, 100).animate({opacity: 0.1}, 100).delay(100).animate({opacity: 1}, 100);

Simple and flexible

Including a .js file within a .js file

I use @gnarf's method, though I fall back on document.writelning a <script> tag for IE<7 as I couldn't get DOM creation to work reliably in IE6 (and TBH didn't care enough to put much effort into it). The core of my code is:

if (horus.script.broken) {
    document.writeln('<script type="text/javascript" src="'+script+'"></script>');   
    horus.script.loaded(script);
} else {
    var s=document.createElement('script');
    s.type='text/javascript';
    s.src=script;
    s.async=true;

    if (horus.brokenDOM){
        s.onreadystatechange=
            function () {
                if (this.readyState=='loaded' || this.readyState=='complete'){
                    horus.script.loaded(script);
                }
        }
    }else{
        s.onload=function () { horus.script.loaded(script) };
    }

    document.head.appendChild(s);
}

where horus.script.loaded() notes that the javascript file is loaded, and calls any pending uncalled routines (saved by autoloader code).

java.io.IOException: Server returned HTTP response code: 500

The problem must be with the parameters you are passing(You must be passing blank parameters). For example : http://www.myurl.com?id=5&name= Check if you are handling this at the server you are calling.

Sort objects in an array alphabetically on one property of the array

// Sorts an array of objects "in place". (Meaning that the original array will be modified and nothing gets returned.)
function sortOn (arr, prop) {
    arr.sort (
        function (a, b) {
            if (a[prop] < b[prop]){
                return -1;
            } else if (a[prop] > b[prop]){
                return 1;
            } else {
                return 0;   
            }
        }
    );
}

//Usage example:

var cars = [
        {make:"AMC",        model:"Pacer",  year:1978},
        {make:"Koenigsegg", model:"CCGT",   year:2011},
        {make:"Pagani",     model:"Zonda",  year:2006},
        ];

// ------- make -------
sortOn(cars, "make");
console.log(cars);

/* OUTPUT:
AMC         : Pacer : 1978
Koenigsegg  : CCGT  : 2011
Pagani      : Zonda : 2006
*/



// ------- model -------
sortOn(cars, "model");
console.log(cars);

/* OUTPUT:
Koenigsegg  : CCGT  : 2011
AMC         : Pacer : 1978
Pagani      : Zonda : 2006
*/



// ------- year -------
sortOn(cars, "year");
console.log(cars);

/* OUTPUT:
AMC         : Pacer : 1978
Pagani      : Zonda : 2006
Koenigsegg  : CCGT  : 2011
*/

Precision String Format Specifier In Swift

//It will more help, by specify how much decimal Point you want.
let decimalPoint = 2
let floatAmount = 1.10001
let amountValue = String(format: "%0.*f", decimalPoint, floatAmount)

Change Default branch in gitlab

To change the default branch in Gitlab 7.7.2:

  • Click Settings in the left-hand bar
  • Change the Default Branch to the desired branch
  • Click Save Changes.

Excel Create Collapsible Indented Row Hierarchies

A much easier way is to go to Data and select Group or Subtotal. Instant collapsible rows without messing with pivot tables or VBA.

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

How to create a link to a directory

Symbolic or soft link (files or directories, more flexible and self documenting)

#     Source                             Link
ln -s /home/jake/doc/test/2000/something /home/jake/xxx

Hard link (files only, less flexible and not self documenting)

#   Source                             Link
ln /home/jake/doc/test/2000/something /home/jake/xxx

More information: man ln


/home/jake/xxx is like a new directory. To avoid "is not a directory: No such file or directory" error, as @trlkly comment, use relative path in the target, that is, using the example:

  1. cd /home/jake/
  2. ln -s /home/jake/doc/test/2000/something xxx

How to get a table cell value using jQuery?

This works

$(document).ready(function() {
    for (var row = 0; row < 3; row++) {
        for (var col = 0; col < 3; col++) {
            $("#tbl").children().children()[row].children[col].innerHTML = "H!";
        }
    }
});

SQLite Query in Android to count rows

If you are using ContentProvider then you can use:

Cursor cursor = getContentResolver().query(CONTENT_URI, new String[] {"count(*)"},
            uname=" + loginname + " and pwd=" + loginpass, null, null);
    cursor.moveToFirst();
    int count = cursor.getInt(0);

copy-item With Alternate Credentials

Since PowerShell doesn't support "-Credential" usage via many of the cmdlets (very annoying), and mapping a network drive via WMI proved to be very unreliable in PS, I found pre-caching the user credentials via a net use command to work quite well:

# cache credentials for our network path
net use \\server\C$ $password /USER:$username

Any operation that uses \\server\C$ in the path seems to work using the *-item cmdlets.

You can also delete the share when you're done:

net use \\server\C$ /delete

Convenient way to parse incoming multipart/form-data parameters in a Servlet

multipart/form-data encoded requests are indeed not by default supported by the Servlet API prior to version 3.0. The Servlet API parses the parameters by default using application/x-www-form-urlencoded encoding. When using a different encoding, the request.getParameter() calls will all return null. When you're already on Servlet 3.0 (Glassfish 3, Tomcat 7, etc), then you can use HttpServletRequest#getParts() instead. Also see this blog for extended examples.

Prior to Servlet 3.0, a de facto standard to parse multipart/form-data requests would be using Apache Commons FileUpload. Just carefully read its User Guide and Frequently Asked Questions sections to learn how to use it. I've posted an answer with a code example before here (it also contains an example targeting Servlet 3.0).

'Java' is not recognized as an internal or external command

if you have cygwin installed in the Windows Box, or using UNIX Shell then

Issue bash#which java

This will tell you whether java is in your classpath or NOT.

How to clear the logs properly for a Docker container?

You can set up logrotate to clear the logs periodically.

Example file in /etc/logrotate.d/docker-logs

/var/lib/docker/containers/*/*.log {
 rotate 7
 daily
 compress
 size=50M
 missingok
 delaycompress
 copytruncate
}

What is a StackOverflowError?

The term "stack overrun (overflow)" is often used but a misnomer; attacks do not overflow the stack but buffers on the stack.

-- from lecture slides of Prof. Dr. Dieter Gollmann

How many characters can you store with 1 byte?

The syntax of TINYINT data type is TINYINT(M),

where M indicates the maximum display width (used only if your MySQL client supports it).

The (m) indicates the column width in SELECT statements; however, it doesn't control the accepted range of numbers for that field.

A TINYINT is an 8-bit integer value, a BIT field can store between 1 bit, BIT(1), and 64 >bits, BIT(64). For a boolean values, BIT(1) is pretty common.

TINYINT()

JWT authentication for ASP.NET Web API

In my case the JWT is created by a separate API so ASP.NET need only decode and validate it. In contrast to the accepted answer we're using RSA which is a non-symmetric algorithm, so the SymmetricSecurityKey class mentioned above won't work.

Here's the result.

using Microsoft.IdentityModel.Protocols;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Threading;
using System.Threading.Tasks;

    public static async Task<JwtSecurityToken> VerifyAndDecodeJwt(string accessToken)
    {
        try
        {
            var configurationManager = new ConfigurationManager<OpenIdConnectConfiguration>($"{securityApiOrigin}/.well-known/openid-configuration", new OpenIdConnectConfigurationRetriever());
            var openIdConfig = await configurationManager.GetConfigurationAsync(CancellationToken.None);
            var validationParameters = new TokenValidationParameters()
            {
                ValidateLifetime = true,
                ValidateAudience = false,
                ValidateIssuer = false,
                RequireSignedTokens = true,
                IssuerSigningKeys = openIdConfig.SigningKeys,
            };
            new JwtSecurityTokenHandler().ValidateToken(accessToken, validationParameters, out var validToken);
            // threw on invalid, so...
            return validToken as JwtSecurityToken;
        }
        catch (Exception ex)
        {
            logger.Info(ex.Message);
            return null;
        }
    }

Find the similarity metric between two strings

There are many metrics to define similarity and distance between strings as mentioned above. I will give my 5 cents by showing an example of Jaccard similarity with Q-Grams and an example with edit distance.

The libraries

from nltk.metrics.distance import jaccard_distance
from nltk.util import ngrams
from nltk.metrics.distance  import edit_distance

Jaccard Similarity

1-jaccard_distance(set(ngrams('Apple', 2)), set(ngrams('Appel', 2)))

and we get:

0.33333333333333337

And for the Apple and Mango

1-jaccard_distance(set(ngrams('Apple', 2)), set(ngrams('Mango', 2)))

and we get:

0.0

Edit Distance

edit_distance('Apple', 'Appel')

and we get:

2

And finally,

edit_distance('Apple', 'Mango')

and we get:

5

Cosine Similarity on Q-Grams (q=2)

Another solution is to work with the textdistance library. I will provide an example of Cosine Similarity

import textdistance
1-textdistance.Cosine(qval=2).distance('Apple', 'Appel')

and we get:

0.5

Make content horizontally scroll inside a div

The problem is that your imgs will always bump down to the next line because of the containing div.

In order to get around this, you need to place the imgs in their own div with a width wide enough to hold all of them. Then you can use your styles as is.

So, when I set the imgs to 120px each and place them inside a

div#insideDiv{
    width:800px;
}

it all works.

Adjust width as necessary.

See http://jsfiddle.net/jasongennaro/8YfRe/

z-index not working with position absolute

z-index only applies to elements that have been given an explicit position. Add position:relative to #popupContent and you should be good to go.

How do I query using fields inside the new PostgreSQL JSON datatype?

With Postgres 9.3+, just use the -> operator. For example,

SELECT data->'images'->'thumbnail'->'url' AS thumb FROM instagram;

see http://clarkdave.net/2013/06/what-can-you-do-with-postgresql-and-json/ for some nice examples and a tutorial.

Execution failed for task ':app:processDebugResources' even with latest build tools

I stucked for two days and finally found my solution. I changed the compileSdkVersion to 27 (same with buildToolsVersion)

compileSdkVersion 27
buildToolsVersion '27.0.3'

Way to get number of digits in an int?

Marian's Solution, now with Ternary:

 public int len(int n){
        return (n<100000)?((n<100)?((n<10)?1:2):(n<1000)?3:((n<10000)?4:5)):((n<10000000)?((n<1000000)?6:7):((n<100000000)?8:((n<1000000000)?9:10)));
    }

Because we can.

time data does not match format

To compare date time, you can try this. Datetime format can be changed

from datetime import datetime

>>> a = datetime.strptime("10/12/2013", "%m/%d/%Y")
>>> b = datetime.strptime("10/15/2013", "%m/%d/%Y")
>>> a>b
False

array filter in python?

tuple(set([6, 7, 8, 9, 10, 11, 12]).difference([6, 9, 12]))

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

TypeError: 'bool' object is not callable

Actually you can fix it with following steps -

  1. Do cls.__dict__
  2. This will give you dictionary format output which will contain {'isFilled':True} or {'isFilled':False} depending upon what you have set.
  3. Delete this entry - del cls.__dict__['isFilled']
  4. You will be able to call the method now.

In this case, we delete the entry which overrides the method as mentioned by BrenBarn.

npm install errors with Error: ENOENT, chmod

I was getting the error "Error: ENOENT, stat 'C:\Users\userName\AppData\Roaming\npm'. But there was no such directory. Created the directory and the npm install started working

How to rollback or commit a transaction in SQL Server

The good news is a transaction in SQL Server can span multiple batches (each exec is treated as a separate batch.)

You can wrap your EXEC statements in a BEGIN TRANSACTION and COMMIT but you'll need to go a step further and rollback if any errors occur.

Ideally you'd want something like this:

BEGIN TRY
    BEGIN TRANSACTION 
        exec( @sqlHeader)
        exec(@sqlTotals)
        exec(@sqlLine)
    COMMIT
END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK
END CATCH

The BEGIN TRANSACTION and COMMIT I believe you are already familiar with. The BEGIN TRY and BEGIN CATCH blocks are basically there to catch and handle any errors that occur. If any of your EXEC statements raise an error, the code execution will jump to the CATCH block.

Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.

What is the maximum length of a URL in different browsers?

The longest URLs I came across are data URLs

Example image URL from Google image results (11747 characters)

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBhQSERIUExQUFRUUFxcXFhQYFBQXGBgYFhkVGBkVFxUXHCYfGBojGRQVHy8gJCcpLCwsFh4xNTAqNSYrLCkBCQoKDgwOGg8PGiokHyQpLDUqKSwsLCksKSwpKSwsLCwpKSkpLCwpLCksKSwpLCkpLCwsLCkpKSwsLCwsLDQsLP/AABEIAM0A9gMBIgACEQEDEQH/xAAcAAACAgMBAQAAAAAAAAAAAAAABQQGAgMHAQj/xABTEAACAAQCBAcLBgsFBwUAAAABAgADBBESIQUGMUEHEyJRYYGRFBYyVHF0lKGxs9IjNEKS0dMXMzVSYmRypMHj8GOTo7LiJENzosLh8RVTgoPD/8QAGQEBAAMBAQAAAAAAAAAAAAAAAAECAwQF/8QAJxEAAgIBAwMEAgMAAAAAAAAAAAECEQMSITEEE0EiUWGBkfAyceH/2gAMAwEAAhEDEQA/AOiaq6q0b0NGzUlMzNTySWMiUSSZaEkkrmbw17z6LxOl9HlfDBqf8wovNpHu0hvACjvPovE6X0eV8MHefReJ0vo8r4YbwQAo7z6LxOl9HlfDB3n0XidL6PK+GG8EAKO8+i8TpfR5Xwwd59F4nS+jyvhhsTaKnX69gzGlUiCc6+FMZsMpTuBYAlj0LnFoxcuCG0ht3n0XidL6PK+GDvPovE6X0eV8MIX0jpQ8pe5SPzeKndmLFl2QuPCpMpnwV1Pg345ZuLc4DbfbG0enlJelp/ZR5EuS3959F4nS+jyvhg7z6LxOl9HlfDDCjrFmosxCSrgM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ERRNloZo0WiuNrt/Y/4n+iPF1z/ALL/ABP9MKILCZF9sApQd1+mESa4DfJJ/wDst/0RtbXUW/En+9/0QLEPT1EqSph3mel/7t4Ig6X0+JqOOLteYreHfYrC3g9MeRJFH//Z

phpmailer error "Could not instantiate mail function"

$mail->AddAddress($address, "her name");

should be changed to

$mail->AddAddress($address);

This worked for my case..

How to insert a new line in strings in Android

I use <br> in a CDATA tag. As an example, my strings.xml file contains an item like this:

<item><![CDATA[<b>My name is John</b><br>Nice to meet you]]></item>

and prints

My name is John
Nice to meet you

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

getPathInfo() gives the extra path information after the URI, used to access your Servlet, where as getRequestURI() gives the complete URI.

I would have thought they would be different, given a Servlet must be configured with its own URI pattern in the first place; I don't think I've ever served a Servlet from root (/).

For example if Servlet 'Foo' is mapped to URI '/foo' then I would have thought the URI:

/foo/path/to/resource

Would result in:

RequestURI = /foo/path/to/resource

and

PathInfo = /path/to/resource

PowerShell Connect to FTP server and get files

Remote pick directory path should be the exact path on the ftp server you are tryng to access.. here is the script to download files from the server.. you can add or modify with SSLMode..

#ftp server 
$ftp = "ftp://example.com/" 
$user = "XX" 
$pass = "XXX"
$SetType = "bin"  
$remotePickupDir = Get-ChildItem 'c:\test' -recurse
$webclient = New-Object System.Net.WebClient 

$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)  
foreach($item in $remotePickupDir){ 
    $uri = New-Object System.Uri($ftp+$item.Name) 
    #$webclient.UploadFile($uri,$item.FullName)
    $webclient.DownloadFile($uri,$item.FullName)
}

Can't draw Histogram, 'x' must be numeric

Because of the thousand separator, the data will have been read as 'non-numeric'. So you need to convert it:

 we <- gsub(",", "", we)   # remove comma
 we <- as.numeric(we)      # turn into numbers

and now you can do

 hist(we)

and other numeric operations.

How to highlight a selected row in ngRepeat?

Each row has an ID. All you have to do is to send this ID to the function setSelected(), store it (in $scope.idSelectedVote for instance), and then check for each row if the selected ID is the same as the current one. Here is a solution (see the documentation for ngClass, if needed):

$scope.idSelectedVote = null;
$scope.setSelected = function (idSelectedVote) {
   $scope.idSelectedVote = idSelectedVote;
};
<ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected: vote.id === idSelectedVote}">
    ...
</ul>

Plunker

How to use support FileProvider for sharing content to other apps?

In my app FileProvider works just fine, and I am able to attach internal files stored in files directory to email clients like Gmail,Yahoo etc.

In my manifest as mentioned in the Android documentation I placed:

<provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.package.name.fileprovider"
        android:grantUriPermissions="true"
        android:exported="false">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/filepaths" />
    </provider>

And as my files were stored in the root files directory, the filepaths.xml were as follows:

 <paths>
<files-path path="." name="name" />

Now in the code:

 File file=new File(context.getFilesDir(),"test.txt");

 Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND_MULTIPLE);

 shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
                                     "Test");

 shareIntent.setType("text/plain");

 shareIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
                                 new String[] {"email-address you want to send the file to"});

   Uri uri = FileProvider.getUriForFile(context,"com.package.name.fileprovider",
                                                   file);

                ArrayList<Uri> uris = new ArrayList<Uri>();
                uris.add(uri);

                shareIntent .putParcelableArrayListExtra(Intent.EXTRA_STREAM,
                                                        uris);


                try {
                   context.startActivity(Intent.createChooser(shareIntent , "Email:").addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));                                                      


                }
                catch(ActivityNotFoundException e) {
                    Toast.makeText(context,
                                   "Sorry No email Application was found",
                                   Toast.LENGTH_SHORT).show();
                }
            }

This worked for me.Hope this helps :)

Fitting iframe inside a div

I think I may have a better solution for having a fully responsive iframe (a vimeo video in my case) embed on your site. Nest the iframe in a div. Give them the following styles:

div {
    width: 100%;
    height: 0;
    padding-bottom: 56%; /* Change this till it fits the dimensions of your video */
    position: relative;
}

div iframe {
    width: 100%;
    height: 100%;
    position: absolute;
    display: block;
    top: 0;
    left: 0;
}

Just did it now for a client, and it seems to be working: http://themilkrunsa.co.za/

Where are static methods and static variables stored in Java?

In addition to the Thomas's answer , static variable are stored in non heap area which is called Method Area.

How to make a stable two column layout in HTML/CSS

Piece of cake.

Use 960Grids Go to the automatic layout builder and make a two column, fluid design. Build a left column to the width of grids that works....this is the only challenge using grids and it's very easy once you read a tutorial. In a nutshell, each column in a grid is a certain width, and you set the amount of columns you want to use. To get a column that's exactly a certain width, you have to adjust your math so that your column width is exact. Not too tough.

No chance of wrapping because others have already fought that battle for you. Compatibility back as far as you likely will ever need to go. Quick and easy....Now, download, customize and deploy.

Voila. Grids FTW.

Difference between CR LF, LF and CR line break types?

CR and LF are control characters, respectively coded 0x0D (13 decimal) and 0x0A (10 decimal).

They are used to mark a line break in a text file. As you indicated, Windows uses two characters the CR LF sequence; Unix only uses LF and the old MacOS ( pre-OSX MacIntosh) used CR.

An apocryphal historical perspective:

As indicated by Peter, CR = Carriage Return and LF = Line Feed, two expressions have their roots in the old typewriters / TTY. LF moved the paper up (but kept the horizontal position identical) and CR brought back the "carriage" so that the next character typed would be at the leftmost position on the paper (but on the same line). CR+LF was doing both, i.e. preparing to type a new line. As time went by the physical semantics of the codes were not applicable, and as memory and floppy disk space were at a premium, some OS designers decided to only use one of the characters, they just didn't communicate very well with one another ;-)

Most modern text editors and text-oriented applications offer options/settings etc. that allow the automatic detection of the file's end-of-line convention and to display it accordingly.

text-align: right on <select> or <option>

The following CSS will right-align both the arrow and the options:

_x000D_
_x000D_
select { text-align-last: right; }_x000D_
option { direction: rtl; }
_x000D_
<!-- example usage -->_x000D_
Choose one: <select>_x000D_
  <option>The first option</option>_x000D_
  <option>A second, fairly long option</option>_x000D_
  <option>Last</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Creating PHP class instance with a string

Yes, you can!

$str = 'One';
$class = 'Class'.$str;
$object = new $class();

When using namespaces, supply the fully qualified name:

$class = '\Foo\Bar\MyClass'; 
$instance = new $class();

Other cool stuff you can do in php are:
Variable variables:

$personCount = 123;
$varname = 'personCount';
echo $$varname; // echo's 123

And variable functions & methods.

$func = 'my_function';
$func('param1'); // calls my_function('param1');

$method = 'doStuff';
$object = new MyClass();
$object->$method(); // calls the MyClass->doStuff() method. 

SVN: Folder already under version control but not comitting?

I had a similar-looking problem after adding a directory tree which contained .svn directories (because it was an svn:external in its source environment): svn status told me "?", but when trying to add it, it was "already under version control".

Since no other versioned directories were present, I did

find . -mindepth 2 -name '.svn' -exec rm -rf '{}' \;

to remove the wrong .svn directories; after doing this, I was able to add the new directory.

Note:

  • If other versioned directories are contained, the find expression must be changed to be more specific
  • If unsure, first omit the "-exec ..." part to see what would be deleted

What MIME type should I use for CSV?

You should use "text/csv" according to RFC 4180.

How to convert const char* to char* in C?

A const to a pointer indicates a "read-only" memory location. Whereas the ones without const are a read-write memory areas. So, you "cannot" convert a const(read-only location) to a normal(read-write) location.

The alternate is to copy the data to a different read-write location and pass this pointer to the required function. You may use strdup() to perform this action.

jQuery If DIV Doesn't Have Class "x"

When you are checking if an element has or does not have a class, make sure you didn't accidentally put a dot in the class name:

<div class="className"></div>

$('div').hasClass('className');
$('div').hasClass('.className'); #will not work!!!!

After a long time of staring at my code I realized I had done this. A little typo like this took me an hour to figure out what I had done wrong. Check your code!

jquery variable syntax

The dollarsign as a prefix in the var name is a usage from the concept of the hungarian notation.

Angular 5 - Copy to clipboard

Modified version of jockeisorby's answer that fixes the event handler not being properly removed.

copyToClipboard(item): void {
    let listener = (e: ClipboardEvent) => {
        e.clipboardData.setData('text/plain', (item));
        e.preventDefault();
    };

    document.addEventListener('copy', listener);
    document.execCommand('copy');
    document.removeEventListener('copy', listener);
}

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

I think the annotation you are looking for is:

public class CompanyName implements Serializable {
//...
@JoinColumn(name = "COMPANY_ID", referencedColumnName = "COMPANY_ID", insertable = false, updatable = false)
private Company company;

And you should be able to use similar mappings in a hbm.xml as shown here (in 23.4.2):

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/example-mappings.html

React Error: Target Container is not a DOM Element

I had encountered the same error with React version 16. This error comes when the Javascript that tries to render the React component is included before the static parent dom element in the html. Fix is same as the accepted answer, i.e. the JavaScript should get included only after the static parent dom element has been defined in the html.

How to make rectangular image appear circular with CSS

This one works well if you know height and width:

img {
  object-fit: cover;
  border-radius: '50%';
  width: 100px;
  height: 100px;
}

via https://medium.com/@chrisnager/center-and-crop-images-with-a-single-line-of-css-ad140d5b4a87