LESS conditional variable change inside mixin - variables

I need to achieve such effect, but even when #padding actually < #height it still use multiplier value 2, which is non-sense...Is there any limitation i don't know about?
.btn-svg-offset(#height, #padding) {
#paddings-n: floor(#height / #padding);
#multiplier: 2;
& when (#padding < #height) {
#multiplier: 1;
}
#btn-svg-offset: #padding + ((#height / #multiplier) * #paddings-n);
};
Any workarounds are welcome)

& when is not if (they usually say so just for short). & {...} is still a regular ruleset with its own scope, and variables defined inside a ruleset are not visible in outer scopes.
To achieve what you need, rewrite this using conditional mixins (mixin's internals (incl. variables) are actually expanded into the caller scope):
.btn-svg-offset(#height, #padding) {
#paddings-n: floor(#height / #padding);
.-() {#multiplier: 2} .-;
.-() when (#padding < #height) {
#multiplier: 1;
}
#btn-svg-offset: #padding + ((#height / #multiplier) * #paddings-n);
}
Note that you can put the same condition onto the .btn-svg-offset mixin itself (so in real code it does not have to be that verbose as in my example... Exact code may vary though depending on the mixin usage and its other internals).
(Upd.) For example the following code (certain variations are possible too) would be an equivalent:
.btn-svg-offset(#height, #padding, #multiplier: 2) {
#paddings-n: floor(#height / #padding);
#btn-svg-offset: #padding + #height / #multiplier * #paddings-n;
}
.btn-svg-offset(#height, #padding) when (#padding < #height) {
.btn-svg-offset(#height, #padding, 1);
}

Related

How do i make a loop like mentioned below in kotlin programming language?

How can I make it in kotlin using for loop?
for (double i = 0; i < 10.0; i += 0.25) {
System.out.println("value is:" + i);
}
You should use the Intellij plugin for converting Java code for Kotlin. It's pretty neat (unless you have complex code using lambdas) This is what it converts to for your given question:
var i = 0.0
while (i < 10.0) {
println("value is:" + i)
i += 0.25
}
Here is the kotlin code equivalent to for loop.
var i = 0.0
while (i < 10.0)
{
println("value is:" + i)
i += 1.0
}
Kotlin for loop only support iterate the arrays.Please refer https://kotlinlang.org/docs/reference/control-flow.html
It's achievable in different way
var length:Double = 10.0
var increment:Double = 0.25
for (index in Array((length/increment).toInt(), { i -> (i * increment) }))
println(index)
I'm not sure if this syntax is new, but natural numbers may be used to iterate values like so.
(0..(10*4)).map {
it / 4.0 as Double
}.forEach {
println(it)
}
I'm avoiding iteration on IEEE 754 floating points, as that could potentially cause errors. It may be fine in this case, but the same may not be true depending on environment, context, and language. It's best to avoid using floating point except in cases where the numbers are expected to have arbitrary precision, i.e. uses real numbers or continuity.
This syntax may be used within a for loop as well if you don't need to store the result. However, for loops should be avoided for the most part if you want immutability (which you should).
for (i in 0..10) {
println("Project Loom is a lie! $i")
}

How does one write custom accessor methods in Perl6?

How does one write custom accessor methods in Perl6?
If I have this class:
class Wizard {
has Int $.mana is rw;
}
I can do this:
my Wizard $gandalf .= new;
$gandalf.mana = 150;
Let's say I want to add a little check to a setter in my Perl6 class without giving up the $gandalf.mana = 150; notation (in other words, I don't want to write this: $gandalf.setMana(150);). The program should die, if it tries to set a negative mana. How do I do this? The Perl6 documentation just mentions it is possible to write custom accessors, but does not say how.
With more recent versions of Rakudo there is a subset named UInt that restricts it to positive values.
class Wizard {
has UInt $.mana is rw;
}
So that you're not stuck in a lurch if you need to something like this; here is how that is defined:
( you can leave off the my, but I wanted to show you the actual line from the Rakudo source )
my subset UInt of Int where * >= 0;
You could also do this:
class Wizard {
has Int $.mana is rw where * >= 0;
}
I would like to point out that the * >= 0 in the where constraint is just a short way to create a Callable.
You could have any of the following as a where constraint:
... where &subroutine # a subroutine that returns a true value for positive values
... where { $_ >= 0 }
... where -> $a { $a >= 0 }
... where { $^a >= 0 }
... where $_ >= 0 # statements also work ( 「$_」 is set to the value it's testing )
( If you wanted it to just not be zero you could also use ... where &prefix:<?> which is probably better spelled as ... where ?* or ... where * !== 0 )
If you feel like being annoying to people using your code you could also do this.
class Wizard {
has UInt $.mana is rw where Bool.pick; # accepts changes randomly
}
If you want to make sure the value "makes sense" when looking at all of the values in the class in aggregate, you will have to go to a lot more work.
( It may require a lot more knowledge of the implementation as well )
class Wizard {
has Int $.mana; # use . instead of ! for better `.perl` representation
# overwrite the method the attribute declaration added
method mana () is rw {
Proxy.new(
FETCH => -> $ { $!mana },
STORE => -> $, Int $new {
die 'invalid mana' unless $new >= 0; # placeholder for a better error
$!mana = $new
}
)
}
}
You can get the same accessor interface that saying $.mana provides by declaring a method is rw. Then you can wrap a proxy around the underlying attribute like so:
#!/usr/bin/env perl6
use v6;
use Test;
plan 2;
class Wizard {
has Int $!mana;
method mana() is rw {
return Proxy.new:
FETCH => sub ($) { return $!mana },
STORE => sub ($, $mana) {
die "It's over 9000!" if ($mana // 0) > 9000;
$!mana = $mana;
}
}
}
my Wizard $gandalf .= new;
$gandalf.mana = 150;
ok $gandalf.mana == 150, 'Updating mana works';
throws_like sub {
$gandalf.mana = 9001;
}, X::AdHoc, 'Too much mana is too much';
Proxy is basically a way to intercept read and write calls to storage and do something other than the default behavior. As their capitalization suggests, FETCH and STORE are called automatically by Perl to resolve expressions like $gandalf.mana = $gandalf.mana + 5.
There's a fuller discussion, including whether you should even attempt this, at PerlMonks. I would recommend against the above -- and public rw attributes in general. It's more a display of what it is possible to express in the language than a useful tool.

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"

Lex Yacc / Flex Bison variables

I was just wondering how any of you guys would implement multi character variables in c using Flex and Bison / Lex and Yacc ?
Any if so can you provide maybe a simple example?
I am attempting to write an interpreter for a language and I can't seem to find a good way to implement variables, so far the methods I've tried have either failed or causing the execution of any program with a lot of variables become really so (I mean it could take minutes to execute a program that just assigns 1000 variables and does nothing else)
Thanks for your time,
Francis
In a lexer provided by ADAIC for Ada the following method is used, i find it ver useful for lexing multu-character literals such as reserved words and variables. It (along with corresponding Bison grammar and some other stuff) is available at ADAIC docs
%%
[a-zA-Z](_?[a-zA-Z0-9])* return(lk_keyword(yytext));
%%
# define NUM_KEYWORDS 69
KEY_TABLE key_tab[NUM_KEYWORDS] =
{
{"ABORT", ABORT},
{"ABS", ABS},
....
....
....
};
lk_keyword(str)
char *str;
{
int min;
int max;
int guess, compare;
min = 0;
max = NUM_KEYWORDS-1;
guess = (min + max) / 2;
to_upper(str);
for (guess=(min+max)/2; min<=max; guess=(min+max)/2) {
if ((compare = strcmp(key_tab[guess].kw, str)) < 0) {
min = guess + 1;
} else if (compare > 0) {
max = guess - 1;
} else {
return key_tab[guess].kwv;
}
}
return identifier;
}

Looping with iterator vs temp object gives different result graphically (Libgdx/Java)

I've got a particle "engine" whom I've implementing a Pool system to and I've tested two different ways of rendering every Particle in a list. Please note that the Pooling really doesn't have anything with the problem to do. I just followed a tutorial and tried to use the second method when I noticed that they behaved differently.
The first way:
for (int i = 0; i < particleList.size(); i++) {
Iterator<Particle> it = particleList.iterator();
while (it.hasNext()) {
Particle p = it.next();
if (p.isDead()){
it.remove();
}
p.render(batch, delta);
}
}
Which works just fine. My particles are sharp and they move with the correct speed.
The second way:
Particle p;
for (int i = 0; i < particleList.size(); i++) {
p = particleList.get(i);
p.render(batch, delta);
if (p.isDead()) {
particleList.remove(i);
bulletPool.free(p);
}
}
Which makes all my particles blurry and moving really slow!
The render method for my particles look like this:
public void render(SpriteBatch batch, float delta) {
sprite.setX(sprite.getX() + (dx * speed) * delta * Assets.FPS);
sprite.setY(sprite.getY() + (dy * speed) * delta * Assets.FPS);
ttl--;
sprite.setScale(sprite.getScaleX() - 0.002f);
if (ttl <= 0 || sprite.getScaleX() <= 0)
isDead = true;
sprite.draw(batch);
}
Why do the different rendering methods provide different results?
Thanks in advance
You are mutating (removing elements from) a list while iterating over it. This is a classic way to make a mess.
The Iterator must have code to handle the delete case correctly. But your index-based for loop does not. Specifically when you call particleList.remove(i) the i is now "out of sync" with the content of the list. Consider what happens when you remove the element at index 3: 'i' will increment to 4, but the old element 4 got shuffled down into index 3, so it will get skipped.
I assume you're avoiding the Iterator to avoid memory allocations. So, one way to side-step this issue is to reverse the loop (go from particleList.size() down to 0). Alternatively, you can only increment i for non-dead particles.