Rectangle 27 37

I'll be honest. I've only recently started writing unit tests, and when I go back to modify an old DLL that's from my bad old days, I'll hunker down and write unit tests to get it near 100% code coverage. I say "near" because the last few percent can be hard to get to due to the way that the code is structured, that it didn't have mocking or unit testing in mind (this happens a lot with the abstract classes or classes that P/Invoke into native code). And while I understand that 100% code coverage is not the same thing as 100% of all code execution paths, I've found that having the tests there is a good way to tell when I'm doing something that's going to break a lot of things.

To be honest, this is probably one reason why it has taken many developers (including myself) so long to get around to adopting unit testing (let's not get into TDD just yet).

I'm not saying that any of these are legitimate reasons, but they did more or less go through my head, and I bet they went through some of yours too:

So, apologies for the rambling post. In summary:

Let the flames begin! =)

very useful, but I think I disagree with you when you say that the end is near

When you use MongoDB database in the your application, I feel Unit Testing would even be more useful especially in testing the CRUD operations of your Entities because MongoDB leaves it to the application developer to ensure Foreign Key Referential integrity is upheld. Unlike RDMS databases, MongoDB and a lot of other NoSQL databases leave enforcement of valid associations of data to the application developer.

testing - Are you really using unit tests? - Stack Overflow

unit-testing testing
Rectangle 27 6

Like ligget78 said, DPAPI would be a good way to go for storing passwords. Check out the ProtectedData class on MSDN for example usage.

c# - What is the easiest way to encrypt a password when I save it to t...

c# encryption passwords
Rectangle 27 6

Like ligget78 said, DPAPI would be a good way to go for storing passwords. Check out the ProtectedData class on MSDN for example usage.

c# - What is the easiest way to encrypt a password when I save it to t...

c# encryption passwords
Rectangle 27 86

The good semantic way would be to use a checkbox, and then style it in different ways if it is checked or not. But there are no good ways do to it. You have to add extra span, extra div, and, for a really nice look, add some javascript.

So the best solution is to use a small jQuery function and two background images for styling the two different statuses of the button. Example with an up/down effect given by borders:

$(document).ready(function() {
  $('a#button').click(function() {
    $(this).toggleClass("down");
  });
});
a {
  background: #ccc;
  cursor: pointer;
  border-top: solid 2px #eaeaea;
  border-left: solid 2px #eaeaea;
  border-bottom: solid 2px #777;
  border-right: solid 2px #777;
  padding: 5px 5px;
}

a.down {
  background: #bbb;
  border-top: solid 2px #777;
  border-left: solid 2px #777;
  border-bottom: solid 2px #eaeaea;
  border-right: solid 2px #eaeaea;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a id="button" title="button">Press Me</a>

Obviously, you can add background images that represent button up and button down, and make the background color transparent.

Here's a JS fiddle with this code so you can try it out live... jsfiddle.net/LmULE

FYI: I did the same thing as this post, only using Google Dart steelpinjata.com/2014/03/20/toggle-buttons-in-dart. Note: works in Chromium, but can be compiled to JavaScript and will work in other modern browsers. IE does not count as a browser ;-)

jquery - How do you create a toggle button? - Stack Overflow

jquery html css
Rectangle 27 3

I'll add a note that in 99% of web apps, even ajax heavy apps, the connection speed and response of the web server is going to drive the performance of your app rather than the javascript. I'm not saying the you should write intentionally slow code or that generally being aware of what things are likely to be faster than others isn't good.

But I am wondering if you're trying to solve a problem that doesn't really exist yet, or even if you're optimizing for something that might change in the near future (say, if more people start using a browser that supports getElementsByClassName() function referred to earlier), making your optimized code actually run slower.

javascript - Good ways to improve jQuery selector performance? - Stack...

javascript jquery performance css-selectors
Rectangle 27 3

I'll add a note that in 99% of web apps, even ajax heavy apps, the connection speed and response of the web server is going to drive the performance of your app rather than the javascript. I'm not saying the you should write intentionally slow code or that generally being aware of what things are likely to be faster than others isn't good.

But I am wondering if you're trying to solve a problem that doesn't really exist yet, or even if you're optimizing for something that might change in the near future (say, if more people start using a browser that supports getElementsByClassName() function referred to earlier), making your optimized code actually run slower.

javascript - Good ways to improve jQuery selector performance? - Stack...

javascript jquery performance css-selectors
Rectangle 27 5

