Programs & Examples On #Resetevent

C# Wait until condition is true

This implementation is totally based on Sinaesthetic's, but adding CancellationToken and keeping the same execution thread and context; that is, delegating the use of Task.Run() up to the caller depending on whether condition needs to be evaluated in the same thread or not.

Also, notice that, if you don't really need to throw a TimeoutException and breaking the loop is enough, you might want to make use of cts.CancelAfter() or new CancellationTokenSource(millisecondsDelay) instead of using timeoutTask with Task.Delay plus Task.WhenAny.

public static class AsyncUtils
{
    /// <summary>
    ///     Blocks while condition is true or task is canceled.
    /// </summary>
    /// <param name="ct">
    ///     Cancellation token.
    /// </param>
    /// <param name="condition">
    ///     The condition that will perpetuate the block.
    /// </param>
    /// <param name="pollDelay">
    ///     The delay at which the condition will be polled, in milliseconds.
    /// </param>
    /// <returns>
    ///     <see cref="Task" />.
    /// </returns>
    public static async Task WaitWhileAsync(CancellationToken ct, Func<bool> condition, int pollDelay = 25)
    {
        try
        {
            while (condition())
            {
                await Task.Delay(pollDelay, ct).ConfigureAwait(true);
            }
        }
        catch (TaskCanceledException)
        {
            // ignore: Task.Delay throws this exception when ct.IsCancellationRequested = true
            // In this case, we only want to stop polling and finish this async Task.
        }
    }

    /// <summary>
    ///     Blocks until condition is true or task is canceled.
    /// </summary>
    /// <param name="ct">
    ///     Cancellation token.
    /// </param>
    /// <param name="condition">
    ///     The condition that will perpetuate the block.
    /// </param>
    /// <param name="pollDelay">
    ///     The delay at which the condition will be polled, in milliseconds.
    /// </param>
    /// <returns>
    ///     <see cref="Task" />.
    /// </returns>
    public static async Task WaitUntilAsync(CancellationToken ct, Func<bool> condition, int pollDelay = 25)
    {
        try
        {
            while (!condition())
            {
                await Task.Delay(pollDelay, ct).ConfigureAwait(true);
            }
        }
        catch (TaskCanceledException)
        {
            // ignore: Task.Delay throws this exception when ct.IsCancellationRequested = true
            // In this case, we only want to stop polling and finish this async Task.
        }
    }

    /// <summary>
    ///     Blocks while condition is true or timeout occurs.
    /// </summary>
    /// <param name="ct">
    ///     The cancellation token.
    /// </param>
    /// <param name="condition">
    ///     The condition that will perpetuate the block.
    /// </param>
    /// <param name="pollDelay">
    ///     The delay at which the condition will be polled, in milliseconds.
    /// </param>
    /// <param name="timeout">
    ///     Timeout in milliseconds.
    /// </param>
    /// <exception cref="TimeoutException">
    ///     Thrown after timeout milliseconds
    /// </exception>
    /// <returns>
    ///     <see cref="Task" />.
    /// </returns>
    public static async Task WaitWhileAsync(CancellationToken ct, Func<bool> condition, int pollDelay, int timeout)
    {
        if (ct.IsCancellationRequested)
        {
            return;
        }

        using (CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(ct))
        {
            Task waitTask     = WaitWhileAsync(cts.Token, condition, pollDelay);
            Task timeoutTask  = Task.Delay(timeout, cts.Token);
            Task finishedTask = await Task.WhenAny(waitTask, timeoutTask).ConfigureAwait(true);

            if (!ct.IsCancellationRequested)
            {
                cts.Cancel();                            // Cancel unfinished task
                await finishedTask.ConfigureAwait(true); // Propagate exceptions
                if (finishedTask == timeoutTask)
                {
                    throw new TimeoutException();
                }
            }
        }
    }

    /// <summary>
    ///     Blocks until condition is true or timeout occurs.
    /// </summary>
    /// <param name="ct">
    ///     Cancellation token
    /// </param>
    /// <param name="condition">
    ///     The condition that will perpetuate the block.
    /// </param>
    /// <param name="pollDelay">
    ///     The delay at which the condition will be polled, in milliseconds.
    /// </param>
    /// <param name="timeout">
    ///     Timeout in milliseconds.
    /// </param>
    /// <exception cref="TimeoutException">
    ///     Thrown after timeout milliseconds
    /// </exception>
    /// <returns>
    ///     <see cref="Task" />.
    /// </returns>
    public static async Task WaitUntilAsync(CancellationToken ct, Func<bool> condition, int pollDelay, int timeout)
    {
        if (ct.IsCancellationRequested)
        {
            return;
        }

        using (CancellationTokenSource cts = CancellationTokenSource.CreateLinkedTokenSource(ct))
        {
            Task waitTask     = WaitUntilAsync(cts.Token, condition, pollDelay);
            Task timeoutTask  = Task.Delay(timeout, cts.Token);
            Task finishedTask = await Task.WhenAny(waitTask, timeoutTask).ConfigureAwait(true);

            if (!ct.IsCancellationRequested)
            {
                cts.Cancel();                            // Cancel unfinished task
                await finishedTask.ConfigureAwait(true); // Propagate exceptions
                if (finishedTask == timeoutTask)
                {
                    throw new TimeoutException();
                }
            }
        }
    }
}

How to resolve this System.IO.FileNotFoundException

I've been mislead by this error more than once. After spending hours googling, updating nuget packages, version checking, then after sitting with a completely updated solution I re-realize a perfectly valid, simpler reason for the error.

If in a threaded enthronement (UI Dispatcher.Invoke for example), System.IO.FileNotFoundException is thrown if the thread manager dll (file) fails to return. So if your main UI thread A, calls the system thread manager dll B, and B calls your thread code C, but C throws for some unrelated reason (such as null Reference as in my case), then C does not return, B does not return, and A only blames B with FileNotFoundException for being lost...

Before going down the dll version path... Check closer to home and verify your thread code is not throwing.

UTF-8 output from PowerShell

Not an expert on encoding, but after reading these...

... it seems fairly clear that the $OutputEncoding variable only affects data piped to native applications.

If sending to a file from withing PowerShell, the encoding can be controlled by the -encoding parameter on the out-file cmdlet e.g.

write-output "hello" | out-file "enctest.txt" -encoding utf8

Nothing else you can do on the PowerShell front then, but the following post may well help you:.

How to block until an event is fired in c#

A very easy kind of event you can wait for is the ManualResetEvent, and even better, the ManualResetEventSlim.

They have a WaitOne() method that does exactly that. You can wait forever, or set a timeout, or a "cancellation token" which is a way for you to decide to stop waiting for the event (if you want to cancel your work, or your app is asked to exit).

You fire them calling Set().

Here is the doc.

Creating a blocking Queue<T> in .NET?

That looks very unsafe (very little synchronization); how about something like:

class SizeQueue<T>
{
    private readonly Queue<T> queue = new Queue<T>();
    private readonly int maxSize;
    public SizeQueue(int maxSize) { this.maxSize = maxSize; }

    public void Enqueue(T item)
    {
        lock (queue)
        {
            while (queue.Count >= maxSize)
            {
                Monitor.Wait(queue);
            }
            queue.Enqueue(item);
            if (queue.Count == 1)
            {
                // wake up any blocked dequeue
                Monitor.PulseAll(queue);
            }
        }
    }
    public T Dequeue()
    {
        lock (queue)
        {
            while (queue.Count == 0)
            {
                Monitor.Wait(queue);
            }
            T item = queue.Dequeue();
            if (queue.Count == maxSize - 1)
            {
                // wake up any blocked enqueue
                Monitor.PulseAll(queue);
            }
            return item;
        }
    }
}

(edit)

In reality, you'd want a way to close the queue so that readers start exiting cleanly - perhaps something like a bool flag - if set, an empty queue just returns (rather than blocking):

bool closing;
public void Close()
{
    lock(queue)
    {
        closing = true;
        Monitor.PulseAll(queue);
    }
}
public bool TryDequeue(out T value)
{
    lock (queue)
    {
        while (queue.Count == 0)
        {
            if (closing)
            {
                value = default(T);
                return false;
            }
            Monitor.Wait(queue);
        }
        value = queue.Dequeue();
        if (queue.Count == maxSize - 1)
        {
            // wake up any blocked enqueue
            Monitor.PulseAll(queue);
        }
        return true;
    }
}

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

Just imagine that the AutoResetEvent executes WaitOne() and Reset() as a single atomic operation.

Git fatal: protocol 'https' is not supported

There is something fishy going on. Probably a github bug that is not consistent (A/B testing?)

I am on windows10, using firefox. I have just copied a checkout URL and got an extra character. But only the first time. A second time it wasn't there. I had to look at my history file to see it!

here is my history:

git clone --recursive https://github.com/amzeratul/halley-template
git clone --recursive http://github.com/amzeratul/halley-template
git clone --recursive github.com/amzeratul/halley-template
git clone --recursive https://github.com/amzeratul/halley-template

the history command doesn't show the extra char. Just like it wasn't rendered when i was copy-pasting it into the terminal. You can see how i tried to remove the 's' and then the entire protocol? I was only triggered to investigate further when the backspace key moved one less character than i was expecting!

I saved my shell history file onto a machine with an hex editor and:

00000000  xx xx xx xx xx xx xx 0a  67 69 74 20 63 6c 6f 6e  |xxxxxxx.git clon|
00000010  65 20 2d 2d 72 65 63 75  72 73 69 76 65 20 c2 96  |e --recursive ..|
00000020  68 74 74 70 73 3a 2f 2f  67 69 74 68 75 62 2e 63  |https://github.c|
00000030  6f 6d 2f 61 6d 7a 65 72  61 74 75 6c 2f 68 61 6c  |om/amzeratul/hal|
00000040  6c 65 79 2d 74 65 6d 70  6c 61 74 65 0a 67 69 74  |ley-template.git|
00000050  20 2d 2d 68 65 6c 70 0a  67 69 74 20 75 70 64 61  | --help.git upda|
00000060  74 65 2d 67 69 74 2d 66  6f 72 2d 77 69 6e 64 6f  |te-git-for-windo|
00000070  77 73 0a 67 69 74 20 63  6c 6f 6e 65 20 2d 2d 72  |ws.git clone --r|
00000080  65 63 75 72 73 69 76 65  20 c2 96 68 74 74 70 73  |ecursive ..https|
00000090  3a 2f 2f 67 69 74 68 75  62 2e 63 6f 6d 2f 61 6d  |://github.com/am|
000000a0  7a 65 72 61 74 75 6c 2f  68 61 6c 6c 65 79 2d 74  |zeratul/halley-t|
000000b0  65 6d 70 6c 61 74 65 0a  63 75 72 6c 20 2d 2d 76  |emplate.curl --v|
000000c0  65 72 73 69 6f 6e 0a 63  64 20 63 6f 64 65 0a 67  |ersion.cd code.g|
000000d0  69 74 20 63 6c 6f 6e 65  20 2d 2d 72 65 63 75 72  |it clone --recur|
000000e0  73 69 76 65 20 c2 96 68  74 74 70 73 3a 2f 2f 67  |sive ..https://g|
000000f0  69 74 68 75 62 2e 63 6f  6d 2f 61 6d 7a 65 72 61  |ithub.com/amzera|
00000100  74 75 6c 2f 68 61 6c 6c  65 79 2d 74 65 6d 70 6c  |tul/halley-templ|
00000110  61 74 65 0a 67 69 74 20  63 6c 6f 6e 65 20 2d 2d  |ate.git clone --|
00000120  72 65 63 75 72 73 69 76  65 20 c2 96 68 74 74 70  |recursive ..http|
00000130  3a 2f 2f 67 69 74 68 75  62 2e 63 6f 6d 2f 61 6d  |://github.com/am|
00000140  7a 65 72 61 74 75 6c 2f  68 61 6c 6c 65 79 2d 74  |zeratul/halley-t|
00000150  65 6d 70 6c 61 74 65 0a  67 69 74 20 63 6c 6f 6e  |emplate.git clon|
00000160  65 20 2d 2d 72 65 63 75  72 73 69 76 65 20 67 69  |e --recursive gi|
00000170  74 68 75 62 2e 63 6f 6d  2f 61 6d 7a 65 72 61 74  |thub.com/amzerat|
00000180  75 6c 2f 68 61 6c 6c 65  79 2d 74 65 6d 70 6c 61  |ul/halley-templa|
00000190  74 65 0a 67 69 74 20 63  6c 6f 6e 65 20 2d 2d 72  |te.git clone --r|
000001a0  65 63 75 72 73 69 76 65  20 68 74 74 70 73 3a 2f  |ecursive https:/|
000001b0  2f 67 69 74 68 75 62 2e  63 6f 6d 2f 61 6d 7a 65  |/github.com/amze|
000001c0  72 61 74 75 6c 2f 68 61  6c 6c 65 79 2d 74 65 6d  |ratul/halley-tem|
000001d0  70 6c 61 74 65 0a                                 |plate.|
000001d6

There i a c2 96 char inserted before the url. No idea what that is. Is it not extended ASCII (where it would be –) and it was hidden from almost every place i pasted while it was on the clipboard. The closest i've found with this hex value would be https://www.fileformat.info/info/unicode/char/c298/index.htm but i didn't see the utf prefix anywhere (again, might have been lost)

This all might be misleading as I lost the page/clipboard and am working exclusively from the saved shell history file, which might very well be missing data from the original bug/malicious injection.

How to use: while not in

The expression 'AND' and 'OR' and 'NOT' always evaluates to 'NOT', so you are effectively doing

while 'NOT' not in some_list:
    print 'No boolean operator'

You can either check separately for all of them

while ('AND' not in some_list and 
       'OR' not in some_list and 
       'NOT' not in some_list):
    # whatever

or use sets

s = set(["AND", "OR", "NOT"])
while not s.intersection(some_list):
    # whatever

Docker error : no space left on device

If you're using the boot2docker image via Docker Toolkit, then the problem stems from the fact that the boot2docker virtual machine has run out of space.

When you do a docker import or add a new image, the image gets copied into the /mnt/sda1 which might have become full.

One way to check what space you have available in the image, is to ssh into the vm and run df -h and check the remaining space in /mnt/sda1

The ssh command is docker-machine ssh default

Once you are sure that it is indeed a space issue, you can either clean up according to the instructions in some of the answers on this question, or you may choose to resize the boot2docker image itself, by increasing the space on /mnt/sda1

You can follow the instructions here to do the resizing of the image https://gist.github.com/joost/a7cfa7b741d9d39c1307

Using "Object.create" instead of "new"

There is really no advantage in using Object.create(...) over new object.

Those advocating this method generally state rather ambiguous advantages: "scalability", or "more natural to JavaScript" etc.

However, I have yet to see a concrete example that shows that Object.create has any advantages over using new. On the contrary there are known problems with it. Sam Elsamman describes what happens when there are nested objects and Object.create(...) is used:

var Animal = {
    traits: {},
}
var lion = Object.create(Animal);
lion.traits.legs = 4;
var bird = Object.create(Animal);
bird.traits.legs = 2;
alert(lion.traits.legs) // shows 2!!!

This occurs because Object.create(...) advocates a practice where data is used to create new objects; here the Animal datum becomes part of the prototype of lion and bird, and causes problems as it is shared. When using new the prototypal inheritance is explicit:

function Animal() {
    this.traits = {};
}

function Lion() { }
Lion.prototype = new Animal();
function Bird() { }
Bird.prototype = new Animal();

var lion = new Lion();
lion.traits.legs = 4;
var bird = new Bird();
bird.traits.legs = 2;
alert(lion.traits.legs) // now shows 4

Regarding, the optional property attributes that are passed into Object.create(...), these can be added using Object.defineProperties(...).

Remove part of a string

Here's the strsplit solution if s is a vector:

> s <- c("TGAS_1121", "MGAS_1432")
> s1 <- sapply(strsplit(s, split='_', fixed=TRUE), function(x) (x[2]))
> s1
[1] "1121" "1432"

