Programs & Examples On #Nvelocity

NVelocity is a port of the Apache Jakarta Velocity project. It is a simple, easy to learn and extensible template engine.

How to implement the ReLU function in Numpy

numpy didn't have the function of relu, but you define it by yourself as follow:

def relu(x):
    return np.maximum(0, x)

for example:

arr = np.array([[-1,2,3],[1,2,3]])

ret = relu(arr)
print(ret) # print [[0 2 3] [1 2 3]]

Currency Formatting in JavaScript

You could use toPrecision() and toFixed() methods of Number type. Check this link How can I format numbers as money in JavaScript?

How to determine the encoding of text?

EDIT: chardet seems to be unmantained but most of the answer applies. Check https://pypi.org/project/charset-normalizer/ for an alternative

Correctly detecting the encoding all times is impossible.

(From chardet FAQ:)

However, some encodings are optimized for specific languages, and languages are not random. Some character sequences pop up all the time, while other sequences make no sense. A person fluent in English who opens a newspaper and finds “txzqJv 2!dasd0a QqdKjvz” will instantly recognize that that isn't English (even though it is composed entirely of English letters). By studying lots of “typical” text, a computer algorithm can simulate this kind of fluency and make an educated guess about a text's language.

There is the chardet library that uses that study to try to detect encoding. chardet is a port of the auto-detection code in Mozilla.

You can also use UnicodeDammit. It will try the following methods:

  • An encoding discovered in the document itself: for instance, in an XML declaration or (for HTML documents) an http-equiv META tag. If Beautiful Soup finds this kind of encoding within the document, it parses the document again from the beginning and gives the new encoding a try. The only exception is if you explicitly specified an encoding, and that encoding actually worked: then it will ignore any encoding it finds in the document.
  • An encoding sniffed by looking at the first few bytes of the file. If an encoding is detected at this stage, it will be one of the UTF-* encodings, EBCDIC, or ASCII.
  • An encoding sniffed by the chardet library, if you have it installed.
  • UTF-8
  • Windows-1252

Git branching: master vs. origin/master vs. remotes/origin/master

I would try to make @ErichBSchulz's answer simpler for beginners:

  • origin/master is the state of master branch on remote repository
  • master is the state of master branch on local repository

How do I make a text input non-editable?

<input type="text" value="3" class="field left" readonly>

No styling necessary.

See <input> on MDN https://developer.mozilla.org/en/docs/Web/HTML/Element/input#Attributes

How to Convert Datetime to Date in dd/MM/yyyy format

Give a different alias

SELECT  Convert(varchar,A.InsertDate,103) as converted_Tran_Date from table as A
order by A.InsertDate 

Fatal error: Call to undefined function sqlsrv_connect()

When you install third-party extensions you need to make sure that all the compilation parameters match:

  • PHP version
  • Architecture (32/64 bits)
  • Compiler (VC9, VC10, VC11...)
  • Thread safety

Common glitches includes:

  • Editing the wrong php.ini file (that's typical with bundles); the right path is shown in phpinfo().
  • Forgetting to restart Apache.
  • Not being able to see the startup errors; those should show up in Apache logs, but you can also use the command line to diagnose it, e.g.:

    php -d display_startup_errors=1 -d error_reporting=-1 -d display_errors -c "C:\Path\To\php.ini" -m
    

If everything's right you should see sqlsrv in the command output and/or phpinfo() (depending on what SAPI you're configuring):

[PHP Modules]
bcmath
calendar
Core
[...]
SPL
sqlsrv
standard
[...]

phpinfo()

Google Authenticator available as a public service?

You can use my solution, posted as the answer to my question (there is full Python code and explanation):

Google Authenticator implementation in Python

It is rather easy to implement it in PHP or Perl, I think. If you have any problems with this, please let me know.

I have also posted my code on GitHub as Python module.

JavaScript before leaving the page

onunload (or onbeforeunload) cannot redirect the user to another page. This is for security reasons.

If you want to show a prompt before the user leaves the page, use onbeforeunload:

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

Or with jQuery:

