Programs & Examples On #Nintendo ds

The DS is a portable gaming console from Nintendo.

How to change UIButton image in Swift

Swift 5 and ensures the image scales to the size of the button but stays within the buttons bounds.

yourButton.clipsToBounds = true
yourButton.contentMode = .scaleAspectFill

// Use setBackgroundImage or setImage
yourButton.setBackgroundImage(UIImage(named: "yourImage"), for: .normal)

how to get the value of css style using jquery

Yes, you're right. With the css() method you can retrieve the desired css value stored in the DOM. You can read more about this at: http://api.jquery.com/css/

But if you want to get its position you can check offset() and position() methods to get it's position.

How to use Visual Studio Code as Default Editor for Git

git config --global core.editor "code --wait"

OR

git config --global core.editor "code -w"

Check

git config --global e

Your configuration will open in Visual Studio Code

What is the most efficient string concatenation method in python?

You may be interested in this: An optimization anecdote by Guido. Although it is worth remembering also that this is an old article and it predates the existence of things like ''.join (although I guess string.joinfields is more-or-less the same)

On the strength of that, the array module may be fastest if you can shoehorn your problem into it. But ''.join is probably fast enough and has the benefit of being idiomatic and thus easier for other python programmers to understand.

Finally, the golden rule of optimization: don't optimize unless you know you need to, and measure rather than guessing.

You can measure different methods using the timeit module. That can tell you which is fastest, instead of random strangers on the internet making guesses.

Execute command without keeping it in history

You can also use the following command:

echo toto; history -d $(history | sed -n '$s/\s*\([0-9]*\)\s*.*$/\1/p')

I think it's a very portable command.

Python: import module from another directory at the same level in project hierarchy

If I move CreateUser.py to the main user_management directory, I can easily use: import Modules.LDAPManager to import LDAPManager.py --- this works.

Please, don't. In this way the LDAPManager module used by CreateUser will not be the same as the one imported via other imports. This can create problems when you have some global state in the module or during pickling/unpickling. Avoid imports that work only because the module happens to be in the same directory.

When you have a package structure you should either:

  • Use relative imports, i.e if the CreateUser.py is in Scripts/:

     from ..Modules import LDAPManager
    

    Note that this was (note the past tense) discouraged by PEP 8 only because old versions of python didn't support them very well, but this problem was solved years ago. The current version of PEP 8 does suggest them as an acceptable alternative to absolute imports. I actually like them inside packages.

  • Use absolute imports using the whole package name(CreateUser.py in Scripts/):

     from user_management.Modules import LDAPManager
    

In order for the second one to work the package user_management should be installed inside the PYTHONPATH. During development you can configure the IDE so that this happens, without having to manually add calls to sys.path.append anywhere.

Also I find it odd that Scripts/ is a subpackage. Because in a real installation the user_management module would be installed under the site-packages found in the lib/ directory (whichever directory is used to install libraries in your OS), while the scripts should be installed under a bin/ directory (whichever contains executables for your OS).

In fact I believe Script/ shouldn't even be under user_management. It should be at the same level of user_management. In this way you do not have to use -m, but you simply have to make sure the package can be found (this again is a matter of configuring the IDE, installing the package correctly or using PYTHONPATH=. python Scripts/CreateUser.py to launch the scripts with the correct path).


In summary, the hierarchy I would use is:

user_management  (package)
        |
        |------- __init__.py
        |
        |------- Modules/
        |           |
        |           |----- __init__.py
        |           |----- LDAPManager.py
        |           |----- PasswordManager.py
        |

 Scripts/  (*not* a package)
        |  
        |----- CreateUser.py
        |----- FindUser.py

Then the code of CreateUser.py and FindUser.py should use absolute imports to import the modules:

from user_management.Modules import LDAPManager

During installation you make sure that user_management ends up somewhere in the PYTHONPATH, and the scripts inside the directory for executables so that they are able to find the modules. During development you either rely on IDE configuration, or you launch CreateUser.py adding the Scripts/ parent directory to the PYTHONPATH (I mean the directory that contains both user_management and Scripts):

PYTHONPATH=/the/parent/directory python Scripts/CreateUser.py

Or you can modify the PYTHONPATH globally so that you don't have to specify this each time. On unix OSes (linux, Mac OS X etc.) you can modify one of the shell scripts to define the PYTHONPATH external variable, on Windows you have to change the environmental variables settings.


Addendum I believe, if you are using python2, it's better to make sure to avoid implicit relative imports by putting:

from __future__ import absolute_import

at the top of your modules. In this way import X always means to import the toplevel module X and will never try to import the X.py file that's in the same directory (if that directory isn't in the PYTHONPATH). In this way the only way to do a relative import is to use the explicit syntax (the from . import X), which is better (explicit is better than implicit).

This will make sure you never happen to use the "bogus" implicit relative imports, since these would raise an ImportError clearly signalling that something is wrong. Otherwise you could use a module that's not what you think it is.

How to save password when using Subversion from the console

Try clearing your .subversion folder in your home directory and try to commit again. It should prompt you for your password and then ask you if you would like to save the password.

How to access the ith column of a NumPy multidimensional array?

>>> test[:,0]
array([1, 3, 5])

Similarly,

>>> test[1,:]
array([3, 4])

lets you access rows. This is covered in Section 1.4 (Indexing) of the NumPy reference. This is quick, at least in my experience. It's certainly much quicker than accessing each element in a loop.

Responsive Images with CSS

.erb-image-wrapper img{
    max-width:100% !important;
    height:auto;
    display:block;
}

Worked for me.
Thanks for MrMisterMan for his assistance.

the getSource() and getActionCommand()

The getActionCommand() method returns an String associated with that Component set through the setActionCommand() , whereas the getSource() method returns an Object of the Object class specifying the source of the event.

Static extension methods

No, but you could have something like:

bool b;
b = b.YourExtensionMethod();

Where do I find the definition of size_t?

size_t is the unsigned integer type of the result of the sizeof operator (ISO C99 Section 7.17.)

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. The value of the result is implementation-de?ned, and its type (an unsigned integer type) is size_t (ISO C99 Section 6.5.3.4.)

Retrieving a property of a JSON object by index?

I know this is an old question but I found a way to get the fields by index. You can do it by using the Object.keys method.

When you call the Object.keys method it returns the keys in the order they were assigned (See the example below). I tested the method below in the following browsers:

  • Google Chrome version 43.0
  • Firefox version 33.1
  • Internet Explorer version 11

I also wrote a small extension to the object class so you can call the nth key of the object using getByIndex.

_x000D_
_x000D_
// Function to get the nth key from the object_x000D_
Object.prototype.getByIndex = function(index) {_x000D_
  return this[Object.keys(this)[index]];_x000D_
};_x000D_
_x000D_
var obj1 = {_x000D_
  "set1": [1, 2, 3],_x000D_
  "set2": [4, 5, 6, 7, 8],_x000D_
  "set3": [9, 10, 11, 12]_x000D_
};_x000D_
_x000D_
var obj2 = {_x000D_
  "set2": [4, 5, 6, 7, 8],_x000D_
  "set1": [1, 2, 3],_x000D_
  "set3": [9, 10, 11, 12]_x000D_
};_x000D_
_x000D_
log('-- Obj1 --');_x000D_
log(obj1);_x000D_
log(Object.keys(obj1));_x000D_
log(obj1.getByIndex(0));_x000D_
_x000D_
_x000D_
log('-- Obj2 --');_x000D_
log(obj2);_x000D_
log(Object.keys(obj2));_x000D_
log(obj2.getByIndex(0));_x000D_
_x000D_
_x000D_
// Log function to make the snippet possible_x000D_
function log(x) {_x000D_
  var d = document.createElement("div");_x000D_
  if (typeof x === "object") {_x000D_
    x = JSON.stringify(x, null, 4);_x000D_
  }_x000D_
  d.textContent= x;_x000D_
  document.body.appendChild(d);_x000D_
}
_x000D_
_x000D_
_x000D_

RVM is not a function, selecting rubies with 'rvm use ...' will not work

For me in Ubuntu(18.08), I have added below line in .bashrc and it works.

 source /home/username/.rvm/scripts/rvm

Please add this line.

Is it possible in Java to check if objects fields are null and then add default value to all those attributes?

Non-reflective solution for Java 8, without using a series of if's, would be to stream all fields and check for nullness:

return Stream.of(id, name).allMatch(Objects::isNull);

This remains quite easy to maintain while avoiding the reflection hammer. This will return true for null attributes.

Work with a time span in Javascript

Here a .NET C# similar implementation of a timespan class that supports days, hours, minutes and seconds. This implementation also supports negative timespans.

const MILLIS_PER_SECOND = 1000;
const MILLIS_PER_MINUTE = MILLIS_PER_SECOND * 60;   //     60,000
const MILLIS_PER_HOUR = MILLIS_PER_MINUTE * 60;     //  3,600,000
const MILLIS_PER_DAY = MILLIS_PER_HOUR * 24;        // 86,400,000

export class TimeSpan {
    private _millis: number;

    private static interval(value: number, scale: number): TimeSpan {
        if (Number.isNaN(value)) {
            throw new Error("value can't be NaN");
        }

        const tmp = value * scale;
        const millis = TimeSpan.round(tmp + (value >= 0 ? 0.5 : -0.5));
        if ((millis > TimeSpan.maxValue.totalMilliseconds) || (millis < TimeSpan.minValue.totalMilliseconds)) {
            throw new TimeSpanOverflowError("TimeSpanTooLong");
        }

        return new TimeSpan(millis);
    }

    private static round(n: number): number {
        if (n < 0) {
            return Math.ceil(n);
        } else if (n > 0) {
            return Math.floor(n);
        }

        return 0;
    }

    private static timeToMilliseconds(hour: number, minute: number, second: number): number {
        const totalSeconds = (hour * 3600) + (minute * 60) + second;
        if (totalSeconds > TimeSpan.maxValue.totalSeconds || totalSeconds < TimeSpan.minValue.totalSeconds) {
            throw new TimeSpanOverflowError("TimeSpanTooLong");
        }

        return totalSeconds * MILLIS_PER_SECOND;
    }

    public static get zero(): TimeSpan {
        return new TimeSpan(0);
    }

    public static get maxValue(): TimeSpan {
        return new TimeSpan(Number.MAX_SAFE_INTEGER);
    }

    public static get minValue(): TimeSpan {
        return new TimeSpan(Number.MIN_SAFE_INTEGER);
    }

    public static fromDays(value: number): TimeSpan {
        return TimeSpan.interval(value, MILLIS_PER_DAY);
    }

    public static fromHours(value: number): TimeSpan {
        return TimeSpan.interval(value, MILLIS_PER_HOUR);
    }

    public static fromMilliseconds(value: number): TimeSpan {
        return TimeSpan.interval(value, 1);
    }

    public static fromMinutes(value: number): TimeSpan {
        return TimeSpan.interval(value, MILLIS_PER_MINUTE);
    }

    public static fromSeconds(value: number): TimeSpan {
        return TimeSpan.interval(value, MILLIS_PER_SECOND);
    }

    public static fromTime(hours: number, minutes: number, seconds: number): TimeSpan;
    public static fromTime(days: number, hours: number, minutes: number, seconds: number, milliseconds: number): TimeSpan;
    public static fromTime(daysOrHours: number, hoursOrMinutes: number, minutesOrSeconds: number, seconds?: number, milliseconds?: number): TimeSpan {
        if (milliseconds != undefined) {
            return this.fromTimeStartingFromDays(daysOrHours, hoursOrMinutes, minutesOrSeconds, seconds, milliseconds);
        } else {
            return this.fromTimeStartingFromHours(daysOrHours, hoursOrMinutes, minutesOrSeconds);
        }
    }

    private static fromTimeStartingFromHours(hours: number, minutes: number, seconds: number): TimeSpan {
        const millis = TimeSpan.timeToMilliseconds(hours, minutes, seconds);
        return new TimeSpan(millis);
    }

    private static fromTimeStartingFromDays(days: number, hours: number, minutes: number, seconds: number, milliseconds: number): TimeSpan {
        const totalMilliSeconds = (days * MILLIS_PER_DAY) +
            (hours * MILLIS_PER_HOUR) +
            (minutes * MILLIS_PER_MINUTE) +
            (seconds * MILLIS_PER_SECOND) +
            milliseconds;

        if (totalMilliSeconds > TimeSpan.maxValue.totalMilliseconds || totalMilliSeconds < TimeSpan.minValue.totalMilliseconds) {
            throw new TimeSpanOverflowError("TimeSpanTooLong");
        }
        return new TimeSpan(totalMilliSeconds);
    }

    constructor(millis: number) {
        this._millis = millis;
    }

    public get days(): number {
        return TimeSpan.round(this._millis / MILLIS_PER_DAY);
    }

    public get hours(): number {
        return TimeSpan.round((this._millis / MILLIS_PER_HOUR) % 24);
    }

    public get minutes(): number {
        return TimeSpan.round((this._millis / MILLIS_PER_MINUTE) % 60);
    }

    public get seconds(): number {
        return TimeSpan.round((this._millis / MILLIS_PER_SECOND) % 60);
    }

    public get milliseconds(): number {
        return TimeSpan.round(this._millis % 1000);
    }

    public get totalDays(): number {
        return this._millis / MILLIS_PER_DAY;
    }

    public get totalHours(): number {
        return this._millis / MILLIS_PER_HOUR;
    }

    public get totalMinutes(): number {
        return this._millis / MILLIS_PER_MINUTE;
    }

    public get totalSeconds(): number {
        return this._millis / MILLIS_PER_SECOND;
    }

    public get totalMilliseconds(): number {
        return this._millis;
    }

    public add(ts: TimeSpan): TimeSpan {
        const result = this._millis + ts.totalMilliseconds;
        return new TimeSpan(result);
    }

    public subtract(ts: TimeSpan): TimeSpan {
        const result = this._millis - ts.totalMilliseconds;
        return new TimeSpan(result);
    }
}

How to use

Create a new TimeSpan object

From zero

    const ts = TimeSpan.zero;

From milliseconds

    const milliseconds = 10000; // 1 second

    // by using the constructor
    const ts1 = new TimeSpan(milliseconds);

    // or as an alternative you can use the static factory method
    const ts2 = TimeSpan.fromMilliseconds(milliseconds);

From seconds

    const seconds = 86400; // 1 day
    const ts = TimeSpan.fromSeconds(seconds);

From minutes

    const minutes = 1440; // 1 day
    const ts = TimeSpan.fromMinutes(minutes);

From hours

    const hours = 24; // 1 day
    const ts = TimeSpan.fromHours(hours);

From days

    const days = 1; // 1 day
    const ts = TimeSpan.fromDays(days);

From time with given hours, minutes and seconds

    const hours = 1;
    const minutes = 1;
    const seconds = 1;
    const ts = TimeSpan.fromTime(hours, minutes, seconds);

From time2 with given days, hours, minutes, seconds and milliseconds

    const days = 1;
    const hours = 1;
    const minutes = 1;
    const seconds = 1;
    const milliseconds = 1;
    const ts = TimeSpan.fromTime(days, hours, minutes, seconds, milliseconds);

