Programs & Examples On #Non type

What does template <unsigned int N> mean?

You templatize your class based on an 'unsigned int'.

Example:

template <unsigned int N>
class MyArray
{
    public:
    private:
        double    data[N]; // Use N as the size of the array
};

int main()
{
    MyArray<2>     a1;
    MyArray<2>     a2;

    MyArray<4>     b1;

    a1 = a2;  // OK The arrays are the same size.
    a1 = b1;  // FAIL because the size of the array is part of the
              //      template and thus the type, a1 and b1 are different types.
              //      Thus this is a COMPILE time failure.
 }

HTML5 video (mp4 and ogv) problems in Safari and Firefox - but Chrome is all good

Just remove the inner quotes - they confuse Firefox. You can just use "video/ogg; codecs=theora,vorbis".

Also, that markup works in my Minefiled 3.7a5pre, so if your ogv file doesn't play, it may be a bogus file. How did you create it? You might want to register a bug with Firefox.

Understanding the ngRepeat 'track by' expression

a short summary:

track by is used in order to link your data with the DOM generation (and mainly re-generation) made by ng-repeat.

when you add track by you basically tell angular to generate a single DOM element per data object in the given collection

this could be useful when paging and filtering, or any case where objects are added or removed from ng-repeat list.

usually, without track by angular will link the DOM objects with the collection by injecting an expando property - $$hashKey - into your JavaScript objects, and will regenerate it (and re-associate a DOM object) with every change.

full explanation:

http://www.bennadel.com/blog/2556-using-track-by-with-ngrepeat-in-angularjs-1-2.htm

a more practical guide:

http://www.codelord.net/2014/04/15/improving-ng-repeat-performance-with-track-by/

(track by is available in angular > 1.2 )

Pyinstaller setting icons don't change

I had similar problem. If no errors from pyinstaller try to change name of .exe file. It works for me

How to create a localhost server to run an AngularJS project

If you have used Visual Studio Community or any other edition for your angular project , then go to the project folder , first type

C:\Project Folder>npm install -g http-server You will see as follows: + [email protected] added 25 packages in 4.213s

Then type C:\Project Folder>http-server –o

You will see that your application automatically comes up at http://127.0.0.1:8080/

How do I kill a process using Vb.NET or C#?

I opened one Word file, 2. Now I open another word file through vb.net runtime programmatically. 3. I want to kill the second process alone through programmatically. 4. Do not kill first process

Android Studio: Add jar as library?

In the project right click

-> new -> module
-> import jar/AAR package
-> import select the jar file to import
-> click ok -> done

Follow the screenshots below:

1:

Step 1

2:

enter image description here

3:

enter image description here

You will see this:

enter image description here

How to build PDF file from binary string returned from a web-service using javascript

I changed this:

var htmlText = '<embed width=100% height=100%'
                 + ' type="application/pdf"'
                 + ' src="data:application/pdf,'
                 + escape(pdfText)
                 + '"></embed>'; 

to

var htmlText = '<embed width=100% height=100%'
                 + ' type="application/pdf"'
                 + ' src="data:application/pdf;base64,'
                 + escape(pdfText)
                 + '"></embed>'; 

and it worked for me.

Passing std::string by Value or Reference

I believe the normal answer is that it should be passed by value if you need to make a copy of it in your function. Pass it by const reference otherwise.

Here is a good discussion: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/

How do I test if a variable is a number in Bash?

I was looking at the answers and... realized that nobody thought about FLOAT numbers (with dot)!

Using grep is great too.
-E means extended regexp
-q means quiet (doesn't echo)
-qE is the combination of both.

To test directly in the command line:

$ echo "32" | grep -E ^\-?[0-9]?\.?[0-9]+$  
# answer is: 32

$ echo "3a2" | grep -E ^\-?[0-9]?\.?[0-9]+$  
# answer is empty (false)

$ echo ".5" | grep -E ^\-?[0-9]?\.?[0-9]+$  
# answer .5

$ echo "3.2" | grep -E ^\-?[0-9]?\.?[0-9]+$  
# answer is 3.2

Using in a bash script:

check=`echo "$1" | grep -E ^\-?[0-9]*\.?[0-9]+$`

if [ "$check" != '' ]; then    
  # it IS numeric
  echo "Yeap!"
else
  # it is NOT numeric.
  echo "nooop"
fi

To match JUST integers, use this:

# change check line to:
check=`echo "$1" | grep -E ^\-?[0-9]+$`

set date in input type date

Your code would have worked if it had been in this format: YYYY-MM-DD, this is the computer standard for date formats http://en.wikipedia.org/wiki/ISO_8601

R plot: size and resolution

A reproducible example:

the_plot <- function()
{
  x <- seq(0, 1, length.out = 100)
  y <- pbeta(x, 1, 10)
  plot(
    x,
    y,
    xlab = "False Positive Rate",
    ylab = "Average true positive rate",
    type = "l"
  )
}

James's suggestion of using pointsize, in combination with the various cex parameters, can produce reasonable results.

png(
  "test.png",
  width     = 3.25,
  height    = 3.25,
  units     = "in",
  res       = 1200,
  pointsize = 4
)
par(
  mar      = c(5, 5, 2, 2),
  xaxs     = "i",
  yaxs     = "i",
  cex.axis = 2,
  cex.lab  = 2
)
the_plot()
dev.off()

Of course the better solution is to abandon this fiddling with base graphics and use a system that will handle the resolution scaling for you. For example,

library(ggplot2)

ggplot_alternative <- function()
{
  the_data <- data.frame(
    x <- seq(0, 1, length.out = 100),
    y = pbeta(x, 1, 10)
  )

ggplot(the_data, aes(x, y)) +
    geom_line() +
    xlab("False Positive Rate") +
    ylab("Average true positive rate") +
    coord_cartesian(0:1, 0:1)
}

ggsave(
  "ggtest.png",
  ggplot_alternative(),
  width = 3.25,
  height = 3.25,
  dpi = 1200
)

Changing upload_max_filesize on PHP

I've faced the same problem , but I found out that not all the configuration settings could be set using ini_set() function , check this Where a configuration setting may be set

How to pass a parameter to routerLink that is somewhere inside the URL?

constructor(private activatedRoute: ActivatedRoute) {

this.activatedRoute.queryParams.subscribe(params => {
  console.log(params['type'])
  });  }

This works for me!

How to merge a transparent png image with another image using PIL

One can also use blending:

im1 = Image.open("im1.png")
im2 = Image.open("im2.png")
blended = Image.blend(im1, im2, alpha=0.5)
blended.save("blended.png")

Is it correct to use alt tag for an anchor link?

You should use the title attribute for anchor tags if you wish to apply descriptive information similarly as you would for an alt attribute. The title attribute is valid on anchor tags and is serves no other purpose than providing information about the linked page.

W3C recommends that the value of the title attribute should match the value of the title of the linked document but it's not mandatory.

http://www.w3.org/MarkUp/1995-archive/Elements/A.html


Alternatively, and likely to be more beneficial, you can use the ARIA accessibility attribute aria-label (not to be confused with aria-labeledby). aria-label serves the same function as the alt attribute does for images but for non-image elements and includes some measure of optimization since your optimizing for screen readers.

http://www.w3.org/WAI/GL/wiki/Using_aria-label_to_provide_labels_for_objects


If you want to describe an anchor tag though, it's usually appropriate to use the rel or rev tag but your limited to specific values, they should not be used for human readable descriptions.

Rel serves to describe the relationship of the linked page to the current page. (e.g. if the linked page is next in a logical series it would be rel=next)

The rev attribute is essentially the reverse relationship of the rel attribute. Rev describes the relationship of the current page to the linked page.

You can find a list of valid values here: http://microformats.org/wiki/existing-rel-values

Is there a JavaScript strcmp()?

How about:

String.prototype.strcmp = function(s) {
    if (this < s) return -1;
    if (this > s) return 1;
    return 0;
}

Then, to compare s1 with 2:

s1.strcmp(s2)

Configure apache to listen on port other than 80

Run this command if your ufw(Uncomplicatd Firewall) is enabled . Add for Example port 8080

$ sudo ufw allow 8080/tcp

And you can check the status by running

$ sudo ufw status

For more info check : https://linuxhint.com/ubuntu_allow_port_firewall

fcntl substitute on Windows

Although this does not help you right away, there is an alternative that can work with both Unix (fcntl) and Windows (win32 api calls), called: portalocker

It describes itself as a cross-platform (posix/nt) API for flock-style file locking for Python. It basically maps fcntl to win32 api calls.

The original code at http://code.activestate.com/recipes/65203/ can now be installed as a separate package - https://pypi.python.org/pypi/portalocker

what's the default value of char?

I think it is '\u00000' or just '' rather than '\u0000' (The 1st one has 5 zeros while the last one has four zeroes.)

Disable nginx cache for JavaScript files

The expires and add_header directives have no impact on NGINX caching the files, those are purely about what the browser sees.

What you likely want instead is:

location stuffyoudontwanttocache {
    # don't cache it
    proxy_no_cache 1;
    # even if cached, don't try to use it
    proxy_cache_bypass 1; 
}

Though usually .js etc is the thing you would cache, so perhaps you should just disable caching entirely?

How do I install Eclipse Marketplace in Eclipse Classic?

first Help then Install new Software then Switch to the Kepler Repository then General Purpose Tools finally Marketplace Client

How to remove duplicate values from an array in PHP

If you concern in performance and have simple array, use:

array_keys(array_flip($array));

It's many times faster than array_unique.

size of uint8, uint16 and uint32?

It's quite unclear how you are computing the size ("the size in debug mode"?").

Use printf():

printf("the size of c is %u\n", (unsigned int) sizeof c);

Normally you'd print a size_t value (which is the type sizeof returns) with %zu, but if you're using a pre-C99 compiler like Visual Studio that won't work.

You need to find the typedef statements in your code that define the custom names like uint8 and so on; those are not standard so nobody here can know how they're defined in your code.

New C code should use <stdint.h> which gives you uint8_t and so on.

Refresh/reload the content in Div using jquery/ajax

$("#mydiv").load(location.href + " #mydiv");

Always take note of the space just before the second # sign, otherwise the above code will return the whole page nested inside you intended DIV. Always put space.

Parse JSON from JQuery.ajax success data

Well... you are about 3/4 of the way there... you already have your JSON as text.

The problem is that you appear to be handling this string as if it was already a JavaScript object with properties relating to the fields that were transmitted.

It isn't... its just a string.

Queries like "content = data[x].Id;" are bound to fail because JavaScript is not finding these properties attached to the string that it is looking at... again, its JUST a string.

You should be able to simply parse the data as JSON through... yup... the parse method of the JSON object.

myResult = JSON.parse(request.responseText);

Now myResult is a javascript object containing the properties that were transmitted through AJAX.

That should allow you to handle it the way you appear to be trying to.

Looks like JSON.parse was added when ECMA5 was added, so anything fairly modern should be able to handle this natively... if you have to handle fossils, you could also try external libraries to handle this, such as jQuery or JSON2.

For the record, this was already answered by Andy E for someone else HERE.

edit - Saw the request for 'official or credible sources', and probably one of the coders that I find the most credible would be John Resig ~ ECMA5 JSON ~ i would have linked to the actual ECMA5 spec regarding native JSON support, but I would rather refer someone to a master like Resig than a dry specification.

Understanding generators in Python

It helps to make a clear distinction between the function foo, and the generator foo(n):

def foo(n):
    yield n
    yield n+1

foo is a function. foo(6) is a generator object.

The typical way to use a generator object is in a loop:

for n in foo(6):
    print(n)

The loop prints

# 6
# 7

Think of a generator as a resumable function.

yield behaves like return in the sense that values that are yielded get "returned" by the generator. Unlike return, however, the next time the generator gets asked for a value, the generator's function, foo, resumes where it left off -- after the last yield statement -- and continues to run until it hits another yield statement.

Behind the scenes, when you call bar=foo(6) the generator object bar is defined for you to have a next attribute.

You can call it yourself to retrieve values yielded from foo:

next(bar)    # Works in Python 2.6 or Python 3.x
bar.next()   # Works in Python 2.5+, but is deprecated. Use next() if possible.

When foo ends (and there are no more yielded values), calling next(bar) throws a StopInteration error.

Splitting on first occurrence

You can also use str.partition:

>>> text = "123mango abcd mango kiwi peach"

>>> text.partition("mango")
('123', 'mango', ' abcd mango kiwi peach')

>>> text.partition("mango")[-1]
' abcd mango kiwi peach'

>>> text.partition("mango")[-1].lstrip()  # if whitespace strip-ing is needed
'abcd mango kiwi peach'

The advantage of using str.partition is that it's always gonna return a tuple in the form:

(<pre>, <separator>, <post>)

So this makes unpacking the output really flexible as there's always going to be 3 elements in the resulting tuple.

Causes of getting a java.lang.VerifyError

After updating Gradle in Android Studio 3.6.1 crashes happened on API 19 in release build.

There was a Glide library error. Solution is to rewrite proguard-rules.txt.

Also downgrading Gradle works (classpath 'com.android.tools.build:gradle:3.5.3'), but it is an outdated solution, don't use it.

Reusing a PreparedStatement multiple times

The second way is a tad more efficient, but a much better way is to execute them in batches:

public void executeBatch(List<Entity> entities) throws SQLException { 
    try (
        Connection connection = dataSource.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL);
    ) {
        for (Entity entity : entities) {
            statement.setObject(1, entity.getSomeProperty());
            // ...

            statement.addBatch();
        }

        statement.executeBatch();
    }
}

You're however dependent on the JDBC driver implementation how many batches you could execute at once. You may for example want to execute them every 1000 batches:

public void executeBatch(List<Entity> entities) throws SQLException { 
    try (
        Connection connection = dataSource.getConnection();
        PreparedStatement statement = connection.prepareStatement(SQL);
    ) {
        int i = 0;

        for (Entity entity : entities) {
            statement.setObject(1, entity.getSomeProperty());
            // ...

            statement.addBatch();
            i++;

            if (i % 1000 == 0 || i == entities.size()) {
                statement.executeBatch(); // Execute every 1000 items.
            }
        }
    }
}

As to the multithreaded environments, you don't need to worry about this if you acquire and close the connection and the statement in the shortest possible scope inside the same method block according the normal JDBC idiom using try-with-resources statement as shown in above snippets.

If those batches are transactional, then you'd like to turn off autocommit of the connection and only commit the transaction when all batches are finished. Otherwise it may result in a dirty database when the first bunch of batches succeeded and the later not.

public void executeBatch(List<Entity> entities) throws SQLException { 
    try (Connection connection = dataSource.getConnection()) {
        connection.setAutoCommit(false);

        try (PreparedStatement statement = connection.prepareStatement(SQL)) {
            // ...

            try {
                connection.commit();
            } catch (SQLException e) {
                connection.rollback();
                throw e;
            }
        }
    }
}

how to make password textbox value visible when hover an icon

Complete example below. I just love the copy/paste :)

HTML

<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
           <div class="panel panel-default">
              <div class="panel-body">
                  <form class="form-horizontal" method="" action="">

                     <div class="form-group">
                        <label class="col-md-4 control-label">Email</label>
                           <div class="col-md-6">
                               <input type="email" class="form-control" name="email" value="">
                           </div>
                     </div>
                     <div class="form-group">
                       <label class="col-md-4 control-label">Password</label>
                          <div class="col-md-6">
                              <input id="password-field" type="password" class="form-control" name="password" value="secret">
                              <span toggle="#password-field" class="fa fa-lg fa-eye field-icon toggle-password"></span>
                          </div>
                     </div>
                 </form>
              </div>
           </div>
      </div>
  </div>