$(window).bind('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

This will just ask the user if they want to leave the page or not, you cannot redirect them if they select to stay on the page. If they select to leave, the browser will go where they told it to go.

You can use onunload to do stuff before the page is unloaded, but you cannot redirect from there (Chrome 14+ blocks alerts inside onunload):

window.onunload = function() {
    alert('Bye.');
}

Or with jQuery:

$(window).unload(function(){
  alert('Bye.');
});

Java String.split() Regex

You could split on a word boundary with \b

Getting the error "Missing $ inserted" in LaTeX

I think it gives the error because of the underscore symbol.

Note : underscore symbol should not be written directly, you have to write like as \_.

So fix these kind special symbol errors.

Cmake is not able to find Python-libraries

For me was helpful next:

> apt-get install python-dev python3-dev

What is the best (idiomatic) way to check the type of a Python variable?

I think it might be preferred to actually do

if isinstance(x, str):
    do_something_with_a_string(x)
elif isinstance(x, dict):
    do_somethting_with_a_dict(x)
else:
    raise ValueError

2 Alternate forms, depending on your code one or the other is probably considered better than that even. One is to not look before you leap

try:
  one, two = tupleOrValue
except TypeError:
  one = tupleOrValue
  two = None

The other approach is from Guido and is a form of function overloading which leaves your code more open ended.

http://www.artima.com/weblogs/viewpost.jsp?thread=155514

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

Clear all State

dbContextGlobalERP.ChangeTracker.Entries().Where(e => e.Entity != null).ToList().ForEach(e => e.State = EntityState.Detached);

href overrides ng-click in Angular.js

In Angular, <a>s are directives. As such, if you have an empty href or no href, Angular will call event.preventDefault.

From the source:

    element.on('click', function(event){
      // if we have no href url, then don't navigate anywhere.
      if (!element.attr(href)) {
        event.preventDefault();
      }
    });

Here's a plnkr demonstrating the missing href scenario.

How to un-commit last un-pushed git commit without losing the changes

PLease make sure to backup your changes before running these commmand in a separate folder

git checkout branch_name

Checkout on your branch

git merge --abort

Abort the merge

git status

Check status of the code after aborting the merge

git reset --hard origin/branch_name

these command will reset your changes and align your code with the branch_name (branch) code.

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

I had similar problem it was caused by MS UNIT Test DLL. My WPF application was compiled as x86 but unit test DLL (referenced EXE file) as "Any CPU". I changed unit test DLL to be compiled for x86 (same as EXE) and it was resovled.

How to comment out a block of code in Python

Hide the triple quotes in a context that won't be mistaken for a docstring, eg:

'''
...statements...
''' and None

or:

if False: '''
...statements...
'''

strdup() - what does it do in C?

The strdup() function is a shorthand for string duplicate, it takes in a parameter as a string constant or a string literal and allocates just enough space for the string and writes the corresponding characters in the space allocated and finally returns the address of the allocated space to the calling routine.

Linux find file names with given string recursively

Use the find command,

find . -type f -name "*John*"

How to avoid "Permission denied" when using pip with virtualenv

I didn't create my virtualenv using sudo. So Sebastian's answer didn't apply to me. My project is called utils. I checked utils directory and saw this:

-rw-r--r--   1 macuser  staff   983  6 Jan 15:17 README.md
drwxr-xr-x   6 root     staff   204  6 Jan 14:36 utils.egg-info
-rw-r--r--   1 macuser  staff    31  6 Jan 15:09 requirements.txt

As you can see, utils.egg-info is owned by root not macuser. That is why it was giving me permission denied error. I also had to remove /Users/macuser/.virtualenvs/armoury/lib/python2.7/site-packages/utils.egg-link as it was created by root as well. I did pip install -e . again after removing those, and it worked.

True/False vs 0/1 in MySQL

If you are into performance, then it is worth using ENUM type. It will probably be faster on big tables, due to the better index performance.

The way of using it (source: http://dev.mysql.com/doc/refman/5.5/en/enum.html):

CREATE TABLE shirts (
    name VARCHAR(40),
    size ENUM('x-small', 'small', 'medium', 'large', 'x-large')
);

But, I always say that explaining the query like this:

EXPLAIN SELECT * FROM shirts WHERE size='medium';

will tell you lots of information about your query and help on building a better table structure. For this end, it is usefull to let phpmyadmin Propose a table table structure - but this is more a long time optimisation possibility, when the table is already filled with lots of data.

Converting a list to a set changes element order

Building on Sven's answer, I found using collections.OrderedDict like so helped me accomplish what you want plus allow me to add more items to the dict:

import collections

x=[1,2,20,6,210]
z=collections.OrderedDict.fromkeys(x)
z
OrderedDict([(1, None), (2, None), (20, None), (6, None), (210, None)])

If you want to add items but still treat it like a set you can just do:

z['nextitem']=None

And you can perform an operation like z.keys() on the dict and get the set:

z.keys()
[1, 2, 20, 6, 210]

Concept behind putting wait(),notify() methods in Object class

wait and notify operations work on implicit lock, and implicit lock is something that make inter thread communication possible. And all objects have got their own copy of implicit object. so keeping wait and notify where implicit lock lives is a good decision.

Alternatively wait and notify could have lived in Thread class as well. than instead of wait() we may have to call Thread.getCurrentThread().wait(), same with notify. For wait and notify operations there are two required parameters, one is thread who will be waiting or notifying other is implicit lock of the object . both are these could be available in Object as well as thread class as well. wait() method in Thread class would have done the same as it is doing in Object class, transition current thread to waiting state wait on the lock it had last acquired.

So yes i think wait and notify could have been there in Thread class as well but its more like a design decision to keep it in object class.

how do I print an unsigned char as hex in c++ using ostream?

In C++20 you'll be able to use std::format to do this:

std::cout << std::format("a is {:x}; b is {:x}\n", a, b);

Output:

a is 0; b is ff

In the meantime you can use the {fmt} library, std::format is based on. {fmt} also provides the print function that makes this even easier and more efficient (godbolt):

fmt::print("a is {:x}; b is {:x}\n", a, b);

Disclaimer: I'm the author of {fmt} and C++20 std::format.

How do I use Wget to download all images into a single folder, from a URL?

The proposed solutions are perfect to download the images and if it is enough for you to save all the files in the directory you are using. But if you want to save all the images in a specified directory without reproducing the entire hierarchical tree of the site, try to add "cut-dirs" to the line proposed by Jon.

wget -r -P /save/location -A jpeg,jpg,bmp,gif,png http://www.boia.de --cut-dirs=1 --cut-dirs=2 --cut-dirs=3

in this case cut-dirs will prevent wget from creating sub-directories until the 3th level of depth in the website hierarchical tree, saving all the files in the directory you specified.You can add more 'cut-dirs' with higher numbers if you are dealing with sites with a deep structure.

How to improve performance of ngRepeat over a huge dataset (angular.js)?

Rule No.1: Never let the user wait for anything.

That in mind a life growing page that needs 10seconds appears way faster than waiting 3 seconds on before a blank screen and get all at once.

So instead of make the page fast, just let the page appear to be fast, even if the final result is slower:

function applyItemlist(items){
    var item = items.shift();
    if(item){
        $timeout(function(){
            $scope.items.push(item);
            applyItemlist(items);
        }, 0); // <-- try a little gap of 10ms
    }
}

The code above let appear the list to be growing row-by-row, and is always slower than render all at once. But for the user it appears to be faster.

Dynamic require in RequireJS, getting "Module name has not been loaded yet for context" error?

The limitation relates to the simplified CommonJS syntax vs. the normal callback syntax:

Loading a module is inherently an asynchronous process due to the unknown timing of downloading it. However, RequireJS in emulation of the server-side CommonJS spec tries to give you a simplified syntax. When you do something like this:

var foomodule = require('foo');
// do something with fooModule

What's happening behind the scenes is that RequireJS is looking at the body of your function code and parsing out that you need 'foo' and loading it prior to your function execution. However, when a variable or anything other than a simple string, such as your example...

var module = require(path); // Call RequireJS require

...then Require is unable to parse this out and automatically convert it. The solution is to convert to the callback syntax;

var moduleName = 'foo';
require([moduleName], function(fooModule){
    // do something with fooModule
})

Given the above, here is one possible rewrite of your 2nd example to use the standard syntax:

define(['dyn_modules'], function (dynModules) {
    require(dynModules, function(){
        // use arguments since you don't know how many modules you're getting in the callback
        for (var i = 0; i < arguments.length; i++){
            var mymodule = arguments[i];
            // do something with mymodule...
        }
    });

});

EDIT: From your own answer, I see you're using underscore/lodash, so using _.values and _.object can simplify the looping through arguments array as above.

Difference between "or" and || in Ruby?

As the others have already explained, the only difference is the precedence. However, I would like to point out that there are actually two differences between the two:

  1. and, or and not have much lower precedence than &&, || and !
  2. and and or have the same precedence, while && has higher precedence than ||

In general, it is good style to avoid the use of and, or and not and use &&, || and ! instead. (The Rails core developers, for example, reject patches which use the keyword forms instead of the operator forms.)

The reason why they exist at all, is not for boolean formulae but for control flow. They made their way into Ruby via Perl's well-known do_this or do_that idiom, where do_this returns false or nil if there is an error and only then is do_that executed instead. (Analogous, there is also the do_this and then_do_that idiom.)

Examples:

download_file_via_fast_connection or download_via_slow_connection
download_latest_currency_rates and store_them_in_the_cache

Sometimes, this can make control flow a little bit more fluent than using if or unless.

It's easy to see why in this case the operators have the "wrong" (i.e. identical) precedence: they never show up together in the same expression anyway. And when they do show up together, you generally want them to be evaluated simply left-to-right.

Validate SSL certificates with Python

I have added a distribution to the Python Package Index which makes the match_hostname() function from the Python 3.2 ssl package available on previous versions of Python.

http://pypi.python.org/pypi/backports.ssl_match_hostname/

You can install it with:

pip install backports.ssl_match_hostname

Or you can make it a dependency listed in your project's setup.py. Either way, it can be used like this:

from backports.ssl_match_hostname import match_hostname, CertificateError
...
sslsock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_SSLv3,
                      cert_reqs=ssl.CERT_REQUIRED, ca_certs=...)
try:
    match_hostname(sslsock.getpeercert(), hostname)
except CertificateError, ce:
    ...

How to retrieve raw post data from HttpServletRequest in java

The request body is available as byte stream by HttpServletRequest#getInputStream():

InputStream body = request.getInputStream();
// ...

Or as character stream by HttpServletRequest#getReader():

Reader body = request.getReader();
// ...

Note that you can read it only once. The client ain't going to resend the same request multiple times. Calling getParameter() and so on will implicitly also read it. If you need to break down parameters later on, you've got to store the body somewhere and process yourself.

Observable Finally on Subscribe

The current "pipable" variant of this operator is called finalize() (since RxJS 6). The older and now deprecated "patch" operator was called finally() (until RxJS 5.5).

I think finalize() operator is actually correct. You say:

do that logic only when I subscribe, and after the stream has ended

which is not a problem I think. You can have a single source and use finalize() before subscribing to it if you want. This way you're not required to always use finalize():

let source = new Observable(observer => {
  observer.next(1);
  observer.error('error message');
  observer.next(3);
  observer.complete();
}).pipe(
  publish(),
);

source.pipe(
  finalize(() => console.log('Finally callback')),
).subscribe(
  value => console.log('#1 Next:', value),
  error => console.log('#1 Error:', error),
  () => console.log('#1 Complete')
);

source.subscribe(
  value => console.log('#2 Next:', value),
  error => console.log('#2 Error:', error),
  () => console.log('#2 Complete')
);

source.connect();

This prints to console:

#1 Next: 1
#2 Next: 1
#1 Error: error message
Finally callback
#2 Error: error message

Jan 2019: Updated for RxJS 6

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

or defined by a module not included in the server configuration

Check to make sure you have mod_rewrite enabled.

From: https://webdevdoor.com/php/mod_rewrite-windows-apache-url-rewriting

  1. Find the httpd.conf file (usually you will find it in a folder called conf, config or something along those lines)
  2. Inside the httpd.conf file uncomment the line LoadModule rewrite_module modules/mod_rewrite.so (remove the pound '#' sign from in front of the line)
  3. Also find the line ClearModuleList is uncommented then find and make sure that the line AddModule mod_rewrite.c is not commented out.

If the LoadModule rewrite_module modules/mod_rewrite.so line is missing from the httpd.conf file entirely, just add it.

Sample command

To enable the module in a standard ubuntu do this:

a2enmod rewrite
systemctl restart apache2

Android: android.content.res.Resources$NotFoundException: String resource ID #0x5

(Just assumption, less info of Exception stacktrace)

I think, this line, incercari.setText(valIncercari); throws Exception because valIncercari is int

So it should be,

incercari.setText(valIncercari+"");

Or

incercari.setText(Integer.toString(valIncercari));

Soft Edges using CSS?

Another option is to use one of my personal favorite CSS tools: box-shadow.

A box shadow is really a drop-shadow on the node. It looks like this:

-moz-box-shadow: 1px 2px 3px rgba(0,0,0,.5);
-webkit-box-shadow: 1px 2px 3px rgba(0,0,0,.5);
box-shadow: 1px 2px 3px rgba(0,0,0,.5);

The arguments are:

1px: Horizontal offset of the effect. Positive numbers shift it right, negative left.
2px: Vertical offset of the effect. Positive numbers shift it down, negative up.
3px: The blur effect.  0 means no blur.
color: The color of the shadow.

So, you could leave your current design, and add a box-shadow like:

box-shadow: 0px -2px 2px rgba(34,34,34,0.6);

This should give you a 'blurry' top-edge.

This website will help with more information: http://css-tricks.com/snippets/css/css-box-shadow/

How to unzip a file in Powershell?

In PowerShell v5.1 this is slightly different compared to v5. According to MS documentation, it has to have a -Path parameter to specify the archive file path.

Expand-Archive -Path Draft.Zip -DestinationPath C:\Reference

Or else, this can be an actual path:

Expand-Archive -Path c:\Download\Draft.Zip -DestinationPath C:\Reference

Expand-Archive Doc

How to write specific CSS for mozilla, chrome and IE

Paul Irish's approach to IE specific CSS is the most elegant I've seen. It uses conditional statements to add classes to the HTML element, which can then be used to apply appropriate IE version specific CSS without resorting to hacks. The CSS validates, and it will continue to work down the line for future browser versions.

The full details of the approach can be seen on his site.

This doesn't cover browser specific hacks for Mozilla and Chrome... but I don't really find I need those anyway.

How to detect input type=file "change" for the same file?

The simplest way would be to set the input value to an empty string directly in the change or input event, which one mostly listens to anyways.

onFileInputChanged(event) {
     // todo: read the filenames and do the work
     
     // reset the value directly using the srcElement property from the event
     event.srcElement.value = ""
}

How do I add indices to MySQL tables?

You can use this syntax to add an index and control the kind of index (HASH or BTREE).

create index your_index_name on your_table_name(your_column_name) using HASH;
or
create index your_index_name on your_table_name(your_column_name) using BTREE;

You can learn about differences between BTREE and HASH indexes here: http://dev.mysql.com/doc/refman/5.5/en/index-btree-hash.html

Should __init__() call the parent class's __init__()?

If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__, you must call it yourself, since that will not happen automatically. But if you don't need anything from super's __init__, no need to call it. Example:

>>> class C(object):
        def __init__(self):
            self.b = 1


>>> class D(C):
        def __init__(self):
            super().__init__() # in Python 2 use super(D, self).__init__()
            self.a = 1


>>> class E(C):
        def __init__(self):
            self.a = 1


>>> d = D()
>>> d.a
1
>>> d.b  # This works because of the call to super's init
1
>>> e = E()
>>> e.a
1
>>> e.b  # This is going to fail since nothing in E initializes b...
Traceback (most recent call last):
  File "<pyshell#70>", line 1, in <module>
    e.b  # This is going to fail since nothing in E initializes b...
AttributeError: 'E' object has no attribute 'b'

__del__ is the same way, (but be wary of relying on __del__ for finalization - consider doing it via the with statement instead).

I rarely use __new__. I do all the initialization in __init__.

how does multiplication differ for NumPy Matrix vs Array classes?

the key things to know for operations on NumPy arrays versus operations on NumPy matrices are:

  • NumPy matrix is a subclass of NumPy array

  • NumPy array operations are element-wise (once broadcasting is accounted for)

  • NumPy matrix operations follow the ordinary rules of linear algebra

some code snippets to illustrate:

>>> from numpy import linalg as LA
>>> import numpy as NP

>>> a1 = NP.matrix("4 3 5; 6 7 8; 1 3 13; 7 21 9")
>>> a1
matrix([[ 4,  3,  5],
        [ 6,  7,  8],
        [ 1,  3, 13],
        [ 7, 21,  9]])

>>> a2 = NP.matrix("7 8 15; 5 3 11; 7 4 9; 6 15 4")
>>> a2
matrix([[ 7,  8, 15],
        [ 5,  3, 11],
        [ 7,  4,  9],
        [ 6, 15,  4]])

>>> a1.shape
(4, 3)

>>> a2.shape
(4, 3)

>>> a2t = a2.T
>>> a2t.shape
(3, 4)

>>> a1 * a2t         # same as NP.dot(a1, a2t) 
matrix([[127,  84,  85,  89],
        [218, 139, 142, 173],
        [226, 157, 136, 103],
        [352, 197, 214, 393]])

but this operations fails if these two NumPy matrices are converted to arrays:

>>> a1 = NP.array(a1)
>>> a2t = NP.array(a2t)

>>> a1 * a2t
Traceback (most recent call last):
   File "<pyshell#277>", line 1, in <module>
   a1 * a2t
   ValueError: operands could not be broadcast together with shapes (4,3) (3,4) 

though using the NP.dot syntax works with arrays; this operations works like matrix multiplication:

>> NP.dot(a1, a2t)
array([[127,  84,  85,  89],
       [218, 139, 142, 173],
       [226, 157, 136, 103],
       [352, 197, 214, 393]])

so do you ever need a NumPy matrix? ie, will a NumPy array suffice for linear algebra computation (provided you know the correct syntax, ie, NP.dot)?

the rule seems to be that if the arguments (arrays) have shapes (m x n) compatible with the a given linear algebra operation, then you are ok, otherwise, NumPy throws.

the only exception i have come across (there are likely others) is calculating matrix inverse.

below are snippets in which i have called a pure linear algebra operation (in fact, from Numpy's Linear Algebra module) and passed in a NumPy array

determinant of an array:

>>> m = NP.random.randint(0, 10, 16).reshape(4, 4)
>>> m
array([[6, 2, 5, 2],
       [8, 5, 1, 6],
       [5, 9, 7, 5],
       [0, 5, 6, 7]])

>>> type(m)
<type 'numpy.ndarray'>

>>> md = LA.det(m)
>>> md
1772.9999999999995

eigenvectors/eigenvalue pairs:

>>> LA.eig(m)
(array([ 19.703+0.j   ,   0.097+4.198j,   0.097-4.198j,   5.103+0.j   ]), 
array([[-0.374+0.j   , -0.091+0.278j, -0.091-0.278j, -0.574+0.j   ],
       [-0.446+0.j   ,  0.671+0.j   ,  0.671+0.j   , -0.084+0.j   ],
       [-0.654+0.j   , -0.239-0.476j, -0.239+0.476j, -0.181+0.j   ],
       [-0.484+0.j   , -0.387+0.178j, -0.387-0.178j,  0.794+0.j   ]]))

matrix norm:

>>>> LA.norm(m)
22.0227

qr factorization:

>>> LA.qr(a1)
(array([[ 0.5,  0.5,  0.5],
        [ 0.5,  0.5, -0.5],
        [ 0.5, -0.5,  0.5],
        [ 0.5, -0.5, -0.5]]), 
 array([[ 6.,  6.,  6.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]))

matrix rank:

>>> m = NP.random.rand(40).reshape(8, 5)
>>> m
array([[ 0.545,  0.459,  0.601,  0.34 ,  0.778],
       [ 0.799,  0.047,  0.699,  0.907,  0.381],
       [ 0.004,  0.136,  0.819,  0.647,  0.892],
       [ 0.062,  0.389,  0.183,  0.289,  0.809],
       [ 0.539,  0.213,  0.805,  0.61 ,  0.677],
       [ 0.269,  0.071,  0.377,  0.25 ,  0.692],
       [ 0.274,  0.206,  0.655,  0.062,  0.229],
       [ 0.397,  0.115,  0.083,  0.19 ,  0.701]])
>>> LA.matrix_rank(m)
5

matrix condition:

>>> a1 = NP.random.randint(1, 10, 12).reshape(4, 3)
>>> LA.cond(a1)
5.7093446189400954

inversion requires a NumPy matrix though:

>>> a1 = NP.matrix(a1)
>>> type(a1)
<class 'numpy.matrixlib.defmatrix.matrix'>

>>> a1.I
matrix([[ 0.028,  0.028,  0.028,  0.028],
        [ 0.028,  0.028,  0.028,  0.028],
        [ 0.028,  0.028,  0.028,  0.028]])
>>> a1 = NP.array(a1)
>>> a1.I

Traceback (most recent call last):
   File "<pyshell#230>", line 1, in <module>
   a1.I
   AttributeError: 'numpy.ndarray' object has no attribute 'I'

but the Moore-Penrose pseudoinverse seems to works just fine

>>> LA.pinv(m)
matrix([[ 0.314,  0.407, -1.008, -0.553,  0.131,  0.373,  0.217,  0.785],
        [ 1.393,  0.084, -0.605,  1.777, -0.054, -1.658,  0.069, -1.203],
        [-0.042, -0.355,  0.494, -0.729,  0.292,  0.252,  1.079, -0.432],
        [-0.18 ,  1.068,  0.396,  0.895, -0.003, -0.896, -1.115, -0.666],
        [-0.224, -0.479,  0.303, -0.079, -0.066,  0.872, -0.175,  0.901]])

>>> m = NP.array(m)

>>> LA.pinv(m)
array([[ 0.314,  0.407, -1.008, -0.553,  0.131,  0.373,  0.217,  0.785],
       [ 1.393,  0.084, -0.605,  1.777, -0.054, -1.658,  0.069, -1.203],
       [-0.042, -0.355,  0.494, -0.729,  0.292,  0.252,  1.079, -0.432],
       [-0.18 ,  1.068,  0.396,  0.895, -0.003, -0.896, -1.115, -0.666],
       [-0.224, -0.479,  0.303, -0.079, -0.066,  0.872, -0.175,  0.901]])

How to mock private method for testing using PowerMock?

i know a way ny which you can call you private function to test in mockito

@Test
    public  void  commandEndHandlerTest() throws  Exception
    {
        Method retryClientDetail_privateMethod =yourclass.class.getDeclaredMethod("Your_function_name",null);
        retryClientDetail_privateMethod.setAccessible(true);
        retryClientDetail_privateMethod.invoke(yourclass.class, null);
    }

Java naming convention for static final variables

Don't live fanatically with the conventions that SUN have med up, do whats feel right to you and your team.

For example this is how eclipse do it, breaking the convention. Try adding implements Serializable and eclipse will ask to generate this line for you.

Update: There were special cases that was excluded didn't know that. I however withholds to do what you and your team seems fit.

Remove old Fragment from fragment manager

If you want to replace a fragment with another, you should have added them dynamically, first of all. Fragments that are hard coded in XML, cannot be replaced.

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

Refer this post: Replacing a fragment with another fragment inside activity group

Refer1: Replace a fragment programmatically

IndexOf function in T-SQL

CHARINDEX is what you are looking for

select CHARINDEX('@', '[email protected]')
-----------
8

(1 row(s) affected)

-or-

select CHARINDEX('c', 'abcde')
-----------
3

(1 row(s) affected)

Create a .txt file if doesn't exist, and if it does append a new line

You don't actually have to check if the file exists, as StreamWriter will do that for you. If you open it in append-mode, the file will be created if it does not exists, then you will always append and never over write. So your initial check is redundant.

TextWriter tw = new StreamWriter(path, true);
tw.WriteLine("The next line!");
tw.Close(); 

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
   t
1 20
2  0
3 30

on change event for file input element

Give unique class and different id for file input

           $("#tab-content").on('change',class,function()
               {
                  var id=$(this).attr('id');
                      $("#"+id).trigger(your function); 
               //for name of file input  $("#"+id).attr("name");
               });

How do I do a simple 'Find and Replace" in MsSQL?

The following will find and replace a string in every database (excluding system databases) on every table on the instance you are connected to:

Simply change 'Search String' to whatever you seek and 'Replace String' with whatever you want to replace it with.

--Getting all the databases and making a cursor
DECLARE db_cursor CURSOR FOR  
SELECT name 
FROM master.dbo.sysdatabases 
WHERE name NOT IN ('master','model','msdb','tempdb')  -- exclude these databases

DECLARE @databaseName nvarchar(1000)
--opening the cursor to move over the databases in this instance
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @databaseName   

WHILE @@FETCH_STATUS = 0   
BEGIN
    PRINT @databaseName
    --Setting up temp table for the results of our search
    DECLARE @Results TABLE(TableName nvarchar(370), RealColumnName nvarchar(370), ColumnName nvarchar(370), ColumnValue nvarchar(3630))

    SET NOCOUNT ON

    DECLARE @SearchStr nvarchar(100), @ReplaceStr nvarchar(100), @SearchStr2 nvarchar(110)
    SET @SearchStr = 'Search String'
    SET @ReplaceStr = 'Replace String'
    SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')

    DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128)
    SET  @TableName = ''

    --Looping over all the tables in the database
    WHILE @TableName IS NOT NULL
    BEGIN
        DECLARE @SQL nvarchar(2000)
        SET @ColumnName = ''
        DECLARE @result NVARCHAR(256)
        SET @SQL = 'USE ' + @databaseName + '
            SELECT @result = MIN(QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME))
            FROM    [' + @databaseName + '].INFORMATION_SCHEMA.TABLES
            WHERE       TABLE_TYPE = ''BASE TABLE'' AND TABLE_CATALOG = ''' + @databaseName + '''
                AND QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME) > ''' + @TableName + '''
                AND OBJECTPROPERTY(
                        OBJECT_ID(
                            QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME)
                                ), ''IsMSShipped''
                                ) = 0'
        EXEC master..sp_executesql @SQL, N'@result nvarchar(256) out', @result out

        SET @TableName = @result
        PRINT @TableName

        WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
        BEGIN
            DECLARE @ColumnResult NVARCHAR(256)
            SET @SQL = '
                SELECT @ColumnResult = MIN(QUOTENAME(COLUMN_NAME))
                FROM    [' + @databaseName + '].INFORMATION_SCHEMA.COLUMNS
                WHERE       TABLE_SCHEMA    = PARSENAME(''[' + @databaseName + '].' + @TableName + ''', 2)
                    AND TABLE_NAME  = PARSENAME(''[' + @databaseName + '].' + @TableName + ''', 1)
                    AND DATA_TYPE IN (''char'', ''varchar'', ''nchar'', ''nvarchar'')
                    AND TABLE_CATALOG = ''' + @databaseName + '''
                    AND QUOTENAME(COLUMN_NAME) > ''' + @ColumnName + ''''
            PRINT @SQL
            EXEC master..sp_executesql @SQL, N'@ColumnResult nvarchar(256) out', @ColumnResult out
            SET @ColumnName = @ColumnResult 

            PRINT @ColumnName

            IF @ColumnName IS NOT NULL
            BEGIN
                INSERT INTO @Results
                EXEC
                (
                    'USE ' + @databaseName + '
                    SELECT ''' + @TableName + ''',''' + @ColumnName + ''',''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                    FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
                )
            END
        END
    END

    --Declaring another temporary table
    DECLARE @time_to_update TABLE(TableName nvarchar(370), RealColumnName nvarchar(370))

    INSERT INTO @time_to_update
    SELECT TableName, RealColumnName FROM @Results GROUP BY TableName, RealColumnName

    DECLARE @MyCursor CURSOR;
    BEGIN
        DECLARE @t nvarchar(370)
        DECLARE @c nvarchar(370)
        --Looping over the search results   
        SET @MyCursor = CURSOR FOR
        SELECT TableName, RealColumnName FROM @time_to_update GROUP BY TableName, RealColumnName

        --Getting my variables from the first item
        OPEN @MyCursor 
        FETCH NEXT FROM @MyCursor 
        INTO @t, @c

        WHILE @@FETCH_STATUS = 0
        BEGIN
            -- Updating the old values with the new value
            DECLARE @sqlCommand varchar(1000)
            SET @sqlCommand = '
                USE ' + @databaseName + '
                UPDATE [' + @databaseName + '].' + @t + ' SET ' + @c + ' = REPLACE(' + @c + ', ''' + @SearchStr + ''', ''' + @ReplaceStr + ''') 
                WHERE ' + @c + ' LIKE ''' + @SearchStr2 + ''''
            PRINT @sqlCommand
            BEGIN TRY
                EXEC (@sqlCommand)
            END TRY
            BEGIN CATCH
                PRINT ERROR_MESSAGE()
            END CATCH

            --Getting next row values
            FETCH NEXT FROM @MyCursor 
            INTO @t, @c 
        END;

        CLOSE @MyCursor ;
        DEALLOCATE @MyCursor;
    END;

    DELETE FROM @time_to_update
    DELETE FROM @Results

    FETCH NEXT FROM db_cursor INTO @databaseName
