Programs & Examples On #Logonserver

How to convert DateTime to a number with a precision greater than days in T-SQL?

And here is a bigint version of the same

``````DECLARE @ts BIGINT
SET @ts = CAST(CAST(getdate() AS TIMESTAMP) AS BIGINT)
SELECT @ts
``````

Calculating a 2D Vector's Cross Product

In short: It's a shorthand notation for a mathematical hack.

Long explanation:

You can't do a cross product with vectors in 2D space. The operation is not defined there.

However, often it is interesting to evaluate the cross product of two vectors assuming that the 2D vectors are extended to 3D by setting their z-coordinate to zero. This is the same as working with 3D vectors on the xy-plane.

If you extend the vectors that way and calculate the cross product of such an extended vector pair you'll notice that only the z-component has a meaningful value: x and y will always be zero.

That's the reason why the z-component of the result is often simply returned as a scalar. This scalar can for example be used to find the winding of three points in 2D space.

From a pure mathematical point of view the cross product in 2D space does not exist, the scalar version is the hack and a 2D cross product that returns a 2D vector makes no sense at all.

How to limit the maximum value of a numeric field in a Django model?

You can use Django's built-in validators

``````from django.db.models import IntegerField, Model
from django.core.validators import MaxValueValidator, MinValueValidator

class CoolModelBro(Model):
limited_integer_field = IntegerField(
default=1,
validators=[
MaxValueValidator(100),
MinValueValidator(1)
]
)
``````

Edit: When working directly with the model, make sure to call the model full_clean method before saving the model in order to trigger the validators. This is not required when using `ModelForm` since the forms will do that automatically.

How do I get an object's unqualified (short) class name?

I found myself in a unique situation where `instanceof` could not be used (specifically namespaced traits) and I needed the short name in the most efficient way possible so I've done a little benchmark of my own. It includes all the different methods & variations from the answers in this question.

``````\$bench = new \xori\Benchmark(1000, 1000);     # https://github.com/Xorifelse/php-benchmark-closure
\$shell = new \my\fancy\namespace\classname(); # Just an empty class named `classname` defined in the `\my\fancy\namespace\` namespace

\$bench->register('strrpos', (function(){
return substr(static::class, strrpos(static::class, '\\') + 1);
})->bindTo(\$shell));

\$bench->register('safe strrpos', (function(){
return substr(static::class, (\$p = strrpos(static::class, '\\')) !== false ? \$p + 1 : 0);
})->bindTo(\$shell));

\$bench->register('strrchr', (function(){
return substr(strrchr(static::class, '\\'), 1);
})->bindTo(\$shell));

\$bench->register('reflection', (function(){
return (new \ReflectionClass(\$this))->getShortName();
})->bindTo(\$shell));

\$bench->register('reflection 2', (function(\$obj){
return \$obj->getShortName();
})->bindTo(\$shell), new \ReflectionClass(\$shell));

\$bench->register('basename', (function(){
return basename(str_replace('\\', '/', static::class));
})->bindTo(\$shell));

\$bench->register('explode', (function(){
\$e = explode("\\", static::class);
return end(\$e);
})->bindTo(\$shell));

\$bench->register('slice', (function(){
return join('',array_slice(explode('\\', static::class), -1));
})->bindTo(\$shell));

print_r(\$bench->start());
``````

A list of the of the entire result is here but here are the highlights:

• If you're going to use reflection anyways, using `\$obj->getShortName()` is the fastest method however; using reflection only to get the short name it is almost the slowest method.
• `'strrpos'` can return a wrong value if the object is not in a namespace so while `'safe strrpos'` is a tiny bit slower I would say this is the winner.
• To make `'basename'` compatible between Linux and Windows you need to use `str_replace()` which makes this method the slowest of them all.

A simplified table of results, speed is measured compared to the slowest method:

``````+-----------------+--------+
| registered name | speed  |
+-----------------+--------+
| reflection 2    | 70.75% |
| strrpos         | 60.38% |
| safe strrpos    | 57.69% |
| strrchr         | 54.88% |
| explode         | 46.60% |
| slice           | 37.02% |
| reflection      | 16.75% |
| basename        | 0.00%  |
+-----------------+--------+
``````

How to generate a git patch for a specific commit?

For generating the patches from the topmost commits from a specific sha1 hash:

``````git format-patch -<n> <SHA1>
``````

The last 10 patches from head in a single patch file:

``````git format-patch -10 HEAD --stdout > 0001-last-10-commits.patch
``````

How to know/change current directory in Python shell?

you want

``````import os
os.getcwd()
os.chdir('..')
``````

Are querystring parameters secure in HTTPS (HTTP + SSL)?

I disagree with the advice given here - even the reference for the accepted answer concludes:

You can of course use query string parameters with HTTPS, but don’t use them for anything that could present a security problem. For example, you could safely use them to identity part numbers or types of display like ‘accountview’ or ‘printpage’, but don’t use them for passwords, credit card numbers or other pieces of information that should not be publicly available.

So, no they aren't really safe...!

Zip lists in Python

`zip` creates a new list, filled with tuples containing elements from the iterable arguments:

``````>>> zip ([1,2],[3,4])
[(1,3), (2,4)]
``````

I expect what you try to so is create a tuple where each element is a list.

How to handle the `onKeyPress` event in ReactJS?

For me `onKeyPress` the `e.keyCode` is always `0`, but `e.charCode` has correct value. If used `onKeyDown` the correct code in `e.charCode`.

``````var Title = React.createClass({
handleTest: function(e) {
if (e.charCode == 13) {
}
if (e.keyCode == 13) {
}
},
render: function() {
return(
<div>
<textarea onKeyPress={this.handleTest} />
</div>
);
}
});
``````

Is Secure.ANDROID_ID unique for each device?

It doesn't seem to be enforced in Android compliance requirements and so manufacturers seem to implement it the way they choose including some using it more as a 'model' ID etc.

Also, be aware that even if a manufacturer has written a generator to make it a UUID (for example), it's not guaranteed to survive a factory reset.

R data formats: RData, Rda, Rds etc

In addition to @KenM's answer, another important distinction is that, when loading in a saved object, you can assign the contents of an `Rds` file. Not so for `Rda`

``````> x <- 1:5
> save(x, file="x.Rda")
> saveRDS(x, file="x.Rds")
> rm(x)

> new_x1
[1] 1 2 3 4 5

## 'ASSIGN' USING load -- note the result
> new_x2
[1] "x"
# NOTE: `load()` simply returns the name of the objects loaded. Not the values.
> x
[1] 1 2 3 4 5
``````

PDO's query vs execute

`query` runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.

`execute` runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. `execute` will also perform better if you are repeating a query multiple times. Example of prepared statements:

``````\$sth = \$dbh->prepare('SELECT name, colour, calories FROM fruit
WHERE calories < :calories AND colour = :colour');
\$sth->bindParam(':calories', \$calories);
\$sth->bindParam(':colour', \$colour);
\$sth->execute();
// \$calories or \$color do not need to be escaped or quoted since the
//    data is separated from the query
``````

Best practice is to stick with prepared statements and `execute` for increased security.

JAVA How to remove trailing zeros from a double

You should use `DecimalFormat("0.#")`

For `4.3000`

``````Double price = 4.3000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));
``````

output is:

``````4.3
``````

In case of 5.000 we have

``````Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));
``````

And the output is:

``````5
``````

Send Message in C#

You don't need to send messages.

Add an event to the one form and an event handler to the other. Then you can use a third project which references the other two to attach the event handler to the event. The two DLLs don't need to reference each other for this to work.

Automapper missing type map configuration or unsupported mapping - Error

I created a new AutomapperProfile class. It extends Profile. We have over 100 projects in our solution. Many projects have an AutomapperProfile class, but this one was new to this existing project. However, I did find what I had to do to fix this issue for us. There is a Binding project. Within the Initialization there is this code:

``````var mappingConfig = new List<Action<IConfiguration>>();