NB: This answer was written back in 2012, when Symfony 2.0 was out and then it was the good way to do! Please don't downvote any more :)

Today I went through same problem myself, so here are my 5 cents. According to the official documentation it is usually not required to inject request into your services. In your service class you can pass kernel container (injecting it is not a big overhead, as it sounds), and then access request like this:

public function __construct(\AppKernel $kernel)
{
    $this->kernel = $kernel;
}

public function getRequest()
{
    if ($this->kernel->getContainer()->has('request')) {
        $request = $this->kernel->getContainer()->get('request');
    } else {
        $request = Request::createFromGlobals();
    }
    return $request;
}

This code is also working fine when service is accessed in CLI (eg, during unit-testing).

Yes, that works. Just a little modification: Since kernel -> getContainer() returns a service_container, its better to inject it instead of the kernel (as the documentation stated). I already did arguments: [@service_container] and it works perfectly - no need to go through the kernel.

You are right. Thanks for the tip!

Quite wrong actually, with Symfony 2.1.x and a CLI command, has returns true, and the subsequent get('request') throws an exception.

@Gremo My answer was written almost a year ago and relevant for Symfony 2.0, so your downvote is not correct :)

symfony - How to inject the @request into a service? - Stack Overflow

symfony service dependency-injection
Rectangle 27 5

NB: This answer was written back in 2012, when Symfony 2.0 was out and then it was the good way to do! Please don't downvote any more :)

Today I went through same problem myself, so here are my 5 cents. According to the official documentation it is usually not required to inject request into your services. In your service class you can pass kernel container (injecting it is not a big overhead, as it sounds), and then access request like this:

public function __construct(\AppKernel $kernel)
{
    $this->kernel = $kernel;
}

public function getRequest()
{
    if ($this->kernel->getContainer()->has('request')) {
        $request = $this->kernel->getContainer()->get('request');
    } else {
        $request = Request::createFromGlobals();
    }
    return $request;
}

This code is also working fine when service is accessed in CLI (eg, during unit-testing).

Yes, that works. Just a little modification: Since kernel -> getContainer() returns a service_container, its better to inject it instead of the kernel (as the documentation stated). I already did arguments: [@service_container] and it works perfectly - no need to go through the kernel.

You are right. Thanks for the tip!

Quite wrong actually, with Symfony 2.1.x and a CLI command, has returns true, and the subsequent get('request') throws an exception.

@Gremo My answer was written almost a year ago and relevant for Symfony 2.0, so your downvote is not correct :)

symfony - How to inject the @request into a service? - Stack Overflow

symfony service dependency-injection
Rectangle 27 10

Unfortunately, there is no good way to simulate a low-battery environment. You actually will most likely need to physically charge your device's battery until it is just above the "low battery" state and then debug your application.

To address what others have said:

  • There is no way to simulate low battery notifications. The project that @Bo. provided does nothing more than schedule random UILocalNotifications. It isn't all that much different than just showing a UIAlertView in your app.
  • You could try what @Andrew R. said and use the private methods found in the UIDevice header. But it is doubtful that you will exactly mimic the effects of a real low-battery environment.

Although it is a pain to have to wait for you device to actually hit the low-battery state, you could add some battery-draining code to your app to assist you. For example, using the GPS might drain the battery a bit quicker.

objective c - Simulating low battery for iPhones - Stack Overflow

iphone objective-c ios-simulator simulation power-management
Rectangle 27 4

This is as good explanation of what is going on as any.

FYI, the link is dead; looks like the domain expired.

c# - IEnumerable to SelectList, no value is selected - Stack O...

c# asp.net-mvc
Rectangle 27 21

Okay, I'll bite... James has a good answer, so I'm going to try a different tact and give a more down-to-earth viewpoint.

Broadly speaking, a class is something that can be instantiated. singleton objects (scala) traits (Scala) and interfaces (Scala) are also commonly considered to be classes. This makes sense, as singletons are still instantiated (via compiler-generated code) and an interface can be instantiated as part of a subclass.

Which brings us to the second point. classes are the primary unit of design in most object-oriented languages (though not the prototype-based ones like javascript). Polymorphism and subclassing are both defined in terms of classes. classes also provide a namespace and visibility controls.

types are a very different beast, every possible value that the system can express will have one or more types, and these can sometimes be equated to classes, for example:

(Int) => String // both the type and class are Function1[Int,String]
"hello world" // class and type are String

