Cancel "allman" brace-style when 'implicit-arrow-linebreak' is "beside" - node.js

I was looking at similar issues, but it seems my case is somewhat special.
I'm wanting to enforce the "allman" brace-style, but also want to set the implicit-arrow-linebreak to "beside", as pictured:
{
// ...
"rules": {
"brace-style": [2, "allman"],
"implicit-arrow-linebreak": [2, "as-beside"],
// ...
}
// ...
}
Now I have this snippet:
this.fetchMeta()
.then(metadata => {
this.meta = metadata;
this.initiateInterval();
}).catch(this.destroy);
The first error I get is regarding the brace-style, which I understand can be fixed by creating a newline. Trying to fix this causes this error, making the this keyword unavailable (which I need). Declaring this as self before-hand does not work.
How do I cancel out the "allman" brace-style when implicit-arrow-linebreak is set to "beside"?

Related

How can I best pattern match in Result::map

I know I can pattern match like this in rust
some_result.map(|some_number| {
match some_number {
1 => HttpResponse::NoContent().finish(),
_ => HttpResponse::NotFound().finish(),
}
})
but in Scala I can do like this
some_option.map {
case 1 => ???
case _ => ???
}
Is there a way to avoid the repetition of the variable some_number in the rust code above?
EDIT:
I found out i could do it this way, but i still think the original question answered my question best.
Ok(match result {
Ok(1) => HttpResponse::NoContent(),
Ok(_) => HttpResponse::NotFound(),
Err(_) => HttpResponse::InternalServerError()
}.finish())
its all about the context and in this case i didnt include much of it ...
EDIT #2:
Changed to another answer. I really like inverting the problem. And if else is not idiomatic rust afaik.
If we're just bike-shedding style, you could avoid introducing some_number entirely by matching on the whole result:
match some_result {
Ok(1) => Ok(HttpResponse::NoContent().finish()),
Ok(_) => Ok(HttpResponse::NotFound().finish()),
Err(e) => Err(e)
};
But this just trades some_number for some Oks and Errs. I would generally prefer the original style, but beauty is in the eye of the beholder.
There is no way that I know of to avoid the repetition, however I think it might be more idiomatic to simply write
some_result.map(
|some_number|
if some_number == 1 {
HttpResponse::NoContent().finish()
} else {
HttpResponse::NotFound().finish()
}
)
since there is no need for a match in such a simple situation.
EDIT: Why is an if statement more idiomatic than a match on in this situation?
The general idea is that match is more powerful than if (every if statement could be replaced by a match statement), therefore if is more specific, and thus should be used when possible (without matches!). The only exception is the switch/case use-case, which could be expressed as an if statement but a match one should be used.
But this is more of a guideline than an argument, so let's break down the reason why if is more idiomatic.
You start with something like
match some_number {
1 => { ... }
_ => { ... }
}
In the situation of
match x {
Pattern => { ... }
_ => { ... }
}
if let is more idiomatic. Since we're in this situation, we can rewrite
if let 1 = some_number { ... } else { ... }
However, in our case, we are matching a single literal, so it is more idiomatic to simply transform the if let into
if some_number == 1 { ... } else { ... }
The only exception is when you are planning to add more branching to the match statement, like
match some_number {
1 => { ... }
2 => { ... }
_ => { ... }
}
in which case it would make sense to keep it like that.
Keep in mind that being idiomatic also means being able to convey by the way you code your intention so that your programming becomes clear.
Note: Why is this more idiomatic than than simply matching the whole result?
Most of the time, being idiomatic is a synonym of being concise. If you are being verbose, it's a good hint you're not being idiomatic. However, it'is not always true, and this is a good example of being idiomatic meaning being more verbose.
When you are matching a result, you are expressing that you want to handle both the error and the ok case. When you are mapping, you are instead expressing that you are only interested in the ok case.
Most of the time, people don't want to handle manually the error case, and just add a ?. However, when they don't, most of the time they want to handle the error case. Finally, they might want not to handle the error, but also not to get rid of it right away.
These three choices are increasingly verbose to implement due to the frequency of usage. This means that you should not aim for the one that is less verbose, but instead for the solution that matches your intention, so that when one reads your code, it's easier to grasp your intention just by your choice structure of implementation.
In your original question, you seemed not to care about the error case, and also you didn't seem to want to get rid of it with ?, which is why I think that having an if statement inside a map is more idiomatic, in the sense that it is more clear and communicates better what you want to achieve. Indeed, I didn't even think about the error case, which is, IMO, what idiomatic means (ie. the capacity of adapting the way one thinks to ease the comprehension of code by writing it in the most expressive way, for a given language).
Finally, I would point out the most idiomatic choice for handling an error, that you didn't seem to take into account, and I wonder why.
if some_result? == 1 {
HttpResponse::NoContent().finish()
} else {
HttpResponse::NotFound().finish()
}
Where you have implemented an appropriate conversion from the eventual error type to the return type.