// Initialize the Automapper Configuration for all Known Assemblies
{
//...
``````

Note that ConfigureProfilesInAssemblyOfType looks like this:

``````    private static void ConfigureProfilesInAssemblyOfType<T>( IConfiguration configuration )
{
var log = LogProvider.Get( typeof (AutomapperConfiguration) );

// The Automapper Profile Type
var automapperProfileType = typeof (Profile);

// The Assembly containing the type
var assembly = typeof (T).Assembly;
log.Debug( "Scanning " + assembly.FullName );

// Configure any Profile classes found in the assembly containing the type.
assembly.GetTypes()
.Where( automapperProfileType.IsAssignableFrom ).ToList()
.ForEach( x =>
{
log.Debug( "Adding Profile '" + x.FullName + "'" );
configuration.AddProfile( Activator.CreateInstance( x ) as Profile );
} );
}
``````

Best regards, -Jeff

Excel tab sheet names vs. Visual Basic sheet names

Actually "Sheet1" object / code name can be changed. In VBA, click on Sheet1 in Excel Objects list. In the properties window, you can change Sheet1 to say rng.

Then you can reference rng as a global object without having to create a variable first. So debug.print rng.name works just fine. No more Worksheets("rng").name.

Unlike the tab, the object name has same restrictions as other variables (i.e. no spaces).

``````set_time_limit(0);
\$file = file_get_contents('path of your file');
file_put_contents('file.ext', \$file);
``````

What's the common practice for enums in Python?

``````class Materials:
Shaded, Shiny, Transparent, Matte = range(4)

>>> print Materials.Matte
3
``````

how to display none through code behind

try this

`<div id="login_div" runat="server">`

and on the code behind.

`login_div.Style.Add("display", "none");`

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

How to get the parent dir location

Here is another relatively simple solution that:

• does not use `dirname()` (which does not work as expected on one level arguments like "file.txt" or relative parents like "..")
• does not use `abspath()` (avoiding any assumptions about the current working directory) but instead preserves the relative character of paths

it just uses `normpath` and `join`:

``````def parent(p):
return os.path.normpath(os.path.join(p, os.path.pardir))

# Example:
for p in ['foo', 'foo/bar/baz', 'with/trailing/slash/',
'dir/file.txt', '../up/', '/abs/path']:
print parent(p)
``````

Result:

``````.
foo/bar
with/trailing
dir
..
/abs
``````

Are the decimal places in a CSS width respected?

If it's a percentage width, then yes, it is respected. As Martin pointed out, things break down when you get to fractional pixels, but if your percentage values yield integer pixel value (e.g. 50.5% of 200px in the example) you'll get sensible, expected behaviour.

Edit: I've updated the example to show what happens to fractional pixels (in Chrome the values are truncated, so 50, 50.5 and 50.6 all show the same width).

Asserting successive calls to a mock method

I always have to look this one up time and time again, so here is my answer.

Asserting multiple method calls on different objects of the same class

Suppose we have a heavy duty class (which we want to mock):

``````In [1]: class HeavyDuty(object):
...:     def __init__(self):
...:         import time
...:         time.sleep(2)  # <- Spends a lot of time here
...:
...:     def do_work(self, arg1, arg2):
...:         print("Called with %r and %r" % (arg1, arg2))
...:
``````

here is some code that uses two instances of the `HeavyDuty` class:

``````In [2]: def heavy_work():
...:     hd1 = HeavyDuty()
...:     hd1.do_work(13, 17)
...:     hd2 = HeavyDuty()
...:     hd2.do_work(23, 29)
...:
``````

Now, here is a test case for the `heavy_work` function:

``````In [3]: from unittest.mock import patch, call
...: def test_heavy_work():
...:     expected_calls = [call.do_work(13, 17),call.do_work(23, 29)]
...:
...:     with patch('__main__.HeavyDuty') as MockHeavyDuty:
...:         heavy_work()
...:         MockHeavyDuty.return_value.assert_has_calls(expected_calls)
...:
``````

We are mocking the `HeavyDuty` class with `MockHeavyDuty`. To assert method calls coming from every `HeavyDuty` instance we have to refer to `MockHeavyDuty.return_value.assert_has_calls`, instead of `MockHeavyDuty.assert_has_calls`. In addition, in the list of `expected_calls` we have to specify which method name we are interested in asserting calls for. So our list is made of calls to `call.do_work`, as opposed to simply `call`.

Exercising the test case shows us it is successful:

``````In [4]: print(test_heavy_work())
None
``````

If we modify the `heavy_work` function, the test fails and produces a helpful error message:

``````In [5]: def heavy_work():
...:     hd1 = HeavyDuty()
...:     hd1.do_work(113, 117)  # <- call args are different
...:     hd2 = HeavyDuty()
...:     hd2.do_work(123, 129)  # <- call args are different
...:

In [6]: print(test_heavy_work())
---------------------------------------------------------------------------
(traceback omitted for clarity)

Expected: [call.do_work(13, 17), call.do_work(23, 29)]
Actual: [call.do_work(113, 117), call.do_work(123, 129)]
``````

Asserting multiple calls to a function

To contrast with the above, here is an example that shows how to mock multiple calls to a function:

``````In [7]: def work_function(arg1, arg2):
...:     print("Called with args %r and %r" % (arg1, arg2))

In [8]: from unittest.mock import patch, call
...: def test_work_function():
...:     expected_calls = [call(13, 17), call(23, 29)]
...:     with patch('__main__.work_function') as mock_work_function:
...:         work_function(13, 17)
...:         work_function(23, 29)
...:         mock_work_function.assert_has_calls(expected_calls)
...:

In [9]: print(test_work_function())
None
``````

There are two main differences. The first one is that when mocking a function we setup our expected calls using `call`, instead of using `call.some_method`. The second one is that we call `assert_has_calls` on `mock_work_function`, instead of on `mock_work_function.return_value`.

I faced the same problem.

Just removed the server from configuration and added it back after restarting eclipse by adding it to the server runtime environment.

How can I select random files from a directory in bash?

This is the only script I can get to play nice with bash on MacOS. I combined and edited snippets from the following two links:

ls command: how can I get a recursive full-path listing, one line per file?

http://www.linuxquestions.org/questions/linux-general-1/is-there-a-bash-command-for-picking-a-random-file-678687/

``````#!/bin/bash

# Reads a given directory and picks a random file.

# The directory you want to use. You could use "\$1" instead if you
# wanted to parametrize it.
DIR="/path/to/"
# DIR="\$1"

# Internal Field Separator set to newline, so file names with
# spaces do not break our script.
IFS='
'

if [[ -d "\${DIR}" ]]
then
# Runs ls on the given dir, and dumps the output into a matrix,
# it uses the new lines character as a field delimiter, as explained above.
#  file_matrix=(\$(ls -LR "\${DIR}"))

file_matrix=(\$(ls -R \$DIR | awk '; /:\$/&&f{s=\$0;f=0}; /:\$/&&!f{sub(/:\$/,"");s=\$0;f=1;next}; NF&&f{ print s"/"\$0 }'))
num_files=\${#file_matrix[*]}

# This is the command you want to run on a random file.
# Change "ls -l" by anything you want, it's just an example.
ls -l "\${file_matrix[\$((RANDOM%num_files))]}"
fi

exit 0
``````

What is the difference between display: inline and display: inline-block?

One thing not mentioned in answers is inline element can break among lines while inline-block can't (and obviously block)! So inline elements can be useful to style sentences of text and blocks inside them, but as they can't be padded you can use line-height instead.

_x000D_
_x000D_
``````<div style="width: 350px">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
<div style="display: inline; background: #F00; color: #FFF">_x000D_
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
</div>_x000D_
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
</div>_x000D_
<hr/>_x000D_
<div style="width: 350px">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
<div style="display: inline-block; background: #F00; color: #FFF">_x000D_
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
</div>_x000D_
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
</div>``````
_x000D_
_x000D_
_x000D_

Get the value for a listbox item by index

Suppose you want the value of the first item.

``````ListBox list = new ListBox();
Console.Write(list.Items[0].Value);
``````

python: creating list from string

I know this is old but here's a one liner list comprehension:

``````data = ['word1, 23, 12','word2, 10, 19','word3, 11, 15']

[[int(item) if item.isdigit() else item for item in items.split(', ')] for items in data]
``````

or

``````[int(item) if item.isdigit() else item for items in data for item in items.split(', ')]
``````

How to autosize and right-align GridViewColumn data in WPF?

If your listview is also re-sizing then you can use a behavior pattern to re-size the columns to fit the full ListView width. Almost the same as you using grid.column definitions

``````<ListView HorizontalAlignment="Stretch"
Behaviours:GridViewColumnResize.Enabled="True">
<ListViewItem></ListViewItem>
<ListView.View>
<GridView>
Behaviours:GridViewColumnResize.Width="*" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBox HorizontalAlignment="Stretch" Text="Example1" />
</DataTemplate>
</GridViewColumn.CellTemplate>
``````

See the following link for some examples and link to source code http://lazycowprojects.tumblr.com/post/7063214400/wpf-c-listview-column-width-auto

bash string equality

There's no difference, `==` is a synonym for `=` (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

using CASE in the WHERE clause

``````SELECT *
FROM logs
WHERE pw='correct'
AND CASE
WHEN id<800 THEN success=1
ELSE 1=1
END
AND YEAR(TIMESTAMP)=2011
``````

Date format Mapping to JSON Jackson

Working for me. SpringBoot.

`````` import com.alibaba.fastjson.annotation.JSONField;

@JSONField(format = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
``````

output:

``````{
"createTime": "2019-06-14 13:07:21"
}
``````

jQuery won't parse my JSON from AJAX query

If returning an array works and returning a single object doesn't, you might also try returning your single object as an array containing that single object:

``````[ { title: "One", key: "1" } ]
``````

that way you are returning a consistent data structure, an array of objects, no matter the data payload.

i see that you've tried wrapping your single object in "parenthesis", and suggest this with example because of course JavaScript treats [ .. ] differently than ( .. )

Java Replace Line In Text File

just how to replace strings :) as i do first arg will be filename second target string third one the string to be replaced instead of targe

``````public class ReplaceString{
public static void main(String[] args)throws Exception {
if(args.length<3)System.exit(0);
String targetStr = args[1];
String altStr = args[2];
java.io.File file = new java.io.File(args[0]);
java.util.Scanner scanner = new java.util.Scanner(file);
StringBuilder buffer = new StringBuilder();
while(scanner.hasNext()){
buffer.append(scanner.nextLine().replaceAll(targetStr, altStr));
if(scanner.hasNext())buffer.append("\n");
}
scanner.close();
java.io.PrintWriter printer = new java.io.PrintWriter(file);
printer.print(buffer);
printer.close();
}
}
``````

I had the same issue on OS X 10.9.1 with python 2.7.5. No issues with `WORKON_HOME` for me, but I did have to manually add `source "/usr/local/bin/virtualenvwrapper.sh"` to `~/.bash_profile` (or `~/.bashrc` in unix) after I ran `pip install virtualenvwrapper`

How to return a html page from a restful controller in spring boot?

``````@Controller
public class WebController {
@GetMapping("/")

public String homePage() {
return "index";
}
}
``````

How can I add an element after another element?

First of all, `input` element shouldn't have a closing tag (from http://www.w3.org/TR/html401/interact/forms.html#edef-INPUT : End tag: forbidden ).

Second thing, you need the `after()`, not `append()` function.

Html.DropdownListFor selected value not being set

This is CSS issues. I don't know why @Html.DropDownListFor in Bootstrap 4 doest work. Surely this is class design problem. Anyways the work arround is, if your Dropdown input box has CSS Padding: #px, # px; element then disable it. Hope this will work.

Center a column using Twitter Bootstrap 3

To center the col- we need to use the below code. cols are floater elements besides margin auto. We will also set it to float none,

``````<body class="container">
<div class="col-lg-1 col-md-4 centered">
<img data-src="holder.js/100x100" alt="" />
</div>
</body>
``````

To center the above col-lg-1 with class of centered, we will write:

``````.centered {
float: none;
margin-left: auto;
margin-right: auto;
}
``````

To center the content inside the div, use `text-align:center`,

``````.centered {
text-align: center;
}
``````

If you want to center it only on the desktop and larger screen, not on mobile, then use the following media query.

``````@media (min-width: 768px) {
.centered {
float: none;
margin-left: auto;
margin-right: auto;
}
}
``````

And to center the div only on mobile version, use the below code.

``````@media (max-width: 768px) {
.centered {
float: none;
margin-left: auto;
margin-right: auto;
}
}
``````

How do I set <table> border width with CSS?

Like this:

``````border: 1px solid black;
``````

Why it didn't work? because:

Always declare the border-style (solid in my example) property before the border-width property. An element must have borders before you can change the color.

Sublime Text 2 keyboard shortcut to open file in specified browser (e.g. Chrome)

I'm not really sure this question is approprate here, but you can add a new "Build System" under `Tools -> Build System -> New Build System...`

As with all configuration in Sublime Text its just JSON, so it should be pretty straight forward. The main thing you are going to want to configure is the `"cmd"` key/val. Here is the build config for launching chrome on my mac.

``````{
"cmd": ["open", "-a", "Google Chrome", "\$file"]
}
``````

Save that as `Chrome.sublime-build`, relaunch Sublime Text and you should see a new `Chrome` option in the build list. Select it, and then you should be able to launch Chrome with Cmd+B on a Mac (or whatever hotkey you have configured for build, maybe its F7 or Ctrl+B on a Windows machine)

At least this should give you a push in the right direction.

Edit:

Another thing I end up doing a lot in Sublime Text 2 is if you right click inside a document, one of the items in the context menu is `Copy File Path`, which puts the current file's full path into the clipboard for easy pasting into whatever browser you want.

Sublime Text 3 (linux example) "shell_cmd": "google-chrome '\$file'"

if you have parent element than your parent element must have overflow: hidden; property because if your children content is getting oveflowed from parent border than your border will be visible .otherwise your borderradius is working but it is hide by your children content.

_x000D_
_x000D_
``````.outer {
width: 200px;
height: 120px;
border: 1px solid black;
margin-left: 50px;
overflow: hidden;
}
.inner1 {
width: 100%;
height: 100%;
border: 1px solid black;
}``````
_x000D_
``````<div class="outer">
<div class="inner1">

</div>
</div>``````
_x000D_
_x000D_
_x000D_

How can I check if a string contains a character in C#?

It will be hard to work in C# without knowing how to work with strings and booleans. But anyway:

``````        String str = "ABC";
if (str.Contains('A'))
{
//...
}

if (str.Contains("AB"))
{
//...
}
``````

PostgreSQL: insert from another table

Just supply literal values in the SELECT:

``````INSERT INTO TABLE1 (id, col_1, col_2, col_3)
SELECT id, 'data1', 'data2', 'data3'
FROM TABLE2
WHERE col_a = 'something';
``````

A select list can contain any value expression:

But the expressions in the select list do not have to reference any columns in the table expression of the FROM clause; they can be constant arithmetic expressions, for instance.

And a string literal is certainly a value expression.

What is the difference between `let` and `var` in swift?

A value can be reassigned in case of var

`````` //Variables
var age = 42
println(age) //Will print 42
age = 90
println(age) //Will Print 90
``````

** the newAge constant cannot be reassigned to a new value. Trying to do so will give a compile time error**

``````//Constants
let newAge = 92 //Declaring a constant using let
println(newAge) //Will print 92.
``````

How to pass parameter to function using in addEventListener?

If the `this` value you want is the just the object that you bound the event handler to, then `addEventListener()` already does that for you. When you do this:

``````productLineSelect.addEventListener('change', getSelection, false);
``````

the `getSelection` function will already be called with `this` set to the object that the event handler was bound to. It will also be passed an argument that represents the event object which has all sorts of object information about the event.

``````function getSelection(event) {
// this will be set to the object that the event handler was bound to
// event is all the detailed information about the event
}
``````

If the desired `this` value is some other value than the object you bound the event handler to, you can just do this:

``````var self = this;
getSelection(self)
},false);
``````

By way of explanation:

1. You save away the value of `this` into a local variable in your other event handler.
2. You then create an anonymous function to pass addEventListener.
3. In that anonymous function, you call your actual function and pass it the saved value of `this`.

android pinch zoom

I have created a project for basic pinch-zoom that supports Android 2.1+

Available here

How to align two elements on the same line without changing HTML

By using display: inline-block; And more generally when you have a parent (always there is a parent except for html) use `display: inline-block;` for the inner elements. and to force them to stay in the same line even when the window get shrunk (contracted). Add for the parent the two property:

``````    white-space: nowrap;
overflow-x: auto;
``````

here a more formatted example to make it clear:

``````.parent {
white-space: nowrap;
overflow-x: auto;
}

.children {
display: inline-block;
margin-left: 20px;
}
``````