From maximal safe integer

    const ts = TimeSpan.maxValue;

From minimal safe integer

    const ts = TimeSpan.minValue;

From minimal safe integer

    const ts = TimeSpan.minValue;

Add

    const ts1 = TimeSpan.fromDays(1);
    const ts2 = TimeSpan.fromHours(1);
    const ts = ts1.add(ts2);

    console.log(ts.days);               // 1
    console.log(ts.hours);              // 1
    console.log(ts.minutes);            // 0
    console.log(ts.seconds);            // 0
    console.log(ts.milliseconds);           // 0

Subtract

    const ts1 = TimeSpan.fromDays(1);
    const ts2 = TimeSpan.fromHours(1);
    const ts = ts1.subtract(ts2);

    console.log(ts.days);               // 0
    console.log(ts.hours);              // 23
    console.log(ts.minutes);            // 0
    console.log(ts.seconds);            // 0
    console.log(ts.milliseconds);           // 0

Getting the intervals

    const days = 1;
    const hours = 1;
    const minutes = 1;
    const seconds = 1;
    const milliseconds = 1;
    const ts = TimeSpan.fromTime2(days, hours, minutes, seconds, milliseconds);

    console.log(ts.days);               // 1
    console.log(ts.hours);              // 1
    console.log(ts.minutes);            // 1
    console.log(ts.seconds);            // 1
    console.log(ts.milliseconds);           // 1

    console.log(ts.totalDays)           // 1.0423726967592593;
    console.log(ts.totalHours)          // 25.016944722222224;
    console.log(ts.totalMinutes)            // 1501.0166833333333;
    console.log(ts.totalSeconds)            // 90061.001;
    console.log(ts.totalMilliseconds);      // 90061001;

See also here: https://github.com/erdas/timespan

How do I find the difference between two values without knowing which is larger?

If you don't need a signed integer, this is an alternative that uses a slightly different approach, is easy to read and doesn't require an import:

def distance(a, b):
  if a > 0 and b > 0:
    return max(a, b) - min(a, b)
  elif a < 0 and b < 0:
    return abs(a - b)
  elif a == b:
    return 0
  return abs(a - 0) + abs(b - 0)

Required attribute on multiple checkboxes with the same name?

To provide another approach similar to the answer by @IvanCollantes. It works by additionally filtering the required checkboxes by name. I also simplified the code a bit and checks for a default checked checkbox.

_x000D_
_x000D_
jQuery(function($) {_x000D_
  var requiredCheckboxes = $(':checkbox[required]');_x000D_
  requiredCheckboxes.on('change', function(e) {_x000D_
    var checkboxGroup = requiredCheckboxes.filter('[name="' + $(this).attr('name') + '"]');_x000D_
    var isChecked = checkboxGroup.is(':checked');_x000D_
    checkboxGroup.prop('required', !isChecked);_x000D_
  });_x000D_
  requiredCheckboxes.trigger('change');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<form target="_blank">_x000D_
  <p>_x000D_
    At least one checkbox from each group is required..._x000D_
  </p>_x000D_
  <fieldset>_x000D_
    <legend>Checkboxes Group test</legend>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test[]" value="1" checked="checked" required="required">test-1_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test[]" value="2" required="required">test-2_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test[]" value="3" required="required">test-3_x000D_
    </label>_x000D_
  </fieldset>_x000D_
  <br>_x000D_
  <fieldset>_x000D_
    <legend>Checkboxes Group test2</legend>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test2[]" value="1" required="required">test2-1_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test2[]" value="2" required="required">test2-2_x000D_
    </label>_x000D_
    <label>_x000D_
      <input type="checkbox" name="test2[]" value="3" required="required">test2-3_x000D_
    </label>_x000D_
  </fieldset>_x000D_
  <hr>_x000D_
  <button type="submit" value="submit">Submit</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

How to allow only numbers in textbox in mvc4 razor

@Html.TextBoxFor(x => x.MobileNo, new { @class = "digit" , @maxlength = "10"})

@section Scripts 
{
    @Scripts.Render("~/bundles/jqueryui")
    @Styles.Render("~/Content/cssjqryUi")

    <script type="text/javascript">
         $(".digit").keypress(function (e) {
            if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) 
            {
                $("#errormsg").html("Digits Only").show().fadeOut("slow");
                return false;
            }
         });
    </script>
}

Excel VBA - How to Redim a 2D array?

Here is how I do this.

Dim TAV() As Variant
Dim ArrayToPreserve() as Variant

TAV = ArrayToPreserve
ReDim ArrayToPreserve(nDim1, nDim2)
For i = 0 To UBound(TAV, 1)
    For j = 0 To UBound(TAV, 2)
        ArrayToPreserve(i, j) = TAV(i, j)
    Next j
Next i

android: how to change layout on button click?

I think what you're trying to do should be done with multiple Activities. If you're learning Android, understanding Activities is something you're going to have to tackle. Trying to write a whole app with just one Activity will end up being a lot more difficult. Read this article to get yourself started, then you should end up with something more like this:

View.OnClickListener handler = new View.OnClickListener(){
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.DownloadView: 
                // doStuff
                startActivity(new Intent(ThisActivity.this, DownloadActivity.class));
                break;
            case R.id.AppView: 
                // doStuff
                startActivity(new Intent(ThisActivity.this, AppActivity.class));
                break;
        }
    }
};

findViewById(R.id.DownloadView).setOnClickListener(handler);
findViewById(R.id.AppView).setOnClickListener(handler);

Which icon sizes should my Windows application's icon include?

From Microsoft MSDN recommendations:

Application icons and Control Panel items: The full set includes 16x16, 32x32, 48x48, and 256x256 (code scales between 32 and 256). The .ico file format is required. For Classic Mode, the full set is 16x16, 24x24, 32x32, 48x48 and 64x64.

So we have already standard recommended sizes of:

  • 16 x 16,
  • 24 x 24,
  • 32 x 32,
  • 48 x 48,
  • 64 x 64,
  • 256 x 256.

If we would like to support high DPI settings, the complete list will include the following sizes as well:

  • 20 x 20,
  • 30 x 30,
  • 36 x 36,
  • 40 x 40,
  • 60 x 60,
  • 72 x 72,
  • 80 x 80,
  • 96 x 96,
  • 128 x 128,
  • 320 x 320,
  • 384 x 384,
  • 512 x 512.

Chrome / Safari not filling 100% height of flex parent

Specifying a flex attribute to the container worked for me:

.container {
    flex: 0 0 auto;
}

This ensures the height is set and doesn't grow either.

Get all directories within directory nodejs

Fully async version with ES6, only native packages, fs.promises and async/await, does file operations in parallel:

const fs = require('fs');
const path = require('path');

async function listDirectories(rootPath) {
    const fileNames = await fs.promises.readdir(rootPath);
    const filePaths = fileNames.map(fileName => path.join(rootPath, fileName));
    const filePathsAndIsDirectoryFlagsPromises = filePaths.map(async filePath => ({path: filePath, isDirectory: (await fs.promises.stat(filePath)).isDirectory()}))
    const filePathsAndIsDirectoryFlags = await Promise.all(filePathsAndIsDirectoryFlagsPromises);
    return filePathsAndIsDirectoryFlags.filter(filePathAndIsDirectoryFlag => filePathAndIsDirectoryFlag.isDirectory)
        .map(filePathAndIsDirectoryFlag => filePathAndIsDirectoryFlag.path);
}

Tested, it works nicely.

Copying sets Java

Java 8+:

Set<String> copy = new HashSet<>(mySet); 

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

I had the same error on my Angular6 project. none of those solutions seemed to work out for me. turned out that the problem was due to an element which was specified as dropdown but it didn't have dropdown options in it. take a look at code below:

<span class="nav-link" id="navbarDropdownMenuLink" data-toggle="dropdown"
                          aria-haspopup="true" aria-expanded="false">
                        <i class="material-icons "
                           style="font-size: 2rem">notifications</i>
                        <span class="notification"></span>
                        <p>
                            <span class="d-lg-none d-md-block">Some Actions</span>
                        </p>
                    </span>
                    <div class="dropdown-menu dropdown-menu-left"
                         *ngIf="global.localStorageItem('isInSadHich')"
                         aria-labelledby="navbarDropdownMenuLink">
                                        <a class="dropdown-item" href="#">You have 5 new tasks</a>
                                        <a class="dropdown-item" href="#">You're now friend with Andrew</a>
                                        <a class="dropdown-item" href="#">Another Notification</a>
                                        <a class="dropdown-item" href="#">Another One</a>
                    </div>

removing the code data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" solved the problem.

I myself think that by each click on the first span element, the scope expected to set style for dropdown children which did not existed in the parent span, so it threw error.

Possible reasons for timeout when trying to access EC2 instance

The following are possible issues:

  • The most likely one is that the Security Group is not configured properly to provide SSH access on port 22 to your i.p. Change in security setting does not require a restart of server for it to be effective but need to wait a few minutes for it to be applicable.

  • The local firewall configuration does not allow SSH access to the server. ( you can try a different internet connection, your phone/dongle to try it)

  • The server is not started properly ( then the access checks will fail even on the amazon console), in which case you would need to stop and start the server.

Remove blank lines with grep

Try the following:

grep -v -e '^$' foo.txt

The -e option allows regex patterns for matching.

The single quotes around ^$ makes it work for Cshell. Other shells will be happy with either single or double quotes.

UPDATE: This works for me for a file with blank lines or "all white space" (such as windows lines with "\r\n" style line endings), whereas the above only removes files with blank lines and unix style line endings:

grep -v -e '^[[:space:]]*$' foo.txt

Which SchemaType in Mongoose is Best for Timestamp?

The current version of Mongoose (v4.x) has time stamping as a built-in option to a schema:

var mySchema = new mongoose.Schema( {name: String}, {timestamps: true} );

This option adds createdAt and updatedAt properties that are timestamped with a Date, and which does all the work for you. Any time you update the document, it updates the updatedAt property. Schema Timestamps Docs.

Genymotion Android emulator - adb access?

Simply do this, with genymotion device running you can open Virtual Box , and see that there is a VM for you device , then go to network Settings of the VM, NAT and do port forwarding of local 5555 to remote 5555 screen attachedVirtual Box Nat Network Port forwarding

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

How do I add 1 day to an NSDate?

Use following code:

NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];

As

addTimeInterval

is now deprecated.

How do I stop/start a scheduled task on a remote computer programmatically?

schtasks /change /disable /tn "Name Of Task" /s REMOTEMACHINENAME /u mydomain\administrator /p adminpassword 

jQuery: Clearing Form Inputs

Took some searching and reading to find a method that suited my situation, on form submit, run ajax to a remote php script, on success/failure inform user, on complete clear the form.

I had some default values, all other methods involved .val('') thereby not resetting but clearing the form.

I got this too work by adding a reset button to the form, which had an id of myform:

$("#myform > input[type=reset]").trigger('click');

This for me had the correct outcome on resetting the form, oh and dont forget the

event.preventDefault();

to stop the form submitting in browser, like I did :).

Regards

Jacko

How to SUM and SUBTRACT using SQL?

I have tried this kind of technique. Multiply the subtract from data by (-1) and then sum() the both amount then you will get subtracted amount.

-- Loan Outstanding
    select  'Loan Outstanding' as Particular, sum(Unit), sum(UptoLastYear), sum(ThisYear), sum(UptoThisYear)
    from
    (
        select 
            sum(laod.dr) as Unit,
            sum(if(lao.created_at <= '2014-01-01',laod.dr,0)) as UptoLastYear,
            sum(if(lao.created_at between '2014-01-01' and '2015-07-14',laod.dr,0)) as ThisYear,
            sum(if(lao.created_at <= '2015-07-14',laod.dr,0)) as UptoThisYear
        from loan_account_opening as lao
        inner join loan_account_opening_detail as laod on lao.id=laod.loan_account_opening_id
        where lao.organization = 3
        union
        select
            sum(lr.installment)*-1 as Unit,
            sum(if(lr.created_at <= '2014-01-01',lr.installment,0))*-1 as UptoLastYear,
            sum(if(lr.created_at between '2014-01-01' and '2015-07-14',lr.installment,0))*-1 as ThisYear,
            sum(if(lr.created_at <= '2015-07-14',lr.installment,0))*-1 as UptoThisYear
        from loan_recovery as lr
        inner join loan_account_opening as lo on lr.loan_account_opening_id=lo.id
        where lo.organization = 3
    ) as t3

AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

I had the same issue. The problem was because 'ng-controller' was defined twice (in routing and also in the HTML).

Check synchronously if file/directory exists in Node.js

fs.exists() is deprecated dont use it https://nodejs.org/api/fs.html#fs_fs_exists_path_callback

You could implement the core nodejs way used at this: https://github.com/nodejs/node-v0.x-archive/blob/master/lib/module.js#L86

function statPath(path) {
  try {
    return fs.statSync(path);
  } catch (ex) {}
  return false;
}

this will return the stats object then once you've got the stats object you could try

var exist = statPath('/path/to/your/file.js');
if(exist && exist.isFile()) {
  // do something
}

Javascript: How to pass a function with string parameters as a parameter to another function

Try this:

onclick="myfunction(
    '/myController/myAction',
    function(){myfuncionOnOK('/myController2/myAction2','myParameter2');},
    function(){myfuncionOnCancel('/myController3/myAction3','myParameter3');}
);"

Then you just need to call these two functions passed to myfunction:

function myfunction(url, f1, f2) {
    // …
    f1();
    f2();
}

console.writeline and System.out.println

First I am afraid your question contains a little mistake. There is not method writeline in class Console. Instead class Console provides method writer() that returns PrintWriter. This print writer has println().

Now what is the difference between

System.console().writer().println("hello from console");

and

System.out.println("hello system out");

If you run your application from command line I think there is no difference. But if console is unavailable System.console() returns null while System.out still exists. This may happen if you invoke your application and perform redirect of STDOUT to file.

Here is an example I have just implemented.

import java.io.Console;


public class TestConsole {
    public static void main(String[] args) {
        Console console = System.console();
        System.out.println("console=" + console);
        console.writer().println("hello from console");
    }
}

When I ran the application from command prompt I got the following:

$ java TestConsole
console=java.io.Console@93dcd
hello from console

but when I redirected the STDOUT to file...

$ java TestConsole >/tmp/test
Exception in thread "main" java.lang.NullPointerException
        at TestConsole.main(TestConsole.java:8)

Line 8 is console.writer().println().

Here is the content of /tmp/test

console=null

I hope my explanations help.

How do I tidy up an HTML file's indentation in VI?

With filetype indent on inside my .vimrc, Vim indents HTML files quite nicely.

Simple example with a shiftwidth of 2:

<html>
  <body>
    <p>
    text
    </p>
  </body>
</html>

Using setImageDrawable dynamically to set image in an ImageView

All the answers posted do not apply today. For example, getDrawable() is deprecated. Here is an updated answer, cheers!