You also get some interesting differences between Scala and Java:

7 // both the class and type are Int in Scala
  // in Java there's no class and the type is Integer.TYPE

println("hello world") // the return type is Unit, of class Unit
                       // Java has void as a type, but no corresponding class

error("oops") // the type and class are both "Nothing"

and the really fun types that aren't classes at all. For example, this.type always refers to the unique type of this. It's unique to a single instance and isn't even compatible with other instances of the same class.

There are also abstract types and type parameters. For example:

type A // 'A' is an undetermined abstract type
       // to be made concrete in a subclass

class Seq[T] { ... } // T is a type, but not a class

Seq is interesting as it's a class, but not a type. More accurately, it's a "type constructor"; something that will construct a valid type when supplied with the necessary type parameter. Another term for type constructors is "higher kinded types", I personally don't like this term, as "type constructor" encourages me to think in terms of supplying types like any other form of argument - a mental model that has served me well for Scala.

"higher-kinded" rightly implies that Seq has a "kind", which is * => *, this notation states that Seq will take a single type and yield a single type (this is similar to curried notation for describing functions). By way of comparison, the kind of Map is * => * => * because it takes two type parameters.

The difference between "type constructor" and "higher kinded type" is a matter of how it can be used. In Java List can't be used as a type (ignoring raw types, which suck) but List can be used as a type constructor. In Scala it can be used either way.

@James - Even that distinction sometimes isn't enough, when you start looking at compiler internal representations it gets even more convoluted. Especially when you start considering erasure.

Just one upvote, seriously? Was the reply that useless?

'Java has void as a type, but no corresponding class'. Java has a type that represents void: java.lang.Void. It can be used similarly to the 'boxing types' Integer, Double, etc. It's used a fair bit in the reflection and concurrent APIs and can be used at will in class declarations and bodies.

What is the difference between a class and a type in Scala (and Java)?...

java class scala types language-design
Rectangle 27 30

I think the main issue is that if you're going to piggyback on the built-in ASP.NET FormsAuthentication class (and there's no good reason you shouldn't), something at the end of the day is going to call FormsAuthentication.RedirectToLoginPage() which is going to look at the one configured URL. There's only one login URL, ever, and that's just how they designed it.

My stab at the problem (possibly a Rube Goldberg implementation) would be to let it redirect to a single login page at the root shared by all clients, say /account/login. This login page wouldn't actually display anything; it inspects either the ReturnUrl parameter or some value I've got in the session or a cookie that identifies the client and uses that to issue an immediate 302 redirect to the specific /client/account/login page. It's an extra redirect, but likely not noticeable and it lets you use the built in redirection mechanisms.

The other option is to create your own custom attribute as you describe and avoid anything that calls the RedirectToLoginPage() method on the FormsAuthentication class, since you'll be replacing it with your own redirection logic. (You might create your own class that is similar.) Since it's a static class, I'm not aware of any mechanism by which you could just inject your own alternative interface and have it magically work with the existing [Authorize] attribute, which blows, but people have done similar things before.

this is probably the safest approach. creating your own [MyAuthorize] attribute is dangerous. unless your build is verifying that people don't use the built-in [Authorize] attribute you risk people (or yourself) forgetting and using the wrong one

.net - How to redirect to a dynamic login URL in ASP.NET MVC - Stack O...

.net asp.net-mvc authentication forms-authentication asp.net-routing
Rectangle 27 18

Using a pre ES5 'hack'

The generic issue of dynamic this in a callback is explained in this answer which is very good - I'm not going to repeat what Felix said. I'm going to discuss promise specific solutions instead:

Promises are specified under the Promises/A+ specification which allows promise libraries to consume eachother's promises seamlessly. Angular $q promises honor that specification and therefor and Angular promise must by definition execute the .then callbacks as functions - that is without setting this. In strict mode doing promise.then(fn) will always evaluate this to undefined inside fn (and to window in non-strict mode).

The reasoning is that ES6 is across the corner and solves these problems more elegantly.

So, what are your options?

  • Some promise libraries provide a .bind method (Bluebird for example), you can use these promises inside Angular and swap out $q.
  • ES6, CoffeeScript, TypeScript and AtScript all include a => operator which binds this.
  • You can use the ES5 solution using .bind
  • You can use one of the hacks in the aforementioned answer by Felix.