For this example particularly, you can apply the above as fellow (i'm supposing the parent is body. if not you put the right parent), you can also like change the html and add a parent for them if it's possible.

``````body { /*body may pose problem depend on you context, there is no better then have a specific parent*/
white-space: nowrap;
overflow-x: auto;
}

#element1, #element2{ /*you can like put each one separately, if the margin for the first element is not wanted*/
display: inline-block;
margin-left: 10px;
}
``````

keep in mind that `white-space: nowrap;` and `overlow-x: auto;` is what you need to force them to be in one line. white-space: nowrap; disable wrapping. And overlow-x:auto; to activate scrolling, when the element get over the frame limit.

The error indicates that the DLL is either not a COM DLL or it's corrupt. If it's not a COM DLL and not being used as a COM DLL by an application then there is no need to register it.
From what you say in your question `(the service is not registered)` it seems that we are talking about a service not correctly installed. I will try to reinstall the application.

How to access full source of old commit in BitBucket?

Great answers from a couple of years ago. Now Bitbucket has made it easier.

Pass a reference to DOM object with ng-click

While you do the following, technically speaking:

``````<button ng-click="doSomething(\$event)"></button>
``````
``````// In controller:
\$scope.doSomething = function(\$event) {
//reference to the button that triggered the function:
\$event.target
};
``````

This is probably something you don't want to do as AngularJS philosophy is to focus on model manipulation and let AngularJS do the rendering (based on hints from the declarative UI). Manipulating DOM elements and attributes from a controller is a big no-no in AngularJS world.

How to make child process die after parent exits?

I've passed parent pid using environment to the child, then periodically checked if /proc/\$ppid exists from the child.

How to format LocalDate to string?

``````System.out.println(LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MMMM yyyy")));
``````

The above answer shows it for today

Which data type for latitude and longitude?

Use Point data type to store Longitude and Latitude in a single column:

``````CREATE TABLE table_name (
id integer NOT NULL,
name text NOT NULL,
location point NOT NULL,
created_on timestamp with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT table_name_pkey PRIMARY KEY (id)
)
``````

Create an Indexing on a 'location' column :

``````CREATE INDEX ON table_name USING GIST(location);
``````

GiST index is capable of optimizing “nearest-neighbor” search :

``````SELECT * FROM table_name ORDER BY location <-> point '(-74.013, 40.711)' LIMIT 10;
``````

Note: The point first element is longitude and the second element is latitude.

How to open a URL in a new Tab using JavaScript or jQuery?

This is as simple as this.

``````window.open('_link is here_', 'name');
``````

Function description:

`name` is a name of the window. Following names are supported:

• `_blank` - URL is loaded into a new tab. This is default.
• `_parent` - URL is loaded into the parent frame
• `_self` - URL replaces the current page
• `_top` - URL replaces any framesets that may be loaded

private constructor

One common use is in the singleton pattern where you want only one instance of the class to exist. In that case, you can provide a `static` method which does the instantiation of the object. This way the number of objects instantiated of a particular class can be controlled.

Visual Studio breakpoints not being hit

One of my projects in my solution was set to Release mode. I changed it back to Debug mode, and the breakpoints are hitting now.

How do I use Maven through a proxy?

To set Maven Proxy :

Edit the proxies session in your ~/.m2/settings.xml file. If you cant find the file, create one.

``````<settings>
<proxies>
<proxy>
<id>httpproxy</id>
<active>true</active>
<protocol>http</protocol>
<host>your-proxy-host</host>
<port>your-proxy-port</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
<proxy>
<id>httpsproxy</id>
<active>true</active>
<protocol>https</protocol>
<host>your-proxy-host</host>
<port>your-proxy-port</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>

</proxies>
</settings>
``````

or

Edit the proxies session in your {M2_HOME}/conf/settings.xml

Hope it Helps.. :)

Convert textbox text to integer

You don't need to write a converter, just do this in your handler/codebehind:

``````int i = Convert.ToInt32(txtMyTextBox.Text);
``````

OR

``````int i = int.Parse(txtMyTextBox.Text);
``````

The `Text` property of your textbox is a `String` type, so you have to perform the conversion in the code.

Wordpress 403/404 Errors: You don't have permission to access /wp-admin/themes.php on this server

Try to disable ModSecurity from your cPanel. Log into your cPanel. Find the category "Security". There you can find ModSecurity link.Click on it and disable it for the domain you are facing the 403 error.

Some 403 errors can be solved by this method too. Go to the wordpress dashboard, settings>permalink and just click save.

Hope this helped. :)

How to change the name of a Django app?

In many cases, I believe @allcaps's answer works well.

However, sometimes it is necessary to actually rename an app, e.g. to improve code readability or prevent confusion.

Most of the other answers involve either manual database manipulation or tinkering with existing migrations, which I do not like very much.

As an alternative, I like to create a new app with the desired name, copy everything over, make sure it works, then remove the original app:

1. Start a new app with the desired name, and copy all code from the original app into that. Make sure you fix the namespaced stuff, in the newly copied code, to match the new app name.

2. `makemigrations` and `migrate`

3. Create a data migration that copies the relevant data from the original app's tables into the new app's tables, and `migrate` again.

At this point, everything still works, because the original app and its data are still in place.

1. Now you can refactor all the dependent code, so it only makes use of the new app. See other answers for examples of what to look out for.

2. Once you are certain that everything works, you can remove the original app.

This has the advantage that every step uses the normal Django migration mechanism, without manual database manipulation, and we can track everything in source control. In addition, we keep the original app and its data in place until we are sure everything works.

LINQ Orderby Descending Query

Just to show it in a different format that I prefer to use for some reason: The first way returns your itemList as an System.Linq.IOrderedQueryable

``````using(var context = new ItemEntities())
{
var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
.OrderByDescending(x => x.Delivery.SubmissionDate);
}
``````

That approach is fine, but if you wanted it straight into a List Object:

``````var itemList = context.Items.Where(x => !x.Items && x.DeliverySelection)
.OrderByDescending(x => x.Delivery.SubmissionDate).ToList();
``````

All you have to do is append a .ToList() call to the end of the Query.

Something to note, off the top of my head I can't recall if the !(not) expression is acceptable in the Where() call.

How to see docker image contents

You should not start a container just to see the image contents. For instance, you might want to look for malicious content, not run it. Use "create" instead of "run";

``````docker create --name="tmp_\$\$" image:tag
docker export tmp_\$\$ | tar t
docker rm tmp_\$\$
``````

React onClick and preventDefault() link refresh/redirect?

React events are actually Synthetic Events, not Native Events. As it is written here:

Event delegation: React doesn't actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping. When an event occurs, React knows how to dispatch it using this mapping. When there are no event handlers left in the mapping, React's event handlers are simple no-ops.

Try to use Use `Event.stopImmediatePropagation`:

``````upvote: (e) ->
e.stopPropagation();
e.nativeEvent.stopImmediatePropagation();
``````

Eclipse: Set maximum line length for auto formatting?

Comments have their own line length setting at the bottom of the setting page java->code style->formatter-> Edit... ->comments

How do I add a foreign key to an existing SQLite table?

If you use Db Browser for sqlite ,then it will be easy for you to modify the table. you can add foreign key in existing table without writing a query.

• Open your database in Db browser,
• Just right click on table and click modify,
• At there scroll to foreign key column,
• double click on field which you want to alter,
• Then select table and it's field and click ok.

that's it. You successfully added foreign key in existing table.

Create a .tar.bz2 file Linux

You are not indicating what to include in the archive.

Go one level outside your folder and try:

``````sudo tar -cvjSf folder.tar.bz2 folder
``````

Or from the same folder try

``````sudo tar -cvjSf folder.tar.bz2 *
``````

Cheers!

jQuery: more than one handler for same event

There is a workaround to guarantee that one handler happens after another: attach the second handler to a containing element and let the event bubble up. In the handler attached to the container, you can look at event.target and do something if it's the one you're interested in.

Crude, maybe, but it definitely should work.

How do I format date and time on ssrs report?

If you click on the empty spot on the report away from any table and then look in properties, one of the Misc fields is called Language which allows you to pick which Language you would like to set, which after doing so can play around with this

``````=FormatDateTime(now,x)
``````

Which `x` can be 1, 2, 3, 4, 5

Dynamically add script tag with src that may include document.write

You can use the `document.createElement()` function like this:

``````function addScript( src ) {
var s = document.createElement( 'script' );
s.setAttribute( 'src', src );
document.body.appendChild( s );
}
``````

Sending emails with Javascript

You can add the following to the `<head>` of your HTML file:

``````<script src="https://smtpjs.com/v3/smtp.js"></script>

<script type="text/javascript">
function sendEmail() {
Email.send({
SecureToken: "security token of your smtp",
To: "[email protected]",
From: "[email protected]",
Subject: "Subject...",
Body: document.getElementById('text').value
}).then(
);
}
</script>
``````

and below is the HMTL part:

``````<textarea id="text">write text here...</textarea>
<input type="button" value="Send Email" onclick="sendEmail()">
``````

So the sendEmail() function gets the inputs using:

document.getElementById('id_of_the_element').value

For example, you can add another HTML element such as the subject (with id="subject"):

` <textarea id="subject">write text here...</textarea>`

and get its value in the sendEmail() function:

Subject: document.getElementById('subject').value

And you are done!

Note: If you do not have a SMTP server you can create one for free here. And then encrypt your SMTP credentials here (the SecureToken attribute in sendEmail() corresponds to the encrypted credentials generated there).

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

You should only need to unbind the service in `onDestroy()`. Then, The warning will go.

See here.

As the Activity doc tries to explain, there are three main bind/unbind groupings you will use: onCreate() and onDestroy(), onStart() and onStop(), and onResume() and onPause().

How to download a Nuget package without nuget.exe or Visual Studio extension?

Or guess the URL. They have the following format:

``````https://www.nuget.org/api/v2/package/{packageID}/{packageVersion}
``````

Then simply unzip the .nupkg file and extract the contents you need.

SVN Repository on Google Drive or DropBox

While possible, it's potentially very risky - if you attempt to commit changes to the repository from 2 different locations simultaneously, you'll get a giant mess due to the file conflicts. Get a free private SVN host somewhere, or set up a repository on a server you have access to.

Edit based on a recent experience: If you have files open that are managed by Dropbox and your computer crashes, your files may be truncated to 0 bytes. If this happens to the files which manage your repository, your repository will be corrupted. If you discover this soon enough, you can use Dropbox's "recover old version" feature but you're still taking a risk.

Correct set of dependencies for using Jackson mapper

The package names in Jackson 2.x got changed to `com.fasterxml`1 from `org.codehaus`2. So if you just need ObjectMapper, I think Jackson 1.X can satisfy with your needs.

C - split string into an array of strings

Here is an example of how to use strtok borrowed from MSDN.

And the relevant bits, you need to call it multiple times. The `token` char* is the part you would stuff into an array (you can figure that part out).

``````char string[] = "A string\tof ,,tokens\nand some  more tokens";
char seps[]   = " ,\t\n";
char *token;

int main( void )
{
printf( "Tokens:\n" );
/* Establish string and get the first token: */
token = strtok( string, seps );
while( token != NULL )
{
/* While there are tokens in "string" */
printf( " %s\n", token );
/* Get next token: */
token = strtok( NULL, seps );
}
}
``````

Named parameters in JDBC

JDBC does not support named parameters. Unless you are bound to using plain JDBC (which causes pain, let me tell you that) I would suggest to use Springs Excellent JDBCTemplate which can be used without the whole IoC Container.

NamedParameterJDBCTemplate supports named parameters, you can use them like that:

`````` NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(dataSource);

MapSqlParameterSource paramSource = new MapSqlParameterSource();
jdbcTemplate.queryForRowSet("SELECT * FROM customers WHERE name = :name AND city = :city", paramSource);
``````

How and where to use ::ng-deep?

I would emphasize the importance of limiting the `::ng-deep` to only children of a component by requiring the parent to be an encapsulated css class.

For this to work it's important to use the `::ng-deep` after the parent, not before otherwise it would apply to all the classes with the same name the moment the component is loaded.

Using the `:host` keyword before `::ng-deep` will handle this automatically:

``````:host ::ng-deep .mat-checkbox-layout
``````

Alternatively you can achieve the same behavior by adding a component scoped CSS class before the `::ng-deep` keyword:

``````.my-component ::ng-deep .mat-checkbox-layout {
background-color: aqua;
}
``````

Component template:

``````<h1 class="my-component">
<mat-checkbox ....></mat-checkbox>
</h1>
``````

Resulting (Angular generated) css will then include the uniquely generated name and apply only to its own component instance:

``````.my-component[_ngcontent-c1] .mat-checkbox-layout {
background-color: aqua;
}
``````

How to make a .jar out from an Android Studio project

the way i found was to find the project compiler output (project structure > project). then find the complied folder of the module you wish to turn to a jar, compress it with zip and change the extension of the output from zip to jar.

Window.open and pass parameters by post method

I found a better way to pass parameters to the popup window and even to retrieve parameters from it :

In the main page :

``````var popupwindow;
var sharedObject = {};

function openPopupWindow()
{
// Define the datas you want to pass
sharedObject.var1 =
sharedObject.var2 =
...

// Open the popup window
window.open(URL_OF_POPUP_WINDOW, NAME_OF_POPUP_WINDOW, POPUP_WINDOW_STYLE_PROPERTIES);
if (window.focus) { popupwindow.focus(); }
}

function closePopupWindow()
{
popupwindow.close();

// Retrieve the datas from the popup window
= sharedObject.var1;
= sharedObject.var2;
...
}
``````

In the popup window :

``````var sharedObject = window.opener.sharedObject;

// function you have to to call to close the popup window
function myclose()
{
//Define the parameters you want to pass to the main calling window
sharedObject.var1 =
sharedObject.var2 =
...
window.opener.closePopupWindow();
}
``````

That's it !

And this is very convenient because:

• You have not to set parameters in the URL of the popup window.
• No form to define
• You can use illimited parameters even objects.
• Bi-directionnal : you can pass parameters AND, if you want you, can retreive new parameters.
• Very easy to implement.

Have Fun!

How to trim white spaces of array values in php

``````function trimArray(&\$value)
{
\$value = trim(\$value);
}
\$pmcArray = array('php ','mysql ', ' code ');
array_walk(\$pmcArray, 'trimArray');
``````

by using array_walk function, we can remove space from array elements and elements return the result in same array.

Send Post Request with params using Retrofit

You should create an interface for that like it is working well

``````public interface Service {
@FormUrlEncoded
@Field("City") String city, @Field("ContactNumber") String  contactnumber,
@Field("PatientName") String name,
@Field("Time") String Time, @Field("DonatedBy") String donar);
}
``````

and youcan vist to https://github.com/rajkumu12/GetandPostUsingRatrofit

why does DateTime.ToString("dd/MM/yyyy") give me dd-MM-yyyy?

Dumb question/answer perhaps, but have you tried `dd/MM/yyyy`? Note the capitalization.

`mm` is for minutes with a leading zero. So I doubt that's what you want.

Which .NET Dependency Injection frameworks are worth looking into?

I've used Spring.NET in the past and had great success with it. I never noticed any substantial overhead with it, though the project we used it on was fairly heavy on its own. It only took a little time reading through the documentation to get it set up.

What are the differences between LDAP and Active Directory?

Active Directory is a super-set of the LDAP protocol. Depending on how the organization uses Active Directory, your LDAP search/set queries may or may not work.

Returning http 200 OK with error within response body

HTTP Is the Protocol handling the transmission of data over the internet.

If that transmission breaks for whatever reason the HTTP error codes tell you why it can't be sent to you.

The data being transmitted is not handled by HTTP Error codes. Only the method of transmission.

HTTP can't say 'Ok, this answer is gobbledigook, but here it is'. it just says `200 OK`.

i.e : I've completed my job of getting it to you, the rest is up to you.

I know this has been answered already but I put it in words I can understand. sorry for any repetition.

How to fix Python indentation

Using Vim, it shouldn't be more involved than hitting Esc, and then typing...

``````:%s/\t/    /g
``````

...on the file you want to change. That will convert all tabs to four spaces. If you have inconsistent spacing as well, then that will be more difficult.

How to find integer array size in java

we can find length of array by using array_name.length attribute

int [] i = i.length;

What is the \$\$hashKey added to my JSON.stringify result

Update : From Angular v1.5, track by `\$index` is now the standard syntax instead of using link as it gave me a `ng-repeat` dupes error.

I ran into this for a nested `ng-repeat` and the below worked.

``````<tbody>
<tr ng-repeat="row in data track by \$index">
<td ng-repeat="field in headers track by \$index">{{row[field.caption] }}</td>
</tr>
``````

How to detect escape key press with pure JS or jQuery?

check for `keyCode` && `which` & `keyup` || `keydown`

``````\$(document).keydown(function(e){
var code = e.keyCode || e.which;
});
``````

Could not find a part of the path ... bin\roslyn\csc.exe

Upgrading `Microsoft.CodeDom.Providers.DotNetCompilerPlatform` from 1.0.0 to 1.0.1 fixed this for me.

How do I load an HTML page in a <div> using JavaScript?

``````\$("button").click(function() {
});
``````

or

``````document.getElementById("target_div").innerHTML='<object type="text/html" data="requesting_page_url.html"></object>';
``````

get everything between <tag> and </tag> with php

this function worked for me

``````<?php

function everything_in_tags(\$string, \$tagname)
{
\$pattern = "#<\s*?\$tagname\b[^>]*>(.*?)</\$tagname\b[^>]*>#s";
preg_match(\$pattern, \$string, \$matches);
return \$matches[1];
}

?>
``````

How to describe "object" arguments in jsdoc?

For `@return` tag use `{{field1: Number, field2: String}}`, see: http://wiki.servoy.com/display/public/DOCS/Annotating+JavaScript+using+JSDoc

MySQL: Convert INT to DATETIME

``````SELECT  FROM_UNIXTIME(mycolumn)
FROM    mytable
``````

Android SDK manager won't open

I tried all the most popular solutions before and no one worked for me, until I realised that the Android SDK folder must not have any spaces, so I changed it from "C:\Android SDK" to "C:\Android_SDK". As simple as that.

Since Swift 4.2

There is a new set of APIs:

``````let randomIntFrom0To10 = Int.random(in: 0 ..< 10)
let randomDouble = Double.random(in: 1 ... 10)
``````
• All numeric types now have the `random(in:)` method that takes `range`.

• It returns a number uniformly distributed in that range.

TL;DR

Well, what is wrong with the "good" old way?

1. You have to use imported C APIs (They are different between platforms).

2. And moreover...

What if I told you that the random is not that random?

If you use `arc4random()` (to calculate the remainder) like `arc4random() % aNumber`, the result is not uniformly distributed between the `0` and `aNumber`. There is a problem called the Modulo bias.

Modulo bias

Normally, the function generates a random number between `0` and MAX (depends on the type etc.). To make a quick, easy example, let's say the max number is `7` and you care about a random number in the range `0 ..< 2` (or the interval [0, 3) if you prefer that).

The probabilities for individual numbers are:

• 0: 3/8 = 37.5%
• 1: 3/8 = 37.5%
• 2: 2/8 = 25%

In other words, you are more likely to end up with 0 or 1 than 2. Of course, bare in mind that this is extremely simplified and the MAX number is much higher, making it more "fair".

This problem is addressed by SE-0202 - Random unification in Swift 4.2

No line-break after a hyphen

IE8/9 render the non-breaking hyphen mentioned in CanSpice's answer longer than a typical hyphen. It is the length of an en-dash instead of a typical hyphen. This display difference was a deal breaker for me.

As I could not use the CSS answer specified by Deb I instead opted to use no break tags.

``````<nobr>e-mail</nobr>
``````

In addition I found a specific scenario that caused IE8/9 to break on a hyphen.

• A string contains words separated by non-breaking spaces - `&nbsp;`
• Width is limited
• Contains a dash

IE renders it like this.

The following code reproduces the problem pictured above. I had to use a meta tag to force rendering to IE9 as IE10 has fixed the issue. No fiddle because it does not support meta tags.

``````<!DOCTYPE html>
<html lang="en">
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<meta charset="utf-8"/>
<style>
div { width: 300px; border: 1px solid gray; }
</style>
<body>
<div>
<p>If&nbsp;there&nbsp;is&nbsp;a&nbsp;-&nbsp;and&nbsp;words&nbsp;are&nbsp;separated&nbsp;by&nbsp;the&nbsp;whitespace&nbsp;code&nbsp;&amp;nbsp;&nbsp;then&nbsp;IE&nbsp;will&nbsp;wrap&nbsp;on&nbsp;the&nbsp;dash.</p>
</div>
</body>
</html>
``````

Java executors: how to be notified, without blocking, when a task completes?

Define a callback interface to receive whatever parameters you want to pass along in the completion notification. Then invoke it at the end of the task.

You could even write a general wrapper for Runnable tasks, and submit these to `ExecutorService`. Or, see below for a mechanism built into Java 8.

``````class CallbackTask implements Runnable {

private final Callback callback;

this.callback = callback;
}

public void run() {
callback.complete();
}

}
``````

With `CompletableFuture`, Java 8 included a more elaborate means to compose pipelines where processes can be completed asynchronously and conditionally. Here's a contrived but complete example of notification.

``````import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

public static void main(String... argv) throws Exception {
ExampleService svc = new ExampleService();
CompletableFuture<String> f = CompletableFuture.supplyAsync(svc::work);
f.thenAccept(listener::notify);
System.out.println("Exiting main()");
}

void notify(String msg) {
}

}

class ExampleService {

String work() {
sleep(7000, TimeUnit.MILLISECONDS); /* Pretend to be busy... */
char[] str = new char[5];
for (int idx = 0; idx < str.length; ++idx)
str[idx] = (char) ('A' + current.nextInt(26));
String msg = new String(str);
System.out.println("Generated message: " + msg);
return msg;
}

public static void sleep(long average, TimeUnit unit) {
long timeout = Math.min(exponential(average), Math.multiplyExact(10, average));
System.out.printf("%s sleeping %d %s...%n", name, timeout, unit);
try {
unit.sleep(timeout);
System.out.println(name + " awoke.");
} catch (InterruptedException abort) {
System.out.println(name + " interrupted.");
}
}

public static long exponential(long avg) {
return (long) (avg * -Math.log(1 - ThreadLocalRandom.current().nextDouble()));
}

}
``````

postgres, ubuntu how to restart service on startup? get stuck on clustering after instance reboot

I guess it would be best to fix the database startup script itself. But as a work around, you can add that line to `/etc/rc.local`, which is executed about last in init phase.

A completely free agile software process tool

Try http://www.icescrum.org . It is free to use. And it has lot of cool features. Perfect for scrum teams.

Difference between the Apache HTTP Server and Apache Tomcat?

Well, Apache is HTTP webserver, where as Tomcat is also webserver for Servlets and JSP. Moreover Apache is preferred over Apache Tomcat in real time

Sort hash by key, return hash in Ruby

I had the same problem ( I had to sort my equipments by their name ) and i solved like this:

``````<% @equipments.sort.each do |name, quantity| %>
...
<% end %>
``````

@equipments is a hash that I build on my model and return on my controller. If you call .sort it will sort the hash based on it's key value.

Datatable select with multiple conditions

If you really don't want to run into lots of annoying errors (datediff and such can't be evaluated in `DataTable.Select` among other things and even if you do as suggested use `DataTable.AsEnumerable` you will have trouble evaluating DateTime fields) do the following:

1) Model Your Data (create a class with DataTable columns)

Example

``````public class Person
{
public string PersonId { get; set; }
public DateTime DateBorn { get; set; }
}
``````