How can I combine Jest matchers, especially for mocked arguments?

I have some tests that accurately test my code's expected behavior, but that are rather brittle because I'm using literals. I'd like to make broader assertions about the shape of something. For example:
expect(mockedModule.mockFunction).toHaveBeenCalledTimes(1);
expect(mockedModule.mockFunction).toHaveLastBeenCalledWith(
"argument1",
{
field1: expect.stringMatching(/^argument1/), // but I also care about several other string matches
// and I _do not_ care about the order.
},
);
I could obviously repeatedly call toHaveLastBeenCalledWith with expect.any() littered through my code. But that's not very succinct, and it's not a great way to express the invariants I'm expecting.
Ideally I'd have something like:
expect(mockedModule.mockFunction).toHaveLastBeenCalledWith(
"argument1",
{
field1: expect.all(
expect.stringMatching(/^argument1/),
expect.any(
expect.stringMatching("42"),
expect.stringMatching("8675309"),
)
)
},
)
or the equivalent:
expect(mockedModule.mockFunction).toHaveLastBeenCalledWith(
"argument1",
{
field1: expect.all(
expect.stringMatching(/^argument1/).and(
expect.stringMatching("42").or(
expect.stringMatching("8675309)
)
),
)
},
)
But I have not found any functionality similar to this. This is most important for toHaveBeenCalledWith calls, where I never get a copy of the actual value, but have to create a matcher.

File or module level 'feature' possible?

Some optimizations/algorithms make code considerably less readable, so it's useful to keep the ability to disable the complex-and-unwieldily functionality within a file/module so any errors introduced when modifying this code can be quickly tested against the simple code.
Currently using const USE_SOME_FEATURE: bool = true; seems a reasonable way, but makes the code read a little strangely, since USE_SOME_FEATURE is being used like an ifdef in C.
For instance, clippy wants you to write:
if foo {
{ ..other code.. }
} else {
// final case
if USE_SOME_FEATURE {
{ ..fancy_code.. }
} else {
{ ..simple_code.. }
}
}
As:
if foo {
{ ..other code.. }
} else if USE_SOME_FEATURE {
// final case
{ ..fancy_code.. }
} else {
// final case
{ ..simple_code.. }
}
Which IMHO hurts readability, and can be ignored - but is caused by using a boolean where a feature might make more sense.
Is there a way to expose a feature within a file without having it listed in the crate?(since this is only for internal debugging and testing changes to code).
You can use a build script to create new cfg conditions. Use println!("cargo:rustc-cfg=whatever") in the build script, and then you can use #[cfg(whatever)] on your functions and statements.

xdebug ignoring error suppression - scream not installed

I have xdebug installed and am developing using Sublimetext 3 on a Ubuntu 14.10 laptop. My issue is with errors that are suppressed using # symbol being parsed by xdebug. So any autoloaders in my neat mvc architecture means that I have to press the run shortcut keys repeatedly to eventually see if my changes worked or not. Very Irritating. Whats more so I do not have scream enabled. In my phpinfo() a search for scream only produces xdebug.scream = Off.
So... in my autoloaders the following will trigger warnings with xdebug.
#include $class . ".php";
Do I have to specifically tell xdebug to not ignore errors? Is there a way for me to programatically state that I want #include( warnings to be ignored by xdebug but include( warnings to be triggered?
any help is appreciated.
SublimeText 3 xdebug settings
{
// For remote debugging to resolve the file locations
// it is required to configure the path mapping
// with the server path as key and local path as value.
//
// Make sure to use absolute path when defining server path,
// because Xdebug debugger engine does not return symbolic links.
//
// Example:
// "/absolute/path/to/file/on/server" : "/path/to/file/on/computer",
// "/var/www/htdocs/example/" : "C:/git/websites/example/"
"path_mapping": {
},
// Determine which URL to launch in the default web browser
// when starting/stopping a session.
"url": "",
// An IDE key is used to identify with debugger engine
// when Sublime Text will start or stop a debugging session.
//
// This package does not filter sessions by IDE key,
// it will accept any IDE key, also ones that do not match this configured IDE key.
// It is merely used when launching the default web browser with the configured URL.
"ide_key": "",
// Which port number Sublime Text should listen
// to connect with debugger engine.
"port": 9000,
// Show super globals in context view.
"super_globals": true,
// Maximum amount of array children
// and object's properties to return.
"max_children": 32,
// Maximum amount of
// variable data to initially retrieve.
"max_data": 1024,
// Maximum amount of nested levels to retrieve
// of array elements and object properties.
"max_depth": 1,
// Break at first line on session start, when debugger engine has connected.
"break_on_start": false,
// Break on exceptions, suspend execution
// when the exception name matches an entry in this list value.
"break_on_exception": [
// E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR
"Fatal error",
// E_RECOVERABLE_ERROR (since PHP 5.2.0)
"Catchable fatal error",
// E_WARNING, E_CORE_WARNING, E_COMPILE_WARNING, E_USER_WARNING
//"Warning"
],
// Always close debug windows and restore layout on session stop.
"close_on_stop": false,
// Do not show possible password values in context output.
"hide_password": false,
// Show in output parsed response instead of raw XML.
"pretty_output": false,
// Always launch browser on session start/stop.
// Note: This will only work if you have the 'url' setting configured.
"launch_browser": false,
// When launching browser on session stop do not execute script.
// By using parameter XDEBUG_SESSION_STOP_NO_EXEC instead of XDEBUG_SESSION_STOP.
"browser_no_execute": false,
// Do not use the debugging window layout.
"disable_layout": false,
// Window layout that is being used when debugging.
"debug_layout" : {
"cols": [0.0, 0.5, 1.0],
"rows": [0.0, 0.7, 1.0],
"cells": [[0, 0, 2, 1], [0, 1, 1, 2], [1, 1, 2, 2]]
},
// Group and index positions for debug views.
"breakpoint_group": 2,
"breakpoint_index": 1,
"context_group": 1,
"context_index": 0,
"stack_group": 2,
"stack_index": 0,
"watch_group": 1,
"watch_index": 1,
// Custom gutter icons for indicating current line or enabled/disabled breakpoints.
//
// Do not use same icon for following values, because Sublime Text is unable
// to use the same icon for different scopes, in case there are duplicate icons
// detected it will fall back to the corresponding icon in the package.
"breakpoint_enabled": "circle",
"breakpoint_disabled": "dot",
"breakpoint_current": "",
"current_line": "bookmark",
// Path to Python installation on your system.
// Which is being used to load missing modules.
//
// It is recommended to configure your Python path for Sublime Text 2
// especially on older UNIX systems, where some modules (xml.parsers.expat)
// might be missing and could improve performance of package.
//
// Example:
// "python_path" : "/usr/lib/python2.7"
"python_path" : "",
// Show detailed log information about communication
// between debugger engine and Sublime Text.
// Log can be found at Packages/User/Xdebug.log
"debug": false
}
And my project specific settings (just in case):
{
"folders":
[
{
"follow_symlinks": true,
"path": "/media/DATA/www/mysite.loc"
}
],
"settings": {
"xdebug": {
"url": "http://mysite.loc/",
}
}
}
I don't have sublime text, I'm a PhpStorm fan, so I can't verify anything for you. However, you should be able to add a break_on_exception configuration that doesn't include Notice, Warning, etc., and see if that works for you:
http://kerryritter.com/quickstart-guide-to-debugging-php-in-sublime-text-3/
"break_on_exception": [
// E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR
"Fatal error",
// E_RECOVERABLE_ERROR (since PHP 5.2.0)
"Catchable fatal error",
// // E_WARNING, E_CORE_WARNING, E_COMPILE_WARNING, E_USER_WARNING
// "Warning",
// // E_PARSE
// "Parse error",
// // E_NOTICE, E_USER_NOTICE
// "Notice",
// // E_STRICT
// "Strict standards",
// // E_DEPRECATED, E_USER_DEPRECATED (since PHP 5.3.0)
// "Deprecated",
// // 0
// "Xdebug",
// // default
// "Unknown error"
],
[UPDATE 2015-03-06]
If your IDE is breaking on even suppressed errors, then I doubt that's an option. However, my suggestion would be to have it NOT break on any errors because you can see the errors in your error log with a tail very easily, and I don't think suppressed errors will go there. However, the fact that this is such a problem for you makes it sound like you are using error suppression for a LOT of errors...just my two cents, but this should never be the case.
http://www.sitepoint.com/why-suppressing-notices-is-wrong/
Even suppressed errors slow down the performance of your app...so if you using suppression to avoid testing for undefined indexes, etc. e.g.
$var = #$_POST['name']
Just to avoid doing this:
$var = isset($_POST['name']) ? $_POST['name'] : null;
Then, you should reconsider what you are doing and stop using suppression. For instance, it would be better to write a wrapper class:
class Input {
private $_input;
public function __construct( array $data ) {
$this->_input= $data;
}
public function get( $name ) {
return isset($this->_input[$name]) ? $this->_input[$name] : null;
}
}
Doing this not only keeps you from having to suppress errors, but makes your code more flexible and--not least to mention--able to be run by unit tests if the Input is injected.
$data = new Input($_POST);
$var = $data->get('name');

In Puppet, how can I access a variable/attribute inside a defined type?

I would like to reference variables inside instances of defined types. For example, what can I do to reference $x and $y of foo a in bar b?
define foo($x, $y) {
}
define bar($foo) {
notify { "${::$foo::x}": } # <- how to make this reference work?
}
foo { 'a':
x => 'oh bar may you reference me',
y => 'please'
}
bar { 'b':
foo => Foo['a'],
require => Foo['a']
}
The reason why I would like this to work is that a foo instance may contain many values that I wouldn't like to repeat to each and every resource that might need them. Instead of passing those values again and again, thus repeating myself, I'd rather pass a reference to their container.
I've been looking all over and tried a bunch of things, but can't seem to find an answer to this question anywhere. I know it is possible to amend attributes, reference resources and read class attributes, but is it possible to read attributes of a resource/defined type? If it isn't what is then the best possible work around?
I've actually just found out that Puppetlab's stdlib module includes a getparam function that can be used to solve this problem.
So here is finally the solution to my own question:
define foo($x, $y) {
}
define bar($foo) {
notify { getparam(Foo[$foo], 'x'): }
notify { getparam(Foo[$foo], 'y'): }
}
foo { 'a':
x => 'oh bar may you reference me',
y => 'please'
}
bar { 'b':
foo => 'a'
}
Please note that the require => Foo['a'] in the definition of Bar['b'] does not appear to be needed.
It doesn't seem that you can access a defined type's attributes. Possible explanation here. What you can do however, is externalize it via hiera.
Hiera is a great way to separate your manifest logic from the data populating it, but it is not difficult to set up.
Installing
In my first try I was trying to access hiera variables by class reference; foo::a for example, but that doesn't work for defined types.
Using http://drewblessing.com/blog/-/blogs/puppet-hiera-implement-defined-resource-types-in-hiera as a guide, you can put declare all those attributes in hiera with a simple config:
Configuring:
hiera.yaml
:backends:
- yaml
:yaml:
:datadir: $hiera_dir
:hierarchy:
- common
$hiera_dir/common.yaml
foo:
a:
x: 'oh bar may you reference me'
y: 'please'
And then in your puppet manifest:
define foo ($x, $y) {
}
define bar($foo) {
require create_my_foos
$all_foos = hiera('foo')
# This is just for proof of concept, to show that the variable can be passed.
file { '/tmp/output.txt':
content => $all_foos[$foo]['x']
}
}
class create_my_foos {
$foo_instances = hiera('foo', [])
create_resources('foo', $foo_instances)
}
bar { 'b':
foo => 'a'
}
Now you can access foo's variables by calling the hiera('foo') function to get an array of foo's attributes, and do array lookups to get the exact parameter you need.
Note that hiera only looks up top-level keys, so you can't do hiera('foo'['a']['x]).

Resources