ContextCompat.getDrawable(mContext, drawable)

From documented method

public static final android.graphics.drawable.Drawable getDrawable(@NotNull android.content.Context context,
@android.support.annotation.DrawableRes int id

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

Instead of using Ajax Post method, you can use dynamic form along with element. It will works even page is loaded in SSL and submitted source is non SSL.

You need to set value value of element of form.

Actually new dynamic form will open as non SSL mode in separate tab of Browser when target attribute has set '_blank'

var f = document.createElement('form');
f.action='http://XX.XXX.XX.XX/vicidial/non_agent_api.php';
f.method='POST';
//f.target='_blank';
//f.enctype="multipart/form-data"

var k=document.createElement('input');
k.type='hidden';k.name='CustomerID';
k.value='7299';
f.appendChild(k);



//var z=document.getElementById("FileNameId")
//z.setAttribute("name", "IDProof");
//z.setAttribute("id", "IDProof");
//f.appendChild(z);

document.body.appendChild(f);
f.submit()

python encoding utf-8

You don't need to encode data that is already encoded. When you try to do that, Python will first try to decode it to unicode before it can encode it back to UTF-8. That is what is failing here:

>>> data = u'\u00c3'            # Unicode data
>>> data = data.encode('utf8')  # encoded to UTF-8
>>> data
'\xc3\x83'
>>> data.encode('utf8')         # Try to *re*-encode it
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Just write your data directly to the file, there is no need to encode already-encoded data.

If you instead build up unicode values instead, you would indeed have to encode those to be writable to a file. You'd want to use codecs.open() instead, which returns a file object that will encode unicode values to UTF-8 for you.

You also really don't want to write out the UTF-8 BOM, unless you have to support Microsoft tools that cannot read UTF-8 otherwise (such as MS Notepad).

For your MySQL insert problem, you need to do two things:

  • Add charset='utf8' to your MySQLdb.connect() call.

  • Use unicode objects, not str objects when querying or inserting, but use sql parameters so the MySQL connector can do the right thing for you:

    artiste = artiste.decode('utf8')  # it is already UTF8, decode to unicode
    
    c.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    
    # ...
    
    c.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
    

It may actually work better if you used codecs.open() to decode the contents automatically instead:

import codecs

sql = mdb.connect('localhost','admin','ugo&(-@F','music_vibration', charset='utf8')

with codecs.open('config/index/'+index, 'r', 'utf8') as findex:
    for line in findex:
        if u'#artiste' not in line:
            continue

        artiste=line.split(u'[:::]')[1].strip()

    cursor = sql.cursor()
    cursor.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    if not cursor.fetchone()[0]:
        cursor = sql.cursor()
        cursor.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
        artists_inserted += 1

You may want to brush up on Unicode and UTF-8 and encodings. I can recommend the following articles:

How can I make a TextArea 100% width without overflowing when padding is present in CSS?

The answer to many CSS formatting problems seems to be "add another <div>!"

So, in that spirit, have you tried adding a wrapper div to which the border/padding are applied and then putting the 100% width textarea inside of that? Something like (untested):

_x000D_
_x000D_
textarea_x000D_
{_x000D_
  width:100%;_x000D_
}_x000D_
.textwrapper_x000D_
{_x000D_
  border:1px solid #999999;_x000D_
  margin:5px 0;_x000D_
  padding:3px;_x000D_
}
_x000D_
<div style="display: block;" id="rulesformitem" class="formitem">_x000D_
  <label for="rules" id="ruleslabel">Rules:</label>_x000D_
  <div class="textwrapper"><textarea cols="2" rows="10" id="rules"/></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to change the default charset of a MySQL table?

The ALTER TABLE MySQL command should do the trick. The following command will change the default character set of your table and the character set of all its columns to UTF8.

ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

This command will convert all text-like columns in the table to the new character set. Character sets use different amounts of data per character, so MySQL will convert the type of some columns to ensure there's enough room to fit the same number of characters as the old column type.

I recommend you read the ALTER TABLE MySQL documentation before modifying any live data.

jQuery - Check if DOM element already exists

In this case, you may want to check if element exists in current DOM

if you want to check if element exist in DOM tree (is attached to DOM), you can use:

var data = $('#data_1'); 
if(jQuery.contains(document.documentElement, data[0])){
    // #data_1 element attached to DOM
} else {
    // is not attached to DOM
}

Which Radio button in the group is checked?

You could use LINQ:

var checkedButton = container.Controls.OfType<RadioButton>()
                                      .FirstOrDefault(r => r.Checked);

Note that this requires that all of the radio buttons be directly in the same container (eg, Panel or Form), and that there is only one group in the container. If that is not the case, you could make List<RadioButton>s in your constructor for each group, then write list.FirstOrDefault(r => r.Checked).

How to scroll to an element in jQuery?

Check jQuery.ScrollTo, I think that's the behavior that you want, check the demo.

How to properly make a http web GET request

Simpliest way for my opinion

  var web = new WebClient();
  var url = $"{hostname}/LoadDataSync?systemID={systemId}";
  var responseString = web.DownloadString(url);

OR

 var bytes = web.DownloadData(url);

How to update and order by using ms sql

You can do a subquery where you first get the IDs of the top 10 ordered by priority and then update the ones that are on that sub query:

UPDATE  messages 
SET status=10 
WHERE ID in (SELECT TOP (10) Id 
             FROM Table 
             WHERE status=0 
             ORDER BY priority DESC);

How to implement a property in an interface

  • but i already assigned values such that irp.WrmVersion = "10.4";

J.Random Coder's answer and initialize version field.


private string version = "10.4';

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

convert streamed buffers to utf8-string

Single Buffer

If you have a single Buffer you can use its toString method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8 if you don't provide a parameter, but I've explicitly set the encoding in this example.

var req = http.request(reqOptions, function(res) {
    ...

    res.on('data', function(chunk) {
        var textChunk = chunk.toString('utf8');
        // process utf8 text chunk
    });
});

Streamed Buffers

If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8-character may be contained in the first Buffer (chunk) and the second byte in the second Buffer then you should use a StringDecoder. :

var StringDecoder = require('string_decoder').StringDecoder;

var req = http.request(reqOptions, function(res) {
    ...
    var decoder = new StringDecoder('utf8');

    res.on('data', function(chunk) {
        var textChunk = decoder.write(chunk);
        // process utf8 text chunk
    });
});

This way bytes of incomplete characters are buffered by the StringDecoder until all required bytes were written to the decoder.

"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) }.

Rails: Adding an index after adding column

Add in the generated migration after creating the column the following (example)

add_index :photographers, :email, :unique => true

How to center an image horizontally and align it to the bottom of the container?

.image_block    {
    width: 175px;
    height: 175px;
    position: relative;
}

.image_block a  {
    width: 100%;
    text-align: center;
    position: absolute;
    bottom: 0px;
}

.image_block img    {
/*  nothing specific  */
}

explanation: an element positioned absolutely will be relative to the closest parent which has a non-static positioning. i'm assuming you're happy with how your .image_block displays, so we can leave the relative positioning there.

as such, the <a> element will be positioned relative to the .image_block, which will give us the bottom alignment. then, we text-align: center the <a> element, and give it a 100% width so that it is the size of .image_block.

the <img> within <a> will then center appropriately.

JavaScript OOP in NodeJS: how?

If you are working on your own, and you want the closest thing to OOP as you would find in Java or C# or C++, see the javascript library, CrxOop. CrxOop provides syntax somewhat familiar to Java developers.

Just be careful, Java's OOP is not the same as that found in Javascript. To get the same behavior as in Java, use CrxOop's classes, not CrxOop's structures, and make sure all your methods are virtual. An example of the syntax is,

crx_registerClass("ExampleClass", 
{ 
    "VERBOSE": 1, 

    "public var publicVar": 5, 
    "private var privateVar": 7, 

    "public virtual function publicVirtualFunction": function(x) 
    { 
        this.publicVar1 = x;
        console.log("publicVirtualFunction"); 
    }, 

    "private virtual function privatePureVirtualFunction": 0, 

    "protected virtual final function protectedVirtualFinalFunction": function() 
    { 
        console.log("protectedVirtualFinalFunction"); 
    }
}); 

crx_registerClass("ExampleSubClass", 
{ 
    VERBOSE: 1, 
    EXTENDS: "ExampleClass", 

    "public var publicVar": 2, 

    "private virtual function privatePureVirtualFunction": function(x) 
    { 
        this.PARENT.CONSTRUCT(pA);
        console.log("ExampleSubClass::privatePureVirtualFunction"); 
    } 
}); 

var gExampleSubClass = crx_new("ExampleSubClass", 4);

console.log(gExampleSubClass.publicVar);
console.log(gExampleSubClass.CAST("ExampleClass").publicVar);

The code is pure javascript, no transpiling. The example is taken from a number of examples from the official documentation.

Mockito: InvalidUseOfMatchersException

Do not use Mockito.anyXXXX(). Directly pass the value to the method parameter of same type. Example:

A expected = new A(10);

String firstId = "10w";
String secondId = "20s";
String product = "Test";
String type = "type2";
Mockito.when(service.getTestData(firstId, secondId, product,type)).thenReturn(expected);

public class A{
   int a ;
   public A(int a) {
      this.a = a;
   }
}

How to print a stack trace in Node.js?

To print stacktrace of Error in console in more readable way:

console.log(ex, ex.stack.split("\n"));

Example result:

[Error] [ 'Error',
  '    at repl:1:7',
  '    at REPLServer.self.eval (repl.js:110:21)',
  '    at Interface.<anonymous> (repl.js:239:12)',
  '    at Interface.EventEmitter.emit (events.js:95:17)',
  '    at Interface._onLine (readline.js:202:10)',
  '    at Interface._line (readline.js:531:8)',
  '    at Interface._ttyWrite (readline.js:760:14)',
  '    at ReadStream.onkeypress (readline.js:99:10)',
  '    at ReadStream.EventEmitter.emit (events.js:98:17)',
  '    at emitKey (readline.js:1095:12)' ]

Java "user.dir" property - what exactly does it mean?

Typically this is the directory where your app (java) was started (working dir). "Typically" because it can be changed, eg when you run an app with Runtime.exec(String[] cmdarray, String[] envp, File dir)

XPath:: Get following Sibling

/html/body/table/tbody/tr[9]/td[1]

In Chrome (possible Safari too) you can inspect an element, then right click on the tag you want to get the xpath for, then you can copy the xpath to select that element.

How do you get total amount of RAM the computer has?

Add a reference to Microsoft.VisualBasic and a using Microsoft.VisualBasic.Devices;.

The ComputerInfo class has all the information that you need.

How to locate the php.ini file (xampp)

In the documentation http://www.apachefriends.org/en/xampp-windows.html (Configuration files section, near the bottom of the page): \xampp\php\php.ini

Java Reflection: How to get the name of a variable?

All you need to do is make an array of fields and then set it to the class you want like shown below.

Field fld[] = (class name).class.getDeclaredFields();   
for(Field x : fld)
{System.out.println(x);}

For example if you did

Field fld[] = Integer.class.getDeclaredFields();
          for(Field x : fld)
          {System.out.println(x);}

you would get

public static final int java.lang.Integer.MIN_VALUE
public static final int java.lang.Integer.MAX_VALUE
public static final java.lang.Class java.lang.Integer.TYPE
static final char[] java.lang.Integer.digits
static final char[] java.lang.Integer.DigitTens
static final char[] java.lang.Integer.DigitOnes
static final int[] java.lang.Integer.sizeTable
private static java.lang.String java.lang.Integer.integerCacheHighPropValue
private final int java.lang.Integer.value
public static final int java.lang.Integer.SIZE
private static final long java.lang.Integer.serialVersionUID

onMeasure custom view explanation

onMeasure() is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in a match_parent situation than a wrap_content situation). These constraints are packaged up into the MeasureSpec values that are passed into the method. Here is a rough correlation of the mode values:

  • EXACTLY means the layout_width or layout_height value was set to a specific value. You should probably make your view this size. This can also get triggered when match_parent is used, to set the size exactly to the parent view (this is layout dependent in the framework).
  • AT_MOST typically means the layout_width or layout_height value was set to match_parent or wrap_content where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.
  • UNSPECIFIED typically means the layout_width or layout_height value was set to wrap_content with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.

The contract that exists with onMeasure() is that setMeasuredDimension() MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found in View, which is why it is safe to call super instead if that fits your use case.

Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with wrap_content in both directions, your view may not show up at all because the framework doesn't know how large it is!

Generally, if you are overriding View and not another existing widget, it is probably a good idea to provide an implementation, even if it is as simple as something like this:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int desiredWidth = 100;
    int desiredHeight = 100;

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int width;
    int height;

    //Measure Width
    if (widthMode == MeasureSpec.EXACTLY) {
        //Must be this size
        width = widthSize;
    } else if (widthMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        width = Math.min(desiredWidth, widthSize);
    } else {
        //Be whatever you want
        width = desiredWidth;
    }

    //Measure Height
    if (heightMode == MeasureSpec.EXACTLY) {
        //Must be this size
        height = heightSize;
    } else if (heightMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        height = Math.min(desiredHeight, heightSize);
    } else {
        //Be whatever you want
        height = desiredHeight;
    }

    //MUST CALL THIS
    setMeasuredDimension(width, height);
}

Hope that Helps.

Adding external resources (CSS/JavaScript/images etc) in JSP

Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file

<style type="text/css">
    <%@include file="css/style.css" %>
</style>
<script type="text/javascript">
    <%@include file="js/script.js" %>
</script>

Find specific string in a text file with VBS script

Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job. Here's the code:

Option Explicit

Dim StdIn:  Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript


Main()

Sub Main()

Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
Set objFSO = CreateObject("Scripting.FileSystemObject")
TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
ForReading = 1
ForWriting = 2
Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
count = 7
text=""
foundFirstMatch = false

Do until objInputFile.AtEndOfStream
    tmpStr = objInputFile.ReadLine
    If foundStrMatch(tmpStr)=true Then
        If foundFirstMatch = false Then
            index = getIndex(tmpStr)
            foundFirstMatch = true
            text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
        End If
        If index = getIndex(tmpStr) Then
            text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
        ElseIf index < getIndex(tmpStr) Then
            index = getIndex(tmpStr)
            text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
        End If
    Else
        text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
    End If
Loop
Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
objOutputFile.Write(text)
End Sub


Function textSubstitution(tmpStr,index,foundMatch)
Dim strToAdd
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
If foundMatch = "false" Then
    textSubstitution = tmpStr
ElseIf foundMatch = "true" Then
    textSubstitution = strToAdd & vbCrLf & tmpStr
End If
End Function


Function getIndex(tmpStr)
Dim substrToFind, charAtPos, char1, char2
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
charAtPos = len(substrToFind) + 1
char1 = Mid(tmpStr, charAtPos, 1)
char2 = Mid(tmpStr, charAtPos+1, 1)
If IsNumeric(char2) Then
    getIndex = CInt(char1 & char2)
Else
    getIndex = CInt(char1)
End If
End Function