CSS

.field-icon {
  float: right;
  margin-right: 8px;
  margin-top: -23px;
  position: relative;
  z-index: 2;
  cursor:pointer;
}

.container{
  padding-top:50px;
  margin: auto;
}

JS

$(".toggle-password").click(function() {
   $(this).toggleClass("fa-eye fa-eye-slash");
   var input = $($(this).attr("toggle"));
   if (input.attr("type") == "password") {
     input.attr("type", "text");
   } else {
     input.attr("type", "password");
   }
});

Try it here: https://codepen.io/anon/pen/ZoMQZP

Generating 8-character only UUIDs

First: Even the unique IDs generated by java UUID.randomUUID or .net GUID are not 100% unique. Especialy UUID.randomUUID is "only" a 128 bit (secure) random value. So if you reduce it to 64 bit, 32 bit, 16 bit (or even 1 bit) then it becomes simply less unique.

So it is at least a risk based decisions, how long your uuid must be.

Second: I assume that when you talk about "only 8 characters" you mean a String of 8 normal printable characters.

If you want a unique string with length 8 printable characters you could use a base64 encoding. This means 6bit per char, so you get 48bit in total (possible not very unique - but maybe it is ok for you application)

So the way is simple: create a 6 byte random array

 SecureRandom rand;
 // ...
 byte[] randomBytes = new byte[16];
 rand.nextBytes(randomBytes);

And then transform it to a Base64 String, for example by org.apache.commons.codec.binary.Base64

BTW: it depends on your application if there is a better way to create "uuid" then by random. (If you create a the UUIDs only once per second, then it is a good idea to add a time stamp) (By the way: if you combine (xor) two random values, the result is always at least as random as the most random of the both).

Authenticate with GitHub using a token

For those coming from GitLab what's worked for me:

Step 1.

add remote

git remote add origin https://<access-token-name>:<access-token>@gitlab.com/path/to/project.git

Step 2.

pull once

https://<access-token-name>:<access-token>@gitlab.com/path/to/project.git

now you are able to read/write to/from repository

How to check identical array in most efficient way?

So, what's wrong with checking each element iteratively?

function arraysEqual(arr1, arr2) {
    if(arr1.length !== arr2.length)
        return false;
    for(var i = arr1.length; i--;) {
        if(arr1[i] !== arr2[i])
            return false;
    }

    return true;
}

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

Code for WebTestPlugIn

public class Protocols : WebTestPlugin
{

    public override void PreRequest(object sender, PreRequestEventArgs e)
    {
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

    }

}

Internet Explorer 11- issue with security certificate error prompt

This behavior is related to Zone that is set - Internet/Intranet/etc and corresponding Security Level

You can change this by setting less secure Security Level (not recommended) or by customizing Display Mixed Content property

You can do that by following steps:

  1. Click on Gear icon at the top of the browser window.
  2. Select Internet Options.
  3. Select the Security tab at the top.
  4. Click the Custom Level... button.
  5. Scroll about halfway down to the Miscellaneous heading (denoted by a "blank page" icon).
  6. Under this heading is the option Display Mixed Content; set this to Enable/Prompt.
  7. Click OK, then Yes when prompted to confirm the change, then OK to close the Options window.
  8. Close and restart the browser.

enter image description here

How to select rows for a specific date, ignoring time in SQL Server

Something like this:

select 
  * 
from sales 
where salesDate >= '11/11/2010' 
  AND salesDate < (Convert(datetime, '11/11/2010') + 1)

Inner join of DataTables in C#

This is my code. Not perfect, but working good. I hope it helps somebody:

    static System.Data.DataTable DtTbl (System.Data.DataTable[] dtToJoin)
    {
        System.Data.DataTable dtJoined = new System.Data.DataTable();

        foreach (System.Data.DataColumn dc in dtToJoin[0].Columns)
            dtJoined.Columns.Add(dc.ColumnName);

        foreach (System.Data.DataTable dt in dtToJoin)
            foreach (System.Data.DataRow dr1 in dt.Rows)
            {
                System.Data.DataRow dr = dtJoined.NewRow();
                foreach (System.Data.DataColumn dc in dtToJoin[0].Columns)
                    dr[dc.ColumnName] = dr1[dc.ColumnName];

                dtJoined.Rows.Add(dr);
            }

        return dtJoined;
    }

How to check if a std::string is set or not?

There is no "unset" state for std::string, it is always set to something.

How to verify Facebook access token?

You can simply request https://graph.facebook.com/me?access_token=xxxxxxxxxxxxxxxxx if you get an error, the token is invalid. If you get a JSON object with an id property then it is valid.

Unfortunately this will only tell you if your token is valid, not if it came from your app.

iOS download and save image inside app

Although it is true that the other answers here will work, they really aren't solutions that should ever be used in production code. (at least not without modification)

Problems

The problem with these answers is that if they are implemented as is and are not called from a background thread, they will block the main thread while downloading and saving the image. This is bad.

If the main thread is blocked, UI updates won't happen until the downloading/saving of the image is complete. As an example of what this means, say you add a UIActivityIndicatorView to your app to show the user that the download is still in progress (I will be using this as an example throughout this answer) with the following rough control flow:

  1. Object responsible for starting the download is loaded.
  2. Tell the activity indicator to start animating.
  3. Start the synchronous download process using +[NSData dataWithContentsOfURL:]
  4. Save the data (image) that was just downloaded.
  5. Tell the activity indicator to stop animating.

Now, this might seem like reasonable control flow, but it is disguising a critical problem.

When you call the activity indicator's startAnimating method on the main (UI) thread, the UI updates for this event won't actually happen until the next time the main run loop updates, and this is where the first major problem is.

Before this update has a chance to happen, the download is triggered, and since this is a synchronous operation, it blocks the main thread until it has finished download (saving has the same problem). This will actually prevent the activity indicator from starting its animation. After that you call the activity indicator's stopAnimating method and expect all to be good, but it isn't.

At this point, you'll probably find yourself wondering the following.

Why doesn't my activity indicator ever show up?

Well, think about it like this. You tell the indicator to start but it doesn't get a chance before the download starts. After the download completes, you tell the indicator to stop animating. Since the main thread was blocked through the whole operation, the behavior you actually see is more along the lines telling the indicator to start and then immediately telling it to stop, even though there was a (possibly) large download task in between.

Now, in the best case scenario, all this does is cause a poor user experience (still really bad). Even if you think this isn't a big deal because you're only downloading a small image and the download happens almost instantaneously, that won't always be the case. Some of your users may have slow internet connections, or something may be wrong server side keeping the download from starting immediately/at all.

In both of these cases, the app won't be able to process UI updates, or even touch events while your download task sits around twiddling its thumbs waiting for the download to complete or for the server to respond to its request.

What this means is that synchronously downloading from the main thread prevents you from possibly implementing anything to indicate to the user that a download is currently in progress. And since touch events are processed on the main thread as well, this throws out the possibility of adding any kind of cancel button as well.

Then in the worst case scenario, you'll start receiving crash reports stating the following.

Exception Type: 00000020 Exception Codes: 0x8badf00d

These are easy to identify by the exception code 0x8badf00d, which can be read as "ate bad food". This exception is thrown by the watch dog timer, whose job is to watch for long running tasks that block the main thread, and to kill the offending app if this goes on for too long. Arguably, this is still a poor user experience issue, but if this starts to occur, the app has crossed the line between bad user experience, and terrible user experience.

Here's some more info on what can cause this to happen from Apple's Technical Q&A about synchronous networking (shortened for brevity).

The most common cause for watchdog timeout crashes in a network application is synchronous networking on the main thread. There are four contributing factors here:

  1. synchronous networking — This is where you make a network request and block waiting for the response.
  2. main thread — Synchronous networking is less than ideal in general, but it causes specific problems if you do it on the main thread. Remember that the main thread is responsible for running the user interface. If you block the main thread for any significant amount of time, the user interface becomes unacceptably unresponsive.
  3. long timeouts — If the network just goes away (for example, the user is on a train which goes into a tunnel), any pending network request won't fail until some timeout has expired....

...

  1. watchdog — In order to keep the user interface responsive, iOS includes a watchdog mechanism. If your application fails to respond to certain user interface events (launch, suspend, resume, terminate) in time, the watchdog will kill your application and generate a watchdog timeout crash report. The amount of time the watchdog gives you is not formally documented, but it's always less than a network timeout.

One tricky aspect of this problem is that it's highly dependent on the network environment. If you always test your application in your office, where network connectivity is good, you'll never see this type of crash. However, once you start deploying your application to end users—who will run it in all sorts of network environments—crashes like this will become common.

Now at this point, I'll stop rambling about why the provided answers might be problematic and will start offering up some alternative solutions. Keep in mind that I've used the URL of a small image in these examples and you'll notice a larger difference when using a higher resolution image.


Solutions

I'll start by showing a safe version of the other answers, with the addition of how to handle UI updates. This will be the first of several examples, all of which will assume that the class in which they are implemented has valid properties for a UIImageView, a UIActivityIndicatorView, as well as the documentsDirectoryURL method to access the documents directory. In production code, you may want to implement your own method to access the documents directory as a category on NSURL for better code reusability, but for these examples, this will be fine.

- (NSURL *)documentsDirectoryURL
{
    NSError *error = nil;
    NSURL *url = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory
                                                        inDomain:NSUserDomainMask
                                               appropriateForURL:nil
                                                          create:NO
                                                           error:&error];
    if (error) {
        // Figure out what went wrong and handle the error.
    }
    
    return url;
}

These examples will also assume that the thread that they start off on is the main thread. This will likely be the default behavior unless you start your download task from somewhere like the callback block of some other asynchronous task. If you start your download in a typical place, like a lifecycle method of a view controller (i.e. viewDidLoad, viewWillAppear:, etc.) this will produce the expected behavior.

This first example will use the +[NSData dataWithContentsOfURL:] method, but with some key differences. For one, you'll notice that in this example, the very first call we make is to tell the activity indicator to start animating, then there is an immediate difference between this and the synchronous examples. Immediately, we use dispatch_async(), passing in the global concurrent queue to move execution to the background thread.

At this point, you've already greatly improved your download task. Since everything within the dispatch_async() block will now happen off the main thread, your interface will no longer lock up, and your app will be free to respond to touch events.

What is important to notice here is that all of the code within this block will execute on the background thread, up until the point where the downloading/saving of the image was successful, at which point you might want to tell the activity indicator to stopAnimating, or apply the newly saved image to a UIImageView. Either way, these are updates to the UI, meaning you must dispatch back the the main thread using dispatch_get_main_queue() to perform them. Failing to do so results in undefined behavior, which may cause the UI to update after an unexpected period of time, or may even cause a crash. Always make sure you move back to the main thread before performing UI updates.

// Start the activity indicator before moving off the main thread
[self.activityIndicator startAnimating];
// Move off the main thread to start our blocking tasks.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Create the image URL from a known string.
    NSURL *imageURL = [NSURL URLWithString:@"http://www.google.com/images/srpr/logo3w.png"];
    
    NSError *downloadError = nil;
    // Create an NSData object from the contents of the given URL.
    NSData *imageData = [NSData dataWithContentsOfURL:imageURL
                                              options:kNilOptions
                                                error:&downloadError];
    // ALWAYS utilize the error parameter!
    if (downloadError) {
        // Something went wrong downloading the image. Figure out what went wrong and handle the error.
        // Don't forget to return to the main thread if you plan on doing UI updates here as well.
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.activityIndicator stopAnimating];
            NSLog(@"%@",[downloadError localizedDescription]);
        });
    } else {
        // Get the path of the application's documents directory.
        NSURL *documentsDirectoryURL = [self documentsDirectoryURL];
        // Append the desired file name to the documents directory path.
        NSURL *saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:@"GCD.png"];

        NSError *saveError = nil;
        BOOL writeWasSuccessful = [imageData writeToURL:saveLocation
                                                options:kNilOptions
                                                  error:&saveError];
        // Successful or not we need to stop the activity indicator, so switch back the the main thread.
        dispatch_async(dispatch_get_main_queue(), ^{
            // Now that we're back on the main thread, you can make changes to the UI.
            // This is where you might display the saved image in some image view, or
            // stop the activity indicator.
            
            // Check if saving the file was successful, once again, utilizing the error parameter.
            if (writeWasSuccessful) {
                // Get the saved image data from the file.
                NSData *imageData = [NSData dataWithContentsOfURL:saveLocation];
                // Set the imageView's image to the image we just saved.
                self.imageView.image = [UIImage imageWithData:imageData];
            } else {
                NSLog(@"%@",[saveError localizedDescription]);
                // Something went wrong saving the file. Figure out what went wrong and handle the error.
            }
            
            [self.activityIndicator stopAnimating];
        });
    }
});

Now keep in mind, that the method shown above is still not an ideal solution considering it can't be cancelled prematurely, it gives you no indication of the progress of the download, it can't handle any kind of authentication challenge, it can't be given a specific timeout interval, etc. (lots and lots of reasons). I'll cover a few of the better options below.

In these examples, I'll only be covering solutions for apps targeting iOS 7 and up considering (at time of writing) iOS 8 is the current major release, and Apple is suggesting only supporting versions N and N-1. If you need to support older iOS versions, I recommend looking into the NSURLConnection class, as well as the 1.0 version of AFNetworking. If you look at the revision history of this answer, you can find basic examples using NSURLConnection and ASIHTTPRequest, although it should be noted that ASIHTTPRequest is no longer being maintained, and should not be used for new projects.


NSURLSession

Lets start with NSURLSession, which was introduced in iOS 7, and greatly improves the ease with which networking can be done in iOS. With NSURLSession, you can easily perform asynchronous HTTP requests with a callback block and handle authentication challenges with its delegate. But what makes this class really special is that it also allows for download tasks to continue running even if the application is sent to the background, gets terminated, or even crashes. Here's a basic example of its usage.

// Start the activity indicator before starting the download task.
[self.activityIndicator startAnimating];

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// Use a session with a custom configuration
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
// Create the image URL from some known string.
NSURL *imageURL = [NSURL URLWithString:@"http://www.google.com/images/srpr/logo3w.png"];
// Create the download task passing in the URL of the image.
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:imageURL completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
    // Get information about the response if neccessary.
    if (error) {
        NSLog(@"%@",[error localizedDescription]);
        // Something went wrong downloading the image. Figure out what went wrong and handle the error.
        // Don't forget to return to the main thread if you plan on doing UI updates here as well.
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.activityIndicator stopAnimating];
        });
    } else {
        NSError *openDataError = nil;
        NSData *downloadedData = [NSData dataWithContentsOfURL:location
                                                       options:kNilOptions
                                                         error:&openDataError];
        if (openDataError) {
            // Something went wrong opening the downloaded data. Figure out what went wrong and handle the error.
            // Don't forget to return to the main thread if you plan on doing UI updates here as well.
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"%@",[openDataError localizedDescription]);
                [self.activityIndicator stopAnimating];
            });
        } else {
            // Get the path of the application's documents directory.
            NSURL *documentsDirectoryURL = [self documentsDirectoryURL];
            // Append the desired file name to the documents directory path.
            NSURL *saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:@"NSURLSession.png"];
            NSError *saveError = nil;
            
            BOOL writeWasSuccessful = [downloadedData writeToURL:saveLocation
                                                          options:kNilOptions
                                                            error:&saveError];
            // Successful or not we need to stop the activity indicator, so switch back the the main thread.
            dispatch_async(dispatch_get_main_queue(), ^{
                // Now that we're back on the main thread, you can make changes to the UI.
                // This is where you might display the saved image in some image view, or
                // stop the activity indicator.
                
                // Check if saving the file was successful, once again, utilizing the error parameter.
                if (writeWasSuccessful) {
                    // Get the saved image data from the file.
                    NSData *imageData = [NSData dataWithContentsOfURL:saveLocation];
                    // Set the imageView's image to the image we just saved.
                    self.imageView.image = [UIImage imageWithData:imageData];
                } else {
                    NSLog(@"%@",[saveError localizedDescription]);
                    // Something went wrong saving the file. Figure out what went wrong and handle the error.
                }
                
                [self.activityIndicator stopAnimating];
            });
        }
    }
}];