``````public static class Extensions
{
/// <summary>
/// Converts datatable to list<T> dynamically
/// </summary>
/// <typeparam name="T">Class name</typeparam>
/// <param name="dataTable">data table to convert</param>
/// <returns>List<T></returns>
public static List<T> ToList<T>(this DataTable dataTable) where T : new()
{
var dataList = new List<T>();

//Define what attributes to be read from the class
const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;

var objFieldNames = typeof(T).GetProperties(flags).Cast<PropertyInfo>().
Select(item => new
{
Name = item.Name,
Type = Nullable.GetUnderlyingType(item.PropertyType) ?? item.PropertyType
}).ToList();

//Read Datatable column names and types
var dtlFieldNames = dataTable.Columns.Cast<DataColumn>().
Select(item => new {
Name = item.ColumnName,
Type = item.DataType
}).ToList();

foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
{
var classObj = new T();

foreach (var dtField in dtlFieldNames)
{
PropertyInfo propertyInfos = classObj.GetType().GetProperty(dtField.Name);

var field = objFieldNames.Find(x => x.Name == dtField.Name);

if (field != null)
{

if (propertyInfos.PropertyType == typeof(DateTime))
{
propertyInfos.SetValue
(classObj, ConvertToDateTime(dataRow[dtField.Name]), null);
}
else if (propertyInfos.PropertyType == typeof(int))
{
propertyInfos.SetValue
(classObj, ConvertToInt(dataRow[dtField.Name]), null);
}
else if (propertyInfos.PropertyType == typeof(long))
{
propertyInfos.SetValue
(classObj, ConvertToLong(dataRow[dtField.Name]), null);
}
else if (propertyInfos.PropertyType == typeof(decimal))
{
propertyInfos.SetValue
(classObj, ConvertToDecimal(dataRow[dtField.Name]), null);
}
else if (propertyInfos.PropertyType == typeof(String))
{
if (dataRow[dtField.Name].GetType() == typeof(DateTime))
{
propertyInfos.SetValue
(classObj, ConvertToDateString(dataRow[dtField.Name]), null);
}
else
{
propertyInfos.SetValue
(classObj, ConvertToString(dataRow[dtField.Name]), null);
}
}
}
}
}
return dataList;
}

private static string ConvertToDateString(object date)
{
if (date == null)
return string.Empty;

return HelperFunctions.ConvertDate(Convert.ToDateTime(date));
}

private static string ConvertToString(object value)
{
return Convert.ToString(HelperFunctions.ReturnEmptyIfNull(value));
}

private static int ConvertToInt(object value)
{
return Convert.ToInt32(HelperFunctions.ReturnZeroIfNull(value));
}

private static long ConvertToLong(object value)
{
return Convert.ToInt64(HelperFunctions.ReturnZeroIfNull(value));
}

private static decimal ConvertToDecimal(object value)
{
return Convert.ToDecimal(HelperFunctions.ReturnZeroIfNull(value));
}

private static DateTime ConvertToDateTime(object date)
{
return Convert.ToDateTime(HelperFunctions.ReturnDateTimeMinIfNull(date));
}

}
public static class HelperFunctions
{

public static object ReturnEmptyIfNull(this object value)
{
if (value == DBNull.Value)
return string.Empty;
if (value == null)
return string.Empty;
return value;
}
public static object ReturnZeroIfNull(this object value)
{
if (value == DBNull.Value)
return 0;
if (value == null)
return 0;
return value;
}
public static object ReturnDateTimeMinIfNull(this object value)
{
if (value == DBNull.Value)
return DateTime.MinValue;
if (value == null)
return DateTime.MinValue;
return value;
}
/// <summary>
/// Convert DateTime to string
/// </summary>
/// <param name="datetTime"></param>
/// <param name="excludeHoursAndMinutes">if true it will execlude time from datetime string. Default is false</param>
/// <returns></returns>
public static string ConvertDate(this DateTime datetTime, bool excludeHoursAndMinutes = false)
{
if (datetTime != DateTime.MinValue)
{
if (excludeHoursAndMinutes)
return datetTime.ToString("yyyy-MM-dd");
return datetTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
}
return null;
}
}
``````

3) Easily convert your `DataTable` (dt) to a List of objects with following code:

``````List<Person> persons = Extensions.ToList<Person>(dt);
``````

4) have fun using Linq without the annoying `row.Field<type>` bit you have to use when using `AsEnumerable`

Example

``````var personsBornOn1980 = persons.Where(x=>x.DateBorn.Year == 1980);
``````

What is .Net Framework 4 extended?

Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.

To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)

The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:

``````* ASP.NET
* Advanced Windows Communication Foundation (WCF) functionality
* .NET Framework Data Provider for Oracle
* MSBuild for compiling
``````

Return only string message from Spring MVC 3 Controller

With Spring 4, if your Controller is annotated with `@RestController` instead of `@Controller`, you don't need the `@ResponseBody` annotation.

The code would be

``````@RestController
public class FooController {

@RequestMapping(value="/controller", method=GET)
public String foo() {
return "Response!";
}

}
``````

You can find the Javadoc for `@RestController` here

How to iterate over a column vector in Matlab?

with many functions in matlab, you don't need to iterate at all.

for example, to multiply by it's position in the list:

``````m = [1:numel(list)]';
elm = list.*m;
``````

vectorized algorithms in matlab are in general much faster.

Why don’t my SVG images scale using the CSS "width" property?

You can also use the `transform: scale("")` option.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

Open Your .edmx file in XML editor and then remove tag from Tag and also change store:Schema="dbo" to Schema="dbo" and rebuild the solution now error will resolve and you will be able to save the data.

How to assign from a function which returns more than one value?

To obtain multiple outputs from a function and keep them in the desired format you can save the outputs to your hard disk (in the working directory) from within the function and then load them from outside the function:

``````myfun <- function(x) {
df1 <- ...
df2 <- ...
save(df1, file = "myfile1")
save(df2, file = "myfile2")
}
``````

How do I clear the dropdownlist values on button click event using jQuery?

``````\$('#dropdownid').empty();
``````

That will remove all `<option>` elements underneath the dropdown element.

If you want to unselect selected items, go with the code from Russ.

Android: How to get a custom View's height and width?

Don't try to get them inside its constructor. Try Call them in `onDraw()` method.

" app-release.apk" how to change this default generated apk name

My solution may also be of help to someone.

Tested and Works on IntelliJ 2017.3.2 with Gradle 4.4

Scenario:

I have 2 flavours in my application, and so I wanted each release to be named appropriately according to each flavor.

The code below will be placed into your module gradle build file found in:

`{app-root}/app/build.gradle`

Gradle code to be added to `android{ }` block:

``````android {
// ...

defaultConfig {
versionCode 10
versionName "1.2.3_build5"
}

buildTypes {
// ...

release {
// ...

applicationVariants.all {
variant.outputs.each { output ->
output.outputFile = new File(output.outputFile.parent, output.outputFile.name.replace(output.outputFile.name, variant.flavorName + "-" + defaultConfig.versionName + "_v" + defaultConfig.versionCode + ".apk"))
}
}

}
}

productFlavors {
myspicyflavor {
applicationIdSuffix ".MySpicyFlavor"
signingConfig signingConfigs.debug
}

mystandardflavor {
applicationIdSuffix ".MyStandardFlavor"
signingConfig signingConfigs.config
}
}
}
``````

The above provides the following APKs found in `{app-root}/app/`:

``````myspicyflavor-release-1.2.3_build5_v10.apk
mystandardflavor-release-1.2.3_build5_v10.apk
``````

Hope it can be of use to someone.

Is it better to use NOT or <> when comparing values?

Because "not ... =" is two operations and "<>" is only one, it is faster to use "<>".

Here is a quick experiment to prove it:

``````StartTime = Timer
For x = 1 to 100000000
If 4 <> 3 Then
End if
Next
WScript.echo Timer-StartTime

StartTime = Timer
For x = 1 to 100000000
If Not (4 = 3) Then
End if
Next
WScript.echo Timer-StartTime
``````

The results I get on my machine:

``````4.783203
5.552734
``````

Error: Cannot find module 'webpack'

For Visual Studio users: Right click on the npm folder and "Restore Packages".

How to get the height of a body element

\$(document).height() seems to do the trick and gives the total height including the area which is only visible through scrolling.

Storing files in SQL Server

There's a really good paper by Microsoft Research called To Blob or Not To Blob.

Their conclusion after a large number of performance tests and analysis is this:

• if your pictures or document are typically below 256K in size, storing them in a database VARBINARY column is more efficient

• if your pictures or document are typically over 1 MB in size, storing them in the filesystem is more efficient (and with SQL Server 2008's FILESTREAM attribute, they're still under transactional control and part of the database)

• in between those two, it's a bit of a toss-up depending on your use

If you decide to put your pictures into a SQL Server table, I would strongly recommend using a separate table for storing those pictures - do not store the employee photo in the employee table - keep them in a separate table. That way, the Employee table can stay lean and mean and very efficient, assuming you don't always need to select the employee photo, too, as part of your queries.

For filegroups, check out Files and Filegroup Architecture for an intro. Basically, you would either create your database with a separate filegroup for large data structures right from the beginning, or add an additional filegroup later. Let's call it "LARGE_DATA".

Now, whenever you have a new table to create which needs to store VARCHAR(MAX) or VARBINARY(MAX) columns, you can specify this file group for the large data:

`````` CREATE TABLE dbo.YourTable
(....... define the fields here ......)
ON Data                   -- the basic "Data" filegroup for the regular data
TEXTIMAGE_ON LARGE_DATA   -- the filegroup for large chunks of data
``````

Check out the MSDN intro on filegroups, and play around with it!

Socket.io + Node.js Cross-Origin Request Blocked

Sometimes this issue is faced when the node server stoped. So, check if your node server working ok.

Then you can use io.set('origins', 'http://yourdomain.com:PORT_NUMBER');

How does Python return multiple values from a function?

Python functions always return a unique value. The comma operator is the constructor of tuples so `self.first_name, self.last_name` evaluates to a tuple and that tuple is the actual value the function is returning.

Parsing Json rest api response in C#

1. Create classes that match your data,
2. then use JSON.NET to convert the JSON data to regular C# objects.

Step 1: a great tool - http://json2csharp.com/ - the results generated by it are below

Step 2: `JToken.Parse(...).ToObject<RootObject>()`.

``````public class Meta
{
public int code { get; set; }
public string status { get; set; }
public string method_name { get; set; }
}

public class Photos
{
public int total_count { get; set; }
}

public class Storage
{
public int used { get; set; }
}

public class Stats
{
public Photos photos { get; set; }
public Storage storage { get; set; }
}

public class From
{
public string id { get; set; }
public string first_name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public List<object> external_accounts { get; set; }
public string email { get; set; }
public string confirmed_at { get; set; }
public string username { get; set; }
public string admin { get; set; }
public Stats stats { get; set; }
}

public class ParticipateUser
{
public string id { get; set; }
public string first_name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public List<object> external_accounts { get; set; }
public string email { get; set; }
public string confirmed_at { get; set; }
public string username { get; set; }
public string admin { get; set; }
public Stats stats { get; set; }
}

public class ChatGroup
{
public string id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string message { get; set; }
public List<ParticipateUser> participate_users { get; set; }
}

public class Chat
{
public string id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string message { get; set; }
public From from { get; set; }
public ChatGroup chat_group { get; set; }
}

public class Response
{
public List<Chat> chats { get; set; }
}

public class RootObject
{
public Meta meta { get; set; }
public Response response { get; set; }
}
``````

\$http get parameters does not work

The 2nd parameter in the `get` call is a config object. You want something like this:

``````\$http
.get('accept.php', {
params: {
category_id: category
}
})
.success(function (data,status) {
\$scope.info_show = data
});
``````

See the Arguments section of http://docs.angularjs.org/api/ng.\$http for more detail

How do I return an int from EditText? (Android)

Set the digits attribute to true, which will cause it to only allow number inputs.

Then do `Integer.valueOf(editText.getText())` to get an int value out.

Detect page change on DataTable

Try using delegate instead of live as here:

``````\$('#link-wrapper').delegate('a', 'click', function() {
// do something ..
}
``````

jQuery UI Slider (setting programmatically)

For me this perfectly triggers slide event on UI Slider :

``````hs=\$('#height_slider').slider();
hs.slider('option', 'value',h);
hs.slider('option','slide')
.call(hs,null,{ handle: \$('.ui-slider-handle', hs), value: h });
``````

Don't forget to set value by `hs.slider('option', 'value',h);` before the trigger. Else slider handler will not be in sync with value.

One thing to note here is that `h` is index/position (not value) in case you are using html `select`.

Entity Framework - Code First - Can't Store List<String>

Of course Pawel has given the right answer. But I found in this post that since EF 6+ it is possible to save private properties. So I would prefer this code, because you are not able to save the Strings in a wrong way.

``````public class Test
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

[Column]
[Required]
private String StringsAsStrings { get; set; }

public List<String> Strings
{
get { return StringsAsStrings.Split(',').ToList(); }
set
{
StringsAsStrings = String.Join(",", value);
}
}
public Test()
{
Strings = new List<string>
{
"test",
"test2",
"test3",
"test4"
};
}
}
``````

open notepad++, then drag and drop the folder you want to open as tree view.

OR

File ->open folder as workspace , select the file you want.

Change limit for "Mysql Row size too large"

