OpenSCAD difference/intersection not working - modeling

I was trying to create a difference if y == 0, however when I put the last 'cube' in it fills in other parts of the shape that should not be filled in & it doesn't even cut out what it should've. However, when I comment out the final cube it works fine (except it doesn't have the last difference obviously). I have tried using openscad.net & the software. Both of them have the same effect. What am I doing wrong?
With cube uncommented
With cube commented
s = 20+8; //Block size in mm
l = 2; //In "blocks"
w = 2; //In "blocks"
h = 40; //In mm
t = 1;
for (x = [0:l-1]) {
for (y = [0:w-1]) {
translate([s*x-s*l/2, s*y-s*w/2, -h/2]) {
if (x==0) {
translate([-s*(2/28)-t, s*(16/28)+t/2, 0]) {
cube([s*(2/28)+t, s*(8/28)-t, h]);
}
translate([-s*(4/28), s*(14/28)+t/2, 0]) {
cube([s*(2/28)-t, s*(12/28)-t, h]);
}
}
if (x==l-1) {
translate([s, s*(4/28)+t/2, 0]) {
cube([s*(2/28)+t, s*(8/28)-t, h]);
}
translate([s+s*(2/28)+t, s*(2/28)+t/2, 0]) {
cube([s*(2/28)-t, s*(12/28)-t, h]);
}
}
if (y==0) {
translate([s*(4/28)+t/2, -s*(2/28)-t, 0]) {
cube([s*(8/28)-t, s*(2/28)+t, h]);
}
translate([s*(2/28)+t/2, -s*(4/28), 0]) {
cube([s*(12/28)-t, s*(2/28)-t, h]);
}
}
difference() {
cube([s, s, h]);
intersection() {
if (x == 0) {
translate([0, s*(4/28), 0]) {
cube([s*(2/28), s*(8/28), h]);
}
translate([s*(2/28), s*(2/28), 0]) {
cube([s*(2/28), s*(12/28), h]);
}
}
if (x==l-1) {
translate([s-s*(4/28), s*(14/28), 0]) {
cube([s*(2/28), s*(12/28), h]);
}
translate([s-s*(2/28), s*(16/28), 0]) {
cube([s*(2/28), s*(8/28), h]);
}
}
if (y==0) {
translate([s*(14/28), -s*(4/28), 0]) {
cube([s*(12/28), s*(2/28), h]);
}
}
}
}
}
}
}

The reason for your results seems to be that when y==0, your intersection results in an empty object, hence nothing is subtracted.
If you slim down your design to a smaller example exhibiting this behavior, it would be a lot easier to debug.
Hint: You can use the # and % operators to highlight objects for debugging (# includes it in the CSG tree, % removes it from the CSG tree).

To add to kintel's answer, I think you intended to do a union() there at line 38, also putting things into module helps a lot when reusing or updating things in the future.

Related

Why is the following a memory leak? [duplicate]

I've got code that looks like this:
for (std::list<item*>::iterator i=items.begin();i!=items.end();i++)
{
bool isActive = (*i)->update();
//if (!isActive)
// items.remove(*i);
//else
other_code_involving(*i);
}
items.remove_if(CheckItemNotActive);
I'd like remove inactive items immediately after update them, inorder to avoid walking the list again. But if I add the commented-out lines, I get an error when I get to i++: "List iterator not incrementable". I tried some alternates which didn't increment in the for statement, but I couldn't get anything to work.
What's the best way to remove items as you are walking a std::list?
You have to increment the iterator first (with i++) and then remove the previous element (e.g., by using the returned value from i++). You can change the code to a while loop like so:
std::list<item*>::iterator i = items.begin();
while (i != items.end())
{
bool isActive = (*i)->update();
if (!isActive)
{
items.erase(i++); // alternatively, i = items.erase(i);
}
else
{
other_code_involving(*i);
++i;
}
}
You want to do:
i= items.erase(i);
That will correctly update the iterator to point to the location after the iterator you removed.
You need to do the combination of Kristo's answer and MSN's:
// Note: Using the pre-increment operator is preferred for iterators because
// there can be a performance gain.
//
// Note: As long as you are iterating from beginning to end, without inserting
// along the way you can safely save end once; otherwise get it at the
// top of each loop.
std::list< item * >::iterator iter = items.begin();
std::list< item * >::iterator end = items.end();
while (iter != end)
{
item * pItem = *iter;
if (pItem->update() == true)
{
other_code_involving(pItem);
++iter;
}
else
{
// BTW, who is deleting pItem, a.k.a. (*iter)?
iter = items.erase(iter);
}
}
Of course, the most efficient and SuperCool® STL savy thing would be something like this:
// This implementation of update executes other_code_involving(Item *) if
// this instance needs updating.
//
// This method returns true if this still needs future updates.
//
bool Item::update(void)
{
if (m_needsUpdates == true)
{
m_needsUpdates = other_code_involving(this);
}
return (m_needsUpdates);
}
// This call does everything the previous loop did!!! (Including the fact
// that it isn't deleting the items that are erased!)
items.remove_if(std::not1(std::mem_fun(&Item::update)));
I have sumup it, here is the three method with example:
1. using while loop
list<int> lst{4, 1, 2, 3, 5};
auto it = lst.begin();
while (it != lst.end()){
if((*it % 2) == 1){
it = lst.erase(it);// erase and go to next
} else{
++it; // go to next
}
}
for(auto it:lst)cout<<it<<" ";
cout<<endl; //4 2
2. using remove_if member funtion in list:
list<int> lst{4, 1, 2, 3, 5};
lst.remove_if([](int a){return a % 2 == 1;});
for(auto it:lst)cout<<it<<" ";
cout<<endl; //4 2
3. using std::remove_if funtion combining with erase member function:
list<int> lst{4, 1, 2, 3, 5};
lst.erase(std::remove_if(lst.begin(), lst.end(), [](int a){
return a % 2 == 1;
}), lst.end());
for(auto it:lst)cout<<it<<" ";
cout<<endl; //4 2
4. using for loop , should note update the iterator:
list<int> lst{4, 1, 2, 3, 5};
for(auto it = lst.begin(); it != lst.end();++it){
if ((*it % 2) == 1){
it = lst.erase(it); erase and go to next(erase will return the next iterator)
--it; // as it will be add again in for, so we go back one step
}
}
for(auto it:lst)cout<<it<<" ";
cout<<endl; //4 2
Use std::remove_if algorithm.
Edit:
Work with collections should be like:
prepare collection.
process collection.
Life will be easier if you won't mix this steps.
std::remove_if. or list::remove_if ( if you know that you work with list and not with the TCollection )
std::for_each
The alternative for loop version to Kristo's answer.
You lose some efficiency, you go backwards and then forward again when deleting but in exchange for the extra iterator increment you can have the iterator declared in the loop scope and the code looking a bit cleaner. What to choose depends on priorities of the moment.
The answer was totally out of time, I know...
typedef std::list<item*>::iterator item_iterator;
for(item_iterator i = items.begin(); i != items.end(); ++i)
{
bool isActive = (*i)->update();
if (!isActive)
{
items.erase(i--);
}
else
{
other_code_involving(*i);
}
}
Here's an example using a for loop that iterates the list and increments or revalidates the iterator in the event of an item being removed during traversal of the list.
for(auto i = items.begin(); i != items.end();)
{
if(bool isActive = (*i)->update())
{
other_code_involving(*i);
++i;
}
else
{
i = items.erase(i);
}
}
items.remove_if(CheckItemNotActive);
Removal invalidates only the iterators that point to the elements that are removed.
So in this case after removing *i , i is invalidated and you cannot do increment on it.
What you can do is first save the iterator of element that is to be removed , then increment the iterator and then remove the saved one.
If you think of the std::list like a queue, then you can dequeue and enqueue all the items that you want to keep, but only dequeue (and not enqueue) the item you want to remove. Here's an example where I want to remove 5 from a list containing the numbers 1-10...
std::list<int> myList;
int size = myList.size(); // The size needs to be saved to iterate through the whole thing
for (int i = 0; i < size; ++i)
{
int val = myList.back()
myList.pop_back() // dequeue
if (val != 5)
{
myList.push_front(val) // enqueue if not 5
}
}
myList will now only have numbers 1-4 and 6-10.
Iterating backwards avoids the effect of erasing an element on the remaining elements to be traversed:
typedef list<item*> list_t;
for ( list_t::iterator it = items.end() ; it != items.begin() ; ) {
--it;
bool remove = <determine whether to remove>
if ( remove ) {
items.erase( it );
}
}
PS: see this, e.g., regarding backward iteration.
PS2: I did not thoroughly tested if it handles well erasing elements at the ends.
You can write
std::list<item*>::iterator i = items.begin();
while (i != items.end())
{
bool isActive = (*i)->update();
if (!isActive) {
i = items.erase(i);
} else {
other_code_involving(*i);
i++;
}
}
You can write equivalent code with std::list::remove_if, which is less verbose and more explicit
items.remove_if([] (item*i) {
bool isActive = (*i)->update();
if (!isActive)
return true;
other_code_involving(*i);
return false;
});
The std::vector::erase std::remove_if idiom should be used when items is a vector instead of a list to keep compexity at O(n) - or in case you write generic code and items might be a container with no effective way to erase single items (like a vector)
items.erase(std::remove_if(begin(items), end(items), [] (item*i) {
bool isActive = (*i)->update();
if (!isActive)
return true;
other_code_involving(*i);
return false;
}));
do while loop, it's flexable and fast and easy to read and write.
auto textRegion = m_pdfTextRegions.begin();
while(textRegion != m_pdfTextRegions.end())
{
if ((*textRegion)->glyphs.empty())
{
m_pdfTextRegions.erase(textRegion);
textRegion = m_pdfTextRegions.begin();
}
else
textRegion++;
}
I'd like to share my method. This method also allows the insertion of the element to the back of the list during iteration
#include <iostream>
#include <list>
int main(int argc, char **argv) {
std::list<int> d;
for (int i = 0; i < 12; ++i) {
d.push_back(i);
}
auto it = d.begin();
int nelem = d.size(); // number of current elements
for (int ielem = 0; ielem < nelem; ++ielem) {
auto &i = *it;
if (i % 2 == 0) {
it = d.erase(it);
} else {
if (i % 3 == 0) {
d.push_back(3*i);
}
++it;
}
}
for (auto i : d) {
std::cout << i << ", ";
}
std::cout << std::endl;
// result should be: 1, 3, 5, 7, 9, 11, 9, 27,
return 0;
}
I think you have a bug there, I code this way:
for (std::list<CAudioChannel *>::iterator itAudioChannel = audioChannels.begin();
itAudioChannel != audioChannels.end(); )
{
CAudioChannel *audioChannel = *itAudioChannel;
std::list<CAudioChannel *>::iterator itCurrentAudioChannel = itAudioChannel;
itAudioChannel++;
if (audioChannel->destroyMe)
{
audioChannels.erase(itCurrentAudioChannel);
delete audioChannel;
continue;
}
audioChannel->Mix(outBuffer, numSamples);
}

Phaser 3: How to detect if there's a group member at location

Okay I have a little game going on Phaser with a slider which the player can move up or down:
As you can see, the slider is on a track which one would assume restricts where the slider can go. At the moment, this isn't the case and the slider can run right off the rail.
How can I detect if there's a slider track in the target location before moving the slider?
Here's where I'm creating the static groups for slider and slider track.
sliders = this.physics.add.staticGroup();
slider_tracks = this.physics.add.staticGroup();
Here's where the objects themselves are being added to the game:
add_slider: function (x, y, data) {
map.add_slider_track(x, y, data);
var slider = sliders.create(x, y, data.direction + '_slider');
for (var key in data) {
slider[key] = data[key];
}
},
add_slider_track: function (x, y, data) {
slider_tracks.create(x, y, data.direction + '_track');
},
And here's the functions which move it:
hitSlider: function (player, slider) {
if (slider.direction == 'vertical') {
if (player.body.onFloor() && player.slamming) {
interaction.moveSliderDown(slider)
} else if (player.body.onCeiling()) {
interaction.moveSliderUp(slider);
}
}
player.slamming = false;
},
moveSliderUp: function (slider) {
slider.setY(slider.y - block_size);
slider.body.position.y = (slider.y - (block_size / 2));
player.setVelocityY(100);
},
moveSliderDown: function (slider) {
slider.setY(slider.y + block_size);
slider.body.position.y = (slider.y - (block_size / 2));
}
I've tried using slider_track.getFirst (https://rexrainbow.github.io/phaser3-rex-notes/docs/site/group/) but it seems to change the location of a given piece of track, not just detect if there's one there.
Just to don't let this question without answer as we normally start a chat, effectively I see in the js/slider_actions.js the solution but I can just say you can use velocity but seriously my level of coding even if I am for a long time in the Phaser community is lower than yours ;)
sliderTrackRight: function (slider) {
track = slider_tracks.children.entries.find(
function (track) {
return (
track.body.y == slider.body.y &&
track.body.x == (slider.body.x + block_size) &&
track.direction == 'horizontal'
)
}
);
return (typeof track != 'undefined');
},

How to search in an array in Node.js in a non-blocking way?

I have an array which is:
[ 4ff023908ed2842c1265d9e4, 4ff0d75c8ed2842c1266099b ]
And I have to find if the following, is inside that array
4ff0d75c8ed2842c1266099b
Here is what I wrote:
Array.prototype.contains = function(k) {
for(p in this)
if(this[p] === k)
return true;
return false;
}
Apparently, it doesn't work properly, or better sometimes it works, but it looks to me blocking. Is there anyone that can check that one?
many thanks
Non-blocking search function
Array.prototype.contains = function(k, callback) {
var self = this;
return (function check(i) {
if (i >= self.length) {
return callback(false);
}
if (self[i] === k) {
return callback(true);
}
return process.nextTick(check.bind(null, i+1));
}(0));
}
Usage:
[1, 2, 3, 4, 5].contains(3, function(found) {
if (found) {
console.log("Found");
} else {
console.log("Not found");
}
});
However, for searching the value in the array it is better to use Javascript built-in array search function, as it will be much faster (so that you probably won't need it to be non-blocking):
if ([1, 2, 3, 4, 5].indexOf(3) >= 0) {
console.log("Found");
} else {
console.log("Not found");
}
Also, consider the underscore library which makes all the stuff cross-platform: http://underscorejs.org/

How to 'Slice' a Collection in Groovy

I have a collection of objects that I want to break up into a collection of collections, where each sequential group of 3 elements is in one collection.
For example, if I have
def l = [1,4,2,4,5,9]
I want to turn this into:
def r = [[1,4,2], [4,5,9]]
I'm doing it now by iterating over the collection and breaking it up.. but I then need to pass those 'groups' into a parallelized function that processes them.. It would be nice to eliminate this O(n) pre-processing work and just say something like
l.slice(3).collectParallel { subC -> process(subC) }
I've found the step method on the Range class, but it looks like that only acts on the indices. Any clever ideas?
Update:
I don't think this is a duplicate of the referenced link, although it's very close. As suggested below, it's more of the iterator-type thing I'm looking for.. the sub-collections will then be passed into a GPars collectParallel. Ideally I wouldn't need to allocate an entire new collection.
Check out groovy 1.8.6. There is a new collate method on List.
def list = [1, 2, 3, 4]
assert list.collate(4) == [[1, 2, 3, 4]] // gets you everything
assert list.collate(2) == [[1, 2], [3, 4]] //splits evenly
assert list.collate(3) == [[1, 2, 3], [4]] // won't split evenly, remainder in last list.
Take a look at the Groovy List documentation for more info because there are a couple of other params that give you some other options, including dropping the remainder.
As far as your parallel processing goes, you can cruise through the lists with gpars.
def list = [1, 2, 3, 4, 5]
GParsPool.withPool {
list.collate(2).eachParallel {
println it
}
}
If I understand you correctly, you're currently copying the elements from the original collection into the sub-collections. For more suggestions along those lines, checkout the answers to the following question: Split collection into sub collections in Groovy
It sounds like what you're instead looking for is a way for the sub-collections to effectively be a view into the original collection. If that's the case, check out the List.subList() method. You could either loop over the indices from 0 to size() in increments of 3 (or whatever slice size you choose) or you could get fancier and build an Iterable/List which would hide the details from the caller. Here's an implementation of the latter, inspired by Ted's answer.
class Slicer implements Iterator {
private List backingList
private int sliceSize
private int index
Slicer(List backingList, int sliceSize) {
this.backingList = backingList
this.sliceSize = sliceSize
}
Object next() {
if (!hasNext()) {
throw new NoSuchElementException()
}
def ret
if (index + sliceSize <= backingList.size()) {
ret = backingList.subList(index, index+sliceSize)
} else if (hasNext()) {
ret = backingList.subList(index, backingList.size())
}
index += sliceSize
return ret
}
boolean hasNext() {
return index < backingList.size()
}
void remove() {
throw new UnsupportedOperationException() //I'm lazy ;)
}
}
I like both solutions but here is a slightly improved version of the first solution that I like very much:
class Slicer implements Iterator {
private List backingList
private int sliceSize
private int index
Slicer(List backingList, int sliceSize) {
this.backingList = backingList;
int ss = sliceSize;
// negitive sliceSize = -N means, split the list into N equal (or near equal) pieces
if( sliceSize < 0) {
ss = -sliceSize;
ss = (int)((backingList.size()+ss-1)/ss);
}
this.sliceSize = ss
}
Object next() {
if (!hasNext()) {
throw new NoSuchElementException()
}
def ret = backingList.subList(index, Math.min(index+sliceSize , backingList.size()) );
index += sliceSize
return ret
}
boolean hasNext() {
return index < backingList.size() - 1
}
void remove() {
throw new UnsupportedOperationException() //I'm lazy ;)
}
List asList() {
this.collect { new ArrayList(it) }
}
List flatten() {
backingList.asImmutable()
}
}
// ======== TESTS
def a = [1,2,3,4,5,6,7,8];
assert [1,2,3,4,5,6,7,8] == a;
assert [[1, 2], [3, 4], [5, 6], [7, 8]] == new Slicer(a,2).asList();
assert [[1,2,3], [4,5,6], [7,8]] == (new Slicer(a,3)).collect { it } // alternative to asList but inner items are subList
assert [3, 2, 1, 6, 5, 4, 8, 7] == ((new Slicer(a,3)).collect { it.reverse() } ).flatten()
// show flatten iterator
//new Slicer(a,2).flattenEach { print it }
//println ""
// negetive slice into N pieces, in this example we split it into 2 pieces
assert [[1, 2, 3, 4], [5, 6, 7, 8]] == new Slicer(a,-2).collect { it as List } // same asList
assert [[1, 2, 3], [4, 5, 6], [7, 8]] == new Slicer(a,-3).asList()
//assert a == (new Slicer(a,3)).flattenCollect { it }
assert [9..10, 19..20, 29..30] == ( (new Slicer(1..30,2)).findAll { slice -> !(slice[1] % 10) } )
assert [[9, 10], [19, 20], [29, 30]] == ( (new Slicer(1..30,2)).findAll { slice -> !(slice[1] % 10) }.collect { it.flatten() } )
println( (new Slicer(1..30,2)).findAll { slice -> !(slice[1] % 10) } )
println( (new Slicer(1..30,2)).findAll { slice -> !(slice[1] % 10) }.collect { it.flatten() } )
There isn't anything built in to do exactly what you want, but if we #Delegate calls to the native lists's iterator, we can write our own class that works just like an Iterator that returns the chunks you're looking for:
class Slicer {
protected Integer sliceSize
#Delegate Iterator iterator
Slicer(objectWithIterator, Integer sliceSize) {
this.iterator = objectWithIterator.iterator()
this.sliceSize = sliceSize
}
Object next() {
List currentSlice = []
while(hasNext() && currentSlice.size() < sliceSize) {
currentSlice << this.iterator.next()
}
return currentSlice
}
}
assert [[1,4,2], [4,5,9]] == new Slicer([1,4,2,4,5,9], 3).collect { it }
Because it has all of the methods that a normal Iterator does, you get the groovy syntactic sugar methods for free with lazy evaluation on anything that has an iterator() method, like a range:
assert [5,6] == new Slicer(1..100, 2).find { slice -> slice.first() == 5 }
assert [[9, 10], [19, 20], [29, 30]] == new Slicer(1..30, 2).findAll { slice -> !(slice[1] % 10) }

jQuery deep copy with Ext JS?

I've tried and surprised how could not I do with ExtJS. Let me explain with a code block.
In jQuery
console.clear();
var a = {
b: 5,
c: 4,
o: {
l: 2,
p: 2
}
}
var b = {
k: 4,
l: 3,
c: 5,
o: {
m: 2,
l: 1
}
}
var ex = $.extend(true, a, b);
console.dir(ex)
Here is the output
ex = {
a: {
q: 2
},
b: 5,
c: 5,
o: {
l: 1,
p: 2,
m: 2
}
}
Ext apply, applyIf, copyTo does not worked like this. How can I produce the output in ExtJS?
Thanks in advance.
For a recent project, we adapted this sample code to produce the following method:
Ext.deepCopy = function(p, c) {
c = c || (p.constructor === Array ? [] : {});
for (var i in p) {
if (typeof p[i] === 'object' && p[i] !== null) {
c[i] = p[i].constructor === Array ? [] : {};
Ext.deepCopy(p[i], c[i]);
} else {
c[i] = p[i];
}
}
return c;
};
Deep copying isn't supported in Ext. There are Ext.apply and Ext.applyIf but they both only work on the first level of a hash map and will override instead of merge any embedded arrays or hashes.
In fact the docs explicitly state that Ext.apply is meant to work on config objects, not that it matters but it's just to illustrate that it's not meant to be used as a merge utility function although it basically could if you only want to merge the first level/depth.
Use the Ext.Object.merge() method, that does exactly what you're looking for.

Resources