// Tell the download task to resume (start).
[task resume];

From this you'll notice that the downloadTaskWithURL: completionHandler: method returns an instance of NSURLSessionDownloadTask, on which an instance method -[NSURLSessionTask resume] is called. This is the method that actually tells the download task to start. This means that you can spin up your download task, and if desired, hold off on starting it (if needed). This also means that as long as you store a reference to the task, you can also utilize its cancel and suspend methods to cancel or pause the task if need be.

What's really cool about NSURLSessionTasks is that with a little bit of KVO, you can monitor the values of its countOfBytesExpectedToReceive and countOfBytesReceived properties, feed these values to an NSByteCountFormatter, and easily create a download progress indicator to your user with human readable units (e.g. 42 KB of 100 KB).

Before I move away from NSURLSession though, I'd like to point out that the ugliness of having to dispatch_async back to the main threads at several different points in the download's callback block can be avoided. If you chose to go this route, you can initialize the session with its initializer that allows you to specify the delegate, as well as the delegate queue. This will require you to use the delegate pattern instead of the callback blocks, but this may be beneficial because it is the only way to support background downloads.

NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration
                                                      delegate:self
                                                 delegateQueue:[NSOperationQueue mainQueue]];

AFNetworking 2.0

If you've never heard of AFNetworking, it is IMHO the end-all of networking libraries. It was created for Objective-C, but it works in Swift as well. In the words of its author:

AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of the Foundation URL Loading System, extending the powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.

AFNetworking 2.0 supports iOS 6 and up, but in this example, I will be using its AFHTTPSessionManager class, which requires iOS 7 and up due to its usage of all the new APIs around the NSURLSession class. This will become obvious when you read the example below, which shares a lot of code with the NSURLSession example above.

There are a few differences that I'd like to point out though. To start off, instead of creating your own NSURLSession, you'll create an instance of AFURLSessionManager, which will internally manage a NSURLSession. Doing so allows you take advantage of some of its convenience methods like -[AFURLSessionManager downloadTaskWithRequest:progress:destination:completionHandler:]. What is interesting about this method is that it lets you fairly concisely create a download task with a given destination file path, a completion block, and an input for an NSProgress pointer, on which you can observe information about the progress of the download. Here's an example.

// Use the default session configuration for the manager (background downloads must use the delegate APIs)
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
// Use AFNetworking's NSURLSessionManager to manage a NSURLSession.
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

// Create the image URL from some known string.
NSURL *imageURL = [NSURL URLWithString:@"http://www.google.com/images/srpr/logo3w.png"];
// Create a request object for the given URL.
NSURLRequest *request = [NSURLRequest requestWithURL:imageURL];
// Create a pointer for a NSProgress object to be used to determining download progress.
NSProgress *progress = nil;

// Create the callback block responsible for determining the location to save the downloaded file to.
NSURL *(^destinationBlock)(NSURL *targetPath, NSURLResponse *response) = ^NSURL *(NSURL *targetPath, NSURLResponse *response) {
    // Get the path of the application's documents directory.
    NSURL *documentsDirectoryURL = [self documentsDirectoryURL];
    NSURL *saveLocation = nil;
    
    // Check if the response contains a suggested file name
    if (response.suggestedFilename) {
        // Append the suggested file name to the documents directory path.
        saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:response.suggestedFilename];
    } else {
        // Append the desired file name to the documents directory path.
        saveLocation = [documentsDirectoryURL URLByAppendingPathComponent:@"AFNetworking.png"];
    }

    return saveLocation;
};

// Create the completion block that will be called when the image is done downloading/saving.
void (^completionBlock)(NSURLResponse *response, NSURL *filePath, NSError *error) = ^void (NSURLResponse *response, NSURL *filePath, NSError *error) {
    dispatch_async(dispatch_get_main_queue(), ^{
        // There is no longer any reason to observe progress, the download has finished or cancelled.
        [progress removeObserver:self
                      forKeyPath:NSStringFromSelector(@selector(fractionCompleted))];
        
        if (error) {
            NSLog(@"%@",error.localizedDescription);
            // Something went wrong downloading or saving the file. Figure out what went wrong and handle the error.
        } else {
            // Get the data for the image we just saved.
            NSData *imageData = [NSData dataWithContentsOfURL:filePath];
            // Get a UIImage object from the image data.
            self.imageView.image = [UIImage imageWithData:imageData];
        }
    });
};

// Create the download task for the image.
NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request
                                                         progress:&progress
                                                      destination:destinationBlock
                                                completionHandler:completionBlock];
// Start the download task.
[task resume];

// Begin observing changes to the download task's progress to display to the user.
[progress addObserver:self
           forKeyPath:NSStringFromSelector(@selector(fractionCompleted))
              options:NSKeyValueObservingOptionNew
              context:NULL];

Of course since we've added the class containing this code as an observer to one of the NSProgress instance's properties, you'll have to implement the -[NSObject observeValueForKeyPath:ofObject:change:context:] method. In this case, I've included an example of how you might update a progress label to display the download's progress. It's really easy. NSProgress has an instance method localizedDescription which will display progress information in a localized, human readable format.

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    // We only care about updates to fractionCompleted
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(fractionCompleted))]) {
        NSProgress *progress = (NSProgress *)object;
        // localizedDescription gives a string appropriate for display to the user, i.e. "42% completed"
        self.progressLabel.text = progress.localizedDescription;
    } else {
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                               change:change
                              context:context];
    }
}

Don't forget, if you want to use AFNetworking in your project, you'll need to follow its installation instructions and be sure to #import <AFNetworking/AFNetworking.h>.

Alamofire

And finally, I'd like to give a final example using Alamofire. This is a the library that makes networking in Swift a cake-walk. I'm out of characters to go into great detail about the contents of this sample, but it does pretty much the same thing as the last examples, just in an arguably more beautiful way.

// Create the destination closure to pass to the download request. I haven't done anything with them
// here but you can utilize the parameters to make adjustments to the file name if neccessary.
let destination = { (url: NSURL!, response: NSHTTPURLResponse!) -> NSURL in
    var error: NSError?
    // Get the documents directory
    let documentsDirectory = NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory,
        inDomain: .UserDomainMask,
        appropriateForURL: nil,
        create: false,
        error: &error
    )
    
    if let error = error {
        // This could be bad. Make sure you have a backup plan for where to save the image.
        println("\(error.localizedDescription)")
    }
    
    // Return a destination of .../Documents/Alamofire.png
    return documentsDirectory!.URLByAppendingPathComponent("Alamofire.png")
}

Alamofire.download(.GET, "http://www.google.com/images/srpr/logo3w.png", destination)
    .validate(statusCode: 200..<299) // Require the HTTP status code to be in the Successful range.
    .validate(contentType: ["image/png"]) // Require the content type to be image/png.
    .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
        // Create an NSProgress object to represent the progress of the download for the user.
        let progress = NSProgress(totalUnitCount: totalBytesExpectedToRead)
        progress.completedUnitCount = totalBytesRead
        
        dispatch_async(dispatch_get_main_queue()) {
            // Move back to the main thread and update some progress label to show the user the download is in progress.
            self.progressLabel.text = progress.localizedDescription
        }
    }
    .response { (request, response, _, error) in
        if error != nil {
            // Something went wrong. Handle the error.
        } else {
            // Open the newly saved image data.
            if let imageData = NSData(contentsOfURL: destination(nil, nil)) {
                dispatch_async(dispatch_get_main_queue()) {
                    // Move back to the main thread and add the image to your image view.
                    self.imageView.image = UIImage(data: imageData)
                }
            }
        }
    }

How to get a path to the desktop for current user in C#?

 string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
 string extension = ".log";
 filePath += @"\Error Log\" + extension;
 if (!Directory.Exists(filePath))
 {
      Directory.CreateDirectory(filePath);
 }

How to create a new instance from a class object in Python

I figured out the answer to the question I had that brought me to this page. Since no one has actually suggested the answer to my question, I thought I'd post it.

class k:
  pass

a = k()
k2 = a.__class__
a2 = k2()

At this point, a and a2 are both instances of the same class (class k).

Deleting DataFrame row in Pandas based on column value

The best way to do this is with boolean masking:

In [56]: df
Out[56]:
     line_date  daysago  line_race  rating    raw  wrating
0   2007-03-31       62         11      56  1.000   56.000
1   2007-03-10       83         11      67  1.000   67.000
2   2007-02-10      111          9      66  1.000   66.000
3   2007-01-13      139         10      83  0.881   73.096
4   2006-12-23      160         10      88  0.793   69.787
5   2006-11-09      204          9      52  0.637   33.106
6   2006-10-22      222          8      66  0.582   38.408
7   2006-09-29      245          9      70  0.519   36.318
8   2006-09-16      258         11      68  0.486   33.063
9   2006-08-30      275          8      72  0.447   32.160
10  2006-02-11      475          5      65  0.165   10.698
11  2006-01-13      504          0      70  0.142    9.969
12  2006-01-02      515          0      64  0.135    8.627
13  2005-12-06      542          0      70  0.118    8.246
14  2005-11-29      549          0      70  0.114    7.963
15  2005-11-22      556          0      -1  0.110   -0.110
16  2005-11-01      577          0      -1  0.099   -0.099
17  2005-10-20      589          0      -1  0.093   -0.093
18  2005-09-27      612          0      -1  0.083   -0.083
19  2005-09-07      632          0      -1  0.075   -0.075
20  2005-06-12      719          0      69  0.049    3.360
21  2005-05-29      733          0      -1  0.045   -0.045
22  2005-05-02      760          0      -1  0.040   -0.040
23  2005-04-02      790          0      -1  0.034   -0.034
24  2005-03-13      810          0      -1  0.031   -0.031
25  2004-11-09      934          0      -1  0.017   -0.017

In [57]: df[df.line_race != 0]
Out[57]:
     line_date  daysago  line_race  rating    raw  wrating
0   2007-03-31       62         11      56  1.000   56.000
1   2007-03-10       83         11      67  1.000   67.000
2   2007-02-10      111          9      66  1.000   66.000
3   2007-01-13      139         10      83  0.881   73.096
4   2006-12-23      160         10      88  0.793   69.787
5   2006-11-09      204          9      52  0.637   33.106
6   2006-10-22      222          8      66  0.582   38.408
7   2006-09-29      245          9      70  0.519   36.318
8   2006-09-16      258         11      68  0.486   33.063
9   2006-08-30      275          8      72  0.447   32.160
10  2006-02-11      475          5      65  0.165   10.698

UPDATE: Now that pandas 0.13 is out, another way to do this is df.query('line_race != 0').

What's the maximum value for an int in PHP?

32-bit builds of PHP:

  • Integers can be from -2,147,483,648 to 2,147,483,647 (~ ± 2 billion)

64-bit builds of PHP:

  • Integers can be from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (~ ± 9 quintillion)

Numbers are inclusive.

Note: some 64-bit builds once used 32-bit integers, particularly older Windows builds of PHP

Values outside of these ranges are represented by floating point values, as are non-integer values within these ranges. The interpreter will automatically determine when this switch to floating point needs to happen based on whether the result value of a calculation can't be represented as an integer.

PHP has no support for "unsigned" integers as such, limiting the maximum value of all integers to the range of a "signed" integer.

Print to the same line and not a new line?

If you are using Spyder, the lines just print continuously with all the previous solutions. A way to avoid that is using:

for i in range(1000):
    print('\r' + str(round(i/len(df)*100,1)) + '% complete', end='')
    sys.stdout.flush()

Use Ant for running program with command line arguments

The only effective mechanism for passing parameters into a build is to use Java properties:

ant -Done=1 -Dtwo=2

The following example demonstrates how you can check and ensure the expected parameters have been passed into the script

<project name="check" default="build">

    <condition property="params.set">
        <and>
            <isset property="one"/>
            <isset property="two"/>
        </and>
    </condition>

    <target name="check">
        <fail unless="params.set">
        Must specify the parameters: one, two
        </fail>
    </target>

    <target name="build" depends="check">
        <echo>
        one = ${one}
        two = ${two}
        </echo>
    </target>

</project>

The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

  1. Why is this happening?

    The entire ext/mysql PHP extension, which provides all functions named with the prefix mysql_, was officially deprecated in PHP v5.5.0 and removed in PHP v7.

    It was originally introduced in PHP v2.0 (November 1997) for MySQL v3.20, and no new features have been added since 2006. Coupled with the lack of new features are difficulties in maintaining such old code amidst complex security vulnerabilities.

    The manual has contained warnings against its use in new code since June 2011.

  2. How can I fix it?

    As the error message suggests, there are two other MySQL extensions that you can consider: MySQLi and PDO_MySQL, either of which can be used instead of ext/mysql. Both have been in PHP core since v5.0, so if you're using a version that is throwing these deprecation errors then you can almost certainly just start using them right away—i.e. without any installation effort.

    They differ slightly, but offer a number of advantages over the old extension including API support for transactions, stored procedures and prepared statements (thereby providing the best way to defeat SQL injection attacks). PHP developer Ulf Wendel has written a thorough comparison of the features.

    Hashphp.org has an excellent tutorial on migrating from ext/mysql to PDO.

  3. I understand that it's possible to suppress deprecation errors by setting error_reporting in php.ini to exclude E_DEPRECATED:

    error_reporting = E_ALL ^ E_DEPRECATED
    

    What will happen if I do that?

    Yes, it is possible to suppress such error messages and continue using the old ext/mysql extension for the time being. But you really shouldn't do this—this is a final warning from the developers that the extension may not be bundled with future versions of PHP (indeed, as already mentioned, it has been removed from PHP v7). Instead, you should take this opportunity to migrate your application now, before it's too late.

    Note also that this technique will suppress all E_DEPRECATED messages, not just those to do with the ext/mysql extension: therefore you may be unaware of other upcoming changes to PHP that would affect your application code. It is, of course, possible to only suppress errors that arise on the expression at issue by using PHP's error control operator—i.e. prepending the relevant line with @—however this will suppress all errors raised by that expression, not just E_DEPRECATED ones.


