Programs & Examples On #Top n

Pandas get topmost n records within each group

Sometimes sorting the whole data ahead is very time consuming. We can groupby first and doing topk for each group:

g = df.groupby(['id']).apply(lambda x: x.nlargest(topk,['value'])).reset_index(drop=True)

Oracle SELECT TOP 10 records

you may use this query for selecting top records in oracle. Rakesh B

select * from User_info where id >= (select max(id)-10 from User_info);

programmatically add column & rows to WPF Datagrid

To programatically add a row:

DataGrid.Items.Add(new DataItem());

To programatically add a column:

DataGridTextColumn textColumn = new DataGridTextColumn(); 
textColumn.Header = "First Name"; 
textColumn.Binding = new Binding("FirstName"); 
dataGrid.Columns.Add(textColumn); 

Check out this post on the WPF DataGrid discussion board for more information.

Variables as commands in bash scripts

Simply don't put whole commands in variables. You'll get into a lot of trouble trying to recover quoted arguments.

Also:

  1. Avoid using all-capitals variable names in scripts. Easy way to shoot yourself on the foot.
  2. Don't use backquotes, use $(...) instead, it nests better.

#! /bin/bash

if [ $# -ne 2 ]
then
    echo "Usage: $(basename $0) DIRECTORY BACKUP_DIRECTORY"
    exit 1
fi

directory=$1
backup_directory=$2
current_date=$(date +%Y-%m-%dT%H-%M-%S)
backup_file="${backup_directory}/${current_date}.backup"

tar cv "$directory" | openssl des3 -salt | split -b 1024m - "$backup_file"

Create tap-able "links" in the NSAttributedString of a UILabel?

Here is my answer based on @Luca Davanzo's answer, override the touchesBegan event instead of a tap gesture:

import UIKit

public protocol TapableLabelDelegate: NSObjectProtocol {
   func tapableLabel(_ label: TapableLabel, didTapUrl url: String, atRange range: NSRange)
}

public class TapableLabel: UILabel {

private var links: [String: NSRange] = [:]
private(set) var layoutManager = NSLayoutManager()
private(set) var textContainer = NSTextContainer(size: CGSize.zero)
private(set) var textStorage = NSTextStorage() {
    didSet {
        textStorage.addLayoutManager(layoutManager)
    }
}

public weak var delegate: TapableLabelDelegate?

public override var attributedText: NSAttributedString? {
    didSet {
        if let attributedText = attributedText {
            textStorage = NSTextStorage(attributedString: attributedText)
        } else {
            textStorage = NSTextStorage()
            links = [:]
        }
    }
}

public override var lineBreakMode: NSLineBreakMode {
    didSet {
        textContainer.lineBreakMode = lineBreakMode
    }
}

public override var numberOfLines: Int {
    didSet {
        textContainer.maximumNumberOfLines = numberOfLines
    }
}


public override init(frame: CGRect) {
    super.init(frame: frame)
    setup()
}

public required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}

public override func layoutSubviews() {
    super.layoutSubviews()
    textContainer.size = bounds.size
}


/// addLinks
///
/// - Parameters:
///   - text: text of link
///   - url: link url string
public func addLink(_ text: String, withURL url: String) {
    guard let theText = attributedText?.string as? NSString else {
        return
    }

    let range = theText.range(of: text)

    guard range.location !=  NSNotFound else {
        return
    }

    links[url] = range
}

private func setup() {
    isUserInteractionEnabled = true
    layoutManager.addTextContainer(textContainer)
    textContainer.lineFragmentPadding = 0
    textContainer.lineBreakMode = lineBreakMode
    textContainer.maximumNumberOfLines  = numberOfLines
}

public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let locationOfTouch = touches.first?.location(in: self) else {
        return
    }

    textContainer.size = bounds.size
    let indexOfCharacter = layoutManager.glyphIndex(for: locationOfTouch, in: textContainer)

    for (urlString, range) in links {
        if NSLocationInRange(indexOfCharacter, range), let url = URL(string: urlString) {
            delegate?.tapableLabel(self, didTapUrl: urlString, atRange: range)
        }
    }
}}

CSS text-decoration underline color

You can't change the color of the line (you can't specify different foreground colors for the same element, and the text and its decoration form a single element). However there are some tricks:

a:link, a:visited {text-decoration: none; color: red; border-bottom: 1px solid #006699; }
a:hover, a:active {text-decoration: none; color: red; border-bottom: 1px solid #1177FF; }

Also you can make some cool effects this way:

a:link {text-decoration: none; color: red; border-bottom: 1px dashed #006699; }

Hope it helps.

Getting the client's time zone (and offset) in JavaScript

As an alternative to new Date().getTimezoneOffset() and moment().format('zz'), you can also use :

_x000D_
_x000D_
var offset = moment.parseZone(Date.now()).utcOffset() / 60_x000D_
console.log(offset);
_x000D_
<script src="https://cdn.jsdelivr.net/momentjs/2.13.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

jstimezone is also quite buggy and unmaintained (https://bitbucket.org/pellepim/jstimezonedetect/issues?status=new&status=open)

How to print variables in Perl

print "Number of lines: $nids\n";
print "Content: $ids\n";

How did Perl complain? print $ids should work, though you probably want a newline at the end, either explicitly with print as above or implicitly by using say or -l/$\.

If you want to interpolate a variable in a string and have something immediately after it that would looks like part of the variable but isn't, enclose the variable name in {}:

print "foo${ids}bar";

Android Studio Gradle Already disposed Module

I also face this problem sometimes. Click on gradle console in bottom bar of android studio, at right side. It will show the exact error in logs. My problem was that I had compile SDK 22 and imported appcomact library was of sdk 23.

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

Just to elaborate a bit more on Henry's answer, you can also use specific error codes, from raise_application_error and handle them accordingly on the client side. For example:

Suppose you had a PL/SQL procedure like this to check for the existence of a location record:

   PROCEDURE chk_location_exists
   (
      p_location_id IN location.gie_location_id%TYPE
   )
   AS
      l_cnt INTEGER := 0;
   BEGIN
      SELECT COUNT(*)
        INTO l_cnt
        FROM location
       WHERE gie_location_id = p_location_id;

       IF l_cnt = 0
       THEN
          raise_application_error(
             gc_entity_not_found,
             'The associated location record could not be found.');
       END IF;
   END;

The raise_application_error allows you to raise a specific error code. In your package header, you can define: gc_entity_not_found INTEGER := -20001;

If you need other error codes for other types of errors, you can define other error codes using -20002, -20003, etc.

Then on the client side, you can do something like this (this example is for C#):

/// <summary>
/// <para>Represents Oracle error number when entity is not found in database.</para>
/// </summary>
private const int OraEntityNotFoundInDB = 20001;

And you can execute your code in a try/catch

try
{
   // call the chk_location_exists SP
}
catch (Exception e)
{
    if ((e is OracleException) && (((OracleException)e).Number == OraEntityNotFoundInDB))
    {
        // create an EntityNotFoundException with message indicating that entity was not found in
        // database; use the message of the OracleException, which will indicate the table corresponding
        // to the entity which wasn't found and also the exact line in the PL/SQL code where the application
        // error was raised
        return new EntityNotFoundException(
            "A required entity was not found in the database: " + e.Message);
    }
}

Updating a JSON object using Javascript

use:

var parsedobj = jQuery.parseJSON( jsonObj);

This will only be useful if you don't need the format to stay in string. otherwise you'd have to convert this back to JSON using the JSON library.

Dynamic height for DIV

This worked for me as-
HTML-

    <div style="background-color: #535; width: 100%; height: 80px;">
        <div class="center">
            Test <br>
            kumar adnioas<br>
            sanjay<br>
            1990
        </div>
    </div> 

CSS-

.center {
    position: relative;
    left: 50%;
    top: 50%;
    height: 82%;
    transform: translate(-50%, -50%);
    transform: -webkit-translate(-50%, -50%);
    transform: -ms-translate(-50%, -50%);
   }  

Hope will help you too.

Detecting a redirect in ajax request?

While the other folks who answered this question are (sadly) correct that this information is hidden from us by the browser, I thought I'd post a workaround I came up with:

I configured my server app to set a custom response header (X-Response-Url) containing the url that was requested. Whenever my ajax code receives a response, it checks if xhr.getResponseHeader("x-response-url") is defined, in which case it compares it to the url that it originally requested via $.ajax(). If the strings differ, I know there was a redirect, and additionally, what url we actually arrived at.

This does have the drawback of requiring some server-side help, and also may break down if the url gets munged (due to quoting/encoding issues etc) during the round trip... but for 99% of cases, this seems to get the job done.


On the server side, my specific case was a python application using the Pyramid web framework, and I used the following snippet:

import pyramid.events

@pyramid.events.subscriber(pyramid.events.NewResponse)
def set_response_header(event):
    request = event.request
    if request.is_xhr:
        event.response.headers['X-Response-URL'] = request.url

How to change the application launcher icon on Flutter?

The one marked as correct answer, is not enough, you need one more step, type this command in the terminal in order to create the icons:

flutter pub run flutter_launcher_icons:main

What is the keyguard in Android?

Yes, I also found it here: http://developer.android.com/tools/testing/activity_testing.html It's seems a key-input protection mechanism which includes the screen-lock, but not only includes it. According to this webpage, it also defines some key-input restriction for auto-test framework in Android.

How to pad zeroes to a string?

Quick timing comparison:

setup = '''
from random import randint
def test_1():
    num = randint(0,1000000)
    return str(num).zfill(7)
def test_2():
    num = randint(0,1000000)
    return format(num, '07')
def test_3():
    num = randint(0,1000000)
    return '{0:07d}'.format(num)
def test_4():
    num = randint(0,1000000)
    return format(num, '07d')
def test_5():
    num = randint(0,1000000)
    return '{:07d}'.format(num)
def test_6():
    num = randint(0,1000000)
    return '{x:07d}'.format(x=num)
def test_7():
    num = randint(0,1000000)
    return str(num).rjust(7, '0')
'''
import timeit
print timeit.Timer("test_1()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_2()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_3()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_4()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_5()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_6()", setup=setup).repeat(3, 900000)
print timeit.Timer("test_7()", setup=setup).repeat(3, 900000)


> [2.281613943830961, 2.2719342631547077, 2.261691106209631]
> [2.311480238815406, 2.318420542148333, 2.3552384305184493]
> [2.3824197456864304, 2.3457239951596485, 2.3353268829498646]
> [2.312442972404032, 2.318053102249902, 2.3054072168069872]
> [2.3482314132374853, 2.3403386400002475, 2.330108825844775]
> [2.424549090688892, 2.4346475296851438, 2.429691196530058]
> [2.3259756401716487, 2.333549212826732, 2.32049893822186]

I've made different tests of different repetitions. The differences are not huge, but in all tests, the zfill solution was fastest.

Get value from JToken that may not exist (best practices)

TYPE variable = jsonbody["key"]?.Value<TYPE>() ?? DEFAULT_VALUE;

e.g.

bool attachMap = jsonbody["map"]?.Value<bool>() ?? false;

SQL, How to Concatenate results?

With MSSQL you can do something like this:

declare @result varchar(500)
set @result = ''
select @result = @result + ModuleValue + ', ' 
from TableX where ModuleId = @ModuleId

Enable UTF-8 encoding for JavaScript

thanks friends, after trying all and not getting desired result i think to use a hidden div with that arabic message and with jQuery fading affects solved the problem. Script I wrote is: .js file

$('#enterOpeningPrice').fadeIn();
$('#enterOpeningPrice').fadeOut(10000);

.html file

<div id="enterOpeningPrice">
    <p>???? ??? ????????</p>
</div>

Thanks to all..

printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

I suspect GCC (mingw) has custom code to disable the checks for the wide printf functions on Windows. This is because Microsoft's own implementation (MSVCRT) is badly wrong and has %s and %ls backwards for the wide printf functions; since GCC can't be sure whether you will be linking with MS's broken implementation or some corrected one, the least-obtrusive thing it can do is just shut off the warning.

Remove all files in a directory

star is expanded by Unix shell. Your call is not accessing shell, it's merely trying to remove a file with the name ending with the star

A formula to copy the values from a formula to another column

you can use those functions together with iferror as a work around.

try =IFERROR(VALUE(A4),(CONCATENATE(A4)))

Delete newline in Vim

While on the upper line in normal mode, hit Shift+j.

You can prepend a count too, so 3J on the top line would join all those lines together.

.rar, .zip files MIME Type

I see many answer reporting for zip and rar the Media Types application/zip and application/x-rar-compressed, respectively.

While the former matching is correct, for the latter IANA reports here https://www.iana.org/assignments/media-types/application/vnd.rar that for rar application/x-rar-compressed is a deprecated alias name and instead application/vnd.rar is the official one. So, right Media Types from IANA in 2020 are:

  1. zip: application/zip
  2. rar: application/vnd.rar

NSURLConnection Using iOS Swift

Swift 3.0

AsynchonousRequest

let urlString = "http://heyhttp.org/me.json"
var request = URLRequest(url: URL(string: urlString)!)
let session = URLSession.shared

session.dataTask(with: request) {data, response, error in
  if error != nil {
    print(error!.localizedDescription)
    return
  }

  do {
    let jsonResult: NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
    print("Synchronous\(jsonResult)")
  } catch {
    print(error.localizedDescription)
  }
}.resume()

Load HTML File Contents to Div [without the use of iframes]

http://www.boutell.com/newfaq/creating/include.html

this would explain how to write your own clientsideinlcude but jQuery is a lot, A LOT easier option ... plus you will gain a lot more by using jQuery anyways

How can I copy the output of a command directly into my clipboard?

Based on previous posts, I ended up with the following light-weigh alias solution that can be added to .bashrc:

if [ -n "$(type -P xclip)" ]
then
  alias xclip='xclip -selection clipboard'
  alias clipboard='if [ -p /dev/stdin ]; then xclip -in; fi; xclip -out'
fi

Examples:

# Copy
$ date | clipboard
Sat Dec 29 14:12:57 PST 2018

# Paste
$ date
Sat Dec 29 14:12:57 PST 2018

# Chain
$ date | clipboard | wc
   1       6      29

WooCommerce - get category for product page

<?php
   $terms = get_the_terms($product->ID, 'product_cat');
      foreach ($terms as $term) {

        $product_cat = $term->name;
           echo $product_cat;
             break;
  }
 ?>

Have a div cling to top of screen if scrolled down past it

Use position:fixed; and set the top:0;left:0;right:0;height:100px; and you should be able to have it "stick" to the top of the page.

<div style="position:fixed;top:0;left:0;right:0;height:100px;">Some buttons</div>

Xcode 4: create IPA file instead of .xcarchive

Assuming you've done a successful Product > Archive then, from Organizer (Shift Apple 2) click Archives.

Select your Archive. Select Share. In the "Select the content and options for sharing:" pane set Contents to "iOS App Store Package (.ipa) and Identity to iPhone Distribution.

Click Next, enter an App name and click Save.

Full gory details with screenshots are here: Xcode4UserGuide

How do I use WPF bindings with RelativeSource?

This is an example of the use of this pattern that worked for me on empty datagrids.

<Style.Triggers>
    <DataTrigger Binding="{Binding Items.Count, RelativeSource={RelativeSource Self}}" Value="0">
        <Setter Property="Background">
            <Setter.Value>
                <VisualBrush Stretch="None">
                    <VisualBrush.Visual>
                        <TextBlock Text="We did't find any matching records for your search..." FontSize="16" FontWeight="SemiBold" Foreground="LightCoral"/>
                    </VisualBrush.Visual>
                </VisualBrush>
            </Setter.Value>
        </Setter>
    </DataTrigger>
</Style.Triggers>

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

I resolved my problem doing this:

  • The .php file is encoded to ANSI. In this file is the function to create the .json file.
  • I use json_encode($array, JSON_UNESCAPED_UNICODE) to encode the data;

The result is a .json file encoded to ANSI as UTF-8.

Getting cursor position in Python

Using pyautogui

To install

pip install pyautogui

and to find the location of the mouse pointer

import pyautogui
print(pyautogui.position())

This will give the pixel location to which mouse pointer is at.

Passing 'this' to an onclick event

You can always call funciton differently: foo.call(this); in this way you will be able to use this context inside the function.

Example:

<button onclick="foo.call(this)" id="bar">Button</button>?

var foo = function()
{
    this.innerHTML = "Not a button";
};

How to create table using select query in SQL Server?

select <column list> into <dest. table> from <source table>;

You could do this way.

SELECT windows_release, windows_service_pack_level, 
       windows_sku, os_language_version
into   new_table_name
FROM   sys.dm_os_windows_info OPTION (RECOMPILE);

Java - ignore exception and continue

Printing the STACK trace, logging it or send message to the user, are very bad ways to process the exceptions. Does any one can describe solutions to fix the exception in proper steps then can trying the broken instruction again?

PHP Converting Integer to Date, reverse of strtotime

The time() function displays the seconds between now and the unix epoch , 01 01 1970 (00:00:00 GMT). The strtotime() transforms a normal date format into a time() format. So the representation of that date into seconds will be : 1388516401

Source: http://www.php.net/time

Getting the class of the element that fired an event using JQuery

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $("a").click(function(event) {_x000D_
    var myClass = $(this).attr("class");_x000D_
    var myId = $(this).attr('id');_x000D_
    alert(myClass + " " + myId);_x000D_
  });_x000D_
})
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <a href="#" id="kana1" class="konbo">click me 1</a>_x000D_
  <a href="#" id="kana2" class="kinta">click me 2</a>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

This works for me. There is no event.target.class function in jQuery.

What is JNDI? What is its basic use? When is it used?

What is JNDI ?

It stands for Java Naming and Directory Interface.

What is its basic use?

JNDI allows distributed applications to look up services in an abstract, resource-independent way.

When it is used?

The most common use case is to set up a database connection pool on a Java EE application server. Any application that's deployed on that server can gain access to the connections they need using the JNDI name java:comp/env/FooBarPool without having to know the details about the connection.

This has several advantages:

  1. If you have a deployment sequence where apps move from devl->int->test->prod environments, you can use the same JNDI name in each environment and hide the actual database being used. Applications don't have to change as they migrate between environments.
  2. You can minimize the number of folks who need to know the credentials for accessing a production database. Only the Java EE app server needs to know if you use JNDI.

Why can't C# interfaces contain fields?

Why not just have a Year property, which is perfectly fine?

Interfaces don't contain fields because fields represent a specific implementation of data representation, and exposing them would break encapsulation. Thus having an interface with a field would effectively be coding to an implementation instead of an interface, which is a curious paradox for an interface to have!

For instance, part of your Year specification might require that it be invalid for ICar implementers to allow assignment to a Year which is later than the current year + 1 or before 1900. There's no way to say that if you had exposed Year fields -- far better to use properties instead to do the work here.

MySQL "between" clause not inclusive?

Set the upper date to date + 1 day, so in your case, set it to 2011-02-01.

How to correctly use the extern keyword in C

All declarations of functions and variables in header files should be extern.

Exceptions to this rule are inline functions defined in the header and variables which - although defined in the header - will have to be local to the translation unit (the source file the header gets included into): these should be static.

In source files, extern shouldn't be used for functions and variables defined in the file. Just prefix local definitions with static and do nothing for shared definitions - they'll be external symbols by default.

The only reason to use extern at all in a source file is to declare functions and variables which are defined in other source files and for which no header file is provided.


Declaring function prototypes extern is actually unnecessary. Some people dislike it because it will just waste space and function declarations already have a tendency to overflow line limits. Others like it because this way, functions and variables can be treated the same way.

Non greedy (reluctant) regex matching in sed?

There is still hope to solve this using pure (GNU) sed. Despite this is not a generic solution in some cases you can use "loops" to eliminate all the unnecessary parts of the string like this:

sed -r -e ":loop" -e 's|(http://.+)/.*|\1|' -e "t loop"
  • -r: Use extended regex (for + and unescaped parenthesis)
  • ":loop": Define a new label named "loop"
  • -e: add commands to sed
  • "t loop": Jump back to label "loop" if there was a successful substitution

The only problem here is it will also cut the last separator character ('/'), but if you really need it you can still simply put it back after the "loop" finished, just append this additional command at the end of the previous command line:

-e "s,$,/,"

How do I enumerate through a JObject?

JObjects can be enumerated via JProperty objects by casting it to a JToken:

foreach (JProperty x in (JToken)obj) { // if 'obj' is a JObject
    string name = x.Name;
    JToken value = x.Value;
}

If you have a nested JObject inside of another JObject, you don't need to cast because the accessor will return a JToken:

foreach (JProperty x in obj["otherObject"]) { // Where 'obj' and 'obj["otherObject"]' are both JObjects
    string name = x.Name;
    JToken value = x.Value;
}

How does the bitwise complement operator (~ tilde) work?

tl;dr ~ flips the bits. As a result the sign changes. ~2 is a negative number (0b..101). To output a negative number ruby prints -, then two's complement of ~2: -(~~2 + 1) == -(2 + 1) == 3. Positive numbers are output as is.

There's an internal value, and its string representation. For positive integers, they basically coincide:

irb(main):001:0> '%i' % 2
=> "2"
irb(main):002:0> 2
=> 2

The latter being equivalent to:

irb(main):003:0> 2.to_s
"2"

~ flips the bits of the internal value. 2 is 0b010. ~2 is 0b..101. Two dots (..) represent an infinite number of 1's. Since the most significant bit (MSB) of the result is 1, the result is a negative number ((~2).negative? == true). To output a negative number ruby prints -, then two's complement of the internal value. Two's complement is calculated by flipping the bits, then adding 1. Two's complement of 0b..101 is 3. As such:

irb(main):005:0> '%b' % 2
=> "10"
irb(main):006:0> '%b' % ~2
=> "..101"
irb(main):007:0> ~2
=> -3

To sum it up, it flips the bits, which changes the sign. To output a negative number it prints -, then ~~2 + 1 (~~2 == 2).

The reason why ruby outputs negative numbers like so, is because it treats the stored value as a two's complement of the absolute value. In other words, what's stored is 0b..101. It's a negative number, and as such it's a two's complement of some value x. To find x, it does two's complement of 0b..101. Which is two's complement of two's complement of x. Which is x (e.g ~(~2 + 1) + 1 == 2).

In case you apply ~ to a negative number, it just flips the bits (which nevertheless changes the sign):

irb(main):008:0> '%b' % -3
=> "..101"
irb(main):009:0> '%b' % ~-3
=> "10"
irb(main):010:0> ~-3
=> 2

What is more confusing is that ~0xffffff00 != 0xff (or any other value with MSB equal to 1). Let's simplify it a bit: ~0xf0 != 0x0f. That's because it treats 0xf0 as a positive number. Which actually makes sense. So, ~0xf0 == 0x..f0f. The result is a negative number. Two's complement of 0x..f0f is 0xf1. So:

irb(main):011:0> '%x' % ~0xf0
=> "..f0f"
irb(main):012:0> (~0xf0).to_s(16)
=> "-f1"

In case you're not going to apply bitwise operators to the result, you can consider ~ as a -x - 1 operator:

irb(main):018:0> -2 - 1
=> -3
irb(main):019:0> --3 - 1
=> 2

But that is arguably of not much use.

An example Let's say you're given a 8-bit (for simplicity) netmask, and you want to calculate the number of 0's. You can calculate them by flipping the bits and calling bit_length (0x0f.bit_length == 4). But ~0xf0 == 0x..f0f, so we've got to cut off the unneeded bits:

irb(main):014:0> '%x' % (~0xf0 & 0xff)
=> "f"
irb(main):015:0> (~0xf0 & 0xff).bit_length
=> 4

Or you can use the XOR operator (^):

irb(main):016:0> i = 0xf0
irb(main):017:0> '%x' % i ^ ((1 << i.bit_length) - 1)
=> "f"

How to run regasm.exe from command line other than Visual Studio command prompt?

For the 64-bit RegAsm.exe you will need to find it someplace like this:

c:\Windows\Microsoft.NET\Framework64\version_number_stuff\regasm.exe

Binding value to input in Angular JS

If you don't wan't to use ng-model there is ng-value you can try.

Here's the fiddle for this: http://jsfiddle.net/Rg9sG/1/

How to add favicon.ico in ASP.NET site

I have the same issue. My url is as below

http://somesite/someapplication

Below doesnot work

<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />

I got it to work like below

<link rel="shortcut icon" type="image/x-icon" href="/someapplication/favicon.ico" />

java.net.URL read stream to byte[]

There's no guarantee that the content length you're provided is actually correct. Try something akin to the following:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = null;
try {
  is = url.openStream ();
  byte[] byteChunk = new byte[4096]; // Or whatever size you want to read in at a time.
  int n;

  while ( (n = is.read(byteChunk)) > 0 ) {
    baos.write(byteChunk, 0, n);
  }
}
catch (IOException e) {
  System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
  e.printStackTrace ();
  // Perform any other exception handling that's appropriate.
}
finally {
  if (is != null) { is.close(); }
}

You'll then have the image data in baos, from which you can get a byte array by calling baos.toByteArray().

This code is untested (I just wrote it in the answer box), but it's a reasonably close approximation to what I think you're after.

Copy / Put text on the clipboard with FireFox, Safari and Chrome

If you support flash you can use https://everyplay.com/assets/clipboard.swf and use the flashvars text to set the text

https://everyplay.com/assets/clipboard.swf?text=It%20Works

Thats the one i use to copy and you can set as extra if doesn't support these options you can use :

For Internet Explorer: window.clipboardData.setData(DataFormat, Text) and window.clipboardData.getData(DataFormat)

You can use the DataFormat's Text and Url to getData and setData.

And to delete data:

You can use the DataFormat's File, HTML, Image, Text and URL. PS: You Need To Use window.clipboardData.clearData(DataFormat);

And for other thats not support window.clipboardData and swf flash files you can also use control + c button on your keyboard for windows and for mac its command + c

how to mysqldump remote db from local machine

Bassed on this page here:

Compare two MySQL databases

I modified it so you can use ddbb in diferent hosts.


#!/bin/sh

echo "Usage: dbdiff [user1:pass1@dbname1:host] [user2:pass2@dbname2:host] [ignore_table1:ignore_table2...]"

dump () {
  up=${1%%@*}; down=${1##*@}; user=${up%%:*}; pass=${up##*:}; dbname=${down%%:*}; host=${down##*:};
  mysqldump --opt --compact --skip-extended-insert -u $user -p$pass $dbname -h $host $table > $2
}

rm -f /tmp/db.diff

# Compare
up=${1%%@*}; down=${1##*@}; user=${up%%:*}; pass=${up##*:}; dbname=${down%%:*}; host=${down##*:};
for table in `mysql -u $user -p$pass $dbname -h $host -N -e "show tables" --batch`; do
  if [ "`echo $3 | grep $table`" = "" ]; then
    echo "Comparing '$table'..."
    dump $1 /tmp/file1.sql
    dump $2 /tmp/file2.sql
    diff -up /tmp/file1.sql /tmp/file2.sql >> /tmp/db.diff
  else
    echo "Ignored '$table'..."
  fi
done
less /tmp/db.diff
rm -f /tmp/file1.sql /tmp/file2.sql

Allow Access-Control-Allow-Origin header using HTML5 fetch API

Like epascarello said, the server that hosts the resource needs to have CORS enabled. What you can do on the client side (and probably what you are thinking of) is set the mode of fetch to CORS (although this is the default setting I believe):

fetch(request, {mode: 'cors'});

However this still requires the server to enable CORS as well, and allow your domain to request the resource.

Check out the CORS documentation, and this awesome Udacity video explaining the Same Origin Policy.

You can also use no-cors mode on the client side, but this will just give you an opaque response (you can't read the body, but the response can still be cached by a service worker or consumed by some API's, like <img>):

fetch(request, {mode: 'no-cors'})
.then(function(response) {
  console.log(response); 
}).catch(function(error) {  
  console.log('Request failed', error)  
});

Vertically aligning a checkbox

Its not a perfect solution, but a good workaround.

You need to assign your elements to behave as table with display: table-cell

Solution: Demo

HTML:

<ul>        
    <li>
        <div><input type="checkbox" value="1" name="test[]" id="myid1"></div>
        <div><label for="myid1">label1</label></div>
    </li>
    <li>
        <div><input type="checkbox" value="2" name="test[]" id="myid2"></div>
        <div><label for="myid2">label2</label></div>
    </li>
</ul>

CSS:

li div { display: table-cell; vertical-align: middle; }

Remove from the beginning of std::vector

Given

std::vector<Rule>& topPriorityRules;

The correct way to remove the first element of the referenced vector is

topPriorityRules.erase(topPriorityRules.begin());

which is exactly what you suggested.

Looks like i need to do iterator overloading.

There is no need to overload an iterator in order to erase first element of std::vector.


P.S. Vector (dynamic array) is probably a wrong choice of data structure if you intend to erase from the front.

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

No, C++ does not support 'finally' blocks. The reason is that C++ instead supports RAII: "Resource Acquisition Is Initialization" -- a poor name for a really useful concept.

The idea is that an object's destructor is responsible for freeing resources. When the object has automatic storage duration, the object's destructor will be called when the block in which it was created exits -- even when that block is exited in the presence of an exception. Here is Bjarne Stroustrup's explanation of the topic.

A common use for RAII is locking a mutex:

// A class with implements RAII
class lock
{
    mutex &m_;

public:
    lock(mutex &m)
      : m_(m)
    {
        m.acquire();
    }
    ~lock()
    {
        m_.release();
    }
};

// A class which uses 'mutex' and 'lock' objects
class foo
{
    mutex mutex_; // mutex for locking 'foo' object
public:
    void bar()
    {
        lock scopeLock(mutex_); // lock object.

        foobar(); // an operation which may throw an exception

        // scopeLock will be destructed even if an exception
        // occurs, which will release the mutex and allow
        // other functions to lock the object and run.
    }
};

RAII also simplifies using objects as members of other classes. When the owning class' is destructed, the resource managed by the RAII class gets released because the destructor for the RAII-managed class gets called as a result. This means that when you use RAII for all members in a class that manage resources, you can get away with using a very simple, maybe even the default, destructor for the owner class since it doesn't need to manually manage its member resource lifetimes. (Thanks to Mike B for pointing this out.)

For those familliar with C# or VB.NET, you may recognize that RAII is similar to .NET deterministic destruction using IDisposable and 'using' statements. Indeed, the two methods are very similar. The main difference is that RAII will deterministically release any type of resource -- including memory. When implementing IDisposable in .NET (even the .NET language C++/CLI), resources will be deterministically released except for memory. In .NET, memory is not deterministically released; memory is only released during garbage collection cycles.

 

† Some people believe that "Destruction is Resource Relinquishment" is a more accurate name for the RAII idiom.

Ctrl+click doesn't work in Eclipse Juno

I found resolving issues with the project's Java Build Path settings fixed this issue.

Right-click the project, select Properties, select Java Build Path.

(NB: I'm using Eclipse Kepler Service Release 2 on Windows 7)

PHP mkdir: Permission denied problem

You need to have file system permission to create the directory.

Example: In Ubuntu 10.04 apache (php) runs as user: www-data in group: www-data

Meaning the user www-data needs access to create the directory.

You can try this yourself by using: 'su www-data' to become the www-data user.

As a quick fix, you can do: sudo chmod 777 my_parent_dir

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

What are you doing: (I am using bytes instead of in for better reading)

You start with int *ap and so on, so your (your computers) memory looks like this:

-------------- memory used by some one else --------
000: ?
001: ?
...
098: ?
099: ?
-------------- your memory  --------
100: something          <- here is *ap
101: 41                 <- here starts a[] 
102: 42
103: 43
104: 44
105: 45
106: something          <- here waits x

lets take a look waht happens when (print short cut for ...print("$d", ...)

print a[0]  -> 41   //no surprise
print a     -> 101  // because a points to the start of the array
print *a    -> 41   // again the first element of array
print a+1   -> guess? 102
print *(a+1)    -> whats behind 102? 42 (we all love this number)

and so on, so a[0] is the same as *a, a[1] = *(a+1), ....

a[n] just reads easier.

now, what happens at line 9?

ap=a[4] // we know a[4]=*(a+4) somehow *105 ==>  45 
// warning! converting int to pointer!
-------------- your memory  --------
100: 45         <- here is *ap now 45

x = *ap;   // wow ap is 45 -> where is 45 pointing to?
-------------- memory used by some one else --------
bang!      // dont touch neighbours garden

So the "warning" is not just a warning it's a severe error.

Sort hash by key, return hash in Ruby

I liked the solution in the earlier post.

I made a mini-class, called it class AlphabeticalHash. It also has a method called ap, which accepts one argument, a Hash, as input: ap variable. Akin to pp (pp variable)

But it will (try and) print in alphabetical list (its keys). Dunno if anyone else wants to use this, it's available as a gem, you can install it as such: gem install alphabetical_hash

For me, this is simple enough. If others need more functionality, let me know, I'll include it into the gem.

EDIT: Credit goes to Peter, who gave me the idea. :)

How do I keep two side-by-side divs the same height?

Using jQuery

Using jQuery, you can do it in a super simple one-line-script.

// HTML
<div id="columnOne">
</div>

<div id="columnTwo">
</div>

// Javascript
$("#columnTwo").height($("#columnOne").height());

Using CSS

This is a bit more interesting. The technique is called Faux Columns. More or less you don't actually set the actual height to be the same, but you rig up some graphical elements so they look the same height.

jQuery find file extension (from string)

Try this:

var extension = fileString.substring(fileString.lastIndexOf('.') + 1);

Why does C++ compilation take so long?

The biggest issues are:

1) The infinite header reparsing. Already mentioned. Mitigations (like #pragma once) usually only work per compilation unit, not per build.

2) The fact that the toolchain is often separated into multiple binaries (make, preprocessor, compiler, assembler, archiver, impdef, linker, and dlltool in extreme cases) that all have to reinitialize and reload all state all the time for each invocation (compiler, assembler) or every couple of files (archiver, linker, and dlltool).

See also this discussion on comp.compilers: http://compilers.iecc.com/comparch/article/03-11-078 specially this one:

http://compilers.iecc.com/comparch/article/02-07-128

Note that John, the moderator of comp.compilers seems to agree, and that this means it should be possible to achieve similar speeds for C too, if one integrates the toolchain fully and implements precompiled headers. Many commercial C compilers do this to some degree.

Note that the Unix model of factoring everything out to a separate binary is a kind of the worst case model for Windows (with its slow process creation). It is very noticable when comparing GCC build times between Windows and *nix, especially if the make/configure system also calls some programs just to obtain information.

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

Java web start - Unable to load resource

i got the same issue, i updated the hosts file with the server address and it worked

How to create a backup of a single table in a postgres database?

pg_dump -h localhost -p 5432 -U postgres -d mydb -t my_table > backup.sql

You can take the backup of a single table but I would suggest to take the backup of whole database and then restore whichever table you need. It is always good to have backup of whole database.

9 ways to use pg_dump

inverting image in Python with OpenCV

Alternatively, you could invert the image using the bitwise_not function of OpenCV:

imagem = cv2.bitwise_not(imagem)

I liked this example.

How to force Selenium WebDriver to click on element which is not currently visible?

To add my grain of sand here: if an element resides behind a fixed div it will be considered as not visible and you won't be able to click it; this happened to me recently and i solved it executing a script as recommended above, which does:

document.evaluate("<xpath locator for element to be clicked>", document, null, XPathResult.ANY_TYPE, null).iterateNext().click()", locator);

How to list AD group membership for AD users using input list?

Everything in one line:

get-aduser -filter * -Properties memberof | select name, @{ l="GroupMembership"; e={$_.memberof  -join ";"  } } | export-csv membership.csv

How to set DialogFragment's width and height?

I don't see a compelling reason to override onResume or onStart to set the width and height of the Window within DialogFragment's Dialog -- these particular lifecycle methods can get called repeatedly and unnecessarily execute that resizing code more than once due to things like multi window switching, backgrounding then foregrounding the app, and so on. The consequences of that repetition are fairly trivial, but why settle for that?

Setting the width/height instead within an overridden onActivityCreated() method will be an improvement because this method realistically only gets called once per instance of your DialogFragment. For example:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Window window = getDialog().getWindow();
    assert window != null;

    WindowManager.LayoutParams layoutParams = window.getAttributes();
    layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
    window.setAttributes(layoutParams);
}

Above I just set the width to be match_parent irrespective of device orientation. If you want your landscape dialog to not be so wide, you can do a check of whether getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT beforehand.

Check if PHP-page is accessed from an iOS device

51Degrees' PHP solution is able to do this. you can get the free Open Source API here https://github.com/51Degrees/Device-Detection. You can use the HardwareFamily Property to determine if it is an iPad/iPod/iPhone etc.

Due to the nature of Apple's User-Agents the initial result will return a generic device, however if you are interested in the specific device you can use a JavaScript client side override to determine to specific model.

To do this you can implement something similar to the following logic once you have determined it is an Apple Device, in this case for an iPhone.

// iPhone model checks.
function getiPhoneModel() {
// iPhone 6 Plus
if ((window.screen.height / window.screen.width == 736 / 414) && 
(window.devicePixelRatio == 3)) {
return "iPhone 6 Plus";
}
// iPhone 6
else if ((window.screen.height / window.screen.width == 667 / 375) && 
(window.devicePixelRatio == 2)) {
return "iPhone 6";
}
// iPhone 5/5C/5S or 6 in zoom mode
else if ((window.screen.height / window.screen.width == 1.775) && 
(window.devicePixelRatio == 2)) {
return "iPhone 5, 5C, 5S or 6 (display zoom)";
}
// iPhone 4/4S
else if ((window.screen.height / window.screen.width == 1.5) && 
(window.devicePixelRatio == 2)) {
return "iPhone 4 or 4S";
}
// iPhone 1/3G/3GS
else if ((window.screen.height / window.screen.width == 1.5) && 
(window.devicePixelRatio == 1)) {
return "iPhone 1, 3G or 3GS";
} else {
return "Not an iPhone";
};
}

Or for an iPad

function getiPadVersion() {
var pixelRatio = getPixelRatio();
var return_string = "Not an iPad";
if (pixelRatio == 1 ) {
return_string = "iPad 1, iPad 2, iPad Mini 1";
}
if (pixelRatio == 2) {
return_string = "iPad 3, iPad 4, iPad Air 1, iPad Air 2, iPad Mini 2, iPad 
Mini 3";
}
return return_string;
}

For more information on research 51Degrees have done into Apple devices you can read their blog post here https://51degrees.com/blog/device-detection-for-apple-iphone-and-ipad.

Disclosure: I work for 51Degrees.

How to implement reCaptcha for ASP.NET MVC?

There are a few great examples:

This has also been covered before in this Stack Overflow question.

NuGet Google reCAPTCHA V2 for MVC 4 and 5

How do I get the max and min values from a set of numbers entered?

You just need to keep track of a max value like this:

int maxValue = 0;

Then as you iterate through the numbers, keep setting the maxValue to the next value if it is greater than the maxValue:

if (value > maxValue) {
    maxValue = value;
}

Repeat in the opposite direction for minValue.

use jQuery to get values of selected checkboxes

You can also use the below code
$("input:checkbox:checked").map(function()
{
return $(this).val();
}).get();

Assign keyboard shortcut to run procedure

I ran into this problem myself. The only solution I have is to record the macro in an excel workbook first. Then, drag and drop THE MODULE from the open workbook into the add-in modules. This will be a copy of the above module, but the keyboard shortcut you assigned to it will thankfully persist.

I just record a garbage macro and move it in there, then copy the code from my real module afterwords.

Felt so great to figure this out, I felt like I had to reply to the 5 year old posts I found on the subject!!!

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

Convert ndarray from float64 to integer

Use .astype.

>>> a = numpy.array([1, 2, 3, 4], dtype=numpy.float64)
>>> a
array([ 1.,  2.,  3.,  4.])
>>> a.astype(numpy.int64)
array([1, 2, 3, 4])

See the documentation for more options.

How to distinguish mouse "click" and "drag"

If you want check the click or drag behavior of a specific element you can do this without having to listen to the body.

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  let click;_x000D_
  _x000D_
  $('.owl-carousel').owlCarousel({_x000D_
    items: 1_x000D_
  });_x000D_
  _x000D_
  // prevent clicks when sliding_x000D_
  $('.btn')_x000D_
    .on('mousemove', function(){_x000D_
      click = false;_x000D_
    })_x000D_
    .on('mousedown', function(){_x000D_
      click = true;_x000D_
    });_x000D_
    _x000D_
  // change mouseup listener to '.content' to listen to a wider area. (mouse drag release could happen out of the '.btn' which we have not listent to). Note that the click will trigger if '.btn' mousedown event is triggered above_x000D_
  $('.btn').on('mouseup', function(){_x000D_
    if(click){_x000D_
      $('.result').text('clicked');_x000D_
    } else {_x000D_
      $('.result').text('dragged');_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
.content{_x000D_
  position: relative;_x000D_
  width: 500px;_x000D_
  height: 400px;_x000D_
  background: #f2f2f2;_x000D_
}_x000D_
.slider, .result{_x000D_
  position: relative;_x000D_
  width: 400px;_x000D_
}_x000D_
.slider{_x000D_
  height: 200px;_x000D_
  margin: 0 auto;_x000D_
  top: 30px;_x000D_
}_x000D_
.btn{_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  justify-content: center;_x000D_
  text-align: center;_x000D_
  height: 100px;_x000D_
  background: #c66;_x000D_
}_x000D_
.result{_x000D_
  height: 30px;_x000D_
  top: 10px;_x000D_
  text-align: center;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css" />_x000D_
<div class="content">_x000D_
  <div class="slider">_x000D_
    <div class="owl-carousel owl-theme">_x000D_
      <div class="item">_x000D_
        <a href="#" class="btn" draggable="true">click me without moving the mouse</a>_x000D_
      </div>_x000D_
      <div class="item">_x000D_
        <a href="#" class="btn" draggable="true">click me without moving the mouse</a>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="result"></div>_x000D_
  </div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

How to print a single backslash?

A hacky way of printing a backslash that doesn't involve escaping is to pass its character code to chr:

>>> print(chr(92))
\

Best practice for partial updates in a RESTful service

You should use PATCH for partial updates - either using json-patch documents (see http://tools.ietf.org/html/draft-ietf-appsawg-json-patch-08 or http://www.mnot.net/blog/2012/09/05/patch) or the XML patch framework (see http://tools.ietf.org/html/rfc5261). In my opinion though, json-patch is the best fit for your kind of business data.

PATCH with JSON/XML patch documents has very strait forward semantics for partial updates. If you start using POST, with modified copies of the original document, for partial updates you soon run into problems where you want missing values (or, rather, null values) to represent either "ignore this property" or "set this property to the empty value" - and that leads down a rabbit hole of hacked solutions that in the end will result in your own kind of patch format.

You can find a more in-depth answer here: http://soabits.blogspot.dk/2013/01/http-put-patch-or-post-partial-updates.html.

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

You can get a non-js-based redirection from an ajax call by putting in one of those meta refresh tags. This here seems to be working: return Content("<meta http-equiv=\"refresh\" content=\"0;URL='" + @Url.Action("Index", "Home") + "'\" />");

Note: I discovered that meta refreshes are auto-disabled by Firefox, rendering this not very useful.

Differences between TCP sockets and web sockets, one more time

WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.

The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).

Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.

To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).

Disable mouse scroll wheel zoom on embedded Google Maps

Here is my solution for the problem, I was building a WP site, so there is a little php code here. But the key is scrollwheel: false, in the map object.

function initMap() {
        var uluru = {lat: <?php echo $latitude; ?>, lng: <?php echo $Longitude; ?>};
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom: 18,
            scrollwheel: false,
            center: uluru
        });
        var marker = new google.maps.Marker({
            position: uluru,
            map: map
        });
    }

Hope this will help. Cheers

Laravel Mail::send() sending to multiple to or bcc addresses

I've tested it using the following code:

$emails = ['[email protected]', '[email protected]','[email protected]'];

Mail::send('emails.welcome', [], function($message) use ($emails)
{    
    $message->to($emails)->subject('This is test e-mail');    
});
var_dump( Mail:: failures());
exit;

Result - empty array for failures.

But of course you need to configure your app/config/mail.php properly. So first make sure you can send e-mail just to one user and then test your code with many users.

Moreover using this simple code none of my e-mails were delivered to free mail accounts, I got only emails to inboxes that I have on my paid hosting accounts, so probably they were caught by some filters (it's maybe simple topic/content issue but I mentioned it just in case you haven't received some of e-mails) .

Simple timeout in java

The example 1 will not compile. This version of it compiles and runs. It uses lambda features to abbreviate it.

/*
 * [RollYourOwnTimeouts.java]
 *
 * Summary: How to roll your own timeouts.
 *
 * Copyright: (c) 2016 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.0 2016-06-28 initial version
 */
package com.mindprod.example;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import static java.lang.System.*;

/**
 * How to roll your own timeouts.
 * Based on code at http://stackoverflow.com/questions/19456313/simple-timeout-in-java
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0 2016-06-28 initial version
 * @since 2016-06-28
 */

public class RollYourOwnTimeout
    {

    private static final long MILLIS_TO_WAIT = 10 * 1000L;

    public static void main( final String[] args )
        {
        final ExecutorService executor = Executors.newSingleThreadExecutor();

        // schedule the work
        final Future<String> future = executor.submit( RollYourOwnTimeout::requestDataFromWebsite );

        try
            {
            // where we wait for task to complete
            final String result = future.get( MILLIS_TO_WAIT, TimeUnit.MILLISECONDS );
            out.println( "result: " + result );
            }

        catch ( TimeoutException e )
            {
            err.println( "task timed out" );
            future.cancel( true /* mayInterruptIfRunning */ );
            }

        catch ( InterruptedException e )
            {
            err.println( "task interrupted" );
            }

        catch ( ExecutionException e )
            {
            err.println( "task aborted" );
            }

        executor.shutdownNow();

        }
/**
 * dummy method to read some data from a website
 */
private static String requestDataFromWebsite()
    {
    try
        {
        // force timeout to expire
        Thread.sleep( 14_000L );
        }
    catch ( InterruptedException e )
        {
        }
    return "dummy";
    }

}

Interface vs Abstract Class (general OO)

i will explain Depth Details of interface and Abstract class.if you know overview about interface and abstract class, then first question arrive in your mind when we should use Interface and when we should use Abstract class. So please check below explanation of Interface and Abstract class.

  1. When we should use Interface?

    if you don't know about implementation just we have requirement specification then we go with Interface

  2. When we should use Abstract Class?

    if you know implementation but not completely (partially implementation) then we go with Abstract class.

    Interface

    every method by default public abstract means interface is 100% pure abstract.

    Abstract

    can have Concrete method and Abstract method, what is Concrete method, which have implementation in Abstract class, An abstract class is a class that is declared abstract—it may or may not include abstract methods.

    Interface

    We cannot declared interface as a private, protected

    Q. Why we are not declaring Interface a private and protected?

    Because by default interface method is public abstract so and so that reason that we are not declaring the interface as private and protected.

    Interface method
    also we cannot declared interface as private,protected,final,static,synchronized,native.....

    i will give the reason: why we are not declaring synchronized method because we cannot create object of interface and synchronize are work on object so and son reason that we are not declaring the synchronized method Transient concept are also not applicable because transient work with synchronized.

    Abstract

    we are happily use with public,private final static.... means no restriction are applicable in abstract.

    Interface

    Variables are declared in Interface as a by default public static final so we are also not declared variable as a private, protected.

    Volatile modifier is also not applicable in interface because interface variable is by default public static final and final variable you cannot change the value once it assign the value into variable and once you declared variable into interface you must to assign the variable.

    And volatile variable is keep on changes so it is opp. to final that is reason we are not use volatile variable in interface.

    Abstract

    Abstract variable no need to declared public static final.

i hope this article is useful.

How to resize an image to fit in the browser window?

CSS3 introduces new units that are measured relative to the viewport, which is the window in this case. These are vh and vw, which measure viewport height and width, respectively. Here is a simple CSS only solution:

img {
    max-width: 100%;
    max-height: 100vh;
    height: auto;
}

The one caveat to this is that it only works if there are no other elements contributing height on the page.

warning: implicit declaration of function

You need to declare the desired function before your main function:

#include <stdio.h>
int yourfunc(void);

int main(void) {

   yourfunc();
 }

How to set a JavaScript breakpoint from code in Chrome?

debugger is a reserved keyword by EcmaScript and given optional semantics since ES5

As a result, it can be used not only in Chrome, but also Firefox and Node.js via node debug myscript.js.

The standard says:

Syntax

DebuggerStatement :
    debugger ;

Semantics

Evaluating the DebuggerStatement production may allow an implementation to cause a breakpoint when run under a debugger. If a debugger is not present or active this statement has no observable effect.

The production DebuggerStatement : debugger ; is evaluated as follows:

  1. If an implementation defined debugging facility is available and enabled, then
    1. Perform an implementation defined debugging action.
    2. Let result be an implementation defined Completion value.
  2. Else
    1. Let result be (normal, empty, empty).
  3. Return result.

No changes in ES6.

Detect changed input text box

try keyup instead of change.

<script type="text/javascript">
   $(document).ready(function () {
       $('#inputDatabaseName').keyup(function () { alert('test'); });
   });
</script>

Here's the official jQuery documentation for .keyup().

Counting the number of elements in array

Just use the length filter on the whole array. It works on more than just strings:

{{ notcount|length }}

The term 'ng' is not recognized as the name of a cmdlet

All answers are about how to fix it, but the best is to download nodeJs and let the installer add to PATH variable.

Version 12 and 13 are too new, so I had to download 11.15 https://nodejs.org/download/release/v11.15.0/

How do I decode a base64 encoded string?

The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd:

string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));

string result = m000493(p0, "_p0lizei.");
//    result == "gaia^unplugged^Ta..."

with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.

Using an image caption in Markdown Jekyll

If you don't want to use any plugins (which means you can push it to GitHub directly without generating the site first), you can create a new file named image.html in _includes:

<figure class="image">
  <img src="{{ include.url }}" alt="{{ include.description }}">
  <figcaption>{{ include.description }}</figcaption>
</figure>

And then display the image from your markdown with:

{% include image.html url="/images/my-cat.jpg" description="My cat, Robert Downey Jr." %}

C# go to next item in list based on if statement in foreach

Use continue; instead of break; to enter the next iteration of the loop without executing any more of the contained code.

foreach (Item item in myItemsList)
{
   if (item.Name == string.Empty)
   {
      // Display error message and move to next item in list.  Skip/ignore all validation
      // that follows beneath
      continue;
   }

   if (item.Weight > 100)
   {
      // Display error message and move to next item in list.  Skip/ignore all validation
      // that follows beneath
      continue;
   }
}

Official docs are here, but they don't add very much color.

Update records in table from CTE

You don't need a CTE for this

UPDATE PEDI_InvoiceDetail
SET
    DocTotal = v.DocTotal
FROM
     PEDI_InvoiceDetail
inner join 
(
   SELECT InvoiceNumber, SUM(Sale + VAT) AS DocTotal
   FROM PEDI_InvoiceDetail
   GROUP BY InvoiceNumber
) v
   ON PEDI_InvoiceDetail.InvoiceNumber = v.InvoiceNumber

how to read value from string.xml in android?

You can read directly the value defined into strings.xml:

<resources>
    <string name="hello">Hello StackOverflow!</string>
</resources>

and set into a variable:

String mymessage = getString(R.string.hello);

but we can define the string into the view:

<TextView
    android:id="@+id/myTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello"/>

Trigger Change event when the Input value changed programmatically?

Vanilla JS solution:

var el = document.getElementById('changeProgramatic');
el.value='New Value'
el.dispatchEvent(new Event('change'));

Note that dispatchEvent doesn't work in old IE (see: caniuse). So you should probably only use it on internal websites (not on websites having wide audience).

So as of 2019 you just might want to make sure your customers/audience don't use Windows XP (yes, some still do in 2019). You might want to use conditional comments to warn customers that you don't support old IE (pre IE 11 in this case), but note that conditional comments only work until IE9 (don't work in IE10). So you might want to use feature detection instead. E.g. you could do an early check for: typeof document.body.dispatchEvent === 'function'.

Why are elementwise additions much faster in separate loops than in a combined loop?

OK, the right answer definitely has to do something with the CPU cache. But to use the cache argument can be quite difficult, especially without data.

There are many answers, that led to a lot of discussion, but let's face it: Cache issues can be very complex and are not one dimensional. They depend heavily on the size of the data, so my question was unfair: It turned out to be at a very interesting point in the cache graph.

@Mysticial's answer convinced a lot of people (including me), probably because it was the only one that seemed to rely on facts, but it was only one "data point" of the truth.

That's why I combined his test (using a continuous vs. separate allocation) and @James' Answer's advice.

The graphs below shows, that most of the answers and especially the majority of comments to the question and answers can be considered completely wrong or true depending on the exact scenario and parameters used.

Note that my initial question was at n = 100.000. This point (by accident) exhibits special behavior:

  1. It possesses the greatest discrepancy between the one and two loop'ed version (almost a factor of three)

  2. It is the only point, where one-loop (namely with continuous allocation) beats the two-loop version. (This made Mysticial's answer possible, at all.)

The result using initialized data:

Enter image description here

The result using uninitialized data (this is what Mysticial tested):

Enter image description here

And this is a hard-to-explain one: Initialized data, that is allocated once and reused for every following test case of different vector size:

Enter image description here

Proposal

Every low-level performance related question on Stack Overflow should be required to provide MFLOPS information for the whole range of cache relevant data sizes! It's a waste of everybody's time to think of answers and especially discuss them with others without this information.

Execution sequence of Group By, Having and Where clause in SQL Server?

In Oracle 12c, you can run code both in either sequence below:

Where
Group By
Having

Or

Where 
Having
Group by

How to keep a git branch in sync with master

The accepted answer via git merge will get the job done but leaves a messy commit hisotry, correct way should be 'rebase' via the following steps(assuming you want to keep your feature branch in sycn with develop before you do the final push before PR).

1 git fetch from your feature branch (make sure the feature branch you are working on is update to date)

2 git rebase origin/develop

3 if any conflict shall arise, resolve them one by one

4 use git rebase --continue once all conflicts are dealt with

5 git push --force

What does the 'L' in front a string mean in C++?

It means the text is stored as wchar_t characters rather than plain old char characters.

(I originally said it meant unicode. I was wrong about that. But it can be used for unicode.)

Replace String in all files in Eclipse

Tonny Madsen said it right, but sometimes this is too simplistic.

What if you want to be more selective in your replacements since not all replacements are correct for what you're trying to do?

Here's how to get more granularity to do the replacements only in certain folders, files, or instances:

First, do like he said:

  • Click Search --> File... OR press Ctrl + H and choose the "File Search" tab.
  • Enter text, file pattern and choose your Workspace or Working Set.

Then:

  • Click Search
  • When your results come up, make some folder, file, or instance selections by Ctrl + clicking on the ones you'd like to select. Ex: here's my selection. I've chosen 3 instances, 1 file, and 1 folder:

enter image description here

  • Now, right-click on your selection and go to --> Replace Selected.... Here's a screenshot of that:

enter image description here

  • Enter what you'd like to replace it "With". In my case you can see it says it is "Replacing 190 matches in 4 files". Now click OK.

enter image description here

Voilà!

References:

How to hide command output in Bash

You should not use bash in this case to get rid of the output. Yum does have an option -q which suppresses the output.

You'll most certainly also want to use -y

echo "Installing nano..."
yum -y -q install nano

To see all the options for yum, use man yum.

super() raises "TypeError: must be type, not classobj" for new-style class

If you look at the inheritance tree (in version 2.6), HTMLParser inherits from SGMLParser which inherits from ParserBase which doesn't inherits from object. I.e. HTMLParser is an old-style class.

About your checking with isinstance, I did a quick test in ipython:

In [1]: class A:
   ...:     pass
   ...: 

In [2]: isinstance(A, object)
Out[2]: True

Even if a class is old-style class, it's still an instance of object.

Open web in new tab Selenium + Python

Strangely, so many answers, and all of them are using surrogates like JS and keyboard shortcuts instead of just using a selenium feature:

def newTab(driver, url="about:blank"):
    wnd = driver.execute(selenium.webdriver.common.action_chains.Command.NEW_WINDOW)
    handle = wnd["value"]["handle"]
    driver.switch_to.window(handle)
    driver.get(url) # changes the handle
    return driver.current_window_handle

Differences between CHMOD 755 vs 750 permissions set

0755 = User:rwx Group:r-x World:r-x

0750 = User:rwx Group:r-x World:--- (i.e. World: no access)

r = read
w = write
x = execute (traverse for directories)

"Continue" (to next iteration) on VBScript

Your suggestion would work, but using a Do loop might be a little more readable.

This is actually an idiom in C - instead of using a goto, you can have a do { } while (0) loop with a break statement if you want to bail out of the construct early.

Dim i

For i = 0 To 10
    Do
        If i = 4 Then Exit Do
        WScript.Echo i
    Loop While False
Next

As crush suggests, it looks a little better if you remove the extra indentation level.

Dim i

For i = 0 To 10: Do
    If i = 4 Then Exit Do
    WScript.Echo i
Loop While False: Next

How to get a value inside an ArrayList java

You haven't shown your Car type, but assuming you'd want the price of the first car, you could use:

public static void processCars(ArrayList<Car> cars) {
    Car car = cars.get(0);
    System.out.println(car.getPrice());
}

Note that I've changed the name of the list from car to cars - this is a list of cars, not a single car. (I've changed the method name in a similar way.)

If you only want the method to process a single car, you should change the parameter to be of type Car:

public static void processCar(Car car)

and then call it like this:

// In the main method
processCar(cars.get(0));

If you do leave it as processing the whole list, it would be worth generalizing the parameter to List<Car> - it's unlikely that you'll really require that it's an ArrayList<Car>.

SQLite DateTime comparison

I had to store the time with the time-zone information in it, and was able to get queries working with the following format:

"SELECT * FROM events WHERE datetime(date_added) BETWEEN 
      datetime('2015-03-06 20:11:00 -04:00') AND datetime('2015-03-06 20:13:00 -04:00')"

The time is stored in the database as regular TEXT in the following format:

2015-03-06 20:12:15 -04:00

Has an event handler already been added?

If this is the only handler, you can check to see if the event is null, if it isn't, the handler has been added.

I think you can safely call -= on the event with your handler even if it's not added (if not, you could catch it) -- to make sure it isn't in there before adding.

AngularJS: Basic example to use authentication in Single Page Application

I like the approach and implemented it on server-side without doing any authentication related thing on front-end

My 'technique' on my latest app is.. the client doesn't care about Auth. Every single thing in the app requires a login first, so the server just always serves a login page unless an existing user is detected in the session. If session.user is found, the server just sends index.html. Bam :-o

Look for the comment by "Andrew Joslin".

https://groups.google.com/forum/?fromgroups=#!searchin/angular/authentication/angular/POXLTi_JUgg/VwStpoWCPUQJ

Wait one second in running program

Personally I think Thread.Sleep is a poor implementation. It locks the UI etc. I personally like timer implementations since it waits then fires.

Usage: DelayFactory.DelayAction(500, new Action(() => { this.RunAction(); }));

//Note Forms.Timer and Timer() have similar implementations. 

public static void DelayAction(int millisecond, Action action)
{
    var timer = new DispatcherTimer();
    timer.Tick += delegate

    {
        action.Invoke();
        timer.Stop();
    };

    timer.Interval = TimeSpan.FromMilliseconds(millisecond);
    timer.Start();
}

HTML Code for text checkbox '?'

?

this is a character . You can do copy/past without problem

Stop fixed position at footer

A pure css solution

<div id="outer-container">
    <div id="scrollable">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam in vulputate turpis. Curabitur a consectetur libero. Nulla ac velit nibh, ac lacinia nulla. In sed urna sit amet mauris vulputate viverra et et eros. Pellentesque laoreet est et neque euismod a bibendum velit laoreet. Nam gravida lectus nec purus porttitor porta. Vivamus tempor tempus auctor. Nam quis porttitor ligula. Vestibulum rutrum fermentum ligula eget luctus. Sed convallis iaculis lorem non adipiscing. Sed in egestas lectus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nunc dictum, lacus quis venenatis ultricies, turpis lorem bibendum dui, quis bibendum lacus ante commodo urna. Fusce ut sem mi, nec molestie tortor. Mauris eu leo diam. Nullam adipiscing, tortor eleifend pellentesque gravida, erat tellus vulputate orci, quis accumsan orci ipsum sed justo. Proin massa massa, pellentesque non tristique non, tristique vel dui. Vestibulum at metus at neque malesuada porta et vitae lectus.
    </div>
    <button id="social-float">The button</button>
</div>
<div>
Footer
</div>
</div>

And css here

#outer-container {
    position: relative;
}

#scrollable {
    height: 100px;
    overflow-y: auto;
}

#social-float {
    position: absolute;
    bottom: 0px;
}

Convert string to float?

String s = "3.14";
float f = Float.parseFloat(s);

ReferenceError: $ is not defined

Add jQuery library before your script which uses $ or jQuery so that $ can be identified in scripts.

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

Key error when selecting columns in pandas dataframe after read_csv

use sep='\s*,\s*' so that you will take care of spaces in column-names:

transactions = pd.read_csv('transactions.csv', sep=r'\s*,\s*',
                           header=0, encoding='ascii', engine='python')

alternatively you can make sure that you don't have unquoted spaces in your CSV file and use your command (unchanged)

prove:

print(transactions.columns.tolist())

Output:

['product_id', 'customer_id', 'store_id', 'promotion_id', 'month_of_year', 'quarter', 'the_year', 'store_sales', 'store_cost', 'unit_sales', 'fact_count']

cast or convert a float to nvarchar?

If you're storing phone numbers in a float typed column (which is a bad idea) then they are presumably all integers and could be cast to int before casting to nvarchar.

So instead of:

select cast(cast(1234567890 as float) as nvarchar(50))
1.23457e+009

You would use:

select cast(cast(cast(1234567890 as float) as int) as nvarchar(50))
1234567890

In these examples the innermost cast(1234567890 as float) is used in place of selecting a value from the appropriate column.

I really recommend that you not store phone numbers in floats though!
What if the phone number starts with a zero?

select cast(0100884555 as float)
100884555

Whoops! We just stored an incorrect phone number...

Regex to match URL end-of-line or "/" character

/(.+)/(\d{4}-\d{2}-\d{2})-(\d+)(/.*)?$

1st Capturing Group (.+)

.+ matches any character (except for line terminators)

  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

2nd Capturing Group (\d{4}-\d{2}-\d{2})

\d{4} matches a digit (equal to [0-9])

  • {4} Quantifier — Matches exactly 4 times

- matches the character - literally (case sensitive)

\d{2} matches a digit (equal to [0-9])

  • {2} Quantifier — Matches exactly 2 times

- matches the character - literally (case sensitive)

\d{2} matches a digit (equal to [0-9])

  • {2} Quantifier — Matches exactly 2 times

- matches the character - literally (case sensitive)

3rd Capturing Group (\d+)

\d+ matches a digit (equal to [0-9])

  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

4th Capturing Group (.*)?

? Quantifier — Matches between zero and one times, as many times as possible, giving back as needed (greedy)

.* matches any character (except for line terminators)

  • * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)