Function foundStrMatch(tmpStr)
Dim substrToFind
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
If InStr(tmpStr, substrToFind) > 0 Then
    foundStrMatch = true
Else
    foundStrMatch = false
End If
End Function

This is the original txt file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>

And this is the result I'm expecting

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>

Apply a theme to an activity in Android?

Before you call setContentView(), call setTheme(android.R.style...) and just replace the ... with the theme that you want(Theme, Theme_NoTitleBar, etc.).

Or if your theme is a custom theme, then replace the entire thing, so you get setTheme(yourThemesResouceId)

Locking a file in Python

Coordinating access to a single file at the OS level is fraught with all kinds of issues that you probably don't want to solve.

Your best bet is have a separate process that coordinates read/write access to that file.

How to convert a PNG image to a SVG?

I'm assuming that you wish to write software to do this. To do it naively you would just find lines and set the vectors. To do it intelligently, you attempt to fit shapes onto the drawing (model fitting). Additionally, you should attempt to ascertain bitmaped regions (regions you can't model through shames or applying textures. I would not recommend going this route as that it will take quite a bit of time and require a bit of graphics and computer vision knowledge. However, the output will much and scale much better than your original output.

Creating a copy of an object in C#

There's already a question about this, you could perhaps read it

Deep cloning objects

There's no Clone() method as it exists in Java for example, but you could include a copy constructor in your clases, that's another good approach.

class A
{
  private int attr

  public int Attr
  {
     get { return attr; }
     set { attr = value }
  }

  public A()
  {
  }

  public A(A p)
  {
     this.attr = p.Attr;
  }  
}

This would be an example, copying the member 'Attr' when building the new object.

How to get the client IP address in PHP

Here's a bit of code that should pick a valid IP by checking through various sources.

First, it checks if 'REMOTE_ADDR' is a public IP or not (and not one of your trusted reverse proxies), then goes through one of the HTTP headers until it finds a public IP and returns it. (PHP 5.2+)

It should be reliable as long as the reverse proxy is trusted or the server is directly connected with the client.

//Get client's IP or null if nothing looks valid
function ip_get($allow_private = false)
{
  //Place your trusted proxy server IPs here.
  $proxy_ip = ['127.0.0.1'];

  //The header to look for (Make sure to pick the one that your trusted reverse proxy is sending or else you can get spoofed)
  $header = 'HTTP_X_FORWARDED_FOR'; //HTTP_CLIENT_IP, HTTP_X_FORWARDED, HTTP_FORWARDED_FOR, HTTP_FORWARDED

  //If 'REMOTE_ADDR' seems to be a valid client IP, use it.
  if(ip_check($_SERVER['REMOTE_ADDR'], $allow_private, $proxy_ip)) return $_SERVER['REMOTE_ADDR'];

  if(isset($_SERVER[$header]))
  {
    //Split comma separated values [1] in the header and traverse the proxy chain backwards.
    //[1] https://en.wikipedia.org/wiki/X-Forwarded-For#Format
    $chain = array_reverse(preg_split('/\s*,\s*/', $_SERVER[$header]));
    foreach($chain as $ip) if(ip_check($ip, $allow_private, $proxy_ip)) return $ip;
  }

   return null;
}

//Check for valid IP. If 'allow_private' flag is set to truthy, it allows private IP ranges as valid client IP as well. (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)
//Pass your trusted reverse proxy IPs as $proxy_ip to exclude them from being valid.
function ip_check($ip, $allow_private = false, $proxy_ip = [])
{
  if(!is_string($ip) || is_array($proxy_ip) && in_array($ip, $proxy_ip)) return false;
  $filter_flag = FILTER_FLAG_NO_RES_RANGE;

  if(!$allow_private)
  {
    //Disallow loopback IP range which doesn't get filtered via 'FILTER_FLAG_NO_PRIV_RANGE' [1]
    //[1] https://www.php.net/manual/en/filter.filters.validate.php
    if(preg_match('/^127\.$/', $ip)) return false;
    $filter_flag |= FILTER_FLAG_NO_PRIV_RANGE;
  }

  return filter_var($ip, FILTER_VALIDATE_IP, $filter_flag) !== false;
}

How to simulate a click by using x,y coordinates in JavaScript?

it doenst work for me but it prints the correct element to the console

this is the code:

function click(x, y)
{
    var ev = new MouseEvent('click', {
        'view': window,
        'bubbles': true,
        'cancelable': true,
        'screenX': x,
        'screenY': y
    });

    var el = document.elementFromPoint(x, y);
    console.log(el); //print element to console
    el.dispatchEvent(ev);
}
click(400, 400);

retrieve links from web page using python and BeautifulSoup

To find all the links, we will in this example use the urllib2 module together with the re.module *One of the most powerful function in the re module is "re.findall()". While re.search() is used to find the first match for a pattern, re.findall() finds all the matches and returns them as a list of strings, with each string representing one match*

import urllib2

import re
#connect to a URL
website = urllib2.urlopen(url)

#read html code
html = website.read()

#use re.findall to get all the links
links = re.findall('"((http|ftp)s?://.*?)"', html)

print links

How can I join on a stored procedure?

I hope your stored procedure is not doing a cursor loop!

If not, take the query from your stored procedure and integrate that query within the query you are posting here:

SELECT t.TenantName, t.CarPlateNumber, t.CarColor, t.Sex, t.SSNO, t.Phone, t.Memo,
        u.UnitNumber,
        p.PropertyName
        ,dt.TenantBalance
FROM tblTenant t
    LEFT JOIN tblRentalUnit u ON t.UnitID = u.ID
    LEFT JOIN tblProperty   p ON u.PropertyID = p.ID
    LEFT JOIN (SELECT ID, SUM(ISNULL(trans.Amount,0)) AS TenantBalance
                   FROM tblTransaction
                   GROUP BY tenant.ID
              ) dt ON t.ID=dt.ID
ORDER BY p.PropertyName, t.CarPlateNumber

If you are doing something more than a query in your stored procedure, create a temp table and execute the stored procedure into this temp table and then join to that in your query.

create procedure test_proc
as
  select 1 as x, 2 as y
  union select 3,4 
  union select 5,6 
  union select 7,8 
  union select 9,10
  return 0
go 

create table #testing
(
  value1   int
  ,value2  int
)

INSERT INTO #testing
exec test_proc


select
  *
  FROM #testing

How to submit an HTML form without redirection

The desired effect can also be achieved by moving the submit button outside of the form as described here:

Prevent page reload and redirect on form submit ajax/jquery

Like this:

<form id="getPatientsForm">
    Enter URL for patient server
    <br/><br/>
    <input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
    <input name="patientRootUrl" size="100"></input>
    <br/><br/>
</form>

<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>

How to open a link in new tab (chrome) using Selenium WebDriver?

First open empty new Tab by using the keys Ctrl + t and then use .get() to fetch the URL you want. Your code should look something like this -

String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,"t");
driver.findElement(By.tagName("body")).sendKeys(selectLinkOpeninNewTab);

driver.get("www.facebook.com");

If you want to open a link on the current view in a new tab then the code you've written above can be used. Instead of By.linkText() make sure you use the appropriate By selector class to select the web element.

Regex to match string containing two names in any order

Explanation of command that i am going to write:-

. means any character, digit can come in place of .

* means zero or more occurrences of thing written just previous to it.

| means 'or'.

So,

james.*jack

would search james , then any number of character until jack comes.

Since you want either jack.*james or james.*jack

Hence Command:

jack.*james|james.*jack

How to add font-awesome to Angular 2 + CLI project

Now there is few ways to install fontAwesome on Angular CLI:

ng add @fortawesome/angular-fontawesome

OR using yarn

yarn add @fortawesome/fontawesome-svg-core
yarn add @fortawesome/free-solid-svg-icons
yarn add @fortawesome/angular-fontawesome

OR Using NPM

npm install @fortawesome/fontawesome-svg-core
npm install @fortawesome/free-solid-svg-icons
npm install @fortawesome/angular-fontawesome

Reference here: https://github.com/FortAwesome/angular-fontawesome

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

I got this problem because I uninstalled VS 2012, I don't want to reinstall it back, so I downloaded the AspNetMVC4Setup.exe from Microsoft.com and fixed my problem.

https://www.microsoft.com/en-us/download/details.aspx?id=30683

How to add new column to MYSQL table?

Something like:

$db = mysqli_connect("localhost", "user", "password", "database");
$name = $db->mysqli_real_escape_string($name);
$query = 'ALTER TABLE assesment ADD ' . $name . ' TINYINT NOT NULL DEFAULT \'0\'';
if($db->query($query)) {
    echo "It worked";
}

Haven't tested it but should work.

Parse strings to double with comma and point

To treat both , and . as decimal point you must not only replace one with the other, but also make sure the Culture used parsing interprets it as a decimal point.

text = text.Replace(',', '.');
return double.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out value);

How do I filter ForeignKey choices in a Django ModelForm?

So, I've really tried to understand this, but it seems that Django still doesn't make this very straightforward. I'm not all that dumb, but I just can't see any (somewhat) simple solution.

I find it generally pretty ugly to have to override the Admin views for this sort of thing, and every example I find never fully applies to the Admin views.

This is such a common circumstance with the models I make that I find it appalling that there's no obvious solution to this...

I've got these classes:

# models.py
class Company(models.Model):
    # ...
class Contract(models.Model):
    company = models.ForeignKey(Company)
    locations = models.ManyToManyField('Location')
class Location(models.Model):
    company = models.ForeignKey(Company)

This creates a problem when setting up the Admin for Company, because it has inlines for both Contract and Location, and Contract's m2m options for Location are not properly filtered according to the Company that you're currently editing.

In short, I would need some admin option to do something like this:

# admin.py
class LocationInline(admin.TabularInline):
    model = Location
class ContractInline(admin.TabularInline):
    model = Contract
class CompanyAdmin(admin.ModelAdmin):
    inlines = (ContractInline, LocationInline)
    inline_filter = dict(Location__company='self')

Ultimately I wouldn't care if the filtering process was placed on the base CompanyAdmin, or if it was placed on the ContractInline. (Placing it on the inline makes more sense, but it makes it hard to reference the base Contract as 'self'.)

Is there anyone out there who knows of something as straightforward as this badly needed shortcut? Back when I made PHP admins for this sort of thing, this was considered basic functionality! In fact, it was always automatic, and had to be disabled if you really didn't want it!

Change first commit of project with Git?

As stated in 1.7.12 Release Notes, you may use

$ git rebase -i --root

How can you undo the last git add?

If you want to remove all added files from git for commit

git reset

If you want to remove an individual file

git rm <file>

Force browser to clear cache

If you are a Wordpress developer I have some great news for you.

Just search for, install and activate the Wordpress plugin called: reBusted.

No configuration is necessary.

It will automatically force cache refresh if the content has been updated and it solves this issue completely and reliably. Tested and used on hundreds of clients Wordpress sites – works perfectly everywhere.

Cannot recommend it enough.

If you use Wordpress, this is by far your best option and most elegant resolution for this issue.

Enjoy!

Filter object properties by key in ES6

Another approach would be to use Array.prototype.forEach() as

_x000D_
_x000D_
const raw = {_x000D_
  item1: {_x000D_
    key: 'sdfd',_x000D_
    value: 'sdfd'_x000D_
  },_x000D_
  item2: {_x000D_
    key: 'sdfd',_x000D_
    value: 'sdfd'_x000D_
  },_x000D_
  item3: {_x000D_
    key: 'sdfd',_x000D_
    value: 'sdfd'_x000D_
  }_x000D_
};_x000D_
_x000D_
const allowed = ['item1', 'item3', 'lll'];_x000D_
_x000D_
var finalObj = {};_x000D_
allowed.forEach(allowedVal => {_x000D_
  if (raw[allowedVal])_x000D_
    finalObj[allowedVal] = raw[allowedVal]_x000D_
})_x000D_
console.log(finalObj)
_x000D_
_x000D_
_x000D_

It includes values of only those keys which are available in the raw data and thus preventing adding any junk data.

Creating SolidColorBrush from hex color value

vb.net version

Me.Background = CType(New BrushConverter().ConvertFrom("#ffaacc"), SolidColorBrush)

How to list files in a directory in a C program?

An example, available for POSIX compliant systems :

/*
 * This program displays the names of all files in the current directory.
 */

#include <dirent.h> 
#include <stdio.h> 

int main(void) {
  DIR *d;
  struct dirent *dir;
  d = opendir(".");
  if (d) {
    while ((dir = readdir(d)) != NULL) {
      printf("%s\n", dir->d_name);
    }
    closedir(d);
  }
  return(0);
}

Beware that such an operation is platform dependant in C.

Source : http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608

how to emulate "insert ignore" and "on duplicate key update" (sql merge) with postgresql?

Try to do an UPDATE. If it doesn't modify any row that means it didn't exist, so do an insert. Obviously, you do this inside a transaction.

You can of course wrap this in a function if you don't want to put the extra code on the client side. You also need a loop for the very rare race condition in that thinking.

There's an example of this in the documentation: http://www.postgresql.org/docs/9.3/static/plpgsql-control-structures.html, example 40-2 right at the bottom.

That's usually the easiest way. You can do some magic with rules, but it's likely going to be a lot messier. I'd recommend the wrap-in-function approach over that any day.

This works for single row, or few row, values. If you're dealing with large amounts of rows for example from a subquery, you're best of splitting it into two queries, one for INSERT and one for UPDATE (as an appropriate join/subselect of course - no need to write your main filter twice)

How to override equals method in Java

I'm not sure of the details as you haven't posted the whole code, but:

  • remember to override hashCode() as well
  • the equals method should have Object, not People as its argument type. At the moment you are overloading, not overriding, the equals method, which probably isn't what you want, especially given that you check its type later.
  • you can use instanceof to check it is a People object e.g. if (!(other instanceof People)) { result = false;}
  • equals is used for all objects, but not primitives. I think you mean age is an int (primitive), in which case just use ==. Note that an Integer (with a capital 'I') is an Object which should be compared with equals.

See What issues should be considered when overriding equals and hashCode in Java? for more details.

JPA CascadeType.ALL does not delete orphans

I just find this solution but in my case it doesn't work:

@OneToMany(cascade = CascadeType.ALL, targetEntity = MyClass.class, mappedBy = "xxx", fetch = FetchType.LAZY, orphanRemoval = true) 

orphanRemoval = true has no effect.

Find the most popular element in int[] array

Array elements value should be less than the array length for this one:

public void findCounts(int[] arr, int n) {
    int i = 0;

    while (i < n) {
        if (arr[i] <= 0) {
            i++;
            continue;
        }

        int elementIndex = arr[i] - 1;

        if (arr[elementIndex] > 0) {
            arr[i] = arr[elementIndex];
            arr[elementIndex] = -1;
        }
        else {
            arr[elementIndex]--;
            arr[i] = 0;
            i++;
        }
    }

    Console.WriteLine("Below are counts of all elements");

    for (int j = 0; j < n; j++) {
        Console.WriteLine(j + 1 + "->" + Math.Abs(arr[j]));
    }
}