What should you do?

  • You are starting a new project.

    There is absolutely no reason to use ext/mysql—choose one of the other, more modern, extensions instead and reap the rewards of the benefits they offer.

  • You have (your own) legacy codebase that currently depends upon ext/mysql.

    It would be wise to perform regression testing: you really shouldn't be changing anything (especially upgrading PHP) until you have identified all of the potential areas of impact, planned around each of them and then thoroughly tested your solution in a staging environment.

    • Following good coding practice, your application was developed in a loosely integrated/modular fashion and the database access methods are all self-contained in one place that can easily be swapped out for one of the new extensions.

      Spend half an hour rewriting this module to use one of the other, more modern, extensions; test thoroughly. You can later introduce further refinements to reap the rewards of the benefits they offer.

    • The database access methods are scattered all over the place and cannot easily be swapped out for one of the new extensions.

      Consider whether you really need to upgrade to PHP v5.5 at this time.

      You should begin planning to replace ext/mysql with one of the other, more modern, extensions in order that you can reap the rewards of the benefits they offer; you might also use it as an opportunity to refactor your database access methods into a more modular structure.

      However, if you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

  • You are using a third party project that depends upon ext/mysql.

    Consider whether you really need to upgrade to PHP v5.5 at this time.

    Check whether the developer has released any fixes, workarounds or guidance in relation to this specific issue; or, if not, pressure them to do so by bringing this matter to their attention. If you have an urgent need to upgrade PHP right away, you might consider suppressing deprecation errors for the time being: but first be sure to identify any other deprecation errors that are also being thrown.

    It is absolutely essential to perform regression testing.

Excel formula to reference 'CELL TO THE LEFT'

The shortest most compatible version is:

=INDIRECT("RC[-1]",0)

"RC[-1]" means one column to the left. "R[1]C[-1]" is bottom-left.

The second parameter 0 means that the first parameter is interpreted using R1C1 notation.

The other options:

=OFFSET(INDIRECT(ADDRESS(ROW(), COLUMN())),0,-1)

Too long in my opinion. But useful if the relative value is dynamic/derived from another cell. e.g.:

=OFFSET(INDIRECT(ADDRESS(ROW(), COLUMN())),0, A1)

The most simple option:

= RC[-1]

has the disadvantage that you need to turn on R1C1 notation using options, which is a no-go when other people have to use the excel.

Bootstrap select dropdown list placeholder

All this options are.... improvisations. Bootstrap already offers a solution for this. If you want to change the placeholder for all your dropdown elements you can change the value of

noneSelectedText in the bootstrap file.

To change individualy, you can use TITLE parameter.

example:

<div class="form-group">
          <label class="control-label col-xs-2" id="country">Continent:</label>
          <div class="col-xs-9">
            <select name="zones[]" class="selectpicker" title="All continents" id="zones" multiple >
              <option value="Africa">Africa</option>
              <option value="Asia">Asia</option>
              <option value="North America">America North</option>
              <option value="South America">America South</option>
              <option value="Antarctica">Antarctica</option>
              <option value="Australia">Australia</option>
              <option value="Europe">Europe</option>
            </select>
          </div>
        </div>

String replacement in java, similar to a velocity template

There are a couple of Expression Language implementations out there that does this for you, could be preferable to using your own implementation as or if your requirments grow, see for example JUEL and MVEL

I like and have successfully used MVEL in at least one project.

Also see the Stackflow post JSTL/JSP EL (Expression Language) in a non JSP (standalone) context

When does socket.recv(recv_size) return?

Yes, your conclusion is correct. socket.recv is a blocking call.

socket.recv(1024) will read at most 1024 bytes, blocking if no data is waiting to be read. If you don't read all data, an other call to socket.recv won't block.

socket.recv will also end with an empty string if the connection is closed or there is an error.

If you want a non-blocking socket, you can use the select module (a bit more complicated than just using sockets) or you can use socket.setblocking.

I had issues with socket.setblocking in the past, but feel free to try it if you want.

Making an array of integers in iOS

If you want to use a NSArray, you need an Objective-C class to put in it - hence the NSNumber requirement.

That said, Obj-C is still C, so you can use regular C arrays and hold regular ints instead of NSNumbers if you need to.

A Windows equivalent of the Unix tail command

If you use PowerShell then this works:

Get-Content filenamehere -Wait -Tail 30

Posting Stefan's comment from below, so people don't miss it

PowerShell 3 introduces a -Tail parameter to include only the last x lines

How to check db2 version

Another one in v11:

select CURRENT APPLICATION COMPATIBILITY from sysibm.sysdummy1

Result:

V11R1

It's not the current version, but the current configured level for the application.

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

From MSDN:

The WPF Font Cache service shares font data between WPF applications. The first WPF application you run starts this service if the service is not already running. If you are using Windows Vista, you can set the "Windows Presentation Foundation (WPF) Font Cache 3.0.0.0" service from "Manual" (the default) to "Automatic (Delayed Start)" to reduce the initial start-up time of WPF applications.

There's no harm in disabling it, but WPF apps tend to start faster and load fonts faster with it running.
It is supposed to be a performance optimization. The fact that it is not in your case makes me suspect that perhaps your font cache is corrupted. To clear it, follow these steps:

  1. Stop the WPF Font Cache 4.0 service.
  2. Delete all of the WPFFontCache_v0400* files. In Windows XP, you'll find them in your C:\Documents and Settings\LocalService\Local Settings\Application Data\ folder.
  3. Start the service again.

href overrides ng-click in Angular.js

I'll add for you an example that work for me and you can change it as you want.

I add the bellow code inside my controller.

     $scope.showNumberFct = function(){
        alert("Work!!!!");
     }

and for my view page I add the bellow code.

<a  href="" ng-model="showNumber" ng-click="showNumberFct()" ng-init="showNumber = false" >Click Me!!!</a>

Convert int to a bit array in .NET

I just ran into an instance where...

int val = 2097152;
var arr = Convert.ToString(val, 2).ToArray();
var myVal = arr[21];

...did not produce the results I was looking for. In 'myVal' above, the value stored in the array in position 21 was '0'. It should have been a '1'. I'm not sure why I received an inaccurate value for this and it baffled me until I found another way in C# to convert an INT to a bit array:

int val = 2097152;
var arr = new BitArray(BitConverter.GetBytes(val));
var myVal = arr[21];

This produced the result 'true' as a boolean value for 'myVal'.

I realize this may not be the most efficient way to obtain this value, but it was very straight forward, simple, and readable.

How to completely remove Python from a Windows machine?

Windows 7 64-bit, with both Python3.4 and Python2.7 installed at some point :)

I'm using Py.exe to route to Py2 or Py3 depending on the script's needs - but I previously improperly uninstalled Python27 before.

Py27 was removed manually from C:\python\Python27 (the folder Python27 was deleted by me previously)

Upon re-installing Python27, it gave the above error you specify.
It would always back out while trying to 'remove shortcuts' during the installation process.

I placed a copy of Python27 back in that original folder, at C:\Python\Python27, and re-ran the same failing Python27 installer. It was happy locating those items and removing them, and proceeded with the install.

This is not the answer that addresses registry key issues (others mention that) but it is somewhat of a workaround if you know of previous installations that were improperly removed.

You could have some insight to this by opening "regedit" and searching for "Python27" - a registry key appeared in my command-shell Cache pointing at c:\python\python27\ (which had been removed and was not present when searching in the registry upon finding it).

That may help point to previously improperly removed installations.

Good luck!

How to use struct timeval to get the execution time?

Change:

struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
                                          delcare a variable with
                                          no name. */

to:

struct timeval tvalBefore, tvalAfter;

It is less likely (IMO) to make this mistake if there is a single declaration per line:

struct timeval tvalBefore;
struct timeval tvalAfter;

It becomes more error prone when declaring pointers to types on a single line:

struct timeval* tvalBefore, tvalAfter;

tvalBefore is a struct timeval* but tvalAfter is a struct timeval.

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

I'd recommend reading that PEP the error gives you. The problem is that your code is trying to use the ASCII encoding, but the pound symbol is not an ASCII character. Try using UTF-8 encoding. You can start by putting # -*- coding: utf-8 -*- at the top of your .py file. To get more advanced, you can also define encodings on a string by string basis in your code. However, if you are trying to put the pound sign literal in to your code, you'll need an encoding that supports it for the entire file.

What are the file limits in Git (number and size)?

It depends on what your meaning is. There are practical size limits (if you have a lot of big files, it can get boringly slow). If you have a lot of files, scans can also get slow.

There aren't really inherent limits to the model, though. You can certainly use it poorly and be miserable.

User GETDATE() to put current date into SQL variable

DECLARE @LastChangeDate as date 
SET @LastChangeDate = GETDATE() 

What does Java option -Xmx stand for?

-Xmx sets the Maximum Heap size

Using Pip to install packages to Anaconda Environment

I know the original question was about conda under MacOS. But I would like to share the experience I've had on Ubuntu 20.04.

In my case, the issue was due to an alias defined in ~/.bashrc: alias pip='/usr/bin/pip3'. That alias was taking precedence on everything else.

So for testing purposes I've removed the alias running unalias pip command. Then the corresponding pip of the active conda environment has been executed properly.

The same issue was applicable to python command.

Run a task every x-minutes with Windows Task Scheduler

On XP, I clicked the Advanced button on the Schedule tab. There is a checkbox for Repeat task. The default is every 10 minutes.

Additionally, you can create scheduled task via the command line. I haven't tried this myself, but it looks like you'd want something along the lines of (not tested):

schtasks /create /tn "Some task name" /tr "app.exe" /sc HOURLY 

How can I change image tintColor in iOS and WatchKit

Swift 3 version of extension answer from fuzz

func imageWithColor(color: UIColor) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
    color.setFill()

    let context = UIGraphicsGetCurrentContext()! as CGContext
    context.translateBy(x: 0, y: self.size.height)
    context.scaleBy(x: 1.0, y: -1.0);
    context.setBlendMode(.normal)

    let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height) as CGRect
    context.clip(to: rect, mask: self.cgImage!)
    context.fill(rect)

    let newImage = UIGraphicsGetImageFromCurrentImageContext()! as UIImage
    UIGraphicsEndImageContext()

    return newImage
}

Server.MapPath - Physical path given, virtual path expected

if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...

How to Convert Int to Unsigned Byte and Back

Handling bytes and unsigned integers with BigInteger:

byte[] b = ...                    // your integer in big-endian
BigInteger ui = new BigInteger(b) // let BigInteger do the work
int i = ui.intValue()             // unsigned value assigned to i

How to open up a form from another form in VB.NET?

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
                          Handles Button3.Click

    Dim box = New AboutBox1()
    box.Show()

End Sub

Update TensorFlow

For anaconda installation, first pick a channel which has the latest version of tensorflow binary. Usually, the latest versions are available at the channel conda-forge. Then simply do:

conda update -f -c conda-forge tensorflow

This will upgrade your existing tensorflow installation to the very latest version available. As of this writing, the latest version is 1.4.0-py36_0

JAXB: how to marshall map into <key>value</key>

I found easiest solution.

@XmlElement(name="attribute")
    public String[] getAttributes(){
        return attributes.keySet().toArray(new String[1]);
    }
}

Now it will generate in you xml output like this:

<attribute>key1<attribute>
...
<attribute>keyN<attribute>

Redirecting Output from within Batch file

This may fail in the case of "toxic" characters in the input. Considering an input like thisIsAnIn^^^^put is a good way how to get understand what is going on. Sure there is a rule that an input string MUST be inside double quoted marks but I have a feeling that this rule is a valid rule only if the meaning of the input is a location on a NTFS partition (maybe it is a rule for URLs I am not sure). But it is not a rule for an arbitrary input string of course (it is "a good practice" but you cannot count with it).

Programmatically getting the MAC of an Android device

I think I just found a way to read MAC addresses without LOCATION permission: Run ip link and parse its output. (you could probably do the similar by looking at this binary's source code)

How do I remove/delete a folder that is not empty?

I'd like to add a "pure pathlib" approach:

from pathlib import Path
from typing import Union

def del_dir(target: Union[Path, str], only_if_empty: bool = False):
    """
    Delete a given directory and its subdirectories.

    :param target: The directory to delete
    :param only_if_empty: Raise RuntimeError if any file is found in the tree
    """
    target = Path(target).expanduser()
    assert target.is_dir()
    for p in sorted(target.glob('**/*'), reverse=True):
        if not p.exists():
            continue
        p.chmod(0o666)
        if p.is_dir():
            p.rmdir()
        else:
            if only_if_empty:
                raise RuntimeError(f'{p.parent} is not empty!')
            p.unlink()
    target.rmdir()

This relies on the fact that Path is orderable, and longer paths will always sort after shorter paths, just like str. Therefore, directories will come before files. If we reverse the sort, files will then come before their respective containers, so we can simply unlink/rmdir them one by one with one pass.

Benefits:

  • It's NOT relying on external binaries: everything uses Python's batteries-included modules (Python >= 3.6)
    • Which means that it does not need to repeatedly start a new subprocess to do unlinking
  • It's quite fast & simple; you don't have to implement your own recursion
  • It's cross-platform (at least, that's what pathlib promises in Python 3.6; no operation above stated to not run on Windows)
  • If needed, one can do a very granular logging, e.g., log each deletion as it happens.

Best dynamic JavaScript/JQuery Grid