$ asserts position at the end of the string

Laravel, sync() - how to sync an array and also pass additional pivot fields?

Add following trait to your project and append it to your model class as a trait. This is helpful, because this adds functionality to use multiple pivots. Probably someone can clean this up a little and improve on it ;)

namespace App\Traits;

trait AppTraits
{
    /**
     * Create pivot array from given values
     *
     * @param array $entities
     * @param array $pivots
     * @return array combined $pivots
     */
    public function combinePivot($entities, $pivots = [])
    {
        // Set array
        $pivotArray = [];
        // Loop through all pivot attributes
        foreach ($pivots as $pivot => $value) {
            // Combine them to pivot array
            $pivotArray += [$pivot => $value];
        }
        // Get the total of arrays we need to fill
        $total = count($entities);
        // Make filler array
        $filler = array_fill(0, $total, $pivotArray);
        // Combine and return filler pivot array with data
        return array_combine($entities, $filler);
    }
}

Model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Example extends Model
{
    use Traits\AppTraits;
    // ...
}

Usage:

// Get id's
$entities = [1, 2, 3];
// Create pivots
$pivots = [
    'price' => 634,
    'name'  => 'Example name',
];
// Combine the ids and pivots
$combination = $model->combinePivot($entities, $pivots);
// Sync the combination with the related model / pivot
$model->relation()->sync($combination);

