why use #{variableName} for bootstrap variables instead of #variableName - less

I'm looking at the bootstrap LESS source code and there is the following piece there:
.calc-grid-column(#index, #class, #type) when (#type = width) and (#index > 0) {
.col-#{class}-#{index} {
width: percentage((#index / #grid-columns));
}
}
Why do they write -#{class} instead of simply -#class?

As already explained by #Damien_The_Unbeliever Less enables you to use selector names, property names, URLs and #import statements. (also attribute selectors?).
The curly braces {} are used to make the variable name clear. In the case of #ab you can read variable #a or #ab. #{a}b forces that the variable #a will be used and has a string b appended.

Related

Is it possible to init a variable in the while condition body for Kotlin?

In the code below:
var verticesCount: Int // to read a vertices count for graph
// Reading until we get a valid vertices count.
while (!Assertions.checkEnoughVertices(
verticesCount = consoleReader.readInt(null, Localization.getLocStr("type_int_vertices_count"))))
// The case when we don't have enough vertices.
println(String.format(Localization.getLocStr("no_enough_vertices_in_graph"),
Assertions.CONFIG_MIN_VERTICES_COUNT))
val resultGraph = Graph(verticesCount)
we are getting next error on the last line:
Error:(31, 33) Kotlin: Variable 'verticesCount' must be initialized
Assertions.checkEnoughVertices accepts a safe type variable as an argument (verticesCount: Int), so it's impossible for verticesCount to be uninitialized or null here (and we're getting no corresponding errors on those lines).
What's going on on the last line when already initialized variable becomes uninitialized again?
The syntax you've used denotes a function call with named arguments, not the assignment of a local variable. So verticesCount = is just an explanation to the reader that the value which is being passed here to checkEnoughVertices corresponds to the parameter of that function named verticesCount. It has nothing to do with the local variable named verticesCount declared just above, so the compiler thinks you've still to initialize that variable.
In Kotlin, the assignment to a variable (a = b) is not an expression, so it cannot be used as a value in other expressions. You have to split the assignment and the while-loop condition to achieve what you want. I'd do this with an infinite loop + a condition inside:
var verticesCount: Int
while (true) {
verticesCount = consoleReader.readInt(...)
if (Assertions.checkEnoughVertices(verticesCount)) break
...
}
val resultGraph = Graph(verticesCount)
Well, technically it is possible to assign values to variables in the while condition - and anything else you might want to do there, too.
The magic comes from the also function:
Try this: (excuse the completely useless thing this is doing...)
var i = 10
var doubleI: Int
while ((i * 2).also { doubleI = it } > 0) {
i--
println(doubleI)
}
Any expression can be "extended" with "something to do" by calling also which takes the expression it is called upon as the it parameter and executes the given block. The value also returns is identical to its caller value.
Here's a very good article to explain this and much more: https://medium.com/#elye.project/mastering-kotlin-standard-functions-run-with-let-also-and-apply-9cd334b0ef84

Different Objective-C enums with the same literals

