SwiftLint: Exclude file for specific rule - swiftlint

I'm trying to do something like this in my .swiftlint.yml file:
force_cast:
severity: warning # explicitly
excluded:
- Dog.swift
I have this code and I don't like the force_try warning I'm getting for it:
let cell = tableView.dequeueReusableCellWithIdentifier(Constants.dogViewCellReuseIdentifier,
forIndexPath: indexPath) as! DogViewCell
I want to suppress the warning for this file by excluding this file from the rule.
Is there a way to do that ?

Well, if you don't want some specific rules to be applied to a specific file you can use the technique mentioned by #Benno Kress. For that you need to add a comment in your swift file as given below.
The rules will be disabled until the end of the file or until the linter sees a matching enable comment:
// swiftlint:disable <rule1>
YOUR CODE WHERE NO rule1 is applied
// swiftlint:enable <rule1>
It is also possible to skip some files by configuring swiftlint.
add a ".swiftlint.yml" file in the directory where you'll run SwiftLint.
Add the following content to exclude some files. Lets say file1, file2 ... etc
excluded:
- file1
- file2
- folder1
- folder1/ExcludedFile.swift
To disable some rules completely add the following to the same ".swiftlint.yml" file.
disabled_rules: # rule identifiers to exclude from running
- colon
- comma
- control_statement
for more information, refer the following links.
https://swifting.io/blog/2016/03/29/11-swiftlint/
https://github.com/realm/SwiftLint#disable-rules-in-code

You can write // swiftlint:disable force_cast at the beginning of the file in which you want to supress the warning for this rule. It gets disabled until the end of the file or until you add the line // swiftlint:enable force_cast.
Source: https://github.com/realm/SwiftLint#disable-rules-in-code

I just get rid with force_cast
Step 1:
cd path-to-your-project
Step 2:
touch .swiftlint.yml
Step 3:
open .swiftlint.yml and add the rule
disabled_rules: # rule identifiers to exclude from running
- force_cast
Reference - https://github.com/realm/SwiftLint#disable-rules-in-code

