Programs & Examples On #Partial trust

Partial trust is a .NET security model in which application code executes with reduced permissions as a measure of protecting the local system from malicious use.

How to delete a file after checking whether it exists

If you want to avoid a DirectoryNotFoundException you will need to ensure that the directory of the file does indeed exist. File.Exists accomplishes this. Another way would be to utilize the Path and Directory utility classes like so:

string file = @"C:\subfolder\test.txt";
if (Directory.Exists(Path.GetDirectoryName(file)))
{
    File.Delete(file);
}

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

Detect IE version (prior to v9) in JavaScript

Simple solution stop thinking browser and use the year.

var year = eval(today.getYear());
if(year < 1900 )
 {alert('Good to go: All browsers and IE 9 & >');}
else
 {alert('Get with it and upgrade your IE to 9 or >');}

Usage of the backtick character (`) in JavaScript

The good part is we can make basic maths directly:

_x000D_
_x000D_
let nuts = 7_x000D_
_x000D_
more.innerHTML = `_x000D_
_x000D_
<h2>You collected ${nuts} nuts so far!_x000D_
_x000D_
<hr>_x000D_
_x000D_
Double it, get ${nuts + nuts} nuts!!_x000D_
_x000D_
`
_x000D_
<div id="more"></div>
_x000D_
_x000D_
_x000D_

It became really useful in a factory function:

_x000D_
_x000D_
function nuts(it){_x000D_
  return `_x000D_
    You have ${it} nuts! <br>_x000D_
    Cosinus of your nuts: ${Math.cos(it)} <br>_x000D_
    Triple nuts: ${3 * it} <br>_x000D_
    Your nuts encoded in BASE64:<br> ${btoa(it)}_x000D_
  `_x000D_
}_x000D_
_x000D_
nut.oninput = (function(){_x000D_
  out.innerHTML = nuts(nut.value)_x000D_
})
_x000D_
<h3>NUTS CALCULATOR_x000D_
<input type="number" id="nut">_x000D_
_x000D_
<div id="out"></div>
_x000D_
_x000D_
_x000D_

Run a task every x-minutes with Windows Task Scheduler

The task must be configured in two steps.

First you create a simple task that start at 0:00, every day. Then, you go in Advanced... (or similar depending on the operating system you are on) and select the Repeat every X minutes option for 24 hours.

The key here is to find the advanced properties. If you are using the XP wizard, it will only offer you to launch the advanced dialog once you created the task.

On more recent versions of Windows (7+ I think?):

  1. Double click the task and a property window will show up.
  2. Click the Triggers tab.
  3. Double click the trigger details and the Edit Trigger window will show up.
  4. Under Advanced settings panel, tick Repeat task every xxx minutes, and set Indefinitely if you need.
  5. Finally, click ok.

Android device is not connected to USB for debugging (Android studio)

This solution works for every unrecognized android device... mostly general brands don´t come with usb debugging drivers...

  • go to settings
  • control panel
  • hardware and sound
  • device manager
  • And look for any devices showing an error. Many androids will show as an unknown USB device or just Android

First thing you need will be your device IDs. You can get them opening up the device manager and finding the "Unknown Device" with a yellow exclamation point. Right click on it and select 'Properties', and then go to the 'Details' tab. Under the 'Property' drop down menu, select hardware IDs. There should be two strings:

USB\VID_2207&PID_0011&REV_0222&MI_01
USB\VID_2207&PID_0011&MI_01

Copy those strings somewhere and then navigate to where you downloaded the Google USB driver. Then you need to open up the file 'android_winusb.inf' in a text editor. I would recommend using Notepad++.

android_winusb.inf

First, create a sub-section for your device. I called mine ';RCA 6378W2' but it doesn't really matter what you call it. Then, under the sub-section you created paste the Device ID strings you copied from the Device Manager, preceded by '%SingleAdbInterface%'. If you need help, look at this screenshot.

NOTE:

If you are using Windows 8 or 8.1, you will need to disable device driver signature checks before you'll be able to install the modified driver. Here's a quick video on how to disable device driver checks http://www.youtube.com/watch?v=NM1MN8QZhnk. Ignore the part at the beginning about 64 bit, your computer architecture doesn't matter.

Please look at this article, for more information and MacOS instructions.

Concatenate in jQuery Selector

Your concatenation syntax is correct.

Most likely the callback function isn't even being called. You can test that by putting an alert(), console.log() or debugger line in that function.

If it isn't being called, most likely there's an AJAX error. Look at chaining a .fail() handler after $.post() to find out what the error is, e.g.:

$.post('ajaxskeleton.php', {
    red: text       
}, function(){
    $('#part' + number).html(text);
}).fail(function(jqXHR, textStatus, errorThrown) {
    console.log(arguments);
});

What are the differences between numpy arrays and matrices? Which one should I use?

Numpy matrices are strictly 2-dimensional, while numpy arrays (ndarrays) are N-dimensional. Matrix objects are a subclass of ndarray, so they inherit all the attributes and methods of ndarrays.

The main advantage of numpy matrices is that they provide a convenient notation for matrix multiplication: if a and b are matrices, then a*b is their matrix product.

import numpy as np

a = np.mat('4 3; 2 1')
b = np.mat('1 2; 3 4')
print(a)
# [[4 3]
#  [2 1]]
print(b)
# [[1 2]
#  [3 4]]
print(a*b)
# [[13 20]
#  [ 5  8]]

On the other hand, as of Python 3.5, NumPy supports infix matrix multiplication using the @ operator, so you can achieve the same convenience of matrix multiplication with ndarrays in Python >= 3.5.

import numpy as np

a = np.array([[4, 3], [2, 1]])
b = np.array([[1, 2], [3, 4]])
print(a@b)
# [[13 20]
#  [ 5  8]]

Both matrix objects and ndarrays have .T to return the transpose, but matrix objects also have .H for the conjugate transpose, and .I for the inverse.

In contrast, numpy arrays consistently abide by the rule that operations are applied element-wise (except for the new @ operator). Thus, if a and b are numpy arrays, then a*b is the array formed by multiplying the components element-wise:

c = np.array([[4, 3], [2, 1]])
d = np.array([[1, 2], [3, 4]])
print(c*d)
# [[4 6]
#  [6 4]]

To obtain the result of matrix multiplication, you use np.dot (or @ in Python >= 3.5, as shown above):

print(np.dot(c,d))
# [[13 20]
#  [ 5  8]]

The ** operator also behaves differently:

print(a**2)
# [[22 15]
#  [10  7]]
print(c**2)
# [[16  9]
#  [ 4  1]]

Since a is a matrix, a**2 returns the matrix product a*a. Since c is an ndarray, c**2 returns an ndarray with each component squared element-wise.

There are other technical differences between matrix objects and ndarrays (having to do with np.ravel, item selection and sequence behavior).

The main advantage of numpy arrays is that they are more general than 2-dimensional matrices. What happens when you want a 3-dimensional array? Then you have to use an ndarray, not a matrix object. Thus, learning to use matrix objects is more work -- you have to learn matrix object operations, and ndarray operations.

Writing a program that mixes both matrices and arrays makes your life difficult because you have to keep track of what type of object your variables are, lest multiplication return something you don't expect.

In contrast, if you stick solely with ndarrays, then you can do everything matrix objects can do, and more, except with slightly different functions/notation.

If you are willing to give up the visual appeal of NumPy matrix product notation (which can be achieved almost as elegantly with ndarrays in Python >= 3.5), then I think NumPy arrays are definitely the way to go.

PS. Of course, you really don't have to choose one at the expense of the other, since np.asmatrix and np.asarray allow you to convert one to the other (as long as the array is 2-dimensional).


There is a synopsis of the differences between NumPy arrays vs NumPy matrixes here.

Android - Back button in the title bar

This is working for me getSupportActionBar().setDisplayHomeAsUpEnabled(false); enter image description here

jQuery $(this) keyword

Have a look at this code:

HTML:

<div class="multiple-elements" data-bgcol="red"></div>
<div class="multiple-elements" data-bgcol="blue"></div>

JS:

$('.multiple-elements').each(
    function(index, element) {
        $(this).css('background-color', $(this).data('bgcol')); // Get value of HTML attribute data-bgcol="" and set it as CSS color
    }
);

this refers to the current element that the DOM engine is sort of working on, or referring to.

Another example:

<a href="#" onclick="$(this).css('display', 'none')">Hide me!</a>

Hope you understand now. The this keyword occurs while dealing with object oriented systems, or as we have in this case, element oriented systems :)

How to configure nginx to enable kinda 'file browser' mode?

All answers contain part of the answer. Let me try to combine all in one.

Quick setup "file browser" mode on freshly installed nginx server:

  1. Edit default config for nginx:

    sudo vim /etc/nginx/sites-available/default
    
  2. Add following to config section:

    location /myfolder {  # new url path
       alias /home/username/myfolder/; # directory to list
       autoindex on;
    }
    
  3. Create folder and sample file there:

    mkdir -p /home/username/myfolder/
    ls -la >/home/username/myfolder/mytestfile.txt
    
  4. Restart nginx

    sudo systemctl restart nginx
    
  5. Check result: http://<your-server-ip>/myfolder for example http://192.168.0.10/myfolder/

enter image description here

Convert a file path to Uri in Android

Please try the following code

Uri.fromFile(new File("/sdcard/sample.jpg"))

How to kill MySQL connections

I would recommend checking the connections to show the maximum thread connection is

show variables like "max_connections";

sample

+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 13  |
+-----------------+-------+
1 row in set

Then increase it by example

set global max_connections = 500;

How much data / information can we save / store in a QR code?

QR codes have three parameters: Datatype, size (number of 'pixels') and error correction level. How much information can be stored there also depends on these parameters. For example the lower the error correction level, the more information that can be stored, but the harder the code is to recognize for readers.

The maximum size and the lowest error correction give the following values:
Numeric only Max. 7,089 characters
Alphanumeric Max. 4,296 characters
Binary/byte Max. 2,953 characters (8-bit bytes)

How do I get bootstrap-datepicker to work with Bootstrap 3?

For anyone else who runs into this...

Version 1.2.0 of this plugin (current as of this post) doesn't quite work in all cases as documented with Bootstrap 3.0, but it does with a minor workaround.

Specifically, if using an input with icon, the HTML markup is of course slightly different as class names have changed:

<div class="input-group" data-datepicker="true">
    <input name="date" type="text" class="form-control" />
    <span class="input-group-addon"><i class="icon-calendar"></i></span>
</div>

It seems because of this, you need to use a selector that points directly to the input element itself NOT the parent container (which is what the auto generated HTML on the demo page suggests).

$('*[data-datepicker="true"] input[type="text"]').datepicker({
    todayBtn: true,
    orientation: "top left",
    autoclose: true,
    todayHighlight: true
});

Having done this you will probably also want to add a listener for clicking/tapping on the icon so it sets focus on the text input when clicked (which is the behaviour when using this plugin with TB 2.x by default).

$(document).on('touch click', '*[data-datepicker="true"] .input-group-addon', function(e){
    $('input[type="text"]', $(this).parent()).focus();
});

NB: I just use a data-datepicker boolean attribute because the class name 'datepicker' is reserved by the plugin and I already use 'date' for styling elements.

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

Powershell script to locate specific file/file name?

In findFileByFilename.ps1 I have:

# https://stackoverflow.com/questions/3428044/powershell-script-to-locate-specific-file-file-name
$filename = Read-Host 'What is the filename to find?'
gci . -recurse -filter $filename -file -ErrorAction SilentlyContinue
# tested works from pwd recursively.

This works great for me. I understand it.

I put it in a folder on my PATH.

I invoke it with:

> findFileByFilename.ps1

C# Wait until condition is true

After digging a lot of stuff, finally, I came up with a good solution that doesn't hang the CI :) Suit it to your needs!

public static Task WaitUntil<T>(T elem, Func<T, bool> predicate, int seconds = 10)
{
    var tcs = new TaskCompletionSource<int>();
    using(var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromSeconds(seconds)))
    {
        cancellationTokenSource.Token.Register(() =>
        {
            tcs.SetException(
                new TimeoutException($"Waiting predicate {predicate} for {elem.GetType()} timed out!"));
            tcs.TrySetCanceled();
        });

        while(!cancellationTokenSource.IsCancellationRequested)
        {
            try
            {
                if (!predicate(elem))
                {
                    continue;
                }
            }
            catch(Exception e)
            {
                tcs.TrySetException(e);
            }

            tcs.SetResult(0);
            break;
        }

        return tcs.Task;
    }
}

CSS Div width percentage and padding without breaking layout

If you want the #header to be the same width as your container, with 10px of padding, you can leave out its width declaration. That will cause it to implicitly take up its entire parent's width (since a div is by default a block level element).

Then, since you haven't defined a width on it, the 10px of padding will be properly applied inside the element, rather than adding to its width:

#container {
    position: relative;
    width: 80%;
}

#header {
    position: relative;
    height: 50px;
    padding: 10px;
}

You can see it in action here.

The key when using percentage widths and pixel padding/margins is not to define them on the same element (if you want to accurately control the size). Apply the percentage width to the parent and then the pixel padding/margin to a display: block child with no width set.


Update

Another option for dealing with this is to use the box-sizing CSS rule:

#container { 
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */

    /* Since this element now uses border-box sizing, the 10px of horizontal
       padding will be drawn inside the 80% width */
    width: 80%;
    padding: 0 10px;
}

Here's a post talking about how box-sizing works.

How to convert Java String to JSON Object

You are passing into the JSONObject constructor an instance of a StringBuilder class.

This is using the JSONObject(Object) constructor, not the JSONObject(String) one.

Your code should be:

JSONObject jsonObj = new JSONObject(jsonString.toString());

How to trigger checkbox click event even if it's checked through Javascript code?

You can use .change() function too

E.g.:

$('form input[type=checkbox]').change(function() { console.log('hello') });

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

The referenced column must be an index of a single column or the first column in multi column index, and the same type and the same collation.

My two tables have the different collations. It can be shown by issuing show table status like table_name and collation can be changed by issuing alter table table_name convert to character set utf8.

How to map with index in Ruby?

If you're using ruby 1.8.7 or 1.9, you can use the fact that iterator methods like each_with_index, when called without a block, return an Enumerator object, which you can call Enumerable methods like map on. So you can do:

arr.each_with_index.map { |x,i| [x, i+2] }

In 1.8.6 you can do:

require 'enumerator'
arr.enum_for(:each_with_index).map { |x,i| [x, i+2] }

top nav bar blocking top content of the page

you should add

#page {
  padding-top: 65px
}

to not destroy a sticky footer or something else

Visual Studio 2015 or 2017 does not discover unit tests

For me upgrading to version 3.7 of NUnit worked.

Convert a list of characters into a string

Use the join method of the empty string to join all of the strings together with the empty string in between, like so:

>>> a = ['a', 'b', 'c', 'd']
>>> ''.join(a)
'abcd'

Spring Boot - inject map from application.yml

I run into the same problem today, but unfortunately Andy's solution didn't work for me. In Spring Boot 1.2.1.RELEASE it's even easier, but you have to be aware of a few things.

Here is the interesting part from my application.yml:

oauth:
  providers:
    google:
     api: org.scribe.builder.api.Google2Api
     key: api_key
     secret: api_secret
     callback: http://callback.your.host/oauth/google

providers map contains only one map entry, my goal is to provide dynamic configuration for other OAuth providers. I want to inject this map into a service that will initialize services based on the configuration provided in this yaml file. My initial implementation was:

@Service
@ConfigurationProperties(prefix = 'oauth')
class OAuth2ProvidersService implements InitializingBean {

    private Map<String, Map<String, String>> providers = [:]

    @Override
    void afterPropertiesSet() throws Exception {
       initialize()
    }

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

After starting the application, providers map in OAuth2ProvidersService was not initialized. I tried the solution suggested by Andy, but it didn't work as well. I use Groovy in that application, so I decided to remove private and let Groovy generates getter and setter. So my code looked like this:

@Service
@ConfigurationProperties(prefix = 'oauth')
class OAuth2ProvidersService implements InitializingBean {

    Map<String, Map<String, String>> providers = [:]

    @Override
    void afterPropertiesSet() throws Exception {
       initialize()
    }

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

After that small change everything worked.

Although there is one thing that might be worth mentioning. After I make it working I decided to make this field private and provide setter with straight argument type in the setter method. Unfortunately it wont work that. It causes org.springframework.beans.NotWritablePropertyException with message:

Invalid property 'providers[google]' of bean class [com.zinvoice.user.service.OAuth2ProvidersService]: Cannot access indexed value in property referenced in indexed property path 'providers[google]'; nested exception is org.springframework.beans.NotReadablePropertyException: Invalid property 'providers[google]' of bean class [com.zinvoice.user.service.OAuth2ProvidersService]: Bean property 'providers[google]' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?

Keep it in mind if you're using Groovy in your Spring Boot application.

Scrolling to element using webdriver?

It's not a direct answer on question (its not about Actions), but it also allow you to scroll easily to required element:

element = driver.find_element_by_id('some_id')
element.location_once_scrolled_into_view

This actually intend to return you coordinates (x, y) of element on page, but also scroll down right to target element

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

From the docs:

The SimpleHTTPServer module has been merged into http.server in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.

So, your command is python -m http.server, or depending on your installation, it can be:

python3 -m http.server

How to install a Mac application using Terminal

Probably not exactly your issue..

Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments

sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /

Pandas: Convert Timestamp to datetime.date

You can convert a datetime.date object into a pandas Timestamp like this:

#!/usr/bin/env python3
# coding: utf-8

import pandas as pd
import datetime

# create a datetime data object
d_time = datetime.date(2010, 11, 12)

# create a pandas Timestamp object
t_stamp = pd.to_datetime('2010/11/12')

# cast `datetime_timestamp` as Timestamp object and compare
d_time2t_stamp = pd.to_datetime(d_time)

# print to double check
print(d_time)
print(t_stamp)
print(d_time2t_stamp)

# since the conversion succeds this prints `True`
print(d_time2t_stamp == t_stamp)

is not JSON serializable

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.

Difference between EXISTS and IN in SQL?

IN:

  • Works on List result set
  • Doesn’t work on subqueries resulting in Virtual tables with multiple columns
  • Compares every value in the result list
  • Performance is comparatively SLOW for larger result set of subquery

EXISTS:

  • Works on Virtual tables
  • Is used with co-related queries
  • Exits comparison when match is found
  • Performance is comparatively FAST for larger result set of subquery

Regular expression for address field validation

Here is the approach I have taken to finding addresses using regular expressions:

A set of patterns is useful to find many forms that we might expect from an address starting with simply a number followed by set of strings (ex. 1 Basic Road) and then getting more specific such as looking for "P.O. Box", "c/o", "attn:", etc.

Below is a simple test in python. The test will find all the addresses but not the last 4 items which are company names. This example is not comprehensive, but can be altered to suit your needs and catch examples you find in your data.

import re
strings = [
    '701 FIFTH AVE',
    '2157 Henderson Highway',
    'Attn: Patent Docketing',
    'HOLLYWOOD, FL 33022-2480',
    '1940 DUKE STREET',
    '111 MONUMENT CIRCLE, SUITE 3700',
    'c/o Armstrong Teasdale LLP',
    '1 Almaden Boulevard',
    '999 Peachtree Street NE',
    'P.O. BOX 2903',
    '2040 MAIN STREET',
    '300 North Meridian Street',
    '465 Columbus Avenue',
    '1441 SEAMIST DR.',
    '2000 PENNSYLVANIA AVENUE, N.W.',
    '465 Columbus Avenue',
    '28 STATE STREET',
    'P.O, Drawer 800889.',
    '2200 CLARENDON BLVD.',
    '840 NORTH PLANKINTON AVENUE',
    '1025 Connecticut Avenue, NW',
    '340 Commercial Street',
    '799 Ninth Street, NW',
    '11318 Lazarro Ln',
    'P.O, Box 65745',
    'c/o Ballard Spahr LLP',
    '8210 SOUTHPARK TERRACE',
    '1130 Connecticut Ave., NW, Suite 420',
    '465 Columbus Avenue',
    "BANNER & WITCOFF , LTD",
    "CHIP LAW GROUP",
    "HAMMER & ASSOCIATES, P.C.",
    "MH2 TECHNOLOGY LAW GROUP, LLP",
]

patterns = [
    "c\/o [\w ]{2,}",
    "C\/O [\w ]{2,}",
    "P.O\. [\w ]{2,}",
    "P.O\, [\w ]{2,}",
    "[\w\.]{2,5} BOX [\d]{2,8}",
    "^[#\d]{1,7} [\w ]{2,}",
    "[A-Z]{2,2} [\d]{5,5}",
    "Attn: [\w]{2,}",
    "ATTN: [\w]{2,}",
    "Attention: [\w]{2,}",
    "ATTENTION: [\w]{2,}"
]
contact_list = []
total_count = len(strings)
found_count = 0
for string in strings:
    pat_no = 1
    for pattern in patterns:
        match = re.search(pattern, string.strip())
        if match:
            print("Item found: " + match.group(0) + " | Pattern no: " + str(pat_no))
            found_count += 1
        pat_no += 1

print("-- Total: " + str(total_count) + " Found: " + str(found_count)) 

Executing Batch File in C#

Have you tried starting it as an administrator? Start Visual Studio as an administrator if you use it, because working with .bat files requires those privileges.

How to get JavaScript variable value in PHP

You might want to start by learning what Javascript and php are. Javascript is a client side script language running in the browser of the machine of the client connected to the webserver on which php runs. These languages can not communicate directly.

Depending on your goal you'll need to issue an AJAX get or post request to the server and return a json/xml/html/whatever response you need and inject the result back in the DOM structure of the site. I suggest Jquery, BackboneJS or any other JS framework for this. See the Jquery documentation for examples.

If you have to pass php data to JS on the same site you can echo the data as JS and turn your php data using json_encode() into JS.

<script type="text/javascript>
    var foo = <?php echo json_encode($somePhpVar); ?>
</script>

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

We can do it with another approach too, Like first of all get the hash value from js and call the ajax using that parameter and can do whatever we want

Android: how to refresh ListView contents?

You don't have to create a new adapter to update your ListView's contents. Simply store your Adapter in a field and update your list with the following code:

mAdapter.setList(yourNewList);
mAdapter.notifyDataSetChanged();

To clarify that, your Activity should look like that:

private YourAdapter mAdapter;

protected void onCreate(...) {

    ...

    mAdapter = new YourAdapter(this);
    setListAdapter(mAdapter);

    updateData();
}

private void updateData() {
    List<Data> newData = getYourNewData();
    mAdapter.setList(yourNewList);
    mAdapter.notifyDataSetChanged();
}

Use grep to report back only line numbers

All of these answers require grep to generate the entire matching lines, then pipe it to another program. If your lines are very long, it might be more efficient to use just sed to output the line numbers:

sed -n '/pattern/=' filename

'Best' practice for restful POST response

Returning the whole object on an update would not seem very relevant, but I can hardly see why returning the whole object when it is created would be a bad practice in a normal use case. This would be useful at least to get the ID easily and to get the timestamps when relevant. This is actually the default behavior got when scaffolding with Rails.

I really do not see any advantage to returning only the ID and doing a GET request after, to get the data you could have got with your initial POST.

Anyway as long as your API is consistent I think that you should choose the pattern that fits your needs the best. There is not any correct way of how to build a REST API, imo.

Why can't I define a static method in a Java interface?

Interfaces are concerned with polymorphism which is inherently tied to object instances, not classes. Therefore static doesn't make sense in the context of an interface.

How do I rename a local Git branch?

git branch -m [old-branch] [new-branch]

-m means move all from [old-branch] to [new-branch] and remember you can use -M for other file systems.

How to prevent user from typing in text field without disabling the field?

One option is to bind a handler to the input event.

The advantage of this approach is that we don't prevent keyboard behaviors that the user expects (e.g. tab, page up/down, etc.).

Another advantage is that it also handles the case when the input value is changed by pasting text through the context menu.

This approach works best if you only care about keeping the input empty. If you want to maintain a specific value, you'll have to track that somewhere else (in a data attribute?) since it will not be available when the input event is received.

_x000D_
_x000D_
const inputEl = document.querySelector('input');_x000D_
_x000D_
inputEl.addEventListener('input', (event) => {_x000D_
  event.target.value = '';_x000D_
});
_x000D_
<input type="text" />
_x000D_
_x000D_
_x000D_

Tested in Safari 10, Firefox 49, Chrome 54, IE 11.

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

According to this: https://www.simplified.guide/phpmyadmin/enable-login-without-password

This $cfg['Servers'][$i]['AllowNoPassword'] = TRUE; should be added twice in /etc/phpmyadmin/config.inc.php

if (!empty($dbname)) {
    // other configuration options
    $cfg['Servers'][$i]['AllowNoPassword'] = TRUE;
    // it should be placed before the following line
    $i++;
}

// other configuration options
$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

Java Read Large Text File With 70million line of text

I tried the following three methods, my file size is 1M, and I got results:

enter image description here

I run the program several times it looks that BufferedReader is faster.

@Test
public void testLargeFileIO_Scanner() throws Exception {

    long start = new Date().getTime();

    String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
    InputStream inputStream = new FileInputStream(fileName);

    try (Scanner fileScanner = new Scanner(inputStream, StandardCharsets.UTF_8.name())) {
        while (fileScanner.hasNextLine()) {
            String line = fileScanner.nextLine();
            //System.out.println(line);
        }
    }
    long end = new Date().getTime();

    long time = end - start;
    System.out.println("Scanner Time Consumed => " + time);

}


@Test
 public void testLargeFileIO_BufferedReader() throws Exception {

    long start = new Date().getTime();

    String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
    try (BufferedReader fileBufferReader = new BufferedReader(new FileReader(fileName))) {
        String fileLineContent;
        while ((fileLineContent = fileBufferReader.readLine()) != null) {
            //System.out.println(fileLineContent);
        }
    }
    long end = new Date().getTime();

    long time = (long) (end - start);
    System.out.println("BufferedReader Time Consumed => " + time);

}


@Test
public void testLargeFileIO_Stream() throws Exception {

    long start = new Date().getTime();

    String fileName = "/Downloads/SampleTextFile_1000kb.txt"; //this path is on my local
    try (Stream inputStream = Files.lines(Paths.get(fileName), StandardCharsets.UTF_8)) {
        //inputStream.forEach(System.out::println);
    }
    long end = new Date().getTime();

    long time = end - start;
    System.out.println("Stream Time Consumed => " + time);

}

Self Join to get employee manager name

try this ..you should do LEFT JOIN to igore null values in the table

SELECT a.emp_Id EmployeeId, a.emp_name EmployeeName,  
       a.emp_mgr_id ManagerId, b.emp_name AS ManagerName 
FROM   tblEmployeeDetails a 
       LEFT JOIN tblEmployeeDetails b
       ON b.emp_mgr_id = b.emp_id

How to redirect verbose garbage collection output to a file?

To add to the above answers, there's a good article: Useful JVM Flags – Part 8 (GC Logging) by Patrick Peschlow.

A brief excerpt:

The flag -XX:+PrintGC (or the alias -verbose:gc) activates the “simple” GC logging mode

By default the GC log is written to stdout. With -Xloggc:<file> we may instead specify an output file. Note that this flag implicitly sets -XX:+PrintGC and -XX:+PrintGCTimeStamps as well.

If we use -XX:+PrintGCDetails instead of -XX:+PrintGC, we activate the “detailed” GC logging mode which differs depending on the GC algorithm used.

With -XX:+PrintGCTimeStamps a timestamp reflecting the real time passed in seconds since JVM start is added to every line.

If we specify -XX:+PrintGCDateStamps each line starts with the absolute date and time.

How to resize an Image C#

This will perform a high quality resize:

/// <summary>
/// Resize the image to the specified width and height.
/// </summary>
/// <param name="image">The image to resize.</param>
/// <param name="width">The width to resize to.</param>
/// <param name="height">The height to resize to.</param>
/// <returns>The resized image.</returns>
public static Bitmap ResizeImage(Image image, int width, int height)
{
    var destRect = new Rectangle(0, 0, width, height);
    var destImage = new Bitmap(width, height);

    destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

    using (var graphics = Graphics.FromImage(destImage))
    {
        graphics.CompositingMode = CompositingMode.SourceCopy;
        graphics.CompositingQuality = CompositingQuality.HighQuality;
        graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
        graphics.SmoothingMode = SmoothingMode.HighQuality;
        graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

        using (var wrapMode = new ImageAttributes())
        {
            wrapMode.SetWrapMode(WrapMode.TileFlipXY);
            graphics.DrawImage(image, destRect, 0, 0, image.Width,image.Height, GraphicsUnit.Pixel, wrapMode);
        }
    }

    return destImage;
}
  • wrapMode.SetWrapMode(WrapMode.TileFlipXY) prevents ghosting around the image borders -- naïve resizing will sample transparent pixels beyond the image boundaries, but by mirroring the image we can get a better sample (this setting is very noticeable)
  • destImage.SetResolution maintains DPI regardless of physical size -- may increase quality when reducing image dimensions or when printing
  • Compositing controls how pixels are blended with the background -- might not be needed since we're only drawing one thing.
  • graphics.InterpolationMode determines how intermediate values between two endpoints are calculated
  • graphics.SmoothingMode specifies whether lines, curves, and the edges of filled areas use smoothing (also called antialiasing) -- probably only works on vectors
  • graphics.PixelOffsetMode affects rendering quality when drawing the new image

Maintaining aspect ratio is left as an exercise for the reader (actually, I just don't think it's this function's job to do that for you).

Also, this is a good article describing some of the pitfalls with image resizing. The above function will cover most of them, but you still have to worry about saving.

How to instantiate a javascript class in another js file?

If you are using javascript in HTML, you should include file1.js and file2.js inside your html:

<script src="path_to/file1.js"></script>
<script src="path_to/file2.js"></script>

Note, file1 should come first before file2.

Delete last N characters from field in a SQL Server database

I got the answer to my own question, ant this is:

select reverse(stuff(reverse('a,b,c,d,'), 1, N, ''))

Where N is the number of characters to remove. This avoids to write the complex column/string twice

Redirect to Action in another controller

Use this:

    return this.RedirectToAction<AccountController>(m => m.LogIn());

Beautiful way to remove GET-variables with PHP?

How about a function to rewrite the query string by looping through the $_GET array

! Rough outline of a suitable function

function query_string_exclude($exclude, $subject = $_GET, $array_prefix=''){
   $query_params = array;
   foreach($subject as $key=>$var){
      if(!in_array($key,$exclude)){
         if(is_array($var)){ //recursive call into sub array
            $query_params[]  = query_string_exclude($exclude, $var, $array_prefix.'['.$key.']');
         }else{
            $query_params[] = (!empty($array_prefix)?$array_prefix.'['.$key.']':$key).'='.$var;
         }
      }
   }

   return implode('&',$query_params);
}

Something like this would be good to keep handy for pagination links etc.

<a href="?p=3&<?= query_string_exclude(array('p')) ?>" title="Click for page 3">Page 3</a>

Golang append an item to a slice

Try this, which I think makes it clear. the underlying array is changed but our slice is not, print just prints len() chars, by another slice to the cap(), you can see the changed array:

func main() {

  for i := 0; i < 7; i++ {
      a[i] = i
  }

  Test(a)

  fmt.Println(a) // prints [0..6]
  fmt.Println(a[:cap(a)] // prints [0..6,100]
}

Change status bar color with AppCompat ActionBarActivity

There are various ways of changing the status bar color.

1) Using the styles.xml. You can use the android:statusBarColor attribute to do this the easy but static way.

Note: You can also use this attribute with the Material theme.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>
</resources>

2) You can get it done dynamically using the setStatusBarColor(int) method in the Window class. But remember that this method is only available for API 21 or higher. So be sure to check that, or your app will surely crash in lower devices.

Here is a working example of this method.

if (Build.VERSION.SDK_INT >= 21) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.setStatusBarColor(getResources().getColor(R.color.primaryDark));
}

where primaryDark is the 700 tint of the primary color I am using in my app. You can define this color in the colors.xml file.

Do give it a try and let me know if you have any questions. Hope it helps.

Is there any difference between GROUP BY and DISTINCT

I know it's an old post. But it happens that I had a query that used group by just to return distinct values when using that query in toad and oracle reports everything worked fine, I mean a good response time. When we migrated from Oracle 9i to 11g the response time in Toad was excellent but in the reporte it took about 35 minutes to finish the report when using previous version it took about 5 minutes.

The solution was to change the group by and use DISTINCT and now the report runs in about 30 secs.

I hope this is useful for someone with the same situation.

c# - How to get sum of the values from List?

How about this?

List<string> monValues = Application["mondayValues"] as List<string>;
int sum = monValues.ConvertAll(Convert.ToInt32).Sum();

How to zip a whole folder using PHP

For anyone reading this post and looking for a why to zip the files using addFile instead of addFromString, that does not zip the files with their absolute path (just zips the files and nothing else), see my question and answer here

How to overplot a line on a scatter plot in python?

plt.plot(X_plot, X_plot*results.params[0] + results.params[1])

versus

plt.plot(X_plot, X_plot*results.params[1] + results.params[0])

Bootstrap 3 select input form inline

I know this is a bit old, but I had the same problem and my search brought me here. I wanted two select elements and a button all inline, which worked in 2 but not 3. I ended up wrapping the three elements in <form class="form-inline">...</form>. This actually worked perfectly for me.

how to get right offset of an element? - jQuery

Brendon Crawford had the best answer here (in comment), so I'll move it to an answer until he does (and maybe expand a little).

var offset = $('#whatever').offset();

offset.right = $(window).width() - (offset.left + $('#whatever').outerWidth(true));
offset.bottom = $(window).height() - (offset.top + $('#whatever').outerHeight(true));

Building a complete online payment gateway like Paypal

Big task, chances are you shouldn't reinvent the wheel rather using an existing wheel (such as paypal).

However, if you insist on continuing. Start small, you can use a credit card processing facility (Moneris, Authorize.NET) to process credit cards. Most providers have an API you can use. Be wary that you may need to use different providers depending on the card type (Discover, Visa, Amex, Mastercard) and Country (USA, Canada, UK). So build it so that you can communicate with multiple credit card processing APIs.

Security is essential if you are storing credit cards and payment details. Ensure that you are encrypting things properly.

Again, don't reinvent the wheel. You are better off using an existing provider and focussing your development attention on solving an problem that can't easily be purchase.

How to concatenate items in a list to a single string?

We can also use Python's reduce function:

from functools import reduce

sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)

Where is git.exe located?

If you've downloaded the latest version try looking in the CMD folder. git.exe should be in there and should work. You may have to input it's path manually with File>Settings>Version Control>Git

Mean Squared Error in Numpy?

Even more numpy

np.square(np.subtract(A, B)).mean()

Hour from DateTime? in 24 hours format

Try this, if your input is string 
For example 

string input= "13:01";
string[] arry = input.Split(':');                  
string timeinput = arry[0] + arry[1];
private string Convert24To12HourInEnglish(string timeinput)

 {

DateTime startTime = new DateTime(2018, 1, 1, int.Parse(timeinput.Substring(0, 2)), 
int.Parse(timeinput.Substring(2, 2)), 0); 
return startTime.ToString("hh:mm tt");

}
out put: 01:01

How do I set proxy for chrome in python webdriver?

This worked for me like a charm:

proxy = "localhost:8080"
desired_capabilities = webdriver.DesiredCapabilities.CHROME.copy()
desired_capabilities['proxy'] = {
    "httpProxy": proxy,
    "ftpProxy": proxy,
    "sslProxy": proxy,
    "noProxy": None,
    "proxyType": "MANUAL",
    "class": "org.openqa.selenium.Proxy",
    "autodetect": False
}

How do I perform a GROUP BY on an aliased column in MS-SQL Server?

You pass the expression you want to group by rather than the alias

SELECT       LastName + ', ' + FirstName AS 'FullName'
FROM         customers
GROUP BY      LastName + ', ' + FirstName

Class file has wrong version 52.0, should be 50.0

If you are using javac to compile, and you get this error, then remove all the .class files

rm *.class     # On Unix-based systems

and recompile.

javac fileName.java

Make the console wait for a user input to close

I'd like to add that usually you'll want the program to wait only if it's connected to a console. Otherwise (like if it's a part of a pipeline) there is no point printing a message or waiting. For that you could use Java's Console like this:

import java.io.Console;
// ...
public static void waitForEnter(String message, Object... args) {
    Console c = System.console();
    if (c != null) {
        // printf-like arguments
        if (message != null)
            c.format(message, args);
        c.format("\nPress ENTER to proceed.\n");
        c.readLine();
    }
}

How to show first commit by 'git log'?

Short answer

git rev-list --max-parents=0 HEAD

(from tiho's comment. As Chris Johnsen notices, --max-parents was introduced after this answer was posted.)

Explanation

Technically, there may be more than one root commit. This happens when multiple previously independent histories are merged together. It is common when a project is integrated via a subtree merge.

The git.git repository has six root commits in its history graph (one each for Linus’s initial commit, gitk, some initially separate tools, git-gui, gitweb, and git-p4). In this case, we know that e83c516 is the one we are probably interested in. It is both the earliest commit and a root commit.

It is not so simple in the general case.

Imagine that libfoo has been in development for a while and keeps its history in a Git repository (libfoo.git). Independently, the “bar” project has also been under development (in bar.git), but not for as long libfoo (the commit with the earliest date in libfoo.git has a date that precedes the commit with the earliest date in bar.git). At some point the developers of “bar” decide to incorporate libfoo into their project by using a subtree merge. Prior to this merge it might have been trivial to determine the “first” commit in bar.git (there was probably only one root commit). After the merge, however, there are multiple root commits and the earliest root commit actually comes from the history of libfoo, not “bar”.

You can find all the root commits of the history DAG like this:

git rev-list --max-parents=0 HEAD

For the record, if --max-parents weren't available, this does also work:

git rev-list --parents HEAD | egrep "^[a-f0-9]{40}$"

If you have useful tags in place, then git name-rev might give you a quick overview of the history:

git rev-list --parents HEAD | egrep "^[a-f0-9]{40}$" | git name-rev --stdin

Bonus

Use this often? Hard to remember? Add a git alias for quick access

git config --global alias.first "rev-list --max-parents=0 HEAD"

Now you can simply do

git first

sql delete statement where date is greater than 30 days

GETDATE() didn't work for me using mySQL 8

ERROR 1305 (42000): FUNCTION mydatabase.GETDATE does not exist

but this does:

DELETE FROM table_name WHERE date_column < CURRENT_DATE - 30;

Warning about SSL connection when connecting to MySQL database

Since I am currently in development mode I set useSSL to No not in tomcat but in mysql server configurations. Went to Manage Access Settings\Manage Server Connections from workbench -> Selected my connection. Inside connection tab went to SSL tab and disabled the settings. Worked for me.

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

How do I print the full value of a long string in gdb?

Using set elements ... isn't always the best way. It would be useful if there were a distinct set string-elements ....

So, I use these functions in my .gdbinit:

define pstr
  ptype $arg0._M_dataplus._M_p
  printf "[%d] = %s\n", $arg0._M_string_length, $arg0._M_dataplus._M_p
end

define pcstr
  ptype $arg0
  printf "[%d] = %s\n", strlen($arg0), $arg0
end

Caveats:

  • The first is c++ lib dependent as it accesses members of std::string, but is easily adjusted.
  • The second can only be used on a running program as it calls strlen.

Android: How do bluetooth UUIDs work?

To sum up: UUid is used to uniquely identify applications. Each application has a unique UUid

So, use the same UUid for each device

Android studio: emulator is running but not showing up in Run App "choose a running device"

Your adb connection is broken.

close eclipse

open cmd-prompt type adb kill-server then adb start-server

reopen eclipse

run the project!

Add back button to action bar

Use this to show back button and move to previous activity,

final ActionBar actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeAsUpIndicator(R.drawable.back_dark);


@Override
    public boolean onOptionsItemSelected(final MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

How to drop columns using Rails migration

In a rails4 app it is possible to use the change method also for removing columns. The third param is the data_type and in the optional forth you can give options. It is a bit hidden in the section 'Available transformations' on the documentation .

class RemoveFieldFromTableName < ActiveRecord::Migration
  def change
    remove_column :table_name, :field_name, :data_type, {}
  end
end

Watch multiple $scope attributes

Angular introduced $watchGroup in version 1.3 using which we can watch multiple variables, with a single $watchGroup block $watchGroup takes array as first parameter in which we can include all of our variables to watch.

$scope.$watchGroup(['var1','var2'],function(newVals,oldVals){
   console.log("new value of var1 = " newVals[0]);
   console.log("new value of var2 = " newVals[1]);
   console.log("old value of var1 = " oldVals[0]);
   console.log("old value of var2 = " oldVals[1]);
});

Found conflicts between different versions of the same dependent assembly that could not be resolved

I had this warning after migrating to Package Reference. In diagnostic output there was information that library was referenced by the same library itself. It might be a bug of new Package Reference. The solution was to enable AutoGenerateBindingRedirects and delete custom binding redirect.

Serial Port (RS -232) Connection in C++

Please take a look here:

1) You can use this with Windows (incl. MinGW) as well as Linux. Alternative you can only use the code as an example.

2) Step-by-step tutorial how to use serial ports on windows

3) You can use this literally on MinGW

Here's some very, very simple code (without any error handling or settings):

#include <windows.h>

/* ... */


// Open serial port
HANDLE serialHandle;

serialHandle = CreateFile("\\\\.\\COM1", GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

// Do some basic settings
DCB serialParams = { 0 };
serialParams.DCBlength = sizeof(serialParams);

GetCommState(serialHandle, &serialParams);
serialParams.BaudRate = baudrate;
serialParams.ByteSize = byteSize;
serialParams.StopBits = stopBits;
serialParams.Parity = parity;
SetCommState(serialHandle, &serialParams);

// Set timeouts
COMMTIMEOUTS timeout = { 0 };
timeout.ReadIntervalTimeout = 50;
timeout.ReadTotalTimeoutConstant = 50;
timeout.ReadTotalTimeoutMultiplier = 50;
timeout.WriteTotalTimeoutConstant = 50;
timeout.WriteTotalTimeoutMultiplier = 10;

SetCommTimeouts(serialHandle, &timeout);

Now you can use WriteFile() / ReadFile() to write / read bytes. Don't forget to close your connection:

CloseHandle(serialHandle);

How can I check if a file exists in Perl?

if (-e $base_path)
{ 
 # code
}

-e is the 'existence' operator in Perl.

You can check permissions and other attributes using the code on this page.

How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

Null must not be set to string...

$this->db->where('archived IS NOT', null);

It works properly when null is not wrapped into quotes.

Room persistance library. Delete all

You can create a DAO method to do this.

@Dao 
interface MyDao {
    @Query("DELETE FROM myTableName")
    public void nukeTable();
}

Is it ok to scrape data from Google results?

Google disallows automated access in their TOS, so if you accept their terms you would break them.

That said, I know of no lawsuit from Google against a scraper. Even Microsoft scraped Google, they powered their search engine Bing with it. They got caught in 2011 red handed :)

There are two options to scrape Google results:

1) Use their API

UPDATE 2020: Google has reprecated previous APIs (again) and has new prices and new limits. Now (https://developers.google.com/custom-search/v1/overview) you can query up to 10k results per day at 1,500 USD per month, more than that is not permitted and the results are not what they display in normal searches.

  • You can issue around 40 requests per hour You are limited to what they give you, it's not really useful if you want to track ranking positions or what a real user would see. That's something you are not allowed to gather.

  • If you want a higher amount of API requests you need to pay.

  • 60 requests per hour cost 2000 USD per year, more queries require a custom deal.

2) Scrape the normal result pages

  • Here comes the tricky part. It is possible to scrape the normal result pages. Google does not allow it.
  • If you scrape at a rate higher than 8 (updated from 15) keyword requests per hour you risk detection, higher than 10/h (updated from 20) will get you blocked from my experience.
  • By using multiple IPs you can up the rate, so with 100 IP addresses you can scrape up to 1000 requests per hour. (24k a day) (updated)
  • There is an open source search engine scraper written in PHP at http://scraping.compunect.com It allows to reliable scrape Google, parses the results properly and manages IP addresses, delays, etc. So if you can use PHP it's a nice kickstart, otherwise the code will still be useful to learn how it is done.

3) Alternatively use a scraping service (updated)

  • Recently a customer of mine had a huge search engine scraping requirement but it was not 'ongoing', it's more like one huge refresh per month.
    In this case I could not find a self-made solution that's 'economic'.
    I used the service at http://scraping.services instead. They also provide open source code and so far it's running well (several thousand resultpages per hour during the refreshes)
  • The downside is that such a service means that your solution is "bound" to one professional supplier, the upside is that it was a lot cheaper than the other options I evaluated (and faster in our case)
  • One option to reduce the dependency on one company is to make two approaches at the same time. Using the scraping service as primary source of data and falling back to a proxy based solution like described at 2) when required.

Custom li list-style with font-awesome icon

I did two things inspired by @OscarJovanny comment, with some hacks.

Step 1:

  • Download icons file as svg from Here, as I only need only this icon from font awesome

Step 2:

<style>
ul {
    list-style-type: none;
    margin-left: 10px;
}

ul li {
    margin-bottom: 12px;
    margin-left: -10px;
    display: flex;
    align-items: center;
}

ul li::before {
    color: transparent;
    font-size: 1px;
    content: " ";
    margin-left: -1.3em;
    margin-right: 15px;
    padding: 10px;
    background-color: orange;
    -webkit-mask-image: url("./assets/img/check-circle-solid.svg");
    -webkit-mask-size: cover;
}
</style>

Results

enter image description here

How to get correlation of two vectors in python

The docs indicate that numpy.correlate is not what you are looking for:

numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
  Cross-correlation of two 1-dimensional sequences.
  This function computes the correlation as generally defined in signal processing texts:
     z[k] = sum_n a[n] * conj(v[n+k])
  with a and v sequences being zero-padded where necessary and conj being the conjugate.

Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:

from scipy.stats.stats import pearsonr   
a = [1,4,6]
b = [1,2,3]   
print pearsonr(a,b)

This gives

(0.99339926779878274, 0.073186395040328034)

You can also use numpy.corrcoef:

import numpy
print numpy.corrcoef(a,b)

This gives:

[[ 1.          0.99339927]
 [ 0.99339927  1.        ]]

How to check list A contains any value from list B?

You can Intersect the two lists:

if (A.Intersect(B).Any())

BASH Syntax error near unexpected token 'done'

What is the error you're getting?

$ bash file.sh
test.sh: line 8: syntax error: unexpected end of file

If you get that error, you may have bad line endings. Unix uses <LF> at the end of the file while Windows uses <CR><LF>. That <CR> character gets interpreted as a character.

You can use od -a test.sh to see the invisible characters in the file.

$ od -a test.sh
0000000    #   !   /   b   i   n   /   b   a   s   h  cr  nl   #  sp  cr
0000020   nl   w   h   i   l   e  sp   :  cr  nl   d   o  cr  nl  sp  sp
0000040   sp  sp   e   c   h   o  sp   "   P   r   e   s   s  sp   [   C
0000060    T   R   L   +   C   ]  sp   t   o  sp   s   t   o   p   "  cr
0000100   nl  sp  sp  sp  sp   s   l   e   e   p  sp   1  cr  nl   d   o
0000120    n   e  cr  nl                                                
0000124

The sp stands for space, the ht stands for tab, the cr stands for <CR> and the nl stands for <LF>. Note that all of the lines end with cr followed by a nl character.

You can also use cat -v test.sh if your cat command takes the -v parameter.

If you have dos2unix on your box, you can use that command to fix your file:

$ dos2unix test.sh

how does int main() and void main() work

Neither main() or void main() are standard C. The former is allowed as it has an implicit int return value, making it the same as int main(). The purpose of main's return value is to return an exit status to the operating system.

In standard C, the only valid signatures for main are:

int main(void)

and

int main(int argc, char **argv)

The form you're using: int main() is an old style declaration that indicates main takes an unspecified number of arguments. Don't use it - choose one of those above.

Automatic HTTPS connection/redirect with node.js/express

var express = require('express');
var app = express();

app.get('*',function (req, res) {
    res.redirect('https://<domain>' + req.url);
});

app.listen(80);

This is what we use and it works great!

Set inputType for an EditText Programmatically?

Try adding this to the EditText/TextView tag in your layout

android:password="true"

Edit: I just re-read your post, perhaps you need to do this after construction. I don't see why your snippet wouldn't work.

Package Manager Console Enable-Migrations CommandNotFoundException only in a specific VS project

In VS 2013, try to install the UPDATE 1(RC1) and the problem is resolved.

How to Find Item in Dictionary Collection?

It's possible to find the element in Dictionary collection by using ContainsKey or TryGetValue as follows:

class Program
{
    protected static Dictionary<string, string> _tags = new Dictionary<string,string>();

    static void Main(string[] args)
    {
        string strValue;

        _tags.Add("101", "C#");
        _tags.Add("102", "ASP.NET");

        if (_tags.ContainsKey("101"))
        {
            strValue = _tags["101"];
            Console.WriteLine(strValue);
        }

        if (_tags.TryGetValue("101", out strValue))
        {
            Console.WriteLine(strValue);
        }
    }
}

Get month name from date in Oracle

to_char(mydate, 'MONTH') will do the job.

How to get exact browser name and version?

I have created a function in PHP language to get browser name, browser version, operating system (windows/linux etc.) along with device type (desktop / mobile / tablet).

function getBrowserInfo(){
    $browserInfo = array('user_agent'=>'','browser'=>'','browser_version'=>'','os_platform'=>'','pattern'=>'', 'device'=>'');

    $u_agent = $_SERVER['HTTP_USER_AGENT']; 
    $bname = 'Unknown';
    $ub = 'Unknown';
    $version = "";
    $platform = 'Unknown';

    $deviceType='Desktop';

    if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i',$u_agent)||preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i',substr($u_agent,0,4))){

        $deviceType='Mobile';

    }

    if($_SERVER['HTTP_USER_AGENT'] == 'Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10') {
        $deviceType='Tablet';
    }

    if(stristr($_SERVER['HTTP_USER_AGENT'], 'Mozilla/5.0(iPad;')) {
        $deviceType='Tablet';
    }

    //$detect = new Mobile_Detect();
    
    //First get the platform?
    if (preg_match('/linux/i', $u_agent)) {
        $platform = 'linux';

    } elseif (preg_match('/macintosh|mac os x/i', $u_agent)) {
        $platform = 'mac';

    } elseif (preg_match('/windows|win32/i', $u_agent)) {
        $platform = 'windows';
    }

    // Next get the name of the user agent yes seperately and for good reason
    if(preg_match('/MSIE/i',$u_agent) && !preg_match('/Opera/i',$u_agent)) 
    { 
        $bname = 'IE'; 
        $ub = "MSIE";

    } else if(preg_match('/Firefox/i',$u_agent))
    { 
        $bname = 'Mozilla Firefox'; 
        $ub = "Firefox"; 

    } else if(preg_match('/Chrome/i',$u_agent) && (!preg_match('/Opera/i',$u_agent) && !preg_match('/OPR/i',$u_agent))) 
    { 
        $bname = 'Chrome'; 
        $ub = "Chrome"; 

    } else if(preg_match('/Safari/i',$u_agent) && (!preg_match('/Opera/i',$u_agent) && !preg_match('/OPR/i',$u_agent))) 
    { 
        $bname = 'Safari'; 
        $ub = "Safari"; 

    } else if(preg_match('/Opera/i',$u_agent) || preg_match('/OPR/i',$u_agent)) 
    { 
        $bname = 'Opera'; 
        $ub = "Opera"; 

    } else if(preg_match('/Netscape/i',$u_agent)) 
    { 
        $bname = 'Netscape'; 
        $ub = "Netscape"; 

    } else if((isset($u_agent) && (strpos($u_agent, 'Trident') !== false || strpos($u_agent, 'MSIE') !== false)))
    {
        $bname = 'Internet Explorer'; 
        $ub = 'Internet Explorer'; 
    } 
    

    // finally get the correct version number
    $known = array('Version', $ub, 'other');
    $pattern = '#(?<browser>' . join('|', $known) . ')[/ ]+(?<version>[0-9.|a-zA-Z.]*)#';

    if (!preg_match_all($pattern, $u_agent, $matches)) {
        // we have no matching number just continue
    }

    // see how many we have
    $i = count($matches['browser']);
    if ($i != 1) {
        //we will have two since we are not using 'other' argument yet
        //see if version is before or after the name
        if (strripos($u_agent,"Version") < strripos($u_agent,$ub)){
            $version= $matches['version'][0];

        } else {
            $version= @$matches['version'][1];
        }

    } else {
        $version= $matches['version'][0];
    }

    // check if we have a number
    if ($version==null || $version=="") {$version="?";}

    return array(
        'user_agent' => $u_agent,
        'browser'      => $bname,
        'browser_version'   => $version,
        'os_platform'  => $platform,
        'pattern'   => $pattern,
        'device'    => $deviceType
    );
}

This solved my problem of browser detection, I hope, this will also help you. Thank you.

How to create and download a csv file from php script?

Try... csv download.

<?php 
mysql_connect('hostname', 'username', 'password');
mysql_select_db('dbname');
$qry = mysql_query("SELECT * FROM tablename");
$data = "";
while($row = mysql_fetch_array($qry)) {
  $data .= $row['field1'].",".$row['field2'].",".$row['field3'].",".$row['field4']."\n";
}

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="filename.csv"');
echo $data; exit();
?>

jQuery - prevent default, then continue default

"Validation injection without submit looping":

I just want to check reCaptcha and some other stuff before HTML5 validation, so I did something like that (the validation function returns true or false):

$(document).ready(function(){
   var application_form = $('form#application-form');

   application_form.on('submit',function(e){

        if(application_form_extra_validation()===true){
           return true;
        }

        e.preventDefault();

   });
});

Looping through all rows in a table column, Excel-VBA

Assuming your table is called "Table1" and your column is called "Column1" then:

For i = 1 To ListObjects("Table1").ListRows.Count
    ListObjects("Table1").ListColumns("Column1").DataBodyRange(i) = "PHEV"
Next i

How to change workspace and build record Root Directory on Jenkins?

EDIT: Per other comments, the "Advanced..." button appears to have been removed in more recent versions of Jenkins. If your version doesn't have it, see knorx's answer.

I had the same problem, and even after finding this old pull request I still had trouble finding where to specify the Workspace Root Directory or Build Record Root Directory at the system level, versus specifying a custom workspace for each job.

To set these:

  1. Navigate to Jenkins -> Manage Jenkins -> Configure System
  2. Right at the top, under Home directory, click the Advanced... button: advanced button under Home directory
  3. Now the fields for Workspace Root Directory and Build Record Root Directory appear: additional directory options
  4. The information that appears if you click the help bubbles to the left of each option is very instructive. In particular (from the Workspace Root Directory help):

    This value may include the following variables:

    • ${JENKINS_HOME} — Absolute path of the Jenkins home directory
    • ${ITEM_ROOTDIR} — Absolute path of the directory where Jenkins stores the configuration and related metadata for a given job
    • ${ITEM_FULL_NAME} — The full name of a given job, which may be slash-separated, e.g. foo/bar for the job bar in folder foo


    The value should normally include ${ITEM_ROOTDIR} or ${ITEM_FULL_NAME}, otherwise different jobs will end up sharing the same workspace.

What is the purpose of willSet and didSet in Swift?

The willSet and didSet observers for the properties whenever the property is assigned a new value. This is true even if the new value is the same as the current value.

And note that willSet needs a parameter name to work around, on the other hand, didSet does not.

The didSet observer is called after the value of property is updated. It compares against the old value. If the total number of steps has increased, a message is printed to indicate how many new steps have been taken. The didSet observer does not provide a custom parameter name for the old value, and the default name of oldValue is used instead.

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

This code worked for me

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserDetail>()
            .HasRequired(d => d.User)
            .WithOptional(u => u.UserDetail)
            .WillCascadeOnDelete(true);
    }

The migration code was:

public override void Up()
    {
        AddForeignKey("UserDetail", "UserId", "User", "UserId", cascadeDelete: true);
    }

And it worked fine. When I first used

modelBuilder.Entity<User>()
    .HasOptional(a => a.UserDetail)
    .WithOptionalDependent()
    .WillCascadeOnDelete(true);

The migration code was:

AddForeignKey("User", "UserDetail_UserId", "UserDetail", "UserId", cascadeDelete: true); 

but it does not match any of the two overloads available (in EntityFramework 6)

Data truncated for column?

However I get an error which doesn't make sense seeing as the column's data type was properly modified?

| Level | Code | Msg | Warn | 12 | Data truncated for column 'incoming_Cid' at row 1

You can often get this message when you are doing something like the following:

REPLACE INTO table2 (SELECT * FROM table1);

Resulted in our case in the following error:

SQL Exception: Data truncated for column 'level' at row 1

The problem turned out to be column misalignment that resulted in a tinyint trying to be stored in a datetime field or vice versa.

remove table row with specific id

Try

$('table#test tr#3').remove();

How to move columns in a MySQL table?

Change column position:

ALTER TABLE Employees 
   CHANGE empName empName VARCHAR(50) NOT NULL AFTER department;

If you need to move it to the first position you have to use term FIRST at the end of ALTER TABLE CHANGE [COLUMN] query:

ALTER TABLE UserOrder 
   CHANGE order_id order_id INT(11) NOT NULL FIRST;

React JS get current date

Your problem is that you are naming your component class Date. When you call new Date() within your class, it won't create an instance of the Date you expect it to create (which is likely this Date)- it will try to create an instance of your component class. Then the constructor will try to create another instance, and another instance, and another instance... Until you run out of stack space and get the error you're seeing.

If you want to use Date within your class, try naming your class something different such as Calendar or DateComponent.

The reason for this is how JavaScript deals with name scope: Whenever you create a new named entity, if there is already an entity with that name in scope, that name will stop referring to the previous entity and start referring to your new entity. So if you use the name Date within a class named Date, the name Date will refer to that class and not to any object named Date which existed before the class definition started.

"Instantiating" a List in Java?

In Java, List is an interface. That is, it cannot be instantiated directly.

Instead you can use ArrayList which is an implementation of that interface that uses an array as its backing store (hence the name).

Since ArrayList is a kind of List, you can easily upcast it:

List<T> mylist = new ArrayList<T>();

This is in contrast with .NET, where, since version 2.0, List<T> is the default implementation of the IList<T> interface.

What is __future__ in Python used for and how/when to use it, and how it works

It can be used to use features which will appear in newer versions while having an older release of Python.

For example

>>> from __future__ import print_function

will allow you to use print as a function:

>>> print('# of entries', len(dictionary), file=sys.stderr)

Passing a varchar full of comma delimited values to a SQL Server IN function

CREATE TABLE t 
  ( 
     id   INT, 
     col1 VARCHAR(50) 
  ) 

INSERT INTO t 
VALUES     (1, 
            'param1') 

INSERT INTO t 
VALUES     (2, 
            'param2') 

INSERT INTO t 
VALUES     (3, 
            'param3') 

INSERT INTO t 
VALUES     (4, 
            'param4') 

INSERT INTO t 
VALUES     (5, 
            'param5') 

DECLARE @params VARCHAR(100) 

SET @params = ',param1,param2,param3,' 

SELECT * 
FROM   t 
WHERE  Charindex(',' + Cast(col1 AS VARCHAR(8000)) + ',', @params) > 0 

working fiddle find here Fiddle

DLL Load Library - Error Code 126

This error can happen because some MFC library (eg. mfc120.dll) from which the DLL is dependent is missing in windows/system32 folder.

What is the size of ActionBar in pixels?

To retrieve the height of the ActionBar in XML, just use

?android:attr/actionBarSize

or if you're an ActionBarSherlock or AppCompat user, use this

?attr/actionBarSize

If you need this value at runtime, use this

final TypedArray styledAttributes = getContext().getTheme().obtainStyledAttributes(
                    new int[] { android.R.attr.actionBarSize });
mActionBarSize = (int) styledAttributes.getDimension(0, 0);
styledAttributes.recycle();

If you need to understand where this is defined:

  1. The attribute name itself is defined in the platform's /res/values/attrs.xml
  2. The platform's themes.xml picks this attribute and assigns a value to it.
  3. The value assigned in step 2 depends on different device sizes, which are defined in various dimens.xml files in the platform, ie. core/res/res/values-sw600dp/dimens.xml

is it possible to add colors to python output?

If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.

Here an example:

print ('This is \x1b[31mred\x1b[0m.') 

Compiling with g++ using multiple cores

There is no such flag, and having one runs against the Unix philosophy of having each tool perform just one function and perform it well. Spawning compiler processes is conceptually the job of the build system. What you are probably looking for is the -j (jobs) flag to GNU make, a la

make -j4

Or you can use pmake or similar parallel make systems.

What is the difference between Scala's case class and class?

No one mentioned that case classes have val constructor parameters yet this is also the default for regular classes (which I think is an inconsistency in the design of Scala). Dario implied such where he noted they are "immutable".

Note you can override the default by prepending the each constructor argument with var for case classes. However, making case classes mutable causes their equals and hashCode methods to be time variant.[1]

sepp2k already mentioned that case classes automatically generate equals and hashCode methods.

Also no one mentioned that case classes automatically create a companion object with the same name as the class, which contains apply and unapply methods. The apply method enables constructing instances without prepending with new. The unapply extractor method enables the pattern matching that others mentioned.

Also the compiler optimizes the speed of match-case pattern matching for case classes[2].

[1] Case Classes Are Cool

[2] Case Classes and Extractors, pg 15.

django no such table:

I think maybe you can try

python manage.py syncdb

Even sqlite3 need syncdb

sencondly, you can check your sql file name

it should look like xxx.s3db

Add/remove HTML inside div using JavaScript

To remove node you can try this solution it helped me.

var rslt = (nodee=document.getElementById(id)).parentNode.removeChild(nodee);

Java collections maintaining insertion order

Depends on what you need the implementation to do well. Insertion order usually is not interesting so there is no need to maintain it so you can rearrange to get better performance.

For Maps it is usually HashMap and TreeMap that is used. By using hash codes, the entries can be put in small groups easy to search in. The TreeMap maintains a sorted order of the inserted entries at the cost of slower search, but easier to sort than a HashMap.

How do you make div elements display inline?

I think you can use this way without using any css -

<table>
    <tr>
        <td>foo</td>
    </tr>
    <tr>
        <td>bar</td>
    </tr>
    <tr>
        <td>baz</td>
    </tr>
</table>

Right now you are using block level element that way you are getting unwanted result. So you can you inline element like span, small etc.

<span>foo</span><span>bar</span><span>baz</span>

Which is the default location for keystore/truststore of Java applications?

In Java, according to the JSSE Reference Guide, there is no default for the keystore, the default for the truststore is "jssecacerts, if it exists. Otherwise, cacerts".

A few applications use ~/.keystore as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).

I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.

Check if number is decimal

if you want "10.00" to return true check Night Owl's answer

If you want to know if the decimals has a value you can use this answer.

Works with all kind of types (int, float, string)

if(fmod($val, 1) !== 0.00){
    // your code if its decimals has a value
} else {
    // your code if the decimals are .00, or is an integer
}

Examples:

(fmod(1.00,    1) !== 0.00)    // returns false
(fmod(2,       1) !== 0.00)    // returns false
(fmod(3.01,    1) !== 0.00)    // returns true
(fmod(4.33333, 1) !== 0.00)    // returns true
(fmod(5.00000, 1) !== 0.00)    // returns false
(fmod('6.50',  1) !== 0.00)    // returns true

Explanation:

fmod returns the floating point remainder (modulo) of the division of the arguments, (hence the (!== 0.00))

Modulus operator - why not use the modulus operator? E.g. ($val % 1 != 0)

From the PHP docs:

Operands of modulus are converted to integers (by stripping the decimal part) before processing.

Which will effectively destroys the op purpose, in other languages like javascript you can use the modulus operator

Make REST API call in Swift

You can do like this :

var url : String = "http://google.com?test=toto&test2=titi"
var request : NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue(), completionHandler:{ (response:NSURLResponse!, data: NSData!, error: NSError!) -> Void in
    var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
    let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary

    if (jsonResult != nil) {
        // process jsonResult
    } else {
       // couldn't load JSON, look at error
    }


})

EDIT : For people have problem with this maybe your JSON stream is an array [] and not an object {} so you have to change jsonResult to NSArray instead of NSDictionary

Printing image with PrintDocument. how to adjust the image to fit paper size

You can use my code here

//Print Button Event Handeler
private void btnPrint_Click(object sender, EventArgs e)
{
    PrintDocument pd = new PrintDocument();
    pd.PrintPage += PrintPage;
    //here to select the printer attached to user PC
    PrintDialog printDialog1 = new PrintDialog();
    printDialog1.Document = pd;
    DialogResult result = printDialog1.ShowDialog();
    if (result == DialogResult.OK)
    {
        pd.Print();//this will trigger the Print Event handeler PrintPage
    }
}

//The Print Event handeler
private void PrintPage(object o, PrintPageEventArgs e)
{
    try
    {
        if (File.Exists(this.ImagePath))
        {
            //Load the image from the file
            System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\myimage.jpg");

            //Adjust the size of the image to the page to print the full image without loosing any part of it
            Rectangle m = e.MarginBounds;

            if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
            {
                m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
            }
            else
            {
                m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
            }
            e.Graphics.DrawImage(img, m);
        }
    }
    catch (Exception)
    {

    }
}

$date + 1 year?

// Declare a variable for this year 
$this_year = date("Y");
// Add 1 to the variable
$next_year = $this_year + 1;
$year_after = $this_year + 2;

// Check your code
    echo "This year is ";
    echo $this_year;
    echo "<br />";
    echo "Next year is ";
    echo $next_year;
    echo "<br />";
    echo "The year after that is ";
    echo $year_after;

What does the ^ (XOR) operator do?

A little more information on XOR operation.

  • XOR a number with itself odd number of times the result is number itself.
  • XOR a number even number of times with itself, the result is 0.
  • Also XOR with 0 is always the number itself.

Extract digits from a string in Java

Using Google Guava:

CharMatcher.DIGIT.retainFrom("123-456-789");

CharMatcher is plug-able and quite interesting to use, for instance you can do the following:

String input = "My phone number is 123-456-789!";
String output = CharMatcher.is('-').or(CharMatcher.DIGIT).retainFrom(input);

output == 123-456-789

select count(*) from select

You're missing a FROM and you need to give the subquery an alias.

SELECT COUNT(*) FROM 
(
  SELECT DISTINCT a.my_id, a.last_name, a.first_name, b.temp_val
   FROM dbo.Table_A AS a 
   INNER JOIN dbo.Table_B AS b 
   ON a.a_id = b.a_id
) AS subquery;

UnicodeDecodeError when reading CSV file in Pandas with Python

In my case this worked for python 2.7:

data = read_csv(filename, encoding = "ISO-8859-1", dtype={'name_of_colum': unicode}, low_memory=False) 

And for python 3, only:

data = read_csv(filename, encoding = "ISO-8859-1", low_memory=False) 

sklearn plot confusion matrix with labels

from sklearn import model_selection
test_size = 0.33
seed = 7
X_train, X_test, y_train, y_test = model_selection.train_test_split(feature_vectors, y, test_size=test_size, random_state=seed)

from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix

model = LogisticRegression()
model.fit(X_train, y_train)
result = model.score(X_test, y_test)
print("Accuracy: %.3f%%" % (result*100.0))
y_pred = model.predict(X_test)
print("F1 Score: ", f1_score(y_test, y_pred, average="macro"))
print("Precision Score: ", precision_score(y_test, y_pred, average="macro"))
print("Recall Score: ", recall_score(y_test, y_pred, average="macro")) 

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix

def cm_analysis(y_true, y_pred, labels, ymap=None, figsize=(10,10)):
    """
    Generate matrix plot of confusion matrix with pretty annotations.
    The plot image is saved to disk.
    args: 
      y_true:    true label of the data, with shape (nsamples,)
      y_pred:    prediction of the data, with shape (nsamples,)
      filename:  filename of figure file to save
      labels:    string array, name the order of class labels in the confusion matrix.
                 use `clf.classes_` if using scikit-learn models.
                 with shape (nclass,).
      ymap:      dict: any -> string, length == nclass.
                 if not None, map the labels & ys to more understandable strings.
                 Caution: original y_true, y_pred and labels must align.
      figsize:   the size of the figure plotted.
    """
    if ymap is not None:
        y_pred = [ymap[yi] for yi in y_pred]
        y_true = [ymap[yi] for yi in y_true]
        labels = [ymap[yi] for yi in labels]
    cm = confusion_matrix(y_true, y_pred, labels=labels)
    cm_sum = np.sum(cm, axis=1, keepdims=True)
    cm_perc = cm / cm_sum.astype(float) * 100
    annot = np.empty_like(cm).astype(str)
    nrows, ncols = cm.shape
    for i in range(nrows):
        for j in range(ncols):
            c = cm[i, j]
            p = cm_perc[i, j]
            if i == j:
                s = cm_sum[i]
                annot[i, j] = '%.1f%%\n%d/%d' % (p, c, s)
            elif c == 0:
                annot[i, j] = ''
            else:
                annot[i, j] = '%.1f%%\n%d' % (p, c)
    cm = pd.DataFrame(cm, index=labels, columns=labels)
    cm.index.name = 'Actual'
    cm.columns.name = 'Predicted'
    fig, ax = plt.subplots(figsize=figsize)
    sns.heatmap(cm, annot=annot, fmt='', ax=ax)
    #plt.savefig(filename)
    plt.show()

cm_analysis(y_test, y_pred, model.classes_, ymap=None, figsize=(10,10))

enter image description here

using https://gist.github.com/hitvoice/36cf44689065ca9b927431546381a3f7

Note that if you use rocket_r it will reverse the colors and somehow it looks more natural and better such as below: enter image description here

Sending emails in Node.js?

@JimBastard's accepted answer appears to be dated, I had a look and that mailer lib hasn't been touched in over 7 months, has several bugs listed, and is no longer registered in npm.

nodemailer certainly looks like the best option, however the url provided in other answers on this thread are all 404'ing.

nodemailer claims to support easy plugins into gmail, hotmail, etc. and also has really beautiful documentation.

How to create a regex for accepting only alphanumeric characters?

Only ASCII or are other characters allowed too?

^\w*$

restricts (in Java) to ASCII letters/digits und underscore,

^[\pL\pN\p{Pc}]*$

also allows international characters/digits and "connecting punctuation".

How to parse XML using vba

You can use a XPath Query:

Dim objDom As Object        '// DOMDocument
Dim xmlStr As String, _
    xPath As String

xmlStr = _
    "<PointN xsi:type='typens:PointN' " & _
    "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " & _
    "xmlns:xs='http://www.w3.org/2001/XMLSchema'> " & _
    "    <X>24.365</X> " & _
    "    <Y>78.63</Y> " & _
    "</PointN>"

Set objDom = CreateObject("Msxml2.DOMDocument.3.0")     '// Using MSXML 3.0

'/* Load XML */
objDom.LoadXML xmlStr

'/*
' * XPath Query
' */        

'/* Get X */
xPath = "/PointN/X"
Debug.Print objDom.SelectSingleNode(xPath).text

'/* Get Y */
xPath = "/PointN/Y"
Debug.Print objDom.SelectSingleNode(xPath).text

add an onclick event to a div

Everythings works well. You can't use divtag.onclick, becease "onclick" attribute doesn't exist. You need first create this attribute by using .setAttribute(). Look on this http://reference.sitepoint.com/javascript/Element/setAttribute . You should read documentations first before you start giving "-".

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

After exiting eclipse I moved .eclipse (found in the user's home directory) to .eclipse.old (just in case I may have had to undo). The error does not show up any more and my projects are working fine after restarting eclipse.

Caution: I have a simple setup and this may not be the best for environments with advanced settings.

I am posting this as a separate answer as previously listed methods did not work for me.

Standard way to embed version into python package?

Per the deferred PEP 396 (Module Version Numbers), there is a proposed way to do this. It describes, with rationale, an (admittedly optional) standard for modules to follow. Here's a snippet:

3) When a module (or package) includes a version number, the version SHOULD be available in the __version__ attribute.

4) For modules which live inside a namespace package, the module SHOULD include the __version__ attribute. The namespace package itself SHOULD NOT include its own __version__ attribute.

5) The __version__ attribute's value SHOULD be a string.

Convert comma separated string of ints to int array

import java.util.*;
import java.io.*;
public class problem
{
public static void main(String args[])enter code here
{
  String line;
  String[] lineVector;
  int n,m,i,j;
  Scanner sc = new Scanner(System.in);
  line = sc.nextLine();
  lineVector = line.split(",");
  //enter the size of the array
  n=Integer.parseInt(lineVector[0]);
  m=Integer.parseInt(lineVector[1]);
  int arr[][]= new int[n][m];
  //enter the array here
  System.out.println("Enter the array:");
  for(i=0;i<n;i++)
  {
  line = sc.nextLine();
  lineVector = line.split(",");
  for(j=0;j<m;j++)
  {
  arr[i][j] = Integer.parseInt(lineVector[j]);
  }
  }
  sc.close();
}
}

On the first line enter the size of the array separated by a comma. Then enter the values in the array separated by a comma.The result is stored in the array arr. e.g input: 2,3 1,2,3 2,4,6 will store values as arr = {{1,2,3},{2,4,6}};

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

I was having the same problem. I tried

rm -f ./.git/index.lock 

and the console gave me an error message. Then, I tried

rm --force ./.git/index.lock

and that worked.

Good Luck! This works super

Repeat table headers in print mode

This is what the THEAD element is for. Official docs here.

Callback when DOM is loaded in react.js

Looks like a combination of componentDidMount and componentDidUpdate will get the job done. The first is called after the initial rendering, when the DOM is available, the second is called after any subsequent renderings, once the updated DOM is available. In my case, I both have them delegate to a common function to do the same thing.

Center a button in a Linear layout

You can also set the width of the LinearLayout to wrap_content and use android:layout_centerInParent, android:layout_centerVertical="true":

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
>

<ImageButton android:id="@+id/btnFindMe" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"       
    android:background="@drawable/findme"/>

How do I get the "id" after INSERT into MySQL database with Python?

SELECT @@IDENTITY AS 'Identity';

or

SELECT last_insert_id();

Am I trying to connect to a TLS-enabled daemon without TLS?

  1. Docker calls itself a self-sufficient runtime for Linux containers. In simple terms it acts both as server and client.
  2. The $ docker version command query is internal to the Docker executable and not to the daemon/service running.
  3. $ docker images or $ docker ps or $ docker pull centos are commands which send queries to the docker daemon/service running.
  4. Docker by default supports TLS connections to its daemon/service.
  5. Only if the user you are logged in as is part of user group docker or you have used sudo before the command, e.g. $ sudo docker images, does it not require TLS connectivity.

Visit Docker documentation page Protect the Docker daemon socket.

Scroll a little to the top and find warning section for clarity.

Using RegEx in SQL Server

A similar approach to @mwigdahl's answer, you can also implement a .NET CLR in C#, with code such as;

using System.Data.SqlTypes;
using RX = System.Text.RegularExpressions;

public partial class UserDefinedFunctions
{
 [Microsoft.SqlServer.Server.SqlFunction]
 public static SqlString Regex(string input, string regex)
 {
  var match = RX.Regex.Match(input, regex).Groups[1].Value;
  return new SqlString (match);
 }
}

Installation instructions can be found here

Elastic Search: how to see the indexed data

A tool that helps me a lot to debug ElasticSearch is ElasticHQ. Basically, it is an HTML file with some JavaScript. No need to install anywhere, let alone in ES itself: just download it, unzip int and open the HTML file with a browser.

Not sure it is the best tool for ES heavy users. Yet, it is really practical to whoever is in a hurry to see the entries.

Best way to convert strings to symbols in hash

Here's a way to deep symbolize an object

def symbolize(obj)
    return obj.inject({}){|memo,(k,v)| memo[k.to_sym] =  symbolize(v); memo} if obj.is_a? Hash
    return obj.inject([]){|memo,v    | memo           << symbolize(v); memo} if obj.is_a? Array
    return obj
end

Laravel 5 not finding css files

Simply you can put a back slash in front of your css link

"Unknown class <MyClass> in Interface Builder file" error at runtime

Not only in project settings, but in Target setting also u have to add -all_load -ObjC flags..

Core-Plot: Unknown class CPLayerHostingView in Interface Builder file

Quadratic and cubic regression in Excel

I know that this question is a little old, but I thought that I would provide an alternative which, in my opinion, might be a little easier. If you're willing to add "temporary" columns to a data set, you can use Excel's Analysis ToolPak?Data Analysis?Regression. The secret to doing a quadratic or a cubic regression analysis is defining the Input X Range:.

If you're doing a simple linear regression, all you need are 2 columns, X & Y. If you're doing a quadratic, you'll need X_1, X_2, & Y where X_1 is the x variable and X_2 is x^2; likewise, if you're doing a cubic, you'll need X_1, X_2, X_3, & Y where X_1 is the x variable, X_2 is x^2 and X_3 is x^3. Notice how the Input X Range is from A1 to B22, spanning 2 columns.

Input for Quadratic Regression Analysis in Excel

The following image the output of the regression analysis. I've highlighted the common outputs, including the R-Squared values and all the coefficients.

Coefficients of Quadratic Regression Analysis in Excel

How do I fix a merge conflict due to removal of a file in a branch?

If you are using Git Gui on windows,

  1. Abort the merge
  2. Make sure you are on your target branch
  3. Delete the conflicting file from explorer
  4. Rescan for changes in Git Gui (F5)
  5. Notice that conflicting file is deleted
  6. Select Stage Changed Files To Commit (Ctrl-I) from Commit menu
  7. Enter a commit comment like "deleted conflicting file"
  8. Commit (ctrl-enter)
  9. Now if you restart the merge it will (hopefully) work.

Get method arguments using Spring AOP?

Yes, the value of any argument can be found using getArgs

@Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))")
public void logBefore(JoinPoint joinPoint) {

   Object[] signatureArgs = thisJoinPoint.getArgs();
   for (Object signatureArg: signatureArgs) {
      System.out.println("Arg: " + signatureArg);
      ...
   }
}

Finding last index of a string in Oracle

Use -1 as the start position:

INSTR('JD-EQ-0001', '-', -1)

How can I define fieldset border color?

I added it for all fieldsets with

fieldset {
        border: 1px solid lightgray;
    }

I didnt work if I set it separately using for example

border-color : red

. Then a black line was drawn next to the red line.

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

Calculating powers of integers

import java.util.*;

public class Power {

    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        int num = 0;
        int pow = 0;
        int power = 0;

        System.out.print("Enter number: ");
        num = sc.nextInt();

        System.out.print("Enter power: ");
        pow = sc.nextInt();

        System.out.print(power(num,pow));
    }

    public static int power(int a, int b)
    {
        int power = 1;

        for(int c = 0; c < b; c++)
            power *= a;

        return power;
    }

}

Git - Ignore files during merge

.gitattributes - is a root-level file of your repository that defines the attributes for a subdirectory or subset of files.

You can specify the attribute to tell Git to use different merge strategies for a specific file. Here, we want to preserve the existing config.xml for our branch. We need to set the merge=foo to config.xml in .gitattributes file.

merge=foo tell git to use our(current branch) file, if a merge conflict occurs.

  1. Add a .gitattributes file at the root level of the repository

  2. You can set up an attribute for confix.xml in the .gitattributes file

     <pattern> merge=foo
    

    Let's take an example for config.xml

     config.xml merge=foo
    
  3. And then define a dummy foo merge strategy with:

     $ git config --global merge.foo.driver true
    

If you merge the stag form dev branch, instead of having the merge conflicts with the config.xml file, the stag branch's config.xml preserves at whatever version you originally had.

for more reference: merge_strategies

Ajax Upload image

Image upload using ajax and check image format and upload max size   

<form class='form-horizontal' method="POST"  id='document_form' enctype="multipart/form-data">
                                    <div class='optionBox1'>
                                        <div class='row inviteInputWrap1 block1'>
                                            <div class='col-3'>
                                                <label class='col-form-label'>Name</label>
                                                <input type='text' class='form-control form-control-sm' name='name[]' id='name' Value=''>
                                            </div>
                                            <div class='col-3'>
                                                <label class='col-form-label'>File</label>
                                                <input type='file' class='form-control form-control-sm' name='file[]' id='file' Value=''>
                                            </div>
                                            <div class='col-3'>
                                                <span class='deleteInviteWrap1 remove1 d-none'>
                                                    <i class='fas fa-trash'></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class='row'>
                                             <div class='col-8 pl-3 pb-4 mt-4'>
                                                <span class='btn btn-info add1 pr-3'>+ Add More</span>
                                                 <button class='btn btn-primary'>Submit</button> 
                                            </div>
                                        </div>
                                    </div>
                                    </form>     
                                    
                                    </div>  
                      
    
      $.validator.setDefaults({
       submitHandler: function (form) 
         {
               $.ajax({
                    url : "action1.php",
                    type : "POST",
                    data : new FormData(form),
                    mimeType: "multipart/form-data",
                    contentType: false,
                    cache: false,
                    dataType:'json',
                    processData: false,
                    success: function(data)
                    {
                        if(data.status =='success')
                            {
                                 swal("Document has been successfully uploaded!", {
                                    icon: "success",
                                 });
                                 setTimeout(function(){
                                    window.location.reload(); 
                                },1200);
                            }
                            else
                            {
                                swal('Oh noes!', "Error in document upload. Please contact to administrator", "error");
                            }   
                    },
                    error:function(data)
                    {
                        swal ( "Ops!" ,  "error in document upload." ,  "error" );
                    }
                });
            }
      });
    
      $('#document_form').validate({
        rules: {
            "name[]": {
              required: true
          },
          "file[]": {
              required: true,
              extension: "jpg,jpeg,png,pdf,doc",
              filesize :2000000 
          }
        },
        messages: {
            "name[]": {
            required: "Please enter name"
          },
          "file[]": {
            required: "Please enter file",
            extension :'Please upload only jpg,jpeg,png,pdf,doc'
          }
        },
        errorElement: 'span',
        errorPlacement: function (error, element) {
          error.addClass('invalid-feedback');
          element.closest('.col-3').append(error);
        },
        highlight: function (element, errorClass, validClass) {
          $(element).addClass('is-invalid');
        },
        unhighlight: function (element, errorClass, validClass) {
          $(element).removeClass('is-invalid');
        }
      });
    
      $.validator.addMethod('filesize', function(value, element, param) {
         return this.optional(element) || (element.files[0].size <= param)
        }, 'File size must be less than 2 MB');

How do I tell if an object is a Promise?

Checking if something is promise unnecessarily complicates the code, just use Promise.resolve

Promise.resolve(valueOrPromiseItDoesntMatter).then(function(value) {

})

How to run multiple Python versions on Windows

As per @alexander you can make a set of symbolic links like below. Put them somewhere which is included in your path so they can be easily invoked

> cd c:\bin
> mklink python25.exe c:\python25\python.exe
> mklink python26.exe c:\python26\python.exe

As long as c:\bin or where ever you placed them in is in your path you can now go

> python25

"End of script output before headers" error in Apache

Check file permissions.

I had exactly the same error on a Linux machine with the wrong permissions set.

chmod 755 myfile.pl

solved the problem.

Convert IEnumerable to DataTable

Look at this one: Convert List/IEnumerable to DataTable/DataView

In my code I changed it into a extension method:

public static DataTable ToDataTable<T>(this List<T> items)
{
    var tb = new DataTable(typeof(T).Name);

    PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

    foreach(var prop in props)
    {
        tb.Columns.Add(prop.Name, prop.PropertyType);
    }

     foreach (var item in items)
    {
       var values = new object[props.Length];
        for (var i=0; i<props.Length; i++)
        {
            values[i] = props[i].GetValue(item, null);
        }

        tb.Rows.Add(values);
    }

    return tb;
}

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

For SQL Server:

ALTER TABLE TableName
    DROP COLUMN Column1, Column2;

The syntax is

DROP { [ CONSTRAINT ] constraint_name | COLUMN column } [ ,...n ] 

For MySQL:

ALTER TABLE TableName
    DROP COLUMN Column1,
    DROP COLUMN Column2;

or like this1:

ALTER TABLE TableName
    DROP Column1,
    DROP Column2;

1 The word COLUMN is optional and can be omitted, except for RENAME COLUMN (to distinguish a column-renaming operation from the RENAME table-renaming operation). More info here.

PHP/regex: How to get the string value of HTML tag?

In your pattern, you simply want to match all text between the two tags. Thus, you could use for example a [\w\W] to match all characters.

function getTextBetweenTags($string, $tagname) {
    $pattern = "/<$tagname>([\w\W]*?)<\/$tagname>/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

Setting focus on an HTML input box on page load

This is one of the common issues with IE and fix for this is simple. Add .focus() twice to the input.

Fix :-

function FocusOnInput() {
    var element = document.getElementById('txtContactMobileNo');
    element.focus();
    setTimeout(function () { element.focus(); }, 1);
}

And call FocusOnInput() on $(document).ready(function () {.....};

How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned

If your table columns contains duplicate data and If you directly apply row_ number() and create PARTITION on column, there is chance to have result in duplicated row and with row number value.

To remove duplicate row, you need one more INNER query in from clause which eliminates duplicate rows and then it will give output to it's foremost outer FROM clause where you can apply PARTITION and ROW_NUMBER ().

As like below example:

SELECT DATE, STATUS, TITLE, ROW_NUMBER() OVER (PARTITION BY DATE, STATUS, TITLE ORDER BY QUANTITY ASC) AS Row_Num
FROM (
     SELECT DISTINCT <column names>...
) AS tbl

Python `if x is not None` or `if not x is None`?

Both Google and Python's style guide is the best practice:

if x is not None:
    # Do something about x

Using not x can cause unwanted results.

See below:

>>> x = 1
>>> not x
False
>>> x = [1]
>>> not x
False
>>> x = 0
>>> not x
True
>>> x = [0]         # You don't want to fall in this one.
>>> not x
False

You may be interested to see what literals are evaluated to True or False in Python:


Edit for comment below:

I just did some more testing. not x is None doesn't negate x first and then compared to None. In fact, it seems the is operator has a higher precedence when used that way:

>>> x
[0]
>>> not x is None
True
>>> not (x is None)
True
>>> (not x) is None
False

Therefore, not x is None is just, in my honest opinion, best avoided.


More edit:

I just did more testing and can confirm that bukzor's comment is correct. (At least, I wasn't able to prove it otherwise.)

This means if x is not None has the exact result as if not x is None. I stand corrected. Thanks bukzor.

However, my answer still stands: Use the conventional if x is not None. :]

How can I display an RTSP video stream in a web page?

If you want to stream RTSP directly to web page, then I am afraid your only option is to use an ActiveX control viewer that comes with the camera. This is a direct connection IP Cam -> Viewer, and should really be the fastest. Not sure why you having issues; Axis ActiveX works pretty good for me.

However, this option is not really bandwidth-efficient and you can not serve multiple concurrent viewers (most of IP Cams have 10 viewers limit). The better option is to upload a single RTSP stream to centrally-hosted streaming server, which will convert your stream to RTMP/MPEG-TS and publish it to Flash players/Set-Top boxes.

Wowza, Erlyvideo, Unreal Media Server, Red5 are your options.

Eclipse error: R cannot be resolved to a variable

I assume you have updated ADT with version 22 and R.java file is not getting generated.

If this is the case, then here is the solution:

Hope you know Android studio has gradle building tool. Same as in eclipse they have given new component in the Tools folder called Android SDK Build-tools that needs to be installed. Open the Android SDK Manager, select the newly added build tools, install it, restart the SDK Manager after the update.

enter image description here

Use of 'const' for function parameters

Being a VB.NET programmer that needs to use a C++ program with 50+ exposed functions, and a .h file that sporadically uses the const qualifier, it is difficult to know when to access a variable using ByRef or ByVal.

Of course the program tells you by generating an exception error on the line where you made the mistake, but then you need to guess which of the 2-10 parameters is wrong.

So now I have the distasteful task of trying to convince a developer that they should really define their variables (in the .h file) in a manner that allows an automated method of creating all of the VB.NET function definitions easily. They will then smugly say, "read the ... documentation."

I have written an awk script that parses a .h file, and creates all of the Declare Function commands, but without an indicator as to which variables are R/O vs R/W, it only does half the job.

EDIT:

At the encouragement of another user I am adding the following;

Here is an example of a (IMO) poorly formed .h entry;

typedef int (EE_STDCALL *Do_SomethingPtr)( int smfID, const char* cursor_name, const char* sql );

The resultant VB from my script;

    Declare Function Do_Something Lib "SomeOther.DLL" (ByRef smfID As Integer, ByVal cursor_name As String, ByVal sql As String) As Integer

Note the missing "const" on the first parameter. Without it, a program (or another developer) has no Idea the 1st parameter should be passed "ByVal." By adding the "const" it makes the .h file self documenting so that developers using other languages can easily write working code.

Python/BeautifulSoup - how to remove all tags from an element?

it looks like this is the way to do! as simple as that

with this line you are joining together the all text parts within the current element

''.join(htmlelement.find(text=True))

Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine

This might also occur if you are running on 64-bit Machine with 32-bit JVM (JDK), switch it to 64-bit JVM. Check your (Right Click on My Computer --> Properties) Control Panel\System and Security\System --> Advanced System Settings -->Advanced Tab--> Environment Variables --> JAVA_HOME...

- java.lang.NullPointerException - setText on null object reference

private void fillTextView (int id, String text) {
    TextView tv = (TextView) findViewById(id);
    tv.setText(text);
}

If this is where you're getting the null pointer exception, there was no view found for the id that you passed into findViewById(), and the actual exception is thrown when you try to call a function setText() on null. You should post your XML for R.layout.activity_main, as it's hard to tell where things went wrong just by looking at your code.

More reading on null pointers: What is a NullPointerException, and how do I fix it?

YouTube embedded video: set different thumbnail

This solution will play the video upon clicking. You'll need to edit your picture to add a button image yourself.

You're going to need the URL of your picture and the YouTube video ID. The YouTube video id is the part of the URL after the v= parameter, so for https://www.youtube.com/watch?v=DODLEX4zzLQ the ID would be DODLEX4zzLQ.

<div width="560px" height="315px" style="position: static; clear: both; width: 560px; height: 315px;">&nbsp;<div style="position: relative"><img id="vidimg" width="560px" height="315px" src="URL_TO_PICTURE" style="position: absolute; top: 0; left: 0; cursor: pointer; pointer-events: none; z-index: 2;" /><iframe id="unlocked-video" style="position: absolute; top: 0; left: 0; z-index: 1;" src="https://www.youtube.com/embed/YOUTUBE_VIDEO_ID" width="560" height="315" frameborder="0" allowfullscreen="allowfullscreen"></iframe></div></div>
<script type="application/javascript">
  // Adapted from https://stackoverflow.com/a/32138108
  var monitor = setInterval(function(){
    var elem = document.activeElement;
    if(elem && elem.id == 'unlocked-video'){
      document.getElementById('vidimg').style.display='none';
      clearInterval(monitor);
    }
  }, 100);
</script>

Be sure to replace URL_TO_PICTURE and YOUTUBE_VIDEO_ID in the above snippet.

To clarify what's going on here, this displays the image on top of the video, but allows clicks to pass through the image. The script monitors for clicks in the video iframe, and then hides the image if a click occurs. You may not need the float: clear.

I haven't compared this to the other answers here, but this is what I have used.

MySQL INSERT INTO ... VALUES and SELECT

just use a subquery right there like:

INSERT INTO table1 VALUES ("A string", 5, (SELECT ...)).

What is a deadlock?

You can take a look at this wonderful articles, under section Deadlock. It is in C# but the idea is still the same for other platform. I quote here for easy reading

A deadlock happens when two threads each wait for a resource held by the other, so neither can proceed. The easiest way to illustrate this is with two locks:

object locker1 = new object();
object locker2 = new object();

new Thread (() => {
                    lock (locker1)
                    {
                      Thread.Sleep (1000);
                      lock (locker2);      // Deadlock
                    }
                  }).Start();
lock (locker2)
{
  Thread.Sleep (1000);
  lock (locker1);                          // Deadlock
}

How can I catch all the exceptions that will be thrown through reading and writing a file?

Yes there is.

try
{
    //Read/write file
}catch(Exception ex)
{
    //catches all exceptions extended from Exception (which is everything)
}

Delete item from array and shrink array

You can always expand an array just by increment the size of it while creating an array or you can also change the size after creating, but to shrink or delete elements. The alternate solution without creating a new array, possibly is:

package sample;

public class Delete {
    int i;
    int h=0;
    int n=10;
    int[] a;
    public Delete()
    {
    a = new int[10];
    a[0]=-1; 
    a[1]=-1; 
    a[2]=-1;
    a[3]=10;
    a[4]=20;
    a[5]=30;
    a[6]=40;
    a[7]=50;
    a[8]=60;
    a[9]=70;
    }
    public void shrinkArray()
    {
    for(i=0;i<n;i++)
            {
                if(a[i]==-1)
                    h++;
                else 
                    break;
            }
            while(h>0)
                {
                    for(i=h;i<n;i++)
                    {
                        a[i-1]=a[i];
                    }
                    h--;
                    n--;
                }
            System.out.println(n);
    }
    public void display()
    {
        for(i=0;i<n;i++)
        {
            System.out.println(a[i]);
        }
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Delete obj = new Delete();
        obj.shrinkArray();
        obj.display();

    }

}

Please comment for any mistakes!!

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

Simple if else onclick then do?

You should use onclick method because the function run once when the page is loaded and no button will be clicked then

So you have to add an even which run every time the user press any key to add the changes to the div background

So the function should be something like this

htmlelement.onclick() = function(){
    //Do the changes 
}

So your code has to look something like this :

var box = document.getElementById("box");
var yes = document.getElementById("yes");
var no = document.getElementById("no");

yes.onclick = function(){
    box.style.backgroundColor = "red";
}

no.onclick = function(){
    box.style.backgroundColor = "green";
}

This is meaning that when #yes button is clicked the color of the div is red and when the #no button is clicked the background is green

Here is a Jsfiddle

PHP "pretty print" json_encode

Hmmm $array = json_decode($json, true); will make your string an array which is easy to print nicely with print_r($array, true);

But if you really want to prettify your json... Check this out

MySQL "between" clause not inclusive?

In MySql between the values are inclusive therefore when you give try to get between '2011-01-01' and '2011-01-31'

it will include from 2011-01-01 00:00:00 upto 2011-01-31 00:00:00 therefore nothing actually in 2011-01-31 since its time should go from 2011-01-31 00:00:00 ~ 2011-01-31 23:59:59

For the upper bound you can change to 2011-02-01 then it will get all data upto 2011-01-31 23:59:59

getch and arrow codes

for a solution that uses ncurses with working code and initialization of ncurses see getchar() returns the same value (27) for up and down arrow keys

How do I add a reference to the MySQL connector for .NET?

As mysql official documentation:

Starting with version 6.7, Connector/Net will no longer include the MySQL for Visual Studio integration. That functionality is now available in a separate product called MySQL for Visual Studio available using the MySQL Installer for Windows (see http://dev.mysql.com/tech-resources/articles/mysql-installer-for-windows.html).

Online Documentation:

MySQL Connector/Net Installation Instructions

Android screen size HDPI, LDPI, MDPI

You should read Supporting multiple screens. You must define dpi on your emulator. 240 is hdpi, 160 is mdpi and below that are usually ldpi.

Extract from Android Developer Guide link above:

320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).  
480dp: a tweener tablet like the Streak (480x800 mdpi).  
600dp: a 7” tablet (600x1024 mdpi).  
720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).

Mockito : how to verify method was called on an object created within a method?

If you don't want to use DI or Factories. You can refactor your class in a little tricky way:

public class Foo {
    private Bar bar;

    public void foo(Bar bar){
        this.bar = (bar != null) ? bar : new Bar();
        bar.someMethod();
        this.bar = null;  // for simulating local scope
    }
}

And your test class:

@RunWith(MockitoJUnitRunner.class)
public class FooTest {
    @Mock Bar barMock;
    Foo foo;

    @Test
    public void testFoo() {
       foo = new Foo();
       foo.foo(barMock);
       verify(barMock, times(1)).someMethod();
    }
}

Then the class that is calling your foo method will do it like this:

public class thirdClass {

   public void someOtherMethod() {
      Foo myFoo = new Foo();
      myFoo.foo(null);
   }
}

As you can see when calling the method this way, you don't need to import the Bar class in any other class that is calling your foo method which is maybe something you want.

Of course the downside is that you are allowing the caller to set the Bar Object.

Hope it helps.

Angular ui-grid dynamically calculate height of the grid

A simpler approach is set use css combined with setting the minRowsToShow and virtualizationThreshold value dynamically.

In stylesheet:

.ui-grid, .ui-grid-viewport {
    height: auto !important;
}

In code, call the below function every time you change your data in gridOptions. maxRowToShow is the value you pre-defined, for my use case, I set it to 25.

ES5:

setMinRowsToShow(){
    //if data length is smaller, we shrink. otherwise we can do pagination.
    $scope.gridOptions.minRowsToShow = Math.min($scope.gridOptions.data.length, $scope.maxRowToShow);
    $scope.gridOptions.virtualizationThreshold = $scope.gridOptions.minRowsToShow ;
}

When is the finalize() method called in Java?

Having wrestled with finalizer methods lately (in order to dispose connection pools during testing), I have to say that finalizer lacks many things. Using VisualVM to observe as well as using weak references to track the actual interaction I found that following things are true in a Java 8 environment (Oracle JDK, Ubuntu 15):

  • Finalize is not called immediately the Finalizer (GC part) individually owns the reference elusively
  • The default Garbage Collector pools unreachable objects
  • Finalize is called in bulk pointing to an implementation detail that there is a certain phase the garbage collector frees the resources.
  • Calling System.gc() often does not result in objects being finalized more often, it just results in the Finalizer getting aware of an unreachable object more rapidly
  • Creating a thread dump almost always result in triggering the finalizer due to high heap overhead during performing the heap dump or some other internal mechanism
  • Finalization seams to be bound by either memory requirements (free up more memory) or by the list of objects being marked for finalization growing of a certain internal limit. So if you have a lot of objects getting finalized the finalization phase will be triggered more often and earlier when compared with only a few
  • There were circumstances a System.gc() triggered a finalize directly but only if the reference was a local and short living. This might be generation related.

Final Thought

Finalize method is unreliable but can be used for one thing only. You can ensure that an object was closed or disposed before it was garbage collected making it possible to implement a fail safe if objects with a more complex life-cylce involving a end-of-life action are handled correctly. That is the one reason I can think of that makes it worth in order to override it.

Can you style html form buttons with css?

write the below style into same html file head section or write into a .css file

<style type="text/css">
.submit input
    {
    color: #000;
    background: #ffa20f;
    border: 2px outset #d7b9c9
    }
</style>

<input type="submit" class="submit"/>

.submit - in css . means class , so i created submit class with set of attributes
and applied that class to the submit tag, using class attribute

How does the Spring @ResponseBody annotation work?

The first basic thing to understand is the difference in architectures.

One end you have the MVC architecture, which is based on your normal web app, using web pages, and the browser makes a request for a page:

Browser <---> Controller <---> Model
               |      |
               +-View-+

The browser makes a request, the controller (@Controller) gets the model (@Entity), and creates the view (JSP) from the model and the view is returned back to the client. This is the basic web app architecture.

On the other end, you have a RESTful architecture. In this case, there is no View. The Controller only sends back the model (or resource representation, in more RESTful terms). The client can be a JavaScript application, a Java server application, any application in which we expose our REST API to. With this architecture, the client decides what to do with this model. Take for instance Twitter. Twitter as the Web (REST) API, that allows our applications to use its API to get such things as status updates, so that we can use it to put that data in our application. That data will come in some format like JSON.

That being said, when working with Spring MVC, it was first built to handle the basic web application architecture. There are may different method signature flavors that allow a view to be produced from our methods. The method could return a ModelAndView where we explicitly create it, or there are implicit ways where we can return some arbitrary object that gets set into model attributes. But either way, somewhere along the request-response cycle, there will be a view produced.

But when we use @ResponseBody, we are saying that we do not want a view produced. We just want to send the return object as the body, in whatever format we specify. We wouldn't want it to be a serialized Java object (though possible). So yes, it needs to be converted to some other common type (this type is normally dealt with through content negotiation - see link below). Honestly, I don't work much with Spring, though I dabble with it here and there. Normally, I use

@RequestMapping(..., produces = MediaType.APPLICATION_JSON_VALUE)

to set the content type, but maybe JSON is the default. Don't quote me, but if you are getting JSON, and you haven't specified the produces, then maybe it is the default. JSON is not the only format. For instance, the above could easily be sent in XML, but you would need to have the produces to MediaType.APPLICATION_XML_VALUE and I believe you need to configure the HttpMessageConverter for JAXB. As for the JSON MappingJacksonHttpMessageConverter configured, when we have Jackson on the classpath.

I would take some time to learn about Content Negotiation. It's a very important part of REST. It'll help you learn about the different response formats and how to map them to your methods.

Android RecyclerView addition & removal of items

Possibly a duplicate answer but quite useful for me. You can implement the method given below in RecyclerView.Adapter<RecyclerView.ViewHolder> and can use this method as per your requirements, I hope it will work for you

public void removeItem(@NonNull Object object) {
        mDataSetList.remove(object);
        notifyDataSetChanged();
    }

Java - Check Not Null/Empty else assign default value

With guava you can use

MoreObjects.firstNonNull(possiblyNullString, defaultValue);

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

    private string GetFileSize(double byteCount)
    {
        string size = "0 Bytes";
        if (byteCount >= 1073741824.0)
            size = String.Format("{0:##.##}", byteCount / 1073741824.0) + " GB";
        else if (byteCount >= 1048576.0)
            size = String.Format("{0:##.##}", byteCount / 1048576.0) + " MB";
        else if (byteCount >= 1024.0)
            size = String.Format("{0:##.##}", byteCount / 1024.0) + " KB";
        else if (byteCount > 0 && byteCount < 1024.0)
            size = byteCount.ToString() + " Bytes";

        return size;
    }

    private void btnBrowse_Click(object sender, EventArgs e)
    {
        if (openFile1.ShowDialog() == DialogResult.OK)
        {
            FileInfo thisFile = new FileInfo(openFile1.FileName);

            string info = "";

            info += "File: " + Path.GetFileName(openFile1.FileName);
            info += Environment.NewLine;
            info += "File Size: " + GetFileSize((int)thisFile.Length);

            label1.Text = info;
        }
    }

This is one way to do it aswell (The number 1073741824.0 is from 1024*1024*1024 aka GB)

What is the C# version of VB.net's InputDialog?

Add reference to Microsoft.VisualBasic and use this function:

string response =  Microsoft.VisualBasic.Interaction.InputBox("What's 1+1?", "Title", "2", 0, 0);

The last 2 number is an X/Y position to display the input dialog.

Change icon-bar (?) color in bootstrap

Try over-riding CSS using !important

like this

.icon-bar {
   background-color:#FF0000 !important;
}

How to get the body's content of an iframe in Javascript?

use content in iframe with JS:

document.getElementById('id_iframe').contentWindow.document.write('content');

Can you do greater than comparison on a date in a Rails 3 search?

If you hit problems where column names are ambiguous, you can do:

date_field = Note.arel_table[:date]
Note.where(user_id: current_user.id, notetype: p[:note_type]).
     where(date_field.gt(p[:date])).
     order(date_field.asc(), Note.arel_table[:created_at].asc())

Loop through checkboxes and count each one checked or unchecked

Using Selectors

You can get all checked checkboxes like this:

var boxes = $(":checkbox:checked");

And all non-checked like this:

var nboxes = $(":checkbox:not(:checked)");

You could merely cycle through either one of these collections, and store those names. If anything is absent, you know it either was or wasn't checked. In PHP, if you had an array of names which were checked, you could simply do an in_array() request to know whether or not any particular box should be checked at a later date.

Serialize

jQuery also has a serialize method that will maintain the state of your form controls. For instance, the example provided on jQuery's website follows:

single=Single2&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio2

This will enable you to keep the information for which elements were checked as well.

Deep copy an array in Angular 2 + TypeScript

This is Daria's suggestion (see comment on the question) which works starting from TypeScript 2.1 and basically clones each element from the array:

this.clonedArray = theArray.map(e => ({ ... e }));

Change NULL values in Datetime format to empty string

declare @date datetime; set @date = null
--declare @date datetime; set @date = '2015-01-01'

select coalesce( convert( varchar(10), @date, 103 ), '')

Border Radius of Table is not working

It works, this is a problem with the tool used: normalized CSS by jsFiddle is causing the problem by hiding you the default of browsers...
See http://jsfiddle.net/XvdX9/5/

EDIT:
normalize.css stylesheet from jsFiddle adds the instruction border-collapse: collapse to all tables and it renders them completely differently in CSS2.1:

Differences between the 2 models can be seen in this other fiddle: http://jsfiddle.net/XvdX9/11/ (with some transparencies on cells and an enormous border-radius on the top-left one, in order to see what happens on table vs its cells)

In the same CSS2.1 page about HTML tables, there are also explanations about what browsers should/could do with empty-cells in the separated borders model, the difference between border-style: none and border-style: hidden in the collapsing borders model, how width is calculated and which border should display if both table, row and cell elements define 3 different styles on the same border.