Have a look at agiletoolkit.org as this has a simple to use CRUD which supports 2,4,6,7,9,10 and 12 out of the box (uses Ajax to defender the grid when adding,deleting data and it integrates with jquery.

I would post some examples but on an iPad at the moment.

How to use PDO to fetch results array in PHP?

Take a look at the PDOStatement.fetchAll method. You could also use fetch in an iterator pattern.

Code sample for fetchAll, from the PHP documentation:

<?php
$sth = $dbh->prepare("SELECT name, colour FROM fruit");
$sth->execute();

/* Fetch all of the remaining rows in the result set */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll(\PDO::FETCH_ASSOC);
print_r($result);

Results:

Array
(
    [0] => Array
        (
            [NAME] => pear
            [COLOUR] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [COLOUR] => pink
        )
)

Playing m3u8 Files with HTML Video Tag

You can use video js library for easily play HLS video's. It allows to directly play videos

<!-- CSS  -->
 <link href="https://vjs.zencdn.net/7.2.3/video-js.css" rel="stylesheet">


<!-- HTML -->
<video id='hls-example'  class="video-js vjs-default-skin" width="400" height="300" controls>
<source type="application/x-mpegURL" src="http://www.streambox.fr/playlists/test_001/stream.m3u8">
</video>


<!-- JS code -->
<!-- If you'd like to support IE8 (for Video.js versions prior to v7) -->
<script src="https://vjs.zencdn.net/ie8/ie8-version/videojs-ie8.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/videojs-contrib-hls/5.14.1/videojs-contrib-hls.js"></script>
<script src="https://vjs.zencdn.net/7.2.3/video.js"></script>

<script>
var player = videojs('hls-example');
player.play();
</script>

GitHub Video Js

How to make program go back to the top of the code instead of closing

You can easily do it with loops, there are two types of loops

For Loops:

for i in range(0,5):
    print 'Hello World'

While Loops:

count = 1
while count <= 5:
    print 'Hello World'
    count += 1

Each of these loops print "Hello World" five times

Changing EditText bottom line color with appcompat v7

In Activit.XML add the code

<EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:id="@+id/editText"
        android:hint="Informe o usuário"
        android:backgroundTint="@android:color/transparent"/>

Where BackgroundTint=color for your desired colour

Getting time elapsed in Objective-C

NSDate *start = [NSDate date];
// do stuff...
NSTimeInterval timeInterval = [start timeIntervalSinceNow];

timeInterval is the difference between start and now, in seconds, with sub-millisecond precision.

Filtering lists using LINQ

I would just use the FindAll method on the List class. i.e.:

List<Person> filteredResults = 
    people.FindAll(p => return !exclusions.Contains(p));

Not sure if the syntax will exactly match your objects, but I think you can see where I'm going with this.

W3WP.EXE using 100% CPU - where to start?

  1. Standard Windows performance counters (look for other correlated activity, such as many GET requests, excessive network or disk I/O, etc); you can read them from code as well as from perfmon (to trigger data collection if CPU use exceeds a threshold, for example)
  2. Custom performance counters (particularly to time for off-box requests and other calls where execution time is uncertain)
  3. Load testing, using tools such as Visual Studio Team Test or WCAT
  4. If you can test on or upgrade to IIS 7, you can configure Failed Request Tracing to generate a trace if requests take more a certain amount of time
  5. Use logparser to see which requests arrived at the time of the CPU spike
  6. Code reviews / walk-throughs (in particular, look for loops that may not terminate properly, such as if an error happens, as well as locks and potential threading issues, such as the use of statics)
  7. CPU and memory profiling (can be difficult on a production system)
  8. Process Explorer
  9. Windows Resource Monitor
  10. Detailed error logging
  11. Custom trace logging, including execution time details (perhaps conditional, based on the CPU-use perf counter)
  12. Are the errors happening when the AppPool recycles? If so, it could be a clue.

Setting selected option in laravel form

Just Simply paste this code you will get the desired output that you needed.

 {{ Form::select ('myselect', ['1' => 'Item 1', '2' => 'Item 2'], 2 , ['id' =>'myselect']) }}` `

Increment a Integer's int value?

Integer objects are immutable. You can't change the value of the integer held by the object itself, but you can just create a new Integer object to hold the result:

Integer start = new Integer(5);
Integer end = start + 5; // end == 10;

How to subtract 2 hours from user's local time?

According to Javascript Date Documentation, you can easily do this way:

var twoHoursBefore = new Date();
twoHoursBefore.setHours(twoHoursBefore.getHours() - 2);

And don't worry about if hours you set will be out of 0..23 range. Date() object will update the date accordingly.

Best way to save a trained model in PyTorch?

If you want to save the model and wants to resume the training later:

Single GPU: Save:

state = {
        'epoch': epoch,
        'state_dict': model.state_dict(),
        'optimizer': optimizer.state_dict(),
}
savepath='checkpoint.t7'
torch.save(state,savepath)

Load:

checkpoint = torch.load('checkpoint.t7')
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']

Multiple GPU: Save

state = {
        'epoch': epoch,
        'state_dict': model.module.state_dict(),
        'optimizer': optimizer.state_dict(),
}
savepath='checkpoint.t7'
torch.save(state,savepath)

Load:

checkpoint = torch.load('checkpoint.t7')
model.load_state_dict(checkpoint['state_dict'])
optimizer.load_state_dict(checkpoint['optimizer'])
epoch = checkpoint['epoch']

#Don't call DataParallel before loading the model otherwise you will get an error

model = nn.DataParallel(model) #ignore the line if you want to load on Single GPU

Alter column in SQL Server

I think you want this syntax:

ALTER TABLE tb_TableName  
add constraint cnt_Record_Status Default '' for Record_Status

Based on some of your comments, I am going to guess that you might already have null values in your table which is causing the alter of the column to not null to fail. If that is the case, then you should run an UPDATE first. Your script will be:

update tb_TableName
set Record_Status  = ''
where Record_Status is null

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL

ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status

See SQL Fiddle with demo

Get single listView SelectedItem

I do this like that:

if (listView1.SelectedItems.Count > 0)
{
     var item = listView1.SelectedItems[0];
     //rest of your logic
}

System.out.println() shortcut on Intellij IDEA

Open up Settings (By default is Alt + Ctrl + S) and search for Live Templates. In the upper part there's an option that says "By default expand with TAB" (TAB is the default), choose "Custom" and then hit "change" and add the keymap "ctrl+spacebar" to the option "Expand Live Template/Emmet Abbreviation".

Now you can hit ctrl + spacebar and expand the live templates. Now, to change it to "syso" instead of "sout", in the Live Templates option, theres a list of tons of options checked, go to "other" and expand it, there you wil find "sout", just rename it to "syso" and hit aply.

Hope this can help you.

How to use paths in tsconfig.json?

It looks like there has been an update to React that doesn't allow you to set the "paths" in the tsconfig.json anylonger.

Nicely React just outputs a warning:

The following changes are being made to your tsconfig.json file:
  - compilerOptions.paths must not be set (aliased imports are not supported)

then updates your tsconfig.json and removes the entire "paths" section for you. There is a way to get around this run

npm run eject

This will eject all of the create-react-scripts settings by adding config and scripts directories and build/config files into your project. This also allows a lot more control over how everything is built, named etc. by updating the {project}/config/* files.

Then update your tsconfig.json

{
    "compilerOptions": {
        "baseUrl": "./src",
        {…}
        "paths": {
            "assets/*": [ "assets/*" ],
            "styles/*": [ "styles/*" ]
        }
    },
}

How to remove last n characters from a string in Bash?

You could use sed,

sed 's/.\{4\}$//' <<< "$var"

EXample:

$ var="some string.rtf"
$ var1=$(sed 's/.\{4\}$//' <<< "$var")
$ echo $var1
some string

jQuery '.each' and attaching '.click' event

One solution you could use is to assign a more generalized class to any div you want the click event handler bound to.

For example:

HTML:

<body>
<div id="dog" class="selected" data-selected="false">dog</div>
<div id="cat" class="selected" data-selected="true">cat</div>
<div id="mouse" class="selected" data-selected="false">mouse</div>

<div class="dog"><img/></div>
<div class="cat"><img/></div>
<div class="mouse"><img/></div>
</body>

JS:

$( ".selected" ).each(function(index) {
    $(this).on("click", function(){
        // For the boolean value
        var boolKey = $(this).data('selected');
        // For the mammal value
        var mammalKey = $(this).attr('id'); 
    });
});

MongoDB or CouchDB - fit for production?

We are running CouchDB as a replacemant for MySQL for our shops (70.0000 items/shop, a total of 4 million attributes of all items, cross connections between items).

Our goals were:

  1. Easy replication from a master-db to several clients with different documents.

  2. Fast pre-calculated data like "how many parts do I have with this attribute and that filter, fitting to those conditions"

facts:

  1. Our shops are now running much faster than with MySQL (and mysql-database needed additionaly 1-3 days of pre-calculating (so updating was twice a month), making the data ready for product counting and filtering, CouchDB needs 5 hours, so we could update product data every night)
  2. Setting up (filtered) data distribution & backups to the shop nodes is fast and easy

but also:

  1. Understanding map/reduce and the limits of not having joins is quite hard
  2. No operation on data like "delete where" or "update where" without external programs
  3. Replication works well, unless there is a problem; then it's really hard to find out what was the reason (for beginners)
  4. The installation of CouchDB without binaries (yes there are a some in the wild, but not for every OS/version) could be hard, if you are not a Linux geek. But the CouchDB Community is helpful (#couchdb), and luckily there are companies out there (cloudant, iriscouch) that offer services from free to big business.
  5. CouchDB is moving forward, so there are a lot of changes (improvements) going on that might change they way you work. But basic things remain stable.

As a result: MySQL as a database for data creation and maintaining is reliable and easy to understand and handle. I think we will not change this. But I also don't want to miss the power of CouchDB views and the ease of replication setup.

Production couches sometimes caused trouble after months of work due to misconfiguration and forgotten logrotates (view building takes too long or hangs, replication stops), but never lost data, and always could be easily reset.

How do I find the index of a character in a string in Ruby?

You can use this

"abcdefg".index('c')   #=> 2

appending list but error 'NoneType' object has no attribute 'append'

When doing pan_list.append(p.last) you're doing an inplace operation, that is an operation that modifies the object and returns nothing (i.e. None).

You should do something like this :

last_list=[]
if p.last_name==None or p.last_name=="": 
    pass
last_list.append(p.last)  # Here I modify the last_list, no affectation
print last_list

How can I make a horizontal ListView in Android?

Gallery is the best solution, i have tried it. I was working on one mail app, in which mails in the inbox where displayed as listview, i wanted an horizontal view, i just converted listview to gallery and everything worked fine as i needed without any errors. For the scroll effect i enabled gesture listener for the gallery. I hope this answer may help u.

Is there an ignore command for git like there is for svn?

It's useful to define a complete .gitignore file for your project. The reward is safe use of the convenient --all or -a flag to commands like add and commit.

Also, consider defining a global ~/.gitignore file for commonly ignored patterns such as *~, which covers temporary files created by Emacs.

Downgrade npm to an older version

Before doing that Download Node Js 8.11.3 from the URL: download

Open command prompt and run this:

npm install -g [email protected]

use this version this is the stable version which works along with cordova 7.1.0

for installing cordova use : • npm install -g [email protected]

• Run command

• Cordova platform remove android (if you have old android code or code is having some issue)

• Cordova platform add android : for building android app in cordova Running: Corodva run android

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

To send an mms for Android 4.0 api 14 or higher without permission to write apn settings, you can use this library: Retrieve mnc and mcc codes from android, then call

Carrier c = Carrier.getCarrier(mcc, mnc);
if (c != null) {
    APN a = c.getAPN();
    if (a != null) {
        String mmsc = a.mmsc;
        String mmsproxy = a.proxy; //"" if none
        int mmsport = a.port; //0 if none
    }
}

To use this, add Jsoup and droid prism jar to the build path, and import com.droidprism.*;

C++: Print out enum value as text

#include <iostream>
using std::cout;
using std::endl;

enum TEnum
{ 
  EOne,
  ETwo,
  EThree,
  ELast
};

#define VAR_NAME_HELPER(name) #name
#define VAR_NAME(x) VAR_NAME_HELPER(x)

#define CHECK_STATE_STR(x) case(x):return VAR_NAME(x);

const char *State2Str(const TEnum state)
{
  switch(state)
  {
    CHECK_STATE_STR(EOne);
    CHECK_STATE_STR(ETwo);
    CHECK_STATE_STR(EThree);
    CHECK_STATE_STR(ELast);
    default:
      return "Invalid";
  }
}

int main()
{
  int myInt=12345;
  cout << VAR_NAME(EOne) " " << VAR_NAME(myInt) << endl;

  for(int i = -1; i < 5;   i)
    cout << i << " " << State2Str((TEnum)i) << endl;
  return 0;
}

font-family is inherit. How to find out the font-family in chrome developer pane?

Developer Tools > Elements > Computed > Rendered Fonts

The picture you attached to your question shows the Style tab. If you change to the next tab, Computed, you can check the Rendered Fonts, that shows the actual font-family rendered.

Developer Tools > Elements > Computed > Rendered Fonts

How to fix homebrew permissions?

In my case the /usr/local/Frameworks didn't even exist, so I did:

sudo mkdir /usr/local/Frameworks
sudo chown -R $(whoami) /usr/local/Frameworks

And then everything worked as expected.

Set proxy through windows command line including login parameters

The best way around this is (and many other situations) in my experience, is to use cntlm which is a local no-authentication proxy which points to a remote authentication proxy. You can then just set WinHTTP to point to your local CNTLM (usually localhost:3128), and you can set CNTLM itself to point to the remote authentication proxy. CNTLM has a "magic NTLM dialect detection" option which generates password hashes to be put into the CNTLM configuration files.

How to keep two folders automatically synchronized?

You can use inotifywait (with the modify,create,delete,move flags enabled) and rsync.

while inotifywait -r -e modify,create,delete,move /directory; do
    rsync -avz /directory /target
done

If you don't have inotifywait on your system, run sudo apt-get install inotify-tools

Error: Tablespace for table xxx exists. Please DISCARD the tablespace before IMPORT

The only way it worked for me was:

  1. Create a similar table
  2. Copy the .frm and .idb files of the new similar table to the name of the corrupt table.
  3. Fix permissions
  4. Restart MariaDB
  5. Drop the corrupt table

Can't concatenate 2 arrays in PHP

Try array_merge.

$array1 = array('Item 1');

$array2 = array('Item 2');

$array3 = array_merge($array1, $array2);

I think its because you are not assigning a key to either, so they both have key of 0, and the + does not re-index, so its trying to over write it.

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.

Start a fragment via Intent within a Fragment

Try this it may help you:

private void changeFragment(Fragment targetFragment){

    getSupportFragmentManager()
         .beginTransaction()
         .replace(R.id.main_fragment, targetFragment, "fragment")
         .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
         .commit();

}

How to generate a number of most distinctive colors in R?

Not an answer to OP's question but it's worth mentioning that there is the viridis package which has good color palettes for sequential data. They are perceptually uniform, colorblind safe and printer-friendly.

To get the palette, simply install the package and use the function viridis_pal(). There are four options "A", "B", "C" and "D" to choose

install.packages("viridis")
library(viridis)
viridis_pal(option = "D")(n)  # n = number of colors seeked

enter image description here

enter image description here

enter image description here

There is also an excellent talk explaining the complexity of good colormaps on YouTube:

A Better Default Colormap for Matplotlib | SciPy 2015 | Nathaniel Smith and Stéfan van der Walt

Angularjs: Get element in controller

You can pass in the element to the controller, just like the scope:

function someControllerFunc($scope, $element){

}

How to get next/previous record in MySQL?

I had the same problem as Dan, so I used his answer and improved it.

First select the row index, nothing different here.

SELECT row
FROM 
(SELECT @rownum:=@rownum+1 row, a.* 
FROM articles a, (SELECT @rownum:=0) r
ORDER BY date, id) as article_with_rows
WHERE id = 50;

Now use two separate queries. For example if the row index is 21, the query to select the next record will be:

SELECT * 
FROM articles
ORDER BY date, id
LIMIT 21, 1

To select the previous record use this query:

SELECT * 
FROM articles
ORDER BY date, id
LIMIT 19, 1

Keep in mind that for the first row (row index is 1), the limit will go to -1 and you will get a MySQL error. You can use an if-statement to prevent this. Just don't select anything, since there is no previous record anyway. In the case of the last record, there will be next row and therefor there will be no result.

Also keep in mind that if you use DESC for ordering, instead of ASC, you queries to select the next and previous rows are still the same, but switched.

Best way to reverse a string

It's very simple

static void Reverse()
    {
        string str = "PankajRawat";
        var arr = str.ToCharArray();
        for (int i = str.Length-1; i >= 0; i--)
        {
            Console.Write(arr[i]);
        }
    }

Is there a way to use two CSS3 box shadows on one element?

Box shadows can use commas to have multiple effects, just like with background images (in CSS3).

Efficiently sorting a numpy array in descending order?

Be careful with dimensions.

Let

x  # initial numpy array
I = np.argsort(x) or I = x.argsort() 
y = np.sort(x)    or y = x.sort()
z  # reverse sorted array

Full Reverse

z = x[I[::-1]]
z = -np.sort(-x)
z = np.flip(y)
  • flip changed in 1.15, previous versions 1.14 required axis. Solution: pip install --upgrade numpy.

First Dimension Reversed

z = y[::-1]
z = np.flipud(y)
z = np.flip(y, axis=0)

Second Dimension Reversed

z = y[::-1, :]
z = np.fliplr(y)
z = np.flip(y, axis=1)

Testing

Testing on a 100×10×10 array 1000 times.

Method       | Time (ms)
-------------+----------
y[::-1]      | 0.126659  # only in first dimension
-np.sort(-x) | 0.133152
np.flip(y)   | 0.121711
x[I[::-1]]   | 4.611778

x.sort()     | 0.024961
x.argsort()  | 0.041830
np.flip(x)   | 0.002026

This is mainly due to reindexing rather than argsort.

# Timing code
import time
import numpy as np


def timeit(fun, xs):
    t = time.time()
    for i in range(len(xs)):  # inline and map gave much worse results for x[-I], 5*t
        fun(xs[i])
    t = time.time() - t
    print(np.round(t,6))

I, N = 1000, (100, 10, 10)
xs = np.random.rand(I,*N)
timeit(lambda x: np.sort(x)[::-1], xs)
timeit(lambda x: -np.sort(-x), xs)
timeit(lambda x: np.flip(x.sort()), xs)
timeit(lambda x: x[x.argsort()[::-1]], xs)
timeit(lambda x: x.sort(), xs)
timeit(lambda x: x.argsort(), xs)
timeit(lambda x: np.flip(x), xs)

Select data from date range between two dates

Here is a query to find all product sales that were running during the month of August

  • Find Product_sales there were active during the month of August
  • Include anything that started before the end of August
  • Exclude anything that ended before August 1st

Also adds a case statement to validate the query

SELECT start_date, 
       end_date, 
       CASE 
         WHEN start_date <= '2015-08-31' THEN 'true' 
         ELSE 'false' 
       END AS started_before_end_of_month, 
       CASE 
         WHEN NOT end_date <= '2015-08-01' THEN 'true' 
         ELSE 'false' 
       END AS did_not_end_before_begining_of_month 
FROM   product_sales 
WHERE  start_date <= '2015-08-31' 
       AND end_date >= '2015-08-01' 
ORDER  BY start_date; 

SELECTING with multiple WHERE conditions on same column

can't really see your table, but flag cannot be both 'Volunteer' and 'Uploaded'. If you have multiple values in a column, you can use

WHERE flag LIKE "%Volunteer%" AND flag LIKE "%UPLOADED%"

not really applicable seeing the formatted table.

On design patterns: When should I use the singleton?

An example with code, perhaps.

Here, the ConcreteRegistry is a singleton in a poker game that allows the behaviours all the way up the package tree access the few, core interfaces of the game (i.e., the facades for the model, view, controller, environment, etc.):

http://www.edmundkirwan.com/servlet/fractal/cs1/frac-cs40.html

Ed.

Angular2: child component access parent class variable/function

If you use input property databinding with a JavaScript reference type (e.g., Object, Array, Date, etc.), then the parent and child will both have a reference to the same/one object. Any changes you make to the shared object will be visible to both parent and child.

In the parent's template:

<child [aList]="sharedList"></child>

In the child:

@Input() aList;
...
updateList() {
    this.aList.push('child');
}

If you want to add items to the list upon construction of the child, use the ngOnInit() hook (not the constructor(), since the data-bound properties aren't initialized at that point):

ngOnInit() {
    this.aList.push('child1')
}

This Plunker shows a working example, with buttons in the parent and child component that both modify the shared list.

Note, in the child you must not reassign the reference. E.g., don't do this in the child: this.aList = someNewArray; If you do that, then the parent and child components will each have references to two different arrays.

If you want to share a primitive type (i.e., string, number, boolean), you could put it into an array or an object (i.e., put it inside a reference type), or you could emit() an event from the child whenever the primitive value changes (i.e., have the parent listen for a custom event, and the child would have an EventEmitter output property. See @kit's answer for more info.)

Update 2015/12/22: the heavy-loader example in the Structural Directives guides uses the technique I presented above. The main/parent component has a logs array property that is bound to the child components. The child components push() onto that array, and the parent component displays the array.

Get absolute path to workspace directory in Jenkins Pipeline plugin

Note: this solution works only if the slaves have the same directory structure as the master. pwd() will return the workspace directory on the master due to JENKINS-33511.

I used to do it using pwd() functionality of pipeline plugin. So, if you need to get a workspace on slave, you may do smth like this:

node('label'){
    //now you are on slave labeled with 'label'
    def workspace = pwd()
    //${workspace} will now contain an absolute path to job workspace on slave 
}

java : non-static variable cannot be referenced from a static context Error

Java has two kind of Variables

a)
Class Level (Static) :
They are one per Class.Say you have Student Class and defined name as static variable.Now no matter how many student object you create all will have same name.

Object Level :
They belong to per Object.If name is non-static ,then all student can have different name.

b)
Class Level :
This variables are initialized on Class load.So even if no student object is created you can still access and use static name variable.

Object Level: They will get initialized when you create a new object ,say by new();

C)
Your Problem : Your class is Just loaded in JVM and you have called its main (static) method : Legally allowed.

Now from that you want to call an Object varibale : Where is the object ??

You have to create a Object and then only you can access Object level varibales.

How to update Python?

The best solution is to install the different Python versions in multiple paths.

eg. C:\Python27 for 2.7, and C:\Python33 for 3.3.

Read this for more info: How to run multiple Python versions on Windows

How to find which git branch I am on when my disk is mounted on other server

Our git repo disk is mounted on AIX box to do BUILD.

It sounds like you mounted the drive on which the git repository is stored on another server, and you are asking how to modify that. If that is the case, this is a bad idea.

The build server should have its own copy of the git repository, and it will be locally managed by git on the build server. The build server's repository will be connected to the "main" git repository with a "remote", and you can issue the command git pull to update the local repository on the build server.

If you don't want to go to the trouble of setting up SSH or a gitolite server or something similar, you can use a file path as the "remote" location. So you could continue to mount the Linux server's file system on the build server, but instead of running the build out of that mounted path, clone the repository into another folder and run it from there.

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

For react-native-firebase, adding this to app/build.gradle dependencies section made it work for me:

implementation('com.squareup.okhttp3:okhttp:3.12.1') { force = true }
implementation('com.squareup.okio:okio:1.15.0') { force = true }
implementation('com.google.code.findbugs:jsr305:3.0.2') { force = true}

CSS change button style after click

What is the code of your button? If it's an a tag, then you could do this:

_x000D_
_x000D_
a {_x000D_
  padding: 5px;_x000D_
  background: green;_x000D_
}_x000D_
a:visited {_x000D_
  background: red;_x000D_
}
_x000D_
<a href="#">A button</a>
_x000D_
_x000D_
_x000D_

Or you could use jQuery to add a class on click, as below:

_x000D_
_x000D_
$("#button").click(function() {_x000D_
  $("#button").addClass('button-clicked');_x000D_
});
_x000D_
.button-clicked {_x000D_
  background: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="button">Button</button>
_x000D_
_x000D_
_x000D_

Use StringFormat to add a string to a WPF XAML binding

Your first example is effectively what you need:

<TextBlock Text="{Binding CelsiusTemp, StringFormat={}{0}°C}" />

Xcode : Adding a project as a build dependency

Under TARGETS in your project, right-click on your project target (should be the same name as your project) and choose GET INFO, then on GENERAL tab you will see DIRECT DEPENDENCIES, simply click the [+] and select SoundCloudAPI.

C: printf a float value

printf("%9.6f", myFloat) specifies a format with 9 total characters: 2 digits before the dot, the dot itself, and six digits after the dot.

TypeError : Unhashable type

You'll find that instances of list do not provide a __hash__ --rather, that attribute of each list is actually None (try print [].__hash__). Thus, list is unhashable.

The reason your code works with list and not set is because set constructs a single set of items without duplicates, whereas a list can contain arbitrary data.

How can I check if PostgreSQL is installed or not via Linux script?

And if everything else fails from these great choice of answers, you can always use "find" like this. Or you may need to use sudo

If you are root, just type $$> find / -name 'postgres'

If you are a user, you will need sudo priv's to run it through all the directories

I run it this way, from the / base to find the whole path that the element is found in. This will return any files or directories with the "postgres" in it.

You could do the same thing looking for the pg_hba.conf or postgresql.conf files also.

How to find the width of a div using vanilla JavaScript?

All Answers are right, but i still want to give some other alternatives that may work.

If you are looking for the assigned width (ignoring padding, margin and so on) you could use.

getComputedStyle(element).width; //returns value in px like "727.7px"

getComputedStyle allows you to access all styles of that elements. For example: padding, paddingLeft, margin, border-top-left-radius and so on.

How to change file encoding in NetBeans?

Just try to set the Projects Encoding to "UTF-8" and copy the file (which is encoded in iso) in the same Project (and if you dont need the old file just delete it) - now the copied file will be as UTF-8 - maybe this will help you :)

NHibernate.MappingException: No persister for: XYZ

I my case I fetched an entity without await:

var company = _unitOfWork.Session.GetAsync<Company>(id);

and then I tried to delete it:

await _unitOfWork.Session.DeleteAsync(company);

I could not decipher the error message that I'm deleting a Task<Company> instead of Company:

MappingException: No persister for: System.Runtime.CompilerServices.AsyncTaskMethodBuilder'1+AsyncStateMachineBox'1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null],[NHibernate.Impl.SessionImpl+d__54`1[[SmartGuide.Core.Domain.Users.Company, SmartGuide.Core, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null]], NHibernate, Version=5.3.0.0, Culture=neutral, PublicKeyToken=aa95f207798dfdb4]]

How to set only time part of a DateTime variable in C#

It isn't possible as DateTime is immutable. The same discussion is available here: How to change time in datetime?

How to access the GET parameters after "?" in Express?

Use req.query, for getting he value in query string parameter in the route. Refer req.query. Say if in a route, http://localhost:3000/?name=satyam you want to get value for name parameter, then your 'Get' route handler will go like this :-

app.get('/', function(req, res){
    console.log(req.query.name);
    res.send('Response send to client::'+req.query.name);

});

Loop through an array of strings in Bash?

listOfNames="db_one db_two db_three"
for databaseName in $listOfNames
do
  echo $databaseName
done

or just

for databaseName in db_one db_two db_three
do
  echo $databaseName
done

Open fancybox from function

function myfunction(){
    $('.classname').fancybox().trigger('click'); 
}

It works for me..

Can I escape html special chars in javascript?

It was interesting to find a better solution:

var escapeHTML = function(unsafe) {
  return unsafe.replace(/[&<"']/g, function(m) {
    switch (m) {
      case '&':
        return '&amp;';
      case '<':
        return '&lt;';
      case '"':
        return '&quot;';
      default:
        return '&#039;';
    }
  });
};

I do not parse > because it does not break XML/HTML code in the result.

Here are the benchmarks: http://jsperf.com/regexpairs Also, I created a universal escape function: http://jsperf.com/regexpairs2

How to Return partial view of another controller by controller?

Normally the views belong with a specific matching controller that supports its data requirements, or the view belongs in the Views/Shared folder if shared between controllers (hence the name).

"Answer" (but not recommended - see below):

You can refer to views/partial views from another controller, by specifying the full path (including extension) like:

return PartialView("~/views/ABC/XXX.cshtml", zyxmodel);

or a relative path (no extension), based on the answer by @Max Toro

return PartialView("../ABC/XXX", zyxmodel);

BUT THIS IS NOT A GOOD IDEA ANYWAY

*Note: These are the only two syntax that work. not ABC\\XXX or ABC/XXX or any other variation as those are all relative paths and do not find a match.

Better Alternatives:

You can use Html.Renderpartial in your view instead, but it requires the extension as well:

Html.RenderPartial("~/Views/ControllerName/ViewName.cshtml", modeldata);

Use @Html.Partial for inline Razor syntax:

@Html.Partial("~/Views/ControllerName/ViewName.cshtml", modeldata)

You can use the ../controller/view syntax with no extension (again credit to @Max Toro):

@Html.Partial("../ControllerName/ViewName", modeldata)

Note: Apparently RenderPartial is slightly faster than Partial, but that is not important.

If you want to actually call the other controller, use:

@Html.Action("action", "controller", parameters)

Recommended solution: @Html.Action

My personal preference is to use @Html.Action as it allows each controller to manage its own views, rather than cross-referencing views from other controllers (which leads to a large spaghetti-like mess).

You would normally pass just the required key values (like any other view) e.g. for your example:

@Html.Action("XXX", "ABC", new {id = model.xyzId })

This will execute the ABC.XXX action and render the result in-place. This allows the views and controllers to remain separately self-contained (i.e. reusable).

Update Sep 2014:

I have just hit a situation where I could not use @Html.Action, but needed to create a view path based on a action and controller names. To that end I added this simple View extension method to UrlHelper so you can say return PartialView(Url.View("actionName", "controllerName"), modelData):

public static class UrlHelperExtension
{
    /// <summary>
    /// Return a view path based on an action name and controller name
    /// </summary>
    /// <param name="url">Context for extension method</param>
    /// <param name="action">Action name</param>
    /// <param name="controller">Controller name</param>
    /// <returns>A string in the form "~/views/{controller}/{action}.cshtml</returns>
    public static string View(this UrlHelper url, string action, string controller)
    {
        return string.Format("~/Views/{1}/{0}.cshtml", action, controller);
    }
}

Disable submit button ONLY after submit

This solution has the advantages of working on mobile and being quite simple:

<form ... onsubmit="myButtonValue.disabled = true; return true;">

Convert timestamp in milliseconds to string formatted time in Java

long second = TimeUnit.MILLISECONDS.toSeconds(millis);
long minute = TimeUnit.MILLISECONDS.toMinutes(millis);
long hour = TimeUnit.MILLISECONDS.toHours(millis);
millis -= TimeUnit.SECONDS.toMillis(second);
return String.format("%02d:%02d:%02d:%d", hour, minute, second, millis);

Enabling CORS in Cloud Functions for Firebase

This might be helpful. I created firebase HTTP cloud function with express(custom URL)

const express = require('express');
const bodyParser = require('body-parser');
const cors = require("cors");
const app = express();
const main = express();

app.post('/endpoint', (req, res) => {
    // code here
})

app.use(cors({ origin: true }));
main.use(cors({ origin: true }));
main.use('/api/v1', app);
main.use(bodyParser.json());
main.use(bodyParser.urlencoded({ extended: false }));

module.exports.functionName = functions.https.onRequest(main);

Please make sure you added rewrite sections

"rewrites": [
      {
        "source": "/api/v1/**",
        "function": "functionName"
      }
]

JSON encode MySQL results

$sth = mysqli_query($conn, "SELECT ...");
$rows = array();
while($r = mysqli_fetch_assoc($sth)) {
    $rows[] = $r;
}
print json_encode($rows);

The function json_encode needs PHP >= 5.2 and the php-json package - as mentioned here

NOTE: mysql is deprecated as of PHP 5.5.0, use mysqli extension instead http://php.net/manual/en/migration55.deprecated.php.

How to get setuptools and easy_install?

For Amazon Linux AMI

yum install -y python-setuptools 

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

Change key in Project > Build Setting "typecheck calls to printf/scanf : NO"

Explanation : [How it works]

Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense.

Hope it work

Other warning

objective c implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int

Change key "implicit conversion to 32Bits Type > Debug > *64 architecture : No"

[caution: It may void other warning of 64 Bits architecture conversion].

How to generate a random String in Java

This is very nice:

http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/RandomStringUtils.html - something like RandomStringUtils.randomNumeric(7).

There are 10^7 equiprobable (if java.util.Random is not broken) distinct values so uniqueness may be a concern.

What is thread Safe in java?

Thread safe simply means that it may be used from multiple threads at the same time without causing problems. This can mean that access to any resources are synchronized, or whatever.

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

Answers above describe well why and how it is used on twitter and facebook, what I missed is explanation what # does by default...

On a 'normal' (not a single page application) you can do anchoring with hash to any element that has id by placing that elements id in url after hash #

Example:

(on Chrome) Click F12 or Rihgt Mouse and Inspect element

enter image description here

then take id="answer-10831233" and add to url like following

https://stackoverflow.com/questions/3009380/whats-the-shebang-hashbang-in-facebook-and-new-twitter-urls-for#answer-10831233

and you will get a link that jumps to that element on the page

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

By using # in a way described in the answers above you are introducing conflicting behaviour... although I wouldn't loose sleep over it... since Angular it became somewhat of a standard....

How to disable a link using only CSS?

CSS can't do that. CSS is for presentation only. Your options are:

  • Don't include the href attribute in your <a> tags.
  • Use JavaScript, to find the anchor elements with that class, and remove their href or onclick attributes accordingly. jQuery would help you with that (NickF showed how to do something similar but better).

Install numpy on python3.3 - Install pip for python3

The normal way to install Python libraries is with pip. Your way of installing it for Python 3.2 works because it's the system Python, and that's the way to install things for system-provided Pythons on Debian-based systems.

If your Python 3.3 is system-provided, you should probably use a similar command. Otherwise you should probably use pip.

I took my Python 3.3 installation, created a virtualenv and run pip install in it, and that seems to have worked as expected:

$ virtualenv-3.3 testenv
$ cd testenv
$ bin/pip install numpy
blablabl

$ bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> 

Does the target directory for a git clone have to match the repo name?

Yes, it is possible:

git clone https://github.com/pitosalas/st3_packages Packages 

You can specify the local root directory when using git clone.

<directory> 

The name of a new directory to clone into.
The "humanish" part of the source repository is used if no directory is explicitly given (repo for /path/to/repo.git and foo for host.xz:foo/.git).
Cloning into an existing directory is only allowed if the directory is empty.


As Chris comments, you can then rename that top directory.
Git only cares about the .git within said top folder, which you can get with various commands:

git rev-parse --show-toplevel git rev-parse --git-dir 

How does one represent the empty char?

The empty space char would be ' '. If you're looking for null that would be '\0'.

How to make a variadic macro (variable number of arguments)

__VA_ARGS__ is the standard way to do it. Don't use compiler-specific hacks if you don't have to.

I'm really annoyed that I can't comment on the original post. In any case, C++ is not a superset of C. It is really silly to compile your C code with a C++ compiler. Don't do what Donny Don't does.

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

In line 2, there's a std::string involved (name). There are operations defined for char[] + std::string, std::string + char[], etc. "Hello " + name gives a std::string, which is added to " you are ", giving another string, etc.

In line 3, you're saying

char[] + char[] + char[]

and you can't just add arrays to each other.

What does -> mean in Python function definitions?

As other answers have stated, the -> symbol is used as part of function annotations. In more recent versions of Python >= 3.5, though, it has a defined meaning.

PEP 3107 -- Function Annotations described the specification, defining the grammar changes, the existence of func.__annotations__ in which they are stored and, the fact that it's use case is still open.

In Python 3.5 though, PEP 484 -- Type Hints attaches a single meaning to this: -> is used to indicate the type that the function returns. It also seems like this will be enforced in future versions as described in What about existing uses of annotations:

The fastest conceivable scheme would introduce silent deprecation of non-type-hint annotations in 3.6, full deprecation in 3.7, and declare type hints as the only allowed use of annotations in Python 3.8.

(Emphasis mine)

This hasn't been actually implemented as of 3.6 as far as I can tell so it might get bumped to future versions.

According to this, the example you've supplied:

def f(x) -> 123:
    return x

will be forbidden in the future (and in current versions will be confusing), it would need to be changed to:

def f(x) -> int:
    return x

for it to effectively describe that function f returns an object of type int.

The annotations are not used in any way by Python itself, it pretty much populates and ignores them. It's up to 3rd party libraries to work with them.

Live Video Streaming with PHP

You can easily build a website as per the requirements. PHP will be there to handle the website development part. All the hosting and normal website development will work just as it is. However, for the streaming part, you will have to choose a good streaming service. Whether it is Red5 or Adobe, you can choose from plenty of services.

Choose a service that provides a dedicated storage to get something done right. If you do not know how to configure the server properly, you can just choose a streaming service. Good services often give a CDN that helps broadcast the stream efficiently. Simply launch your website in PHP and embed the YouTube player in the said web page to get it working.

How do you make Vim unhighlight what you searched for?

:noh (short for nohighlight) will do the trick.

C# Encoding a text string with line breaks

Try this :

string myStr = ...
myStr = myStr.Replace("\n", Environment.NewLine)

List<Map<String, String>> vs List<? extends Map<String, String>>

As you mentioned, there could be two below versions of defining a List:

  1. List<? extends Map<String, String>>
  2. List<?>

2 is very open. It can hold any object type. This may not be useful in case you want to have a map of a given type. In case someone accidentally puts a different type of map, for example, Map<String, int>. Your consumer method might break.

In order to ensure that List can hold objects of a given type, Java generics introduced ? extends. So in #1, the List can hold any object which is derived from Map<String, String> type. Adding any other type of data would throw an exception.

How to install psycopg2 with "pip" on Python?

I've been battling with this for days, and have finally figured out how to get the "pip install psycopg2" command to run in a virtualenv in Windows (running Cygwin).

I was hitting the "pg_config executable not found." error, but I had already downloaded and installed postgres in Windows. It installed in Cygwin as well; running "which pg_config" in Cygwin gave "/usr/bin/pg_config", and running "pg_config" gave sane output -- however the version installed with Cygwin is:

VERSION = PostgreSQL 8.2.11

This won't work with the current version of psycopg2, which appears to require at least 9.1. When I added "c:\Program Files\PostgreSQL\9.2\bin" to my Windows path, the Cygwin pip installer was able to find the correct version of PostgreSQL, and I was able to successfully install the module using pip. (This is probably preferable to using the Cygwin version of PostgreSQL anyway, as the native version will run much quicker).

NUnit Unit tests not showing in Test Explorer with Test Adapter installed

I had a working setup (for NUnit2 and NUnit3 depending on the solution, and multiple versions of Visual Studio between 2012 and 2017), and it suddenly stopped working one day: no tests detected in any solution or version of VS.

In my case, it helped to delete %localappdata%\Temp\VisualStudioTestExplorerExtensions. After a restart of VS, everything worked as before.

PDO Prepared Inserts multiple rows in single query

A shorter answer: flatten the array of data ordered by columns then

//$array = array( '1','2','3','4','5', '1','2','3','4','5');
$arCount = count($array);
$rCount = ($arCount  ? $arCount - 1 : 0);
$criteria = sprintf("(?,?,?,?,?)%s", str_repeat(",(?,?,?,?,?)", $rCount));
$sql = "INSERT INTO table(c1,c2,c3,c4,c5) VALUES$criteria";

When inserting a 1,000 or so records you don't want to have to loop through every record to insert them when all you need is a count of the values.

Failing to run jar file from command line: “no main manifest attribute”

Export you Java Project as an Runnable Jar file rather than Jar.

I exported my project as Jar and even though the Manifest was present it gave me the error no main manifest attribute in jar even though the Manifest file was present in the Jar. However there is only one entry in the Manifest file and it didn't specify the Main class or Function to execute or any dependent JAR's

After exporting it as Runnable Jar file it works as expected.

How to use SQL Select statement with IF EXISTS sub query?

You can also use ISNULL and a select statement to get this result

SELECT
Table1.ID,
ISNULL((SELECT 'TRUE' FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID),'FALSE') AS columName,
etc
FROM TABLE1

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I would change the query in the following ways:

  1. Do the aggregation in subqueries. This can take advantage of more information about the table for optimizing the group by.
  2. Combine the second and third subqueries. They are aggregating on the same column. This requires using a left outer join to ensure that all data is available.
  3. By using count(<fieldname>) you can eliminate the comparisons to is null. This is important for the second and third calculated values.
  4. To combine the second and third queries, it needs to count an id from the mde table. These use mde.mdeid.

The following version follows your example by using union all:

SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
       SUM(TOTALMAILED) as TotalMailed,
       SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
       SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
              NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract
       where SentDate is not null
       group by SentDate
      ) union all
      (select MDE.ReturnMailDate AS ReceiptDate, 0,
              COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
              SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract MDE left outer join
            DTSharedData.dbo.ScanData SD
            ON SD.ScanDataID = MDE.ReturnScanDataID
       group by MDE.ReturnMailDate;
      )
     ) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;

The following does something similar using full outer join:

SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
       sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
       mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
      from MailDataExtract
      where SentDate is not null
      group by cast(SentDate as date)
     ) sd full outer join
    (select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
            COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
            SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
     from MailDataExtract MDE left outer join
          DTSharedData.dbo.ScanData SD
          ON SD.ScanDataID = MDE.ReturnScanDataID
     group by cast(MDE.ReturnMailDate as date)
    ) mde
    on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;

python re.split() to split by spaces, commas, and periods, but not in cases like 1,000 or 1.50

So you want to split on spaces, and on commas and periods that aren't surrounded by numbers. This should work:

r" |(?<![0-9])[.,](?![0-9])"

Returning from a void function

The only reason to have a return in a void function would be to exit early due to some conditional statement:

void foo(int y)
{
    if(y == 0) return;

    // do stuff with y
}

As unwind said: when the code ends, it ends. No need for an explicit return at the end.

How to check if PHP array is associative or sequential?

I met this problem once again some days ago and i thought to take advantage of the array_merge special property:

If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array. So why not to use:

function Is_Indexed_Arr($arr){
    $arr_copy = $arr;
    if((2*count($arr)) == count(array_merge($arr, $arr_copy))){
        return 1;
    }
    return 0;
}

PHP not displaying errors even though display_errors = On

Although this is old post... i had similar situation that gave me headache. Finally, i figured that i was including sub pages in index.php with "@include ..." "@" hides all errors even if display_errors is ON

How to import Google Web Font in CSS file?

Use the @import method:

@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');

Obviously, "Open Sans" (Open+Sans) is the font that is imported. So replace it with yours. If the font's name has multiple words, URL-encode it by adding a + sign between each word, as I did.

Make sure to place the @import at the very top of your CSS, before any rules.

Google Fonts can automatically generate the @import directive for you. Once you have chosen a font, click the (+) icon next to it. In bottom-left corner, a container titled "1 Family Selected" will appear. Click it, and it will expand. Use the "Customize" tab to select options, and then switch back to "Embed" and click "@import" under "Embed Font". Copy the CSS between the <style> tags into your stylesheet.

Any way to write a Windows .bat file to kill processes?

As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:

TSKILL processName

or

TSKILL PID

Have on mind that processName should not have the .exe suffix and is limited to 18 characters.

Another option is WMIC :

wmic Path win32_process Where "Caption Like 'MyProcess%.exe'" Call Terminate

wmic offer even more flexibility than taskkill with its SQL-like matchers .With wmic Path win32_process get you can see the available fileds you can filter (and % can be used as a wildcard).

Remove certain characters from a string

UPDATE yourtable 
SET field_or_column =REPLACE ('current string','findpattern', 'replacepattern') 
WHERE 1

What is the naming convention in Python for variable and function names?

further to what @JohnTESlade has answered. Google's python style guide has some pretty neat recommendations,

Names to Avoid

  • single character names except for counters or iterators
  • dashes (-) in any package/module name
  • \__double_leading_and_trailing_underscore__ names (reserved by Python)

Naming Convention

  • "Internal" means internal to a module or protected or private within a class.
  • Prepending a single underscore (_) has some support for protecting module variables and functions (not included with import * from). Prepending a double underscore (__) to an instance variable or method effectively serves to make the variable or method private to its class (using name mangling).
  • Place related classes and top-level functions together in a module. Unlike Java, there is no need to limit yourself to one class per module.
  • Use CapWords for class names, but lower_with_under.py for module names. Although there are many existing modules named CapWords.py, this is now discouraged because it's confusing when the module happens to be named after a class. ("wait -- did I write import StringIO or from StringIO import StringIO?")

Guidelines derived from Guido's Recommendations enter image description here

How to make Visual Studio copy a DLL file to the output directory?

$(OutDir) turned out to be a relative path in VS2013, so I had to combine it with $(ProjectDir) to achieve the desired effect:

xcopy /y /d  "$(ProjectDir)External\*.dll" "$(ProjectDir)$(OutDir)"

BTW, you can easily debug the scripts by adding 'echo ' at the beginning and observe the expanded text in the build output window.

Measuring the distance between two coordinates in PHP

Try this gives awesome results

function getDistance($point1_lat, $point1_long, $point2_lat, $point2_long, $unit = 'km', $decimals = 2) {
        // Calculate the distance in degrees
        $degrees = rad2deg(acos((sin(deg2rad($point1_lat))*sin(deg2rad($point2_lat))) + (cos(deg2rad($point1_lat))*cos(deg2rad($point2_lat))*cos(deg2rad($point1_long-$point2_long)))));

        // Convert the distance in degrees to the chosen unit (kilometres, miles or nautical miles)
        switch($unit) {
            case 'km':
                $distance = $degrees * 111.13384; // 1 degree = 111.13384 km, based on the average diameter of the Earth (12,735 km)
                break;
            case 'mi':
                $distance = $degrees * 69.05482; // 1 degree = 69.05482 miles, based on the average diameter of the Earth (7,913.1 miles)
                break;
            case 'nmi':
                $distance =  $degrees * 59.97662; // 1 degree = 59.97662 nautic miles, based on the average diameter of the Earth (6,876.3 nautical miles)
        }
        return round($distance, $decimals);
    }

How to programmatically disable page scrolling with jQuery

I put an answer that might help here: jQuery simplemodal disable scrolling

It shows how to turn off the scroll bars without shifting the text around. You can ignore the parts about simplemodal.

Comparison of DES, Triple DES, AES, blowfish encryption for data

AES is the currently accepted standard algorithm to use (hence the name Advanced Encryption Standard).

The rest are not.

jQuery select child element by class with unknown path

$('#thisElement').find('.classToSelect') will find any descendents of #thisElement with class classToSelect.

Asp.net MVC ModelState.Clear

Got it in the end. My Custom ModelBinder which was not being registered and does this :

var mymsPage = new MyCmsPage();

NameValueCollection frm = controllerContext.HttpContext.Request.Form;

myCmsPage.SeoTitle = (!String.IsNullOrEmpty(frm["seoTitle"])) ? frm["seoTitle"] : null;

So something that the default model binding was doing must have been causing the problem. Not sure what, but my problem is at least fixed now that my custom model binder is being registered.

Removing duplicate elements from an array in Swift

Swift 4

Guaranteed to keep ordering.

extension Array where Element: Equatable {
    func removingDuplicates() -> Array {
        return reduce(into: []) { result, element in
            if !result.contains(element) {
                result.append(element)
            }
        }
    }
}

How to make the overflow CSS property work with hidden as value

This worked for me

<div style="display: flex; position: absolute; width: 100%;">
  <div style="white-space: nowrap; overflow: hidden;text-overflow: ellipsis;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi.
  </div>
</div>

Adding position:absolute to the parent container made it work.

PS: This is for anyone looking for a solution to dynamically truncating text.

EDIT: This was meant to be an answer for this question but since they are related and it could help someone on this question I shall also leave it here instead of deleting it.

Log4j, configuring a Web App to use a relative path

If you use Spring you can:

1) create a log4j configuration file, e.g. "/WEB-INF/classes/log4j-myapp.properties" DO NOT name it "log4j.properties"

Example:

log4j.rootLogger=ERROR, stdout, rollingFile

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n

log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.File=${myWebapp-instance-root}/WEB-INF/logs/application.log
log4j.appender.rollingFile.MaxFileSize=512KB
log4j.appender.rollingFile.MaxBackupIndex=10
log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.rollingFile.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.rollingFile.Encoding=UTF-8

We'll define "myWebapp-instance-root" later on point (3)

2) Specify config location in web.xml:

<context-param>
  <param-name>log4jConfigLocation</param-name>
  <param-value>/WEB-INF/classes/log4j-myapp.properties</param-value>
</context-param>

3) Specify a unique variable name for your webapp's root, e.g. "myWebapp-instance-root"

<context-param>
  <param-name>webAppRootKey</param-name>
  <param-value>myWebapp-instance-root</param-value>
</context-param>

4) Add a Log4jConfigListener:

<listener>
  <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>

If you choose a different name, remember to change it in log4j-myapp.properties, too.

See my article (Italian only... but it should be understandable): http://www.megadix.it/content/configurare-path-relativi-log4j-utilizzando-spring

UPDATE (2009/08/01) I've translated my article to English: http://www.megadix.it/node/136

How can I delete Docker's images?

In Bash:

for i in `sudo docker images|grep \<none\>|awk '{print $3}'`;do sudo docker rmi $i;done

This will remove all images with name "<none>". I found those images redundant.

How to access session variables from any class in ASP.NET?

I had the same error, because I was trying to manipulate session variables inside a custom Session class.

I had to pass the current context (system.web.httpcontext.current) into the class, and then everything worked out fine.

MA

How to compare strings in sql ignoring case?

You can use:

select * from your_table where upper(your_column) like '%ANGEL%'

Otherwise, you can use:

select * from your_table where upper(your_column) = 'ANGEL'

Which will be more efficient if you are looking for a match with no additional characters before or after your_column field as Gary Ray suggested in his comments.

why is plotting with Matplotlib so slow?

First off, (though this won't change the performance at all) consider cleaning up your code, similar to this:

import matplotlib.pyplot as plt
import numpy as np
import time

x = np.arange(0, 2*np.pi, 0.01)
y = np.sin(x)

fig, axes = plt.subplots(nrows=6)
styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
lines = [ax.plot(x, y, style)[0] for ax, style in zip(axes, styles)]

fig.show()

tstart = time.time()
for i in xrange(1, 20):
    for j, line in enumerate(lines, start=1):
        line.set_ydata(np.sin(j*x + i/10.0))
    fig.canvas.draw()

print 'FPS:' , 20/(time.time()-tstart)

With the above example, I get around 10fps.

Just a quick note, depending on your exact use case, matplotlib may not be a great choice. It's oriented towards publication-quality figures, not real-time display.

However, there are a lot of things you can do to speed this example up.

There are two main reasons why this is as slow as it is.

1) Calling fig.canvas.draw() redraws everything. It's your bottleneck. In your case, you don't need to re-draw things like the axes boundaries, tick labels, etc.

2) In your case, there are a lot of subplots with a lot of tick labels. These take a long time to draw.

Both these can be fixed by using blitting.

To do blitting efficiently, you'll have to use backend-specific code. In practice, if you're really worried about smooth animations, you're usually embedding matplotlib plots in some sort of gui toolkit, anyway, so this isn't much of an issue.

However, without knowing a bit more about what you're doing, I can't help you there.

Nonetheless, there is a gui-neutral way of doing it that is still reasonably fast.

import matplotlib.pyplot as plt
import numpy as np
import time

x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)

fig, axes = plt.subplots(nrows=6)

fig.show()

# We need to draw the canvas before we start animating...
fig.canvas.draw()

styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
    return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]

# Let's capture the background of the figure
backgrounds = [fig.canvas.copy_from_bbox(ax.bbox) for ax in axes]

tstart = time.time()
for i in xrange(1, 2000):
    items = enumerate(zip(lines, axes, backgrounds), start=1)
    for j, (line, ax, background) in items:
        fig.canvas.restore_region(background)
        line.set_ydata(np.sin(j*x + i/10.0))
        ax.draw_artist(line)
        fig.canvas.blit(ax.bbox)

print 'FPS:' , 2000/(time.time()-tstart)

This gives me ~200fps.

To make this a bit more convenient, there's an animations module in recent versions of matplotlib.

As an example:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)

fig, axes = plt.subplots(nrows=6)

styles = ['r-', 'g-', 'y-', 'm-', 'k-', 'c-']
def plot(ax, style):
    return ax.plot(x, y, style, animated=True)[0]
lines = [plot(ax, style) for ax, style in zip(axes, styles)]

def animate(i):
    for j, line in enumerate(lines, start=1):
        line.set_ydata(np.sin(j*x + i/10.0))
    return lines

# We'd normally specify a reasonable "interval" here...
ani = animation.FuncAnimation(fig, animate, xrange(1, 200), 
                              interval=0, blit=True)
plt.show()

How to install pip for Python 3.6 on Ubuntu 16.10?

In at least in ubuntu 16.10, the default python3 is python3.5. As such, all of the python3-X packages will be installed for python3.5 and not for python3.6.

You can verify this by checking the shebang of pip3:

$ head -n1 $(which pip3)
#!/usr/bin/python3

Fortunately, the pip installed by the python3-pip package is installed into the "shared" /usr/lib/python3/dist-packages such that python3.6 can also take advantage of it.

You can install packages for python3.6 by doing:

python3.6 -m pip install ...

For example:

$ python3.6 -m pip install requests
$ python3.6 -c 'import requests; print(requests.__file__)'
/usr/local/lib/python3.6/dist-packages/requests/__init__.py

Representing Directory & File Structure in Markdown Syntax

If you are concerned about Unicode characters you can use ASCII to build the structures, so your example structure becomes

.
+-- _config.yml
+-- _drafts
|   +-- begin-with-the-crazy-ideas.textile
|   +-- on-simplicity-in-technology.markdown
+-- _includes
|   +-- footer.html
|   +-- header.html
+-- _layouts
|   +-- default.html
|   +-- post.html
+-- _posts
|   +-- 2007-10-29-why-every-programmer-should-play-nethack.textile
|   +-- 2009-04-26-barcamp-boston-4-roundup.textile
+-- _data
|   +-- members.yml
+-- _site
+-- index.html

Which is similar to the format tree uses if you select ANSI output.

grep --ignore-case --only

It should be a problem in your version of grep.

Your test cases are working correctly here on my machine:

$ echo "abc" | grep -io abc
abc
$ echo "ABC" | grep -io abc
ABC

And my version is:

$ grep --version
grep (GNU grep) 2.10

VB.NET: how to prevent user input in a ComboBox

Using 'DropDownList' for the 'DropDownStyle' property of the combo box doesn't work as it changes the look and feel of the combo box. I am using Visual Studio 2019 Community Edition.

Using 'e.Handled = True' also doesn't work either as it still allows user input. Using 'False' for the 'Enabled' property of the combo box also doesn't work too because it stops the user from being able to use the combo box.

All of the "solutions" that have been proposed above are complete rubbish. What really works is this following code which restricts user input to certain keys such as up / down (for navigating through the list of all available choices in the combo box), suppressing all other key inputs:-

Private Sub ComboBox1_KeyDown(sender As Object, e As KeyEventArgs) Handles 
  ComboBox1.KeyDown
    REM The following code is executed whenever the user has pressed
    REM a key.  Added on Wednesday 1st January 2020.

    REM Determine what key the user has pressed.  Added on Wednesday
    REM 1st January 2020.
    Select Case e.KeyCode
        Case Keys.Down, Keys.Up
            REM This section is for whenever the user has pressed either
            REM the arrow down key or arrow up key.  Added on Wednesday
            REM 1st January 2020.

        Case Else
            REM This section is for whenever the user has pressed any
            REM other key.  Added on Wednesday 1st January 2020.

            REM Cancelling the key that the user has pressed.  Added on
            REM Wednesday 1st January 2020.
            e.SuppressKeyPress = True

    End Select

End Sub

Drawing a dot on HTML5 canvas

This should do the job

//get a reference to the canvas
var ctx = $('#canvas')[0].getContext("2d");

//draw a dot
ctx.beginPath();
ctx.arc(20, 20, 10, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();

How to encode the plus (+) symbol in a URL

It's safer to always percent-encode all characters except those defined as "unreserved" in RFC-3986.

unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"

So, percent-encode the plus character and other special characters.

The problem that you are having with pluses is because, according to RFC-1866 (HTML 2.0 specification), paragraph 8.2.1. subparagraph 1., "The form field names and values are escaped: space characters are replaced by `+', and then reserved characters are escaped"). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.

Create a menu Bar in WPF?

<StackPanel VerticalAlignment="Top">
    <Menu Width="Auto" Height="20">
        <MenuItem Header="_File">
            <MenuItem x:Name="AppExit" Header="E_xit" HorizontalAlignment="Left" Width="140" Click="AppExit_Click"/>
        </MenuItem>
        <MenuItem Header="_Tools">
            <MenuItem x:Name="Options" Header="_Options" HorizontalAlignment="Left" Width="140"/>
        </MenuItem>
        <MenuItem Header="_Help">
            <MenuItem x:Name="About" Header="&amp;About" HorizontalAlignment="Left" Width="140"/>
        </MenuItem>
    </Menu>
    <Label Content="Label"/>
</StackPanel>

Initial size for the ArrayList

if you want to use Collections.fill(list, obj); in order to fill the list with a repeated object alternatively you can use

ArrayList<Integer> arr=new ArrayList<Integer>(Collections.nCopies(10, 0));

the line copies 10 times 0 in to your ArrayList

How to initialize log4j properly?

As per Apache Log4j FAQ page:

Why do I see a warning about "No appenders found for logger" and "Please configure log4j properly"?

This occurs when the default configuration files log4j.properties and log4j.xml can not be found and the application performs no explicit configuration. log4j uses Thread.getContextClassLoader().getResource() to locate the default configuration files and does not directly check the file system. Knowing the appropriate location to place log4j.properties or log4j.xml requires understanding the search strategy of the class loader in use. log4j does not provide a default configuration since output to the console or to the file system may be prohibited in some environments.

Basically the warning No appenders could be found for logger means that you're using log4j logging system, but you haven't added any Appenders (such as FileAppender, ConsoleAppender, SocketAppender, SyslogAppender, etc.) into your configuration file or the configuration file is missing.

There are three ways to configure log4j: with a properties file (log4j.properties), with an XML file and through Java code (rootLogger.addAppender(new NullAppender());).

log4j.properties

If you've property file present (e.g. when installing Solr), you need to place this file within your classpath directory.

classpath

Here are some command suggestions in Linux how to determine your classpath value:

$ echo $CLASSPATH
$ ps wuax | grep -i classpath
$ grep -Ri classpath /etc/tomcat? /var/lib/tomcat?/conf /usr/share/tomcat?

or from Java: System.getProperty("java.class.path").

Log4j XML

Below is a basic XML configuration file for log4j in XML format:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  <appender name="console" class="org.apache.log4j.ConsoleAppender"> 
    <param name="Target" value="System.out"/> 
    <layout class="org.apache.log4j.PatternLayout"> 
      <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/> 
    </layout> 
  </appender> 

  <root> 
    <priority value ="debug" /> 
    <appender-ref ref="console" /> 
  </root>
  
</log4j:configuration>

Tomcat

If you're using Tomcat, you may place your log4j.properties into: /usr/share/tomcat?/lib/ or /var/lib/tomcat?/webapps/*/WEB-INF/lib/ folder.

Solr

For the reference, Solr default log4j.properties file looks like:

#  Logging level
solr.log=logs/
log4j.rootLogger=INFO, file, CONSOLE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender

log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x \u2013 %m%n

#- size rotation with log cleanup.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=4MB
log4j.appender.file.MaxBackupIndex=9

#- File to log to and log format
log4j.appender.file.File=${solr.log}/solr.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS}; %C; %m\n