Restangular.one('me').get().bind(this).then(function(response) {
    this._myVariable = true; // this is correct
});
Restangular.one('me').get().then(response => {
    this._myVariable = true; // this is correct
});
Restangular.one('me').get().then(function(response) {
    this._myVariable = true; // this is correct
}.bind(this));
var that = this;
Restangular.one('me').get().then(function(response) {
    that._myVariable = true; // this is correct
});

Your current design does not contain any way to _know when _myVariable is available. You'd have to poll it or rely on internal state ordering. I believe you can do better and have a design where you always execute code when the variable is available:

Then you can use _myVariable via this._myVariable.then(function(value){. This might seem tedious but if you use $q.all you can easily do this with several values and this is completely safe in terms of synchronization of state.

If you want to lazy load it and not call it the first time (that is, only when myFunction is called) - I totally get that. You can use a getter and do:

app.service('exampleService', ['Restangular', function(Restangular) {
    this.__hidden = null;
    Object.defineProperty(this,"_myVariable", {
      get: function(){ 
        return this.__hidden || (this.__hidden = Restangular.one('me')); 
      }
    });
}];

Great answer!!!. Could you please give a clear example on the last point you mentioned about $q.all??

bind - Using this within a promise in AngularJS - Stack Overflow

this bind promise
Rectangle 27 1

I would say that using a sorting algorithm and then going through the sorted list to find the number is a good way to do it.

And now the problem is finding "the best" sorting algorithm. There are a lot of sorting algorithms, each of them with its strong and weak points, so this is quite a complicated question. The Wikipedia entry seems like a nice source of info on that.

algorithm - Finding a single number in a list - Stack Overflow

algorithm puzzle
Rectangle 27 12

If you have two or more products that are going to share a good amount of common code, like a suite of products, you might want to consider creating just a single xcode project, and then add a different target for each product that will be built from both shared and product-specific code. With a lot of shared code, a client/server pair of products would possibly be great candidates for going this way.

Boiled-down, the basic deal is that for each target in your xcode project that you want to build, you specify which files should be used to build it: source files, art, xibs, and so on. This way, for example, you can setup your client product to be built using files A,B,C,D,E,F, and your server product to be built using files A,F,X,Y,Z.

I really like having every related product living under a single xcode project "roof", because you wont have to jump around xcode projects, and it really simplifies SCM management for the shared files.

Update: there's a little bit of extra hassle involved when it comes to configuring target-specific header files in xcode (it's always something...right?!); for example, use "myHeaderA.h" for this target and "myHeaderB.h" for that target. Here's a great post that shares how to do it: controlling which project header file Xcode will include. Caution: after you set things up this way, xcode no longer knows any paths to search for any of your target header files, so you have to set them up manually. To do this, right-click Get Info on your target, select Build category, then add your paths via the "Header Search Paths" setting. The paths are searched in the order that you enter them.

Can this be done with the new workspace now?

Yes - I'm now running Xcode 4.3.2 and didn't need to change a thing.

Sharing classes between projects in xcode/objective-c - Stack Overflow

objective-c xcode macos sharing
Rectangle 27 10

i was annoyed by this as well but working with and refactoring projects with large codebases quickly taught me otherwise. Having embraced the concept i think that it's a very good way to structure your code "physically" as well as logically. When you have a large project and the namespaces do not match up to the folders it becomes difficult to locate files quickly. It's also that much more difficult to remember where things are...

Also, if ReSharper recommends it, then it's probably a good idea. E.g. R# will complain if your class' namespace does not match its folder name.

Yes, but ReSharper also adds a "Namespace Provider" property to the property grid for a folder. If you set it to false, then the folder will no longer contribute to the namespace. This is good, for instance, for folders containing generated code.

Any idea how this can be enforced without resharper?

c# - Should I stop fighting Visual Studio's default namespace naming c...

c# visual-studio naming-conventions namespaces
Rectangle 27 4

2) Yes there is a better way. You're doing the regex because you want to match parts of the URL that you don't know. Why not do $parts = explode("/", $uri) then see if you can find the page you're looking for? You will need to define how many parameters you're expecting for each page or you wont know whether to pick forums with parameters array("viewform", 123) or forums/viewforum with parameters array(123).

explode feels loads better than a regex. It also adds the benefit of improved error handling. What if the argument passed to viewforum is not a number? Surely you can do better than "404" ;)

3) Make a seperate ajax handler. Ajax is hidden from view anyway so you don't need to bother with providing semantic URLs.