END   

CLOSE db_cursor   
DEALLOCATE db_cursor

Note: this isn't ideal, nor is it optimized

PHP Get all subdirectories of a given directory

<?php
    /*this will do what you asked for, it only returns the subdirectory names in a given
      path, and you can make hyperlinks and use them:
    */

    $yourStartingPath = "photos\\";
    $iterator = new RecursiveIteratorIterator( 
        new RecursiveDirectoryIterator($yourStartingPath),  
        RecursiveIteratorIterator::SELF_FIRST);

    foreach($iterator as $file) { 
        if($file->isDir()) { 
            $path = strtoupper($file->getRealpath()) ; 
            $path2 = PHP_EOL;
            $path3 = $path.$path2;

            $result = end(explode('/', $path3)); 

            echo "<br />". basename($result );
        } 
    } 

    /* best regards,
        Sanaan Barzinji
        Erbil
    */
?>

Get page title with Selenium WebDriver using Java

If you're using Selenium 2.0 / Webdriver you can call driver.getTitle() or driver.getPageSource() if you want to search through the actual page source.

Different ways of clearing lists

del list[:] 

Will delete the values of that list variable

del list

Will delete the variable itself from memory

SQL Server: Multiple table joins with a WHERE clause

When using LEFT JOIN or RIGHT JOIN, it makes a difference whether you put the filter in the WHERE or into the JOIN.

See this answer to a similar question I wrote some time ago:
What is the difference in these two queries as getting two different result set?

