Don't wanna be here? Send us removal request.
Text
How do I select sibling elements in XPath?
Say I have the following structure:
<div> <input type="text" name="hoge" /> <span class="validation_error"></span> </div>
And imagine this general structure repeats a lot. How do you get the specific span elements next to a given input?
The following-sibling accessor is your friend here. It fetches an element that follows whatever you've singled out. It looks like this:
//input[@name="hoge"]/following-sibing::span
0 notes
Text
Shortcuts with the null coalesce operator
Something I only today realised you can do:
// say I have: $clans = [ 'Firebirds' => ['Jeff', 'Sally', 'Trent'], 'Team Bagel' => ['Tony', 'Maddy', 'Jude'], ] // and I also have: $blackList = ['Firebirds', 'The Racists']; // I might find myself doing this: foreach ($blackList as $ban) { if (isset($clans[$ban])) { foreach($clans[$ban] as $clanUser) { banUser($clanUser); } } } // but it turns out you can do this: foreach ($blackList as $ban) { foreach ($clans[$ban] ?? [] as $clanUser) { banUser($clanUser); } } // this seems like a pretty contrived example, but especially // when dealing with fixture data for tests, this arrangement // of data happens ALL THE TIME. It's a small thing, but getting // rid of one conditional, and one level of indentation makes a // surprisingly huge difference to code readability (at the expense // of maybe somebody reading the code and being thrown for a few // seconds by the null coalescing operator)
but also note:
foreach ($banList as $ban) { foreach ($clan[$ban] ?? [] as &$clanUser) { $clanUser = "banned"; } } foreach($clan['Firebirds'] as $user) { print($user . " "); // does not print "banned banned banned" } // because the null coalescing operator does not return a *reference* // to whatever you pass it, but a *copy*. This is going to limit how // much utility you get out of the shortcut, but if you're not // interested in altering the data inside your objects (e.g., you're // reading out of a heirarchical fixture file) then it shouldn't be // a huge problem (unless maybe if you're dealing with very large // data sets, in which case copyign the array might be an issue).
0 notes
Text
How do I type hint objects in plain PHP view templates?
Before it was Java, PHP was a templating language. Which is just as well, since working on legacy system often means that instead of Blade or Twig or Pug or whatever, the only thing you'll have to put your views together is PHP itself. Great! Maybe?
Anyway, if you're using an IDE to make the refactoring work easier, you'll want to make sure you let it know when you're using entities in your views.
/** @var $boomer Acme\Dynamite\BoomStick */
PHP Storm will pick this up and start delivering auto completions, which is good, but better is that if you decide to do some work on the BoomStick class later on it will more accurately let you know where that class was used in views.
0 notes
Text
Why won’t Go acknowledge my variables after if/else!?
func doProcess(foo bool) { bar := false if foo { bar := getRandomTrueOrFalse() } if bar { fmt.Println("bar") } else { fmt.Println("foo") } }
This pseudo code will not compile. You'll get an error saying that bar is never used, even though it plainly is being used.
I've seen this issue a few times, and I've also seen people get frustrated by this more than they should.
The answer is that (usually) Go isn't getting it wrong at all. bar isn't being used because the bar that gets declared in the if/else block is not the bar that gets declared outside of it. Remember that in Go, blocks carry their own variables, and := is a shortcut for initializing a new variable and then assigning to it. The following code can be fixed by changing the assignment of bar in the if statement from:
bar := getRandomTrueOrFalse()
to
bar = getRandomTrueOrFalse()
1 note
·
View note
Text
How do I check if a variable is there or not in PHP?
In most languages, using a variable if it doesn't exist will cause an exception or error or panic, or whatever that langauge does to tell you you're doing something stupid and potentially dangerous. PHP is no different. To avoid being scolded by the interpreter, you'll often want to check if a variable exists before you try to use it. In PHP you can use the isset method, which works like this:
if (isset($foo)) { echo $foo; }
This is pretty common knowledge, but what you might have missed if you learned how to use isset from a tutorial without reading its manual entry, is that this method can take a variable number of parameters. That means if you want to check if a whole bunch of variables exist or not, you don't need to write:
if (isset($foo) && isset($bar) && isset($baz)) { echo $foo + bar + baz; }
You can shorten it to:
if (isset($foo, $bar, $bar)) { echo $foo + bar + baz; }
0 notes
Text
How do I iterate through a multidimensional array in c#
Multidimensional arrays in c# work a little differently than you might imagine. While there is a Length property you can access, this returns the length of the entire array.
To get the number of dimensions in the array, use the Rank property. To get the number of elements inside specific dimensions, use the GetLenth(int)method.
Finally, to access properties inside the array, use the same comma notation that you used to create the array in the first place.
var md = int[,] {{1,2,3},{4,5,6}}; System.Console.WriteLine("total elements: {1}", md.Length); for (var d = 0; d < md.GetLength(0); ++d) { for (var i = 0; i < md.GetLength(1); ++i) { System.Console.WriteLine(md[d,i]); } }
0 notes
Text
How do I unit test a View Composer in Laravel?
Unit testing View Composers is pleasantly easy. Recall all we're aiming to do in this kind of test is make sure the wiring is hooked up correctly. Say we have this view composer:
<?php namespace App\Http\ViewComposers; use Illuminate\View\View; class FooComposer { public function compose(View $view) { $foo = \FooService::getSomeFoo(4); $view->with('foo', $foo); } }
All this composer does is query a Foo service and retreive a value, which it then passes to the view. For which views the composer is called is up to the service provider that does the registration (this can be tested sperately for each controller by checking that variables were made available to view).
Since all the dependencies are passed in to the method, and since Facades are also very testable, the unit test for the composer becomes trivial:
<?php use App\Http\ViewComposers\FooComposer; use Illuminate\View\View; class FooComposerTest extends TestCase { /** * @test */ public function it_passes_foo_data_to_view () { $composer = new SideBarComposer(); $view = Mockery::mock(View::class); \FooService::shouldReceive('getSomeFoo')->With(4)->once()->andReturn('some foo'); $view->shouldReceive('with')->with('foo', 'some foo')->once(); $composer->compose($view); } }
1 note
·
View note
Text
What counts as true for PHP’s isset ?
isset will return true for set variables that are public, exist, and have been initialized, otherwise false. That means private, protected, or variables fetched magically with __get will all count as false.
class Foo { private $foo; protected $bar; public $baz; public $baz_no_init; public function __construct(){ $this->foo = "foo"; $this->bar = "bar"; $this->baz = "baz"; } public function __get($name) { if ($name === "bax") { return "bax"; } } } $f = new Foo(); isset($f->foo); isset($f->bar); isset($f->baz); isset($f->bax_no_init); isset($f->bax);
This will return: FALSE, FALSE, TRUE, FALSE, FALSE.
1 note
·
View note
Text
How do I speed up HTML Purifier?
HTMLPurifier is a PHP library that cleans up HTML content, removing evil tags and making sure existing ones and normalising everything else. Very highly recommended. Works excellently. But the kind of work it’s doing (in PHP no less) means it’s also painfully slow even on small strings. It also eats up a huge amounts of memory. If you need to run it more than once per request, your server load is going to increase dramatically.
That said, it’s still possible to use HTMLPurifier more efficiently. The trick is to only use it when you absolutely need to. The less calls you make to that thing the better.
So, how to cut back on calls? We had to worry about this at work a while back, and what we wound up doing was using Redis as a temporary store for any sanitised content. The general process:
Before sanitising anything make a hash of the string, then check to see if there’s a key in Redis matching the hash. If so, use that. It’s the sanitised content. If not, sanitise, then put the sanitised content into the memory cache for next time.
$key = "safeStrings::" . md5($string); $safe = $this->cache->get($key); if ($safe !== null) { return $safe; } $safe = $this->purifier->purify($string); $this->cache->add($key, $safe, 60); return $safe;
This approach works because the cost of hashing text and storing/pulling it from the cache, no matter how big, is way faster than purifying it.
It also provides a simple kind of self regulation. Expressions used often stay in the cache. Those that aren’t are eventually phased out. This is (in my opinion) better than relying on a database stored purified string, since it will take up less room over time, and because it means you don’t need to take it on faith that things you purified before storing them in the db will still be purified the next time you take them out.
Savings wise, how much does this optimisation impact the server? Before we started caching results, we were spending a 50MB per request, mostly just on the purifying (we were running it about 10 to 15 times per request). After the optimisation, that went down to 8MB.
The only drawback I can think of is that there may be privacy issues if you can somehow gain access to the cache, but I feel that since all the text being parsed is destined for a publicly readable space anyway, this is a concession I’m happy to make.
1 note
·
View note
Text
What are the Start and Awake Timings for Loaded and Instantiated Unity Objects?
Instantiated Unity objects will have Awake triggered as soon as they enter the scene. Start will be called the first time the object is given an opportunity to update. Then it's Update all the way down.
However, game objects that are loaded from the Resources folder will only call their constructor. They will not have Awake or Start triggered until you specifically Instantiate them.
This is important to remember if you're relying on data setup in Awake during the object initialization phase.
0 notes
Text
How Do I Read YAML With Go?
Or more specifically, how I read the YAML Front Matter from a Jekyll post using Go? Reading a JSON file is a peice of cake, but YAML isn't exactly supported out of the box. This is how I'm currently going about it.
First, you need an external dependency, yaml.v2, which will provide the Marshall and Unmarshall methods for YAML.
Second, you need a structure to put your parsed YAML into. Like parsing JSON in Go, you can read YAML to an arbitrary map, but for the time being assume that we're going to read a file with a known structure to a predefined go struct.
YAML uses three dashes (---) to separate content document in streams, and Jekyll bundles its YAML front matter together with the post, between two sets of ---. We don't really want to bother with anything outside those separators, so we will only parse stuff so long as its contained between those sets of dashes.
So, we're looking for the YAML in a file like this:
--- layout: bar title: bax --- This is the post content...
And putting it into this structure:
type FrontMatter struct { Layout string Title string }
This makes a pretty simple task a little more complex since now we can't just read in the contents of a file and throw it at the YAML lib. Not that much more difficult, it just means the problem has two parts:
Extracting the YAML from the Jekyll post, and decoding that content.
To extract the content, first we open the file, and then use a scanner to read content into a buffer. Before we start processing, we split content into lines, which gives us a cleaner way of checking if we're inside the Jekyll front matter block or not.
var err error data, err := os.Open("path/to/file.md") if (err != nil) { // do error handling } scanner := bufio.NewScanner(data) scanner.Split(bufio.ScanLines)
Now we write to the buffer, add a newline after each read, since those are stripped out during the previous step.
var buffer bytes.Buffer inside := false for scanner.Scan() { text := scanner.Text() if (text == "---" && !inside) { inside = true continue } else if (text == "---" && inside) { break } buffer.WriteString(text + "\n") }
We now have a buffer that should be filled with YAML data. The second part of the problem is easy. We pass an array of bytes from the buffer into the Unmarshal method, and let it populate an object that we pass by reference.
var front FrontMatter err = yaml.Unmarshal([]byte(buffer.String()), &front) if (err != nil) { // do more error handling }
Now front contains the values that were stored in the post front matter!
0 notes
Text
What’s Happening to My Events In Unity Animations?
Imagine you’re making a Unity game where each level starts out with a small user interface animation. After the animation, enemies spawn and the player is allowed to start blasting them. You want the game level to be visible while the animation is playing, but you only want to spawn those monsters when the animation is done. So how do you do that?
Obviously polling the animation each frame is too stupid to consider, so instead you mighty try doing it with Animation Events. These allow you to put a marker on your animation that points to a method defined in the animation class.
You see the small blue tick at the end? That's a Unity Animation Event. You could set this one up to call a method that would let your game know that the animation is over and it was safe to start the wave.
In isolation. this will work.
However, as soon as your blend your animation, you may find that all of a sudden the event stops firing, or only fires some of the time.
Well that was fun while it lasted. The problem is the blending between animations.
You see how the event is triggered inside of the range designated by the blend? Turns out those events probably aren't going to trigger.
The reason is that during a blend, Unity interpolates between animations, which means that the frame with your trigger in it is as likely to fire as not. Probably less likely.
Ok, so now we know what the problem is we can figure something out, right? You may be tempted to do this:
This will also work!
But it's clearly a bad solution. For one it means that so long as events are important to your game logic, you can't use Unity's animation blending. For something like the UI you might be willing to take that cost, but it means that if you want to abstract this pattern out and use it elsewhere you’ll have to negate transitions there too. In short, it's a bad idea.
What do you use if not Animation events? State Machine Behaviours.
I don't really like these either, since now we're outside the animation logic, and we're looking at the entrance and exit times of the states themselves, but they are a more reliable solution, and the end result is the same.
So if you use State Machine Behaviours for driving logic out of animations, what do you use Animation Events for? As near as I can tell they're useful for anything that will add some kind of non-essential visual flair to your animations. For example, triggering a particle system or playing a sound when an animation reaches a certain point.
Other than that they're not reliable enough to be useful for anything.
0 notes
Text
How Do I Partially Mock Laravel Facades?
Facades make working with Laravel a lot easier than it could be otherwise. They're not magic bullets, but they do help to reduce the overall complexity of your application. That said, one problem with facades is easily testing them. You can turn them into mocks easily enough, but for facades that are called in lots of different places, this can make testing, especially integration testing, difficult. The solution is to use partial mocks.
With Laravel 5.2 You can turn a regular facade mock into a partial easily enough. Just call makePartial() after you set initial expectations.
\Config::shouldReceive('get')->once()->with('foo')->andReturn('bar'); \Config::makePartial();
This will override behaviour on the config for any call to get that wants foo, but leave all other calls free to pass through to the real object.
0 notes
Text
How Do I Mock PHP Built-In Methods?
Mocking classes and objects is easy. But what about mocking the built in PHP functions like date or fopen? PHP-Mock is a library that (in most circumstances) lets you mock the responses of those functions. So, while previously if you had code that relied on date() you might start thinking of ways to wrap that usage in a mockable object, PHPMock allows you to control the response to be whatever you want.
While this might now be a big deal for a log of modern code, which tends on rely on abstraction into single-use classes, this is still a particularly handy thing to be able to do when you're dealing with legacy code. In that case, you probably don't want to immediately start moving things and wrapping method calls, but you still want to be able to test that things are doing what they ostensibly should be.
There's even a PHPUnit integration that allows you to write code like this:
use PHPMock; public function testOpenFile () { $file_path = "/path/to/file.jpg"; $fopen = $this->getFunctionMock(__NAMESPACE__, 'fopen'); $fopen->expects($this->once())->willReturnCallback(function($file, $mode) use ($file_path) { $this->assertEquals($file_path, $file); $this->assertEquals('r', $mode); return 'foo-stream'; }); $result = fopen($file_path); $this->assertEquals('foo-stream', $result); }
Things to keep in mind: The mocked method cannot exist in the global namespace. Also, you need to be clear about the namespace you assign the mock method to. If you declare the mock in namespace A, you can't use it in namespace B.
0 notes