function find_route($parts) {
    foreach ($uri_route_map as $route => $route_data) {
        $route_check = implode("/", array_slice($parts, 0, count($parts) - $route_data['num_arguments']));
        if ($route_check === $route) {
            return $route_data;
        }
    }
    throw new Exception("404?");
}

$uri = "forum/viewforum/522";

$parts = explode("/", $uri);
$route = find_route($parts);
$arguments = array_slice($parts, count($parts) - $route['num_arguments']);

$controller = $rRoute['controller'];
$method = $rRoute['method'];
$controller_instance = new $controller();
call_user_func_array(array($controller_instance, $method), $arguments);

Because of $uri_route_map you can't 'dynamically' register more plugins or pages or 'routes'. I'd add a function to add more routes dynamically to the Router.

Additionally you could consider some auto-discovery scheme that, for instance, will check the folder plugins/ for folders with a file called "manifest.php" that, when called, will optionally add more routes to Router.

Thanks for the input my previous attempt, actually used the explode method but then I realized I needed to check for page numbers if they existed and id numbers if they existed. I am not exactly sure how I would use explode and still be able to check for the page numbers and id numbers

I've added an example. This gets the arguments as a list, you could choose to name them if you want but I don't think you need to.

this looks interesting, I am trying to get the example to work, could you help debug it so I could see how it works, $uri_route_map is not being read by the function to start, thanks for the help this far

In my example I didn't bother passing in $uri_route_map as I expect find_route will be a function in a class somewhere.

regex - Is this a good way to match URI to class/method in PHP for MVC...

php regex performance model-view-controller uri
Rectangle 27 42

Conflicts are going to happen if both branches have changes to the files. This is a good thing. Keeping your branches up-to-date with each other will prevent some of them . However over all, conflicts are not bad. The rebase option can also prevent many of them from happening.

git merge branch_1

If you are on master, merging will bring the changes as you expect.

git rebase branch_1

This will take the changes from branch_1 and append them to master without a merge commit.

Git merge branch into master - Stack Overflow

git git-branch git-merge
Rectangle 27 3

What you have in the post that you've mentioned is not a good way to go. I suggest starting your TDD adventure without mocking. Start with test-first approach and you will end up with design, which does not require such hideous testing (e.g. partial mocking). Then start mocking, but remember: only mock what you own (so if ResultSet is a JDBC class, you definately should not mock it).

unit testing - Local objects impact on Mocking - Stack Overflow

unit-testing mocking tdd
Rectangle 27 2

Writing a C program that checks for ESTALE is a good option if you don't mind waiting for the command to finish because of the stale file system. If you want to implement a "timeout" option the best way I've found to implement it (in a C program) is to fork a child process that tries to open the file. You then check if the child process has finished reading a file successfully in the filesystem within an allocated amount of time.

Here is a small proof of concept C program to do this:

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/wait.h>


void readFile();
void waitForChild(int pid);


int main(int argc, char *argv[])
{
  int pid;

  pid = fork();

  if(pid == 0) {
    // Child process.
    readFile();
  }
  else if(pid > 0) {
    // Parent process.
    waitForChild(pid);
  }
  else {
    // Error
    perror("Fork");
    exit(1);
  }

  return 0;
}

void waitForChild(int child_pid)
{
  int timeout = 2; // 2 seconds timeout.
  int status;
  int pid;

  while(timeout != 0) {
    pid = waitpid(child_pid, &status, WNOHANG);
    if(pid == 0) {
      // Still waiting for a child.
      sleep(1);
      timeout--;
    }
    else if(pid == -1) {
      // Error
      perror("waitpid()");
      exit(1);
    }
    else {
      // The child exited.
      if(WIFEXITED(status)) {
        // Child was able to call exit().
        if(WEXITSTATUS(status) == 0) {
          printf("File read successfully!\n");
          return;
        }
      }
      printf("File NOT read successfully.\n");
      return;
    }
  }

  // The child did not finish and the timeout was hit.
  kill(child_pid, 9);
  printf("Timeout reading the file!\n");
}

void readFile()
{
  int fd;

  fd = open("/path/to/a/file", O_RDWR);
  if(fd == -1) {
    // Error
    perror("open()");
    exit(1);
  }
  else {
    close(fd);
    exit(0);
  }
}

linux - Is there a good way to detect a stale NFS mount - Stack Overfl...

linux bash unix shell nfs