When & why to use delegates?

Delegates are extremely useful when wanting to declare a block of code that you want to pass around. For example when using a generic retry mechanism.

Pseudo:

function Retry(Delegate func, int numberOfTimes)
    try
    {
       func.Invoke();
    }
    catch { if(numberOfTimes blabla) func.Invoke(); etc. etc. }

Or when you want to do late evaluation of code blocks, like a function where you have some Transform action, and want to have a BeforeTransform and an AfterTransform action that you can evaluate within your Transform function, without having to know whether the BeginTransform is filled, or what it has to transform.

And of course when creating event handlers. You don't want to evaluate the code now, but only when needed, so you register a delegate that can be invoked when the event occurs.

Remove all special characters except space from a string using JavaScript

_x000D_
_x000D_
const str = "abc's@thy#^g&test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));
_x000D_
_x000D_
_x000D_

How to use filter, map, and reduce in Python 3

The functionality of map and filter was intentionally changed to return iterators, and reduce was removed from being a built-in and placed in functools.reduce.

So, for filter and map, you can wrap them with list() to see the results like you did before.

>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> list(filter(f, range(2, 25)))
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x): return x*x*x
...
>>> list(map(cube, range(1, 11)))
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>> import functools
>>> def add(x,y): return x+y
...
>>> functools.reduce(add, range(1, 11))
55
>>>

