How can I despawn an entity in bevy 0.5.0 that was spawned with commands.spawn_bundle() - bevy

This is a very simple question.
I already rewrote my code to work with the syntax and other changes, that came with the new version of bevy.
Everything seems to work when compiling, except the despawning of an entity.
I spawn in said entity like:
commands.spawn_bundle(PbrBundle {
mesh: meshes.add(Mesh::from(shape::Cube { size: 1.0 })),
material: builder_texture.clone(),
transform: Transform::from_matrix(Mat4::from_scale_rotation_translation(
Vec3::splat(0.75),
Quat::from_rotation_x(0.0),
Vec3::new(0.0, 0.0, 0.0),
)),
..Default::default()
})
.insert(controll::BuilderIndicator);
but I'm unable to despawn it like:
fn despawn(
mut entity: Query<(Entity, controll::BuilderIndicator), With<controll::BuilderIndicator>>,
mut commands: Commands,
) {
for (entity, example) in entity.iter_mut() {
commands.despawn(entity);
}
}
It returns:
error[E0599]: no method named `despawn` found for struct `bevy::prelude::Commands<'_>` in the current scope
--> src/controll.rs:120:26
|
120 | commands.despawn(entity);
| ^^^^^^^ help: there is an associated function with a similar name: `spawn`
error: aborting due to previous error
What do I have to do to make it work?

It seems that some methods have been moved to EntityCommands.
So you'd have to do:
commands.entity(entity).despawn();
I haven't tested yet.

Related

Why does vscode's "Run Doctest" helper filter all of my crate's Doctests?