The maximum row size for an InnoDB table, which applies to data stored locally within a database page, is slightly less than half a page for 4KB, 8KB, 16KB, and 32KB

For 16kb pages (default), we can calculate:

``````Slightly less than half a page 8126 / Number of bytes to threshold for overflow 767 = 10.59 fields of 767 bytes maximum
``````

Basically, you could max out a row with:

• 11 varchar fields > 767 characters (latin1 = 1 byte per char) or
• 11 varchar fields > 255 characters (utf-8 on mysql = 3 bytes per char).

Remember, it will only overflow to an overflow page if the field is > 767 bytes. If there are too many fields of 767 bytes, it will bust (passing beyond max row_size). Not usual with latin1 but very possible with utf-8 if the developers aren’t careful.

For this case, I think you could possibly bump the innodb_page_size to 32kb.

in my.cnf:

``````innodb_page_size=32K
``````

References:

Is JavaScript's "new" keyword considered harmful?

Javascript being dynamic language there a zillion ways to mess up where another language would stop you.

Avoiding a fundamental language feature such as `new` on the basis that you might mess up is a bit like removing your shiny new shoes before walking through a minefield just in case you might get your shoes muddy.

I use a convention where function names begin with a lower case letter and 'functions' that are actually class definitions begin with a upper case letter. The result is a really quite compelling visual clue that the 'syntax' is wrong:-

``````var o = MyClass();  // this is clearly wrong.
``````

On top of this good naming habits help. After all functions do things and therefore there should be a verb in its name whereas classes represent objects and are nouns and adjectives with no verb.

``````var o = chair() // Executing chair is daft.
var o = createChair() // makes sense.
``````

Its interesting how SO's syntax colouring has interpretted the code above.

What is the HTML5 equivalent to the align attribute in table cells?

You can use inline css :
`<td style = "text-align: center;">`

Why is printing "B" dramatically slower than printing "#"?

I performed tests on Eclipse vs Netbeans 8.0.2, both with Java version 1.8; I used `System.nanoTime()` for measurements.

Eclipse:

I got the same time on both cases - around 1.564 seconds.

Netbeans:

• Using "#": 1.536 seconds
• Using "B": 44.164 seconds

So, it looks like Netbeans has bad performance on print to console.

After more research I realized that the problem is line-wrapping of the max buffer of Netbeans (it's not restricted to `System.out.println` command), demonstrated by this code:

``````for (int i = 0; i < 1000; i++) {
long t1 = System.nanoTime();
System.out.print("BBB......BBB"); \\<-contain 1000 "B"
long t2 = System.nanoTime();
System.out.println(t2-t1);
System.out.println("");
}
``````

The time results are less then 1 millisecond every iteration except every fifth iteration, when the time result is around 225 millisecond. Something like (in nanoseconds):

``````BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
BBB...31744
BBB...31744
BBB...31744
BBB...31744
BBB...226365807
.
.
.
``````

And so on..

Summary:

1. Eclipse works perfectly with "B"
2. Netbeans has a line-wrapping problem that can be solved (because the problem does not occur in eclipse)(without adding space after B ("B ")).

How can I set the opacity or transparency of a Panel in WinForms?

Try this:

``````panel1.BackColor = Color.FromArgb(100, 88, 44, 55);
``````

change alpha(A) to get desired opacity.

How can I ssh directly to a particular directory?

I've created a tool to SSH and CD into a server consecutively – aptly named sshcd. For the example you've given, you'd simply use:

``````sshcd somehost:/some/directory/somewhere/named/Foo
``````

Let me know if you have any questions or problems!

How do I convert from int to String?

Normal ways would be `Integer.toString(i)` or `String.valueOf(i)`.

The concatenation will work, but it is unconventional and could be a bad smell as it suggests the author doesn't know about the two methods above (what else might they not know?).

Java has special support for the + operator when used with strings (see the documentation) which translates the code you posted into:

``````StringBuilder sb = new StringBuilder();
sb.append("");
sb.append(i);
String strI = sb.toString();
``````

at compile-time. It's slightly less efficient (`sb.append()` ends up calling `Integer.getChars()`, which is what `Integer.toString()` would've done anyway), but it works.

To answer Grodriguez's comment: ** No, the compiler doesn't optimise out the empty string in this case - look:

``````simon@lucifer:~\$ cat TestClass.java
public class TestClass {
public static void main(String[] args) {
int i = 5;
String strI = "" + i;
}
}
simon@lucifer:~\$ javac TestClass.java && javap -c TestClass
Compiled from "TestClass.java"
public class TestClass extends java.lang.Object{
public TestClass();
Code:
1:    invokespecial    #1; //Method java/lang/Object."<init>":()V
4:    return

public static void main(java.lang.String[]);
Code:
0:    iconst_5
1:    istore_1
``````

Initialise the StringBuilder:

``````   2:    new    #2; //class java/lang/StringBuilder
5:    dup
6:    invokespecial    #3; //Method java/lang/StringBuilder."<init>":()V
``````

Append the empty string:

``````   9:    ldc    #4; //String
11:    invokevirtual    #5; //Method java/lang/StringBuilder.append:
(Ljava/lang/String;)Ljava/lang/StringBuilder;
``````

Append the integer:

``````   14:    iload_1
15:    invokevirtual    #6; //Method java/lang/StringBuilder.append:
(I)Ljava/lang/StringBuilder;
``````

Extract the final string:

``````   18:    invokevirtual    #7; //Method java/lang/StringBuilder.toString:
()Ljava/lang/String;
21:    astore_2
22:    return
}
``````

There's a proposal and ongoing work to change this behaviour, targetted for JDK 9.

Fetch API request timeout?

there's no timeout support in the fetch API yet. But it could be achieved by wrapping it in a promise.

for eg.

``````  function fetchWrapper(url, options, timeout) {
return new Promise((resolve, reject) => {
fetch(url, options).then(resolve, reject);

if (timeout) {
const e = new Error("Connection timed out");
setTimeout(reject, timeout, e);
}
});
}
``````

Why doesn't Dijkstra's algorithm work for negative weight edges?

You can use dijkstra's algorithm with negative edges not including negative cycle, but you must allow a vertex can be visited multiple times and that version will lose it's fast time complexity.

In that case practically I've seen it's better to use SPFA algorithm which have normal queue and can handle negative edges.

How to pass credentials to the Send-MailMessage command for sending emails

So..it was SSL problem. Whatever I was doing was absolutely correct. Only that I was not using the ssl option. So I added "-Usessl true" to my original command and it worked.

How do I add a newline to command output in PowerShell?

I think you had the correct idea with your last example. You only got an error because you were trying to put quotes inside an already quoted string. This will fix it:

``````gci -path hklm:\software\microsoft\windows\currentversion\uninstall | ForEach-Object -Process { write-output (\$_.GetValue("DisplayName") + "`n") }
``````

Edit: Keith's \$() operator actually creates a better syntax (I always forget about this one). You can also escape quotes inside quotes as so:

``````gci -path hklm:\software\microsoft\windows\currentversion\uninstall | ForEach-Object -Process { write-output "\$(\$_.GetValue(`"DisplayName`"))`n" }
``````

ipad safari: disable scrolling, and bounce effect?

Try this JS solution that toggles `webkitOverflowScrolling` style. The trick here is that this style is off, mobile Safari goes to ordinary scrolling and prevents over-bounce — alas, it is not able to cancel ongoing drag. This complex solution also tracks `onscroll` as bounce over the top makes `scrollTop` negative that may be tracked. This solution was tested on iOS 12.1.1 and has single drawback: while accelerating the scroll single over-bounce still happens as resetting the style may not cancel it immediately.

``````function preventScrollVerticalBounceEffect(container) {
setTouchScroll(true) //!: enable before the first scroll attempt

container.addEventListener("touchmove", onTouch, { passive: false })

function isTouchScroll() {
return !!container.style.webkitOverflowScrolling
}

let prevScrollTop = 0, prevTouchY, opid = 0

function setTouchScroll(on) {
container.style.webkitOverflowScrolling = on ? "touch" : null

//Hint: auto-enabling after a small pause makes the start
// smoothly accelerated as required. After the pause the
// scroll position is settled, and there is no delta to
// make over-bounce by dragging the finger. But still,
// accelerated content makes short single over-bounce
// as acceleration may not be off instantly.

const xopid = ++opid
!on && setTimeout(() => (xopid === opid) && setTouchScroll(true), 250)

if(!on && container.scrollTop < 16)
container.scrollTop = 0
prevScrollTop = container.scrollTop
}

function isBounceOverTop() {
const dY = container.scrollTop - prevScrollTop
return dY < 0 && container.scrollTop < 16
}

function isBounceOverBottom(touchY) {
const dY = touchY - prevTouchY

//Hint: trying to bounce over the bottom, the finger moves
// up the screen, thus Y becomes smaller. We prevent this.

return dY < 0 && container.scrollHeight - 16 <=
container.scrollTop + container.offsetHeight
}

function onTouchStart(e) {
prevTouchY = e.touches[0].pageY
}

function onTouch(e) {
const touchY = e.touches[0].pageY

if(isBounceOverBottom(touchY)) {
if(isTouchScroll())
setTouchScroll(false)
e.preventDefault()
}

prevTouchY = touchY
}

function onTouchEnd() {
prevTouchY = undefined
}

function onScroll() {
if(isTouchScroll() && isBounceOverTop()) {
setTouchScroll(false)
}
}
}
``````

Split array into chunks of N length

Maybe this code helps:

_x000D_
_x000D_
``````var chunk_size = 10;_x000D_
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];_x000D_
var groups = arr.map( function(e,i){ _x000D_
return i%chunk_size===0 ? arr.slice(i,i+chunk_size) : null; _x000D_
}).filter(function(e){ return e; });_x000D_
console.log({arr, groups})``````
_x000D_
_x000D_
_x000D_

How to generate an MD5 file hash in JavaScript?

You can use a lightweight library pure-md5. Just a 4.7kb.