log4j.logger.org.apache.zookeeper=WARN
log4j.logger.org.apache.hadoop=WARN

# set to INFO to enable infostream log messages
log4j.logger.org.apache.solr.update.LoggingInfoStream=OFF

Why can't log4j find my properties file in a J2EE or WAR application?

The short answer: the log4j classes and the properties file are not within the scope of the same classloader.

Log4j only uses the default Class.forName() mechanism for loading classes. Resources are handled similarly. See the documentation for java.lang.ClassLoader for more details.

So, if you're having problems, try loading the class or resource yourself. If you can't find it, neither will log4j. ;)


See also:

How to POST a FORM from HTML to ASPX page

In the html form, you need to supply additional viewstate variable and disable ViewState in a server page. This requires some control on both sides , though.

Form HTML:

<html><body> <form id='postForm' action='WebForm.aspx' method='POST'>
        <input type='text' name='postData' value='base-64-encoded-value' />
        <input type='hidden' name='__VIEWSTATE' value='' />  <!-- still need __VIEWSTATE, even empty one -->
    </form>

</body></html>

Note empty __VIEWSTATE.

WebForm.aspx:

<%@ Page Language="C#" AutoEventWireup="true" 
CodeBehind="WebForm.aspx.cs" Inherits="WebForm"
 EnableEventValidation="False" EnableViewState="false" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="postForm" runat="server">
        <asp:TextBox ID="postData" runat="server"></asp:TextBox>
    <div>

    </div>
    </form>