Expected Behavior:
Clicking "Run doctest" in vscode should execute one test from doctest snippets.
Terminal output SHOULD say ("1 passed;" or "1 failed;"), and "1 filtered out;".
Actual Behavior:
Clicking "Run doctest" in vscode executes 0 tests, and shows that 2 were filtered out.
Terminal output:
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 2 filtered out; finished in 0.00s
Source code:
My misbehaving crate: https://github.com/darrow-olykos/rusty-gists/blob/main/crates/my_cache/src/lib.rs
Behaving crate (where this is not an issue): https://github.com/darrow-olykos/rusty-gists/blob/main/crates/math/src/lib.rs
My machine:
macOS 12
rustc 1.57.0
rust analyzer v0.3.954
What I have done to try to narrow down the scope of the problem:
Running the "same" command in the terminal demonstrates expected behavior. The terminal output shows test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 1 filtered out; finished in 0.40s when I run cargo test --doc --package my_cache -- "Cacher<T>::new" --nocapture, which is exactly what the terminal says is ran when I click on "Run Doctest".
Clicking "Run Doctest" in another crate I have, (called "math") in the same repo, demonstrates expected behavior.
Looking at the differences between my misbehaving crate and my working crate:
A. This misbehaving crate has it's doctest is inside of an impl where-as that other crate's doctest is at the root level of the file.
B. This misbehaving crate's doctest is for a generic struct that accepts a closure type.
C. Executing cargo test from crates/my_cache demonstrates expected behavior, with the following terminal output:
// ... some output omitted
Doc-tests my_cache
running 2 tests
test src/lib.rs - Cacher<T>::new (line 26) ... ok
test src/lib.rs - Cacher<T>::value (line 42) ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.44s
Again, here is the source code:
Misbehaving crate: https://github.com/darrow-olykos/rusty-gists/blob/main/crates/my_cache/src/lib.rs
Behaving crate: https://github.com/darrow-olykos/rusty-gists/blob/main/crates/math/src/lib.rs
Maybe? notable details:
I have modeled my git repo after the structure of https://github.com/rust-analyzer/rust-analyzer, such that I'm using cargo workspaces and crates/* are members. I have a root cargo.toml which can specify local dependencies with something like my_cache = {path = "crates/my_cache}, however I cannot think of a reason why this would be a contributing factor because I've proven that my math crate can be in this structure without vscode getting confused and filtering out doctests in that crate unexpected.
My suspicions?:
Something is happening that is causing the doctest to be filtered out when it should not be filtered out.
Maybe the command that claims to be executing when I click Run Doctest isn't the ACTUAL command getting executed.
Maybe the (bug?) has something to do with the closure type. I forget where I read this, but I vaguely recall Rust closure types are "unnamed" in a way that makes referencing them strange. Unfortunately I cannot find the resource that I was reviewing that walked through this in detail. (It might have been a resource that was covering the Rust compiler and how the Rust compiler manifests data types in memory, but I do not recall details (maybe someone reading this will know what I'm referring to here)).
Here is the misbehaving crate's source code copied into this answer for the sake of longevity in case I make changes to my github repo:
// Credit to: https://doc.rust-lang.org/book/ch13-01-closures.html
// (I've modified their example to use a HashMap instead of a single value)
use std::collections::HashMap;
/// cacher for calculation with two u64's as input and u64 as output
/// can be generalized more
pub struct Cacher<T>
where
T: FnMut(u64, u64) -> u64,
{
calculation: T,
values: HashMap<String, u64>,
}
impl<T> Cacher<T>
where
T: FnMut(u64, u64) -> u64,
{
/// Returns a Cacher<T> which can cache results of calculations for the provided closure.
///
/// # Arguments
///
/// `T` - Closure that computes produces a value. Value is cached based on args. Cached value is returend on subsequent calls if args are the same.
///
/// # Examples
/// ```rust
/// use my_cache::Cacher;
/// let mut cacher = Cacher::new(|x,y|x+y);
/// ```
pub fn new(calculation: T) -> Self {
let values = HashMap::new();
Cacher {
calculation,
values,
}
}
/// Returns value of calculation `T`. Cached value is returned if unique `n`, `k` pair provided, otherwise calcuation runs and then value is cached.
///
/// # Examples
///
/// ```rust
/// use std::rc::Rc;
/// use std::cell::{RefCell, RefMut};
///
/// use my_cache::Cacher;
///
/// let mut count = Rc::new(RefCell::new(0));
/// let add = |x, y| {
/// let mut count_mut_ref = count.borrow_mut();
/// *count_mut_ref += 1; x + y
/// };
/// let mut cacher = Cacher::new(add);
///
/// assert_eq!(*count.borrow(), 0);
/// assert_eq!(cacher.value(2, 3), 5); // new calculation, count += 1
/// assert_eq!(*count.borrow(), 1);
/// assert_eq!(cacher.value(2, 3), 5); // repeat, use cache
/// assert_eq!(*count.borrow(), 1);
/// assert_eq!(cacher.value(2, 4), 6); // new calculation, count += 1
/// assert_eq!(*count.borrow(), 2);
/// ```
pub fn value(&mut self, n: u64, k: u64) -> u64 {
let key = n.to_string() + &k.to_string();
let cached_result = self.values.get(&key);
if let Some(value) = cached_result {
*value
} else {
let v = (self.calculation)(n, k);
self.values.insert(key, v);
v
}
}
}
This is a bug in a pre-release version of vscode's rust analyzer extension (v3.0.954) and can be mitigated by switching back to the latest release version of rust analyzer.
I realized to check this once I posted my question and confirmed that the unexpected behavior was only present in v3.0.954, however the latest release of rust analyzer vscode extension v0.2.948 works as expected (does not filter out the doctest unexpectedly).

Babel: replaceWithSourceString giving Unexpected token (1:1)

I am trying to replace dynamically "import" statements.
Here is an example that checks if the import ends with a Plus.
module.exports = function(babel) {
return {
visitor: {
ImportDeclaration: function(path, state) {
// import abc from "./logic/+"
if( ! path.node.source.value.endsWith("/+"))
return;
path.replaceWithSourceString('import all from "./logic/all"')
}
}
}
}
This gives an error of
SyntaxError: src/boom.js: Unexpected token (1:1) - make sure this is an expression.
> 1 | (import all from "./logic/all")
The problem is that replaceWithSourceString is wrapping the string in rounded braces.
If I change the replaceWithSourceString to
path.replaceWithSourceString('console.log("Hi")')
and this works.. ¯_(ツ)_/¯
Any and all help you be great
replaceWithSourceString should really be avoided, because it is just not a very good API, as you are seeing. The recommended approach for creating ASTs to insert into the script is to use template. Assuming this is for Babel 7.x, you can do
const importNode = babel.template.statement.ast`import all from "./logic/all"`;
path.replaceWith(importNode);

Understanding merge in rxjs6 (and redux-observable specifically)

Context: I'm trying to use redux-observable with rxjs v6 to trigger multiple actions after fetching a resource.
Problem: I can trigger a single action after fetching the resource no problem; but my attempt to trigger multiple actions has me stumped. Specifically, my attempt shown below to use rxjs merge to trigger multiple actions seems so standard and close to documented examples (see e.g. here) that I can't understand where I'm going wrong. Here is a breakdown of my code with typescript types indicated in comments; I've simplified things for the sake of problem clarity:
import { from } from "rxjs";
import { merge, mergeMap, map } from "rxjs/operators";
import { AnyAction } from "redux";
... //Setup related to rxjs-observable epics
function myEpic(
action$: Observable<AnyAction>,
state$: any,
{fetchPromisedStrings}: any
) {
return action$.pipe(
ofType('MY_ACTION'),
mergeMap(
action =>
{
const demoAction1: AnyAction = {type:'FOO1', payload:'BAR1'};
const demoAction2: AnyAction = {type:'FOO2', payload:'BAR2'};
const w = from(fetchPromisedStrings()) //const w: Observable<string[]>
const x = w.pipe( map(() => demoAction1)); //const x: Observable<AnyAction>
const y = w.pipe( map(() => demoAction2)); //const y: Observable<AnyAction>
//My attempt to merge observables:
const z = merge(x,y); // const z: OperatorFunction<{}, {} | AnyAction>
// return x; // Works :)
// return y; // Works :)
return z; // Doesn't work :(
}
)
);
}
This code gives me the following error when I try to return z:
TypeError: You provided 'function (source) { return source.lift.call(_observable_merge__WEBPACK_IMPORTED_MODULE_0__["merge"].apply(void 0, [source].concat(observables))); }' where a stream was expected. You can provide an Observable, Promise, Array, or Iterable
So what's the problem here? I'd expect merge in the above code to take the two Observable<AnyAction> types and return a single Observable<AnyAction> type (or some more general type that's compatible with Observable<AnyAction>, which my epic needs in order to function correctly). Instead, I get some opaque type called OperatorFunction<{}, {} | AnyAction> that, evidently, isn't compatible with Observable<AnyAction>. Could someone please unmuddle my thinking here? Is merge not the operator I am supposed to use here, or is my entire rxjs-v6 pattern wrong for the (seemingly) simple goal of triggering multiple actions after fetching a promised resource?
Your code is ok, but you've imported merge operator instead of merge observable factory
Just do:
import { merge } from 'rxjs';

Unity 5.3 and .NET | AppendText & CreateText

Even though I have already changed the API Compatibility Level from .NET 2.0 Subset to .NET 2.0 in Edit->Project Settings->Player under Optimizations, upon upgrading to Unity 5.3.0 I am still getting the following two error messages:
`System.IO.File' does not contain a definition for `AppendText'
`System.IO.File' does not contain a definition for `CreateText'
They refer to the following code snippets:
using(StreamWriter writer = File.CreateText(saveFilePath))
{
string sLine = "time;joint;pos_x;pos_y;poz_z";
writer.WriteLine(sLine);
}
using(StreamWriter writer = File.AppendText(saveFilePath))
{
string sLine = string.Format("{0:F3};{1};{2:F3};{3:F3};{4:F3}", Time.time, (int)joint, jointPos.x, jointPos.y, jointPos.z);
writer.WriteLine(sLine);
}
How do I resolve this?
Are you tried this case?
using (var f = new StreamWriter("file path", true))
{
f.WriteLine("appended text");
f.Flush();
}

Collection.update giving server error

Trying to learn the Meteor framework as well as coffeescript/node all at once. Been working on a simple file upload program that utilizes onloadend. When the FileReader onloadend event function is called I try to determine if the file already exists and if so I update with the new file data and version.
The code works for insert but not update. Can someone help? I've posted to meteor-talk w/o an answer as I suspect its the weekend (when I do most of my experimentation).
Code snippet...
file_reader.onloadend = ((file_event) ->
(event) ->
f_filename = escape file_event.name
version = 0
f_record = null
f_record = doc_repo.findOne { name: f_filename }
if f_record && f_record.name
doc_repo.update
name: f_filename
,
$set:
version: 10
else
doc_repo.insert
name: f_filename
data: event.target.result
version: 0
)(file_obj)
Error
Exception while invoking method '/documents/update' TypeError: Cannot read property 'toBSON' of undefined
at Function.calculateObjectSize (/usr/local/meteor/lib/node_modules/mongodb/node_modules/bson/lib/bson/bson.js:210:12)
at BSON.calculateObjectSize (/usr/local/meteor/lib/node_modules/mongodb/node_modules/bson/lib/bson/bson.js:1463:15)
at UpdateCommand.toBinary (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/commands/update_command.js:67:20)
at Connection.write (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/connection/connection.js:138:40)
at __executeInsertCommand (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/db.js:1837:14)
at Db._executeInsertCommand (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/db.js:1912:7)
at Collection.update (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/collection.js:445:13)
at app/packages/mongo-livedata/mongo_driver.js:178:16
at Db.collection (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/db.js:507:44)
at _Mongo._withCollection (app/packages/mongo-livedata/mongo_driver.js:51:13)
It looks like Mongo is not getting the second parameter which it needs to do the update. So in regular JavaScript it's expecting this:
collection.update({..selector..}, { .. modifier });
So I'd try putting some curly brackets around the modifier object, like this:
doc_repo.update
name: f_filename,
{
$set:
version: 10
}