How to compare two List<String> to each other?

You can check in all the below ways for a List

List<string> FilteredList = new List<string>();
//Comparing the two lists and gettings common elements.
FilteredList = a1.Intersect(a2, StringComparer.OrdinalIgnoreCase);

How can you get the active users connected to a postgreSQL database via SQL?

(question) Don't you get that info in

select * from pg_user;

or using the view pg_stat_activity:

select * from pg_stat_activity;

Added:

the view says:

One row per server process, showing database OID, database name, process ID, user OID, user name, current query, query's waiting status, time at which the current query began execution, time at which the process was started, and client's address and port number. The columns that report data on the current query are available unless the parameter stats_command_string has been turned off. Furthermore, these columns are only visible if the user examining the view is a superuser or the same as the user owning the process being reported on.

can't you filter and get that information? that will be the current users on the Database, you can use began execution time to get all queries from last 5 minutes for example...

something like that.

Is Python interpreted, or compiled, or both?

The python code you write is compiled into python bytecode, which creates file with extension .pyc. If compiles, again question is, why not compiled language.

Note that this isn't compilation in the traditional sense of the word. Typically, we’d say that compilation is taking a high-level language and converting it to machine code. But it is a compilation of sorts. Compiled in to intermediate code not into machine code (Hope you got it Now).

Back to the execution process, your bytecode, present in pyc file, created in compilation step, is then executed by appropriate virtual machines, in our case, the CPython VM The time-stamp (called as magic number) is used to validate whether .py file is changed or not, depending on that new pyc file is created. If pyc is of current code then it simply skips compilation step.

How to combine two vectors into a data frame

You can use expand.grid( ) function.

x <-c(1,2,3)
y <-c(100,200,300)
expand.grid(cond=x,rating=y)

Open another application from your own (intent)

Open application if it is exist, or open Play Store application for install it:

private void open() {
    openApplication(getActivity(), "com.app.package.here");
}

public void openApplication(Context context, String packageN) {
    Intent i = context.getPackageManager().getLaunchIntentForPackage(packageN);
    if (i != null) {
        i.addCategory(Intent.CATEGORY_LAUNCHER);
        context.startActivity(i);
    } else {
        try {
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + packageN)));
        }
        catch (android.content.ActivityNotFoundException anfe) {
            context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://play.google.com/store/apps/details?id=" + packageN)));
        }
    }
}

How do I do a not equal in Django queryset filtering?

Pending design decision. Meanwhile, use exclude()

The Django issue tracker has the remarkable entry #5763, titled "Queryset doesn't have a "not equal" filter operator". It is remarkable because (as of April 2016) it was "opened 9 years ago" (in the Django stone age), "closed 4 years ago", and "last changed 5 months ago".

Read through the discussion, it is interesting. Basically, some people argue __ne should be added while others say exclude() is clearer and hence __ne should not be added.

(I agree with the former, because the latter argument is roughly equivalent to saying Python should not have != because it has == and not already...)

ldap query for group members

Active Directory does not store the group membership on user objects. It only stores the Member list on the group. The tools show the group membership on user objects by doing queries for it.

How about:

(&(objectClass=group)(member=cn=my,ou=full,dc=domain))

(You forgot the (& ) bit in your example in the question as well).

How can I get the Google cache age of any URL or web page?

you can Use CachedPages website

Cached pages are usually saved and stored by large companies with powerful web servers. Since such servers are usually very fast, a cached page can often be accessed faster than the live page itself:

  • Google usually keeps a recent copy of the page (1 to 15 days old).
  • Coral also keeps a recent copy, although it's usually not as recent as Google.
  • Through Archive.org, you can access several copies of a web page saved throughout the years.

Disabling buttons on react native

You can build an CustButton with TouchableWithoutFeedback, and set the effect and logic you want with onPressIn, onPressout or other props.

Moment.js with ReactJS (ES6)

in my case i want getting timeZone of several country ,first install moment js

npm install moment --save  

then install moment-timezone.js

npm install moment-timezone --save

then i import themn in my component like this

import moment from 'moment';
import timezone from 'moment-timezone'

then because iwant getting hour and minutes and second sepratly i do like this

<Clock minutes={moment().tz('Australia/Sydney').minute()} hour={moment().tz('Australia/Sydney').hours()} second={moment().tz('Australia/Sydney').second()}/>

Save file Javascript with file name

Replace your "Save" button with an anchor link and set the new download attribute dynamically. Works in Chrome and Firefox:

var d = "ha";
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");

Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/

Here a compatibility table for downloadattribute: http://caniuse.com/download

NumPy first and last element from array

>>> test = [1,23,4,6,7,8]
>>> from itertools import izip_longest
>>> for e in izip_longest(test, reversed(test)):
    print e


(1, 8)
(23, 7)
(4, 6)
(6, 4)
(7, 23)
(8, 1)

Another option

>>> test = [1,23,4,6,7,8]
>>> start, end = iter(test), reversed(test)
>>> try:
    while True:
        print map(next, [start, end])
except StopIteration:
    pass

[1, 8]
[23, 7]
[4, 6]
[6, 4]
[7, 23]
[8, 1]

How do I change the font-size of an <option> element within <select>?

.service-small option {
    font-size: 14px;
    padding: 5px;
    background: #5c5c5c;
}

I think it because you used .styled-select in start of the class code.

VB.net Need Text Box to Only Accept Numbers

Public Function Isnumber(ByVal KCode As String) As Boolean
    If Not Isnumeric(KCode) And KCode <> ChrW(Keys.Back) And KCode <> ChrW(Keys.Enter) And KCode <> "."c Then

        MsgBox("Please Enter Numbers only", MsgBoxStyle.OkOnly)
    End If
End Function

Private Sub txtBalance_KeyPress(ByVal sender As System.Object, ByVal e As 
System.Windows.Forms.KeyPressEventArgs) Handles txtBalance.KeyPress

    If Not Isnumber(e.KeyChar) Then
        e.KeyChar = ""
    End If

End Sub

How to see query history in SQL Server Management Studio

[Since this question will likely be closed as a duplicate.]

If SQL Server hasn't been restarted (and the plan hasn't been evicted, etc.), you may be able to find the query in the plan cache.

SELECT t.[text]
FROM sys.dm_exec_cached_plans AS p
CROSS APPLY sys.dm_exec_sql_text(p.plan_handle) AS t
WHERE t.[text] LIKE N'%something unique about your query%';

If you lost the file because Management Studio crashed, you might be able to find recovery files here:

C:\Users\<you>\Documents\SQL Server Management Studio\Backup Files\

Otherwise you'll need to use something else going forward to help you save your query history, like SSMS Tools Pack as mentioned in Ed Harper's answer - though it isn't free in SQL Server 2012+. Or you can set up some lightweight tracing filtered on your login or host name (but please use a server-side trace, not Profiler, for this).


As @Nenad-Zivkovic commented, it might be helpful to join on sys.dm_exec_query_stats and order by last_execution_time:

SELECT t.[text], s.last_execution_time
FROM sys.dm_exec_cached_plans AS p
INNER JOIN sys.dm_exec_query_stats AS s
   ON p.plan_handle = s.plan_handle
CROSS APPLY sys.dm_exec_sql_text(p.plan_handle) AS t
WHERE t.[text] LIKE N'%something unique about your query%'
ORDER BY s.last_execution_time DESC;

Exit a Script On Error

Are you looking for exit?

This is the best bash guide around. http://tldp.org/LDP/abs/html/

In context:

if jarsigner -verbose -keystore $keyst -keystore $pass $jar_file $kalias
then
    echo $jar_file signed sucessfully
else
    echo ERROR: Failed to sign $jar_file. Please recheck the variables 1>&2
    exit 1 # terminate and indicate error
fi

...

How to automatically close cmd window after batch file execution?

Just try /s as listed below.

As the last line in the batch file type:

exit /s

The above command will close the Windows CMD window.

/s - stands for silent as in (it would wait for an input from the keyboard).

How to check for valid email address?

I found an excellent (and tested) way to check for valid email address. I paste my code here:

# here i import the module that implements regular expressions
import re
# here is my function to check for valid email address
def test_email(your_pattern):
pattern = re.compile(your_pattern)
# here is an example list of email to check it at the end
emails = ["[email protected]", "[email protected]", "wha.t.`1an?ug{}[email protected]"]
for email in emails:
    if not re.match(pattern, email):
        print "You failed to match %s" % (email)
    elif not your_pattern:
        print "Forgot to enter a pattern!"
    else:
        print "Pass"
# my pattern that is passed as argument in my function is here!
pattern = r"\"?([-a-zA-Z0-9.`?{}]+@\w+\.\w+)\"?"   
# here i test my function passing my pattern
test_email(pattern)

How to add an object to an ArrayList in Java

Contacts.add(objt.Data(name, address, contact));

This is not a perfect way to call a constructor. The constructor is called at the time of object creation automatically. If there is no constructor java class creates its own constructor.

The correct way is:

// object creation. 
Data object1 = new Data(name, address, contact);      

// adding Data object to ArrayList object Contacts.
Contacts.add(object1);                              

Recreate the default website in IIS

Other answers are basically right, thanks to them I was able to restore my default web site, they're just missing some more or less important details.

This was the complete process to restore the Default Web Site in my case (IIS 7 on Windows 7 64bit):

  1. open IIS Manager
  2. right click Sites node under your machine in the Connections tree on the left side and click Add Website
  3. enter "Default Web Site" as a Site name
  4. set Application pool back to DefaultAppPool!
  5. set Physical path to %SystemDrive%\inetpub\wwwroot
  6. leave Binding and everything else as is

Possible issues:

  1. If the newly created web site cannot be started with the following message:

    Internet Information Services (IIS) Manager - The process cannot access the file because it is being used by another process. (Exception from HRESULT: 0x80070020)

    ...it's possible that port 80 is already assigned to another application (Skype in my case :). You can change the binding port to e.g. 8080 by right clicking Default Web Site and selecting Edit Bindings... and Edit.... See Error 0x80070020 when you try to start a Web site in IIS 7.0 for details. Or you can just close the application sitting on the port 80, of course.

  2. Some applications require Default Web Site to have the ID 1. In my case, it got ID 1 after recreation automatically. If it's not your case, see Re-create “default Website” in IIS after accidentally deleting. It's different for IIS 6 and 7.


Note: I had to recreate the Default Web Site, because I wasn't able to even open a project configured to run under IIS in Visual Studio. I had a solution with a couple of projects inside. One of the projects failed to load with the following error message:

The Web Application Project is configured to use IIS. The Web server 'http://localhost:8080/' could not be found.

After I have recreated the Default Web Site in IIS Manager, I was able to reload and open that specific project.

How to input matrix (2D list) in Python?

The problem is on the initialization step.

for i in range (0,m):
  matrix[i] = columns

This code actually makes every row of your matrix refer to the same columns object. If any item in any column changes - every other column will change:

>>> for i in range (0,m):
...     matrix[i] = columns
... 
>>> matrix
[[0, 0, 0], [0, 0, 0]]
>>> matrix[1][1] = 2
>>> matrix
[[0, 2, 0], [0, 2, 0]]

You can initialize your matrix in a nested loop, like this:

matrix = []
for i in range(0,m):
    matrix.append([])
    for j in range(0,n):
        matrix[i].append(0)

or, in a one-liner by using list comprehension:

matrix = [[0 for j in range(n)] for i in range(m)]

or:

matrix = [x[:] for x in [[0]*n]*m]

See also:

Hope that helps.

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

I had the exact same problem and solved it running the folowing command from the command line as an admin :

1) first stop the service with the following

net stop http /y

2) then disable the startup (optional)

sc config http start= disabled

Postgres: INSERT if does not exist already