Time complexity of this will be O(N) and space complexity will be O(1).

How to perform element-wise multiplication of two lists?

import ast,sys
input_str = sys.stdin.read()

input_list = ast.literal_eval(input_str)

list_1 = input_list[0]

list_2 = input_list[1]

import numpy as np

array_1 = np.array(list_1)

array_2 = np.array(list_2)

array_3 = array_1*array_2


print(list(array_3))

Why is "throws Exception" necessary when calling a function?

package javaexception;


public class JavaException {
   void show() throws Exception
    {
        throw new Exception("my.own.Exception");
    }

void show2() throws Exception  // Why throws is necessary here ?
{
    show();
}

void show3() throws Exception  // Why throws is necessary here ?
{
    show2();
}
public static void main(String[] args) {

   JavaException a = new JavaException();

   try{
   a.show3();
   }catch(Exception e){
       System.out.println(e.getMessage());
   }
}

Only small changes in your program. What It seems to be misunderstood by many regarding the main issue, is whenever you throw exception you need to handle it, not necessary in the same place ( ex. show1,2,3 method in your program) but you must at first caller method inside the 'main'. in one word, there is 'throw', there must be 'catch/try', even if not same method where exception happens.

Decompile .smali files on an APK

dex2jar helps to decompile your apk but not 100%. You will have some problems with .smali files. Dex2jar cannot convert it to java. I know one application that can decompile your apk source files and no problems with .smali files. Here is a link http://www.hensence.com/en/smali2java/

How to automatically update an application without ClickOnce?

A Lay men's way is

on Main() rename the executing assembly file .exe to some thing else check date and time of created. and the updated file date time and copy to the application folder.

//Rename he executing file
System.IO.FileInfo file = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);

System.IO.File.Move(file.FullName, file.DirectoryName + "\\" + file.Name.Replace(file.Extension,"") + "-1" + file.Extension);

then do the logic check and copy the new file to executing folder

How to get pandas.DataFrame columns containing specific dtype

Someone will give you a better answe than this possibly, but one thing I tend to do is if all my numeric data are int64 or float64 objects, then you can create a dict of the column data types and then use the values to create your list of columns.

So for example, in a dataframe where I have columns of type float64, int64 and object firstly you can look at the data types as so:

DF.dtypes

and if they conform to the standard whereby the non-numeric columns of data are all object types (as they are in my dataframes), then you can do the following to get a list of the numeric columns:

[key for key in dict(DF.dtypes) if dict(DF.dtypes)[key] in ['float64', 'int64']]

Its just a simple list comprehension. Nothing fancy. Again, though whether this works for you will depend upon how you set up you dataframe...

Is it possible to add dynamically named properties to JavaScript object?

Yes.

_x000D_
_x000D_
var data = {_x000D_
    'PropertyA': 1,_x000D_
    'PropertyB': 2,_x000D_
    'PropertyC': 3_x000D_
};_x000D_
_x000D_
data["PropertyD"] = 4;_x000D_
_x000D_
// dialog box with 4 in it_x000D_
alert(data.PropertyD);_x000D_
alert(data["PropertyD"]);
_x000D_
_x000D_
_x000D_

How can I update window.location.hash without jumping the document?

The problem is you are setting the window.location.hash to an element's ID attribute. It is the expected behavior for the browser to jump to that element, regardless of whether you "preventDefault()" or not.

One way to get around this is to prefix the hash with an arbitrary value like so:

window.location.hash = 'panel-' + id.replace('#', '');

Then, all you need to do is to check for the prefixed hash on page load. As an added bonus, you can even smooth scroll to it since you are now in control of the hash value...

$(function(){
    var h = window.location.hash.replace('panel-', '');
    if (h) {
        $('#slider').scrollTo(h, 800);
    }
});

If you need this to work at all times (and not just on the initial page load), you can use a function to monitor changes to the hash value and jump to the correct element on-the-fly:

var foundHash;
setInterval(function() {
    var h = window.location.hash.replace('panel-', '');
    if (h && h !== foundHash) {
        $('#slider').scrollTo(h, 800);
        foundHash = h;
    }
}, 100);

How to disable a input in angular2

A note in response to Belter's comment on fedtuck's accepted answer above, since I lack the reputation to add comments.

This is not true for any of which I am aware, in line with the Mozilla docs

disabled equals to true or false

When the disabled attribute is present the element is disabled regardless of value. See this example

<input placeholder="i can be changed"/>
<input disabled placeholder="i can NOT be changed"/>
<input disabled="true" placeholder="i can NOT be changed"/>
<input disabled="false" placeholder="i can NOT be changed"/>

Correct way to work with vector of arrays

Every element of your vector is a float[4], so when you resize every element needs to default initialized from a float[4]. I take it you tried to initialize with an int value like 0?

Try:

static float zeros[4] = {0.0, 0.0, 0.0, 0.0};
myvector.resize(newsize, zeros);

How to create Drawable from resource

This code is deprecated:

Drawable drawable = getResources().getDrawable( R.drawable.icon );

Use this instead:

Drawable drawable = ContextCompat.getDrawable(getApplicationContext(),R.drawable.icon);

How do I add slashes to a string in Javascript?

var str = "This is a single quote: ' and so is this: '";
console.log(str);

var replaced = str.replace(/'/g, "\\'");
console.log(replaced);

Gives you:

This is a single quote: ' and so is this: '
This is a single quote: \' and so is this: \'

How to JSON decode array elements in JavaScript?

Suppose you have an array in PHP as $iniData with 5 fields. If using ajax -

echo json_encode($iniData);

In Javascript, use the following :

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            type: "GET",
            url: "ajaxCalls.php",
            data: "dataType=ini",
            success: function(msg)
            {
                var x = eval('(' + msg + ')');
                $('#allowed').html(x.allowed);              // these are the fields which you can now easily access..
                $('#completed').html(x.completed);
                $('#running').html(x.running);
                $('#expired').html(x.expired);
                $('#balance').html(x.balance);
            }
        });
    });
</script>

How can I get the current stack trace in Java?

Getting stacktrace:

StackTraceElement[] ste = Thread.currentThread().getStackTrace();

Printing stacktrace (JAVA 8+):

Arrays.asList(ste).forEach(System.out::println);

Printing stacktrage (JAVA 7):

StringBuilder sb = new StringBuilder();

for (StackTraceElement st : ste) {
    sb.append(st.toString() + System.lineSeparator());
}
System.out.println(sb);

Map a 2D array onto a 1D array

Example : we want to represent an 2D array of SIZE_X and SIZE_Y size. That means that we will have MAXY consecutive rows of MAXX size. Hence the set function is

void set_array( int x, int y, int val ) { array[ x * SIZE_Y + y ] = val; }

The get would be:

int get_array( int x, int y ) { return array[ x * SIZE_Y + y ]; }

Javascript decoding html entities

Using jQuery the easiest will be:

var text = '&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;';

var output = $("<div />").html(text).text();
console.log(output);

DEMO: http://jsfiddle.net/LKGZx/

Set focus on textbox in WPF

Another possible solution is to use FocusBehavior provided by free DevExpress MVVM Framework:

<TextBox Text="This control is focused on startup">
    <dxmvvm:Interaction.Behaviors>
        <dxmvvm:FocusBehavior/>
    </dxmvvm:Interaction.Behaviors>
</TextBox>

It allows you to focus a control when it's loaded, when a certain event is raised or a property is changed.

Put a Delay in Javascript

If you're okay with ES2017, await is good:

const DEF_DELAY = 1000;

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms || DEF_DELAY));
}

await sleep(100);

Note that the await part needs to be in an async function:

//IIAFE (immediately invoked async function expression)
(async()=>{
  //Do some stuff
  await sleep(100);
  //Do some more stuff
})()

Android Left to Right slide animation

Also, you can do this:

FirstClass.this.overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);

And you don't need to add any animation xml

Entity Framework - Linq query with order by and group by

It's method syntax (which I find easier to read) but this might do it

Updated post comment

Use .FirstOrDefault() instead of .First()

With regard to the dates average, you may have to drop that ordering for the moment as I am unable to get to an IDE at the moment

var groupByReference = context.Measurements
                              .GroupBy(m => m.Reference)
                              .Select(g => new {Creation = g.FirstOrDefault().CreationTime, 
//                                              Avg = g.Average(m => m.CreationTime.Ticks),
                                                Items = g })
                              .OrderBy(x => x.Creation)
//                            .ThenBy(x => x.Avg)
                              .Take(numOfEntries)
                              .ToList();

Laravel Eloquent LEFT JOIN WHERE NULL

use Illuminate\Database\Eloquent\Builder;

$query = Customers::with('orders');
$query = $query->whereHas('orders', function (Builder $query) use ($request) {
     $query = $query->where('orders.customer_id', 'NULL') 
});
    $query = $query->get();

How do you right-justify text in an HTML textbox?

Did you try setting the style:

input {
    text-align:right;
}

Just tested, this works fine (in FF3 at least):

<html>
    <head>
        <title>Blah</title>
        <style type="text/css">
        input { text-align:right; }
        </style>
    </head>
    <body>
        <input type="text" value="2">
    </body>
</html>

You'll probably want to throw a class on these inputs, and use that class as the selector. I would shy away from "rightAligned" or something like that. In a class name, you want to describe what the element's function is, not how it should be rendered. "numeric" might be good, or perhaps the business function of the text boxes.

What does 'low in coupling and high in cohesion' mean

Low Coupling and High Cohesion is a recommended phenomenon.

Coupling means to what extent various modules are interdependent and how the other modules are affected on changing some/considerable functionality of a module. Low coupling is emphasized as the dependency has to be maintained low so that very least/negligible changes are made to other modules.

c# why can't a nullable int be assigned null as a value

Another option is to use

int? accom = (accomStr == "noval" ? Convert.DBNull : Convert.ToInt32(accomStr); 

I like this one most.

Get current cursor position

GetCursorPos() will return to you the x/y if you pass in a pointer to a POINT structure.

Hiding the cursor can be done with ShowCursor().

How to use UTF-8 in resource properties with ResourceBundle

Speaking for current (2021-2) Java versions there is still the old ISO-8859-1 function utils.Properties#load.

Allow me to quote from the official doc.

PropertyResourceBundle

PropertyResourceBundle can be constructed either from an InputStream or a Reader, which represents a property file. Constructing a PropertyResourceBundle instance from an InputStream requires that the input stream be encoded in UTF-8. By default, if a MalformedInputException or an UnmappableCharacterException occurs on reading the input stream, then the PropertyResourceBundle instance resets to the state before the exception, re-reads the input stream in ISO-8859-1, and continues reading. If the system property java.util.PropertyResourceBundle.encoding is set to either "ISO-8859-1" or "UTF-8", the input stream is solely read in that encoding, and throws the exception if it encounters an invalid sequence. If "ISO-8859-1" is specified, characters that cannot be represented in ISO-8859-1 encoding must be represented by Unicode Escapes as defined in section 3.3 of The Java™ Language Specification whereas the other constructor which takes a Reader does not have that limitation. Other encoding values are ignored for this system property. The system property is read and evaluated when initializing this class. Changing or removing the property has no effect after the initialization.

https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/PropertyResourceBundle.html

Properties#load

Reads a property list (key and element pairs) from the input byte stream. The input stream is in a simple line-oriented format as specified in load(Reader) and is assumed to use the ISO 8859-1 character encoding; that is each byte is one Latin1 character. Characters not in Latin1, and certain special characters, are represented in keys and elements using Unicode escapes as defined in section 3.3 of The Java™ Language Specification.

https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Properties.html#load(java.io.InputStream)

bootstrap 4 responsive utilities visible / hidden xs sm lg not working

Bootstrap 4 (^beta) has changed the classes for responsive hiding/showing elements. See this link for correct classes to use: http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements

How to add a border just on the top side of a UIView

Old question, but the autolayout-solution with runtime border adjustments still missing.

borders(for: [.left, .bottom], width: 2, color: .red)

The following UIView extension will add the border only on the given edges. If you change the edges at runtime, the borders will adjust accordingly.

extension UIView {
    func borders(for edges:[UIRectEdge], width:CGFloat = 1, color: UIColor = .black) {

        if edges.contains(.all) {
            layer.borderWidth = width
            layer.borderColor = color.cgColor
        } else {
            let allSpecificBorders:[UIRectEdge] = [.top, .bottom, .left, .right]

            for edge in allSpecificBorders {
                if let v = viewWithTag(Int(edge.rawValue)) {
                    v.removeFromSuperview()
                }

                if edges.contains(edge) {
                    let v = UIView()
                    v.tag = Int(edge.rawValue)
                    v.backgroundColor = color
                    v.translatesAutoresizingMaskIntoConstraints = false
                    addSubview(v)

                    var horizontalVisualFormat = "H:"
                    var verticalVisualFormat = "V:"

                    switch edge {
                    case UIRectEdge.bottom:
                        horizontalVisualFormat += "|-(0)-[v]-(0)-|"
                        verticalVisualFormat += "[v(\(width))]-(0)-|"
                    case UIRectEdge.top:
                        horizontalVisualFormat += "|-(0)-[v]-(0)-|"
                        verticalVisualFormat += "|-(0)-[v(\(width))]"
                    case UIRectEdge.left:
                        horizontalVisualFormat += "|-(0)-[v(\(width))]"
                        verticalVisualFormat += "|-(0)-[v]-(0)-|"
                    case UIRectEdge.right:
                        horizontalVisualFormat += "[v(\(width))]-(0)-|"
                        verticalVisualFormat += "|-(0)-[v]-(0)-|"
                    default:
                        break
                    }

                    self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: horizontalVisualFormat, options: .directionLeadingToTrailing, metrics: nil, views: ["v": v]))
                    self.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: verticalVisualFormat, options: .directionLeadingToTrailing, metrics: nil, views: ["v": v]))
                }
            }
        }
    }
}

Converting String to "Character" array in Java

I used the StringReader class in java.io. One of it's functions read(char[] cbuf) reads a string's contents into an array.

String str = "hello";
char[] array = new char[str.length()];
StringReader read = new StringReader(str);

try {
    read.read(array); //Reads string into the array. Throws IOException
} catch (IOException e) {
    e.printStackTrace();
}

for (int i = 0; i < str.length(); i++) {
        System.out.println("array["+i+"] = "+array[i]);
}

Running this gives you the output:

array[0] = h
array[1] = e
array[2] = l
array[3] = l
array[4] = o

How to update and delete a cookie?

http://www.quirksmode.org/js/cookies.html

update would just be resetting it using createCookie

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 *1000));
        var expires = "; expires=" + date.toGMTString();
    } else {
        var expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') {
            c = c.substring(1,c.length);
        }
        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length,c.length);
        }
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

What is the difference between document.location.href and document.location?

The document.location is an object that contains properties for the current location.

The href property is one of these properties, containing the complete URL, i.e. all the other properties put together.

Some browsers allow you to assign an URL to the location object and acts as if you assigned it to the href property. Some other browsers are more picky, and requires you to use the href property. Thus, to make the code work in all browsers, you have to use the href property.