</body>
</html>

Note EnableEventValidation="False", EnableViewState="false" to prevent validation error for empty view state. Code Behind/Inherits values are not precise.

WebForm.cs:

public partial class WebForm : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string value = Encoding.Unicode.GetString(Convert.FromBase64String(this.postData.Text));
    }
}

JavaScript ternary operator example with functions

Heh, there are some pretty exciting uses of ternary syntax in your question; I like the last one the best...

x = (1 < 2) ? true : false;

The use of ternary here is totally unnecessary - you could simply write

x = (1 < 2);

Likewise, the condition element of a ternary statement is always evaluated as a Boolean value, and therefore you can express:

(IsChecked == true) ? removeItem($this) : addItem($this);

Simply as:

(IsChecked) ? removeItem($this) : addItem($this);

In fact, I would also remove the IsChecked temporary as well which leaves you with:

($this.hasClass("IsChecked")) ? removeItem($this) : addItem($this);

As for whether this is acceptable syntax, it sure is! It's a great way to reduce four lines of code into one without impacting readability. The only word of advice I would give you is to avoid nesting multiple ternary statements on the same line (that way lies madness!)

fork() child and parent processes

This is the correct way for getting the correct output.... However, childs parent id maybe sometimes printed as 1 because parent process gets terminated and the root process with pid = 1 controls this orphan process.

 pid_t  pid;
 pid = fork();
 if (pid == 0) 
    printf("This is the child process. My pid is %d and my parent's id 
      is %d.\n", getpid(), getppid());
 else 
     printf("This is the parent process. My pid is %d and my parent's 
         id is %d.\n", getpid(), pid);

Alternative to itoa() for converting integer to string C++?

int number = 123;

stringstream = s;

s << number;

cout << ss.str() << endl;

Running java with JAVA_OPTS env variable has no effect

I don't know of any JVM that actually checks the JAVA_OPTS environment variable. Usually this is used in scripts which launch the JVM and they usually just add it to the java command-line.

The key thing to understand here is that arguments to java that come before the -jar analyse.jar bit will only affect the JVM and won't be passed along to your program. So, modifying the java line in your script to:

java $JAVA_OPTS -jar analyse.jar $*

Should "just work".