If you say that many of your rows are identical you will end checking many times. You can send them and the database will determine if insert it or not with the ON CONFLICT clause as follows

  INSERT INTO Hundred (name,name_slug,status) VALUES ("sql_string += hundred  
  +",'" + hundred_slug + "', " + status + ") ON CONFLICT ON CONSTRAINT
  hundred_pkey DO NOTHING;" cursor.execute(sql_string);

Found a swap file by the name

Accepted answer fails to mention how to delete the .swp file.

Hit "D" when the prompt comes up and it will remove it.

In my case, after I hit D it left the latest saved version intact and deleted the .swp which got created because I exited VIM incorrectly

What is the Oracle equivalent of SQL Server's IsNull() function?

Instead of ISNULL(), use NVL().

T-SQL:

SELECT ISNULL(SomeNullableField, 'If null, this value') FROM SomeTable

PL/SQL:

SELECT NVL(SomeNullableField, 'If null, this value') FROM SomeTable

How can I decrease the size of Ratingbar?

Using Widget.AppCompat.RatingBar, you have 2 styles to use; Indicator and Small for large and small sizes respectively. See example below.

<RatingBar
    android:id="@+id/rating_star_value"
    style="@style/Widget.AppCompat.RatingBar.Small"
    ... />

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

In XML, xmlns declares a Namespace. In fact, when you do:

<LinearLayout android:id>
</LinearLayout>

Instead of calling android:id, the xml will use http://schemas.android.com/apk/res/android:id to be unique. Generally this page doesn't exist (it's a URI, not a URL), but sometimes it is a URL that explains the used namespace.

The namespace has pretty much the same uses as the package name in a Java application.

Here is an explanation.

Uniform Resource Identifier (URI)

A Uniform Resource Identifier (URI) is a string of characters which identifies an Internet Resource.

The most common URI is the Uniform Resource Locator (URL) which identifies an Internet domain address. Another, not so common type of URI is the Universal Resource Name (URN).

In our examples we will only use URLs.

What is the difference between active and passive FTP?

Active and passive are the two modes that FTP can run in.

For background, FTP actually uses two channels between client and server, the command and data channels, which are actually separate TCP connections.

The command channel is for commands and responses while the data channel is for actually transferring files.

This separation of command information and data into separate channels a nifty way of being able to send commands to the server without having to wait for the current data transfer to finish. As per the RFC, this is only mandated for a subset of commands, such as quitting, aborting the current transfer, and getting the status.


In active mode, the client establishes the command channel but the server is responsible for establishing the data channel. This can actually be a problem if, for example, the client machine is protected by firewalls and will not allow unauthorised session requests from external parties.

In passive mode, the client establishes both channels. We already know it establishes the command channel in active mode and it does the same here.

However, it then requests the server (on the command channel) to start listening on a port (at the servers discretion) rather than trying to establish a connection back to the client.

As part of this, the server also returns to the client the port number it has selected to listen on, so that the client knows how to connect to it.

Once the client knows that, it can then successfully create the data channel and continue.

More details are available in the RFC: https://www.ietf.org/rfc/rfc959.txt

How do I find the authoritative name-server for a domain name?

We've built a dns lookup tool that gives you the domain's authoritative nameservers and its common dns records in one request.

Example: https://www.misk.com/tools/#dns/stackoverflow.com

Our tool finds the authoritative nameservers by performing a realtime (uncached) dns lookup at the root nameservers and then following the nameserver referrals until we reach the authoritative nameservers. This is the same logic that dns resolvers use to obtain authoritative answers. A random authoritative nameserver is selected (and identified) on each query allowing you to find conflicting dns records by performing multiple requests.

You can also view the nameserver delegation path by clicking on "Authoritative Nameservers" at the bottom of the dns lookup results from the example above.

Example: https://www.misk.com/tools/#dns/[email protected]

How to remove decimal part from a number in C#

Because the numbers after point is only zero, the best solution is to use the Math.Round(MyNumber)

Sorting Python list based on the length of the string

I can do it using below two methods, using function

def lensort(x):
    list1 = []
    for i in x:
        list1.append([len(i),i])
    return sorted(list1)

lista = ['a', 'bb', 'ccc', 'dddd']
a=lensort(lista)
print([l[1] for l in a])

In one Liner using Lambda, as below, a already answered above.

 lista = ['a', 'bb', 'ccc', 'dddd']
 lista.sort(key = lambda x:len(x))
 print(lista)

curl.h no such file or directory

If after the installation curl-dev luarocks does not see the headers:

find /usr -name 'curl.h'
Example: /usr/include/x86_64-linux-gnu/curl/curl.h

luarocks install lua-cURL CURL_INCDIR=/usr/include/x86_64-linux-gnu/

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

similar to answers above but this has worked faithfully for me... in a service add:

    //sometimes you need to refresh scope, use this to prevent conflict
    this.applyAsNeeded = function (scope) {
        if (!scope.$$phase) {
            scope.$apply();
        }
    };

Setting up FTP on Amazon Cloud Server

I followed clone45's answer all the way to the end. A great article! Since I needed the FTP access to install plug-ins to one of my wordpress sites, I changed the home directory to /var/www/mysitename. Then I continued to add my ftp user to the apache(or www) group like this:

sudo usermod -a -G apache myftpuser

After this I still saw this error on WP's plugin installation page: "Unable to locate WordPress Content directory (wp-content)". Searched and found this solution on a wp.org Q&A session: https://wordpress.org/support/topic/unable-to-locate-wordpress-content-directory-wp-content and added the following to the end of wp-config.php:

if(is_admin()) {
    add_filter('filesystem_method', create_function('$a', 'return "direct";' ));
    define( 'FS_CHMOD_DIR', 0751 );
}

After this my WP plugin was installed successfully.

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Take a look at DATEDIFF, this should be what you're looking for. It takes the two dates you're comparing, and the date unit you want the difference in (days, months, seconds...)

drop down list value in asp.net

You can try this

your_ddl_id.Items.Insert(0,new ListItem("Select","");

Is there such a thing as min-font-size and max-font-size?

This is actually being proposed in CSS4

Working draft at the W3C

Quote:

These two properties allow a website or user to require an element’s font size to be clamped within the range supplied with these two properties. If the computed value font-size is outside the bounds created by font-min-size and font-max-size, the use value of font-size is clamped to the values specified in these two properties.

This would actually work as following:

.element {
    font-min-size: 10px;
    font-max-size: 18px;
    font-size: 5vw; // viewport-relative units are responsive.
}

This would literally mean, the font size will be 5% of the viewport's width, but never smaller than 10 pixels, and never larger than 18 pixels.

Unfortunately, this feature isn't implemented anywhere yet, (not even on caniuse.com).

How to return PDF to browser in MVC?

You must specify :

Response.AppendHeader("content-disposition", "inline; filename=file.pdf");
return new FileStreamResult(stream, "application/pdf")

For the file to be opened directly in the browser instead of being downloaded

Press enter in textbox to and execute button command

Since everybody covered the KeyDown answers, how about using the IsDefault on the button?

You can read this tip for a quick howto and what it does: http://www.codeproject.com/Tips/665886/Button-Tip-IsDefault-IsCancel-and-other-usability

Here's an example from the article linked:

<Button IsDefault = "true" 
        Click     = "SaveClicked"
        Content   = "Save"  ... />
'''

Search for all occurrences of a string in a mysql database

Scott gives a good example of how to do it, but the question is why would you want to? If you need to do a find-and-replace on a specific string, you could also try doing a mysqldump of your database, do a find-and-replace in an editor, then re-load the database.

Maybe if you gave some background on what you are trying to achieve, others might be able to provide better answers.

Can regular expressions be used to match nested patterns?

as zsolt mentioned, some regex engines support recursion -- of course, these are typically the ones that use a backtracking algorithm so it won't be particularly efficient. example: /(?>[^{}]*){(?>[^{}]*)(?R)*(?>[^{}]*)}/sm

How to call a vue.js function on page load

You can call this function in beforeMount section of a Vue component: like following:

 ....
 methods:{
     getUnits: function() {...}
 },
 beforeMount(){
    this.getUnits()
 },
 ......

Working fiddle: https://jsfiddle.net/q83bnLrx/1/

There are different lifecycle hooks Vue provide:

I have listed few are :

  1. beforeCreate: Called synchronously after the instance has just been initialized, before data observation and event/watcher setup.
  2. created: Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the $el property will not be available yet.
  3. beforeMount: Called right before the mounting begins: the render function is about to be called for the first time.
  4. mounted: Called after the instance has just been mounted where el is replaced by the newly created vm.$el.
  5. beforeUpdate: Called when the data changes, before the virtual DOM is re-rendered and patched.
  6. updated: Called after a data change causes the virtual DOM to be re-rendered and patched.

You can have a look at complete list here.

You can choose which hook is most suitable to you and hook it to call you function like the sample code provided above.

How to overwrite files with Copy-Item in PowerShell

Robocopy is designed for reliable copying with many copy options, file selection restart, etc.

/xf to excludes files and /e for subdirectories:

robocopy $copyAdmin $AdminPath /e /xf "web.config" "Deploy"

How to send an HTTP request with a header parameter?

If it says the API key is listed as a header, more than likely you need to set it in the headers option of your http request. Normally something like this :

headers: {'Authorization': '[your API key]'}

Here is an example from another Question

$http({method: 'GET', url: '[the-target-url]', headers: {
  'Authorization': '[your-api-key]'}
});

Edit : Just saw you wanted to store the response in a variable. In this case I would probably just use AJAX. Something like this :

$.ajax({ 
   type : "GET", 
   url : "[the-target-url]", 
   beforeSend: function(xhr){xhr.setRequestHeader('Authorization', '[your-api-key]');},
   success : function(result) { 
       //set your variable to the result 
   }, 
   error : function(result) { 
     //handle the error 
   } 
 }); 

I got this from this question and I'm at work so I can't test it at the moment but looks solid

Edit 2: Pretty sure you should be able to use this line :

headers: {'Authorization': '[your API key]'},

instead of the beforeSend line in the first edit. This may be simpler for you

jQuery's .on() method combined with the submit event

You need to delegate event to the document level

$(document).on('submit','form.remember',function(){
   // code
});

$('form.remember').on('submit' work same as $('form.remember').submit( but when you use $(document).on('submit','form.remember' then it will also work for the DOM added later.

How to initialize an array of custom objects

Here is a concise way to initialize an array of custom objects in PowerShell.

> $body = @( @{ Prop1="1"; Prop2="2"; Prop3="3" }, @{ Prop1="1"; Prop2="2"; Prop3="3" } )
> $body

Name                           Value
----                           -----
Prop2                          2
Prop1                          1
Prop3                          3
Prop2                          2
Prop1                          1
Prop3                          3  

Back button and refreshing previous activity

The think best way to to it is using

Intent i = new Intent(this.myActivity, SecondActivity.class); 
startActivityForResult(i, 1);

How to exit an Android app programmatically?

If you use both finish and exit your app will close complitely

finish();

System.exit(0);

How do I view cookies in Internet Explorer 11 using Developer Tools

How about typing document.cookie into the console? It just shows the values, but it's something.

enter image description here

Directory index forbidden by Options directive

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

alternative to "!is.null()" in R

The shiny package provides the convenient functions validate() and need() for checking that variables are both available and valid. need() evaluates an expression. If the expression is not valid, then an error message is returned. If the expression is valid, NULL is returned. One can use this to check if a variable is valid. See ?need for more information.

I suggest defining a function like this:

is.valid <- function(x) {
  require(shiny)
  is.null(need(x, message = FALSE))  
}

This function is.valid() will return FALSE if x is FALSE, NULL, NA, NaN, an empty string "", an empty atomic vector, a vector containing only missing values, a logical vector containing only FALSE, or an object of class try-error. In all other cases, it returns TRUE.

That means, need() (and is.valid()) covers a really broad range of failure cases. Instead of writing:

if (!is.null(x) && !is.na(x) && !is.nan(x)) {
  ...
}

one can write simply:

if (is.valid(x)) {
  ...
}

With the check for class try-error, it can even be used in conjunction with a try() block to silently catch errors: (see https://csgillespie.github.io/efficientR/programming.html#communicating-with-the-user)

bad = try(1 + "1", silent = TRUE)
if (is.valid(bad)) {
  ...
}

Nesting optgroups in a dropdownlist/select

I needed clean and lightweight solution (so no jQuery and alike), which will look exactly like plain HTML, would also continue working when only plain HTML is preset (so javascript will only enhance it), and which will allow searching by starting letters (including national UTF-8 letters) if possible where it does not add extra weight. It also must work fast on very slow browsers (think rPi - so preferably no javascript executing after page load).

In firefox it uses CSS identing and thus allow searching by letters, and in other browsers it will use &nbsp; prepending (but there it does not support quick search by letters). Anyway, I'm quite happy with results.

You can try it in action here

It goes like this:

CSS:

.i0 { }
.i1 { margin-left: 1em; }
.i2 { margin-left: 2em; }
.i3 { margin-left: 3em; }
.i4 { margin-left: 4em; }
.i5 { margin-left: 5em; }

HTML (class "i1", "i2" etc denote identation level):

<form action="/filter/" method="get">
<select name="gdje" id="gdje">
<option value=1 class="i0">Svugdje</option>
<option value=177 class="i1">Bosna i Hercegovina</option>
<option value=190 class="i2">Babin Do</option>  
<option value=258 class="i2">Banja Luka</option>
<option value=181 class="i2">Tuzla</option>
<option value=307 class="i1">Crna Gora</option>
<option value=308 class="i2">Podgorica</option>
<option value=2 SELECTED class="i1">Hrvatska</option>
<option value=5 class="i2">Bjelovarsko-bilogorska županija</option>
<option value=147 class="i3">Bjelovar</option>
<option value=79 class="i3">Daruvar</option>  
<option value=94 class="i3">Garešnica</option>
<option value=329 class="i3">Grubišno Polje</option>
<option value=368 class="i3">Cazma</option>
<option value=6 class="i2">Brodsko-posavska županija</option>
<option value=342 class="i3">Gornji Bogicevci</option>
<option value=158 class="i3">Klakar</option>
<option value=140 class="i3">Nova Gradiška</option>
</select>
</form>

<script>
<!--
        window.onload = loadFilter;
// -->   
</script>

JavaScript:

function loadFilter() {
  'use strict';
  // indents all options depending on "i" CSS class
  function add_nbsp() {
    var opt = document.getElementsByTagName("option");
    for (var i = 0; i < opt.length; i++) {
      if (opt[i].className[0] === 'i') {
      opt[i].innerHTML = Array(3*opt[i].className[1]+1).join("&nbsp;") + opt[i].innerHTML;      // this means "&nbsp;" x (3*$indent)
      }
    }
  }
  // detects browser
  navigator.sayswho= (function() {
    var ua= navigator.userAgent, tem,
    M= ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*([\d\.]+)/i) || [];
    if(/trident/i.test(M[1])){
        tem=  /\brv[ :]+(\d+(\.\d+)?)/g.exec(ua) || [];
        return 'IE '+(tem[1] || '');
    }
    M= M[2]? [M[1], M[2]]:[navigator.appName, navigator.appVersion, '-?'];
    if((tem= ua.match(/version\/([\.\d]+)/i))!= null) M[2]= tem[1];
    return M.join(' ');
  })();
  // quick detection if browser is firefox
  function isFirefox() {
    var ua= navigator.userAgent,
    M= ua.match(/firefox\//i);  
    return M;
  }
  // indented select options support for non-firefox browsers
  if (!isFirefox()) {
    add_nbsp();
  }
}  

Server Error in '/' Application. ASP.NET

Looks like you have <authentication mode="Windows" /> in your web.config file but your hosting provider won't let you use that. Just remove that line.

How to select ALL children (in any level) from a parent in jQuery?

Use jQuery.find() to find children more than one level deep.

The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

$('#google_translate_element').find('*').unbind('click');

You need the '*' in find():

Unlike in the rest of the tree traversal methods, the selector expression is required in a call to .find(). If we need to retrieve all of the descendant elements, we can pass in the universal selector '*' to accomplish this.

How does one generate a random number in Apple's Swift language?

Details

xCode 9.1, Swift 4

Math oriented solution (1)

import Foundation

class Random {

    subscript<T>(_ min: T, _ max: T) -> T where T : BinaryInteger {
        get {
            return rand(min-1, max+1)
        }
    }
}

let rand = Random()

func rand<T>(_ min: T, _ max: T) -> T where T : BinaryInteger {
    let _min = min + 1
    let difference = max - _min
    return T(arc4random_uniform(UInt32(difference))) + _min
}

Usage of solution (1)

let x = rand(-5, 5)       // x = [-4, -3, -2, -1, 0, 1, 2, 3, 4]
let x = rand[0, 10]       // x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Programmers oriented solution (2)

Do not forget to add Math oriented solution (1) code here

import Foundation

extension CountableRange where Bound : BinaryInteger {

    var random: Bound {
        return rand(lowerBound-1, upperBound)
    }
}

extension CountableClosedRange where Bound : BinaryInteger {

    var random: Bound {
        return rand[lowerBound, upperBound]
    }
}

Usage of solution (2)

let x = (-8..<2).random           // x = [-8, -7, -6, -5, -4, -3, -2, -1, 0, 1]
let x = (0..<10).random           // x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
let x = (-10 ... -2).random       // x = [-10, -9, -8, -7, -6, -5, -4, -3, -2]

Full Sample

Do not forget to add solution (1) and solution (2) codes here

private func generateRandNums(closure:()->(Int)) {

    var allNums = Set<Int>()
    for _ in 0..<100 {
        allNums.insert(closure())
    }
    print(allNums.sorted{ $0 < $1 })
}

generateRandNums {
    (-8..<2).random
}

generateRandNums {
    (0..<10).random
}

generateRandNums {
    (-10 ... -2).random
}

generateRandNums {
    rand(-5, 5)
}
generateRandNums {
    rand[0, 10]
}

Sample result

enter image description here

Time stamp in the C programming language

If you want to find elapsed time, this method will work as long as you don't reboot the computer between the start and end.

In Windows, use GetTickCount(). Here's how:

DWORD dwStart = GetTickCount();
...
... process you want to measure elapsed time for
...
DWORD dwElapsed = GetTickCount() - dwStart;

dwElapsed is now the number of elapsed milliseconds.

In Linux, use clock() and CLOCKS_PER_SEC to do about the same thing.

If you need timestamps that last through reboots or across PCs (which would need quite good syncronization indeed), then use the other methods (gettimeofday()).

Also, in Windows at least you can get much better than standard time resolution. Usually, if you called GetTickCount() in a tight loop, you'd see it jumping by 10-50 each time it changed. That's because of the time quantum used by the Windows thread scheduler. This is more or less the amount of time it gives each thread to run before switching to something else. If you do a:

timeBeginPeriod(1);

at the beginning of your program or process and a:

timeEndPeriod(1);

at the end, then the quantum will change to 1 ms, and you will get much better time resolution on the GetTickCount() call. However, this does make a subtle change to how your entire computer runs processes, so keep that in mind. However, Windows Media Player and many other things do this routinely anyway, so I don't worry too much about it.

I'm sure there's probably some way to do the same in Linux (probably with much better control, or maybe with sub-millisecond quantums) but I haven't needed to do that yet in Linux.

Easy way to get a test file into JUnit

If you need to actually get a File object, you could do the following:

URL url = this.getClass().getResource("/test.wsdl");
File testWsdl = new File(url.getFile());

Which has the benefit of working cross platform, as described in this blog post.

Is there a way to only install the mysql client (Linux)?

at a guess:

sudo apt-get install mysql-client

The import android.support cannot be resolved

Another way to solve the issue:

If you are using the support library, you need to add the appcompat lib to the project. This link shows how to add the support lib to your project.

Assuming you have added the support lib earlier but you are getting the mentioned issue, you can follow the steps below to fix that.

  1. Right click on the project and navigate to Build Path > Configure Build Path.

  2. On the left side of the window, select Android. You will see something like this:

enter image description here

  1. You can notice that no library is referenced at the moment. Now click on the Add button shown at the bottom-right side. You will see a pop up window as shown below.

enter image description here

  1. Select the appcompat lib and press OK. (Note: The lib will be shown if you have added them as mentioned earlier). Now you will see the following window:

enter image description here

  1. Press OK. That's it. The lib is now added to your project (notice the red mark) and the errors relating inclusion of support lib must be gone.

Python Create unix timestamp five minutes in the future

Now in Python >= 3.3 you can just call the timestamp() method to get the timestamp as a float.

import datetime
current_time = datetime.datetime.now(datetime.timezone.utc)
unix_timestamp = current_time.timestamp() # works if Python >= 3.3

unix_timestamp_plus_5_min = unix_timestamp + (5 * 60)  # 5 min * 60 seconds

How to Set/Update State of StatefulWidget from other StatefulWidget in Flutter?

1.On Child Widget : add parameter Function paramter

class ChildWidget extends StatefulWidget {
  final Function() notifyParent;
  ChildWidget({Key key, @required this.notifyParent}) : super(key: key);
}

2.On Parent Widget : create a Function for the child to callback

refresh() {
  setState(() {});
}

3.On Parent Widget : pass parentFunction to Child Widget

new ChildWidget( notifyParent: refresh );  

4.On Child Widget : call the Parent Function

  widget.notifyParent();

plot different color for different categorical levels using matplotlib

Here a combination of markers and colors from a qualitative colormap in matplotlib:

import itertools
import numpy as np
from matplotlib import markers
import matplotlib.pyplot as plt

m_styles = markers.MarkerStyle.markers
N = 60
colormap = plt.cm.Dark2.colors  # Qualitative colormap
for i, (marker, color) in zip(range(N), itertools.product(m_styles, colormap)):
    plt.scatter(*np.random.random(2), color=color, marker=marker, label=i)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., ncol=4);

enter image description here

Set opacity of background image without affecting child elements

I found a pretty good and simple tutorial about this issue. I think it works great (and though it supports IE, I just tell my clients to use other browsers):

CSS background transparency without affecting child elements, through RGBa and filters

From there you can add gradient support, etc.

LINQ to SQL - Left Outer Join with multiple join conditions

You need to introduce your join condition before calling DefaultIfEmpty(). I would just use extension method syntax:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in fg.Where(f => f.otherid == 17).DefaultIfEmpty()
where p.companyid == 100
select f.value

Or you could use a subquery:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in (from f in fg
             where f.otherid == 17
             select f).DefaultIfEmpty()
where p.companyid == 100
select f.value

Lock down Microsoft Excel macro

The modern approach is to move away from VBA for important code, and write a .NET managed Add-In using c# or vb.net, there are a lot of resources for this on the www, and you could use the Express version of MS Visual Studio

Show space, tab, CRLF characters in editor of Visual Studio

The shortcut didn't work for me in Visual Studio 2015, also it was not in the edit menu.

Download and install the Productivity Power Tools for VS2015 and than you can find these options in the edit > advanced menu.

How to avoid annoying error "declared and not used"

I ran into this while I was learning Go 2 years ago, so I declared my own function.

// UNUSED allows unused variables to be included in Go programs
func UNUSED(x ...interface{}) {}

And then you can use it like so:

UNUSED(x)
UNUSED(x, y)
UNUSED(x, y, z)

The great thing about it is, you can pass anything into UNUSED.

Is it better than the following?

_, _, _ = x, y, z

That's up to you.

css ellipsis on second line

if someone is using SASS/SCSS and stumbles upon this question - maybe this mixin could be of help:

@mixin line-clamp($numLines : 1, $lineHeight: 1.412) {
  overflow: hidden;
  text-overflow: -o-ellipsis-lastline;
  text-overflow: ellipsis;
  display: block;
  /* autoprefixer: off */
  display: -webkit-box;
  -webkit-line-clamp: $numLines;
  -webkit-box-orient: vertical;
  max-height: $numLines * $lineHeight + unquote('em');
}

this only adds the ellipsis in webkit browsers. rest just cuts it off.

How do I redirect to another webpage?

This is how I use it.

   window.location.replace('yourPage.aspx');   
   // If you're on root and redirection page is also on the root

   window.location.replace(window.location.host + '/subDirectory/yourPage.aspx');

   // If you're in sub directory and redirection page is also in some other sub directory.

How to sort an array of objects in Java?

You can implement the "Comparable" interface on a class whose objects you want to compare.

And also implement the "compareTo" method in that.

Add the instances of the class in an ArrayList

Then the "java.utils.Collections.sort()" method will do the necessary magic.

Here's--->(https://deva-codes.herokuapp.com/CompareOnTwoKeys) a working example where objects are sorted based on two keys first by the id and then by name.

How to loop over directories in Linux?

If you want to execute multiple commands in a for loop, you can save the result of find with mapfile (bash >= 4) as an variable and go through the array with ${dirlist[@]}. It also works with directories containing spaces.

The find command is based on the answer by Boldewyn. Further information about the find command can be found there.

IFS=""
mapfile -t dirlist < <( find . -maxdepth 1 -mindepth 1 -type d -printf '%f\n' )
for dir in ${dirlist[@]}; do
    echo ">${dir}<"
    # more commands can go here ...
done

Two onClick actions one button

Additional attributes (in this case, the second onClick) will be ignored. So, instead of onclick calling both fbLikeDump(); and WriteCookie();, it will only call fbLikeDump();. To fix, simply define a single onclick attribute and call both functions within it:

<input type="button" value="Don't show this again! " onclick="fbLikeDump();WriteCookie();" />

How do you share constants in NodeJS modules?

From previous project experience, this is a good way:

In the constants.js:

// constants.js

'use strict';

let constants = {
    key1: "value1",
    key2: "value2",
    key3: {
        subkey1: "subvalue1",
        subkey2: "subvalue2"
    }
};

module.exports =
        Object.freeze(constants); // freeze prevents changes by users

In main.js (or app.js, etc.), use it as below:

// main.js

let constants = require('./constants');

console.log(constants.key1);

console.dir(constants.key3);

How can I get the last day of the month in C#?

try this. It will solve your problem.

 var lastDayOfMonth = DateTime.DaysInMonth(int.Parse(ddlyear.SelectedValue), int.Parse(ddlmonth.SelectedValue));
DateTime tLastDayMonth = Convert.ToDateTime(lastDayOfMonth.ToString() + "/" + ddlmonth.SelectedValue + "/" + ddlyear.SelectedValue);

How to pass a function as a parameter in Java?

Java does not (yet) support closures. But there are other languages like Scala and Groovy which run in the JVM and do support closures.

C#: How do you edit items and subitems in a listview?

Sorry, don't have enough rep, or would have commented on CraigTP's answer.

I found the solution from the 1st link - C# Editable ListView, quite easy to use. The general idea is to:

  • identify the SubItem that was selected and overlay a TextBox with the SubItem's text over the SubItem
  • give this TextBox focus
  • change SubItem's text to that of TextBox's when TextBox loses focus

What a workaround for a seemingly simple operation :-|

how to break the _.each function in underscore.js

_([1,2,3]).find(function(v){
    return v if (v==2);
})

Fastest way to reset every value of std::vector<int> to 0

How about the assign member function?

some_vector.assign(some_vector.size(), 0);

tqdm in Jupyter Notebook prints new progress bars repeatedly

Most of the answers are outdated now. Better if you import tqdm correctly.

from tqdm import tqdm_notebook as tqdm

enter image description here

How to find if directory exists in Python

You're looking for os.path.isdir, or os.path.exists if you don't care whether it's a file or a directory:

>>> import os
>>> os.path.isdir('new_folder')
True
>>> os.path.exists(os.path.join(os.getcwd(), 'new_folder', 'file.txt'))
False

Alternatively, you can use pathlib:

 >>> from pathlib import Path
 >>> Path('new_folder').is_dir()
 True
 >>> (Path.cwd() / 'new_folder' / 'file.txt').exists()
 False

Iterate through the fields of a struct in Go

After you've retrieved the reflect.Value of the field by using Field(i) you can get a interface value from it by calling Interface(). Said interface value then represents the value of the field.

There is no function to convert the value of the field to a concrete type as there are, as you may know, no generics in go. Thus, there is no function with the signature GetValue() T with T being the type of that field (which changes of course, depending on the field).

The closest you can achieve in go is GetValue() interface{} and this is exactly what reflect.Value.Interface() offers.

The following code illustrates how to get the values of each exported field in a struct using reflection (play):

import (
    "fmt"
    "reflect"
)

func main() {
    x := struct{Foo string; Bar int }{"foo", 2}

    v := reflect.ValueOf(x)

    values := make([]interface{}, v.NumField())

    for i := 0; i < v.NumField(); i++ {
        values[i] = v.Field(i).Interface()
    }

    fmt.Println(values)
}

How do I get a file's directory using the File object?

I found this more useful for getting the absolute file location.

File file = new File("\\TestHello\\test.txt");
System.out.println(file.getAbsoluteFile());

How to disable a input in angular2

Demo

make is_edit of type boolean.

<input [disabled]=is_edit id="name" type="text">

export class App {
  name:string;
  is_edit: boolean; 
  constructor() {
    this.name = 'Angular2'
    this.is_edit = true;
  }
}

How do I make an HTML text box show a hint when empty?


You can use a attribute called placeholder="" Here's a demo:

<html>
<body>
// try this out!
<input placeholder="This is my placeholder"/>
</body>
</html>

Homebrew: Could not symlink, /usr/local/bin is not writable

For me the solution was to run brew update.

So, DO THIS FIRST.

This might be normal practice for people familiar with homebrew, but I'm not one of those people.

Edit: I discovered that I needed to update by running brew doctor as suggested by @kinnth's answer to this same question.

A general troubleshooting workflow might look like this: 1. run brew update 2. if that doesn't help run brew doctor and follow its directions 3. if that doesn't help check stack overflow

How do I define a method in Razor?

You can simply declare them as local functions in a razor block (i.e. @{}).

@{
    int Add(int x, int y)
    {
        return x + y;
    }
}

<div class="container">
    <p>
        @Add(2, 5)
    </p>
</div>

How to add 10 minutes to my (String) time?

You have a plenty of easy approaches within above answers. This is just another idea. You can convert it to millisecond and add the TimeZoneOffset and add / deduct the mins/hours/days etc by milliseconds.

String myTime = "14:10";
int minsToAdd = 10;
Date date = new Date();
date.setTime((((Integer.parseInt(myTime.split(":")[0]))*60 + (Integer.parseInt(myTime.split(":")[1])))+ date1.getTimezoneOffset())*60000);
System.out.println(date.getHours() + ":"+date.getMinutes());
date.setTime(date.getTime()+ minsToAdd *60000);
System.out.println(date.getHours() + ":"+date.getMinutes());

Output :

14:10
14:20

Xpath for href element

Try below locator.

selenium.click("css=a[href*='listDetails.do'][id='oldcontent']");

or

selenium.click("xpath=//a[contains(@href,'listDetails.do') and @id='oldcontent']");

.Net picking wrong referenced assembly version

This error was somewhat misleading - I was loading some DLLs that required x64 architecture to be specified. In the .csproj file:

<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release-ABC|AnyCPU'">
    <OutputPath>bin\Release-ABC</OutputPath>
    <PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

A missing PlatformTarget caused this error.

Is it possible to write data to file using only JavaScript?

Yes its possible Here the code is

_x000D_
_x000D_
const fs = require('fs') 
let data = "Learning how to write in a file."
fs.writeFile('Output.txt', data, (err) => { 
      
    // In case of a error throw err. 
    if (err) throw err; 
}) 
_x000D_
_x000D_
_x000D_

Change user-agent for Selenium web-driver

There is no way in Selenium to read the request or response headers. You could do it by instructing your browser to connect through a proxy that records this kind of information.

Setting the User Agent in Firefox

The usual way to change the user agent for Firefox is to set the variable "general.useragent.override" in your Firefox profile. Note that this is independent from Selenium.

You can direct Selenium to use a profile different from the default one, like this:

from selenium import webdriver
profile = webdriver.FirefoxProfile()
profile.set_preference("general.useragent.override", "whatever you want")
driver = webdriver.Firefox(profile)

Setting the User Agent in Chrome

With Chrome, what you want to do is use the user-agent command line option. Again, this is not a Selenium thing. You can invoke Chrome at the command line with chrome --user-agent=foo to set the agent to the value foo.

With Selenium you set it like this:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
opts = Options()
opts.add_argument("user-agent=whatever you want")

driver = webdriver.Chrome(chrome_options=opts)

Both methods above were tested and found to work. I don't know about other browsers.

Getting the User Agent

Selenium does not have methods to query the user agent from an instance of WebDriver. Even in the case of Firefox, you cannot discover the default user agent by checking what general.useragent.override would be if not set to a custom value. (This setting does not exist before it is set to some value.)

Once the browser is started, however, you can get the user agent by executing:

agent = driver.execute_script("return navigator.userAgent")

The agent variable will contain the user agent.

jQuery if checkbox is checked

See main difference between ATTR | PROP | IS below:

Source: http://api.jquery.com/attr/

_x000D_
_x000D_
$( "input" )_x000D_
  .change(function() {_x000D_
    var $input = $( this );_x000D_
    $( "p" ).html( ".attr( 'checked' ): <b>" + $input.attr( "checked" ) + "</b><br>" +_x000D_
      ".prop( 'checked' ): <b>" + $input.prop( "checked" ) + "</b><br>" +_x000D_
      ".is( ':checked' ): <b>" + $input.is( ":checked" ) + "</b>" );_x000D_
  })_x000D_
  .change();
_x000D_
p {_x000D_
    margin: 20px 0 0;_x000D_
  }_x000D_
  b {_x000D_
    color: blue;_x000D_
  }
_x000D_
<meta charset="utf-8">_x000D_
  <title>attr demo</title>_x000D_
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
 _x000D_
<input id="check1" type="checkbox" checked="checked">_x000D_
<label for="check1">Check me</label>_x000D_
<p></p>_x000D_
 _x000D_
_x000D_
 _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

What is the idiomatic Go equivalent of C's ternary operator?

If all your branches make side-effects or are computationally expensive the following would a semantically-preserving refactoring:

index := func() int {
    if val > 0 {
        return printPositiveAndReturn(val)
    } else {
        return slowlyReturn(-val)  // or slowlyNegate(val)
    }
}();  # exactly one branch will be evaluated

with normally no overhead (inlined) and, most importantly, without cluttering your namespace with a helper functions that are only used once (which hampers readability and maintenance). Live Example

Note if you were to naively apply Gustavo's approach:

    index := printPositiveAndReturn(val);
    if val <= 0 {
        index = slowlyReturn(-val);  // or slowlyNegate(val)
    }

you'd get a program with a different behavior; in case val <= 0 program would print a non-positive value while it should not! (Analogously, if you reversed the branches, you would introduce overhead by calling a slow function unnecessarily.)

.NET Excel Library that can read/write .xls files

I'd recommend NPOI. NPOI is FREE and works exclusively with .XLS files. It has helped me a lot.

Detail: you don't need to have Microsoft Office installed on your machine to work with .XLS files if you use NPOI.

Check these blog posts:

Creating Excel spreadsheets .XLS and .XLSX in C#

NPOI with Excel Table and dynamic Chart

[UPDATE]

NPOI 2.0 added support for XLSX and DOCX.

You can read more about it here:

NPOI 2.0 series of posts scheduled

File Upload using AngularJS

The code will helps to insert file

<body ng-app = "myApp">
<form ng-controller="insert_Ctrl"  method="post" action=""  name="myForm" enctype="multipart/form-data" novalidate>
    <div>
        <p><input type="file" ng-model="myFile" class="form-control"  onchange="angular.element(this).scope().uploadedFile(this)">
            <span style="color:red" ng-show="(myForm.myFile.$error.required&&myForm.myFile.$touched)">Select Picture</span>
        </p>
    </div>
    <div>
        <input type="button" name="submit"  ng-click="uploadFile()" class="btn-primary" ng-disabled="myForm.myFile.$invalid" value="insert">
    </div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
<script src="insert.js"></script>
</body>

insert.js

var app = angular.module('myApp',[]);
app.service('uploadFile', ['$http','$window', function ($http,$window) {
    this.uploadFiletoServer = function(file,uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(data){
            alert("insert successfull");
            $window.location.href = ' ';//your window location
        })
        .error(function(){
            alert("Error");
        });
    }
}]);
app.controller('insert_Ctrl',  ['$scope', 'uploadFile', function($scope, uploadFile){
    $scope.uploadFile = function() {
        $scope.myFile = $scope.files[0];
        var file = $scope.myFile;
        var url = "save_data.php";
        uploadFile.uploadFiletoServer(file,url);
    };
    $scope.uploadedFile = function(element) {
        var reader = new FileReader();
        reader.onload = function(event) {
            $scope.$apply(function($scope) {
                $scope.files = element.files;
                $scope.src = event.target.result  
            });
        }
        reader.readAsDataURL(element.files[0]);
    }
}]);

save_data.php

<?php
    require "dbconnection.php";
    $ext = pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
    $image = time().'.'.$ext;
    move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$image);
    $query="insert into test_table values ('null','$image')";
    mysqli_query($con,$query);
?>

What is the difference between DTR/DSR and RTS/CTS flow control?

The difference between them is that they use different pins. Seriously, that's it. The reason they both exist is that RTS/CTS wasn't supposed to ever be a flow control mechanism, originally; it was for half-duplex modems to coordinate who was sending and who was receiving. RTS and CTS got misused for flow control so often that it became standard.

How to import jquery using ES6 syntax?

index.js

import {$,jQuery} from 'jquery';
// export for others scripts to use
window.$ = $;
window.jQuery = jQuery;

First, as @nem suggested in comment, the import should be done from node_modules/:

Well, importing from dist/ doesn't make sense since that is your distribution folder with production ready app. Building your app should take what's inside node_modules/ and add it to the dist/ folder, jQuery included.

Next, the glob –* as– is wrong as I know what object I'm importing (e.g. jQuery and $), so a straigforward import statement will work.

Last you need to expose it to other scripts using the window.$ = $.

Then, I import as both $ and jQuery to cover all usages, browserify remove import duplication, so no overhead here! ^o^y

What is meaning of negative dbm in signal strength?

The power in dBm is the 10 times the logarithm of the ratio of actual Power/1 milliWatt.

dBm stands for "decibel milliwatts". It is a convenient way to measure power. The exact formula is

P(dBm) = 10 · log10( P(W) / 1mW ) 

where

P(dBm) = Power expressed in dBm   
P(W) = the absolute power measured in Watts   
mW = milliWatts   
log10 = log to base 10

From this formula, the power in dBm of 1 Watt is 30 dBm. Because the calculation is logarithmic, every increase of 3dBm is approximately equivalent to doubling the actual power of a signal.

There is a conversion calculator and a comparison table here. There is also a comparison table on the Wikipedia english page, but the value it gives for mobile networks is a bit off.

Your actual question was "does the - sign count?"

The answer is yes, it does.

-85 dBm is less powerful (smaller) than -60 dBm. To understand this, you need to look at negative numbers. Alternatively, think about your bank account. If you owe the bank 85 dollars/rands/euros/rupees (-85), you're poorer than if you only owe them 65 (-65), i.e. -85 is smaller than -65. Also, in temperature measurements, -85 is colder than -65 degrees.

Signal strengths for mobile networks are always negative dBm values, because the transmitted network is not strong enough to give positive dBm values.

How will this affect your location finding? I have no idea, because I don't know what technology you are using to estimate the location. The values you quoted correspond roughly to a 5 bar network in GSM, UMTS or LTE, so you shouldn't have be having any problems due to network strength.

How do I vertically center an H1 in a div?

You can achieve this with the display property:

html, body {
    height:100%;
    margin:0;
    padding:0;
}
#section1 {
    width:100%; /*full width*/
    min-height:90%;
    text-align:center;
    display:table; /*acts like a table*/
}
h1{
    margin:0;
    padding:0;
    vertical-align:middle; /*middle centred*/
    display:table-cell; /*acts like a table cell*/
}

Demo: http://jsfiddle.net/a3Kns/

Getting absolute URLs using ASP.NET Core

You can get the url like this:

Request.Headers["Referer"]

Explanation

The Request.UrlReferer will throw a System.UriFormatException if the referer HTTP header is malformed (which can happen since it is not usually under your control).

As for using Request.ServerVariables, per MSDN:

Request.ServerVariables Collection

The ServerVariables collection retrieves the values of predetermined environment variables and request header information.

Request.Headers Property

Gets a collection of HTTP headers.

I guess I don't understand why you would prefer the Request.ServerVariables over Request.Headers, since Request.ServerVariables contains all of the environment variables as well as the headers, where Request.Headers is a much shorter list that only contains the headers.

So the best solution is to use the Request.Headers collection to read the value directly. Do heed Microsoft's warnings about HTML encoding the value if you are going to display it on a form, though.

How can I get a specific field of a csv file?

There is an interesting point you need to catch about csv.reader() object. The csv.reader object is not list type, and not subscriptable.

This works:

for r in csv.reader(file_obj): # file not closed
    print r

This does not:

r = csv.reader(file_obj) 
print r[0]

So, you first have to convert to list type in order to make the above code work.

r = list( csv.reader(file_obj) )
print r[0]          

failed to push some refs to [email protected]

When I tried git pull heroku master, I got an error fatal: refusing to merge unrelated histories.

So I tried git pull heroku master --allow-unrelated-histories and it worked for me

Selecting only first-level elements in jquery

Simply you can use this..

$("ul li a").click(function() {
  $(this).parent().find(">ul")...Something;
}

See example : https://codepen.io/gmkhussain/pen/XzjgRE

Upgrading React version and it's dependencies by reading package.json

Use this command to update react npm install --save [email protected] Don't forget to change 16.12.0 to the latest version or the version you need to setup.

How to add a Browse To File dialog to a VB.NET application

You should use the OpenFileDialog class like this

Dim fd As OpenFileDialog = New OpenFileDialog() 
Dim strFileName As String

fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True

If fd.ShowDialog() = DialogResult.OK Then
   strFileName = fd.FileName
End If

Then you can use the File class.

Auto start print html page using javascript

Use this script

 <script type="text/javascript">
      window.onload = function() { window.print(); }
 </script>

Python function as a function argument?

Decorators are very powerful in Python since it allows programmers to pass function as argument and can also define function inside another function.

def decorator(func):
      def insideFunction():
        print("This is inside function before execution")
        func()
      return insideFunction

def func():
    print("I am argument function")

func_obj = decorator(func) 
func_obj()

Output

  • This is inside function before execution
  • I am argument function

How to sum array of numbers in Ruby?

You can use .map and .sum like:

array.map { |e| e }.sum

jQuery has deprecated synchronous XMLHTTPRequest

It was mentioned as a comment by @henri-chan, but I think it deserves some more attention:

When you update the content of an element with new html using jQuery/javascript, and this new html contains <script> tags, those are executed synchronously and thus triggering this error. Same goes for stylesheets.

You know this is happening when you see (multiple) scripts or stylesheets being loaded as XHR in the console window. (firefox).

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

I've just started using Typescript and I've been trying to solve a similar problem like this; how to tell the Typescript that I'm passing a callback without an interface.

After browsing a few answers on Stack Overflow and GitHub issues, I finally found a solution that may help anyone with the same problem.

A function's type can be defined with (arg0: type0) => returnType and we can use this type definition in another function's parameter list.

function runCallback(callback: (sum: number) => void, a: number, b: number): void {
    callback(a + b);
}

// Another way of writing the function would be:
// let logSum: (sum: number) => void = function(sum: number): void {
//     console.log(sum);
// };
function logSum(sum: number): void {
    console.log(`The sum is ${sum}.`);
}

runCallback(logSum, 2, 2);

Swift: Reload a View Controller

If you need to update the canvas by redrawing views after some change, you should call setNeedsDisplay.

Thank you @Vincent from an earlier comment.enter image description here

Trim last character from a string

"Hello! world!".TrimEnd('!');

read more

EDIT:

What I've noticed in this type of questions that quite everyone suggest to remove the last char of given string. But this does not fulfill the definition of Trim method.

Trim - Removes all occurrences of white space characters from the beginning and end of this instance.

MSDN-Trim

Under this definition removing only last character from string is bad solution.

So if we want to "Trim last character from string" we should do something like this

Example as extension method:

public static class MyExtensions
{
  public static string TrimLastCharacter(this String str)
  {
     if(String.IsNullOrEmpty(str)){
        return str;
     } else {
        return str.TrimEnd(str[str.Length - 1]);
     }
  }
}

Note if you want to remove all characters of the same value i.e(!!!!)the method above removes all existences of '!' from the end of the string, but if you want to remove only the last character you should use this :

else { return str.Remove(str.Length - 1); }

Update query with PDO and MySQL

Your update syntax is incorrect. Please check Update Syntax for the correct syntax.

$sql = "UPDATE `access_users` set `contact_first_name` = :firstname,  `contact_surname` = :surname, `contact_email` = :email, `telephone` = :telephone";

Matplotlib: ValueError: x and y must have same first dimension

You should make x and y numpy arrays, not lists:

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,
              0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78])
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,
              0.478,0.335,0.365,0.424,0.390,0.585,0.511])

With this change, it produces the expect plot. If they are lists, m * x will not produce the result you expect, but an empty list. Note that m is anumpy.float64 scalar, not a standard Python float.

I actually consider this a bit dubious behavior of Numpy. In normal Python, multiplying a list with an integer just repeats the list:

In [42]: 2 * [1, 2, 3]
Out[42]: [1, 2, 3, 1, 2, 3]

while multiplying a list with a float gives an error (as I think it should):

In [43]: 1.5 * [1, 2, 3]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-43-d710bb467cdd> in <module>()
----> 1 1.5 * [1, 2, 3]
TypeError: can't multiply sequence by non-int of type 'float'

The weird thing is that multiplying a Python list with a Numpy scalar apparently works:

In [45]: np.float64(0.5) * [1, 2, 3]
Out[45]: []

In [46]: np.float64(1.5) * [1, 2, 3]
Out[46]: [1, 2, 3]

In [47]: np.float64(2.5) * [1, 2, 3]
Out[47]: [1, 2, 3, 1, 2, 3]

So it seems that the float gets truncated to an int, after which you get the standard Python behavior of repeating the list, which is quite unexpected behavior. The best thing would have been to raise an error (so that you would have spotted the problem yourself instead of having to ask your question on Stackoverflow) or to just show the expected element-wise multiplication (in which your code would have just worked). Interestingly, addition between a list and a Numpy scalar does work:

In [69]: np.float64(0.123) + [1, 2, 3]
Out[69]: array([ 1.123,  2.123,  3.123])

How to convert an object to a byte array in C#

If you want the serialized data to be really compact, you can write serialization methods yourself. That way you will have a minimum of overhead.

Example:

public class MyClass {

   public int Id { get; set; }
   public string Name { get; set; }

   public byte[] Serialize() {
      using (MemoryStream m = new MemoryStream()) {
         using (BinaryWriter writer = new BinaryWriter(m)) {
            writer.Write(Id);
            writer.Write(Name);
         }
         return m.ToArray();
      }
   }

   public static MyClass Desserialize(byte[] data) {
      MyClass result = new MyClass();
      using (MemoryStream m = new MemoryStream(data)) {
         using (BinaryReader reader = new BinaryReader(m)) {
            result.Id = reader.ReadInt32();
            result.Name = reader.ReadString();
         }
      }
      return result;
   }

}

Why not use Double or Float to represent currency?

As said earlier "Representing money as a double or float will probably look good at first as the software rounds off the tiny errors, but as you perform more additions, subtractions, multiplications and divisions on inexact numbers, you’ll lose more and more precision as the errors add up. This makes floats and doubles inadequate for dealing with money, where perfect accuracy for multiples of base 10 powers is required."

Finally Java has a standard way to work with Currency And Money!

JSR 354: Money and Currency API

JSR 354 provides an API for representing, transporting, and performing comprehensive calculations with Money and Currency. You can download it from this link:

JSR 354: Money and Currency API Download

The specification consists of the following things:

  1. An API for handling e. g. monetary amounts and currencies
  2. APIs to support interchangeable implementations
  3. Factories for creating instances of the implementation classes
  4. Functionality for calculations, conversion and formatting of monetary amounts
  5. Java API for working with Money and Currencies, which is planned to be included in Java 9.
  6. All specification classes and interfaces are located in the javax.money.* package.

Sample Examples of JSR 354: Money and Currency API:

An example of creating a MonetaryAmount and printing it to the console looks like this:

MonetaryAmountFactory<?> amountFactory = Monetary.getDefaultAmountFactory();
MonetaryAmount monetaryAmount = amountFactory.setCurrency(Monetary.getCurrency("EUR")).setNumber(12345.67).create();
MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(Locale.getDefault());
System.out.println(format.format(monetaryAmount));

When using the reference implementation API, the necessary code is much simpler:

MonetaryAmount monetaryAmount = Money.of(12345.67, "EUR");
MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(Locale.getDefault());
System.out.println(format.format(monetaryAmount));

The API also supports calculations with MonetaryAmounts:

MonetaryAmount monetaryAmount = Money.of(12345.67, "EUR");
MonetaryAmount otherMonetaryAmount = monetaryAmount.divide(2).add(Money.of(5, "EUR"));

CurrencyUnit and MonetaryAmount

// getting CurrencyUnits by locale
CurrencyUnit yen = MonetaryCurrencies.getCurrency(Locale.JAPAN);
CurrencyUnit canadianDollar = MonetaryCurrencies.getCurrency(Locale.CANADA);

MonetaryAmount has various methods that allow accessing the assigned currency, the numeric amount, its precision and more:

MonetaryAmount monetaryAmount = Money.of(123.45, euro);
CurrencyUnit currency = monetaryAmount.getCurrency();
NumberValue numberValue = monetaryAmount.getNumber();

int intValue = numberValue.intValue(); // 123
double doubleValue = numberValue.doubleValue(); // 123.45
long fractionDenominator = numberValue.getAmountFractionDenominator(); // 100
long fractionNumerator = numberValue.getAmountFractionNumerator(); // 45
int precision = numberValue.getPrecision(); // 5

// NumberValue extends java.lang.Number.
// So we assign numberValue to a variable of type Number
Number number = numberValue;

MonetaryAmounts can be rounded using a rounding operator:

CurrencyUnit usd = MonetaryCurrencies.getCurrency("USD");
MonetaryAmount dollars = Money.of(12.34567, usd);
MonetaryOperator roundingOperator = MonetaryRoundings.getRounding(usd);
MonetaryAmount roundedDollars = dollars.with(roundingOperator); // USD 12.35

When working with collections of MonetaryAmounts, some nice utility methods for filtering, sorting and grouping are available.

List<MonetaryAmount> amounts = new ArrayList<>();
amounts.add(Money.of(2, "EUR"));
amounts.add(Money.of(42, "USD"));
amounts.add(Money.of(7, "USD"));
amounts.add(Money.of(13.37, "JPY"));
amounts.add(Money.of(18, "USD"));

Custom MonetaryAmount operations

// A monetary operator that returns 10% of the input MonetaryAmount
// Implemented using Java 8 Lambdas
MonetaryOperator tenPercentOperator = (MonetaryAmount amount) -> {
    BigDecimal baseAmount = amount.getNumber().numberValue(BigDecimal.class);
    BigDecimal tenPercent = baseAmount.multiply(new BigDecimal("0.1"));
    return Money.of(tenPercent, amount.getCurrency());
};

MonetaryAmount dollars = Money.of(12.34567, "USD");

// apply tenPercentOperator to MonetaryAmount
MonetaryAmount tenPercentDollars = dollars.with(tenPercentOperator); // USD 1.234567

Resources:

Handling money and currencies in Java with JSR 354

Looking into the Java 9 Money and Currency API (JSR 354)

See Also: JSR 354 - Currency and Money

ImportError: No module named matplotlib.pyplot

I bashed my head on this for hours until I thought about checking my .bash_profile. I didn't have a path listed for python3 so I added the following code:

# Setting PATH for Python 3.6
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.6/bin:${PATH}"
export PATH

And then re-installed matplotlib with sudo pip3 install matplotlib. All is working beautifully now.

How to set locale in DatePipe in Angular 2?

This might be a little bit late, but in my case (angular 6), I created a simple pipe on top of DatePipe, something like this:

private _regionSub: Subscription;
private _localeId: string;

constructor(private _datePipe: DatePipe, private _store: Store<any>) {
  this._localeId = 'en-AU';
  this._regionSub = this._store.pipe(select(selectLocaleId))
    .subscribe((localeId: string) => {
      this._localeId = localeId || 'en-AU';
    });
}

ngOnDestroy() { // Unsubscribe }

transform(value: string | number, format?: string): string {
  const dateFormat = format || getLocaleDateFormat(this._localeId, FormatWidth.Short);
  return this._datePipe.transform(value, dateFormat, undefined, this._localeId);
}

May not be the best solution, but simple and works.

What is the difference between Cloud, Grid and Cluster?

There's some pretty good answers here but I want to elaborate on all topics:

Cloud: shailesh's answer is awesome, nothing to add there! Basically, An application that's served seamlessly over the network can be considered a Cloud application. Cloud isn't a new invention and it's very similar to Grid computing, but it's more of a buzzword with the spike of recent popularity.

Grid: Grid is defined as a large collection as machines connected by a private network and offers a set of services to users, it acts as a sort of supercomputer by sharing processing power across the machines. Source: Tenenbaum, Andrew.

Cluster: A cluster is different from those two. Clusters are two or more computers who share a network connection that acts as a heart-beat. Clusters are configurable in Active-Active or Active-Passive ways. Active-Active being that each computer runs it's own set of services (Say, one runs a SQL instance, the other runs a web server) and they share some resources such as storage. If one of the computers in a cluster goes down the service fails over to the other node and almost seamlessly starts running there. Active-Passive is similar, but only one machine runs these services and only takes over once there's a failure.

Rails 4 - passing variable to partial

From the Rails api on PartialRender:

Rendering the default case

If you're not going to be using any of the options like collections or layouts, you can also use the short-hand defaults of render to render partials.

Examples:

# Instead of <%= render partial: "account" %>
<%= render "account" %>

# Instead of <%= render partial: "account", locals: { account: @buyer } %>
<%= render "account", account: @buyer %>

# @account.to_partial_path returns 'accounts/account', so it can be used to replace:
# <%= render partial: "accounts/account", locals: { account: @account} %>
<%= render @account %>

# @posts is an array of Post instances, so every post record returns 'posts/post' on `to_partial_path`,
# that's why we can replace:
# <%= render partial: "posts/post", collection: @posts %>
<%= render @posts %>

So, you can use pass a local variable size to render as follows:

<%= render @users, size: 50 %>

and then use it in the _user.html.erb partial:

<li>
    <%= gravatar_for user, size: size %>
    <%= link_to user.name, user %>
</li>

Note that size: size is equivalent to :size => size.

Apache Prefork vs Worker MPM

Take a look at this for more detail. It refers to how Apache handles multiple requests. Preforking, which is the default, starts a number of Apache processes (2 by default here, though I believe one can configure this through httpd.conf). Worker MPM will start a new thread per request, which I would guess, is more memory efficient. Historically, Apache has used prefork, so it's a better-tested model. Threading was only added in 2.0.

How do I extract the contents of an rpm?

To debug / inspect your rpm I suggest to use redline which is a java program

Usage :

java -cp redline-1.2.1-jar-with-dependencies.jar org.redline_rpm.Scanner foo.rpm

Download : https://github.com/craigwblake/redline/releases

How to read integer value from the standard input in Java

Check this one:

public static void main(String[] args) {
    String input = null;
    int number = 0;
    try {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        input = bufferedReader.readLine();
        number = Integer.parseInt(input);
    } catch (NumberFormatException ex) {
       System.out.println("Not a number !");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Export to xls using angularjs

$scope.ExportExcel= function () { //function define in html tag                          

                        //export to excel file
                        var tab_text = '<table border="1px" style="font-size:20px" ">';
                        var textRange;
                        var j = 0;
                        var tab = document.getElementById('TableExcel'); // id of table
                        var lines = tab.rows.length;

                        // the first headline of the table
                        if (lines > 0) {
                            tab_text = tab_text + '<tr bgcolor="#DFDFDF">' + tab.rows[0].innerHTML + '</tr>';
                        }

                        // table data lines, loop starting from 1
                        for (j = 1 ; j < lines; j++) {
                            tab_text = tab_text + "<tr>" + tab.rows[j].innerHTML + "</tr>";                                
                        }

                        tab_text = tab_text + "</table>";
                        tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, "");          //remove if u want links in your table
                        tab_text = tab_text.replace(/<img[^>]*>/gi, "");             // remove if u want images in your table
                        tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

                        // console.log(tab_text); // aktivate so see the result (press F12 in browser)               
                        var fileName = 'report.xls'                            
                        var exceldata = new Blob([tab_text], { type: "application/vnd.ms-excel;charset=utf-8" }) 

                        if (window.navigator.msSaveBlob) { // IE 10+
                            window.navigator.msSaveOrOpenBlob(exceldata, fileName);
                            //$scope.DataNullEventDetails = true;
                        } else {
                            var link = document.createElement('a'); //create link download file
                            link.href = window.URL.createObjectURL(exceldata); // set url for link download
                            link.setAttribute('download', fileName); //set attribute for link created
                            document.body.appendChild(link);
                            link.click();
                            document.body.removeChild(link);
                        }

                    }

        //html of button 

How can I comment a single line in XML?

It is the same as the HTML or JavaScript block comments:

<!-- The to-be-commented XML block goes here. -->

Compare two dates in Java

The easiest way to compare two dates is converting them to numeric value (like unix timestamp).

You can use Date.getTime() method that return the unix time.

Date questionDate = question.getStartDate();
Date today = new Date();
if((today.getTime() == questionDate.getTime())) {
    System.out.println("Both are equals");
}

jQuery keypress() event not firing?

With jQuery, I've done it this way:

function checkKey(e){
     switch (e.keyCode) {
        case 40:
            alert('down');
            break;
        case 38:
            alert('up');
            break;
        case 37:
            alert('left');
            break;
        case 39:
            alert('right');
            break;
        default:
            alert('???');  
            }      
}

if ($.browser.mozilla) {
    $(document).keypress (checkKey);
} else {
    $(document).keydown (checkKey);
}

Also, try these plugins, which looks like they do all that work for you:

http://www.openjs.com/scripts/events/keyboard_shortcuts

http://www.webappers.com/2008/07/31/bind-a-hot-key-combination-with-jquery-hotkeys/

Change DIV content using ajax, php and jQuery

<script>

function getSummary(id)
{
   $.ajax({

     type: "GET",
     url: 'Your URL',
     data: "id=" + id, // appears as $_GET['id'] @ your backend side
     success: function(data) {
           // data is ur summary
          $('#summary').html(data);
     }

   });

}
</script>

And add onclick event in your lists

<a onclick="getSummary('1')">View Text</a>
<div id="#summary">This text will be replaced when the onclick event (link is clicked) is triggered.</div>

How to set opacity to the background color of a div?

I think this covers just about all of the browsers. I have used it successfully in the past.

#div {
    filter: alpha(opacity=50); /* internet explorer */
    -khtml-opacity: 0.5;      /* khtml, old safari */
    -moz-opacity: 0.5;       /* mozilla, netscape */
    opacity: 0.5;           /* fx, safari, opera */
}

Youtube iframe wmode issue

I know this is an old question, but it still comes up in the top searches for this issue so I'm adding a new answer to help those looking for one for IE:

Adding &wmode=opaque to the end of the URL does NOT work in IE 10...

However, adding ?wmode=opaque does the trick!


Found this solution here: http://alamoxie.com/blog/web-design/stop-iframes-covering-site-elements

How to enable Logger.debug() in Log4j

If you are coming here because you are using Apache commons logging with log4j and log4j isn't working as you expect then check that you actually have a log4j.jar in your run-time classpath. That one had me puzzled for a little while. I have now configured the runner in my dev environment to include -Dlog4j.debug in the Java command line so I can always see that Log4j is being initialized correctly

Storing integer values as constants in Enum manner in java

Well, you can't quite do it that way. PAGE.SIGN_CREATE will never return 1; it will return PAGE.SIGN_CREATE. That's the point of enumerated types.

However, if you're willing to add a few keystrokes, you can add fields to your enums, like this:


    public enum PAGE{
        SIGN_CREATE(0),
        SIGN_CREATE_BONUS(1),
        HOME_SCREEN(2),
        REGISTER_SCREEN(3);

        private final int value;

        PAGE(final int newValue) {
            value = newValue;
        }

        public int getValue() { return value; }
    }

And then you call PAGE.SIGN_CREATE.getValue() to get 0.

How to set button click effect in Android?

You can simply use foreground for your View to achieve clickable effect:

android:foreground="?android:attr/selectableItemBackground"


For use with dark theme add also theme to your layout (to clickable effect be clear):

android:theme="@android:style/ThemeOverlay.Material.Dark"

How to "scan" a website (or page) for info, and bring it into my program?

You could also try jARVEST.

It is based on a JRuby DSL over a pure-Java engine to spider-scrape-transform web sites.

Example:

Find all links inside a web page (wget and xpath are constructs of the jARVEST's language):

wget | xpath('//a/@href')

Inside a Java program:

Jarvest jarvest = new Jarvest();
  String[] results = jarvest.exec(
    "wget | xpath('//a/@href')", //robot! 
    "http://www.google.com" //inputs
  );
  for (String s : results){
    System.out.println(s);
  }

How to create a fixed-size array of objects

One thing you could do would be to create a dictionary. Might be a little sloppy considering your looking for 64 elements but it gets the job done. Im not sure if its the "preferred way" to do it but it worked for me using an array of structs.

var tasks = [0:[forTasks](),1:[forTasks](),2:[forTasks](),3:[forTasks](),4:[forTasks](),5:[forTasks](),6:[forTasks]()]

Can I set an opacity only to the background image of a div?

This can be done by using the different div class for the text Hi There...

<div class="myDiv">
    <div class="bg">
   <p> Hi there</p>
</div>
</div>

Now you can apply the styles to the

tag. otherwise for bg class. I am sure it works fine

How to Ping External IP from Java Android

This is what I implemented myself, which returns the average latency:

/*
Returns the latency to a given server in mili-seconds by issuing a ping command.
system will issue NUMBER_OF_PACKTETS ICMP Echo Request packet each having size of 56 bytes
every second, and returns the avg latency of them.
Returns 0 when there is no connection
 */
public double getLatency(String ipAddress){
    String pingCommand = "/system/bin/ping -c " + NUMBER_OF_PACKTETS + " " + ipAddress;
    String inputLine = "";
    double avgRtt = 0;

    try {
        // execute the command on the environment interface
        Process process = Runtime.getRuntime().exec(pingCommand);
        // gets the input stream to get the output of the executed command
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        inputLine = bufferedReader.readLine();
        while ((inputLine != null)) {
            if (inputLine.length() > 0 && inputLine.contains("avg")) {  // when we get to the last line of executed ping command
                break;
            }
            inputLine = bufferedReader.readLine();
        }
    }
    catch (IOException e){
        Log.v(DEBUG_TAG, "getLatency: EXCEPTION");
        e.printStackTrace();
    }

    // Extracting the average round trip time from the inputLine string
    String afterEqual = inputLine.substring(inputLine.indexOf("="), inputLine.length()).trim();
    String afterFirstSlash = afterEqual.substring(afterEqual.indexOf('/') + 1, afterEqual.length()).trim();
    String strAvgRtt = afterFirstSlash.substring(0, afterFirstSlash.indexOf('/'));
    avgRtt = Double.valueOf(strAvgRtt);

    return avgRtt;
}

Options for HTML scraping?

I use Hpricot on Ruby. As an example this is a snippet of code that I use to retrieve all book titles from the six pages of my HireThings account (as they don't seem to provide a single page with this information):

pagerange = 1..6
proxy = Net::HTTP::Proxy(proxy, port, user, pwd)
proxy.start('www.hirethings.co.nz') do |http|
  pagerange.each do |page|
    resp, data = http.get "/perth_dotnet?page=#{page}" 
    if resp.class == Net::HTTPOK
      (Hpricot(data)/"h3 a").each { |a| puts a.innerText }
    end
  end
end 

It's pretty much complete. All that comes before this are library imports and the settings for my proxy.

PHPUnit assert that an exception was thrown?

Here's all the exception assertions you can do. Note that all of them are optional.

class ExceptionTest extends PHPUnit_Framework_TestCase
{
    public function testException()
    {
        // make your exception assertions
        $this->expectException(InvalidArgumentException::class);
        // if you use namespaces:
        // $this->expectException('\Namespace\MyExceptio??n');
        $this->expectExceptionMessage('message');
        $this->expectExceptionMessageRegExp('/essage$/');
        $this->expectExceptionCode(123);
        // code that throws an exception
        throw new InvalidArgumentException('message', 123);
   }

   public function testAnotherException()
   {
        // repeat as needed
        $this->expectException(Exception::class);
        throw new Exception('Oh no!');
    }
}

Documentation can be found here.

Where's the DateTime 'Z' format specifier?

Label1.Text = dt.ToString("dd MMM yyyy | hh:mm | ff | zzz | zz | z");

will output:

07 Mai 2009 | 08:16 | 13 | +02:00 | +02 | +2

I'm in Denmark, my Offset from GMT is +2 hours, witch is correct.

if you need to get the CLIENT Offset, I recommend that you check a little trick that I did. The Page is in a Server in UK where GMT is +00:00 and, as you can see you will get your local GMT Offset.


Regarding you comment, I did:

DateTime dt1 = DateTime.Now;
DateTime dt2 = dt1.ToUniversalTime();

Label1.Text = dt1.ToString("dd MMM yyyy | hh:mm | ff | zzz | zz | z");
Label2.Text = dt2.ToString("dd MMM yyyy | hh:mm | FF | ZZZ | ZZ | Z");

and I get this:

07 Mai 2009 | 08:24 | 14 | +02:00 | +02 | +2
07 Mai 2009 | 06:24 | 14 | ZZZ | ZZ | Z 

I get no Exception, just ... it does nothing with capital Z :(

I'm sorry, but am I missing something?


Reading carefully the MSDN on Custom Date and Time Format Strings

there is no support for uppercase 'Z'.

Google Maps API throws "Uncaught ReferenceError: google is not defined" only when using AJAX

For me

Adding this line

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

Before this line.

<script id="microloader" type="text/javascript" src=".sencha/app/microloader/development.js"></script>

worked

How to get the caller's method name in the called method?

Shorter version:

import inspect

def f1(): f2()

def f2():
    print 'caller name:', inspect.stack()[1][3]

f1()

(with thanks to @Alex, and Stefaan Lippen)

Disabling user input for UITextfield in swift

I like to do it like old times. You just use a custom UITextField Class like this one:

//
//  ReadOnlyTextField.swift
//  MediFormulas
//
//  Created by Oscar Rodriguez on 6/21/17.
//  Copyright © 2017 Nica Code. All rights reserved.
//

import UIKit

class ReadOnlyTextField: UITextField {

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

    override init(frame: CGRect) {
        super.init(frame: frame)

        // Avoid keyboard to show up
        self.inputView = UIView()
    }

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

        // Avoid keyboard to show up
        self.inputView = UIView()
    }

    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        // Avoid cut and paste option show up
        if (action == #selector(self.cut(_:))) {
            return false
        } else if (action == #selector(self.paste(_:))) {
            return false
        }

        return super.canPerformAction(action, withSender: sender)
    }

}

C# equivalent of the IsNull() function in SQL Server

You Write Two Function

    //When Expression is Number
    public static double? isNull(double? Expression, double? Value)
    {
        if (Expression ==null)
        {
            return Value;
        }
        else
        {
            return Expression;
        }
    }


    //When Expression is string (Can not send Null value in string Expression
    public static string isEmpty(string Expression, string Value)
    {
        if (Expression == "")
        {
            return Value;
        }
        else
        {
            return Expression;
        }
    }

They Work Very Well

How to do vlookup and fill down (like in Excel) in R?

Starting with:

houses <- read.table(text="Semi            1
Single          2
Row             3
Single          2
Apartment       4
Apartment       4
Row             3",col.names=c("HouseType","HouseTypeNo"))

... you can use

as.numeric(factor(houses$HouseType))

... to give a unique number for each house type. You can see the result here:

> houses2 <- data.frame(houses,as.numeric(factor(houses$HouseType)))
> houses2
  HouseType HouseTypeNo as.numeric.factor.houses.HouseType..
1      Semi           1                                    3
2    Single           2                                    4
3       Row           3                                    2
4    Single           2                                    4
5 Apartment           4                                    1
6 Apartment           4                                    1
7       Row           3                                    2

... so you end up with different numbers on the rows (because the factors are ordered alphabetically) but the same pattern.

(EDIT: the remaining text in this answer is actually redundant. It occurred to me to check and it turned out that read.table() had already made houses$HouseType into a factor when it was read into the dataframe in the first place).

However, you may well be better just to convert HouseType to a factor, which would give you all the same benefits as HouseTypeNo, but would be easier to interpret because the house types are named rather than numbered, e.g.:

> houses3 <- houses
> houses3$HouseType <- factor(houses3$HouseType)
> houses3
  HouseType HouseTypeNo
1      Semi           1
2    Single           2
3       Row           3
4    Single           2
5 Apartment           4
6 Apartment           4
7       Row           3
> levels(houses3$HouseType)
[1] "Apartment" "Row"       "Semi"      "Single"  

Search and replace a line in a file in Python

I guess something like this should do it. It basically writes the content to a new file and replaces the old file with the new file:

from tempfile import mkstemp
from shutil import move, copymode
from os import fdopen, remove

def replace(file_path, pattern, subst):
    #Create temp file
    fh, abs_path = mkstemp()
    with fdopen(fh,'w') as new_file:
        with open(file_path) as old_file:
            for line in old_file:
                new_file.write(line.replace(pattern, subst))
    #Copy the file permissions from the old file to the new file
    copymode(file_path, abs_path)
    #Remove original file
    remove(file_path)
    #Move new file
    move(abs_path, file_path)

How to find out the MySQL root password

System:

  • CentOS Linux 7
  • mysql Ver 14.14 Distrib 5.7.25

Procedure:

  1. Open two shell sessions, logging in to one as the Linux root user and the other as a nonroot user with access to the mysql command.

  2. In your root session, stop the normal mysqld listener and start a listener which bypasses password authentication (note: this is a significant security risk as anyone with access to the mysql command may access your databases without a password. You may want to close active shell sessions and/or disable shell access before doing this):

    # systemctl stop mysqld
    # /usr/sbin/mysqld --skip-grant-tables -u mysql &

  3. In your nonroot session, log in to mysql and set the mysql root password:

    $ mysql
    mysql> flush privileges;
    Query OK, 0 rows affected (0.00 sec)

    mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');
    Query OK, 0 rows affected, 1 warning (0.01 sec)

    mysql> quit;

  4. In your root session, kill the passwordless instance of mysqld and restore the normal mysqld listener to service:

    # kill %1
    # systemctl start mysqld

  5. In your nonroot session, test the new root password you configured above:

    $ mysql -u root -p
    Enter password:
    Welcome to the MySQL monitor. Commands end with ; or \g.
    ...
    mysql>

Android - border for button

Create a button_border.xml file in your drawable folder.

res/drawable/button_border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <solid android:color="#FFDA8200" />

    <stroke
        android:width="3dp"
        android:color="#FFFF4917" />

</shape>

And add button to your XML activity layout and set background android:background="@drawable/button_border".

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/button_border"
    android:text="Button Border" />

Installing SetupTools on 64-bit Windows

Create a file named python2.7.reg (registry file) and put this content into it:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Help]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Help\MainPythonDocumentation]
@="C:\\Python27\\Doc\\python26.chm"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\InstallPath]
@="C:\\Python27\\"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\InstallPath\InstallGroup]
@="Python 2.7"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\Modules]

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Python\PythonCore\2.7\PythonPath]
@="C:\\Python27\\Lib;C:\\Python27\\DLLs;C:\\Python27\\Lib\\lib-tk"

And make sure every path is right!

Then run (merge) it and done :)

Conda activate not working?

In the windows environment use "anaconda prompt" instead of "command prompt".

How to get cookie expiration date / creation date from javascript?

Yes, It is possible. I've separated the code in two files:

index.php

<?php

    $time = time()+(60*60*24*10);
    $timeMemo = (string)$time;
    setcookie("cookie", "" . $timeMemo . "", $time);

?>
<html>
    <head>
        <title>
            Get cookie expiration date from JS
        </title>
        <script type="text/javascript">

            function cookieExpirationDate(){

                var infodiv = document.getElementById("info");

                var xmlhttp;
                if (window.XMLHttpRequest){ 
                    xmlhttp = new XMLHttpRequest;
                }else{
                    xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);
                }

                xmlhttp.onreadystatechange = function (){
                    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                        infodiv.innerHTML = xmlhttp.responseText;
                    }
                }

                xmlhttp.open("GET", "cookie.php", true);
                xmlhttp.send();

            }

        </script>
    </head>
    <body>
        <input type="button" onclick="javascript:cookieExpirationDate();" value="Get Cookie expire date" />
        <hr />
        <div id="info">
        </div>
    </body>
</html>

cookie.php

<?php

    function secToDays($sec){
        return ($sec / 60 / 60 / 24);
    }

    if(isset($_COOKIE['cookie'])){

        if(round(secToDays((intval($_COOKIE['cookie']) - time())),1) < 1){
            echo "Cookie will expire today";
        }else{
            echo "Cookie will expire in " . round(secToDays((intval($_COOKIE['cookie']) - time())),1) . " day(s)";
        }
    }else{
        echo "Cookie not set...";
    }

?>

Now, index.php must be loaded once. The button "Get Cookie expire date", thru an AJAX request, will always get you an updated "time left" for cookie expiration, in this case in days.

Java file path in Linux

The Official Documentation is clear about Path.

Linux Syntax: /home/joe/foo

Windows Syntax: C:\home\joe\foo


Note: joe is your username for these examples.

Google Gson - deserialize list<class> object? (generic type)

Since Gson 2.8, we can create util function like

public <T> List<T> getList(String jsonArray, Class<T> clazz) {
    Type typeOfT = TypeToken.getParameterized(List.class, clazz).getType();
    return new Gson().fromJson(jsonArray, typeOfT);
}

Example using

String jsonArray = ...
List<User> user = getList(jsonArray, User.class);

Angular EXCEPTION: No provider for Http

Just include the following libraries:

import { HttpModule } from '@angular/http';
import { YourHttpTestService } from '../services/httpTestService';

and include the http class in providers section, as follows:

@Component({
  selector: '...',
  templateUrl: './test.html',
  providers: [YourHttpTestService]

Combining INSERT INTO and WITH/CTE

You need to put the CTE first and then combine the INSERT INTO with your select statement. Also, the "AS" keyword following the CTE's name is not optional:

WITH tab AS (
    bla bla
)
INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (
BatchID,
AccountNo,
APartyNo,
SourceRowID
)  
SELECT * FROM tab

Please note that the code assumes that the CTE will return exactly four fields and that those fields are matching in order and type with those specified in the INSERT statement. If that is not the case, just replace the "SELECT *" with a specific select of the fields that you require.

As for your question on using a function, I would say "it depends". If you are putting the data in a table just because of performance reasons, and the speed is acceptable when using it through a function, then I'd consider function to be an option. On the other hand, if you need to use the result of the CTE in several different queries, and speed is already an issue, I'd go for a table (either regular, or temp).

WITH common_table_expression (Transact-SQL)

I need an unordered list without any bullets

Small refinement to the previous answers: To make longer lines more readable if they spill over to additional screen lines:

ul, li {list-style-type: none;}

li {padding-left: 2em; text-indent: -2em;}

How to use patterns in a case statement?

if and grep -Eq

arg='abc'
if echo "$arg" | grep -Eq 'a.c|d.*'; then
  echo 'first'
elif echo "$arg" | grep -Eq 'a{2,3}'; then
  echo 'second'
fi

where:

  • -q prevents grep from producing output, it just produces the exit status
  • -E enables extended regular expressions

I like this because:

One downside is that this is likely slower than case since it calls an external grep program, but I tend to consider performance last when using Bash.

case is POSIX 7

Bash appears to follow POSIX by default without shopt as mentioned by https://stackoverflow.com/a/4555979/895245

Here is the quote: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_01 section "Case Conditional Construct":

The conditional construct case shall execute the compound-list corresponding to the first one of several patterns (see Pattern Matching Notation) [...] Multiple patterns with the same compound-list shall be delimited by the '|' symbol. [...]

The format for the case construct is as follows:

case word in
     [(] pattern1 ) compound-list ;;
     [[(] pattern[ | pattern] ... ) compound-list ;;] ...
     [[(] pattern[ | pattern] ... ) compound-list]
  esac

and then http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_13 section "2.13. Pattern Matching Notation" only mentions ?, * and [].

Unix command to find lines common in two files

The command you are seeking is comm. eg:-

comm -12 1.sorted.txt 2.sorted.txt

Here:

-1 : suppress column 1 (lines unique to 1.sorted.txt)

-2 : suppress column 2 (lines unique to 2.sorted.txt)

How do you echo a 4-digit Unicode character in Bash?

If hex value of unicode character is known

H="2620"
printf "%b" "\u$H"

If the decimal value of a unicode character is known

declare -i U=2*4096+6*256+2*16
printf -vH "%x" $U              # convert to hex
printf "%b" "\u$H"

How can I check that JButton is pressed? If the isEnable() is not work?

Seems you need to use JToggleButton :

JToggleButton tb = new JToggleButton("push me");
tb.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        JToggleButton btn =  (JToggleButton) e.getSource();
        btn.setText(btn.isSelected() ? "pushed" : "push me");
    }
});

How can I change the version of npm using nvm?

Slight variation on the above instructions, worked for me. (MacOS Sierra 10.12.6)

npm install -g [email protected]
rm /usr/local/bin/npm
ln -s ~/.npm-packages/bin/npm /usr/local/bin/npm
npm --version

Using Alert in Response.Write Function in ASP.NET

Concatenate the string separating the slash and the word script in this way.

Response.Write("<script language='javascript'>alert('Especifique Usuario y Contraseña');</" + "script>");

Online SQL syntax checker conforming to multiple databases

I don't know of any such, and my experience is that it doesn't currently exist. Most are side by side comparisons of two databases. That information requires experts in all the databases encountered, which isn't common. Versions depend too, to know what is supported.

ANSI functions are making strides to ensure syntax is supported across databases, but it's dependent on vendors implementing the spec. And to date, they aren't implementing the entire ANSI spec at a time.

But you can crowd source on sites like this one by asking specific questions and including the databases involved and the versions used.

How to find GCD, LCM on a set of numbers

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int n0 = input.nextInt(); // number of intended input.
        int [] MyList = new int [n0];

        for (int i = 0; i < n0; i++)
            MyList[i] = input.nextInt();
            //input values stored in an array
        int i = 0;
        int count = 0;
            int gcd = 1; // Initial gcd is 1
            int k = 2; // Possible gcd
            while (k <= MyList[i] && k <= MyList[i]) {
                if (MyList[i] % k == 0 && MyList[i] % k == 0)
                    gcd = k; // Update gcd
                k++;
                count++; //checking array for gcd
            }
           // int i = 0;
            MyList [i] = gcd;
            for (int e: MyList) {
                System.out.println(e);

            }

            }

        }

How to tell Jackson to ignore a field during serialization if its value is null?

Just to expand on the other answers - if you need to control the omission of null values on a per-field basis, annotate the field in question (or alternatively annotate the field's 'getter').

example - here only fieldOne will be ommitted from json if it is null. fieldTwo will always be included regardless of if it is null.

public class Foo {

    @JsonInclude(JsonInclude.Include.NON_NULL) 
    private String fieldOne;

    private String fieldTwo;
}

To omit all null values in the class as a default, annotate the class. Per-field/getter annotations can still be used to override this default if necessary.

example - here fieldOne and fieldTwo will be ommitted from json if they are null, respectively, because this is the default set by the class annotation. fieldThree however will override the default and will always be included, because of the annotation on the field.

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Foo {

    private String fieldOne;

    private String fieldTwo;

    @JsonInclude(JsonInclude.Include.ALWAYS)
    private String fieldThree;
}

UPDATE

The above is for Jackson 2. For earlier versions of Jackson you need to use:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) 

instead of

@JsonInclude(JsonInclude.Include.NON_NULL)

If this update is useful, please upvote ZiglioUK's answer below, it pointed out the newer Jackson 2 annotation long before I updated my answer to use it!

Git push error: "origin does not appear to be a git repository"

As it has already been mentioned in che's answer about adding the remote part, which I believe you are still missing.

Regarding your edit for adding remote on your local USB drive. First of all you must have a 'bare repository' if you want your repository to be a shared repository i.e. to be able to push/pull/fetch/merge etc..

To create a bare/shared repository, go to your desired location. In your case:

$ cd /Volumes/500gb/   
$ git init --bare myproject.git

See here for more info on creating bare repository

Once you have a bare repository set up in your desired location you can now add it to your working copy as a remote.

$ git remote add origin /Volumes/500gb/myproject.git

And now you can push your changes to your repository

$ git push origin master

How to link HTML5 form action to Controller ActionResult method in ASP.NET MVC 4

Here I'm basically wrapping a button in a link. The advantage is that you can post to different action methods in the same form.

<a href="Controller/ActionMethod">
    <input type="button" value="Click Me" />
</a>

Adding parameters:

<a href="Controller/ActionMethod?userName=ted">
    <input type="button" value="Click Me" />
</a>

Adding parameters from a non-enumerated Model:

<a href="Controller/[email protected]">
    <input type="button" value="Click Me" />
</a>

You can do the same for an enumerated Model too. You would just have to reference a single entity first. Happy Coding!

How can I get the content of CKEditor using JQuery?

First of all you should include ckeditor and jquery connector script in your page,

then create a textarea

<textarea name="content" class="editor" id="ms_editor"></textarea>

attach ckeditor to the text area, in my project I use something like this:

$('textarea.editor').ckeditor(function() {
        }, { toolbar : [
            ['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
            ['Undo','Redo'],
            ['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
            ['NumberedList','BulletedList','-','Outdent','Indent','Blockquote'],
            ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
            ['Link','Unlink','Anchor', 'Image', 'Smiley'],
            ['Table','HorizontalRule','SpecialChar'],
            ['Styles','BGColor']
        ], toolbarCanCollapse:false, height: '300px', scayt_sLang: 'pt_PT', uiColor : '#EBEBEB' } );

on submit get the content using:

var content = $( 'textarea.editor' ).val();

That's it! :)

Linq select object from list depending on objects attribute

if a.Correct is a bool flag for the correct answer then you need.

Answer answer = Answers.Single(a => a.Correct);

Checking for NULL pointer in C/C++

If style and format are going to be part of your reviews, there should be an agreed upon style guide to measure against. If there is one, do what the style guide says. If there's not one, details like this should be left as they are written. It's a waste of time and energy, and distracts from what code reviews really ought to be uncovering. Seriously, without a style guide I would push to NOT change code like this as a matter of principle, even when it doesn't use the convention I prefer.

And not that it matters, but my personal preference is if (ptr). The meaning is more immediately obvious to me than even if (ptr == NULL).

Maybe he's trying to say that it's better to handle error conditions before the happy path? In that case I still don't agree with the reviewer. I don't know that there's an accepted convention for this, but in my opinion the most "normal" condition ought to come first in any if statement. That way I've got less digging to do to figure out what the function is all about and how it works.

The exception to this is if the error causes me to bail from the function, or I can recover from it before moving on. In those cases, I do handle the error first:

if (error_condition)
  bail_or_fix();
  return if not fixed;

// If I'm still here, I'm on the happy path

By dealing with the unusual condition up front, I can take care of it and then forget about it. But if I can't get back on the happy path by handling it up front, then it should be handled after the main case because it makes the code more understandable. In my opinion.

But if it's not in a style guide then it's just my opinion, and your opinion is just as valid. Either standardize or don't. Don't let a reviewer pseudo-standardize just because he's got an opinion.

Appending an element to the end of a list in Scala

Lists in Scala are not designed to be modified. In fact, you can't add elements to a Scala List; it's an immutable data structure, like a Java String. What you actually do when you "add an element to a list" in Scala is to create a new List from an existing List. (Source)

Instead of using lists for such use cases, I suggest to either use an ArrayBuffer or a ListBuffer. Those datastructures are designed to have new elements added.

Finally, after all your operations are done, the buffer then can be converted into a list. See the following REPL example:

scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer

scala> var fruits = new ListBuffer[String]()
fruits: scala.collection.mutable.ListBuffer[String] = ListBuffer()

scala> fruits += "Apple"
res0: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple)

scala> fruits += "Banana"
res1: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana)

scala> fruits += "Orange"
res2: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana, Orange)

scala> val fruitsList = fruits.toList
fruitsList: List[String] = List(Apple, Banana, Orange)

Change Oracle port from port 8080

From Start | Run open a command window. Assuming your environmental variables are set correctly start with the following:

C:\>sqlplus /nolog
SQL*Plus: Release 10.2.0.1.0 - Production on Tue Aug 26 10:40:44 2008
Copyright (c) 1982, 2005, Oracle.  All rights reserved.

SQL> connect
Enter user-name: system
Enter password: <enter password if will not be visible>
Connected.

SQL> Exec DBMS_XDB.SETHTTPPORT(3010); [Assuming you want to have HTTP going to this port]    
PL/SQL procedure successfully completed.

SQL>quit 

then open browser and use 3010 port.

ggplot2, change title size

+ theme(plot.title = element_text(size=22))

Here is the full set of things you can change in element_text:

element_text(family = NULL, face = NULL, colour = NULL, size = NULL,
  hjust = NULL, vjust = NULL, angle = NULL, lineheight = NULL,
  color = NULL)

What is the difference between lower bound and tight bound?

If I were lazy, I could say that binary search on a sorted array is O(n2), O(n3), and O(2n), and I would be technically correct in every case.

We can use o-notation ("little-oh") to denote an upper bound that is not asymptotically tight. Both big-oh and little-oh are similar. But, big-oh is likely used to define asymptotically tight upper bound.

How do I change Android Studio editor's background color?

You can change it by going File => Settings (Shortcut CTRL+ ALT+ S) , from Left panel Choose Appearance , Now from Right Panel choose theme.

enter image description here

Android Studio 2.1

Preference -> Search for Appearance -> UI options , Click on DropDown Theme

enter image description here

Android 2.2

Android studio -> File -> Settings -> Appearance & Behavior -> Look for UI Options

EDIT :

Import External Themes

You can download custom theme from this website. Choose your theme, download it. To set theme Go to Android studio -> File -> Import Settings -> Choose the .jar file downloaded.

datetime to string with series in python pandas

There is no str accessor for datetimes and you can't do dates.astype(str) either, you can call apply and use datetime.strftime:

In [73]:

dates = pd.to_datetime(pd.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.apply(lambda x: x.strftime('%Y-%m-%d'))
Out[73]:
0    2001-01-01
1    2001-03-31
dtype: object

You can change the format of your date strings using whatever you like: strftime() and strptime() Behavior.

Update

As of version 0.17.0 you can do this using dt.strftime

dates.dt.strftime('%Y-%m-%d')

will now work

Using scanner.nextLine()

Rather than placing an extra scanner.nextLine() each time you want to read something, since it seems you want to accept each input on a new line, you might want to instead changing the delimiter to actually match only newlines (instead of any whitespace, as is the default)

import java.util.Scanner;

class ScannerTest {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        scanner.useDelimiter("\\n");

        System.out.print("Enter an index: ");
        int index = scanner.nextInt();

        System.out.print("Enter a sentence: ");
        String sentence = scanner.next();

        System.out.println("\nYour sentence: " + sentence);
        System.out.println("Your index: " + index);
    }
}

Thus, to read a line of input, you only need scanner.next() that has the same behavior delimiter-wise of next{Int, Double, ...}

The difference with the "nextLine() every time" approach, is that the latter will accept, as an index also <space>3, 3<space> and 3<space>whatever while the former only accepts 3 on a line on its own

"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" error

The template it is referring to is the Html helper DisplayFor.

DisplayFor expects to be given an expression that conforms to the rules as specified in the error message.

You are trying to pass in a method chain to be executed and it doesn't like it.

This is a perfect example of where the MVVM (Model-View-ViewModel) pattern comes in handy.

You could wrap up your Trainer model class in another class called TrainerViewModel that could work something like this:

class TrainerViewModel
{
    private Trainer _trainer;

    public string ShortDescription
    {
        get
        {
            return _trainer.Description.ToString().Substring(0, 100);
        }
    }

    public TrainerViewModel(Trainer trainer)
    {
        _trainer = trainer;
    }
}

You would modify your view model class to contain all the properties needed to display that data in the view, hence the name ViewModel.

Then you would modify your controller to return a TrainerViewModel object rather than a Trainer object and change your model type declaration in your view file to TrainerViewModel too.

Convert list to tuple in Python

You might have done something like this:

>>> tuple = 45, 34  # You used `tuple` as a variable here
>>> tuple
(45, 34)
>>> l = [4, 5, 6]
>>> tuple(l)   # Will try to invoke the variable `tuple` rather than tuple type.

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    tuple(l)
TypeError: 'tuple' object is not callable
>>>
>>> del tuple  # You can delete the object tuple created earlier to make it work
>>> tuple(l)
(4, 5, 6)

Here's the problem... Since you have used a tuple variable to hold a tuple (45, 34) earlier... So, now tuple is an object of type tuple now...

It is no more a type and hence, it is no more Callable.

Never use any built-in types as your variable name... You do have any other name to use. Use any arbitrary name for your variable instead...

What are the -Xms and -Xmx parameters when starting JVM?

The flag Xmx specifies the maximum memory allocation pool for a Java Virtual Machine (JVM), while Xms specifies the initial memory allocation pool.

This means that your JVM will be started with Xms amount of memory and will be able to use a maximum of Xmx amount of memory. For example, starting a JVM like below will start it with 256 MB of memory and will allow the process to use up to 2048 MB of memory:

java -Xms256m -Xmx2048m

The memory flag can also be specified in different sizes, such as kilobytes, megabytes, and so on.

-Xmx1024k
-Xmx512m
-Xmx8g

The Xms flag has no default value, and Xmx typically has a default value of 256 MB. A common use for these flags is when you encounter a java.lang.OutOfMemoryError.

When using these settings, keep in mind that these settings are for the JVM's heap, and that the JVM can and will use more memory than just the size allocated to the heap. From Oracle's documentation:

Note that the JVM uses more memory than just the heap. For example Java methods, thread stacks and native handles are allocated in memory separate from the heap, as well as JVM internal data structures.

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

Here is my Approach based on DarKalimHero's Suggestion by selecting only on Explorer.exe processes

Function Get-RdpSessions 
{
    param(
        [string]$computername 
    )

    $processinfo = Get-WmiObject -Query "select * from win32_process where name='explorer.exe'" -ComputerName $computername

    $processinfo | ForEach-Object { $_.GetOwner().User } | Sort-Object -Unique | ForEach-Object { New-Object psobject -Property @{Computer=$computername;LoggedOn=$_} } | Select-Object Computer,LoggedOn
}

How do I list all cron jobs for all users?

This script worked for me in CentOS to list all crons in the environment:

sudo cat /etc/passwd | sed 's/^\([^:]*\):.*$/sudo crontab -u \1 -l 2>\&1/' | grep -v "no crontab for" | sh

Storing sex (gender) in database

There is already an ISO standard for this; no need to invent your own scheme:

http://en.wikipedia.org/wiki/ISO_5218

Per the standard, the column should be called "Sex" and the 'closest' data type would be tinyint with a CHECK constraint or lookup table as appropriate.

How do you tell if caps lock is on using JavaScript?

This jQuery-based answer posted by @user110902 was useful for me. However, I improved it a little to prevent a flaw mentioned in @B_N 's comment: it failed detecting CapsLock while you press Shift:

$('#example').keypress(function(e) { 
    var s = String.fromCharCode( e.which );
    if (( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey )
    ||  ( s.toLowerCase() === s && s.toUpperCase() !== s && e.shiftKey )) {
        alert('caps is on');
    }
});

Like this, it will work even while pressing Shift.

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Removing elements from an array in C

Try this simple code:

#include <stdio.h>
#include <conio.h>
void main(void)
{ 
    clrscr();
    int a[4], i, b;
    printf("enter nos ");
    for (i = 1; i <= 5; i++) {
        scanf("%d", &a[i]);
    }
    for(i = 1; i <= 5; i++) {
        printf("\n%d", a[i]);
    }
    printf("\nenter element you want to delete ");
    scanf("%d", &b);
    for (i = 1; i <= 5; i++) {
        if(i == b) {
            a[i] = i++;
        }
        printf("\n%d", a[i]);
    }
    getch();
}

how to get file path from sd card in android

Environment.getExternalStorageDirectory() will NOT return path to micro SD card Storage.

how to get file path from sd card in android

By sd card, I am assuming that, you meant removable micro SD card.

In API level 19 i.e. in Android version 4.4 Kitkat, they have added File[] getExternalFilesDirs (String type) in Context Class that allows apps to store data/files in micro SD cards.

Android 4.4 is the first release of the platform that has actually allowed apps to use SD cards for storage. Any access to SD cards before API level 19 was through private, unsupported APIs.

Environment.getExternalStorageDirectory() was there from API level 1

getExternalFilesDirs(String type) returns absolute paths to application-specific directories on all shared/external storage devices. It means, it will return paths to both internal and external memory. Generally, second returned path would be the storage path for microSD card (if any).

But note that,

Shared storage may not always be available, since removable media can be ejected by the user. Media state can be checked using getExternalStorageState(File).

There is no security enforced with these files. For example, any application holding WRITE_EXTERNAL_STORAGE can write to these files.

The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.

Where are static variables stored in C and C++?

I don't believe there will be a collision. Using static at the file level (outside functions) marks the variable as local to the current compilation unit (file). It's never visible outside the current file so never has to have a name that can be used externally.

Using static inside a function is different - the variable is only visible to the function (whether static or not), it's just its value is preserved across calls to that function.

In effect, static does two different things depending on where it is. In both cases however, the variable visibility is limited in such a way that you can easily prevent namespace clashes when linking.

Having said that, I believe it would be stored in the DATA section, which tends to have variables that are initialized to values other than zero. This is, of course, an implementation detail, not something mandated by the standard - it only cares about behaviour, not how things are done under the covers.

Select the first 10 rows - Laravel Eloquent

The simplest way in laravel 5 is:

$listings=Listing::take(10)->get();

return view('view.name',compact('listings'));

what is .subscribe in angular?

A Subscription is an object that represents a disposable resource, usually the execution of an Observable. A Subscription has one important method, unsubscribe, that takes no argument and just disposes of the resource held by the subscription.

import { interval } from 'rxjs';

const observable = interval(1000);
const subscription = observable.subscribe(a=> console.log(a));

/** This cancels the ongoing Observable execution which
was started by calling subscribe with an Observer.*/

subscription.unsubscribe();

A Subscription essentially just has an unsubscribe() function to release resources or cancel Observable executions.

import { interval } from 'rxjs';

const observable1 = interval(400);
const observable2 = interval(300);

const subscription = observable1.subscribe(x => console.log('first: ' + x));
const childSubscription = observable2.subscribe(x => console.log('second: ' + x));

subscription.add(childSubscription);

setTimeout(() => {
// It unsubscribes BOTH subscription and childSubscription
subscription.unsubscribe();
}, 1000);

According to the official documentation, Angular should unsubscribe for you, but apparently, there is a bug.

check if array is empty (vba excel)

The problem with VBA is that there are both dynamic and static arrays...

Dynamic Array Example

Dim myDynamicArray() as Variant

Static Array Example

Dim myStaticArray(10) as Variant
Dim myOtherStaticArray(0 To 10) as Variant

Using error handling to check if the array is empty works for a Dynamic Array, but a static array is by definition not empty, there are entries in the array, even if all those entries are empty.

So for clarity's sake, I named my function "IsZeroLengthArray".

    Public Function IsZeroLengthArray(ByRef subject() As Variant) As Boolean
        'Tell VBA to proceed if there is an error to the next line.
        On Error Resume Next
    
        Dim UpperBound As Integer
        Dim ErrorNumber As Long
        Dim ErrorDescription As String
        Dim ErrorSource As String
    
        'If the array is empty this will throw an error because a zero-length 
          'array has no UpperBound (or LowerBound).
        'This only works for dynamic arrays.  If this was a static array there 
          'would be both an upper and lower bound.
        UpperBound = UBound(subject)


        'Store the Error Number and then clear the Error object 
         'because we want VBA to treat unintended errors normally
        ErrorNumber = Err.Number
        ErrorDescription = Err.Description
        ErrorSource = Err.Source
        Err.Clear
        On Error GoTo 0
    
        'Check the Error Object to see if we have a "subscript out of range" error.  
          'If we do (the number is 9) then we can assume that the array is zero-length.
        If ErrorNumber = 9 Then
            IsZeroLengthArray = True

        'If the Error number is something else then 9 we want to raise 
        'that error again...
        ElseIf ErrorNumber <> 0 Then
            Err.Raise ErrorNumber, ErrorSource, ErrorDescription

        'If the Error number is 0 then we have no error and can assume that the
         'array is not of zero-length
        ElseIf ErrorNumber = 0 Then
            IsZeroLengthArray = False
        End If
    End Function

I hope that this helps others as it helped me.

Android and setting alpha for (image) view alpha

Use this form to ancient version of android.

ImageView myImageView;
myImageView = (ImageView) findViewById(R.id.img);

AlphaAnimation alpha = new AlphaAnimation(0.5F, 0.5F);
alpha.setDuration(0); 
alpha.setFillAfter(true); 
myImageView.startAnimation(alpha);

How to reverse MD5 to get the original string?

No, that's not really possible, as

  • there can be more than one string giving the same MD5
  • it was designed to be hard to "reverse"

The goal of the MD5 and its family of hashing functions is

  • to get short "extracts" from long string
  • to make it hard to guess where they come from
  • to make it hard to find collisions, that is other words having the same hash (which is a very similar exigence as the second one)

Think that you can get the MD5 of any string, even very long. And the MD5 is only 16 bytes long (32 if you write it in hexa to store or distribute it more easily). If you could reverse them, you'd have a magical compacting scheme.

This being said, as there aren't so many short strings (passwords...) used in the world, you can test them from a dictionary (that's called "brute force attack") or even google for your MD5. If the word is common and wasn't salted, you have a reasonable chance to succeed...

AttributeError("'str' object has no attribute 'read'")

You need to open the file first. This doesn't work:

json_file = json.load('test.json')

But this works:

f = open('test.json')
json_file = json.load(f)