Both the window and document objects has a location object. You can set the URL using either window.location.href or document.location.href. However, logically the document.location object should be read-only (as you can't change the URL of a document; changing the URL loads a new document), so to be on the safe side you should rather use window.location.href when you want to set the URL.

What is Express.js?

ExpressJS is bare-bones web application framework on top of NodeJS.

It can be used to build WebApps, RESTFUL APIs etc quickly.

Supports multiple template engines like Jade, EJS.

ExpressJS keeps only a minimalist functionality as core features and as such there are no ORMs or DBs supported as default. But with a little effort expressjs apps can be integrated with different databases.

For a getting started guide on creating ExpressJS apps, look into the following link:

ExpressJS Introductory Tutorial

Understanding unique keys for array children in React.js

var TableRowItem = React.createClass({
  render: function() {

    var td = function() {
        return this.props.columns.map(function(c, i) {
          return <td key={i}>{this.props.data[c]}</td>;
        }, this);
      }.bind(this);

    return (
      <tr>{ td(this.props.item) }</tr>
    )
  }
});

This will sove the problem.

Difference between onCreate() and onStart()?

onCreate() method gets called when activity gets created, and its called only once in whole Activity life cycle. where as onStart() is called when activity is stopped... I mean it has gone to background and its onStop() method is called by the os. onStart() may be called multiple times in Activity life cycle.More details here

Display a float with two decimal places in Python

String Formatting:

a = 6.789809823
print('%.2f' %a)

OR

print ("{0:.2f}".format(a)) 

Round Function can be used:

print(round(a, 2))

Good thing about round() is that, we can store this result to another variable, and then use it for other purposes.

b = round(a, 2)
print(b)

What is the best way to use a HashMap in C++?

Here's a more complete and flexible example that doesn't omit necessary includes to generate compilation errors:

#include <iostream>
#include <unordered_map>

class Hashtable {
    std::unordered_map<const void *, const void *> htmap;

public:
    void put(const void *key, const void *value) {
            htmap[key] = value;
    }

    const void *get(const void *key) {
            return htmap[key];
    }

};

int main() {
    Hashtable ht;
    ht.put("Bob", "Dylan");
    int one = 1;
    ht.put("one", &one);
    std::cout << (char *)ht.get("Bob") << "; " << *(int *)ht.get("one");
}

Still not particularly useful for keys, unless they are predefined as pointers, because a matching value won't do! (However, since I normally use strings for keys, substituting "string" for "const void *" in the declaration of the key should resolve this problem.)

Difference between "\n" and Environment.NewLine

As others have mentioned, Environment.NewLine returns a platform-specific string for beginning a new line, which should be:

  • "\r\n" (\u000D\u000A) for Windows
  • "\n" (\u000A) for Unix
  • "\r" (\u000D) for Mac (if such implementation existed)

Note that when writing to the console, Environment.NewLine is not strictly necessary. The console stream will translate "\n" to the appropriate new-line sequence, if necessary.

Populating a razor dropdownlist from a List<object> in MVC

Something close to:

@Html.DropDownListFor(m => m.UserRole, 
   new SelectList(Model.Roles, "UserRoleId", "UserRole", Model.Roles.First().UserRoleId), 
   new { /* any html  attributes here */ }) 

You need a SelectList to populate the DropDownListFor. For any HTML attributes you need, you can add:

new { @class = "DropDown", @id = "dropdownUserRole" }

How do I deserialize a complex JSON object in C# .NET?

I solved this problem to add a public setter for all properties, which should be deserialized.

Environment Variable with Maven

I suggest using the amazing tool direnv. With it you can inject environment variables once you cd into the project. These steps worked for me:

.envrc file

source_up
dotenv

.env file

_JAVA_OPTIONS="-DYourEnvHere=123"

How to check if ping responded or not in a batch file

I hope this helps someone. I use this bit of logic to verify if network shares are responsive before checking the individual paths. It should handle DNS names and IP addresses

A valid path in the text file would be \192.168.1.2\'folder' or \NAS\'folder'

@echo off
title Network Folder Check

pushd "%~dp0"
:00
cls

for /f "delims=\\" %%A in (Files-to-Check.txt) do set Server=%%A
    setlocal EnableDelayedExpansion
        ping -n 1 %Server% | findstr TTL= >nul 
            if %errorlevel%==1 ( 
                ping -n 1 %Server% | findstr "Reply from" | findstr "time" >nul
                    if !errorlevel!==1 (echo Network Asset %Server% Not Found & pause & goto EOF)
            )
:EOF

To get specific part of a string in c#

Your question is vague (are you always looking for the first part?), but you can get the exact output you asked for with string.Split:

string[] substrings = a.Split(',');
b = substrings[0];
Console.WriteLine(b);

Output:

abc

Cygwin Make bash command not found

I faced the same problem too. Look up to the left side, and select (full). (Make), (gcc) and many others will appear. You will be able to chose the search bar to find them easily.

Converting string into datetime

Create a small utility function like:

def date(datestr="", format="%Y-%m-%d"):
    from datetime import datetime
    if not datestr:
        return datetime.today().date()
    return datetime.strptime(datestr, format).date()

This is versatile enough:

  • If you don't pass any arguments it will return today's date.
  • There's a date format as default that you can override.
  • You can easily modify it to return a datetime.

How to set up Android emulator proxy settings

Easiest way is to delete default APN from emulator(in my case its T- mobile) and create new APN with your proxy settings.

Note: i have tried all command line options and also tried setting the proxy for emulators default APN but nothing worked.

How do I record audio on iPhone with AVAudioRecorder?

I have uploaded a sample project. You can take a look.

VoiceRecorder

How to play .mp4 video in videoview in android?

Check the format of the video you are rendering. Rendering of mp4 format started from API level 11 and the format must be mp4(H.264)

I encountered the same problem, I had to convert my video to many formats before I hit the format: Use total video converter to convert the video to mp4. It works like a charm.

Android, Java: HTTP POST Request

to @BalusC answer I would add how to convert the response in a String:

HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
    InputStream instream = entity.getContent();

    String result = RestClient.convertStreamToString(instream);
    Log.i("Read from server", result);
}

Here is an example of convertStramToString.

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

set <ORACLE_HOME> path variable

example

path ORACLE_HOME

value is C:\oraclexe\app\oracle\product\10.2.0\server

enter image description here

How can I completely uninstall nodejs, npm and node in Ubuntu

Note: This will completely remove nodejs from your system; then you can make a fresh install from the below commands.

Removing Nodejs and Npm

sudo apt-get remove nodejs npm node
sudo apt-get purge nodejs

Now remove .node and .npm folders from your system

sudo rm -rf /usr/local/bin/npm 
sudo rm -rf /usr/local/share/man/man1/node* 
sudo rm -rf /usr/local/lib/dtrace/node.d 
sudo rm -rf ~/.npm 
sudo rm -rf ~/.node-gyp 
sudo rm -rf /opt/local/bin/node 
sudo rm -rf opt/local/include/node 
sudo rm -rf /opt/local/lib/node_modules  

sudo rm -rf /usr/local/lib/node*
sudo rm -rf /usr/local/include/node*
sudo rm -rf /usr/local/bin/node*

Go to home directory and remove any node or node_modules directory, if exists.

You can verify your uninstallation by these commands; they should not output anything.

which node
which nodejs
which npm

Installing NVM (Node Version Manager) by downloading and running a script

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.34.0/install.sh | bash

The command above will clone the NVM repository from Github to the ~/.nvm directory:

Close and reopen your terminal to start using nvm or run the following to use it now:

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

As the output above says, you should either close and reopen the terminal or run the commands to add the path to nvm script to the current shell session. You can do whatever is easier for you.

Once the script is in your PATH, verify that nvm was properly installed by typing:

nvm --version

which should give this output:

0.34.0

Installing Node.js and npm

nvm install node
nvm install --lts

Once the installation is completed, verify it by printing the Node.js version:

node --version

should give this output:

v12.8.1

Npm should also be installed with node, verify it using

npm -v

should give:

6.13.4

Extra - [Optional] You can also use two different versions of node using nvm easily

nvm install 8.10.0 # just put the node version number Now switch between node versions

$ nvm ls
->     v12.14.1
        v13.7.0