The recommendation now is that you replace your usage of map and filter with generators expressions or list comprehensions. Example:

>>> def f(x): return x % 2 != 0 and x % 3 != 0
...
>>> [i for i in range(2, 25) if f(i)]
[5, 7, 11, 13, 17, 19, 23]
>>> def cube(x): return x*x*x
...
>>> [cube(i) for i in range(1, 11)]
[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
>>>

They say that for loops are 99 percent of the time easier to read than reduce, but I'd just stick with functools.reduce.

Edit: The 99 percent figure is pulled directly from the What’s New In Python 3.0 page authored by Guido van Rossum.

Java Error opening registry key

Uninstall Java (via Control Panel / Programs and Features)

Install Java JRE 7 --> OFFLINE <-- Configure JAVA_HOME and Path = %JAVA_HOME%/bin;%PATH%

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

For TF2.x, you can do like this.

import tensorflow as tf
with tf.compat.v1.Session() as sess:
    hello = tf.constant('hello world')
    print(sess.run(hello))

>>> b'hello world

How to center an element in the middle of the browser window?

div#wrapper {
    position: absolute;
    top:  50%;
    left: 50%;
    transform: translate(-50%,-50%);
}

How to deploy ASP.NET webservice to IIS 7?

  1. rebuild project in VS
  2. copy project folder to iis folder, probably C:\inetpub\wwwroot\
  3. in iis manager (run>inetmgr) add website, point to folder, point application pool based on your .net
  4. add web service to created website, almost the same as 3.
  5. INSTALL ASP for windows 7 and .net 4.0: c:\windows\microsoft.net framework\v4.(some numbers)\regiis.exe -i
  6. check access to web service on your browser

Debugging "Element is not clickable at point" error

I had the same problem and spent hours in finding the solution. I tried to click a cell at the bottom of a long ngGrid using protractor. Here is a snapshot of my ngGrid html:

....many rows here..
<!- row in renderedRows ->
   <!- column in renderedColumns ->
   <div ...> <a ngclick="selectRow(row)"...>the test link 100000</a>...
....

all clicking function did not work. The solution is to use evaluate in the element's current scope:

element(by.cssContainingText("a", "the test link 100000"))
    .evaluate("selectRow(row)")

HTTP Headers for File Downloads

You can try this force-download script. Even if you don't use it, it'll probably point you in the right direction:

<?php

$filename = $_GET['file'];

// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
  ini_set('zlib.output_compression', 'Off');

// addition by Jorg Weske
$file_extension = strtolower(substr(strrchr($filename,"."),1));

if( $filename == "" ) 
{
  echo "<html><title>eLouai's Download Script</title><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>";
  exit;
} elseif ( ! file_exists( $filename ) ) 
{
  echo "<html><title>eLouai's Download Script</title><body>ERROR: File not found. USE force-download.php?file=filepath</body></html>";
  exit;
};
switch( $file_extension )
{
  case "pdf": $ctype="application/pdf"; break;
  case "exe": $ctype="application/octet-stream"; break;
  case "zip": $ctype="application/zip"; break;
  case "doc": $ctype="application/msword"; break;
  case "xls": $ctype="application/vnd.ms-excel"; break;
  case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
  case "gif": $ctype="image/gif"; break;
  case "png": $ctype="image/png"; break;
  case "jpeg":
  case "jpg": $ctype="image/jpg"; break;
  default: $ctype="application/octet-stream";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers 
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();

Keyword not supported: "data source" initializing Entity Framework Context

Just use \" instead ", it should resolve the issue.

Rails: Why "sudo" command is not recognized?

Sudo is a Unix specific command designed to allow a user to carry out administrative tasks with the appropriate permissions. Windows doesn't not have (need?) this.

Yes, windows don't have sudo on its terminal. Try using pip instead.

  1. Install pip using the steps here.
  2. type pip install [package name] on the terminal. In this case, it may be pdfkit or wkhtmltopdf.

How to scroll to bottom in a ScrollView on activity startup

You can do this in layout file:

                android:id="@+id/listViewContent"
                android:layout_width="wrap_content"
                android:layout_height="381dp" 
                android:stackFromBottom="true"
                android:transcriptMode="alwaysScroll">

iPad browser WIDTH & HEIGHT standard

You can try this:

    /*iPad landscape oriented styles */

    @media only screen and (device-width:768px)and (orientation:landscape){
        .yourstyle{

        }

    }

    /*iPad Portrait oriented styles */

    @media only screen and (device-width:768px)and (orientation:portrait){
        .yourstyle{

        }
    }

Retrieving Property name from lambda expression

I've updated @Cameron's answer to include some safety checks against Convert typed lambda expressions:

PropertyInfo GetPropertyName<TSource, TProperty>(
Expression<Func<TSource, TProperty>> propertyLambda)
{
  var body = propertyLambda.Body;
  if (!(body is MemberExpression member)
    && !(body is UnaryExpression unary
      && (member = unary.Operand as MemberExpression) != null))
    throw new ArgumentException($"Expression '{propertyLambda}' " +
      "does not refer to a property.");

  if (!(member.Member is PropertyInfo propInfo))
    throw new ArgumentException($"Expression '{propertyLambda}' " +
      "refers to a field, not a property.");

  var type = typeof(TSource);
  if (!propInfo.DeclaringType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()))
    throw new ArgumentException($"Expresion '{propertyLambda}' " + 
      "refers to a property that is not from type '{type}'.");

  return propInfo;
}

How do I set the selenium webdriver get timeout?

try

driver.executeScript("window.location.href='http://www.sina.com.cn'")

this statement will return immediately.

And after that , you can add a WebDriverWait with timeout to check if the page title or any element is ok.

Hope this will help you.

Programmatically check Play Store for app updates

Google introduced In-app updates feature, (https://developer.android.com/guide/app-bundle/in-app-updates) it works on Lollipop+ and gives you the ability to ask the user for an update with a nice dialog (FLEXIBLE) or with mandatory full-screen message (IMMEDIATE).

Here is how Flexible update will look like: enter image description here

and here is Immedtiate update flow: enter image description here

You can check my answer here https://stackoverflow.com/a/56808529/5502121 to get the complete sample code of implementing both Flexible and Immediate update flows. Hope it helps!

Check/Uncheck a checkbox on datagridview

I was making my own version of a Checkbox to control a DataGridViewCheckBoxColumn when I saw this post wasn't actually answered. To set the checked state of a DataGridViewCheckBoxCell use:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    dataGridView1.Rows[row.Index].SetValues(true);
}

For anyone else trying to accomplish the same thing, here is what I came up with.

This makes the two controls behave like the checkbox column in Gmail. It keeps functionality for both mouse and keyboard.

using System;
using System.Windows.Forms;

namespace Check_UnCheck_All
{
    public partial class Check_UnCheck_All : Form
    {
        public Check_UnCheck_All()
        {
            InitializeComponent();
            dataGridView1.RowCount = 10;
            dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvApps_CellContentClick);
            this.dataGridView1.CellMouseUp += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.myDataGrid_OnCellMouseUp);
            this.dataGridView1.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.myDataGrid_OnCellValueChanged);
            this.checkBox1.Click += new System.EventHandler(this.checkBox1_Click);
        }

        public int chkInt = 0;
        public bool chked = false;

        public void myDataGrid_OnCellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dataGridView1.Rows[0].Index && e.RowIndex != -1)
            {
                DataGridViewCheckBoxCell chk = dataGridView1.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell;

                if (Convert.ToBoolean(chk.Value) == true) chkInt++;
                if (Convert.ToBoolean(chk.Value) == false) chkInt--;
                if (chkInt < dataGridView1.Rows.Count && chkInt > 0)
                {
                    checkBox1.CheckState = CheckState.Indeterminate;
                    chked = true;
                }
                else if (chkInt == 0)
                {
                    checkBox1.CheckState = CheckState.Unchecked;
                    chked = false;
                }
                else if (chkInt == dataGridView1.Rows.Count)
                {
                    checkBox1.CheckState = CheckState.Checked;
                    chked = true;
                }
            }
        }
        public void myDataGrid_OnCellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            // End of edition on each click on column of checkbox
            if (e.ColumnIndex == dataGridView1.Rows[0].Index && e.RowIndex != -1)
            {
                dataGridView1.EndEdit();
            }
            dataGridView1.BeginEdit(true);
        }
        public void dgvApps_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.CurrentCell.GetType() == typeof(DataGridViewCheckBoxCell))
            {
                if (dataGridView1.CurrentCell.IsInEditMode)
                {
                    if (dataGridView1.IsCurrentCellDirty)
                    {
                        dataGridView1.EndEdit();
                    }
                }
                dataGridView1.BeginEdit(true);
            }
        }
        public void checkBox1_Click(object sender, EventArgs e)
        {
            if (chked == true)
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
                    if (chk.Value == chk.TrueValue)
                    {
                        chk.Value = chk.FalseValue;
                    }
                    else
                    {
                        chk.Value = chk.TrueValue;
                    }
                }
                chked = false;
                chkInt = 0;
                return;
            }
            if (chked == false)
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    dataGridView1.Rows[row.Index].SetValues(true);
                }
                chked = true;
                chkInt = dataGridView1.Rows.Count;
            }
        }
    }
}

Randomize a List<T>

Your question is how to randomize a list. This means:

  1. All unique combinations should be possible of happening
  2. All unique combinations should occur with the same distribution (AKA being non-biased).

A large number of the answers posted for this question do NOT satisfy the two requirements above for being "random".

Here's a compact, non-biased pseudo-random function following the Fisher-Yates shuffle method.

public static void Shuffle<T>(this IList<T> list, Random rnd)
{
    for (var i = list.Count-1; i > 0; i--)
    {
        var randomIndex = rnd.Next(i + 1); //maxValue (i + 1) is EXCLUSIVE
        list.Swap(i, randomIndex); 
    }
}

public static void Swap<T>(this IList<T> list, int indexA, int indexB)
{
   var temp = list[indexA];
   list[indexA] = list[indexB];
   list[indexB] = temp;
}

What is a magic number, and why is it bad?

I assume this is a response to my answer to your earlier question. In programming, a magic number is an embedded numerical constant that appears without explanation. If it appears in two distinct locations, it can lead to circumstances where one instance is changed and not another. For both these reasons, it's important to isolate and define the numerical constants outside the places where they're used.

How to change the Title of the window in Qt?

void    QWidget::setWindowTitle ( const QString & )

EDIT: If you are using QtDesigner, on the property tab, there is an editable property called windowTitle which can be found under the QWidget section. The property tab can usually be found on the lower right part of the designer window.

Is it possible to capture the stdout from the sh DSL command in the pipeline

You can try to use as well this functions to capture StdErr StdOut and return code.

def runShell(String command){
    def responseCode = sh returnStatus: true, script: "${command} &> tmp.txt" 
    def output =  readFile(file: "tmp.txt")

    if (responseCode != 0){
      println "[ERROR] ${output}"
      throw new Exception("${output}")
    }else{
      return "${output}"
    }
}

Notice:

&>name means 1>name 2>name -- redirect stdout and stderr to the file name

Delete specific line from a text file?

One way to do it if the file is not very big is to load all the lines into an array:

string[] lines = File.ReadAllLines("filename.txt");
string[] newLines = RemoveUnnecessaryLine(lines);
File.WriteAllLines("filename.txt", newLines);

Form Submission without page refresh

Just catch the submit event and prevent that, then do ajax