Configure SwiftLint by adding a .swiftlint.yml file from the directory you'll run SwiftLint from. Here is the complete set of options you can use in your .swiftlint.yml file
disabled_rules: # rule identifiers to exclude from running
- colon
- comma
- control_statement
opt_in_rules: # some rules are only opt-in
- empty_count
# Find all the available rules by running:
# swiftlint rules
included: # paths to include during linting. `--path` is ignored if present.
- Source
excluded: # paths to ignore during linting. Takes precedence over `included`.
- Carthage
- Pods
- Source/ExcludedFolder
- Source/ExcludedFile.swift
- Source/*/ExcludedFile.swift # Exclude files with a wildcard
analyzer_rules: # Rules run by `swiftlint analyze` (experimental)
- explicit_self
# configurable rules can be customized from this configuration file
# binary rules can set their severity level
force_cast: warning # implicitly
force_try:
severity: warning # explicitly
# rules that have both warning and error levels, can set just the warning level
# implicitly
line_length: 110
# they can set both implicitly with an array
type_body_length:
- 300 # warning
- 400 # error
# or they can set both explicitly
file_length:
warning: 500
error: 1200
# naming rules can set warnings/errors for min_length and max_length
# additionally they can set excluded names
type_name:
min_length: 4 # only warning
max_length: # warning and error
warning: 40
error: 50
excluded: iPhone # excluded via string
identifier_name:
min_length: # only min_length
error: 4 # only error
excluded: # excluded via string array
- id
- URL
- GlobalAPIKey
reporter: "xcode" # reporter type (xcode, json, csv, checkstyle, junit, html, emoji, sonarqube, markdown)
Reference: github.com/realm/SwiftLint#disable-rules-in-code

You can add a new .swiftlint.yml file to the excluded folder and override rules there:
project_root/.swiftlint.yml:
opt_in_rules:
force_unwrapping
.. and other rules
and in
project_root/your_excluded_folder/.swiftlint.yml
disabled_rules:
- force_unwrapping
Then force_unwrapping will not be applied to your_excluded_folder and all subfolders
Config file from subfolder will "override" rules in the root config file.
This is useful for example for the unit tests folder

Maybe this is a better approach:
guard let cell = tableView.dequeueReusableCellWithIdentifier(Constants.dogViewCellReuseIdentifier,
forIndexPath: indexPath) as? DogViewCell else {
return UITableviewCell()
}

Related

How do I list files and directories those are not hidden in current directory using crystal language?

I wrote my own minimal version of "ls" command (Linux) using crystal language and here is my code:
require "dir"
require "file"
def main()
pwd = Dir.current
list_dir = Dir.children(pwd)
puts("[+] location: #{pwd}")
puts("------------------------------------------")
list_dir.each do |line|
check = File.file?(line)
if check == true
puts("[+] file : #{line}")
elsif check == false
puts("[+] directory: #{line}")
else
puts("[+] unknown : #{line}")
end
end
end
main
It works but it also listing all hidden files and directories (.files & .directories) too and I do not want to show those. I want the result more like "ls -l" command's result not like "ls -la".
So, what I need to implement to stop showing hidden files and directories?
There is nothing special about "hidden" files. It's just a convention to hide file names starting with a dot in some contexts by default. Dir.children does not follow that convention and expects the user to apply approriate filtering.
The recommended way to check if a file name starts with a dot is file_name.starts_with?(".").

Sphinx builtin themes not found

In my conf.py it says I should see the documentation for a list of builtin-themes. Now my first google hit leads me to http://www.sphinx-doc.org/en/stable/theming.html#builtin-themes . There are a bunch of themes in there which my sphinx does not know about. For example 'classic'.
in conf.py
html_theme = 'classic'
On my shell I do: sphinx-build -b html source build
writing output... [100%] index
Exception occurred:
File "~\appdata\local\programs\python\python35\lib\site-packages\sphinx\jinja2glue.py", line 200, in get_source
raise TemplateNotFound(template)
jinja2.exceptions.TemplateNotFound: about.html
sphinx version: 1.6.3.
I had same problem because I used alabaster theme before. There are a few lines in conf.py that are needed for alabaster and break other themes. You need to comment them out.
# Custom sidebar templates, must be a dictionary that maps document names
# to template names.
#
# This is required for the alabaster theme
# refs: http://alabaster.readthedocs.io/en/latest/installation.html#sidebars
# html_sidebars = {
# '**': [
# 'about.html',
# 'navigation.html',
# 'relations.html', # needs 'show_related': True theme option to display
# 'searchbox.html',
# 'donate.html',
# ]
# }
It is an issue after changing alabaster theme to another one that doesn't use about.html. Laurent said the workaround.
Issue:
https://github.com/sphinx-doc/sphinx/issues/3987

rspec running with development database as opposed to test database

When I run my rspec test, I noticed that the test is using my development database as opposed to using the one for test environment.
My spec_helper.rb file is as follow:
# This file was generated by the `rails generate rspec:install` command. Conventionally, all
# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
# The generated `.rspec` file contains `--require spec_helper` which will cause this
# file to always be loaded, without a need to explicitly require it in any files.
#
# Given that it is always loaded, you are encouraged to keep this file as
# light-weight as possible. Requiring heavyweight dependencies from this file
# will add to the boot time of your test suite on EVERY test run, even for an
# individual file that may not need all of that loaded. Instead, consider making
# a separate helper file that requires the additional dependencies and performs
# the additional setup, and require it from the spec files that actually need it.
# require 'webmock/rspec'
# WebMock.disable_net_connect!(allow_localhost: true)
#
# The `.rspec` file also contains a few flags that are not defaults but that
# users commonly want.
#
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
require 'rubygems'
# require 'test/unit'
require 'redis'
ENV['RAILS_ENV'] = 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'factory_girl_rails'
# Capybara.register_driver :selenium do |app|
# Capybara::Selenium::Driver.new(app, :browser => :chrome)
# end
RSpec.configure do |config|
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
# rspec-mocks config goes here. You can use an alternate test double
# library (such as bogus or mocha) by changing the `mock_with` option here.
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended, and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
config.mock_with :rspec
config.before(:all) do
ActiveRecord::Base.skip_callbacks = true
end
config.after(:all) do
ActiveRecord::Base.skip_callbacks = false
end
end
And the rails_helper.rb file is as follow:
# This file is copied to spec/ when you run 'rails generate rspec:install'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'database_cleaner'
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }
# Checks for pending migrations before tests are run.
# If you are not using ActiveRecord, you can remove this line.
ActiveRecord::Migration.maintain_test_schema!
RSpec.configure do |config|
# Remove this line if you're not using ActiveRecord or ActiveRecord fixtures
config.fixture_path = "#{::Rails.root}/spec/fixtures"
# If you're not using ActiveRecord, or you'd prefer not to run each of your
# examples within a transaction, remove the following line or assign false
# instead of true.
config.use_transactional_fixtures = false
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
end
BTW: if it is any help, I just finished solving an issue with database_cleaner wiping my development db according to this post.
How can I restrict the test to run only in test environment, and using only the test database?
All help is welcome, thank you.
My database.yml is as follow:
# PostgreSQL. Versions 8.2 and up are supported.
#
# Install the pg driver:
# gem install pg
# On OS X with Homebrew:
# gem install pg -- --with-pg-config=/usr/local/bin/pg_config
# On OS X with MacPorts:
# gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config
# On Windows:
# gem install pg
# Choose the win32 build.
# Install PostgreSQL and put its /bin directory on your path.
#
# Configure Using Gemfile
# gem 'pg'
#
default: &default
adapter: postgresql
encoding: unicode
# For details on connection pooling, see rails configuration guide
# http://guides.rubyonrails.org/configuring.html#database-pooling
pool: 5
development:
<<: *default
database: directory-service_development
# The specified database role being used to connect to postgres.
# To create additional roles in postgres see `$ createuser --help`.
# When left blank, postgres will use the default role. This is
# the same name as the operating system user that initialized the database.
#username: directory-service
# The password associated with the postgres role (username).
#password:
# Connect on a TCP socket. Omitted by default since the client uses a
# domain socket that doesn't need configuration. Windows does not have
# domain sockets, so uncomment these lines.
#host: localhost
# The TCP port the server listens on. Defaults to 5432.
# If your server runs on a different port number, change accordingly.
#port: 5432
# Schema search path. The server defaults to $user,public
#schema_search_path: myapp,sharedapp,public
# Minimum log levels, in increasing order:
# debug5, debug4, debug3, debug2, debug1,
# log, notice, warning, error, fatal, and panic
# Defaults to warning.
#min_messages: notice
# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
<<: *default
database: directory-service_test
# As with config/secrets.yml, you never want to store sensitive information,
# like your database password, in your source code. If your source code is
# ever seen by anyone, they now have access to your database.
#
# Instead, provide the password as a unix environment variable when you boot
# the app. Read http://guides.rubyonrails.org/configuring.html#configuring-a-database
# for a full rundown on how to provide these environment variables in a
# production deployment.
#
# On Heroku and other platform providers, you may have a full connection URL
# available as an environment variable. For example:
#
# DATABASE_URL="postgres://myuser:mypass#localhost/somedatabase"
#
# You can use this database configuration with:
#
# production:
# url: <%= ENV['DATABASE_URL'] %>
#
production:
<<: *default
database: directory-service_production
username: directory-service
password: <%= ENV['DIRECTORY-SERVICE_DATABASE_PASSWORD'] %>
On puts ENV["RAILS_ENV"], it shows that my test was running straight on test environment.
But the local foreman server that was running was getting data from the development environment.
By manually specifying that the server should run on test environment, the test also uses data from the test environment.
Big thanks to #AndyWaite.
What worked for me is the following:
Stop foreman (or your server running in development)
bin/rails db:migrate RAILS_ENV=test (optional)
bin/rails db:environment:set RAILS_ENV=test (set env explicitly)
rails server -e test (in another window)
rspec ___ (start testing)

Using Mixins with Foundation 5

I've just installed Foundation 5 with Sass and am using Compass to watch my stylesheets. I wanted to know what's the best practice for adding my custom styles. I've already created a custom.scss file and am referencing it using #import "custom"; in my app.scss file.
If I wanted to go ahead and change the background colour of the body, for example, how would I go about doing this using the mixins. I'm adding:
$body-bg: red;
to my custom.scss file, but the body's background isn't changing. Should I just edit the _settings.scss file, that seems wrong...
Any idea what I'm doing wrong? Thanks in advance!
Here's my config.rb:
# Require any additional compass plugins here.
add_import_path "bower_components/foundation/scss"
# Set this to the root of your project when deployed:
http_path = "/"
css_dir = "stylesheets"
sass_dir = "scss"
images_dir = "images"
javascripts_dir = "javascripts"
# You can select your preferred output style here (can be overridden via the command line):
# output_style = :expanded or :nested or :compact or :compressed
# To enable relative paths to assets via compass helper functions. Uncomment:
# relative_assets = true
# To disable debugging comments that display the original location of your selectors. Uncomment:
# line_comments = false
# If you prefer the indented syntax, you might want to regenerate this
# project again passing --syntax sass, or you can uncomment this:
# preferred_syntax = :sass
# and then run:
# sass-convert -R --from scss --to sass sass scss && rm -rf sass && mv scss sass
In your case maybe would be better use these structure:
app.scss:
#import "custom"; //where you define variables for foundation such as $body-bg: red;
#import "foundation";
#import "other styles";
Yes, I've always just edited the _settings.scss file -- then use a decent file comparison (like Araxis Merge or Kaleidoscope to merge in new options as updates are made). If I have custom variables, I'll stick those at the top of the settings file (that need to effect both the settings and my global stuff after the fact).

.txt file is no longer written to by snmptrapd daemon after opening and closing with ifstream in C++

I am running Net-Snmp (environment is a virtual machine running Linux Mint OS 11) and have configured it to send trap information to a text file that I have called trapd.txt.
If I reboot the VM, any trap that is generated is sent to the file no problem. However If I run a C++ program using ifstream to open it and then close it no trap information can be written to it again until I reboot.
When I generate a trap during this state I will sometimes even see the trapd.txt file flicker in the GUI as if it tried to write but failed. This situation happens if I do a clean reboot and run the following code and it alone:
ifstream file;
file.open("trapd.txt");
if(file)
cout<<"open"<<endl;
file.close();
file.open("nothing.txt");
file.close();
exit(0);
Clearly this code is not changing permissions or the SNMP configuration files. The only reason I can think that would prevent trap information from coming in afterwards is that the ifstream is not actually getting closed all the way.
If you have any ideas for a fix or a work around or any insight whatsoever I will be extremely grateful! This is a fairly important to me...
Here's my snmp.conf file:
oidOutputFormat 1
oidOutputFormat 5
logTimestamp yes
escapeQuotes yes
snmptrapd.conf:
authCommunity log,execute,net public
authCommunity log,execute,net private
outputOption auSs
logOption f /home/utd/Desktop/REPO/src/Manager/trapd.txt
snmpd.conf:
authtrapenable 1
master all
linkUpDownNotifications yes
defaultMonitors yes
trap2sink localhost public
rwcommunity private localhost
rocommunity public localhost
###############################################################################
#
# EXAMPLE.conf:
# An example configuration file for configuring the Net-SNMP agent ('snmpd')
# See the 'snmpd.conf(5)' man page for details
#
# Some entries are deliberately commented out, and will need to be explicitly activated
#
###############################################################################
#
# AGENT BEHAVIOUR
#
# Listen for connections from the local system only
agentAddress udp:127.0.0.1:161
# Listen for connections on all interfaces (both IPv4 *and* IPv6)
#agentAddress udp:161,udp6:[::1]:161
###############################################################################
#
# SNMPv3 AUTHENTICATION
#
# Note that these particular settings don't actually belong here.
# They should be copied to the file /var/lib/snmp/snmpd.conf
# and the passwords changed, before being uncommented in that file *only*.
# Then restart the agent
# createUser authOnlyUser MD5 "remember to change this password"
# createUser authPrivUser SHA "remember to change this one too" DES
# createUser internalUser MD5 "this is only ever used internally, but still change the password"
# If you also change the usernames (which might be sensible),
# then remember to update the other occurances in this example config file to match.
###############################################################################
#
# ACCESS CONTROL
#
# system + hrSystem groups only
view systemonly included .1.3.6.1.2.1.1
view systemonly included .1.3.6.1.2.1.25.1
# Full access from the local host
# Default access to basic system info
# Full access from an example network
# Adjust this network address to match your local
# settings, change the community string,
# and check the 'agentAddress' setting above
# Full read-only access for SNMPv3
rouser authOnlyUser
# Full write access for encrypted requests
# Remember to activate the 'createUser' lines above
#rwuser authPrivUser priv
# It's no longer typically necessary to use the full 'com2sec/group/access' configuration
# r[ou]user and r[ow]community, together with suitable views, should cover most requirements
###############################################################################
#
# SYSTEM INFORMATION
#
# Note that setting these values here, results in the corresponding MIB objects being 'read-only'
# See snmpd.conf(5) for more details
sysContact Me <me#example.org>
# Application + End-to-End layers
sysServices 72
#
# Process Monitoring
#
# At least one 'mountd' process
proc mountd
# No more than 4 'ntalkd' processes - 0 is OK
proc ntalkd 4
# At least one 'sendmail' process, but no more than 10
proc sendmail 10 1
# Walk the UCD-SNMP-MIB::prTable to see the resulting output
# Note that this table will be empty if there are no "proc" entries in the snmpd.conf file
#
# Disk Monitoring
#
# 10 MB required on root disk, 5% free on /var, 10% free on all other disks
disk / 10000
disk /var 5%
includeAllDisks 10%
# Walk the UCD-SNMP-MIB::dskTable to see the resulting output
# Note that this table will be empty if there are no "disk" entries in the snmpd.conf file
#
# System Load
#
# Unacceptable 1-, 5-, and 15-minute load averages
load 12 10 5
# Walk the UCD-SNMP-MIB::laTable to see the resulting output
# Note that this table *will* be populated, even without a "load" entry in the snmpd.conf file
###############################################################################
#
# ACTIVE MONITORING
#
# Send SNMPv1 traps
# Send SNMPv2c traps
# Send SNMPv2c INFORMs
# Note that you typically only want *one* of these three lines
# Uncommenting two (or all three) will result in multiple copies of each notification.
#
# Event MIB - automatically generate alerts
#
# Remember to activate the 'createUser' lines above
iquerySecName internalUser
rouser internalUser
# Generate traps on UCD error conditions
# Generate traps on linkUp/Down
###############################################################################
#
# EXTENDING THE AGENT
#
#
# Arbitrary extension commands
#
extend test1 /bin/echo Hello, world!
extend-sh test2 echo Hello, world! ; echo Hi there ; exit 35
#perl $debugging = \'1\';
#perl $verbose = \'1\';
#perl {$regat = \'.1.3.6.1.4.1.8072.999\'; $extenstion = \'1\'; $mibdata = \'/etc/passwd\'; $delimT=\'\'; $delimV=\':\'; do \'/etc/snmp/snmpagent.pl\';}
#perl print STDERR 'Test'
#perl $debugging = '1';
#perl $verbose = '1';
#perl $regat = '.1.3.6.1.4.8072.999';
#perl $extenstion = '1';
#perl $mibdata = '/etc/passwd';
#perl $delimT='';
#perl $delimV=':';
#perl do '/home/utd/snmpagent.pl';
#perl print STDERR 'Now loading Perl extensions...\n'
#perl $mibdata = "dick.txt";
#perl do '/home/utd/mymod.pl';
#extend-sh test3 /bin/sh /tmp/shtest
# Note that this last entry requires the script '/tmp/shtest' to be created first,
# containing the same three shell commands, before the line is uncommented
# Walk the NET-SNMP-EXTEND-MIB tables (nsExtendConfigTable, nsExtendOutput1Table
# and nsExtendOutput2Table) to see the resulting output
# Note that the "extend" directive supercedes the previous "exec" and "sh" directives
# However, walking the UCD-SNMP-MIB::extTable should still returns the same output,
# as well as the fuller results in the above tables.
#
# "Pass-through" MIB extension command
#
#pass .1.3.6.1.4.1.8072.2.255 /bin/sh PREFIX/local/passtest
#pass .1.3.6.1.4.1.8072.2.255 /usr/bin/perl PREFIX/local/passtest.pl
# Note that this requires one of the two 'passtest' scripts to be installed first,
# before the appropriate line is uncommented.
# These scripts can be found in the 'local' directory of the source distribution,
# and are not installed automatically.
# Walk the NET-SNMP-PASS-MIB::netSnmpPassExamples subtree to see the resulting output
#
# AgentX Sub-agents
#
# Run as an AgentX master agent
master agentx
# Listen for network connections (from localhost)
# rather than the default named socket /var/agentx/master
#agentXSocket tcp:localhost:705
perl $mibdata = "/etc/snmp/agenty.conf";
perl do "/etc/snmp/agenty.pl";
The problem's origin was actually from the editing and saving of the file itself by myself using gedit. While I still do not understand why this would cause the issue I can work around it by not editing the file. Thanks to everyone who replied.