default -> lts/* (-> v12.14.1)
node -> stable (-> v13.7.0) (default)
stable -> 13.7 (-> v13.7.0) (default)
iojs -> N/A (default)
unstable -> N/A (default)
lts/* -> lts/erbium (-> v12.14.1)
lts/argon -> v4.9.1 (-> N/A)
lts/boron -> v6.17.1 (-> N/A)
lts/carbon -> v8.17.0 (-> N/A)
lts/dubnium -> v10.18.1 (-> N/A)

In my case v12.14.1 and v13.7.0 both are installed, to switch I have to just use

nvm use 12.14.1

Configuring npm for global installations In your home directory, create a directory for global installations:

mkdir ~/.npm-global

Configure npm to use the new directory path:

npm config set prefix '~/.npm-global'

In your preferred text editor, open or create a ~/.profile file if does not exist and add this line:

PATH="$HOME/.npm-global/bin:$PATH"

On the command line, update your system variables:

source ~/.profile

That's all

How to use sed to remove all double quotes within a file

You just need to escape the quote in your first example:

$ sed 's/\"//g' file.txt

Swift days between two NSDates

Erin's method updated to Swift 3, This shows days from today (disregarding time of day)

func daysBetweenDates( endDate: Date) -> Int 
    let calendar: Calendar = Calendar.current 
    let date1 = calendar.startOfDay(for: Date()) 
    let date2 = calendar.startOfDay(for: secondDate) 
    return calendar.dateComponents([.day], from: date1, to: date2).day! 
}

What is the Swift equivalent of respondsToSelector?

Currently (Swift 2.1) you can check it using 3 ways:

  1. Using respondsToSelector answered by @Erik_at_Digit
  2. Using '?' answered by @Sulthan

  3. And using as? operator:

    if let delegateMe = self.delegate as? YourCustomViewController
    {
       delegateMe.onSuccess()
    }
    

Basically it depends on what you are trying to achieve:

  • If for example your app logic need to perform some action and the delegate isn't set or the pointed delegate didn't implement the onSuccess() method (protocol method) so option 1 and 3 are the best choice, though I'd use option 3 which is Swift way.
  • If you don't want to do anything when delegate is nil or method isn't implemented then use option 2.

JavaScript function in href vs. onclick

In addition to all here, the href is shown on browser's status bar, and onclick not. I think it's not user friendly to show javascript code there.

How exactly does binary code get converted into letters?

Here's a way to convert binary numbers to ASCII characters that is often simple enough to do in your head.

1 - Convert every 4 binary digits into one hex digit.

Here's a binary to hex conversion chart:

0001 = 1 
0010 = 2 
0011 = 3 
0100 = 4 
0101 = 5
0110 = 6
0111 = 7
1000 = 8

1001 = 9
1010 = a (the hex number a, not the letter a)
1011 = b
1100 = c
1101 = d
1110 = e
1111 = f

(The hexadecimal numbers a through f are the decimal numbers 10 through 15. That's what hexadecimal, or "base 16" is - instead of each digit being capable of representing 10 different numbers [0 - 9], like decimal or "base 10" does, each digit is instead capable of representing 16 different numbers [0 - f].)

Once you know that chart, converting any string of binary digits into a string of hex digits is simple.

For example,

01000100 = 0100 0100 = 44 hex
1010001001110011 = 1010 0010 0111 0011 = a273 hex

Simple enough, right? It is a simple matter to convert a binary number of any length into its hexadecimal equivalent.

(This works because hexadecimal is base 16 and binary is base 2 and 16 is the 4th power of 2, so it takes 4 binary digits to make 1 hex digit. 10, on the other hand, is not a power of 2, so we can't convert binary to decimal nearly as easily.)

2 - Split the string of hex digits into pairs.

When converting a number into ASCII, every 2 hex digits is a character. So break the hex string into sets of 2 digits.

You would split a hex number like 7340298b392 this into 6 pairs, like this:

7340298b392 = 07 34 02 98 b3 92

(Notice I prepended a 0, since I had an odd number of hex digits.)

That's 6 pairs of hex digits, so its going to be 6 letters. (Except I know right away that 98, b3 and 92 aren't letters. I'll explain why in a minute.)

3 - Convert each pair of hex digits into a decimal number.

Do this by multiplying the (decimal equivalent of the) left digit by 16, and adding the 2nd.

For example, b3 hex = 11*16 + 3, which is 110 + 66 + 3, which is 179. (b hex is 11 decimal.)

4 - Convert the decimal numbers into ASCII characters.

Now, to get the ASCII letters for the decimal numbers, simply keep in mind that in ASCII, 65 is an uppercase 'A', and 97 is a lowercase 'a'.

So what letter is 68?

68 is the 4th letter of the alphabet in uppercase, right?
65 = A, 66 = B, 67 = C, 68 = D.

So 68 is 'D'.

You take the decimal number, subtract 64 for uppercase letters if the number is less than 97, or 96 for lowercase letters if the number is 97 or larger, and that's the number of the letter of the alphabet associated with that set of 2 hex digits.


Alternatively, if you're not afraid of a little bit of easy hex arithmetic, you can skip step 3, and just go straight from hex to ASCII, by remembering, for example, that

hex 41 = 'A' 
hex 61 = 'a'

So subtract 40 hex for uppercase letters or 60 hex for lowercase letters, and convert what's left to decimal to get the alphabet letter number.

For example

01101100 = 6c, 6c - 60 = c = 12 decimal = 'l'
01010010 = 52, 52 - 40 = 12 hex = 18 decimal = 'R'

(When doing this, it's helpful to remember that 'm' (or 'M') is the 13 letter of the alphabet. So you can count up or down from 13 to find a letter that's nearer to the middle than to either end.)

I saw this on a shirt once, and was able to read it in my head:

01000100
01000001
01000100

I did it like this:

01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D
01000001 = 0100 0001 = 41 hex, - 40 hex = ucase letter 1 = A
01000100 = 0100 0100 = 44 hex, - 40 hex = ucase letter 4 = D

The shirt said "DAD", which I thought was kinda cool, since it was being purchased by a pregnant woman. Her husband must be a geek like me.


How did I know right away that 92, b3, and 98 were not letters?

Because the ASCII code for a lowercase 'z' is 96 + 26 = 122, which in hex is 7a. 7a is the largest hex number for a letter. Anything larger than 7a is not a letter.


So that's how you can do it as a human.

How do computer programs do it?

For each set of 8 binary digits, convert it to a number, and look it up in an ASCII table.

(That's one pretty obvious and straight forward way. A typical programmer could probably think of 10 or 15 other ways in the space of a few minutes. The details depend on the computer language environment.)

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

Just to add another solution to the list, what I've found is that Visual Studio (2012 in my case) occasionally locks files under different processes.

So, on a crash, devenv.exe might still be running and holding onto the file(s). Alternatively (as I just discovered), vstestrunner or vstestdiscovery might be holding onto the file as well.

Kill all those processes and it might fix up the issue.

What is Domain Driven Design?

I do not want to repeat others' answers, so, in short I explain some common misunderstanding

  • Practical resource: PATTERNS, PRINCIPLES, AND PRACTICES OF DOMAIN-DRIVEN DESIGN by Scott Millett
  • It is a methodology for complicated business systems. It takes all the technical matters out when communicating with business experts
  • It provides an extensive understanding of (simplified and distilled model of) business across the whole dev team.
  • it keeps business model in sync with code model by using ubiquitous language (the language understood by the whole dev team, business experts, business analysts, ...), which is used for communication within the dev team or dev with other teams
  • It has nothing to do with Project Management. Although it can be perfectly used in project management methods like Agile.
  • You should avoid using it all across your project

    DDD stresses the need to focus the most effort on the core subdomain. The core subdomain is the area of your product that will be the difference between it being a success and it being a failure. It’s the product’s unique selling point, the reason it is being built rather than bought.

    Basically, it is because it takes too much time and effort. So, it is suggested to break down the whole domain into subdomain and just apply it in those with high business value. (ex not in generic subdomain like email, ...)

  • It is not object oriented programming. It is mostly problem solving approach and (sometimes) you do not need to use OO patterns (such as Gang of Four) in your domain models. Simply because it can not be understood by Business Experts (they do not know much about Factory, Decorator, ...). There are even some patterns in DDD (such as The Transaction Script, Table Module) which are not 100% in line with OO concepts.

What is the meaning of ToString("X2")?

It formats the string as two uppercase hexadecimal characters.

In more depth, the argument "X2" is a "format string" that tells the ToString() method how it should format the string. In this case, "X2" indicates the string should be formatted in Hexadecimal.

byte.ToString() without any arguments returns the number in its natural decimal representation, with no padding.

Microsoft documents the standard numeric format strings which generally work with all primitive numeric types' ToString() methods. This same pattern is used for other types as well: for example, standard date/time format strings can be used with DateTime.ToString().

how to check if input field is empty

As javascript is dynamically typed, rather than using the .length property as above you can simply treat the input value as a boolean:

var input = $.trim($("#spa").val());

if (input) {
    // Do Stuff
}

You can also extract the logic out into functions, then by assigning a class and using the each() method the code is more dynamic if, for example, in the future you wanted to add another input you wouldn't need to change any code.

So rather than hard coding the function call into the input markup, you can give the inputs a class, in this example it's test, and use:

$(".test").each(function () {
    $(this).keyup(function () {
        $("#submit").prop("disabled", CheckInputs());
    });
});

which would then call the following and return a boolean value to assign to the disabled property:

function CheckInputs() {
    var valid = false;
    $(".test").each(function () {
        if (valid) { return valid; }
        valid = !$.trim($(this).val());
    });
    return valid;
}

You can see a working example of everything I've mentioned in this JSFiddle.

Does Java support default parameter values?

You can do this is in Scala, which runs on the JVM and is compatible with Java programs. http://www.scala-lang.org/

i.e.

class Foo(var prime: Boolean = false, val rib: String)  {}

How store a range from excel into a Range variable?

When you use a Range object, you cannot simply use the following syntax:

Dim myRange as Range
myRange = Range("A1")  

You must use the set keyword to assign Range objects:

Function getData(currentWorksheet As Worksheet, dataStartRow As Integer, dataEndRow As Integer, DataStartCol As Integer, dataEndCol As Integer)

    Dim dataTable As Range
    Set dataTable = currentWorksheet.Range(currentWorksheet.Cells(dataStartRow, DataStartCol), currentWorksheet.Cells(dataEndRow, dataEndCol))

    Set getData = dataTable

End Function

Sub main()
    Dim test As Range

    Set test = getData(ActiveSheet, 1, 3, 2, 5)
    test.select

End Sub

Note that every time a range is declared I use the Set keyword.


You can also allow your getData function to return a Range object instead of a Variant although this is unrelated to the problem you are having.

Easy way to print Perl array? (with a little formatting)

Map can also be used, but sometimes hard to read when you have lots of things going on.

map{ print "element $_\n" }   @array; 

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

From Android Studio v3 and up, Infer Constraint was removed from the dropdown.

Use the magic wand icon in the toolbar menu above the design preview; there is the "Infer Constraints" button. Click on this button, this will automatically add some lines in the text field and the red line will be removed.

enter image description here

How to hide elements without having them take space on the page?

Try setting display:none to hide and set display:block to show.

How can I check if a key exists in a dictionary?

Another method is has_key() (if still using Python 2.X):

>>> a={"1":"one","2":"two"}
>>> a.has_key("1")
True

How to list files using dos commands?

Try dir /b, for bare format.

dir /? will show you documentation of what you can do with the dir command. Here is the output from my Windows 7 machine:

C:\>dir /?
Displays a list of files and subdirectories in a directory.

DIR [drive:][path][filename] [/A[[:]attributes]] [/B] [/C] [/D] [/L] [/N]
  [/O[[:]sortorder]] [/P] [/Q] [/R] [/S] [/T[[:]timefield]] [/W] [/X] [/4]

  [drive:][path][filename]
              Specifies drive, directory, and/or files to list.

  /A          Displays files with specified attributes.
  attributes   D  Directories                R  Read-only files
               H  Hidden files               A  Files ready for archiving
               S  System files               I  Not content indexed files
               L  Reparse Points             -  Prefix meaning not
  /B          Uses bare format (no heading information or summary).
  /C          Display the thousand separator in file sizes.  This is the
              default.  Use /-C to disable display of separator.
  /D          Same as wide but files are list sorted by column.
  /L          Uses lowercase.
  /N          New long list format where filenames are on the far right.
  /O          List by files in sorted order.
  sortorder    N  By name (alphabetic)       S  By size (smallest first)
               E  By extension (alphabetic)  D  By date/time (oldest first)
               G  Group directories first    -  Prefix to reverse order
  /P          Pauses after each screenful of information.
  /Q          Display the owner of the file.
  /R          Display alternate data streams of the file.
  /S          Displays files in specified directory and all subdirectories.
  /T          Controls which time field displayed or used for sorting
  timefield   C  Creation
              A  Last Access
              W  Last Written
  /W          Uses wide list format.
  /X          This displays the short names generated for non-8dot3 file
              names.  The format is that of /N with the short name inserted
              before the long name. If no short name is present, blanks are
              displayed in its place.
  /4          Displays four-digit years

Switches may be preset in the DIRCMD environment variable.  Override
preset switches by prefixing any switch with - (hyphen)--for example, /-W.

How can I display a list view in an Android Alert Dialog?

You can actually create a simple Array with Alert Dialog like this.

 val sexArray = arrayOf("Male", "Female")
 val selectedPosition = 0

 AlertDialog.Builder(requireContext())
    .setSingleChoiceItems(sexArray, 0) { dialog, position ->
        val selectedSex = sexArray[position]
    }.show()

How do I run a Python program?

In IDLE press F5

You can open your .py file with IDLE and press F5 to run it.

You can open that same file with other editor ( like Komodo as you said ) save it and press F5 again; F5 works with IDLE ( even when the editing is done with another tool ).

If you want to run it directly from Komodo according to this article: Executing Python Code Within Komodo Edit you have to:

  1. go to Toolbox -> Add -> New Command...
  2. in the top field enter the name 'Run Python file'
  3. in the 'Command' field enter this text:

    %(python) %F 3.a optionall click on the 'Key Binding' tab and assign a key command to this command

  4. click Ok.

How to properly add include directories with CMake

First, you use include_directories() to tell CMake to add the directory as -I to the compilation command line. Second, you list the headers in your add_executable() or add_library() call.

As an example, if your project's sources are in src, and you need headers from include, you could do it like this:

include_directories(include)

add_executable(MyExec
  src/main.c
  src/other_source.c
  include/header1.h
  include/header2.h
)

What is the preferred syntax for defining enums in JavaScript?

Create an object literal:

const Modes = {
  DRAGGING: 'drag',
  SCALING:  'scale',
  CLICKED:  'click'
};

How do I iterate and modify Java Sets?

Firstly, I believe that trying to do several things at once is a bad practice in general and I suggest you think over what you are trying to achieve.

It serves as a good theoretical question though and from what I gather the CopyOnWriteArraySet implementation of java.util.Set interface satisfies your rather special requirements.

http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/CopyOnWriteArraySet.html

Get value from hashmap based on key to JSTL

could you please try below code

<c:forEach var="hash" items="${map['key']}">
        <option><c:out value="${hash}"/></option>
  </c:forEach>

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

Edit: Documented by Apple although I couldn't actually get it to work: WKWebView Behavior with Keyboard Displays: "In iOS 10, WKWebView objects match Safari’s native behavior by updating their window.innerHeight property when the keyboard is shown, and do not call resize events" (perhaps can use focus or focus plus delay to detect keyboard instead of using resize).

Edit: code presumes onscreen keyboard, not external keyboard. Leaving it because info may be useful to others that only care about onscreen keyboards. Use http://jsbin.com/AbimiQup/4 to view page params.

We test to see if the document.activeElement is an element which shows the keyboard (input type=text, textarea, etc).

The following code fudges things for our purposes (although not generally correct).

function getViewport() {
    if (window.visualViewport && /Android/.test(navigator.userAgent)) {
        // https://developers.google.com/web/updates/2017/09/visual-viewport-api    Note on desktop Chrome the viewport subtracts scrollbar widths so is not same as window.innerWidth/innerHeight
        return {
            left: visualViewport.pageLeft,
            top: visualViewport.pageTop,
            width: visualViewport.width,
            height: visualViewport.height
        };
    }
    var viewport = {
            left: window.pageXOffset,   // http://www.quirksmode.org/mobile/tableViewport.html
            top: window.pageYOffset,
            width: window.innerWidth || documentElement.clientWidth,
            height: window.innerHeight || documentElement.clientHeight
    };
    if (/iPod|iPhone|iPad/.test(navigator.platform) && isInput(document.activeElement)) {       // iOS *lies* about viewport size when keyboard is visible. See http://stackoverflow.com/questions/2593139/ipad-web-app-detect-virtual-keyboard-using-javascript-in-safari Input focus/blur can indicate, also scrollTop: 
        return {
            left: viewport.left,
            top: viewport.top,
            width: viewport.width,
            height: viewport.height * (viewport.height > viewport.width ? 0.66 : 0.45)  // Fudge factor to allow for keyboard on iPad
        };
    }
    return viewport;
}


function isInput(el) {
    var tagName = el && el.tagName && el.tagName.toLowerCase();
    return (tagName == 'input' && el.type != 'button' && el.type != 'radio' && el.type != 'checkbox') || (tagName == 'textarea');
};

The above code is only approximate: It is wrong for split keyboard, undocked keyboard, physical keyboard. As per comment at top, you may be able to do a better job than the given code on Safari (since iOS8?) or WKWebView (since iOS10) using window.innerHeight property.

I have found failures under other circumstances: e.g. give focus to input then go to home screen then come back to page; iPad shouldnt make viewport smaller; old IE browsers won't work, Opera didnt work because Opera kept focus on element after keyboard closed.

However the tagged answer (changing scrolltop to measure height) has nasty UI side effects if viewport zoomable (or force-zoom enabled in preferences). I don't use the other suggested solution (changing scrolltop) because on iOS, when viewport is zoomable and scrolling to focused input, there are buggy interactions between scrolling & zoom & focus (that can leave a just focused input outside of viewport - not visible).

How do I make an auto increment integer field in Django?

You can use default primary key (id) which auto increaments.

Note: When you use first design i.e. use default field (id) as a primary key, initialize object by mentioning column names. e.g.

class User(models.Model):
    user_name = models.CharField(max_length = 100)

then initialize,

user = User(user_name="XYZ")

if you initialize in following way,

user = User("XYZ")

then python will try to set id = "XYZ" which will give you error on data type.

Composer - the requested PHP extension mbstring is missing from your system

  1. find your php.ini
  2. make sure the directive extension_dir=C:\path\to\server\php\ext is set and adjust the path (set your PHP extension dir)
  3. make sure the directive extension=php_mbstring.dll is set (uncommented)

If this doesn't work and the php_mbstring.dll file is missing, then the PHP installation of this stack is simply broken.

Call to undefined function mysql_connect

Just for future reference, copying all these extension files to Windows/System or Windows/System32 is unnecessary.

All that is required is a copy of the php.ini file you edit in the PHP dir to copied to the root Windows dir.

phpinfo will clearly explain the below: Configuration File (php.ini) Path C:\Windows

Logical sense will explain that php wants to load a config located in the Windows dir. :-)

Adb Devices can't find my phone

I have a Fascinate as well, and had to change the phone's USB communication mode from MODEM to PDA. Use:

  • enter **USBUI (**87284)

to change both USB and UART to PDA mode. I also had to disconnect and reconnect the USB cable. Once Windows re-recognized the device again, "adb devices" started returning my device.

BTW if you use CDMA workshop or the equivalent, you will need to switch the setting back to MODEM.

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

Check if inputs are empty using jQuery

The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)

    $("#inputname").keyup(function() {

if (!this.value) {
    alert('The box is empty');
}});

Unlocking tables if thread is lost

Here's what i do to FORCE UNLOCK FOR some locked tables in MySQL

1) Enter MySQL

mysql -u your_user -p

2) Let's see the list of locked tables

mysql> show open tables where in_use>0;

3) Let's see the list of the current processes, one of them is locking your table(s)

mysql> show processlist;

4) Let's kill one of these processes

mysql> kill put_process_id_here;

Get method arguments using Spring AOP?

if your using @Aspect an option is add this method inside your Aspect and send the JoinPoint and the name of parameter you need.

private Object getParameter(ProceedingJoinPoint joinPoint, String parameterName) {
    Object valueParameter = null;
    if (Objects.nonNull(joinPoint) && joinPoint.getSignature() instanceof MethodSignature
            && Objects.nonNull(parameterName) ) {
        MethodSignature method = (MethodSignature)joinPoint.getSignature();
        String[] parameters = method.getParameterNames();
        for (int t = 0; t< parameters.length; t++) {
            if( Objects.nonNull(parameters[t]) && parameters[t].equals(parameterName)) {
                Object[] obj = joinPoint.getArgs();
                valueParameter = obj[t];
            }
        }
    }
    return valueParameter;
}

and the call example:

Object parameterObject = getParameter(joinPoint, "nameClient");
if ( Objects.nonNull(parameterObject) ) {
    String parametro = String.valueOf(parameterObject);
}

Only need know the type of object for convert

How to call Stored Procedures with EntityFramework?

Based up the OP's original request to be able to called a stored proc like this...

using (Entities context = new Entities())
{
    context.MyStoreadProcedure(Parameters); 
}

Mindless passenger has a project that allows you to call a stored proc from entity frame work like this....

using (testentities te = new testentities())
{
    //-------------------------------------------------------------
    // Simple stored proc
    //-------------------------------------------------------------
    var parms1 = new testone() { inparm = "abcd" };
    var results1 = te.CallStoredProc<testone>(te.testoneproc, parms1);
    var r1 = results1.ToList<TestOneResultSet>();
}

... and I am working on a stored procedure framework (here) which you can call like in one of my test methods shown below...

[TestClass]
public class TenantDataBasedTests : BaseIntegrationTest
{
    [TestMethod]
    public void GetTenantForName_ReturnsOneRecord()
    {
        // ARRANGE
        const int expectedCount = 1;
        const string expectedName = "Me";

        // Build the paraemeters object
        var parameters = new GetTenantForTenantNameParameters
        {
            TenantName = expectedName
        };

        // get an instance of the stored procedure passing the parameters
        var procedure = new GetTenantForTenantNameProcedure(parameters);

        // Initialise the procedure name and schema from procedure attributes
        procedure.InitializeFromAttributes();

        // Add some tenants to context so we have something for the procedure to return!
        AddTenentsToContext(Context);

        // ACT
        // Get the results by calling the stored procedure from the context extention method 
        var results = Context.ExecuteStoredProcedure(procedure);

        // ASSERT
        Assert.AreEqual(expectedCount, results.Count);
    }
}

internal class GetTenantForTenantNameParameters
{
    [Name("TenantName")]
    [Size(100)]
    [ParameterDbType(SqlDbType.VarChar)]
    public string TenantName { get; set; }
}

[Schema("app")]
[Name("Tenant_GetForTenantName")]
internal class GetTenantForTenantNameProcedure
    : StoredProcedureBase<TenantResultRow, GetTenantForTenantNameParameters>
{
    public GetTenantForTenantNameProcedure(
        GetTenantForTenantNameParameters parameters)
        : base(parameters)
    {
    }
}

If either of those two approaches are any good?

Create a jTDS connection string

Really, really, really check if the TCP/IP protocol is enabled in your local SQLEXPRESS instance.

Follow these steps to make sure:

  • Open "Sql Server Configuration Manager" in "Start Menu\Programs\Microsoft SQL Server 2012\Configuration Tools\"
  • Expand "SQL Server Network Configuration"
  • Go in "Protocols for SQLEXPRESS"
  • Enable TCP/IP

If you have any problem, check this blog post for details, as it contains screenshots and much more info.

Also check if the "SQL Server Browser" windows service is activated and running:

  • Go to Control Panel -> Administrative Tools -> Services
  • Open "SQL Server Browser" service and enable it (make it manual or automatic, depends on your needs)
  • Start it.

That's it.

After I installed a fresh local SQLExpress, all I had to do was to enable TCP/IP and start the SQL Server Browser service.

Below a code I use to test the SQLEXPRESS local connection. Of course, you should change the IP, DatabaseName and user/password as needed.:

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JtdsSqlExpressInstanceConnect {
    public static void main(String[] args) throws SQLException {
        Connection conn = null;
        ResultSet rs = null;
        String url = "jdbc:jtds:sqlserver://127.0.0.1;instance=SQLEXPRESS;DatabaseName=master";
        String driver = "net.sourceforge.jtds.jdbc.Driver";
        String userName = "user";
        String password = "password";
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, userName, password);
            System.out.println("Connected to the database!!! Getting table list...");
            DatabaseMetaData dbm = conn.getMetaData();
            rs = dbm.getTables(null, null, "%", new String[] { "TABLE" });
            while (rs.next()) { System.out.println(rs.getString("TABLE_NAME")); }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            conn.close();
            rs.close();
        }
    }
}

And if you use Maven, add this to your pom.xml:

<dependency>
    <groupId>net.sourceforge.jtds</groupId>
    <artifactId>jtds</artifactId>
    <version>1.2.4</version>
</dependency>

What is the difference between SQL Server 2012 Express versions?

This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.

Summary compiled from the above document:

    * = contains the feature
                                           SQLEXPR    SQLEXPRWT   SQLEXPRADV
 ----------------------------------------------------------------------------
    > SQL Server Core                         *           *           *
    > SQL Server Management Studio            -           *           *
    > Distributed Replay – Admin Tool         -           *           *
    > LocalDB                                 -           *           *
    > SQL Server Data Tools (SSDT)            -           -           *
    > Full-text and semantic search           -           -           *
    > Specification of language in query      -           -           *
    > some of Reporting services features     -           -           *

SQL query: Delete all records from the table except latest N?

Using id for this task is not an option in many cases. For example - table with twitter statuses. Here is a variant with specified timestamp field.

delete from table 
where access_time >= 
(
    select access_time from  
    (
        select access_time from table 
            order by access_time limit 150000,1
    ) foo    
)

Input placeholders for Internet Explorer

I created my own jQuery plugin after becoming frustrated that the existing shims would hide the placeholder on focus, which creates an inferior user experience and also does not match how Firefox, Chrome and Safari handle it. This is especially the case if you want an input to be focused when a page or popup first loads, while still showing the placeholder until text is entered.

https://github.com/nspady/jquery-placeholder-labels/

How to amend older Git commit?

git rebase -i HEAD^^^

Now mark the ones you want to amend with edit or e (replace pick). Now save and exit.

Now make your changes, then

git add .
git rebase --continue

If you want to add an extra delete remove the options from the commit command. If you want to adjust the message, omit just the --no-edit option.

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

VBA subs are no macros. A VBA sub can be a macro, but it is not a must.

The term "macro" is only used for recorded user actions. from these actions a code is generated and stored in a sub. This code is simple and do not provide powerful structures like loops, for example Do .. until, for .. next, while.. do, and others.

The more elegant way is, to design and write your own VBA code without using the macro features!

VBA is a object based and event oriented language. Subs, or bette call it "sub routines", are started by dedicated events. The event can be the pressing of a button or the opening of a workbook and many many other very specific events.

If you focus to VB6 and not to VBA, then you can state, that there is always a main-window or main form. This form is started if you start the compiled executable "xxxx.exe".

In VBA you have nothing like this, but you have a XLSM file wich is started by Excel. You can attach some code to the Workbook_Open event. This event is generated, if you open your desired excel file which is called a workbook. Inside the workbook you have worksheets.

It is useful to get more familiar with the so called object model of excel. The workbook has several events and methods. Also the worksheet has several events and methods.

In the object based model you have objects, that have events and methods. methods are action you can do with a object. events are things that can happen to an object. An objects can contain another objects, and so on. You can create new objects, like sheets or charts.

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

It is two problems - is the slashes the right places and is it a valid date. I would suggest you catch input changes and put the slashes in yourself. (annoying for the user)

The interesting problem is whether they put in a valid date and I would suggest exploiting how flexible js is:

_x000D_
_x000D_
function isValidDate(str) {_x000D_
  var newdate = new Date();_x000D_
  var yyyy = 2000 + Number(str.substr(4, 2));_x000D_
  var mm = Number(str.substr(2, 2)) - 1;_x000D_
  var dd = Number(str.substr(0, 2));_x000D_
  newdate.setFullYear(yyyy);_x000D_
  newdate.setMonth(mm);_x000D_
  newdate.setDate(dd);_x000D_
  return dd == newdate.getDate() && mm == newdate.getMonth() && yyyy == newdate.getFullYear();_x000D_
}_x000D_
console.log(isValidDate('jk'));//false_x000D_
console.log(isValidDate('290215'));//false_x000D_
console.log(isValidDate('290216'));//true_x000D_
console.log(isValidDate('292216'));//false
_x000D_
_x000D_
_x000D_

Transparent background on winforms?

The manner I have used before is to use a wild color (a color no one in their right mind would use) for the BackColor and then set the transparency key to that.

this.BackColor = Color.LimeGreen;
this.TransparencyKey = Color.LimeGreen;

How can I specify the schema to run an sql file against in the Postgresql command line

I'm using something like this and works very well:* :-)

(echo "set schema 'acme';" ; \
  cat ~/git/soluvas-framework/schedule/src/main/resources/org/soluvas/schedule/tables_postgres.sql) \
  | psql -Upostgres -hlocalhost quikdo_app_dev 

Note: Linux/Mac/Bash only, though probably there's a way to do that in Windows/PowerShell too.

Adding an onclick event to a table row

Simple way is generating code as bellow:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<style>_x000D_
  table, td {_x000D_
      border:1px solid black;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<p>Click on each tr element to alert its index position in the table:</p>_x000D_
<table>_x000D_
  <tr onclick="myFunction(this)">_x000D_
    <td>Click to show rowIndex</td>_x000D_
  </tr>_x000D_
  <tr onclick="myFunction(this)">_x000D_
    <td>Click to show rowIndex</td>_x000D_
  </tr>_x000D_
  <tr onclick="myFunction(this)">_x000D_
    <td>Click to show rowIndex</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<script>_x000D_
  function myFunction(x) {_x000D_
      alert("Row index is: " + x.rowIndex);_x000D_
  }_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Resizing a button

Another alternative is that you are allowed to have multiple classes in a tag. Consider:

 <div class="button big">This is a big button</div>
 <div class="button small">This is a small button</div>

And the CSS:

 .button {
     /* all your common button styles */
 }

 .big {
     height: 60px;
     width: 100px;
 }
 .small {
     height: 40px;
     width: 70px;
 }