_x000D_
_x000D_
``````\$("#file-dialog").change(function() {_x000D_
handleFiles(this.files);_x000D_
});_x000D_
_x000D_
function handleFiles(files) {_x000D_
for (var index = 0; index < files.length; index++) {_x000D_
var file = files[index];_x000D_
\$('body').append(`_x000D_
<div style="margin-top: 2rem;">_x000D_
<span>\${file.name}: </span>_x000D_
<span>\${(md5(e.target.result))}</span>_x000D_
</div>_x000D_
`);_x000D_
}_x000D_
_x000D_
}_x000D_
_x000D_
}``````
_x000D_
``````body {_x000D_
font-family: sans-serif;_x000D_
}``````
_x000D_
``````<script src="https://unpkg.com/[email protected]/lib/index.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="file" id="file-dialog" multiple="true" accept="image/*">``````
_x000D_
_x000D_
_x000D_

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

Well, for a link, there must be a link tag around. what you can also do is that make a css class for the button and assign that class to the link tag. like,

_x000D_
_x000D_
``````#btn {_x000D_
background: url(https://image.flaticon.com/icons/png/128/149/149668.png) no-repeat 0 0;_x000D_
display: block;_x000D_
width: 128px;_x000D_
height: 128px;_x000D_
border: none;_x000D_
outline: none;_x000D_
}``````
_x000D_
``<a href="btnlink.html" id="btn"></a>``
_x000D_
_x000D_
_x000D_

Javascript form validation with password confirming

``````<form  id="regform" action="insert.php" method="post">
``````

``````<script>
function myFunction() {
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
if (pass1 != pass2) {
document.getElementById("pass1").style.borderColor = "#E34234";
document.getElementById("pass2").style.borderColor = "#E34234";
}
else {
document.getElementById("regForm").submit();
}
}
</script>
``````

How to select distinct query using symfony2 doctrine query builder?

This works:

``````\$category = \$catrep->createQueryBuilder('cc')
->select('cc.categoryid')
->where('cc.contenttype = :type')
->setParameter('type', 'blogarticle')
->distinct()
->getQuery();

\$categories = \$category->getResult();
``````

Edit for Symfony 3 & 4.

You should use `->groupBy('cc.categoryid')` instead of `->distinct()`

finding multiples of a number in Python

Based on mathematical concepts, I understand that:

• all natural numbers that, divided by `n`, having `0` as remainder, are all multiples of `n`

Therefore, the following calculation also applies as a solution (multiples between 1 and 100):

``````>>> multiples_5 = [n for n in range(1, 101) if n % 5 == 0]
>>> multiples_5
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]
``````

Drag and drop elements from list into separate blocks

Dragging an object and placing in a different location is part of the standard of HTML5. All the objects can be draggable. But the Specifications of below web browser should be followed. API Chrome Internet Explorer Firefox Safari Opera Version 4.0 9.0 3.5 6.0 12.0

You can find example from below: https://www.w3schools.com/html/tryit.asp?filename=tryhtml5_draganddrop2

How to create a directory in Java?

``````public class Test1 {
public static void main(String[] args)
{
String path = System.getProperty("user.home");
File dir=new File(path+"/new folder");
if(dir.exists()){
System.out.println("A folder with name 'new folder' is already exist in the path "+path);
}else{
dir.mkdir();
}

}
}
``````

Is there a combination of "LIKE" and "IN" in SQL?

u can even try this

Function

``````CREATE  FUNCTION [dbo].[fn_Split](@text varchar(8000), @delimiter varchar(20))
RETURNS @Strings TABLE
(
position int IDENTITY PRIMARY KEY,
value varchar(8000)
)
AS
BEGIN

DECLARE @index int
SET @index = -1

WHILE (LEN(@text) > 0)
BEGIN
SET @index = CHARINDEX(@delimiter , @text)
IF (@index = 0) AND (LEN(@text) > 0)
BEGIN
INSERT INTO @Strings VALUES (@text)
BREAK
END
IF (@index > 1)
BEGIN
INSERT INTO @Strings VALUES (LEFT(@text, @index - 1))
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
ELSE
SET @text = RIGHT(@text, (LEN(@text) - @index))
END
RETURN
END
``````

Query

``````select * from my_table inner join (select value from fn_split('ABC,MOP',','))
as split_table on my_table.column_name like '%'+split_table.value+'%';
``````

How can I use an ES6 import in Node.js?

Node.js has included experimental support for ES6 support. Read more about here: https://nodejs.org/docs/latest-v13.x/api/esm.html#esm_enabling.

TLDR;

Node.js >= v13

It's very simple in Node.js 13 and above. You need to either:

• Save the file with `.mjs` extension, or
• Add `{ "type": "module" }` in the nearest `package.json`.

You only need to do one of the above to be able to use ECMAScript modules.

Node.js <= v12

If you are using Node.js version 8-12, save the file with ES6 modules with `.mjs` extension and run it like:

``````node --experimental-modules my-app.mjs
``````

How do you add PostgreSQL Driver as a dependency in Maven?

``````<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
``````

Try this.

``````public function getDownload()
{

'Content-Type: application/pdf',
);

}
``````

`"./download/info.pdf"`will not work as you have to give full physical path.

Update 20/05/2016

Laravel 5, 5.1, 5.2 or 5.* users can use the following method instead of `Response` facade. However, my previous answer will work for both Laravel 4 or 5. (the `\$header` array structure change to associative array `=>`- the colon after 'Content-Type' was deleted - if we don't do those changes then headers will be added in wrong way: the name of header wil be number started from 0,1,...)

``````\$headers = [
'Content-Type' => 'application/pdf',
];

``````

How to get the selected index of a RadioGroup in Android

Kotlin:

``````val selectedIndex = radioButtonGroup?.indexOfChild(
)
``````

Sort columns of a dataframe by column name

Here is what I found out to achieve a similar problem with my data set.

First, do what James mentioned above, i.e.

``````test[ , order(names(test))]
``````

Second, use the everything() function in dplyr to move specific columns of interest (e.g., "D", "G", "K") at the beginning of the data frame, putting the alphabetically ordered columns after those ones.

``````select(test, D, G, K, everything())
``````

­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

Removing special characters VBA Excel

This is what I use, based on this link

``````Function StripAccentb(RA As Range)

Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
'Const AccChars = "ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöùúûüýÿ"
'Const RegChars = "SZszYAAAAAACEEEEIIIIDNOOOOOUUUUYaaaaaaceeeeiiiidnooooouuuuyy"
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
S = RA.Cells.Text
For i = 1 To Len(AccChars)
A = Mid(AccChars, i, 1)
B = Mid(RegChars, i, 1)
S = Replace(S, A, B)
'Debug.Print (S)
Next

StripAccentb = S

Exit Function
End Function
``````

Usage:

``````=StripAccentb(B2) ' cell address
``````

Sub version for all cells in a sheet:

``````Sub replacesub()
Dim A As String * 1
Dim B As String * 1
Dim i As Integer
Dim S As String
Const AccChars = "ñéúãíçóêôöá" ' using less characters is faster
Const RegChars = "neuaicoeooa"
Range("A1").Resize(Cells.Find(what:="*", SearchOrder:=xlRows, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Row, _
Cells.Find(what:="*", SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, LookIn:=xlValues).Column).Select '
For Each cell In Selection
If cell <> "" Then
S = cell.Text
For i = 1 To Len(AccChars)
A = Mid(AccChars, i, 1)
B = Mid(RegChars, i, 1)
S = replace(S, A, B)
Next
cell.Value = S
Debug.Print "celltext "; (cell.Text)
End If
Next cell
End Sub
``````

Escape double quotes in Java

For example, Use a substitution char for the quotes and then replace that char with `\"`

``````String newstring = String.replaceAll("%","\"");
``````

or replace all instances of `\"` with `\\\"`

``````String newstring = String.replaceAll("\"","\\\"");
``````

jQuery scrollTop not working in Chrome but working in Firefox

I use:

``````var \$scrollEl = \$.browser.mozilla ? \$('html') : \$('body');
``````

Go to beginning of line without opening new line in VI

I just found 0(zero) and shift+0 works on vim.

logout and redirecting session in php

``````<?
session_start();
session_unset();
session_destroy();

exit();
?>
``````

Determine version of Entity Framework I am using?

Another way to get the EF version you are using is to open the Package Manager Console (PMC) in Visual Studio and type Get-Package at the prompt. The first line with be for EntityFramework and list the version the project has installed.

``````PM> Get-Package

Id                             Version              Description/Release Notes
--                             -------              -------------------------
EntityFramework                5.0.0                Entity Framework is Microsoft's recommended data access technology for new applications.
jQuery                         1.7.1.1              jQuery is a new kind of JavaScript Library....                                           `enter code here```````

It displays much more and you may have to scroll back up to find the EF line, but this is the easiest way I know of to find out.

Keeping session alive with Curl and PHP

``````curl_setopt (\$ch, CURLOPT_COOKIEJAR, COOKIE_FILE);
``````

How do I make a newline after a twitter bootstrap element?

Bootstrap 4:

``````<div class="w-100"></div>
``````

Using two values for one switch case statement

With the integration of JEP 325: Switch Expressions (Preview) in JDK-12 early access builds, one can now make use of the new form of the switch label as :-

``````case text1, text4 -> {
//blah
}
``````

or to rephrase the demo from one of the answers, something like :-

``````public class RephraseDemo {

public static void main(String[] args) {
int month = 9;
int year = 2018;
int numDays = 0;

switch (month) {
case 1, 3, 5, 7, 8, 10, 12 ->{
numDays = 31;
}
case 4, 6, 9, 11 ->{
numDays = 30;
}
case 2 ->{
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
}
default ->{
System.out.println("Invalid month.");

}
}
System.out.println("Number of Days = " + numDays);
}
}
``````

Here is how you can give it a try - Compile a JDK12 preview feature with Maven

How to remove duplicate white spaces in string using Java?

You can also try using String Tokeniser, for any space, tab, newline, and all. A simple way is,

``````String s = "Your Text Here";
StringTokenizer st = new StringTokenizer( s, " " );
while(st.hasMoreTokens())
{
System.out.print(st.nextToken());
}
``````

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

Gulp 4.0 has changed the way that tasks should be defined if the task depends on another task to execute. The list parameter has been deprecated.

An example from your gulpfile.js would be:

``````// Starts a BrowerSync instance
browser.init({server: './_site', port: port});
});
``````

Instead of the list parameter they have introduced `gulp.series()` and `gulp.parallel()`.

This task should be changed to something like this:

``````// Starts a BrowerSync instance
browser.init({server: './_site', port: port});
}));
``````

I'm not an expert in this. You can see a more robust example in the gulp documentation for running tasks in series or these following excellent blog posts by Jhey Thompkins and Stefan Baumgartner

https://codeburst.io/switching-to-gulp-4-0-271ae63530c0

https://fettblog.eu/gulp-4-parallel-and-series/

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

IF they Give Path Directory Error!

In MAC Then Go to Folder Get Info and Open Storage and Permission change to privileges Read To Write

Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click

If element is not clickable and overlay issue is ocuring we use arguments[0].click().

WebElement ele = driver.findElement(By.xpath("//div[@class='input-group-btn']/input")); JavascriptExecutor executor = (JavascriptExecutor)driver; executor.executeScript("arguments[0].click();", ele);

How can I check for IsPostBack in JavaScript?

Lots of options here.

For a pure JS solution, have your page submit to itself, but with additional URL parameter (mypage.html?postback=true) - you can then get the page url with window.location.href, and parse that using a split or regex to look for your variable.

The much easier one, assuming you sending back to some sort of scripting language to proces the page (php/perl/asp/cf et. al), is to have them echo a line of javascript in the page setting a variable:

``````<html>

<?php
if (\$_POST['myVar']) {
//postback
echo '<script>var postingBack = true;</script>';
//Do other processing
} else {
echo '<script>var postingBack = false;</script>'
} ?>
<script>
if (postingBack == false) {
//Do stuff
}
}

``````

Can I force a page break in HTML printing?

You can use the CSS property `page-break-before` (or `page-break-after`). Just set `page-break-before: always` on those block-level elements (e.g., heading, `div`, `p`, or `table` elements) that should start on a new line.

For example, to cause a line break before any 2nd level heading and before any element in class `newpage` (e.g., `<div class=newpage>`...), you would use

``````h2, .newpage { page-break-before: always }
``````

How to remove "index.php" in codeigniter's path

``````<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\$ index.php/\$1 [L]
</IfModule>
``````

How to make Scrollable Table with fixed headers using CSS

I can think of a cheeky way to do it, I don't think this will be the best option but it will work.

Create the header as a separate table then place the other in a div and set a max size, then allow the scroll to come in by using `overflow`.

_x000D_
_x000D_
``````table {_x000D_
width: 500px;_x000D_
}_x000D_
_x000D_
.scroll {_x000D_
max-height: 60px;_x000D_
overflow: auto;_x000D_
}``````
_x000D_
``````<table border="1">_x000D_
<tr>_x000D_
</tr>_x000D_
</table>_x000D_
<div class="scroll">_x000D_
<table>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>More Text</td><td>More Text</td><td>More Text</td><td>More Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td></tr>_x000D_
</table>_x000D_
</div>``````
_x000D_
_x000D_
_x000D_

Waiting till the async task finish its work

wait until this call is finish its executing

You will need to call AsyncTask.get() method for getting result back and make wait until `doInBackground` execution is not complete. but this will freeze Main UI thread if you not call get method inside a Thread.

To get result back in UI Thread start `AsyncTask` as :

``````String str_result= new RunInBackGround().execute().get();
``````

A potentially dangerous Request.Form value was detected from the client

Please bear in mind that some .NET controls will automatically HTML encode the output. For instance, setting the .Text property on a TextBox control will automatically encode it. That specifically means converting `<` into `&lt;`, `>` into `&gt;` and `&` into `&amp;`. So be wary of doing this...

``````myTextBox.Text = Server.HtmlEncode(myStringFromDatabase); // Pseudo code
``````

However, the .Text property for HyperLink, Literal and Label won't HTML encode things, so wrapping Server.HtmlEncode(); around anything being set on these properties is a must if you want to prevent `<script> window.location = "http://www.google.com"; </script>` from being output into your page and subsequently executed.

Do a little experimenting to see what gets encoded and what doesn't.

Click a button programmatically

in c# this is working :D

``````protect void button1_Click(object sender, EventArgs e){
button2_Click(button2, null);
}

protect void button2_Click(object sender, EventeArgs e){
//some codes here
}
``````

for vb.net

``````Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button1.Click
Button2_Click(Sender, e)
End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button2.Click
//some codes here
End Sub
``````

Bash script to check running process

A solution with `service` and `awk` that takes in a comma-delimited list of service names.

First it's probably a good bet you'll need root privileges to do what you want. If you don't need to check then you can remove that part.

``````#!/usr/bin/env bash

# First parameter is a comma-delimited string of service names i.e. service1,service2,service3
SERVICES=\$1

ALL_SERVICES_STARTED=true

if [ \$EUID -ne 0 ]; then
if [ "\$(id -u)" != "0" ]; then
echo "root privileges are required" 1>&2
exit 1
fi
exit 1
fi

for service in \${SERVICES//,/ }
do
STATUS=\$(service \${service} status | awk '{print \$2}')

if [ "\${STATUS}" != "started" ]; then
echo "\${service} not started"
ALL_SERVICES_STARTED=false
fi
done

if \${ALL_SERVICES_STARTED} ; then
echo "All services started"
exit 0
else
echo "Check Failed"
exit 1
fi
``````

Does Spring @Transactional attribute work on a private method?

If you need to wrap a private method inside a transaction and don't want to use aspectj, you can use TransactionTemplate.

``````@Service
public class MyService {

@Autowired
private TransactionTemplate transactionTemplate;

private void process(){
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
processInTransaction();
}
});

}

private void processInTransaction(){
//...
}

}
``````

Sum across multiple columns with dplyr

Using `reduce()` from `purrr` is slightly faster than `rowSums` and definately faster than `apply`, since you avoid iterating over all the rows and just take advantage of the vectorized operations:

``````library(purrr)
library(dplyr)
iris %>% mutate(Petal = reduce(select(., starts_with("Petal")), `+`))
``````

See this for timings

Working with huge files in VIM

emacs works very well with files into the 100's of megabytes, I've used it on log files without too much trouble.

But generally when I have some kind of analysis task, I find writing a perl script a better choice.

jQuery ajax request with json response, how to?

Connect your javascript clientside controller and php serverside controller using sending and receiving opcodes with binded data. So your php code can send as response functional delta for js recepient/listener

How to get the previous page URL using JavaScript?

You want in page A to know the URL of page B?

Or to know in page B the URL of page A?

In Page B: document.referrer if set. As already shown here: How to get the previous URL in JavaScript?

In page A you would need to read a cookie or local/sessionStorage you set in page B, assuming the same domains

.map() a Javascript ES6 Map?

_x000D_
_x000D_
``````const mapMap = (callback, map) => new Map(Array.from(map).map(callback))_x000D_
_x000D_
var myMap = new Map([["thing1", 1], ["thing2", 2], ["thing3", 3]]);_x000D_
_x000D_
var newMap = mapMap((pair) => [pair[0], pair[1] + 1], myMap); // Map { 'thing1' => 2, 'thing2' => 3, 'thing3' => 4 }``````
_x000D_
_x000D_
_x000D_

Spring expected at least 1 bean which qualifies as autowire candidate for this dependency

You should put this line in your application context:

``````<context:component-scan base-package="com.cinebot.service" />
``````

Bootstrap - dropdown menu not working?

Check if you're referencing `jquery.js` BEFORE `bootstrap.js` and `bootstrap.js` is loaded only once. That fixed the same error for me:

``````<script type="text/javascript" src="js/jquery-1.8.0.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
``````

How to convert a string to lower or upper case in Ruby

... and the uppercase is:

``````"Awesome String".upcase
=> "AWESOME STRING"
``````

How can I remove item from querystring in asp.net using c#?

Here is a simple way. Reflector is not needed.

``````    public static string GetQueryStringWithOutParameter(string parameter)
{
var nameValueCollection = System.Web.HttpUtility.ParseQueryString(HttpContext.Current.Request.QueryString.ToString());
nameValueCollection.Remove(parameter);
string url = HttpContext.Current.Request.Path + "?" + nameValueCollection;

return url;
}
``````

Here `QueryString.ToString()` is required because `Request.QueryString` collection is read only.

Is it possible to decrypt MD5 hashes?

The MD5 Hash algorithm is not reversible, so MD5 decode in not possible, but some website have bulk set of password match, so you can try online for decode MD5 hash.

Try online :

MD5 Decrypt

md5online

md5decrypter

powershell 2.0 try catch how to access the exception

Try something like this:

``````try {
\$w = New-Object net.WebClient
}
catch [Net.WebException] {
Write-Host \$_.Exception.ToString()
}
``````

The exception is in the `\$_` variable. You might explore `\$_` like this:

``````try {
\$w = New-Object net.WebClient
}
catch [Net.WebException] {
\$_ | fl * -Force
}
``````

I think it will give you all the info you need.

My rule: if there is some data that is not displayed, try to use `-force`.

Access And/Or exclusions

Seeing that it appears you are running using the SQL syntax, try with the correct wild card.

``SELECT * FROM someTable WHERE (someTable.Field NOT LIKE '%RISK%') AND (someTable.Field NOT LIKE '%Blah%') AND someTable.SomeOtherField <> 4; ``

How do you get centered content using Twitter Bootstrap?

Update 2019 - Bootstrap 4

"Centered content" can mean many different things, and Bootstrap centering has changed a lot since the original post.

Horizontal Center

Bootstrap 3

• `text-center` is used for `display:inline` elements
• `center-block` to center `display:block` elements
• `col-*offset-*` to center grid columns
• see this answer to center the navbar

Demo Bootstrap 3 Horizontal Centering

Bootstrap 4

• `text-center` is still used for `display:inline` elements
• `mx-auto` replaces `center-block` to center `display:block` elements
• `offset-*` or `mx-auto` can be used to center grid columns
• `justify-content-center` in `row` can also be used to center `col-*`

`mx-auto` (auto x-axis margins) will center `display:block` or `display:flex` elements that have a defined width, (`%`, `vw`, `px`, etc..). Flexbox is used by default on grid columns, so there are also various flexbox centering methods.

Demo Bootstrap 4 Horizontal Centering

Vertical Center

Now that Bootstrap 4 is flexbox by default there are many different approaches to vertical alignment using: auto-margins, flexbox utils, or the display utils along with vertical align utils. At first "vertical align utils" seems obvious but these only work with inline and table display elements. Here are some Bootstrap 4 vertical centering options..

1 - Vertical Center Using Auto Margins:

Another way to vertically center is to use `my-auto`. This will center the element within it's container. For example, `h-100` makes the row full height, and `my-auto` will vertically center the `col-sm-12` column.

``````<div class="row h-100">
<div class="col-sm-12 my-auto">
<div class="card card-block w-25">Card</div>
</div>
</div>
``````

Vertical Center Using Auto Margins Demo

`my-auto` represents margins on the vertical y-axis and is equivalent to:

``````margin-top: auto;
margin-bottom: auto;
``````

2 - Vertical Center with Flexbox:

Since Bootstrap 4 `.row` is now `display:flex` you can simply use `align-self-center` on any column to vertically center it...

``````       <div class="row">
<div class="col-6 align-self-center">
<div class="card card-block">
Center
</div>
</div>
<div class="col-6">
<div class="card card-inverse card-danger">
Taller
</div>
</div>
</div>
``````

or, use `align-items-center` on the entire `.row` to vertically center align all `col-*` in the row...

``````       <div class="row align-items-center">
<div class="col-6">
<div class="card card-block">
Center
</div>
</div>
<div class="col-6">
<div class="card card-inverse card-danger">
Taller
</div>
</div>
</div>
``````

Vertical Center Different Height Columns Demo

3 - Vertical Center Using Display Utils:

Bootstrap 4 has display utils that can be used for `display:table`, `display:table-cell`, `display:inline`, etc.. These can be used with the vertical alignment utils to align inline, inline-block or table cell elements.

``````<div class="row h-50">
<div class="col-sm-12 h-100 d-table">
<div class="card card-block d-table-cell align-middle">
I am centered vertically
</div>
</div>
</div>
``````

Vertical Center Using Display Utils Demo

SQL MAX of multiple columns?

Scalar Function cause all sorts of performance issues, so its better to wrap the logic into an Inline Table Valued Function if possible. This is the function I used to replace some User Defined Functions which selected the Min/Max dates from a list of upto ten dates. When tested on my dataset of 1 Million rows the Scalar Function took over 15 minutes before I killed the query the Inline TVF took 1 minute which is the same amount of time as selecting the resultset into a temporary table. To use this call the function from either a subquery in the the SELECT or a CROSS APPLY.

``````CREATE FUNCTION dbo.Get_Min_Max_Date
(
@Date1  datetime,
@Date2  datetime,
@Date3  datetime,
@Date4  datetime,
@Date5  datetime,
@Date6  datetime,
@Date7  datetime,
@Date8  datetime,
@Date9  datetime,
@Date10 datetime
)
RETURNS TABLE
AS
RETURN
(
SELECT      Max(DateValue)  Max_Date,
Min(DateValue)  Min_Date
FROM        (
VALUES  (@Date1),
(@Date2),
(@Date3),
(@Date4),
(@Date5),
(@Date6),
(@Date7),
(@Date8),
(@Date9),
(@Date10)
)   AS Dates(DateValue)
)
``````

Python unittest - opposite of assertRaises?

you can try like that. try: self.assertRaises(None,function,arg1, arg2) except: pass if you don't put code inside try block it will through exception' AssertionError: None not raised " and test case will be failed. Test case will be pass if put inside try block which is expected behaviour.

How to empty (clear) the logcat buffer in Android

For anyone coming to this question wondering how to do this in Eclipse, You can remove the displayed text from the logCat using the button provided (often has a red X on the icon)

I had researched this and the URLRewrite method works well. Can't seem to find the change scripted anywhere well. I wrote this compatible with PowerShell v2 and above and tested it on IIS 7.5.

``````# Add Allowed Server Variable
Add-WebConfiguration /system.webServer/rewrite/allowedServerVariables -atIndex 0 -value @{name="RESPONSE_SERVER"}
# Rule Name
\$ruleName = "Remove Server Response Header"
# Add outbound IIS Rewrite Rule
Add-WebConfigurationProperty -pspath "iis:\" -filter "system.webServer/rewrite/outboundrules" -name "." -value @{name=\$ruleName; stopProcessing='False'}
#Set Properties of newly created outbound rule
Set-WebConfigurationProperty -pspath "MACHINE/WEBROOT/APPHOST"  -filter "system.webServer/rewrite/outboundRules/rule[@name='\$ruleName']/match" -name "serverVariable" -value "RESPONSE_SERVER"
Set-WebConfigurationProperty -pspath "MACHINE/WEBROOT/APPHOST"  -filter "system.webServer/rewrite/outboundRules/rule[@name='\$ruleName']/match" -name "pattern" -value ".*"
Set-WebConfigurationProperty -pspath "MACHINE/WEBROOT/APPHOST"  -filter "system.webServer/rewrite/outboundRules/rule[@name='\$ruleName']/action" -name "type" -value "Rewrite"
``````

Parsing a CSV file using NodeJS

I use this simple one: https://www.npmjs.com/package/csv-parser

Very simple to use:

``````const csv = require('csv-parser')
const fs = require('fs')
const results = [];

.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', () => {
console.log(results);
console.log(results[0]['Lowest Selling Price'])
});
``````

MySQL server has gone away - in exactly 60 seconds

Increasing SQL-Wait-Timeout worked for me in this case, try this:

``````mysql_query("SET @@session.wait_timeout=900", \$link);
``````

before you first "normal" SQL queries.

See what's in a stash without applying it

From the `man git-stash` page:

The modifications stashed away by this command can be listed with git stash list, inspected with git stash show

``````show [<stash>]
Show the changes recorded in the stash as a diff between the stashed state and
its original parent. When no <stash> is given, shows the latest one. By default,
the command shows the diffstat, but it will accept any format known to git diff
(e.g., git stash show -p stash@{1} to view the second most recent stash in patch
form).
``````

To list the stashed modifications

`git stash list`

To show files changed in the last stash

`git stash show`

So, to view the content of the most recent stash, run

``````git stash show -p
``````

To view the content of an arbitrary stash, run something like

``````git stash show -p stash@{1}
``````

jQuery - how to write 'if not equal to' (opposite of ==)

``````!=
``````

For example,

``````if ("apple" != "orange")
// true, the string "apple" is not equal to the string "orange"
``````

Means not. See also the logical operators list. Also, when you see triple characters, it's a type sensitive comparison. (e.g. `if (1 === '1')` [not equal])

PHP order array by date?

I recommend using DateTime objects instead of strings, because you cannot easily compare strings, which is required for sorting. You also get additional advantages for working with dates.

Once you have the DateTime objects, sorting is quite easy:

``````usort(\$array, function(\$a, \$b) {
return (\$a['date'] < \$b['date']) ? -1 : 1;
});
``````