$(document).ready(function () {
    $('#myform').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url : $(this).attr('action') || window.location.pathname,
            type: "GET",
            data: $(this).serialize(),
            success: function (data) {
                $("#form_output").html(data);
            },
            error: function (jXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    });
});

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

After trying and searching different solutions, I think the most safest way is adding the following code at the end of the Podfile

post_install do |pi|
   pi.pods_project.targets.each do |t|
       t.build_configurations.each do |bc|
          bc.build_settings['ARCHS[sdk=iphonesimulator*]'] =  `uname -m`
       end
   end
end

This way you only override the iOS simulator's compiler architecture as your current cpu's architecture. Compared to others, this solution will also work on computers with Apple Silicon.

PHP FPM - check if running

Assuming you are on Linux, check if php-fpm is running by searching through the process list:

ps aux | grep php-fpm

If running over IP (as opposed to over Unix socket) then you can also check for the port:

netstat -an | grep :9000

Or using nmap:

nmap localhost -p 9000

Lastly, I've read that you can request the status, but in my experience this has proven unreliable:

/etc/init.d/php5-fpm status

What is the difference between "long", "long long", "long int", and "long long int" in C++?

long is equivalent to long int, just as short is equivalent to short int. A long int is a signed integral type that is at least 32 bits, while a long long or long long int is a signed integral type is at least 64 bits.

This doesn't necessarily mean that a long long is wider than a long. Many platforms / ABIs use the LP64 model - where long (and pointers) are 64 bits wide. Win64 uses the LLP64, where long is still 32 bits, and long long (and pointers) are 64 bits wide.

There's a good summary of 64-bit data models here.

long double doesn't guarantee much other than it will be at least as wide as a double.

javaw.exe cannot find path

Make sure to download these from here:

enter image description here

Also create PATH enviroment variable on you computer like this (if it doesn't exist already):

  1. Right click on My Computer/Computer
  2. Properties
  3. Advanced system settings (or just Advanced)
  4. Enviroment variables
  5. If PATH variable doesn't exist among "User variables" click New (Variable name: PATH, Variable value : C:\Program Files\Java\jdk1.8.0\bin; <-- please check out the right version, this may differ as Oracle keeps updating Java). ; in the end enables assignment of multiple values to PATH variable.
  6. Click OK! Done

enter image description here

To be sure that everything works, open CMD Prompt and type: java -version to check for Java version and javac to be sure that compiler responds.

enter image description here

I hope this helps. Good luck!

How to enable PHP's openssl extension to install Composer?

If you're doing this on Windows without one of the WAMP stacks, here's how to get this going

  1. Download an installation of PHP for Windows. Generally you'll want a non-thread safe install. You can use 32-bit or 64-bit builds
  2. Extract the zip file somewhere. I would suggest C:\php. Composer's installer found it there without any additional prompting
  3. The latest versions of PHP for Windows do not come with a php.ini by default. Instead, you'll see two files, as noted below. Rename one to php.ini or copy it into php.ini.
    • php.ini-development
    • php.ini-production
  4. Open your php.ini file and remove the semicolon from this line (you might want to uncomment other things as well but this line is the only one necessary for Composer)

    ;extension=php_openssl.dll
    

That should be all you need to do. The Composer installer should do everything else you need from here.

How to change the blue highlight color of a UITableViewCell?

Zonble has already provided an excellent answer. I thought it may be useful to include a short code snippet for adding a UIView to the tableview cell that will present as the selected background view.

cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

    UIView *selectionColor = [[UIView alloc] init];
    selectionColor.backgroundColor = [UIColor colorWithRed:(245/255.0) green:(245/255.0) blue:(245/255.0) alpha:1];
    cell.selectedBackgroundView = selectionColor;
  • cell is my UITableViewCell
  • I created a UIView and set its background color using RGB colours (light gray)
  • I then set the cell selectedBackgroundView to be the UIView that I created with my chosen background colour

This worked well for me. Thanks for the tip Zonble.

Hibernate: Automatically creating/updating the db tables based on entity classes

In support to @thorinkor's answer I would extend my answer to use not only @Table (name = "table_name") annotation for entity, but also every child variable of entity class should be annotated with @Column(name = "col_name"). This results into seamless updation to the table on the go.

For those who are looking for a Java class based hibernate config, the rule applies in java based configurations also(NewHibernateUtil). Hope it helps someone else.

Value does not fall within the expected range

I had from a totaly different reason the same notice "Value does not fall within the expected range" from the Visual studio 2008 while trying to use the: Tools -> Windows Embedded Silverlight Tools -> Update Silverlight For Windows Embedded Project.

After spending many ohurs I found out that the problem was that there wasn't a resource file and the update tool looks for the .RC file

Therefor the solution is to add to the resource folder a .RC file and than it works perfectly. I hope it will help someone out there

%Like% Query in spring JpaRepository

when call funtion, I use: findByPlaceContaining("%" + place);

or: findByPlaceContaining(place + "%");

or: findByPlaceContaining("%" + place + "%");

React.js: How to append a component on click?

As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.

In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field

class HealthConditions extends React.Component {
  constructor(props) {
    super(props);


    this.state = {
      inputLinkClicked: false
    }
  }

  handleAddSecondInput() {
    this.setState({
      inputLinkClicked: true
    })
  }


  render() {
    return(
      <main id="wrapper" className="" data-reset-cookie-tab>
        <div id="content" role="main">
          <div className="inner-block">

            <H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>

            <InputField label="Name of condition"
              InputType="text"
              InputId="id-condition"
              InputName="condition"
            />

            {
              this.state.inputLinkClicked?

              <InputField label=""
                InputType="text"
                InputId="id-condition2"
                InputName="condition2"
              />

              :

              <div></div>
            }

            <button
              type="button"
              className="make-button-link"
              data-add-button=""
              href="#"
              onClick={this.handleAddSecondInput}
            >
              Add a condition
            </button>

            <FormButton buttonLabel="Next"
              handleSubmit={this.handleSubmit}
              linkto={
                this.state.illnessOrDisability === 'true' ?
                "/404"
                :
                "/add-your-details"
              }
            />

            <BackLink backLink="/add-your-details" />

          </div>
         </div>
      </main>
    );
  }
}

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

You can use T-SQL to convert the date before it gets to your .NET program. This often is simpler if you don't need to do additional date conversion in your .NET program.

DECLARE @Date DATETIME = Getdate()
DECLARE @DateInt INT = CONVERT(VARCHAR(30), @Date, 112)
DECLARE @TimeInt INT = REPLACE(CONVERT(VARCHAR(30), @Date, 108), ':', '')
DECLARE @DateTimeInt BIGINT = CONVERT(VARCHAR(30), @Date, 112) + REPLACE(CONVERT(VARCHAR(30), @Date, 108), ':', '')
SELECT @Date as Date, @DateInt DateInt, @TimeInt TimeInt, @DateTimeInt DateTimeInt

Date                    DateInt     TimeInt     DateTimeInt
------------------------- ----------- ----------- --------------------
2013-01-07 15:08:21.680 20130107    150821      20130107150821

Use HTML5 to resize an image before upload

if any interested I've made a typescript version:

interface IResizeImageOptions {
  maxSize: number;
  file: File;
}
const resizeImage = (settings: IResizeImageOptions) => {
  const file = settings.file;
  const maxSize = settings.maxSize;
  const reader = new FileReader();
  const image = new Image();
  const canvas = document.createElement('canvas');
  const dataURItoBlob = (dataURI: string) => {
    const bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
        atob(dataURI.split(',')[1]) :
        unescape(dataURI.split(',')[1]);
    const mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
    const max = bytes.length;
    const ia = new Uint8Array(max);
    for (var i = 0; i < max; i++) ia[i] = bytes.charCodeAt(i);
    return new Blob([ia], {type:mime});
  };
  const resize = () => {
    let width = image.width;
    let height = image.height;

    if (width > height) {
        if (width > maxSize) {
            height *= maxSize / width;
            width = maxSize;
        }
    } else {
        if (height > maxSize) {
            width *= maxSize / height;
            height = maxSize;
        }
    }

    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(image, 0, 0, width, height);
    let dataUrl = canvas.toDataURL('image/jpeg');
    return dataURItoBlob(dataUrl);
  };

  return new Promise((ok, no) => {
      if (!file.type.match(/image.*/)) {
        no(new Error("Not an image"));
        return;
      }

      reader.onload = (readerEvent: any) => {
        image.onload = () => ok(resize());
        image.src = readerEvent.target.result;
      };
      reader.readAsDataURL(file);
  })    
};

and here's the javascript result:

var resizeImage = function (settings) {
    var file = settings.file;
    var maxSize = settings.maxSize;
    var reader = new FileReader();
    var image = new Image();
    var canvas = document.createElement('canvas');
    var dataURItoBlob = function (dataURI) {
        var bytes = dataURI.split(',')[0].indexOf('base64') >= 0 ?
            atob(dataURI.split(',')[1]) :
            unescape(dataURI.split(',')[1]);
        var mime = dataURI.split(',')[0].split(':')[1].split(';')[0];
        var max = bytes.length;
        var ia = new Uint8Array(max);
        for (var i = 0; i < max; i++)
            ia[i] = bytes.charCodeAt(i);
        return new Blob([ia], { type: mime });
    };
    var resize = function () {
        var width = image.width;
        var height = image.height;
        if (width > height) {
            if (width > maxSize) {
                height *= maxSize / width;
                width = maxSize;
            }
        } else {
            if (height > maxSize) {
                width *= maxSize / height;
                height = maxSize;
            }
        }
        canvas.width = width;
        canvas.height = height;
        canvas.getContext('2d').drawImage(image, 0, 0, width, height);
        var dataUrl = canvas.toDataURL('image/jpeg');
        return dataURItoBlob(dataUrl);
    };
    return new Promise(function (ok, no) {
        if (!file.type.match(/image.*/)) {
            no(new Error("Not an image"));
            return;
        }
        reader.onload = function (readerEvent) {
            image.onload = function () { return ok(resize()); };
            image.src = readerEvent.target.result;
        };
        reader.readAsDataURL(file);
    });
};

usage is like:

resizeImage({
    file: $image.files[0],
    maxSize: 500
}).then(function (resizedImage) {
    console.log("upload resized image")
}).catch(function (err) {
    console.error(err);
});

or (async/await):

const config = {
    file: $image.files[0],
    maxSize: 500
};
const resizedImage = await resizeImage(config)
console.log("upload resized image")

5.7.57 SMTP - Client was not authenticated to send anonymous mail during MAIL FROM error

If you reorder your code this way, it should work:

SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(mailOut, pswMailOut);
client.Port = 587; // 25 587
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;

MailMessage mail = new MailMessage();            
mail.From = new MailAddress(mailOut, displayNameMailOut);
mail.To.Add(new MailAddress(mailOfTestDestine));
mail.Subject = "A special subject";
mail.Body = sb.ToString();

client.Send(mail);

What is the equivalent of bigint in C#?

You can use long type or Int64

select data up to a space?

select left(col, charindex(' ', col) - 1)

MySQL compare DATE string with string from DATETIME field

Use the following:

SELECT * FROM `calendar` WHERE DATE(startTime) = '2010-04-29'

Just for reference I have a 2 million record table, I ran a similar query. Salils answer took 4.48 seconds, the above took 2.25 seconds.

So if the table is BIG I would suggest this rather.

How do I mock a class without an interface?

Most mocking frameworks (Moq and RhinoMocks included) generate proxy classes as a substitute for your mocked class, and override the virtual methods with behavior that you define. Because of this, you can only mock interfaces, or virtual methods on concrete or abstract classes. Additionally, if you're mocking a concrete class, you almost always need to provide a parameterless constructor so that the mocking framework knows how to instantiate the class.

Why the aversion to creating interfaces in your code?

Convert Char to String in C

Using fgetc(fp) only to be able to call strcpy(buffer,c); doesn't seem right.

You could simply build this buffer on your own:

char buffer[MAX_SIZE_OF_MY_BUFFER];

int i = 0;
char ch;
while (i < MAX_SIZE_OF_MY_BUFFER - 1 && (ch = fgetc(fp)) != EOF) {
    buffer[i++] = ch;
}
buffer[i] = '\0';  // terminating character

Note that this relies on the fact that you will read less than MAX_SIZE_OF_MY_BUFFER characters

The database cannot be opened because it is version 782. This server supports version 706 and earlier. A downgrade path is not supported

Another solution is to migrate the database to e.g 2012 when you "export" the DB from e.g. Sql Server manager 2014. This is done in menu Tasks-> generate scripts when right-click on DB. Just follow this instruction:

https://www.mssqltips.com/sqlservertip/2810/how-to-migrate-a-sql-server-database-to-a-lower-version/

It generates an scripts with everything and then in your SQL server manager e.g. 2012 run the script as specified in the instruction. I have performed the test with success.

Trim whitespace from a String

Your code is fine. What you are seeing is a linker issue.

If you put your code in a single file like this:

#include <iostream>
#include <string>

using namespace std;

string trim(const string& str)
{
    size_t first = str.find_first_not_of(' ');
    if (string::npos == first)
    {
        return str;
    }
    size_t last = str.find_last_not_of(' ');
    return str.substr(first, (last - first + 1));
}

int main() {
    string s = "abc ";
    cout << trim(s);

}

then do g++ test.cc and run a.out, you will see it works.

You should check if the file that contains the trim function is included in the link stage of your compilation process.

Multiple types were found that match the controller named 'Home'

I have found this error can occur with traditional ASP.NET website when you create the Controller in non App_Code directory (sometimes Visual Studio prevents this).

It sets the file type to "Compile" whereas any code added to "App_Code" is set to "Content". If you copy or move the file into App_Code then it is still set as "Compile".

I suspect it has something to with Website Project operation as website projects do not have any build operation.Clearing the bin folder and changing to "Content" seems to fix it.

Laravel Eloquent get results grouped by days

I know this is an OLD Question and there are multiple answers. How ever according to the docs and my experience on laravel below is the good "Eloquent way" of handling things

In your model, add a mutator/Getter like this

public function getCreatedAtTimeAttribute()
{
   return $this->created_at->toDateString();
}

Another way is to cast the columns in your model, populate the $cast array

$casts = [
   'created_at' => 'string'
]

The catch here is that you won't be able to use the Carbon on this model again since Eloquent will always cast the column into string

Hope it helps :)

Intercept page exit event

I have users who have not been completing all required data.

<cfset unloadCheck=0>//a ColdFusion precheck in my page generation to see if unload check is needed
var erMsg="";
$(document).ready(function(){
<cfif q.myData eq "">
    <cfset unloadCheck=1>
    $("#myInput").change(function(){
        verify(); //function elsewhere that checks all fields and populates erMsg with error messages for any fail(s)
        if(erMsg=="") window.onbeforeunload = null; //all OK so let them pass
        else window.onbeforeunload = confirmExit(); //borrowed from Jantimon above;
    });
});
<cfif unloadCheck><!--- if any are outstanding, set the error message and the unload alert --->
    verify();
    window.onbeforeunload = confirmExit;
    function confirmExit() {return "Data is incomplete for this Case:"+erMsg;}
</cfif>

adding css class to multiple elements

try this:

.button input, .button a {
//css here
}

That will apply the style to all a tags nested inside of <p class="button"></p>

How to replace blank (null ) values with 0 for all records?

I used a two step process to change rows with "blank" values to "Null" values as place holders.

UPDATE [TableName] SET [TableName].[ColumnName] = "0"
WHERE ((([TableName].[ColumnName])=""));

UPDATE [TableName] SET [TableName].[ColumnName] = "Null"
WHERE ((([TableName].[ColumnName])="0"));

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

How to set a default entity property value with Hibernate

If you want to do it in database:

Set the default value in database (sql server sample):

ALTER TABLE [TABLE_NAME] ADD  CONSTRAINT [CONSTRAINT_NAME]  DEFAULT (newid()) FOR [COLUMN_NAME]

Mapping hibernate file:

    <hibernate-mapping ....
    ...    
    <property name="fieldName" column="columnName" type="Guid" access="field" not-null="false"  insert="false" update="false"  />
    ...

See, the key is insert="false" update="false"

iPhone - Grand Central Dispatch main thread

Dispatching blocks to the main queue from the main thread can be useful. It gives the main queue a chance to handle other blocks that have been queued so that you're not simply blocking everything else from executing.

For example you could write an essentially single threaded server that nonetheless handles many concurrent connections. As long as no individual block in the queue takes too long the server stays responsive to new requests.

If your program does nothing but spend its whole life responding to events then this can be quite natural. You just set up your event handlers to run on the main queue and then call dispatch_main(), and you may not need to worry about thread safety at all.

Why should C++ programmers minimize use of 'new'?

There are two widely-used memory allocation techniques: automatic allocation and dynamic allocation. Commonly, there is a corresponding region of memory for each: the stack and the heap.

Stack

The stack always allocates memory in a sequential fashion. It can do so because it requires you to release the memory in the reverse order (First-In, Last-Out: FILO). This is the memory allocation technique for local variables in many programming languages. It is very, very fast because it requires minimal bookkeeping and the next address to allocate is implicit.

In C++, this is called automatic storage because the storage is claimed automatically at the end of scope. As soon as execution of current code block (delimited using {}) is completed, memory for all variables in that block is automatically collected. This is also the moment where destructors are invoked to clean up resources.

Heap

The heap allows for a more flexible memory allocation mode. Bookkeeping is more complex and allocation is slower. Because there is no implicit release point, you must release the memory manually, using delete or delete[] (free in C). However, the absence of an implicit release point is the key to the heap's flexibility.

Reasons to use dynamic allocation

Even if using the heap is slower and potentially leads to memory leaks or memory fragmentation, there are perfectly good use cases for dynamic allocation, as it's less limited.

Two key reasons to use dynamic allocation:

  • You don't know how much memory you need at compile time. For instance, when reading a text file into a string, you usually don't know what size the file has, so you can't decide how much memory to allocate until you run the program.

  • You want to allocate memory which will persist after leaving the current block. For instance, you may want to write a function string readfile(string path) that returns the contents of a file. In this case, even if the stack could hold the entire file contents, you could not return from a function and keep the allocated memory block.

Why dynamic allocation is often unnecessary

In C++ there's a neat construct called a destructor. This mechanism allows you to manage resources by aligning the lifetime of the resource with the lifetime of a variable. This technique is called RAII and is the distinguishing point of C++. It "wraps" resources into objects. std::string is a perfect example. This snippet:

int main ( int argc, char* argv[] )
{
    std::string program(argv[0]);
}

actually allocates a variable amount of memory. The std::string object allocates memory using the heap and releases it in its destructor. In this case, you did not need to manually manage any resources and still got the benefits of dynamic memory allocation.

In particular, it implies that in this snippet:

int main ( int argc, char* argv[] )
{
    std::string * program = new std::string(argv[0]);  // Bad!
    delete program;
}

there is unneeded dynamic memory allocation. The program requires more typing (!) and introduces the risk of forgetting to deallocate the memory. It does this with no apparent benefit.

Why you should use automatic storage as often as possible

Basically, the last paragraph sums it up. Using automatic storage as often as possible makes your programs:

  • faster to type;
  • faster when run;
  • less prone to memory/resource leaks.

Bonus points

In the referenced question, there are additional concerns. In particular, the following class:

class Line {
public:
    Line();
    ~Line();
    std::string* mString;
};

Line::Line() {
    mString = new std::string("foo_bar");
}

Line::~Line() {
    delete mString;
}

Is actually a lot more risky to use than the following one:

class Line {
public:
    Line();
    std::string mString;
};

Line::Line() {
    mString = "foo_bar";
    // note: there is a cleaner way to write this.
}

The reason is that std::string properly defines a copy constructor. Consider the following program:

int main ()
{
    Line l1;
    Line l2 = l1;
}

Using the original version, this program will likely crash, as it uses delete on the same string twice. Using the modified version, each Line instance will own its own string instance, each with its own memory and both will be released at the end of the program.

Other notes

Extensive use of RAII is considered a best practice in C++ because of all the reasons above. However, there is an additional benefit which is not immediately obvious. Basically, it's better than the sum of its parts. The whole mechanism composes. It scales.

If you use the Line class as a building block:

 class Table
 {
      Line borders[4];
 };

Then

 int main ()
 {
     Table table;
 }

allocates four std::string instances, four Line instances, one Table instance and all the string's contents and everything is freed automagically.

ssh connection refused on Raspberry Pi

Apparently, the SSH server on Raspbian is now disabled by default. If there is no server listening for connections, it will not accept them. You can manually enable the SSH server according to this raspberrypi.org tutorial :

As of the November 2016 release, Raspbian has the SSH server disabled by default.

There are now multiple ways to enable it. Choose one:

From the desktop

  1. Launch Raspberry Pi Configuration from the Preferences menu
  2. Navigate to the Interfaces tab
  3. Select Enabled next to SSH
  4. Click OK

From the terminal with raspi-config

  1. Enter sudo raspi-config in a terminal window
  2. Select Interfacing Options
  3. Navigate to and select SSH
  4. Choose Yes
  5. Select Ok
  6. Choose Finish

Start the SSH service with systemctl

sudo systemctl enable ssh
sudo systemctl start ssh

On a headless Raspberry Pi

For headless setup, SSH can be enabled by placing a file named ssh, without any extension, onto the boot partition of the SD card. When the Pi boots, it looks for the ssh file. If it is found, SSH is enabled, and the file is deleted. The content of the file does not matter: it could contain text, or nothing at all.

What is the "hasClass" function with plain JavaScript?

Simply use classList.contains():

if (document.body.classList.contains('thatClass')) {
    // do some stuff
}

Other uses of classList:

document.body.classList.add('thisClass');
// $('body').addClass('thisClass');

document.body.classList.remove('thatClass');
// $('body').removeClass('thatClass');

document.body.classList.toggle('anotherClass');
// $('body').toggleClass('anotherClass');

Browser Support:

  • Chrome 8.0
  • Firefox 3.6
  • IE 10
  • Opera 11.50
  • Safari 5.1

classList Browser Support

Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3

In my case, I was producing multiple products from the same project. For one of the products, the main.m file imported a header file from another folder under the same project. But that file was not included in "Complied Sources" under "Build Phase". This caused a linker error.

After carefully comparing the "Build Phases" settings for a product that could be built successfully, I realized that the .m file of the header needs to be included in the list of "Compiled Source". My issue was resolved after adding that file. Attaching a picture for clarity. The highlighted file had to be added.

enter image description here

How to get the url parameters using AngularJS

Simple and easist way to get url value

First add # to url (e:g -  test.html#key=value)

url in browser (https://stackover.....king-angularjs-1-5#?brand=stackoverflow)

var url = window.location.href 

(output: url = "https://stackover.....king-angularjs-1-5#?brand=stackoverflow")

url.split('=').pop()
output "stackoverflow"

How to delete and recreate from scratch an existing EF Code First database

If you created your database following this tutorial: https://msdn.microsoft.com/en-au/data/jj193542.aspx

... then this might work:

  1. Delete all .mdf and .ldf files in your project directory
  2. Go to View / SQL Server Object Explorer and delete the database from the (localdb)\v11.0 subnode. See also https://stackoverflow.com/a/15832184/2279059

How can I get a JavaScript stack trace when I throw an exception?

Edit 2 (2017):

In all modern browsers you can simply call: console.trace(); (MDN Reference)

Edit 1 (2013):

A better (and simpler) solution as pointed out in the comments on the original question is to use the stack property of an Error object like so:

function stackTrace() {
    var err = new Error();
    return err.stack;
}

This will generate output like this:

DBX.Utils.stackTrace@http://localhost:49573/assets/js/scripts.js:44
DBX.Console.Debug@http://localhost:49573/assets/js/scripts.js:9
.success@http://localhost:49573/:462
x.Callbacks/c@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
x.Callbacks/p.fireWith@http://localhost:49573/assets/js/jquery-1.10.2.min.js:4
k@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6
.send/r@http://localhost:49573/assets/js/jquery-1.10.2.min.js:6

Giving the name of the calling function along with the URL, its calling function, and so on.

Original (2009):

A modified version of this snippet may somewhat help:

function stacktrace() { 
  function st2(f) {
    return !f ? [] : 
        st2(f.caller).concat([f.toString().split('(')[0].substring(9) + '(' + f.arguments.join(',') + ')']);
  }
  return st2(arguments.callee.caller);
}

Catch an exception thrown by an async void method

The exception can be caught in the async function.

public async void Foo()
{
    try
    {
        var x = await DoSomethingAsync();
        /* Handle the result, but sometimes an exception might be thrown
           For example, DoSomethingAsync get's data from the network
           and the data is invalid... a ProtocolException might be thrown */
    }
    catch (ProtocolException ex)
    {
          /* The exception will be caught here */
    }
}

public void DoFoo()
{
    Foo();
}

How to get the text of the selected value of a dropdown list?

The easiest way is through css3 $("select option:selected") and then use the .text() or .html() function. depending on what you want to have.

Android XXHDPI resources

The resolution is 480 dpi, the launcher icon is 144*144px all is scaled 3x respect to mdpi (so called "base", "baseline" or "normal") sizes.

Display UIViewController as Popup in iPhone

NOTE : This solution is broken in iOS 8. I will post new solution ASAP.

I am going to answer here using storyboard but it is also possible without storyboard.

  1. Init: Create two UIViewController in storyboard.

    • lets say FirstViewController which is normal and SecondViewController which will be the popup.

  2. Modal Segue: Put UIButton in FirstViewController and create a segue on this UIButton to SecondViewController as modal segue.

  3. Make Transparent: Now select UIView (UIView Which is created by default with UIViewController) of SecondViewController and change its background color to clear color.

  4. Make background Dim: Add an UIImageView in SecondViewController which covers whole screen and sets its image to some dimmed semi transparent image. You can get a sample from here : UIAlertView Background Image

  5. Display Design: Now add an UIView and make any kind of design you want to show. Here is a screenshot of my storyboard storyboard

    • Here I have add segue on login button which open SecondViewController as popup to ask username and password
  6. Important: Now that main step. We want that SecondViewController doesn't hide FirstViewController completely. We have set clear color but this is not enough. By default it adds black behind model presentation so we have to add one line of code in viewDidLoad of FirstViewController. You can add it at another place also but it should run before segue.

    [self setModalPresentationStyle:UIModalPresentationCurrentContext];

  7. Dismiss: When to dismiss depends on your use case. This is a modal presentation so to dismiss we do what we do for modal presentation:

    [self dismissViewControllerAnimated:YES completion:Nil];

Thats all.....

Any kind of suggestion and comment are welcome.

Demo : You can get demo source project from Here : Popup Demo

NEW : Someone have done very nice job on this concept : MZFormSheetController
New : I found one more code to get this kind of function : KLCPopup


iOS 8 Update : I made this method to work with both iOS 7 and iOS 8

+ (void)setPresentationStyleForSelfController:(UIViewController *)selfController presentingController:(UIViewController *)presentingController
{
    if (iOSVersion >= 8.0)
    {
        presentingController.providesPresentationContextTransitionStyle = YES;
        presentingController.definesPresentationContext = YES;

        [presentingController setModalPresentationStyle:UIModalPresentationOverCurrentContext];
    }
    else
    {
        [selfController setModalPresentationStyle:UIModalPresentationCurrentContext];
        [selfController.navigationController setModalPresentationStyle:UIModalPresentationCurrentContext];
    }
}

Can use this method inside prepareForSegue deligate like this

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

    PopUpViewController *popup = segue.destinationViewController;
    [self setPresentationStyleForSelfController:self presentingController:popup]
}

Directory index forbidden by Options directive

Another issue that you might run into if you're running RHEL (I ran into it) is that there is a default welcome page configured with the httpd package that will override your settings, even if you put Options Indexes. The file is in /etc/httpd/conf.d/welcome.conf. See the following link for more info: http://wpapi.com/solved-issue-directory-index-forbidden-by-options-directive/

"SyntaxError: Unexpected token < in JSON at position 0"

The wording of the error message corresponds to what you get from Google Chrome when you run JSON.parse('<...'). I know you said the server is setting Content-Type:application/json, but I am led to believe the response body is actually HTML.

Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0"

with the line console.error(this.props.url, status, err.toString()) underlined.

The err was actually thrown within jQuery, and passed to you as a variable err. The reason that line is underlined is simply because that is where you are logging it.

I would suggest that you add to your logging. Looking at the actual xhr (XMLHttpRequest) properties to learn more about the response. Try adding console.warn(xhr.responseText) and you will most likely see the HTML that is being received.

Hash and salt passwords in C#

I've been reading that hashing functions like SHA256 weren't really intended for use with storing passwords: https://patrickmn.com/security/storing-passwords-securely/#notpasswordhashes

Instead adaptive key derivation functions like PBKDF2, bcrypt or scrypt were. Here is a PBKDF2 based one that Microsoft wrote for PasswordHasher in their Microsoft.AspNet.Identity library:

/* =======================
 * HASHED PASSWORD FORMATS
 * =======================
 * 
 * Version 3:
 * PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
 * Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
 * (All UInt32s are stored big-endian.)
 */

public string HashPassword(string password)
{
    var prf = KeyDerivationPrf.HMACSHA256;
    var rng = RandomNumberGenerator.Create();
    const int iterCount = 10000;
    const int saltSize = 128 / 8;
    const int numBytesRequested = 256 / 8;

    // Produce a version 3 (see comment above) text hash.
    var salt = new byte[saltSize];
    rng.GetBytes(salt);
    var subkey = KeyDerivation.Pbkdf2(password, salt, prf, iterCount, numBytesRequested);

    var outputBytes = new byte[13 + salt.Length + subkey.Length];
    outputBytes[0] = 0x01; // format marker
    WriteNetworkByteOrder(outputBytes, 1, (uint)prf);
    WriteNetworkByteOrder(outputBytes, 5, iterCount);
    WriteNetworkByteOrder(outputBytes, 9, saltSize);
    Buffer.BlockCopy(salt, 0, outputBytes, 13, salt.Length);
    Buffer.BlockCopy(subkey, 0, outputBytes, 13 + saltSize, subkey.Length);
    return Convert.ToBase64String(outputBytes);
}

public bool VerifyHashedPassword(string hashedPassword, string providedPassword)
{
    var decodedHashedPassword = Convert.FromBase64String(hashedPassword);

    // Wrong version
    if (decodedHashedPassword[0] != 0x01)
        return false;

    // Read header information
    var prf = (KeyDerivationPrf)ReadNetworkByteOrder(decodedHashedPassword, 1);
    var iterCount = (int)ReadNetworkByteOrder(decodedHashedPassword, 5);
    var saltLength = (int)ReadNetworkByteOrder(decodedHashedPassword, 9);

    // Read the salt: must be >= 128 bits
    if (saltLength < 128 / 8)
    {
        return false;
    }
    var salt = new byte[saltLength];
    Buffer.BlockCopy(decodedHashedPassword, 13, salt, 0, salt.Length);

    // Read the subkey (the rest of the payload): must be >= 128 bits
    var subkeyLength = decodedHashedPassword.Length - 13 - salt.Length;
    if (subkeyLength < 128 / 8)
    {
        return false;
    }
    var expectedSubkey = new byte[subkeyLength];
    Buffer.BlockCopy(decodedHashedPassword, 13 + salt.Length, expectedSubkey, 0, expectedSubkey.Length);

    // Hash the incoming password and verify it
    var actualSubkey = KeyDerivation.Pbkdf2(providedPassword, salt, prf, iterCount, subkeyLength);
    return actualSubkey.SequenceEqual(expectedSubkey);
}