and so on.

Inverse of matrix in R

You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package

how to set image from url for imageView

if you are making a RecyclerView and using an adapter, what worked for me was:

@Override
public void onBindViewHolder(ADAPTERVIEWHOLDER holder, int position) {
    MODEL model = LIST.get(position);
    holder.TEXTVIEW.setText(service.getTitle());
    holder.TEXTVIEW.setText(service.getDesc());

    Context context = holder.IMAGEVIEW.getContext();
    Picasso.with(context).load(model.getImage()).into(holder.IMAGEVIEW);
}

How do I compile a .c file on my Mac?

Just for the record in modern times,

for 2017 !

1 - Just have updated Xcode on your machine as you normally do

2 - Open terminal and

$ xcode-select --install

it will perform a short install of a minute or two.

3 - Launch Xcode. "New" "Project" ... you have to choose "Command line tool"

Note - confusingly this is under the "macOS" tab.

choose this one

Select "C" language on the next screen...

enter image description here

4- You'll be asked to save the project somewhere on your desktop. The name you give the project here is just the name of the folder that will hold the project. It does not have any importance in the actual software.

5 - You're golden! You can now enjoy c with Mac and Xcode.

you're golden

How to trace the path in a Breadth-First Search?

You should have look at http://en.wikipedia.org/wiki/Breadth-first_search first.


Below is a quick implementation, in which I used a list of list to represent the queue of paths.

# graph is in adjacent list representation
graph = {
        '1': ['2', '3', '4'],
        '2': ['5', '6'],
        '5': ['9', '10'],
        '4': ['7', '8'],
        '7': ['11', '12']
        }

def bfs(graph, start, end):
    # maintain a queue of paths
    queue = []
    # push the first path into the queue
    queue.append([start])
    while queue:
        # get the first path from the queue
        path = queue.pop(0)
        # get the last node from the path
        node = path[-1]
        # path found
        if node == end:
            return path
        # enumerate all adjacent nodes, construct a new path and push it into the queue
        for adjacent in graph.get(node, []):
            new_path = list(path)
            new_path.append(adjacent)
            queue.append(new_path)

print bfs(graph, '1', '11')

Another approach would be maintaining a mapping from each node to its parent, and when inspecting the adjacent node, record its parent. When the search is done, simply backtrace according the parent mapping.

graph = {
        '1': ['2', '3', '4'],
        '2': ['5', '6'],
        '5': ['9', '10'],
        '4': ['7', '8'],
        '7': ['11', '12']
        }

def backtrace(parent, start, end):
    path = [end]
    while path[-1] != start:
        path.append(parent[path[-1]])
    path.reverse()
    return path


def bfs(graph, start, end):
    parent = {}
    queue = []
    queue.append(start)
    while queue:
        node = queue.pop(0)
        if node == end:
            return backtrace(parent, start, end)
        for adjacent in graph.get(node, []):
            if node not in queue :
                parent[adjacent] = node # <<<<< record its parent 
                queue.append(adjacent)

print bfs(graph, '1', '11')

The above codes are based on the assumption that there's no cycles.

How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.

This can be resolved by specifying a primary key on the @new_super table, as follows:

DECLARE @new_super TABLE (
  row_num INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
  super_id   int
);

This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.

asp.net Button OnClick event not firing

I had a similar issue and none of the answers worked for me. Maybe someone finds my solution helpful. In case you do not mind submitting on button click, only attaching to click event setting UseSubmitBehavior="false" may be worth trying.

How to get out of while loop in java with Scanner method "hasNext" as condition?

Modify the while loop as below. Declare s1 as String s1; one time outside the loop. To end the loop, simply use ctrl+z.

  while (sc.hasNext())
  {    
    s1 = sc.next();
    System.out.println(s1);
    System.out.print("Enter your sentence: ");
  }

Passing an array of data as an input parameter to an Oracle procedure

This is one way to do it:

SQL> set serveroutput on
SQL> CREATE OR REPLACE TYPE MyType AS VARRAY(200) OF VARCHAR2(50);
  2  /

Type created

SQL> CREATE OR REPLACE PROCEDURE testing (t_in MyType) IS
  2  BEGIN
  3    FOR i IN 1..t_in.count LOOP
  4      dbms_output.put_line(t_in(i));
  5    END LOOP;
  6  END;
  7  /

Procedure created

SQL> DECLARE
  2    v_t MyType;
  3  BEGIN
  4    v_t := MyType();
  5    v_t.EXTEND(10);
  6    v_t(1) := 'this is a test';
  7    v_t(2) := 'A second test line';
  8    testing(v_t);
  9  END;
 10  /

this is a test
A second test line

To expand on my comment to @dcp's answer, here's how you could implement the solution proposed there if you wanted to use an associative array:

SQL> CREATE OR REPLACE PACKAGE p IS
  2    TYPE p_type IS TABLE OF VARCHAR2(50) INDEX BY BINARY_INTEGER;
  3  
  4    PROCEDURE pp (inp p_type);
  5  END p;
  6  /

Package created
SQL> CREATE OR REPLACE PACKAGE BODY p IS
  2    PROCEDURE pp (inp p_type) IS
  3    BEGIN
  4      FOR i IN 1..inp.count LOOP
  5        dbms_output.put_line(inp(i));
  6      END LOOP;
  7    END pp;
  8  END p;
  9  /

Package body created
SQL> DECLARE
  2    v_t p.p_type;
  3  BEGIN
  4    v_t(1) := 'this is a test of p';
  5    v_t(2) := 'A second test line for p';
  6    p.pp(v_t);
  7  END;
  8  /

this is a test of p
A second test line for p

PL/SQL procedure successfully completed

SQL> 

This trades creating a standalone Oracle TYPE (which cannot be an associative array) with requiring the definition of a package that can be seen by all in order that the TYPE it defines there can be used by all.

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

just add your .jar file in applet tag as an attribute as shown below:

<applet
    code="file.class"
    archive="file.jar"
    height=550 
    width=1100>         
</applet>

List of Java processes

For better output format check this command:

ps -fC java