I wish to have two different enums, but they might have the same literal; for example:
typedef enum {ONE,TWO,THREE,FOUR,FIVE,SIX} NumbersEnum;
typedef enum {ONE,TWO,THREE,FIVE,EIGHT} FibonacciEnum;
This will raise a compile error because ONE, TWO, THREE, FIVE are repeated in both enums.
Is there a way to make this work as-is (not changing the literals' names or adding a prefix or suffix)?
Is there any way my code using the literals can look like this: int num = NumbersEnum.SIX; and not like this int num = SIX;?
No. That's part of the C and Objective-C language from the beginning of time. You're not going to change it, and nobody is going to change it for you.
You cannot do this with enums; their members are global and the names must be unique. There is, however, a neat technique you can use to make pseudo-namespaces for constants with structs.
Declare your "namespace" in the appropriate header:
extern const struct _FibonacciNumbers
{
int one;
int two;
int three;
int five;
} FibonacciNumbers;
Then initialize the values in an implementation file:
const struct _FibonacciNumbers FibonacciNumbers = {
.one = 1,
.two = 2,
.three = 3,
.five = 5
};
You now access a constant as, e.g., FibonacciNumbers.one, and other struct types can use the same names since the names are private to each of them.
So that's "No" for your first option, but "Yes" to the second.

Auto-generate LESS styles for sprite icons

I have icon sprites image with each icon in a 20 by 20 pixel area. Each icon has several variants (black, colour, white small etc.). And have a significant amount of them. Instead of writing styles for each individual icon I'd rather just provide their names in my LESS file and let the processor generate styles for them.
This is what I came up with but it doesn't seem to work.
#icons: upvote,downvote,comment,new,notify,search,popup,eye,cross;
#array: ~`(function(i){ return (i + "").replace(/[\[\] ]/gi, "").split(","); })("#{icons}")`;
#count: ~`(function(i){ return i.split(",").length; })("#{icons}")`;
.iconize (#c) when (#c < #count) {
#val: ~`(function(a){ return a.replace(" ","").split(",")[0]; })("#{array}")`;
#array: ~`(function(a){ a = a.replace(" ","").split(","); a.splice(0, 1); return a; })("#{array}")`;
&.#{val} { background-position: (-20px * #c) 0; }
&.color.#{val} { background-position: (-20px * #c) -20px; }
&.white.#{val} { background-position: (-20px * #c) -40px; }
.iconize(#c + 1);
}
.iconize(#c) when (#c = #count) {}
.iconize(0);
The only thing I'd like to edit is the #icons variable where I just enter their names. And I'm using Web Essentials addin for Visual Studio 2013 to automatically process my LESS file on file save.
What am I doing wrong?
Pure LESS (assuming you're using Web Essentials 2013 which uses LESS 1.5.x):
#icons: upvote, downvote, comment, new, notify, search, popup, eye, cross;
.iconize();
.iconize(#i: length(#icons)) when (#i > 0) {
.iconize((#i - 1));
#value: extract(#icons, #i); // LESS arrays are 1-based
.#{value} {background-position: (-20px * (#i - 1)) 0}
.color.#{value} {background-position: (-20px * (#i - 1)) -20px}
.white.#{value} {background-position: (-20px * (#i - 1)) -40px}
}
I removed & from selector names since it has no effect when you generate these classes in the global scope (but put it back if you actually need .iconize to be nested in another ruleset). It is also possible to calculate array length in earlier LESS versions (that have no length function) w/o any javascript, but I don't list this method here since it's quite scary (and you don't need it anyway).
Your javascript based loop is in fact less or more correct but the problem is all values returned by LESS inline javascript are of so-called "anonymous value" type and not a numbers so that when (#c < #count) condition is always true and the loop becomes infinite. (basically the condition is expanded exactly as when (0 < ~'9') ... when (9 < ~'9') = true etc.)
I think it depends on the version of LESS you use. Different versions of LESS handle array like structures and their length different.
Since LESS 1.5 you can define an array with quotes, like:
#array: "value1","value2"; and calculate its length with length(#array).
For example see also:
Sprites LESS CSS Variable increment issue
With LESS 1.5 your code ends in an endless loop: "SyntaxError: Maximum call stack size exceeded in"

If (BOOL) in Objective C: unused variable

In an implementation of a CGRect, I attempt this:
BOOL didStartPressing = NO;
if ( didStartPressing) {int nmax=5;}
else{int nmax=500;}
for (int n=1; n<nmax; n=n+1){ *... working code that draws some circles ....* }
This gives yellow warnings about "unused variable nmax" in the first part above
and red warnings about "use of undeclared variable nmax." for the for loop.
If however I simply replace the first three lines above with
int nmax=500;
I get a lovely picture that I drew in CGRect.
Greatest of thanks for help, as I'm complete noob up against the hard wall of learning curve.
You've limited the scope of nmax to the braces after the if and the else. So you have two variables with that name, neither of which is visible to the for loop. To solve, move the declaration to the outer scope and simply assign to the variable in the if/else scopes:
int nmax = 0; // the = 0 is optional in this case because all code
// paths assign a value to nmax
BOOL didStartPressing = NO;
if (didStartPressing) {
nmax=5;
} else {
nmax=500;
}
for (int n=1; n<nmax; n=n+1) {
/*... working code that draws some circles ....*/
}
This is a C language thing. The scope of a variable that's declared inside a pair of braces is only the section inside the braces. That means you have two different variables, both called nmax and each limited to its section of the if/else statement.
You can make it work with:
int nmax = 500;
if ( didStartPressing) {
nmax=5;
}
Look at a book on C programming for more details.

Conventions for naming class operations?

What conventions do you use for naming class operations?
Full word doc : Download C# Coding Standards & Best Practices
Naming Conventions and Standards
Note :
The terms Pascal Casing and Camel Casing are used throughout this document.
Pascal Casing - First character of all words are Upper Case and other characters are lower case.
Example: BackColor
Camel Casing - First character of all words, except the first word are Upper Case and other characters are lower case.
Example: backColor
Use Pascal casing for Class names
public class HelloWorld
{
...
}
Use Pascal casing for Method names
void SayHello(string name)
{
...
}
Use Camel casing for variables and method parameters
int totalCount = 0;
void SayHello(string name)
{
string fullMessage = "Hello " + name;
...
}
Use the prefix β€œI” with Camel Casing for interfaces ( Example: IEntity )
Do not use Hungarian notation to name variables.
In earlier days most of the programmers liked it - having the data type as a prefix for the variable name and using m_ as prefix for member variables. Eg:
string m_sName;
int nAge;
However, in .NET coding standards, this is not recommended. Usage of data type and m_ to represent member variables should not be used. All variables should use camel casing.
Some programmers still prefer to use the prefix m_ to represent member variables, since there is no other easy way to identify a member variable.
Use Meaningful, descriptive words to name variables. Do not use abbreviations.
Good:
string address
int salary
Not Good:
string nam
string addr
int sal
Do not use single character variable names like i, n, s etc. Use names like index, temp
One exception in this case would be variables used for iterations in loops:
for ( int i = 0; i < count; i++ )
{
...
}
If the variable is used only as a counter for iteration and is not used anywhere else in the loop, many people still like to use a single char variable (i) instead of inventing a different suitable name.
Do not use underscores (_) for local variable names.
All member variables must be prefixed with underscore (_) so that they can be identified from other local variables.
Do not use variable names that resemble keywords.
Prefix boolean variables, properties and methods with β€œis” or similar prefixes.
Ex: private bool _isFinished
Namespace names should follow the standard pattern
...
Use appropriate prefix for the UI elements so that you can identify them from the rest of the variables.
There are 2 different approaches recommended here.
a. Use a common prefix ( ui_ ) for all UI elements. This will help you group all of the UI elements together and easy to access all of them from the intellisense.
b. Use appropriate prefix for each of the ui element. A brief list is given below. Since .NET has given several controls, you may have to arrive at a complete list of standard prefixes for each of the controls (including third party controls) you are using.
Control Prefix
Label lbl
TextBox txt
DataGrid dtg
Button btn
ImageButton imb
Hyperlink hlk
DropDownList ddl
ListBox lst
DataList dtl
Repeater rep
Checkbox chk
CheckBoxList cbl
RadioButton rdo
RadioButtonList rbl
Image img
Panel pnl
PlaceHolder phd
Table tbl
Validators val
File name should match with class name.
For example, for the class HelloWorld, the file name should be helloworld.cs (or, helloworld.vb)
Use Pascal Case for file names.
Indentation and Spacing
Use TAB for indentation. Do not use SPACES. Define the Tab size as 4.
Comments should be in the same level as the code (use the same level of indentation).
Good:
// Format a message and display
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );
Not Good:
// Format a message and display
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );
Curly braces ( {} ) should be in the same level as the code outside the braces.
Use one blank line to separate logical groups of code.
Good:
bool SayHello ( string name )
{
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );
if ( ... )
{
// Do something
// ...
return false;
}
return true;
}
Not Good:
bool SayHello (string name)
{
string fullMessage = "Hello " + name;
DateTime currentTime = DateTime.Now;
string message = fullMessage + ", the time is : " + currentTime.ToShortTimeString();
MessageBox.Show ( message );
if ( ... )
{
// Do something
// ...
return false;
}
return true;
}
There should be one and only one single blank line between each method inside the class.
The curly braces should be on a separate line and not in the same line as if, for etc.
Good:
if ( ... )
{
// Do something
}
Not Good:
if ( ... ) {
// Do something
}
Use a single space before and after each operator and brackets.
Good:
if ( showResult == true )
{
for ( int i = 0; i < 10; i++ )
{
//
}
}
Not Good:
if(showResult==true)
{
for(int i= 0;i<10;i++)
{
//
}
}
Use #region to group related pieces of code together. If you use proper grouping using #region, the page should like this when all definitions are collapsed.
Keep private member variables, properties and methods in the top of the file and public members in the bottom.
I find it makes everyone's life easier to use the same naming conventions used by the language and framework you are working in.
For example, .Net has a convention. Model what your language does, and the "users" of your code and libraries will be happier. So, the answer may be, it depends on your language and / or platform...
Naming conventions are a controversial topic, because it's an arbitrary distinction.
The two answers above are good ones. My addition is this:
Your goal is readability. Your code tells a story, albeit a sometimes kind of boring one. Make sure the story is clear.
For extra fun see these links:
http://www.joelonsoftware.com/articles/Wrong.html
http://en.wikipedia.org/wiki/Naming_convention_%28programming%29