In short:

  • if you put it into the WHERE clause (like you did, the results that aren't associated with that computer are completely filtered out
  • if you put it into the JOIN instead, the results that aren't associated with that computer appear in the query result, only with NULL values
    --> this is what you want

adding directory to sys.path /PYTHONPATH

This is working as documented. Any paths specified in PYTHONPATH are documented as normally coming after the working directory but before the standard interpreter-supplied paths. sys.path.append() appends to the existing path. See here and here. If you want a particular directory to come first, simply insert it at the head of sys.path:

import sys
sys.path.insert(0,'/path/to/mod_directory')

That said, there are usually better ways to manage imports than either using PYTHONPATH or manipulating sys.path directly. See, for example, the answers to this question.

Gradle Build Android Project "Could not resolve all dependencies" error

I had this message in Android Studio 2.1.1 in the Gradle Build tab. I installed a lot of files from the SDK Manager but it did not help.

I needed to click the next tab "Gradle Sync". There was a link "Install Repository and sync project" which installed the "Android Support Repository".

How to remove an element from a list by index

Use the del statement:

del listName[-N]

For example, if you want to remove the last 3 items, your code should be:

del listName[-3:]

For example, if you want to remove the last 8 items, your code should be:

del listName[-8:]

What is the best way to conditionally apply attributes in AngularJS?

I actually wrote a patch to do this a few months ago (after someone asked about it in #angularjs on freenode).

It probably won't be merged, but it's very similar to ngClass: https://github.com/angular/angular.js/pull/4269

Whether it gets merged or not, the existing ng-attr-* stuff is probably suitable for your needs (as others have mentioned), although it might be a bit clunkier than the more ngClass-style functionality that you're suggesting.

TextView Marquee not working

Very Simple working code:

For infinitely scrolling text

            <TextView
            android:id="@+id/textView_News_HeadLine"
            style="@style/black_extra_large_heading_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="8dp"
            android:ellipsize="marquee"
            android:marqueeRepeatLimit="-1"
            android:singleLine="true"
            android:text="HeadLine: Banglawash To be Continued" />

& you should must write from your activity

textView.setSelected(true);

MySQL Job failed to start

Reinstallation will works because it will reset all the value to default. It is better to find what the real culprits (my.cnf editing mistake does happens, e.g. bad/outdated parameter suggestion during mysql tuning.)

Here is the mysql diagnosis if you suspect some value is wrong inside my.cnf : Run the mysqld to show you the results.

sudo -u mysql  mysqld 

Afterwards, fix all the my.cnf key error that pop out from the screen until mysqld startup successfully.

Then restart it using

sudo service mysql restart

View HTTP headers in Google Chrome?

For Version 78.0.3904.87, OS = Windows 7, 64 bit PC

Steps:

  1. Press F12
  2. Select Network Tab
  3. Select XHR
  4. Under Name --> you can see all the XHR requests made.
  5. To view Request Headers of a particular XHR request, click on that request. All details about that XHR request will appear on right hand side.

Pass Javascript variable to PHP via ajax

Pass the data like this to the ajax call (http://api.jquery.com/jQuery.ajax/):

data: { userID : userID }

And in your PHP do this:

if(isset($_POST['userID']))
{
    $uid = $_POST['userID'];

    // Do whatever you want with the $uid
}

isset() function's purpose is to check wheter the given variable exists, not to get its value.

When to use RSpec let()?

Note to Joseph -- if you are creating database objects in a before(:all) they won't be captured in a transaction and you're much more likely to leave cruft in your test database. Use before(:each) instead.

The other reason to use let and its lazy evaluation is so you can take a complicated object and test individual pieces by overriding lets in contexts, as in this very contrived example:

context "foo" do
  let(:params) do
     { :foo => foo,  :bar => "bar" }
  end
  let(:foo) { "foo" }
  it "is set to foo" do
    params[:foo].should eq("foo")
  end
  context "when foo is bar" do
    let(:foo) { "bar" }
    # NOTE we didn't have to redefine params entirely!
    it "is set to bar" do
      params[:foo].should eq("bar")
    end
  end
end

How do I make a WinForms app go Full Screen

To the base question, the following will do the trick (hiding the taskbar)

private void Form1_Load(object sender, EventArgs e)
{
    this.TopMost = true;
    this.FormBorderStyle = FormBorderStyle.None;
    this.WindowState = FormWindowState.Maximized;
}

But, interestingly, if you swap those last two lines the Taskbar remains visible. I think the sequence of these actions will be hard to control with the properties window.

How to get UTF-8 working in Java webapps?

To add to kosoant's answer, if you are using Spring, rather than writing your own Servlet filter, you can use the class org.springframework.web.filter.CharacterEncodingFilter they provide, configuring it like the following in your web.xml:

 <filter>
    <filter-name>encoding-filter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
       <param-name>encoding</param-name>
       <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
       <param-name>forceEncoding</param-name>
       <param-value>FALSE</param-value>
    </init-param>
 </filter>
 <filter-mapping>
    <filter-name>encoding-filter</filter-name>
    <url-pattern>/*</url-pattern>
 </filter-mapping>

Encode a FileStream to base64 with c#

A simple Stream extension method would do the job:

public static class StreamExtensions
{
    public static string ConvertToBase64(this Stream stream)
    {
        var bytes = new Byte[(int)stream.Length];

        stream.Seek(0, SeekOrigin.Begin);
        stream.Read(bytes, 0, (int)stream.Length);

        return Convert.ToBase64String(bytes);
    }
}

The methods for Read (and also Write) and optimized for the respective class (whether is file stream, memory stream, etc.) and will do the work for you. For simple task like this, there is no need of readers, and etc.

The only drawback is that the stream is copied into byte array, but that is how the conversion to base64 via Convert.ToBase64String works unfortunately.

how to write an array to a file Java

If the result is for humans to read and the elements of the array have a proper toString() defined...

outputString.write(Arrays.toString(array));

How do I create a shortcut via command-line in Windows?

To create a shortcut for warp-cli.exe, I based rojo's Powershell command and added WorkingDirectory, Arguments, IconLocation and minimized WindowStyle attribute to it.

powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Start Menu\Programs\Startup\CWarp_DoH.lnk');$s.TargetPath='E:\Program\CloudflareWARP\warp-cli.exe';$s.Arguments='connect';$s.IconLocation='E:\Program\CloudflareWARP\Cloudflare WARP.exe';$s.WorkingDirectory='E:\Program\CloudflareWARP';$s.WindowStyle=7;$s.Save()"

Other PS attributes for CreateShortcut: https://stackoverflow.com/a/57547816/4127357

OPENSSL file_get_contents(): Failed to enable crypto

Ok I have found a solution. The problem is that the site uses SSLv3. And I know that there are some problems in the openssl module. Some time ago I had the same problem with the SSL versions.

<?php
function getSSLPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSLVERSION,3); 
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

var_dump(getSSLPage("https://eresearch.fidelity.com/eresearch/evaluate/analystsOpinionsReport.jhtml?symbols=api"));
?>

When you set the SSL Version with curl to v3 then it works.

Edit:

Another problem under Windows is that you don't have access to the certificates. So put the root certificates directly to curl.

http://curl.haxx.se/docs/caextract.html

here you can download the root certificates.

curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . "/certs/cacert.pem");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);

Then you can use the CURLOPT_SSL_VERIFYPEER option with true otherwise you get an error.

How do I return a char array from a function?

A char array is returned by char*, but the function you wrote does not work because you are returning an automatic variable that disappears when the function exits.

Use something like this:

char *testfunc() {
    char* arr = malloc(100);
    strcpy(arr,"xxxx");
    return arr;
}

This is of course if you are returning an array in the C sense, not an std:: or boost:: or something else.

As noted in the comment section: remember to free the memory from the caller.

FULL OUTER JOIN vs. FULL JOIN

Microsoft® SQL Server™ 2000 uses these SQL-92 keywords for outer joins specified in a FROM clause:

  • LEFT OUTER JOIN or LEFT JOIN

  • RIGHT OUTER JOIN or RIGHT JOIN

  • FULL OUTER JOIN or FULL JOIN

From MSDN

The full outer join or full join returns all rows from both tables, matching up the rows wherever a match can be made and placing NULLs in the places where no matching row exists.

How can I limit ngFor repeat to some number of items in Angular?

 <div *ngFor="let item of list;trackBy: trackByFunc" >
   {{item.value}}
 </div>

In your ts file

 trackByFunc(index, item){
    return item ? item.id : undefined;
  }

GitHub - failed to connect to github 443 windows/ Failed to connect to gitHub - No Error

If your git was already set to something and you only copied that folder to some other location, simply run:

git config --global http.proxy ""

And git will set itself straight, after what, you can pull again :)

Android: Vertical alignment for multi line EditText (Text area)

Now a day use of gravity start is best choise:

android:gravity="start"

For EditText (textarea):

<EditText
    android:id="@+id/EditText02"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:lines="5"
    android:gravity="start"
    android:inputType="textMultiLine"
/>

Using Panel or PlaceHolder

The Placeholder does not render any tags for itself, so it is great for grouping content without the overhead of outer HTML tags.

The Panel does have outer HTML tags but does have some cool extra properties.

  • BackImageUrl: Gets/Sets the background image's URL for the panel

  • HorizontalAlign: Gets/Sets the
    horizontal alignment of the parent's contents

  • Wrap: Gets/Sets whether the
    panel's content wraps

There is a good article at startvbnet here.

Removing an activity from the history stack

One way that works pre API 11 is to start ActivityGameMain first, then in the onCreate of that Activity start your ActivitySplashScreen activity. The ActivityGameMain won't appear as you call startActivity too soon for the splash.

Then you can clear the stack when starting ActivityGameMain by setting these flags on the Intent:

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

You also must add this to ActivitySplashScreen:

@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

So that pressing back on that activity doesn't go back to your ActivityGameMain.

I assume you don't want the splash screen to be gone back to either, to achieve this I suggest setting it to noHistory in your AndroidManifest.xml. Then put the goBackPressed code in your ActivitySplashScreenSignUp class instead.

However I have found a few ways to break this. Start another app from a notification while ActivitySplashScreenSignUp is shown and the back history is not reset.

The only real way around this is in API 11:

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

Find and replace - Add carriage return OR Newline

If you set "Use regular expressions" flag then \n would be translated. But keep in mind that you would have to modify you search term to be regexp friendly. In your case it should be escaped like this "\~\~\?" (no quotes).

What I can do to resolve "1 commit behind master"?

  1. Clone your fork:

  2. Add remote from original repository in your forked repository:

    • cd into/cloned/fork-repo
    • git remote add upstream git://github.com/ORIGINAL-DEV-USERNAME/REPO-YOU-FORKED-FROM.git
    • git fetch upstream
  3. Updating your fork from original repo to keep up with their changes:

    • git pull upstream master
    • git push

Auto increment in MongoDB to store sequence of Unique User ID

First Record should be add

"_id" = 1    in your db

$database = "demo";
$collections ="democollaction";
echo getnextid($database,$collections);

function getnextid($database,$collections){

     $m = new MongoClient();
    $db = $m->selectDB($database);
    $cursor = $collection->find()->sort(array("_id" => -1))->limit(1);
    $array = iterator_to_array($cursor);

    foreach($array as $value){



        return $value["_id"] + 1;

    }
 }

How can I debug a HTTP POST in Chrome?

  1. Go to Chrome Developer Tools (Chrome Menu -> More Tools -> Developer Tools)
  2. Choose "Network" tab
  3. Refresh the page you're on
  4. You'll get list of http queries that happened, while the network console was on. Select one of them in the left
  5. Choose "Headers" tab

Voila!

enter image description here

How do you use https / SSL on localhost?

This question is really old, but I came across this page when I was looking for the easiest and quickest way to do this. Using Webpack is much simpler:

install webpack-dev-server

npm i -g webpack-dev-server

start webpack-dev-server with https

webpack-dev-server --https

ALTER TABLE add constraint

ALTER TABLE `User`
ADD CONSTRAINT `user_properties_foreign`
FOREIGN KEY (`properties`)
REFERENCES `Properties` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;

No generated R.java file in my project

java .... than debug.. or Remove the 'import R.java' line from your code. Its done by Eclipse in order to solve the problem. Go to "note_edit.xml" file. Wherever you find "match_parent" as an attribute value, replace it with either "fill_parent" or "wrap_content". Do a clean build. R.java will be generated automatically

How to check if a "lateinit" variable has been initialized?

kotlin.UninitializedPropertyAccessException: lateinit property clientKeypair has not been initialized

Bytecode says...blah blah..

public final static synthetic access$getClientKeypair$p(Lcom/takharsh/ecdh/MainActivity;)Ljava/security/KeyPair;

`L0
LINENUMBER 11 L0
ALOAD 0
GETFIELD com/takharsh/ecdh/MainActivity.clientKeypair : Ljava/security/KeyPair;
DUP
IFNONNULL L1
LDC "clientKeypair"
INVOKESTATIC kotlin/jvm/internal/Intrinsics.throwUninitializedPropertyAccessException (Ljava/lang/String;)V
    L1
ARETURN

L2 LOCALVARIABLE $this Lcom/takharsh/ecdh/MainActivity; L0 L2 0 MAXSTACK = 2 MAXLOCALS = 1

Kotlin creates an extra local variable of same instance and check if it null or not, if null then throws 'throwUninitializedPropertyAccessException' else return the local object. Above bytecode explained here Solution Since kotlin 1.2 it allows to check weather lateinit var has been initialized or not using .isInitialized

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

I have read all answers and I want to summarize for better understanding at first glance like following:

Firstly, the whole command that gets executed in the container includes two parts: the command and the arguments

  • ENTRYPOINT defines the executable invoked when the container is started (for command)

  • CMD specifies the arguments that get passed to the ENTRYPOINT (for arguments)

In the Kubernetes In Action book points an important note about it. (chapter 7)

Although you can use the CMD instruction to specify the command you want to execute when the image is run, the correct way is to do it through the ENTRYPOINT instruction and to only specify the CMD if you want to define the default arguments.

You can also read this article for great explanation in a simple way

Java Object Null Check for method

This question is quite older. The Questioner might have been turned into an experienced Java Developer by this time. Yet I want to add some opinion here which would help beginners.

For JDK 7 users, Here using

Objects.requireNotNull(object[, optionalMessage]);

is not safe. This function throws NullPointerException if it finds null object and which is a RunTimeException.

That will terminate the whole program!!. So better check null using == or !=.

Also, use List instead of Array. Although access speed is same, yet using Collections over Array has some advantages like if you ever decide to change the underlying implementation later on, you can do it flexibly. For example, if you need synchronized access, you can change the implementation to a Vector without rewriting all your code.

public static double calculateInventoryTotal(List<Book> books) {
    if (books == null || books.isEmpty()) {
        return 0;
    }

    double total = 0;

    for (Book book : books) {
        if (book != null) {
            total += book.getPrice();
        }
    }
    return total;
}

Also, I would like to upvote @1ac0 answer. We should understand and consider the purpose of the method too while writing. Calling method could have further logics to implement based on the called method's returned data.

Also if you are coding with JDK 8, It has introduced a new way to handle null check and protect the code from NullPointerException. It defined a new class called Optional. Have a look at this for detail

Finally, Pardon my bad English.

Catch browser's "zoom" event in JavaScript

I'd like to suggest an improvement to previous solution with tracking changes to window width. Instead of keeping your own array of event listeners you can use existing javascript event system and trigger your own event upon width change, and bind event handlers to it.

$(window).bind('myZoomEvent', function() { ... });

function pollZoomFireEvent() 
{ 

    if ( ... width changed ... ) {
        $(window).trigger('myZoomEvent');
    }
}

Throttle/debounce can help with reducing the rate of calls of your handler.

What happens to C# Dictionary<int, int> lookup if the key does not exist?

If you're just checking before trying to add a new value, use the ContainsKey method:

if (!openWith.ContainsKey("ht"))
{
    openWith.Add("ht", "hypertrm.exe");
}

If you're checking that the value exists, use the TryGetValue method as described in Jon Skeet's answer.

Calling a PHP function from an HTML form in the same file

Without reloading, using HTML and PHP only it is not possible, but this can be very similar to what you want, but you have to reload:

<?php
    function test() {
        echo $_POST["user"];
    }

    if (isset($_POST[])) { // If it is the first time, it does nothing
        test();
    }
?>

<form action="test.php" method="post">
    <input type="text" name="user" placeholder="enter a text" />
    <input type="submit" value="submit" onclick="test()" />
</form>

Android - Set text to TextView

This should do the trick:

TextView.setText("test");

Sorting an Array of int using BubbleSort

You're only making one pass through your array! Bubble sort requires you to keep looping until you find that you are no longer doing any swapping; hence the running time of O(n^2).

Try this:

public void sortArray(int[] x) {
    boolean swapped = true;
    while (swapped) {
       swapped = false;
       for(int i=1; i<x.length; i++) {
           int temp=0;
           if(x[i-1] > x[i]) {
               temp = x[i-1];
                x[i-1] = x[i];
                x[i] = temp;
                swapped = true;
            }
        }
    }
}

Once swapped == false at the end of a loop, you have made a whole pass without finding any instances where x[i-1] > x[i] and, hence, you know the array is sorted. Only then can you terminate the algorithm.

You can also replace the outer while loop with a for loop of n+1 iterations, which will guarantee that the array is in order; however, the while loop has the advantage of early termination in a better-than-worst-case scenario.

Best way to load module/class from lib folder in Rails 3?

Warning: if you want to load the 'monkey patch' or 'open class' from your 'lib' folder, don't use the 'autoload' approach!!!

  • "config.autoload_paths" approach: only works if you are loading a class that defined only in ONE place. If some class has been already defined somewhere else, then you can't load it again by this approach.

  • "config/initializer/load_rb_file.rb" approach: always works! whatever the target class is a new class or an "open class" or "monkey patch" for existing class, it always works!

For more details , see: https://stackoverflow.com/a/6797707/445908

How to redirect to another page using AngularJS?

I used the below code to redirect to new page

$window.location.href = '/foldername/page.html';

and injected $window object in my controller function.

Unnamed/anonymous namespaces vs. static functions

From experience I'll just note that while it is the C++ way to put formerly-static functions into the anonymous namespace, older compilers can sometimes have problems with this. I currently work with a few compilers for our target platforms, and the more modern Linux compiler is fine with placing functions into the anonymous namespace.

But an older compiler running on Solaris, which we are wed to until an unspecified future release, will sometimes accept it, and other times flag it as an error. The error is not what worries me, it's what it might be doing when it accepts it. So until we go modern across the board, we are still using static (usually class-scoped) functions where we'd prefer the anonymous namespace.

How do I remove a comma off the end of a string?

Precede that with:

if(substr($string, -1)==",")

How can I add a .npmrc file?

This issue is because of you having some local or private packages. For accessing those packages you have to create .npmrc file for this issue. Just refer the following link for your solution. https://nodesource.com/blog/configuring-your-npmrc-for-an-optimal-node-js-environment

Multiple input in JOptionPane.showInputDialog

Yes. You know that you can put any Object into the Object parameter of most JOptionPane.showXXX methods, and often that Object happens to be a JPanel.

In your situation, perhaps you could use a JPanel that has several JTextFields in it:

import javax.swing.*;

public class JOptionPaneMultiInput {
   public static void main(String[] args) {
      JTextField xField = new JTextField(5);
      JTextField yField = new JTextField(5);

      JPanel myPanel = new JPanel();
      myPanel.add(new JLabel("x:"));
      myPanel.add(xField);
      myPanel.add(Box.createHorizontalStrut(15)); // a spacer
      myPanel.add(new JLabel("y:"));
      myPanel.add(yField);

      int result = JOptionPane.showConfirmDialog(null, myPanel, 
               "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
      if (result == JOptionPane.OK_OPTION) {
         System.out.println("x value: " + xField.getText());
         System.out.println("y value: " + yField.getText());
      }
   }
}

How do I show/hide a UIBarButtonItem?

I am currently running OS X Yosemite Developer Preview 7 and Xcode 6 beta 6 targeting iOS 7.1 and following solution works fine for me:

  • Create outlet for UINavigationItemand UIBarButtonItems
  • Run following code to remove

    [self.navItem setRightBarButtonItem:nil];
    [self.navItem setLeftBarButtonItem:nil];
    
  • Run following codes to add buttons again

    [self.navItem setRightBarButtonItem:deleteItem];
    [self.navItem setLeftBarButtonItem:addItem];
    

Chaining multiple filter() in Django, is this a bug?

As you can see in the generated SQL statements the difference is not the "OR" as some may suspect. It is how the WHERE and JOIN is placed.

Example1 (same joined table) :

(example from https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships)

Blog.objects.filter(entry__headline__contains='Lennon', entry__pub_date__year=2008)

This will give you all the Blogs that have one entry with both (entry_headline_contains='Lennon') AND (entry__pub_date__year=2008), which is what you would expect from this query. Result: Book with {entry.headline: 'Life of Lennon', entry.pub_date: '2008'}

Example 2 (chained)

Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)

This will cover all the results from Example 1, but it will generate slightly more result. Because it first filters all the blogs with (entry_headline_contains='Lennon') and then from the result filters (entry__pub_date__year=2008).

The difference is that it will also give you results like: Book with {entry.headline: 'Lennon', entry.pub_date: 2000}, {entry.headline: 'Bill', entry.pub_date: 2008}

In your case

I think it is this one you need:

Book.objects.filter(inventory__user__profile__vacation=False, inventory__user__profile__country='BR')

And if you want to use OR please read: https://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

Which font is used in Visual Studio Code Editor and how to change fonts?

Go to Preferences > User Settings. (Alternatively, Ctrl + , / Cmd + , on macOS)

Then you can type inside the JSON object any settings you want to override. User settings are per user. You can also configure workspace settings, which are for the project that you are currently working on.

Here's an example:

// Controls the font family.
"editor.fontFamily": "Consolas",

// Controls the font size.
"editor.fontSize": 13

Useful links:

SQL Server remove milliseconds from datetime

Try:

SELECT * 
FROM table 
WHERE datetime > 
CONVERT(DATETIME, 
CONVERT(VARCHAR(20), 
CONVERT(DATETIME, '2010-07-20 03:21:52'), 120))

Or if your date is an actual datetime value:

DECLARE @date DATETIME
SET @date = GETDATE()
SELECT CONVERT(DATETIME, CONVERT(VARCHAR(20), @date, 120))

The conversion to style 120 cuts off the milliseconds...

Convert HTML Character Back to Text Using Java Standard Library

Or you can use unescapeHtml4:

    String miCadena="GU&#205;A TELEF&#211;NICA";
    System.out.println(StringEscapeUtils.unescapeHtml4(miCadena));

This code print the line: GUÍA TELEFÓNICA

Differentiate between function overloading and function overriding

Function overloading is done when you want to have the same function with different parameters

void Print(string s);//Print string
void Print(int i);//Print integer

Function overriding is done to give a different meaning to the function in the base class

class Stream//A stream of bytes
{
public virtual void Read();//read bytes
}

class FileStream:Stream//derived class
{
public override void Read();//read bytes from a file
}
class NetworkStream:Stream//derived class
{
public override void Read();//read bytes from a network
}

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • CSS how to make scrollable list

    Another solution would be as below where the list is placed under a drop-down button.

      <button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
        >Markets<span class="caret"></span></button>
    
        <ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
          {{ form.markets }}
        </ul>
    

    addClass - can add multiple classes on same div?

    $('.page-address-edit').addClass('test1 test2 test3');
    

    Ref- jQuery

    Colspan all columns

    I have IE 7.0, Firefox 3.0 and Chrome 1.0

    The colspan="0" attribute in a TD is NOT spanning across all TDs in any of the above browsers.

    Maybe not recommended as proper markup practice, but if you give a higher colspan value than the total possible no. of columns in other rows, then the TD would span all the columns.

    This does NOT work when the table-layout CSS property is set to fixed.

    Once again, this is not the perfect solution but seems to work in the above mentioned 3 browser versions when the table-layout CSS property is automatic. Hope this helps.

    CSS background image to fit width, height should auto-scale in proportion

    body{
        background-image: url(../url/imageName.jpg);
        background-attachment: fixed;
        background-size: auto 100%;
        background-position: center;
    }
    

    javax.servlet.ServletException cannot be resolved to a type in spring web app

    I guess this may work, in Eclipse select your project ? then click on project menu bar on top ? goto to properties ? click on Targeted Runtimes ? now you must select a check box next to the server you are using to run current project ? click Apply ? then click OK button. That's it, give a try.

    Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

    I don't think that replacing "Require all denied" with "Require all granted" in this directive:

    <Directory>
    
        Options FollowSymLinks
        AllowOverride None
        #Require all denied
        Require all granted
    </Directory>
    

    as suggested by Jan Czarny and seonded by user3801675 is the most secure way of solving this problem.

    According to the Apache configuration files, that line denies access to the entirety of your server's filesystem. Replacing it might indeed allow access to your virtual host folders but at the price of allowing access to your entire computer as well!

    Gev Balyan's approach seems to be the most secure approach here. It was the answer to the "access denied problems" plaguing me after setting up my new Apache server this morning.

    What is the difference between range and xrange functions in Python 2.X?

    xrange() and range() in python works similarly as for the user , but the difference comes when we are talking about how the memory is allocated in using both the function.

    When we are using range() we allocate memory for all the variables it is generating, so it is not recommended to use with larger no. of variables to be generated.

    xrange() on the other hand generate only a particular value at a time and can only be used with the for loop to print all the values required.

    Error With Port 8080 already in use

    I faced a similar problem , here's the solution.

    Step 1 : Double click on the server listed in Eclipse. Here It will display Server Configuration.

    Step 2 : Just change the port Number like from 8080 to 8085.

    Step 3 : Save the changes.

    Step 4 : re-start your server.

    The server will start .Hope it'll help you.

    Clearing NSUserDefaults

    If you need it while developing, you can also reset your simulator, deleting all the NSUserDefaults.

    iOS Simulator -> Reset Content and Settings...

    Bear in mind that it will also delete all the apps and files on simulator.

    MySQl Error #1064

    In my case I was having the same error and later I come to know that the 'condition' is mysql reserved keyword and I used that as field name.

    Clearing an HTML file upload field via JavaScript

    I know it is quite old, but testing in the browser:

    $0.value=null; // when $0 is the file upload element we talking about
    

    erased the value and allow me to rechoose THE SAME FILE as before (means it worked!)

    Tested in Chrome 81, FF 76, Safari (on iPad mini), 360 browser, Baidu browser, QQ browser, android browser.

    Explanation:

    As per my point of view that files selected can be more than 1, you'd better not set the value to a string - the final value sits in $0.files which may be more than 1. The browser need to parse the selected values from "value", so it is an active property. Set it to null, as per my understanding, will cause the browser to parse it to [] empty list in $0.files (this is what happened...)

    How to make a Div appear on top of everything else on the screen?

    dropdowns always show up on top, only solution for this problem is to hide dropdowns when image is displayed (display:block or visibility:visibile) and show them when image hidden (display:none or visibility:hidden)

    Laravel Eloquent limit and offset

    Quick:

    Laravel has a fast pagination method, paginate, which only needs to pass in the number of data displayed per page.

    
    //use the paginate
    Book::orderBy('updated_at', 'desc')->paginate(8);
    
    

    how to customize paging:

    you can use these method: offset,limit ,skip,take

    • offset,limit : where does the offset setting start, limiting the amount of data to be queried

    • skip,take: skip skips a few pieces of data and takes a lot of data

    for example:

    
    Model::offset(0)->limit(10)->get();
    
    Model::skip(3)->take(3)->get();
    
    
    //i use it in my project, work fine ~
    
    class BookController extends Controller
    {
        public function getList(Request $request) {
    
            $page = $request->has('page') ? $request->get('page') : 1;
            $limit = $request->has('limit') ? $request->get('limit') : 10;
    
            $books = Book::where('status', 0)->limit($limit)->offset(($page - 1) * $limit)->get()->toArray();
    
            return $this->getResponse($books, count($books));
        }
    }
    
    
    

    Why can't I center with margin: 0 auto?

    Why not?

    #header {
        text-align: center;
    }
    
    #header ul {
        display: inline;
    }
    

    How to move a git repository into another directory and make that directory a git repository?

    I am no expert, but I copy the .git folder to a new folder, then invoke: git reset --hard

    Add empty columns to a dataframe with specified names from a vector

    set.seed(1)
    example <- data.frame(col1 = rnorm(10, 0, 1), col2 = rnorm(10, 2, 3))
    namevector <- c("col3", "col4")
    example[ , namevector] <- NA
    
    example
    #          col1       col2 col3 col4
    # 1  -0.6264538  6.5353435   NA   NA
    # 2   0.1836433  3.1695297   NA   NA
    # 3  -0.8356286  0.1362783   NA   NA
    # 4   1.5952808 -4.6440997   NA   NA
    # 5   0.3295078  5.3747928   NA   NA
    # 6  -0.8204684  1.8651992   NA   NA
    # 7   0.4874291  1.9514292   NA   NA
    # 8   0.7383247  4.8315086   NA   NA
    # 9   0.5757814  4.4636636   NA   NA
    # 10 -0.3053884  3.7817040   NA   NA
    

    How to check if a table is locked in sql server

    sys.dm_tran_locks contains the locking information of the sessions

    If you want to know a specific table is locked or not, you can use the following query

    SELECT 
     * 
    from 
     sys.dm_tran_locks 
    where 
      resource_associated_entity_id = object_id('schemaname.tablename')
    

    if you are interested in finding both login name of the user and the query being run

    SELECT
     DB_NAME(resource_database_id)
     , s.original_login_name
     , s.status
     , s.program_name
     , s.host_name
     , (select text from sys.dm_exec_sql_text(exrequests.sql_handle))
     ,*
    from
      sys.dm_tran_locks dbl
         JOIN sys.dm_exec_sessions s ON dbl.request_session_id = s.session_id
      INNER JOIN  sys.dm_exec_requests exrequests on dbl.request_session_id = exrequests.session_id
    where
     DB_NAME(dbl.resource_database_id) = 'dbname'
    

    For more infomraton locking query

    More infor about sys.dm_tran_locks

    How to access URL segment(s) in blade in Laravel 5?

    Here is how one can do it via the global request helper function.

    {{ request()->segment(1) }}

    Note: request() returns the object of the Request class.

    Why is datetime.strptime not working in this simple example?

    You are importing the module datetime, which doesn't have a strptime function.

    That module does have a datetime object with that method though:

    import datetime
    dtDate = datetime.datetime.strptime(sDate, "%m/%d/%Y")
    

    Alternatively you can import the datetime object from the module:

    from datetime import datetime
    dtDate = datetime.strptime(sDate, "%m/%d/%Y")
    

    Note that the strptime method was added in python 2.5; if you are using an older version use the following code instead:

    import datetime, time
    dtDate = datetime.datetime(*time.strptime(sDate, "%m/%d/%Y")[:6])
    

    WordPress asking for my FTP credentials to install plugins

    I changed the ownership of the wordpress folder to www-data recursively and restarted apache.

    sudo chown -R www-data:www-data <folderpath>
    

    It worked like a charm!

    Remove padding or margins from Google Charts

    By adding and tuning some configuration options listed in the API documentation, you can create a lot of different styles. For instance, here is a version that removes most of the extra blank space by setting the chartArea.width to 100% and chartArea.height to 80% and moving the legend.position to bottom:

    // Set chart options
    var options = {'title': 'How Much Pizza I Ate Last Night',
                   'width': 350,
                   'height': 400,
                   'chartArea': {'width': '100%', 'height': '80%'},
                   'legend': {'position': 'bottom'}
        };
    

    If you want to tune it more, try changing these values or using other properties from the link above.

    How to detect orientation change?

    With iOS 13.1.2, orientation always return 0 until device is rotated. I need to call UIDevice.current.beginGeneratingDeviceOrientationNotifications() before any rotation event occurs to get actual rotation.

    How to use PDO to fetch results array in PHP?

    There are three ways to fetch multiple rows returned by PDO statement.

    The simplest one is just to iterate over PDOStatement itself:

    $stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
    $stmt->execute(array("%$query%"));
    // iterating over a statement
    foreach($stmt as $row) {
        echo $row['name'];
    }
    

    another one is to fetch rows using fetch() method inside a familiar while statement:

    $stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
    $stmt->execute(array("%$query%"));
    // using while
    while($row = $stmt->fetch()) {
        echo $row['name'];
    }
    

    but for the modern web application we should have our datbase iteractions separated from output and thus the most convenient method would be to fetch all rows at once using fetchAll() method:

    $stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
    $stmt->execute(array("%$query%"));
    // fetching rows into array
    $data = $stmt->fetchAll();
    

    or, if you need to preprocess some data first, use the while loop and collect the data into array manually

    $result = [];
    $stmt = $pdo->prepare("SELECT * FROM auction WHERE name LIKE ?")
    $stmt->execute(array("%$query%"));
    // using while
    while($row = $stmt->fetch()) {
        $result[] = [
            'newname' => $row['oldname'],
            // etc
        ];
    }
    

    and then output them in a template:

    <ul>
    <?php foreach($data as $row): ?>
        <li><?=$row['name']?></li>
    <?php endforeach ?>
    </ul>
    

    Note that PDO supports many sophisticated fetch modes, allowing fetchAll() to return data in many different formats.

    How to group pandas DataFrame entries by date in a non-unique column

    This should work:

    data.groupby(lambda x: data['date'][x].year)
    

    What's a clean way to stop mongod on Mac OS X?

    Simple way is to get the process id of mongodb and kill it. Please note DO NOT USE kill -9 pid for this as it may cause damage to the database.

    so, 1. get the pid of mongodb

    $ pgrep mongo

    you will get pid of mongo, Now

    $ kill

    You may use kill -15 as well

    What exactly is std::atomic?

    Each instantiation and full specialization of std::atomic<> represents a type that different threads can simultaneously operate on (their instances), without raising undefined behavior:

    Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.

    In addition, accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses as specified by std::memory_order.

    std::atomic<> wraps operations that, in pre-C++ 11 times, had to be performed using (for example) interlocked functions with MSVC or atomic bultins in case of GCC.

    Also, std::atomic<> gives you more control by allowing various memory orders that specify synchronization and ordering constraints. If you want to read more about C++ 11 atomics and memory model, these links may be useful:

    Note that, for typical use cases, you would probably use overloaded arithmetic operators or another set of them:

    std::atomic<long> value(0);
    value++; //This is an atomic op
    value += 5; //And so is this
    

    Because operator syntax does not allow you to specify the memory order, these operations will be performed with std::memory_order_seq_cst, as this is the default order for all atomic operations in C++ 11. It guarantees sequential consistency (total global ordering) between all atomic operations.

    In some cases, however, this may not be required (and nothing comes for free), so you may want to use more explicit form:

    std::atomic<long> value {0};
    value.fetch_add(1, std::memory_order_relaxed); // Atomic, but there are no synchronization or ordering constraints
    value.fetch_add(5, std::memory_order_release); // Atomic, performs 'release' operation
    

    Now, your example:

    a = a + 12;
    

    will not evaluate to a single atomic op: it will result in a.load() (which is atomic itself), then addition between this value and 12 and a.store() (also atomic) of final result. As I noted earlier, std::memory_order_seq_cst will be used here.

    However, if you write a += 12, it will be an atomic operation (as I noted before) and is roughly equivalent to a.fetch_add(12, std::memory_order_seq_cst).

    As for your comment:

    A regular int has atomic loads and stores. Whats the point of wrapping it with atomic<>?

    Your statement is only true for architectures that provide such guarantee of atomicity for stores and/or loads. There are architectures that do not do this. Also, it is usually required that operations must be performed on word-/dword-aligned address to be atomic std::atomic<> is something that is guaranteed to be atomic on every platform, without additional requirements. Moreover, it allows you to write code like this:

    void* sharedData = nullptr;
    std::atomic<int> ready_flag = 0;
    
    // Thread 1
    void produce()
    {
        sharedData = generateData();
        ready_flag.store(1, std::memory_order_release);
    }
    
    // Thread 2
    void consume()
    {
        while (ready_flag.load(std::memory_order_acquire) == 0)
        {
            std::this_thread::yield();
        }
    
        assert(sharedData != nullptr); // will never trigger
        processData(sharedData);
    }
    

    Note that assertion condition will always be true (and thus, will never trigger), so you can always be sure that data is ready after while loop exits. That is because:

    • store() to the flag is performed after sharedData is set (we assume that generateData() always returns something useful, in particular, never returns NULL) and uses std::memory_order_release order:

    memory_order_release

    A store operation with this memory order performs the release operation: no reads or writes in the current thread can be reordered after this store. All writes in the current thread are visible in other threads that acquire the same atomic variable

    • sharedData is used after while loop exits, and thus after load() from flag will return a non-zero value. load() uses std::memory_order_acquire order:

    std::memory_order_acquire

    A load operation with this memory order performs the acquire operation on the affected memory location: no reads or writes in the current thread can be reordered before this load. All writes in other threads that release the same atomic variable are visible in the current thread.

    This gives you precise control over the synchronization and allows you to explicitly specify how your code may/may not/will/will not behave. This would not be possible if only guarantee was the atomicity itself. Especially when it comes to very interesting sync models like the release-consume ordering.

    Laravel 5.1 API Enable Cors

    I am using Laravel 5.4 and unfortunately although the accepted answer seems fine, for preflighted requests (like PUT and DELETE) which will be preceded by an OPTIONS request, specifying the middleware in the $routeMiddleware array (and using that in the routes definition file) will not work unless you define a route handler for OPTIONS as well. This is because without an OPTIONS route Laravel will internally respond to that method without the CORS headers.

    So in short either define the middleware in the $middleware array which runs globally for all requests or if you're doing it in $middlewareGroups or $routeMiddleware then also define a route handler for OPTIONS. This can be done like this:

    Route::match(['options', 'put'], '/route', function () {
        // This will work with the middleware shown in the accepted answer
    })->middleware('cors');
    

    I also wrote a middleware for the same purpose which looks similar but is larger in size as it tries to be more configurable and handles a bunch of conditions as well:

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    
    class Cors
    {
        private static $allowedOriginsWhitelist = [
          'http://localhost:8000'
        ];
    
        // All the headers must be a string
    
        private static $allowedOrigin = '*';
    
        private static $allowedMethods = 'OPTIONS, GET, POST, PUT, PATCH, DELETE';
    
        private static $allowCredentials = 'true';
    
        private static $allowedHeaders = '';
    
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
          if (! $this->isCorsRequest($request))
          {
            return $next($request);
          }
    
          static::$allowedOrigin = $this->resolveAllowedOrigin($request);
    
          static::$allowedHeaders = $this->resolveAllowedHeaders($request);
    
          $headers = [
            'Access-Control-Allow-Origin'       => static::$allowedOrigin,
            'Access-Control-Allow-Methods'      => static::$allowedMethods,
            'Access-Control-Allow-Headers'      => static::$allowedHeaders,
            'Access-Control-Allow-Credentials'  => static::$allowCredentials,
          ];
    
          // For preflighted requests
          if ($request->getMethod() === 'OPTIONS')
          {
            return response('', 200)->withHeaders($headers);
          }
    
          $response = $next($request)->withHeaders($headers);
    
          return $response;
        }
    
        /**
         * Incoming request is a CORS request if the Origin
         * header is set and Origin !== Host
         *
         * @param  \Illuminate\Http\Request  $request
         */
        private function isCorsRequest($request)
        {
          $requestHasOrigin = $request->headers->has('Origin');
    
          if ($requestHasOrigin)
          {
            $origin = $request->headers->get('Origin');
    
            $host = $request->getSchemeAndHttpHost();
    
            if ($origin !== $host)
            {
              return true;
            }
          }
    
          return false;
        }
    
        /**
         * Dynamic resolution of allowed origin since we can't
         * pass multiple domains to the header. The appropriate
         * domain is set in the Access-Control-Allow-Origin header
         * only if it is present in the whitelist.
         *
         * @param  \Illuminate\Http\Request  $request
         */
        private function resolveAllowedOrigin($request)
        {
          $allowedOrigin = static::$allowedOrigin;
    
          // If origin is in our $allowedOriginsWhitelist
          // then we send that in Access-Control-Allow-Origin
    
          $origin = $request->headers->get('Origin');
    
          if (in_array($origin, static::$allowedOriginsWhitelist))
          {
            $allowedOrigin = $origin;
          }
    
          return $allowedOrigin;
        }
    
        /**
         * Take the incoming client request headers
         * and return. Will be used to pass in Access-Control-Allow-Headers
         *
         * @param  \Illuminate\Http\Request  $request
         */
        private function resolveAllowedHeaders($request)
        {
          $allowedHeaders = $request->headers->get('Access-Control-Request-Headers');
    
          return $allowedHeaders;
        }
    }
    

    Also written a blog post on this.

    hadoop No FileSystem for scheme: file

    Another possible cause (though the OPs question doesn't itself suffer from this) is if you create a configuration instance that does not load the defaults:

    Configuration config = new Configuration(false);
    

    If you don't load the defaults then you won't get the default settings for things like the FileSystem implementations which leads to identical errors like this when trying to access HDFS. Switching to the parameterless constructor of passing in true to load defaults may resolve this.

    Additionally if you are adding custom configuration locations (e.g. on the file system) to the Configuration object be careful of which overload of addResource() you use. For example if you use addResource(String) then Hadoop assumes that the string is a class path resource, if you need to specify a local file try the following:

    File configFile = new File("example/config.xml");
    config.addResource(new Path("file://" + configFile.getAbsolutePath()));
    

    Multiline input form field using Bootstrap

    I think the problem is that you are using type="text" instead of textarea. What you want is:

    <textarea class="span6" rows="3" placeholder="What's up?" required></textarea>
    

    To clarify, a type="text" will always be one row, where-as a textarea can be multiple.

    How to use Visual Studio Code as Default Editor for Git

    I set up Visual Studio Code as a default to open .txt file. And next I did use simple command: git config --global core.editor "'C:\Users\UserName\AppData\Local\Code\app-0.7.10\Code.exe\'". And everything works pretty well.

    Cannot read property 'style' of undefined -- Uncaught Type Error

    It's currently working, I've just changed the operator > in order to work in the snippet, take a look:

    _x000D_
    _x000D_
    window.onload = function() {_x000D_
    _x000D_
      if (window.location.href.indexOf("test") <= -1) {_x000D_
        var search_span = document.getElementsByClassName("securitySearchQuery");_x000D_
        search_span[0].style.color = "blue";_x000D_
        search_span[0].style.fontWeight = "bold";_x000D_
        search_span[0].style.fontSize = "40px";_x000D_
    _x000D_
      }_x000D_
    _x000D_
    }
    _x000D_
    <h1 class="keyword-title">Search results for<span class="securitySearchQuery"> "hi".</span></h1>
    _x000D_
    _x000D_
    _x000D_

    What's the difference between integer class and numeric class in R

    To quote the help page (try ?integer), bolded portion mine:

    Integer vectors exist so that data can be passed to C or Fortran code which expects them, and so that (small) integer data can be represented exactly and compactly.

    Note that current implementations of R use 32-bit integers for integer vectors, so the range of representable integers is restricted to about +/-2*10^9: doubles can hold much larger integers exactly.

    Like the help page says, R's integers are signed 32-bit numbers so can hold between -2147483648 and +2147483647 and take up 4 bytes.

    R's numeric is identical to an 64-bit double conforming to the IEEE 754 standard. R has no single precision data type. (source: help pages of numeric and double). A double can store all integers between -2^53 and 2^53 exactly without losing precision.

    We can see the data type sizes, including the overhead of a vector (source):

    > object.size(1:1000)
    4040 bytes
    > object.size(as.numeric(1:1000))
    8040 bytes
    

    sudo: port: command not found

    I found the answer in the official website

    $ vi ~/.profile
    
    # add the following line
    export PATH=/opt/local/bin:/opt/local/sbin:$PATH
    

    And now restart the terminal or type source !$ (equivalent to source ~/.profile)

    Caching a jquery ajax response in javascript/browser

    I was looking for caching for my phonegap app storage and I found the answer of @TecHunter which is great but done using localCache.

    I found and come to know that localStorage is another alternative to cache the data returned by ajax call. So, I created one demo using localStorage which will help others who may want to use localStorage instead of localCache for caching.

    Ajax Call:

    $.ajax({
        type: "POST",
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        url: url,
        data: '{"Id":"' + Id + '"}',
        cache: true, //It must "true" if you want to cache else "false"
        //async: false,
        success: function (data) {
            var resData = JSON.parse(data);
            var Info = resData.Info;
            if (Info) {
                customerName = Info.FirstName;
            }
        },
        error: function (xhr, textStatus, error) {
            alert("Error Happened!");
        }
    });
    

    To store data into localStorage:

    $.ajaxPrefilter(function (options, originalOptions, jqXHR) {
    if (options.cache) {
        var success = originalOptions.success || $.noop,
            url = originalOptions.url;
    
        options.cache = false; //remove jQuery cache as we have our own localStorage
        options.beforeSend = function () {
            if (localStorage.getItem(url)) {
                success(localStorage.getItem(url));
                return false;
            }
            return true;
        };
        options.success = function (data, textStatus) {
            var responseData = JSON.stringify(data.responseJSON);
            localStorage.setItem(url, responseData);
            if ($.isFunction(success)) success(responseJSON); //call back to original ajax call
        };
    }
    });
    

    If you want to remove localStorage, use following statement wherever you want:

    localStorage.removeItem("Info");
    

    Hope it helps others!

    How do you access the value of an SQL count () query in a Java program

    The answers provided by Bohzo and Brabster will obviously work, but you could also just use:

    rs3.getInt(1);
    

    to get the value in the first, and in your case, only column.

    .NET Core vs Mono

    .Net Core does not require mono in the sense of the mono framework. .Net Core is a framework that will work on multiple platforms including Linux. Reference https://dotnet.github.io/.

    However the .Net core can use the mono framework. Reference https://docs.asp.net/en/1.0.0-rc1/getting-started/choosing-the-right-dotnet.html (note rc1 documentatiopn no rc2 available), however mono is not a Microsoft supported framework and would recommend using a supported framework

    Now entity framework 7 is now called Entity Framework Core and is available on multiple platforms including Linux. Reference https://github.com/aspnet/EntityFramework (review the road map)

    I am currently using both of these frameworks however you must understand that it is still in release candidate stage (RC2 is the current version) and over the beta & release candidates there have been massive changes that usually end up with you scratching your head.

    Here is a tutorial on how to install MVC .Net Core into Linux. https://docs.asp.net/en/1.0.0-rc1/getting-started/installing-on-linux.html

    Finally you have a choice of Web Servers (where I am assuming the fast cgi reference came from) to host your application on Linux. Here is a reference point for installing to a Linux enviroment. https://docs.asp.net/en/1.0.0-rc1/publishing/linuxproduction.html

    I realise this post ends up being mostly links to documentation but at this point those are your best sources of information. .Net core is still relatively new in the .Net community and until its fully released I would be hesitant to use it in a product environment given the breaking changes between released version.

    Disabling Strict Standards in PHP 5.4

    If you would need to disable E_DEPRACATED also, use:

    php_value error_reporting 22527
    

    In my case CMS Made Simple was complaining "E_STRICT is enabled in the error_reporting" as well as "E_DEPRECATED is enabled". Adding that one line to .htaccess solved both misconfigurations.

    How to use ArgumentCaptor for stubbing?

    The line

    when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
    

    would do the same as

    when(someObject.doSomething(Matchers.any())).thenReturn(true);
    

    So, using argumentCaptor.capture() when stubbing has no added value. Using Matchers.any() shows better what really happens and therefor is better for readability. With argumentCaptor.capture(), you can't read what arguments are really matched. And instead of using any(), you can use more specific matchers when you have more information (class of the expected argument), to improve your test.

    And another problem: If using argumentCaptor.capture() when stubbing it becomes unclear how many values you should expect to be captured after verification. We want to capture a value during verification, not during stubbing because at that point there is no value to capture yet. So what does the argument captors capture method capture during stubbing? It capture anything because there is nothing to be captured yet. I consider it to be undefined behavior and I don't want to use undefined behavior.

    How to combine two or more querysets in a Django view?

    The big downside of your current approach is its inefficiency with large search result sets, as you have to pull down the entire result set from the database each time, even though you only intend to display one page of results.

    In order to only pull down the objects you actually need from the database, you have to use pagination on a QuerySet, not a list. If you do this, Django actually slices the QuerySet before the query is executed, so the SQL query will use OFFSET and LIMIT to only get the records you will actually display. But you can't do this unless you can cram your search into a single query somehow.

    Given that all three of your models have title and body fields, why not use model inheritance? Just have all three models inherit from a common ancestor that has title and body, and perform the search as a single query on the ancestor model.

    Jquery $.ajax fails in IE on cross domain calls

    Microsoft always ploughs a self-defeating (at least in IE) furrow:

    http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/

    CORS works with XDomainRequest in IE8. But IE 8 does not support Preflighted or Credentialed Requests while Firefox 3.5+, Safari 4+, and Chrome all support such requests.

    How to rename uploaded file before saving it into a directory?

    You can simply change the name of the file by changing the name of the file in the second parameter of move_uploaded_file.

    Instead of

    move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);
    

    Use

    $temp = explode(".", $_FILES["file"]["name"]);
    $newfilename = round(microtime(true)) . '.' . end($temp);
    move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);
    

    Changed to reflect your question, will product a random number based on the current time and append the extension from the originally uploaded file.

    How can I pass variable to ansible playbook in the command line?

    ansible-playbook release.yml -e "version=1.23.45 other_variable=foo"
    

    HTML Button Close Window

    JavaScript can only close a window that was opened using JavaScript. Example below:

    <script>
    function myFunction() {
      var str = "Sample";
      var result = str.link("https://sample.com");
      document.getElementById("demo").innerHTML = result;
    }
    </script>
    

    Changing route doesn't scroll to top in the new page

    I found this solution. If you go to a new view the function gets executed.

    var app = angular.module('hoofdModule', ['ngRoute']);
    
        app.controller('indexController', function ($scope, $window) {
            $scope.$on('$viewContentLoaded', function () {
                $window.scrollTo(0, 0);
            });
        });
    

    Change UITableView height dynamically

    I found adding constraint programmatically much easier than in storyboard.

        var leadingMargin = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.LeadingMargin, relatedBy: NSLayoutRelation.Equal, toItem: self.mView, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1, constant: 0.0)
    
        var trailingMargin = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.TrailingMargin, relatedBy: NSLayoutRelation.Equal, toItem: mView, attribute: NSLayoutAttribute.TrailingMargin, multiplier: 1, constant: 0.0)
    
        var height = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: screenSize.height - 55)
    
        var bottom = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.BottomMargin, relatedBy: NSLayoutRelation.Equal, toItem: self.mView, attribute: NSLayoutAttribute.BottomMargin, multiplier: 1, constant: screenSize.height - 200)
    
        var top = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.TopMargin, relatedBy: NSLayoutRelation.Equal, toItem: self.mView, attribute: NSLayoutAttribute.TopMargin, multiplier: 1, constant: 250)
    
        self.view.addConstraint(leadingMargin)
        self.view.addConstraint(trailingMargin)
        self.view.addConstraint(height)
        self.view.addConstraint(bottom)
        self.view.addConstraint(top)
    

    How to divide flask app into multiple py files?

    You can use simple trick which is import flask app variable from main inside another file, like:

    test-routes.py

    from __main__ import app
    
    @app.route('/test', methods=['GET'])
    def test():
        return 'it works!'
    

    and in your main files, where you declared flask app, import test-routes, like:

    app.py

    from flask import Flask, request, abort
    
    app = Flask(__name__)
    
    # import declared routes
    import test-routes
    

    It works from my side.

    'ng' is not recognized as an internal or external command, operable program or batch file

    I was with the same problem and now discovered a working solution. After successful installation of node and angular CLI do the following steps.

    Open C:\usr\local and copy the path or the path where angular CLI located on your machine.

    enter image description here

    Now open environment variable in your Windows, and add copied path in the following location:

    Advanced > Environment Variable > User Variables and System Variables as below image:

    enter image description here

    That's all, now open cmd and try with any 'ng' command:

    enter image description here

    Searching for file in directories recursively

    Using EnumerateFiles to get files in nested directories. Use AllDirectories to recurse throught directories.

    using System;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
        // Call EnumerateFiles in a foreach-loop.
        foreach (string file in Directory.EnumerateFiles(@"c:\files",
            "*.xml",
            SearchOption.AllDirectories))
        {
            // Display file path.
            Console.WriteLine(file);
        }
        }
    }
    

    javascript popup alert on link click

    Single line works just fine:

    <a href="http://example.com/"
     onclick="return confirm('Please click on OK to continue.');">click me</a>
    

    Adding another line with a different link on the same page works fine too:

    <a href="http://stackoverflow.com/"
     onclick="return confirm('Click on another OK to continue.');">another link</a>
    

    Fixed GridView Header with horizontal and vertical scrolling in asp.net

    <script type="text/javascript">
            $(document).ready(function () {
                var gridHeader = $('#<%=grdSiteWiseEmpAttendance.ClientID%>').clone(true); // Here Clone Copy of Gridview with style
                $(gridHeader).find("tr:gt(0)").remove(); // Here remove all rows except first row (header row)
                $('#<%=grdSiteWiseEmpAttendance.ClientID%> tr th').each(function (i) {
                    // Here Set Width of each th from gridview to new table(clone table) th 
                    $("th:nth-child(" + (i + 1) + ")", gridHeader).css('width', ($(this).width()).toString() + "px");
                });
                $("#GHead1").append(gridHeader);
                $('#GHead1').css('position', 'top');
                $('#GHead1').css('top', $('#<%=grdSiteWiseEmpAttendance.ClientID%>').offset().top);
    
            });
        </script>
    
    <div class="row">
                                                            <div class="col-lg-12" style="width: auto;">
                                                                <div id="GHead1"></div>
                                                                <div id="divGridViewScroll1" style="height: 600px; overflow: auto">
                                                                    <div class="table-responsive">
                                                                        <asp:GridView ID="grdSiteWiseEmpAttendance" CssClass="table table-small-font table-bordered table-striped" Font-Size="Smaller" EmptyDataRowStyle-ForeColor="#cc0000" HeaderStyle-Font-Size="8" HeaderStyle-Font-Names="Calibri" HeaderStyle-Font-Italic="true" runat="server" AutoGenerateColumns="false"
                                                                            BackColor="#f0f5f5" OnRowDataBound="grdSiteWiseEmpAttendance_RowDataBound" HeaderStyle-ForeColor="#990000">
    
                                                                            <Columns>
                                                                            </Columns>
                                                                            <HeaderStyle HorizontalAlign="Justify" VerticalAlign="Top" />
                                                                            <RowStyle Font-Names="Calibri" ForeColor="#000000" />
                                                                        </asp:GridView>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
    

    Reference member variables as class members

    It's called dependency injection via constructor injection: class A gets the dependency as an argument to its constructor and saves the reference to dependent class as a private variable.

    There's an interesting introduction on wikipedia.

    For const-correctness I'd write:

    using T = int;
    
    class A
    {
    public:
      A(const T &thing) : m_thing(thing) {}
      // ...
    
    private:
       const T &m_thing;
    };
    

    but a problem with this class is that it accepts references to temporary objects:

    T t;
    A a1{t};    // this is ok, but...
    
    A a2{T()};  // ... this is BAD.
    

    It's better to add (requires C++11 at least):

    class A
    {
    public:
      A(const T &thing) : m_thing(thing) {}
      A(const T &&) = delete;  // prevents rvalue binding
      // ...
    
    private:
      const T &m_thing;
    };
    

    Anyway if you change the constructor:

    class A
    {
    public:
      A(const T *thing) : m_thing(*thing) { assert(thing); }
      // ...
    
    private:
       const T &m_thing;
    };
    

    it's pretty much guaranteed that you won't have a pointer to a temporary.

    Also, since the constructor takes a pointer, it's clearer to users of A that they need to pay attention to the lifetime of the object they pass.


    Somewhat related topics are:

    How to read a list of files from a folder using PHP?

    There is this function scandir():

    $dir = 'dir';
    $files = scandir($dir, 0);
    for($i = 2; $i < count($files); $i++)
        print $files[$i]."<br>";
    

    More here in the php.net manual

    React JS onClick event handler

    Two ways I can think of are

    var TestApp = React.createClass({
        getComponent: function(index) {
            $(this.getDOMNode()).find('li:nth-child(' + index + ')').css({
                'background-color': '#ccc'
            });
        },
        render: function() {
            return (
                <div>
                  <ul>
                    <li onClick={this.getComponent.bind(this, 1)}>Component 1</li>
                    <li onClick={this.getComponent.bind(this, 2)}>Component 2</li>
                    <li onClick={this.getComponent.bind(this, 3)}>Component 3</li>
                  </ul>
                </div>
            );
        }
    });
    React.renderComponent(<TestApp /> , document.getElementById('soln1'));
    

    This is my personal favorite.

    var ListItem = React.createClass({
        getInitialState: function() {
            return {
                isSelected: false
            };
        },
        handleClick: function() {
            this.setState({
                isSelected: true
            })
        },
        render: function() {
            var isSelected = this.state.isSelected;
            var style = {
                'background-color': ''
            };
            if (isSelected) {
                style = {
                    'background-color': '#ccc'
                };
            }
            return (
                <li onClick={this.handleClick} style={style}>{this.props.content}</li>
            );
        }
    });
    
    var TestApp2 = React.createClass({
        getComponent: function(index) {
            $(this.getDOMNode()).find('li:nth-child(' + index + ')').css({
                'background-color': '#ccc'
            });
        },
        render: function() {
            return (
                <div>
                 <ul>
                  <ListItem content="Component 1" />
                  <ListItem content="Component 2" />
                  <ListItem content="Component 3" />
                 </ul>
                </div>
            );
        }
    });
    React.renderComponent(<TestApp2 /> , document.getElementById('soln2'));
    

    Here is a DEMO

    I hope this helps.

    using stored procedure in entity framework

    Simple. Just instantiate your entity, set it to an object and pass it to your view in your controller.

    enter image description here

    Entity

    VehicleInfoEntities db = new VehicleInfoEntities();

    Stored Procedure

    dbo.prcGetMakes()

    or

    you can add any parameters in your stored procedure inside the brackets ()

    dbo.prcGetMakes("BMW")

    Controller

    public class HomeController : Controller
    {
        VehicleInfoEntities db = new VehicleInfoEntities();
    
        public ActionResult Index()
        {
            var makes = db.prcGetMakes(null);
    
            return View(makes);
        }
    }
    

    How do I get a range's address including the worksheet name, but not the workbook name, in Excel VBA?

    Ben is right. I also can't think of any way to do this. I'd suggest either the method Ben recommends, or the following to strip the Workbook name off.

    Dim cell As Range
    Dim address As String
    Set cell = Worksheets(1).Cells.Range("A1")
    address = cell.address(External:=True)
    address = Right(address, Len(address) - InStr(1, address, "]"))
    

    RegEx for Javascript to allow only alphanumeric

    Input these code to your SCRATCHPAD and see the action.

    var str=String("Blah-Blah1_2,oo0.01&zz%kick").replace(/[^\w-]/ig, '');
    

    How to run a command as a specific user in an init script?

    If you have start-stop-daemon

    start-stop-daemon --start --quiet -u username -g usergroup --exec command ...
    

    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 connect to my existing Git repository using Visual Studio Code?

    Use the Git GUI in the Git plugin.

    Clone your online repository with the URL which you have.

    After cloning, make changes to the files. When you make changes, you can see the number changes. Commit those changes.

    Fetch from the remote (to check if anything is updated while you are working).

    If the fetch operation gives you an update about the changes in the remote repository, make a pull operation which will update your copy in Visual Studio Code. Otherwise, do not make a pull operation if there aren't any changes in the remote repository.

    Push your changes to the upstream remote repository by making a push operation.

    How to create custom spinner like border around the spinner with down triangle on the right side?

    You can achieve the following by using a single line in your spinner declaration in XML: enter image description here

    Just add this: style="@android:style/Widget.Holo.Light.Spinner"

    This is a default generated style in android. It doesn't contain borders around it though. For that you'd better search something on google.

    Hope this helps.

    UPDATE: AFter a lot of digging I got something which works well for introducing border around spinner.

    <?xml version="1.0" encoding="utf-8"?>
    <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <item
            android:bottom="8dp"
            android:top="8dp">
            <shape>
                <solid android:color="@android:color/white" />
                <corners android:radius="4dp" />
                <stroke
                    android:width="2dp"
                    android:color="#9E9E9E" />
                <padding
                    android:bottom="16dp"
                    android:left="8dp"
                    android:right="16dp"
                    android:top="16dp" />
            </shape>
        </item>
    </layer-list>
    

    Place this in the drawable folder and use it as a background for spinner. Like this:

    <RelativeLayout
            android:id="@+id/speaker_relative_layout"
            android:layout_width="0dp"
            android:layout_height="70dp"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="16dp"
            android:background="@drawable/spinner_style"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent">
    
            <Spinner
                android:id="@+id/select_speaker_spinner"
                style="@style/Widget.AppCompat.DropDownItem.Spinner"
                android:layout_width="match_parent"
                android:layout_height="70dp"
                android:entries="@array/select_speaker_spinner_array"
                android:spinnerMode="dialog" />
    
        </RelativeLayout>
    

    Non-conformable arrays error in code

    The problem is that omega in your case is matrix of dimensions 1 * 1. You should convert it to a vector if you wish to multiply t(X) %*% X by a scalar (that is omega)

    In particular, you'll have to replace this line:

    omega   = rgamma(1,a0,1) / L0
    

    with:

    omega   = as.vector(rgamma(1,a0,1) / L0)
    

    everywhere in your code. It happens in two places (once inside the loop and once outside). You can substitute as.vector(.) or c(t(.)). Both are equivalent.

    Here's the modified code that should work:

    gibbs = function(data, m01 = 0, m02 = 0, k01 = 0.1, k02 = 0.1, 
                         a0 = 0.1, L0 = 0.1, nburn = 0, ndraw = 5000) {
        m0      = c(m01, m02) 
        C0      = matrix(nrow = 2, ncol = 2) 
        C0[1,1] = 1 / k01 
        C0[1,2] = 0 
        C0[2,1] = 0 
        C0[2,2] = 1 / k02 
        beta    = mvrnorm(1,m0,C0) 
        omega   = as.vector(rgamma(1,a0,1) / L0)
        draws   = matrix(ncol = 3,nrow = ndraw) 
        it      = -nburn 
    
        while (it < ndraw) {
            it    = it + 1 
            C1    = solve(solve(C0) + omega * t(X) %*% X) 
            m1    = C1 %*% (solve(C0) %*% m0 + omega * t(X) %*% y)
            beta  = mvrnorm(1, m1, C1) 
            a1    = a0 + n / 2 
            L1    = L0 + t(y - X %*% beta) %*% (y - X %*% beta) / 2 
            omega = as.vector(rgamma(1, a1, 1) / L1)
            if (it > 0) { 
                draws[it,1] = beta[1]
                draws[it,2] = beta[2]
                draws[it,3] = omega
            }
        }
        return(draws)
    }
    

    Removing leading zeroes from a field in a SQL statement

    you can try this SELECT REPLACE(columnname,'0','') FROM table

    Why when I transfer a file through SFTP, it takes longer than FTP?

    Your results make sense. Since FTP operates over a non-encrypted channel it is faster than SFTP (which is subsystem on top of the SSH version 2 protocol). Also remember that SFTP is a packet based protocol unlike FTP which is command based.

    Each packet in SFTP is encrypted before being written to the outgoing socket from the client and subsequently decrypted when received by the server. This of-course leads to slow transfer rates but very secure transfer. Using compression such as zlib with SFTP improves the transfer time but still it won't be anywhere near plain text FTP. Perhaps a better comparison is to compare SFTP with FTPS which both use encryption?

    Speed for SFTP depends on the cipher used for encryption/decryption, the compression used e.g. zlib, packet sizes and buffer sizes used for the socket connection.

    Web.Config Debug/Release

    If your are going to replace all of the connection strings with news ones for production environment, you can simply replace all connection strings with production ones using this syntax:

    <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
    
    <connectionStrings xdt:Transform="Replace">
        <!-- production environment config --->
        <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
          providerName="System.Data.SqlClient" />
        <add name="Testing1" connectionString="Data Source=test;Initial Catalog=TestDatabase;Integrated Security=True"
          providerName="System.Data.SqlClient" />
    </connectionStrings>
    ....
    

    Information for this answer are brought from this answer and this blog post.

    notice: As others explained already, this setting will apply only when application publishes not when running/debugging it (by hitting F5).

    lambda expression for exists within list

    I would look at the Join operator:

    from r in list join i in listofIds on r.Id equals i select r
    

    I'm not sure how this would be optimized over the Contains methods, but at least it gives the compiler a better idea of what you're trying to do. It's also sematically closer to what you're trying to achieve.

    Edit: Extension method syntax for completeness (now that I've figured it out):

    var results = listofIds.Join(list, i => i, r => r.Id, (i, r) => r);
    

    CSS get height of screen resolution

    You can bind the current height and width of the screen to css variables: var(--screen-x) and var(--screen-y) with this javascript:

    var root = document.documentElement;
    
    document.addEventListener('resize', () => {
      root.style.setProperty('--screen-x', window.screenX)
      root.style.setProperty('--screen-y', window.screenY)
    })
    

    This was directly adapted from lea verou's example in her talk on css variables here: https://leaverou.github.io/css-variables/#slide31

    Spring: how do I inject an HttpServletRequest into a request-scoped bean?

    Spring exposes the current HttpServletRequest object (as well as the current HttpSession object) through a wrapper object of type ServletRequestAttributes. This wrapper object is bound to ThreadLocal and is obtained by calling the static method RequestContextHolder.currentRequestAttributes().

    ServletRequestAttributes provides the method getRequest() to get the current request, getSession() to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:

    HttpServletRequest curRequest = 
    ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
    .getRequest();
    

    Note that the RequestContextHolder.currentRequestAttributes() method returns an interface and needs to be typecasted to ServletRequestAttributes that implements the interface.


    Spring Javadoc: RequestContextHolder | ServletRequestAttributes

    How to read PDF files using Java?

    PDFBox is the best library I've found for this purpose, it's comprehensive and really quite easy to use if you're just doing basic text extraction. Examples can be found here.

    It explains it on the page, but one thing to watch out for is that the start and end indexes when using setStartPage() and setEndPage() are both inclusive. I skipped over that explanation first time round and then it took me a while to realise why I was getting more than one page back with each call!

    Itext is another alternative that also works with C#, though I've personally never used it. It's more low level than PDFBox, so less suited to the job if all you need is basic text extraction.

    HEAD and ORIG_HEAD in Git

    From git reset

    "pull" or "merge" always leaves the original tip of the current branch in ORIG_HEAD.

    git reset --hard ORIG_HEAD
    

    Resetting hard to it brings your index file and the working tree back to that state, and resets the tip of the branch to that commit.

    git reset --merge ORIG_HEAD
    

    After inspecting the result of the merge, you may find that the change in the other branch is unsatisfactory. Running "git reset --hard ORIG_HEAD" will let you go back to where you were, but it will discard your local changes, which you do not want. "git reset --merge" keeps your local changes.


    Before any patches are applied, ORIG_HEAD is set to the tip of the current branch.
    This is useful if you have problems with multiple commits, like running 'git am' on the wrong branch or an error in the commits that is more easily fixed by changing the mailbox (e.g. +errors in the "From:" lines).

    In addition, merge always sets '.git/ORIG_HEAD' to the original state of HEAD so a problematic merge can be removed by using 'git reset ORIG_HEAD'.


    Note: from here

    HEAD is a moving pointer. Sometimes it means the current branch, sometimes it doesn't.

    So HEAD is NOT a synonym for "current branch" everywhere already.

    HEAD means "current" everywhere in git, but it does not necessarily mean "current branch" (i.e. detached HEAD).

    But it almost always means the "current commit".
    It is the commit "git commit" builds on top of, and "git diff --cached" and "git status" compare against.
    It means the current branch only in very limited contexts (exactly when we want a branch name to operate on --- resetting and growing the branch tip via commit/rebase/etc.).

    Reflog is a vehicle to go back in time and time machines have interesting interaction with the notion of "current".

    HEAD@{5.minutes.ago} could mean "dereference HEAD symref to find out what branch we are on RIGHT NOW, and then find out where the tip of that branch was 5 minutes ago".
    Alternatively it could mean "what is the commit I would have referred to as HEAD 5 minutes ago, e.g. if I did "git show HEAD" back then".


    git1.8.4 (July 2013) introduces introduced a new notation!
    (Actually, it will be for 1.8.5, Q4 2013: reintroduced with commit 9ba89f4), by Felipe Contreras.

    Instead of typing four capital letters "HEAD", you can say "@" now,
    e.g. "git log @".

    See commit cdfd948

    Typing 'HEAD' is tedious, especially when we can use '@' instead.

    The reason for choosing '@' is that it follows naturally from the ref@op syntax (e.g. HEAD@{u}), except we have no ref, and no operation, and when we don't have those, it makes sens to assume 'HEAD'.

    So now we can use 'git show @~1', and all that goody goodness.

    Until now '@' was a valid name, but it conflicts with this idea, so let's make it invalid. Probably very few people, if any, used this name.

    How can I use jQuery to move a div across the screen

    In jQuery 1.2 and newer you no longer have to position the element absolutely; you can use normal relative positioning and use += or -= to add to or subtract from properties, e.g.

    $("#startAnimation").click(function(){
        $(".toBeAnimated").animate({ 
            marginLeft: "+=250px",
        }, 1000 );
    });
    

    And to echo the guy who answered first's advice: Javascript is not performant. Don't overuse animations, or expect things than run nice and fast on your high performance PC on Chrome to look good on a bog-standard PC running IE. Test it, and make sure it degrades well!

    sendUserActionEvent() is null

    Same issue on a Galaxy Tab and on a Xperia S, after uninstall and install again it seems that disappear.

    The code that suddenly appear to raise this problem is this:

    public void unlockMainActivity() {
        SharedPreferences prefs = getSharedPreferences("CALCULATOR_PREFS", 0);
        boolean hasCode = prefs.getBoolean("HAS_CODE", false);
        Context context = this.getApplicationContext();
        Intent intent = null;
    
        if (!hasCode) {
            intent = new Intent(context, WellcomeActivity.class);
        } else {
            intent = new Intent(context, CalculatingActivity.class);
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        (context).startActivity(intent);
    }
    

    Read XML Attribute using XmlDocument

    I have an Xml File books.xml

    <ParameterDBConfig>
        <ID Definition="1" />
    </ParameterDBConfig>
    

    Program:

    XmlDocument doc = new XmlDocument();
    doc.Load("D:/siva/books.xml");
    XmlNodeList elemList = doc.GetElementsByTagName("ID");     
    for (int i = 0; i < elemList.Count; i++)     
    {
        string attrVal = elemList[i].Attributes["Definition"].Value;
    }
    

    Now, attrVal has the value of ID.

    Is there a wikipedia API just for retrieve content summary?

    You can also get content such as the first pagagraph via DBPedia which takes Wikipedia content and creates structured information from it (RDF) and makes this available via an API. The DBPedia API is a SPARQL one (RDF-based) but it outputs JSON and it is pretty easy to wrap.

    As an example here's a super simple JS library named WikipediaJS that can extract structured content including a summary first paragraph: http://okfnlabs.org/wikipediajs/

    You can read more about it in this blog post: http://okfnlabs.org/blog/2012/09/10/wikipediajs-a-javascript-library-for-accessing-wikipedia-article-information.html

    The JS library code can be found here: https://github.com/okfn/wikipediajs/blob/master/wikipedia.js

    How do I get a button to open another activity?

    Using an OnClickListener

    Inside your Activity instance's onCreate() method you need to first find your Button by it's id using findViewById() and then set an OnClickListener for your button and implement the onClick() method so that it starts your new Activity.

    Button yourButton = (Button) findViewById(R.id.your_buttons_id);
    
    yourButton.setOnClickListener(new OnClickListener(){
        public void onClick(View v){                        
            startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
        }
    });
    

    This is probably most developers preferred method. However, there is a common alternative.

    Using onClick in XML

    Alternatively you can use the android:onClick="yourMethodName" to declare the method name in your Activity which is called when you click your Button, and then declare your method like so;

    public void yourMethodName(View v){
        startActivity(new Intent(YourCurrentActivity.this, YourNewActivity.class));
    }
    

    Also, don't forget to declare your new Activity in your manifest.xml. I hope this helps.

    References;

    Set select option 'selected', by value

    Best way is like this:

    $(`#YourSelect option[value='${YourValue}']`).prop('selected', true);
    

    What is an attribute in Java?

    Attributes is same term used alternativly for properties or fields or data members or class members.

    Sending GET request with Authentication headers using restTemplate

    You can use postForObject with an HttpEntity. It would look like this:

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", "Bearer "+accessToken);
    
    HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
    String result = restTemplate.postForObject(url, entity, String.class);
    

    In a GET request, you'd usually not send a body (it's allowed, but it doesn't serve any purpose). The way to add headers without wiring the RestTemplate differently is to use the exchange or execute methods directly. The get shorthands don't support header modification.

    The asymmetry is a bit weird on a first glance, perhaps this is going to be fixed in future versions of Spring.

    How to Replace Multiple Characters in SQL?

    I suggest you to create a scalar user defined function. This is an example (sorry in advance, because the variable names are in spanish):

    CREATE FUNCTION [dbo].[Udf_ReplaceChars] (
      @cadena VARCHAR(500),  -- String to manipulate
      @caracteresElim VARCHAR(100),  -- String of characters to be replaced
      @caracteresReem VARCHAR(100)   -- String of characters for replacement
    ) 
    RETURNS VARCHAR(500)
    AS
    BEGIN
      DECLARE @cadenaFinal VARCHAR(500), @longCad INT, @pos INT, @caracter CHAR(1), @posCarER INT;
      SELECT
        @cadenaFinal = '',
        @longCad = LEN(@cadena),
        @pos = 1;
    
      IF LEN(@caracteresElim)<>LEN(@caracteresReem)
        BEGIN
          RETURN NULL;
        END
    
      WHILE @pos <= @longCad
        BEGIN
          SELECT
            @caracter = SUBSTRING(@cadena,@pos,1),
            @pos = @pos + 1,
            @posCarER = CHARINDEX(@caracter,@caracteresElim);
    
          IF @posCarER <= 0
            BEGIN
              SET @cadenaFinal = @cadenaFinal + @caracter;
            END
          ELSE
            BEGIN
              SET @cadenaFinal = @cadenaFinal + SUBSTRING(@caracteresReem,@posCarER,1)
            END
        END
    
      RETURN @cadenaFinal;
    END
    

    Here is an example using this function:

    SELECT dbo.Udf_ReplaceChars('This is a test.','sat','Z47');
    

    And the result is: 7hiZ iZ 4 7eZ7.

    As you can see, each character of the @caracteresElim parameter is replaced by the character in the same position from the @caracteresReem parameter.

    Mercurial: how to amend the last commit?

    With the release of Mercurial 2.2, you can use the --amend option with hg commit to update the last commit with the current working directory

    From the command line reference:

    The --amend flag can be used to amend the parent of the working directory with a new commit that contains the changes in the parent in addition to those currently reported by hg status, if there are any. The old commit is stored in a backup bundle in .hg/strip-backup (see hg help bundle and hg help unbundle on how to restore it).

    Message, user and date are taken from the amended commit unless specified. When a message isn't specified on the command line, the editor will open with the message of the amended commit.

    The great thing is that this mechanism is "safe", because it relies on the relatively new "Phases" feature to prevent updates that would change history that's already been made available outside of the local repository.

    How to make a cross-module variable?

    I wondered if it would be possible to avoid some of the disadvantages of using global variables (see e.g. http://wiki.c2.com/?GlobalVariablesAreBad) by using a class namespace rather than a global/module namespace to pass values of variables. The following code indicates that the two methods are essentially identical. There is a slight advantage in using class namespaces as explained below.

    The following code fragments also show that attributes or variables may be dynamically created and deleted in both global/module namespaces and class namespaces.

    wall.py

    # Note no definition of global variables
    
    class router:
        """ Empty class """
    

    I call this module 'wall' since it is used to bounce variables off of. It will act as a space to temporarily define global variables and class-wide attributes of the empty class 'router'.

    source.py

    import wall
    def sourcefn():
        msg = 'Hello world!'
        wall.msg = msg
        wall.router.msg = msg
    

    This module imports wall and defines a single function sourcefn which defines a message and emits it by two different mechanisms, one via globals and one via the router function. Note that the variables wall.msg and wall.router.message are defined here for the first time in their respective namespaces.

    dest.py

    import wall
    def destfn():
    
        if hasattr(wall, 'msg'):
            print 'global: ' + wall.msg
            del wall.msg
        else:
            print 'global: ' + 'no message'
    
        if hasattr(wall.router, 'msg'):
            print 'router: ' + wall.router.msg
            del wall.router.msg
        else:
            print 'router: ' + 'no message'
    

    This module defines a function destfn which uses the two different mechanisms to receive the messages emitted by source. It allows for the possibility that the variable 'msg' may not exist. destfn also deletes the variables once they have been displayed.

    main.py

    import source, dest
    
    source.sourcefn()
    
    dest.destfn() # variables deleted after this call
    dest.destfn()
    

    This module calls the previously defined functions in sequence. After the first call to dest.destfn the variables wall.msg and wall.router.msg no longer exist.

    The output from the program is:

    global: Hello world!
    router: Hello world!
    global: no message
    router: no message

    The above code fragments show that the module/global and the class/class variable mechanisms are essentially identical.

    If a lot of variables are to be shared, namespace pollution can be managed either by using several wall-type modules, e.g. wall1, wall2 etc. or by defining several router-type classes in a single file. The latter is slightly tidier, so perhaps represents a marginal advantage for use of the class-variable mechanism.

    Thymeleaf: how to use conditionals to dynamically add/remove a CSS class

    What @Nilsi mentioned is perfectly correct. However, adminclass and user class need to be wrapped in single quotes as this might fail due to Thymeleaf looking for adminClass or userclass variables which should be strings. That said,

    it should be: -

     <a href="" class="baseclass" th:classappend="${isAdmin} ? 'adminclass' : 
     'userclass'"> 
     </a>
    

    or just:

    <a href="" th:class="${isAdmin} ? 'newclass' : 
      'baseclass'"> 
     </a>
    

    Cast object to T

    Actually, the problem here is the use of ReadContentAsObject. Unfortunately, this method does not live up to its expectations; while it should detect the most appropirate type for the value, it actually returns a string, no matter what(this can be verified using Reflector).

    However, in your specific case, you already know the type you want to cast to, therefore i would say you are using the wrong method.

    Try using ReadContentAs instead, it's exactly what you need.

    private static T ReadData<T>(XmlReader reader, string value)
    {
        reader.MoveToAttribute(value);
        object readData = reader.ReadContentAs(typeof(T), null);
        return (T)readData;
    }
    

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

    If you still have problems with Eclipse finding your files, you might try the following:

    1. Verify that the file exists according to the current execution environment by using the java.io.File class to get a canonical path format and verify that (a) the file exists and (b) what the canonical path is.
    2. Verify the default working directory by printing the following in your main:

          System.out.println("Working dir:  " + System.getProperty("user.dir"));
      

    For (1) above, I put the following debugging code around the specific file I was trying to access:

                File imageFile = new File(source);
                System.out.println("Canonical path of target image: " + imageFile.getCanonicalPath());
                if (!imageFile.exists()) {
                    System.out.println("file " + imageFile + " does not exist");
                }
                image = ImageIO.read(imageFile);                
    

    For whatever reason, I ended up ignoring most of the other posts telling me to put the image files in "src" or some other variant, as I verified that the system was looking at the root of the Eclipse project directory hierarchy (e.g., $HOME/workspace/myProject).

    Having the images in src/ (which is automatically copied to bin/) didn't do the trick on Eclipse Luna.

    How do you do the "therefore" (?) symbol on a Mac or in Textmate?

    First you use a full stop, then you hold down alt and press the letter H and put in another full stop. .?.

    correct configuration for nginx to localhost?

    Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

     server {
                listen       80;
                server_name  localhost;
    
                access_log  logs/localhost.access.log  main;
    
                location / {
                    root /var/www/board/public;
                    index index.html index.htm index.php;
                }
           }
    

    Changing SqlConnection timeout

    I found an excellent blogpost on this subject: https://improve.dk/controlling-sqlconnection-timeouts/

    Basically, you either set Connect Timeout in the connection string, or you set ConnectionTimeout on the command object.

    Be aware that the timeout time is in seconds.

    Why is there no Char.Empty like String.Empty?

    If you want to remove characters that satisfy a specific condition, you may use this:

    string s = "SoMEthInG";
    s = new string(s.Where(c => char.IsUpper(c)).ToArray());
    

    (This will leave only the uppercase characters in the string.)

    In other words, you may "use" the string as an IEnumerable<char>, make changes on it and then convert it back to a string as shown above.

    Again, this enables to not only remove a specific char because of the lambda expression, although you can do so if you change the lambda expression like this: c => c != 't'.

    HTML Input - already filled in text

    You seem to look for the input attribute value, "the initial value of the control"?

    <input type="text" value="Morlodenhof 7" />
    

    https://developer.mozilla.org/de/docs/Web/HTML/Element/Input#attr-value

    Using Case/Switch and GetType to determine the object

    I actually prefer the approach given as the answer here: Is there a better alternative than this to 'switch on type'?

    There is however a good argument about not implementing any type comparison methids in an object oriented language like C#. You could as an alternative extend and add extra required functionality using inheritance.

    This point was discussed in the comments of the authors blog here: http://blogs.msdn.com/b/jaredpar/archive/2008/05/16/switching-on-types.aspx#8553535

    I found this an extremely interesting point which changed my approach in a similar situation and only hope this helps others.

    Kind Regards, Wayne

    JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

    Use above annotation if someone is facing :--org.hibernate.jpa.HibernatePersistenceProvider persistence provider when it attempted to create the container entity manager factory for the paymentenginePU persistence unit. The following error occurred: [PersistenceUnit: paymentenginePU] Unable to build Hibernate SessionFactory ** This is a solution if you are using Audit table.@Audit

    Use:- @Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED) on superclass.

    Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

    scanf needs to know the size of the data being pointed at by &d to fill it properly, whereas variadic functions promote floats to doubles (not entirely sure why), so printf is always getting a double.