private static void WriteNetworkByteOrder(byte[] buffer, int offset, uint value)
{
    buffer[offset + 0] = (byte)(value >> 24);
    buffer[offset + 1] = (byte)(value >> 16);
    buffer[offset + 2] = (byte)(value >> 8);
    buffer[offset + 3] = (byte)(value >> 0);
}

private static uint ReadNetworkByteOrder(byte[] buffer, int offset)
{
    return ((uint)(buffer[offset + 0]) << 24)
        | ((uint)(buffer[offset + 1]) << 16)
        | ((uint)(buffer[offset + 2]) << 8)
        | ((uint)(buffer[offset + 3]));
}

Note this requires Microsoft.AspNetCore.Cryptography.KeyDerivation nuget package installed which requires .NET Standard 2.0 (.NET 4.6.1 or higher). For earlier versions of .NET see the Crypto class from Microsoft's System.Web.Helpers library.

Update Nov 2015
Updated answer to use an implementation from a different Microsoft library which uses PBKDF2-HMAC-SHA256 hashing instead of PBKDF2-HMAC-SHA1 (note PBKDF2-HMAC-SHA1 is still secure if iterCount is high enough). You can check out the source the simplified code was copied from as it actually handles validating and upgrading hashes implemented from previous answer, useful if you need to increase iterCount in the future.

How to get text from each cell of an HTML table?

I have not used Selenium 2. Selenium 1.x has selenium.getTable("tablename".columnNumber.rowNumber) to reach the required cell. May be you can use webdriverbackedselenium and do this.

And you can get the total rows and columns by using

int numOfRows = selenium.getXpathCount("//table[@id='tableid']//tr")

int numOfCols=selenium.getXpathCount("//table[@id='tableid']//tr//td")

CSS media query to target only iOS devices

As mentioned above, the short answer is no. But I'm in need of something similar in the app I'm working on now, yet the areas where the CSS needs to be different are limited to very specific areas of a page.

If you're like me and don't need to serve up an entirely different stylesheet, another option would be to detect a device running iOS in the way described in this question's selected answer: Detect if device is iOS

Once you've detected the iOS device you could add a class to the area you're targeting using Javascript (eg. the document.getElementsByTagName("yourElementHere")[0].setAttribute("class", "iOS-device");, jQuery, PHP or whatever, and style that class accordingly using the pre-existing stylesheet.

.iOS-device {
      style-you-want-to-set: yada;
}

How to remove docker completely from ubuntu 14.04

Apparently, the system I was using had the docker-ce not Docker. Thus, running below command did the trick.

sudo apt-get purge docker-ce

sudo rm -rf /var/lib/docker

hope it helps

Error importing SQL dump into MySQL: Unknown database / Can't create database

If you create your database in direct admin or cpanel, you must edit your sql with notepad or notepad++ and change CREATE DATABASE command to CREATE DATABASE IF NOT EXISTS in line22

Calculate the mean by group

There are many ways to do this in R. Specifically, by, aggregate, split, and plyr, cast, tapply, data.table, dplyr, and so forth.

Broadly speaking, these problems are of the form split-apply-combine. Hadley Wickham has written a beautiful article that will give you deeper insight into the whole category of problems, and it is well worth reading. His plyr package implements the strategy for general data structures, and dplyr is a newer implementation performance tuned for data frames. They allow for solving problems of the same form but of even greater complexity than this one. They are well worth learning as a general tool for solving data manipulation problems.

Performance is an issue on very large datasets, and for that it is hard to beat solutions based on data.table. If you only deal with medium-sized datasets or smaller, however, taking the time to learn data.table is likely not worth the effort. dplyr can also be fast, so it is a good choice if you want to speed things up, but don't quite need the scalability of data.table.

Many of the other solutions below do not require any additional packages. Some of them are even fairly fast on medium-large datasets. Their primary disadvantage is either one of metaphor or of flexibility. By metaphor I mean that it is a tool designed for something else being coerced to solve this particular type of problem in a 'clever' way. By flexibility I mean they lack the ability to solve as wide a range of similar problems or to easily produce tidy output.


Examples

base functions

tapply:

tapply(df$speed, df$dive, mean)
#     dive1     dive2 
# 0.5419921 0.5103974

aggregate:

aggregate takes in data.frames, outputs data.frames, and uses a formula interface.

aggregate( speed ~ dive, df, mean )
#    dive     speed
# 1 dive1 0.5790946
# 2 dive2 0.4864489

by:

In its most user-friendly form, it takes in vectors and applies a function to them. However, its output is not in a very manipulable form.:

res.by <- by(df$speed, df$dive, mean)
res.by
# df$dive: dive1
# [1] 0.5790946
# ---------------------------------------
# df$dive: dive2
# [1] 0.4864489

To get around this, for simple uses of by the as.data.frame method in the taRifx library works:

library(taRifx)
as.data.frame(res.by)
#    IDX1     value
# 1 dive1 0.6736807
# 2 dive2 0.4051447

split:

As the name suggests, it performs only the "split" part of the split-apply-combine strategy. To make the rest work, I'll write a small function that uses sapply for apply-combine. sapply automatically simplifies the result as much as possible. In our case, that means a vector rather than a data.frame, since we've got only 1 dimension of results.

splitmean <- function(df) {
  s <- split( df, df$dive)
  sapply( s, function(x) mean(x$speed) )
}
splitmean(df)
#     dive1     dive2 
# 0.5790946 0.4864489 

External packages

data.table:

library(data.table)
setDT(df)[ , .(mean_speed = mean(speed)), by = dive]
#    dive mean_speed
# 1: dive1  0.5419921
# 2: dive2  0.5103974

dplyr:

library(dplyr)
group_by(df, dive) %>% summarize(m = mean(speed))

plyr (the pre-cursor of dplyr)

Here's what the official page has to say about plyr:

It’s already possible to do this with base R functions (like split and the apply family of functions), but plyr makes it all a bit easier with:

  • totally consistent names, arguments and outputs
  • convenient parallelisation through the foreach package
  • input from and output to data.frames, matrices and lists
  • progress bars to keep track of long running operations
  • built-in error recovery, and informative error messages
  • labels that are maintained across all transformations

In other words, if you learn one tool for split-apply-combine manipulation it should be plyr.

library(plyr)
res.plyr <- ddply( df, .(dive), function(x) mean(x$speed) )
res.plyr
#    dive        V1
# 1 dive1 0.5790946
# 2 dive2 0.4864489

reshape2:

The reshape2 library is not designed with split-apply-combine as its primary focus. Instead, it uses a two-part melt/cast strategy to perform a wide variety of data reshaping tasks. However, since it allows an aggregation function it can be used for this problem. It would not be my first choice for split-apply-combine operations, but its reshaping capabilities are powerful and thus you should learn this package as well.

library(reshape2)
dcast( melt(df), variable ~ dive, mean)
# Using dive as id variables
#   variable     dive1     dive2
# 1    speed 0.5790946 0.4864489

Benchmarks

10 rows, 2 groups

library(microbenchmark)
m1 <- microbenchmark(
  by( df$speed, df$dive, mean),
  aggregate( speed ~ dive, df, mean ),
  splitmean(df),
  ddply( df, .(dive), function(x) mean(x$speed) ),
  dcast( melt(df), variable ~ dive, mean),
  dt[, mean(speed), by = dive],
  summarize( group_by(df, dive), m = mean(speed) ),
  summarize( group_by(dt, dive), m = mean(speed) )
)

> print(m1, signif = 3)
Unit: microseconds
                                           expr  min   lq   mean median   uq  max neval      cld
                    by(df$speed, df$dive, mean)  302  325  343.9    342  362  396   100  b      
              aggregate(speed ~ dive, df, mean)  904  966 1012.1   1020 1060 1130   100     e   
                                  splitmean(df)  191  206  249.9    220  232 1670   100 a       
  ddply(df, .(dive), function(x) mean(x$speed)) 1220 1310 1358.1   1340 1380 2740   100      f  
         dcast(melt(df), variable ~ dive, mean) 2150 2330 2440.7   2430 2490 4010   100        h
                   dt[, mean(speed), by = dive]  599  629  667.1    659  704  771   100   c     
 summarize(group_by(df, dive), m = mean(speed))  663  710  774.6    744  782 2140   100    d    
 summarize(group_by(dt, dive), m = mean(speed)) 1860 1960 2051.0   2020 2090 3430   100       g 

autoplot(m1)

benchmark 10 rows

As usual, data.table has a little more overhead so comes in about average for small datasets. These are microseconds, though, so the differences are trivial. Any of the approaches works fine here, and you should choose based on:

  • What you're already familiar with or want to be familiar with (plyr is always worth learning for its flexibility; data.table is worth learning if you plan to analyze huge datasets; by and aggregate and split are all base R functions and thus universally available)
  • What output it returns (numeric, data.frame, or data.table -- the latter of which inherits from data.frame)

10 million rows, 10 groups

But what if we have a big dataset? Let's try 10^7 rows split over ten groups.

df <- data.frame(dive=factor(sample(letters[1:10],10^7,replace=TRUE)),speed=runif(10^7))
dt <- data.table(df)
setkey(dt,dive)

m2 <- microbenchmark(
  by( df$speed, df$dive, mean),
  aggregate( speed ~ dive, df, mean ),
  splitmean(df),
  ddply( df, .(dive), function(x) mean(x$speed) ),
  dcast( melt(df), variable ~ dive, mean),
  dt[,mean(speed),by=dive],
  times=2
)

> print(m2, signif = 3)
Unit: milliseconds
                                           expr   min    lq    mean median    uq   max neval      cld
                    by(df$speed, df$dive, mean)   720   770   799.1    791   816   958   100    d    
              aggregate(speed ~ dive, df, mean) 10900 11000 11027.0  11000 11100 11300   100        h
                                  splitmean(df)   974  1040  1074.1   1060  1100  1280   100     e   
  ddply(df, .(dive), function(x) mean(x$speed))  1050  1080  1110.4   1100  1130  1260   100      f  
         dcast(melt(df), variable ~ dive, mean)  2360  2450  2492.8   2490  2520  2620   100       g 
                   dt[, mean(speed), by = dive]   119   120   126.2    120   122   212   100 a       
 summarize(group_by(df, dive), m = mean(speed))   517   521   531.0    522   532   620   100   c     
 summarize(group_by(dt, dive), m = mean(speed))   154   155   174.0    156   189   321   100  b      

autoplot(m2)

benchmark 1e7 rows, 10 groups

Then data.table or dplyr using operating on data.tables is clearly the way to go. Certain approaches (aggregate and dcast) are beginning to look very slow.

10 million rows, 1,000 groups

If you have more groups, the difference becomes more pronounced. With 1,000 groups and the same 10^7 rows:

df <- data.frame(dive=factor(sample(seq(1000),10^7,replace=TRUE)),speed=runif(10^7))
dt <- data.table(df)
setkey(dt,dive)

# then run the same microbenchmark as above
print(m3, signif = 3)
Unit: milliseconds
                                           expr   min    lq    mean median    uq   max neval    cld
                    by(df$speed, df$dive, mean)   776   791   816.2    810   828   925   100  b    
              aggregate(speed ~ dive, df, mean) 11200 11400 11460.2  11400 11500 12000   100      f
                                  splitmean(df)  5940  6450  7562.4   7470  8370 11200   100     e 
  ddply(df, .(dive), function(x) mean(x$speed))  1220  1250  1279.1   1280  1300  1440   100   c   
         dcast(melt(df), variable ~ dive, mean)  2110  2190  2267.8   2250  2290  2750   100    d  
                   dt[, mean(speed), by = dive]   110   111   113.5    111   113   143   100 a     
 summarize(group_by(df, dive), m = mean(speed))   625   630   637.1    633   644   701   100  b    
 summarize(group_by(dt, dive), m = mean(speed))   129   130   137.3    131   142   213   100 a     

autoplot(m3)

enter image description here

So data.table continues scaling well, and dplyr operating on a data.table also works well, with dplyr on data.frame close to an order of magnitude slower. The split/sapply strategy seems to scale poorly in the number of groups (meaning the split() is likely slow and the sapply is fast). by continues to be relatively efficient--at 5 seconds, it's definitely noticeable to the user but for a dataset this large still not unreasonable. Still, if you're routinely working with datasets of this size, data.table is clearly the way to go - 100% data.table for the best performance or dplyr with dplyr using data.table as a viable alternative.

Setting up and using environment variables in IntelliJ Idea

It is possible to reference an intellij 'Path Variable' in an intellij 'Run Configuration'.

In 'Path Variables' create a variable for example ANALYTICS_VERSION.

In a 'Run Configuration' under 'Environment Variables' add for example the following:

ANALYTICS_LOAD_LOCATION=$MAVEN_REPOSITORY$\com\my\company\analytics\$ANALYTICS_VERSION$\bin

To answer the original question you would need to add an APP_HOME environment variable to your run configuration which references the path variable:

APP_HOME=$APP_HOME$

YAML Multi-Line Arrays

A YAML sequence is an array. So this is the right way to express it:

key:
  - string1
  - string2      
  - string3
  - string4
  - string5
  - string6

That's identical in meaning to:

key: ['string1', 'string2', 'string3', 'string4', 'string5', 'string6']

It's also legal to split a single-line array over several lines:

key: ['string1', 'string2', 'string3', 
  'string4', 'string5', 
  'string6']

and even have multi-line strings in single-line arrays:

key: ['string1', 'long
  string', 'string3', 'string4', 'string5', 'string6']

CASE (Contains) rather than equal statement

Pseudo code, something like:

CASE
  When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'

This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.

Set value to an entire column of a pandas dataframe

This provides you with the possibility of adding conditions on the rows and then change all the cells of a specific column corresponding to those rows:

df.loc[(df['issueid'] == '001'), 'industry'] = str('yyy')

installing apache: no VCRUNTIME140.dll

Also, please make sure you installed the correct version of apache on your computer. For example, not install a x86 on a 64bit system. Vice versa.

How using try catch for exception handling is best practice

You should consider these Design Guidelines for Exceptions

  • Exception Throwing
  • Using Standard Exception Types
  • Exceptions and Performance

https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/exceptions

How can I select an element with multiple classes in jQuery?

If you want to match only elements with both classes (an intersection, like a logical AND), just write the selectors together without spaces in between:

$('.a.b')

The order is not relevant, so you can also swap the classes:

$('.b.a')

So to match a div element that has an ID of a with classes b and c, you would write:

$('div#a.b.c')

(In practice, you most likely don't need to get that specific, and an ID or class selector by itself is usually enough: $('#a').)

Convert a RGB Color Value to a Hexadecimal String

A one liner but without String.format for all RGB colors:

Color your_color = new Color(128,128,128);

String hex = "#"+Integer.toHexString(your_color.getRGB()).substring(2);

You can add a .toUpperCase()if you want to switch to capital letters. Note, that this is valid (as asked in the question) for all RGB colors.

When you have ARGB colors you can use:

Color your_color = new Color(128,128,128,128);

String buf = Integer.toHexString(your_color.getRGB());
String hex = "#"+buf.substring(buf.length()-6);

A one liner is theoretically also possible but would require to call toHexString twice. I benchmarked the ARGB solution and compared it with String.format():

enter image description here