PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label reference. Show all posts
Showing posts with label reference. Show all posts

Wednesday, December 14, 2022

[FIXED] Why do some people prefer "T const&" over "const T&"?

 December 14, 2022     c++, pointers, reference, syntax, types     No comments   

Issue

So, I realize that const T& and T const& are identical and both mean a reference to a const T. In both cases, the reference is also constant (references cannot be reassigned, unlike pointers). I've observed, in my somewhat limited experience, that most C++ programmers use const T&, but I have come across a few people who use T const&. I use const T& simply because I learned it that way, and so T const& looks a little bit funny to me. What is the reason that you use the variant that you use? Do any of you work at an organization for which the coding standards mandate the use of one variant over the other?

Edit
Based on the answers, it would appear that one reason for choosing between the two is whether you want to read it like the compiler (right-to-left) or like English (left-to-right). If one reads it like the compiler, then "T const&" reads as "& (reference) const (to a constant) T (of type T)". If one reads it like English, from left-to-right, then "const T&" is read as "a constant object of type T in the form of a reference". I prefer to read it like English prose, but I can certainly see the sense in interpreting it the way that the compiler does.

No one has answered the organization or coding standards question, but I strongly suspect that most organizations do not mandate one over the other, although they might strive for consistency.


Solution

I think some people simply prefer to read the declarations from right to left. const applies to the left-hand token, except when there is nothing there and it applies on the right-hand token. Hence const T& involves the "except"-clause and can perhaps be thought more complicated (in reality both should be as easy to understand).

Compare:

const T* p;  (pointer to T that is const)
T const* p;  (pointer to const T) //<- arguable more natural to read
T* const p;  (const pointer to T)


Answered By - UncleBens
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, December 12, 2022

[FIXED] What do the ampersand '&' and star '*' symbols mean in Rust?

 December 12, 2022     dereference, reference, rust, syntax     No comments   

Issue

Despite thoroughly reading the documentation, I'm rather confused about the meaning of the & and * symbol in Rust, and more generally about what is a Rust reference exactly.

In this example, it seems to be similar to a C++ reference (that is, an address that is automatically dereferenced when used):

fn main() {
    let c: i32 = 5;
    let rc = &c;
    let next = rc + 1;
    println!("{}", next); // 6
}

However, the following code works exactly the same:

fn main() {
    let c: i32 = 5;
    let rc = &c;
    let next = *rc + 1;
    println!("{}", next); // 6
}

Using * to dereference a reference wouldn't be correct in C++. So I'd like to understand why this is correct in Rust.

My understanding so far, is that, inserting * in front of a Rust reference dereferences it, but the * is implicitly inserted anyway so you don't need to add it (while in C++, it's implicitly inserted and if you insert it you get a compilation error).

However, something like this doesn't compile:

fn main() {
    let mut c: i32 = 5;
    let mut next: i32 = 0;
    {
        let rc = &mut c;
        next = rc + 1;
    }
    println!("{}", next);
}
error[E0369]: binary operation `+` cannot be applied to type `&mut i32`
 --> src/main.rs:6:16
  |
6 |         next = rc + 1;
  |                ^^^^^^
  |
  = note: this is a reference to a type that `+` can be applied to; you need to dereference this variable once for this operation to work
  = note: an implementation of `std::ops::Add` might be missing for `&mut i32`

But this works:

fn main() {
    let mut c: i32 = 5;
    let mut next: i32 = 0;
    {
        let rc = &mut c;
        next = *rc + 1;
    }
    println!("{}", next);  // 6
}

It seems that implicit dereferencing (a la C++) is correct for immutable references, but not for mutable references. Why is this?


Solution

Using * to dereference a reference wouldn't be correct in C++. So I'd like to understand why this is correct in Rust.

A reference in C++ is not the same as a reference in Rust. Rust's references are much closer (in usage, not in semantics) to C++'s pointers. With respect to memory representation, Rust's references often are just a single pointer, while C++'s references are supposed to be alternative names of the same object (and thus have no memory representation).

The difference between C++ pointers and Rust references is that Rust's references are never NULL, never uninitialized and never dangling.


The Add trait is implemented (see the bottom of the doc page) for the following pairs and all other numeric primitives:

  • &i32 + i32
  • i32 + &i32
  • &i32 + &i32

This is just a convenience thing the std-lib developers implemented. The compiler can figure out that a &mut i32 can be used wherever a &i32 can be used, but that doesn't work (yet?) for generics, so the std-lib developers would need to also implement the Add traits for the following combinations (and those for all primitives):

  • &mut i32 + i32
  • i32 + &mut i32
  • &mut i32 + &mut i32
  • &mut i32 + &i32
  • &i32 + &mut i32

As you can see that can get quite out of hand. I'm sure that will go away in the future. Until then, note that it's rather rare to end up with a &mut i32 and trying to use it in a mathematical expression.



Answered By - oli_obk
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, October 31, 2022

[FIXED] How can I use "map" in "perl" to return a hash reference whose key is looked up from an array reference whose value is looked up from another array?

 October 31, 2022     hashref, performance, perl, reference     No comments   

Issue

I've searched other many Stack questions on map however this requirement is particular and well try as I might I cannot quite get the solution I am looking for, or I think that does exist.

This question is simply about performance.

As limited, background, this code segment used in decoding incoming tokens so it's used on every web request and therefore the performance is critical and I know "map" can be used so want to use it.

Here is a trimmed down but nevertheless fully working code segment which I am currently using and works perfectly well:

use strict;
use Data::Dumper qw (Dumper);

my $api_token = { array => [ 'user_id', 'session_id', 'expiry' ], max => 3, name => 'session' };
my $token_got = [ 9923232345812112323, 1111323232000000465, 1002323001752323232 ];

my $rt;
for (my $i=0; $i<scalar @{$api_token->{array}}; $i++) {
  $rt->{$api_token->{array}->[$i]} = $token_got->[$i];
}

$rt->{type} = $api_token->{name};
print Dumper ($rt) . "\n";

The question is: What is the absolute BEST POSSIBLE PERL CODE to replicate the foreach statement above in terms of performance?


Solution

Looks like you only need a hash slice

my %rt;

@rt{ @{ $api_token->{array} } } = @$token_got;

Or, if the hash reference is needed

my $rt;

@{ $rt } { @{ $api_token->{array} } } = @$token_got;

or with the newer postfix dereferencing, on both array and hash slices, perhaps a bit nicer

my $rt;

$rt->@{ $api_token->{array}->@* } = @$token_got;

One can also do it using List::MoreUtils::mesh, and in one statement

my $rt = { mesh @{ $api_token->{array} }, @$token_got };

or with pairwise from the same library

my $rt = { pairwise { $a, $b } @{ $api_token->{array} }, @$token_got };

These go via C code if the library gets installed with List::MoreUtils::XS.


Benchmarked all above, with the tiny datasets from the question (realistic though?), and whatever implementation mesh/pairwise have they are multiple times as slow as the others.

On an old laptop with v5.26

              Rate use_pair use_mesh use_href use_post use_hash
use_pair  373639/s       --     -36%     -67%     -67%     -68%
use_mesh  580214/s      55%       --     -49%     -49%     -51%
use_href 1129422/s     202%      95%       --      -1%      -5%
use_post 1140634/s     205%      97%       1%       --      -4%
use_hash 1184835/s     217%     104%       5%       4%       --

On a server with v5.36 the numbers are around 160%--170% against pairwise (with mesh being a bit faster than it, similarly to above)

Of the others, on the laptop the hash-based one is always a few percent quicker, while on a server with v5.36 they are all very close. Easy to call it a tie.


The following is edit by OP, who timed a 61% speedup (see comments)

CHANGED CODE:

@rt{ @{ $api_token->{array} } } = @$token_got; ### much faster onliner replaced the loop. @zdim credit


Answered By - zdim
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, October 21, 2022

[FIXED] How to reach a table's column from an id in another table rails

 October 21, 2022     activerecord, has-many, reference, ruby-on-rails     No comments   

Issue

I have 2 tables in my project: Transactions and Accounts Every transactions "belong_to" an account. And one account can have many transactions. I modified the models file accordingly.

    ActiveRecord::Schema.define(version: 2021_09_26_204408) do

  create_table "accounts", force: :cascade do |t|
    t.string "title"
    t.float "balance"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
  end

  create_table "transactions", force: :cascade do |t|
    t.string "title"
    t.float "value"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.string "notes"
    t.integer "account_id"
    t.index ["account_id"], name: "index_transactions_on_account_id"
  end

  add_foreign_key "transactions", "accounts"
end

This is my Accounts controller

        class AccountsController
  def index
    @accounts = Account.all
  end

  def show
    @transaction = Transaction.find(params[:id])
    @account = Account.find_by(id: @transaction.account_id)
  end
end

I am trying to show the Title of the account for every transaction shown on my index. And I'd like to able to sum the values of every transactions with that id to get a balance.

I am able to get the transaction.account_id but I can't reach further into the table.

I tried this in my index.html.erb

<% @accounts.each do |account| %>
    <%= account.title %>
<% end %> 

But I get the @accounts is not defined or Nill.

Routes.rb

Rails.application.routes.draw do
  root "transactions#index"

  resources :transactions
  resources :accounts
end

Thank you for your help


Solution

first of all seems you have not all transactions have account_id present.

To fix it I suggest to add validator and not null declaration for transaction table like this

  create_table "transactions", force: :cascade do |t|
    ...
    t.integer "account_id",  null: false
    ... 
  end

that will protect you from having transaction without account on database level.

Next problem what I see is that you are fetching accounts via index action, but transaction via show action.

Assuming you have models like

class Account < ApplicationRecord
  has_many :transactions
end

class Transaction < ApplicationRecord
  belongs_to :account
end

Than your accounts controller might looks like

class AccountsController
  def index
    @accounts = Account.all
  end

  def show
    @account = Account.find(params[:id])
  end
end

Than you can render accounts via template in cycle, like you did.

Regarding question about sum of transactions per account, I'll just give you direction to understand how it works (try use rails console to check next snippet)

@accounts =  Account.joins(:transactions).select("accounts.* ,sum(transactions.value) as transactions_sum ").group("transactions.account_id")

@accounts.each do |account|
   puts account.title
   puts account.transactions_sum.to_s
end

similar question has_many with sum active record

And last typo - use decimals in database for storing amounts, not floats

Good luck!



Answered By - Fivell
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, July 10, 2022

[FIXED] How can I delete all unreferenced files in an Xcode project?

 July 10, 2022     delete-file, reference, xcode     No comments   

Issue

I added a bunch of files at different times to my project then later deleted them, and I forgot to make Xcode trash the files in addition to the references. Since Xcode doesn't store the grouped files in separate directories, I now have hundreds of files and folders all together in my project directory, and it would be a pain to sift through and take out the ones I don't want.

I'm using Xcode 5. How do I make it automatically delete all files in my project directory that aren't actually part of the project? Note: I am not referring to files referenced in my source code, just the Xcode project itself.

I had the idea of using the built-in git functionality to solve this by pushing the project to Github, deleting the local copy, then cloning it back. But apparently, removing referenced files in Xcode won't prevent them from being committed. If there's some option to make Xcode only include referenced files in the git repository, that would work too (even though it's a hack workaround).


Solution

AFAIK, there are no trivial way to find unreferenced files in an Xcode project.

I wrote a tool to do it though.



Answered By - Frizlab
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why does a = a['k'] = {} create an infinitely nested dictionary?

 July 10, 2022     assignment-operator, dictionary, operator-precedence, python, reference     No comments   

Issue

Here is my Python code that creates an infinitely nested dictionary:

a = a['k'] = {}

print(a)
print(a['k'])
print(a['k']['k'])
print(a is a['k'])

Here is the output:

{'k': {...}}
{'k': {...}}
{'k': {...}}
True

The output shows that a['k'] refers to a itself which makes it infinitely nested.

I am guessing that the statement:

a = a['k'] = {}

is behaving like:

new = {}
a = new
a['k'] = new

which would indeed create an infinitely nested dictionary.

I looked at Section 7.2: Assignment statements of The Python Language Reference but I couldn't find anything that implies that a = a['k'] = {} should first set a to the new dictionary and then insert a key/value pair in that dictionary. Here are some excerpts from the reference that I found relevant but did not answer my question:

If the target list is a single target with no trailing comma, optionally in parentheses, the object is assigned to that target.

If the target is a subscription: The primary expression in the reference is evaluated. It should yield either a mutable sequence object (such as a list) or a mapping object (such as a dictionary). Next, the subscript expression is evaluated.

If the primary is a mapping object (such as a dictionary), the subscript must have a type compatible with the mapping’s key type, and the mapping is then asked to create a key/datum pair which maps the subscript to the assigned object. This can either replace an existing key/value pair with the same key value, or insert a new key/value pair (if no key with the same value existed).

Each of these excerpts define the behaviour of an assignment with a single target such as a = {} and a['k'] = {} but they don't seem to talk about what should happen in case of a = a['k'] = {}. Where is the order of evaluation for such a statement documented?


This question is now resolved. GPhilo's answer pointed to the relevant clause of Section 7.2: Assignment statements. The relevant clause was right at the beginning but I had overlooked it earlier. Here it is:

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

Let us compare it with the grammar now.

The assignment statement is defined as

assignment_stmt ::=  (target_list "=")+ (starred_expression | yield_expression)

So the statement

a = a['k'] = {}

has two target_list elements, i.e., a and a['k'], and a starred_expression element, i.e., {}, so {} is assigned to each of the target lists a and a['k'] from left to right.


Solution

Assignments in an assignment statement are resolved from left to right, as per the section 7.2 you quoted (emphasis mine):

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

That means that yes, indeed your statement is equivalent to:

new = {}
a = new
a['k'] = new

As a quick counter-proof, swapping the order of the assignments results in error:

a['k'] = a = {}

raises

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined


Answered By - GPhilo
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to access a widget in another widget event handler : Tkinter

 July 10, 2022     global-variables, python, reference, tkinter     No comments   

Issue

I am creating a GUI in tkinter having a listbox and a Text item in a child window which appears after a button click. Listbox is displaying values of a dict which are basically names of files/directories in disk image. I want to change the text of Text widget on <ListboxSelect> event and display type or path of selected file.

Now I cant make Text global since it has to appear on child window, so I need a way to access it in event handler of Listbox. Can I give handler reference of Textbox?

Here is my code;

def command(event):
    ...          #Need to change the Text here, how to access it?

def display_info(dict,filename):
    child_w = Tk()
    listbox = Listbox(child_w)
    textview = Text(child_w)

    ...

    listbox.bind(<ListboxSelect>,command)

def upload_file():



window = Tk()
upl_button = Button(command=upload_file)

window.mainloop()
    

Is there a way to create a textview as global and then change its properties later to be displayed in child_window etc.


Solution

Two solutions here that I can think of is to make textview a globalized variable or to pass textview to command() as an argument.

  • Parameter solution:
def command(event,txtbox):
    txtbox.delete(...)

def display_info(dict,filename):
    child_w = Tk()
    listbox = Listbox(child_w)
    textview = Text(child_w)

    ...

    listbox.bind('<ListboxSelect>',lambda event: command(event,textview))
  • Or simply just globalize it:
def command(event):
    textview.delete(...)

def display_info(dict,filename):
    global textview

    child_w = Tk()
    listbox = Listbox(child_w)
    textview = Text(child_w)

    ...

    listbox.bind('<ListboxSelect>',command)

While saying all this, it is good to keep in mind that creating more than one instance of Tk is almost never a good idea. Read: Why are multiple instances of Tk discouraged?



Answered By - Delrius Euphoria
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to create a cumulative report based on differences between data updated daily in google sheets?

 July 10, 2022     google-sheets, google-sheets-formula, reference, vlookup     No comments   

Issue

I am trying to create a report from another report(source sheet). :) The source sheet updates daily automatically by inserting new rows with progress on sales on top of the rows completed a day before:

Date Product Units sold
11/15 A 35
11/15 B 12
11/15 C 18
11/14 A 30
11/14 C 11
11/14 B 10
11/13 F 88
11/12 B 7
11/12 A 29
11/12 C 10
11/11 C 8
11/11 A 29
11/11 B 3

The "Units sold" column is cumulative meaning that a newer record on a certain product will show a greater or equal value to a previous record on that specific product. New products appear in the source sheet when entering the company and they disappear from it when they are sold out, pretty much randomly. (e.g. product "F" that showed up and sold out in the same day) In the first column in the source report i already found a formula that concatenates date and product and is used by another reports.

To solve this, in the results report i made on column T the same concat of date and product. Then, in my new report, in the results column, i used the following formula: =vlookup(T2,Source!$A2:$C$10000,3,0)-vlookup(T2,Source!$A3:$C$10000,3,0) with the intention to obtain the difference between the amount of products sold in the last day vs the amount of products sold in the day before it, or, better said, the amount of each of the products sold on a specific date. Finally, by using a column of =year() and one of =month() applied on date column and a couple of pivot tables i was able to obtain the value of the daily increment for each and/or year.

The problem i couldn't find a solution for is that when the source sheet updates, the new rows added with the freshest data move down the cell references from the vlookup formula i used in the results sheet. Please help me find a way to "pin down" the cell references in the vlookup formula without being affected by the new rows insertions.

Thank you!


Solution

to "pin down" the references you can use INDIRECT

example:

A1:A >>> INDIRECT("A1:A")


Answered By - player0
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why is the return type of Deref::deref itself a reference?

 July 10, 2022     pointers, reference, rust     No comments   

Issue

I was reading the docs for Rust's Deref trait:

pub trait Deref {
    type Target: ?Sized;
    fn deref(&self) -> &Self::Target;
}

The type signature for the deref function seems counter-intuitive to me; why is the return type a reference? If references implement this trait so they can be dereferenced, what effect would this have at all?

The only explanation that I can come up with is that references don't implement Deref, but are considered "primitively dereferenceable". However, how would a polymorphic function which would work for any dereferenceable type, including both Deref<T> and &T, be written then?


Solution

that references don't implement Deref

You can see all the types that implement Deref, and &T is in that list:

impl<'a, T> Deref for &'a T where T: ?Sized

The non-obvious thing is that there is syntactical sugar being applied when you use the * operator with something that implements Deref. Check out this small example:

use std::ops::Deref;

fn main() {
    let s: String = "hello".into();
    let _: () = Deref::deref(&s);
    let _: () = *s;
}
error[E0308]: mismatched types
 --> src/main.rs:5:17
  |
5 |     let _: () = Deref::deref(&s);
  |                 ^^^^^^^^^^^^^^^^ expected (), found &str
  |
  = note: expected type `()`
             found type `&str`

error[E0308]: mismatched types
 --> src/main.rs:6:17
  |
6 |     let _: () = *s;
  |                 ^^ expected (), found str
  |
  = note: expected type `()`
             found type `str`

The explicit call to deref returns a &str, but the operator * returns a str. It's more like you are calling *Deref::deref(&s), ignoring the implied infinite recursion (see docs).

Xirdus is correct in saying

If deref returned a value, it would either be useless because it would always move out, or have semantics that drastically differ from every other function

Although "useless" is a bit strong; it would still be useful for types that implement Copy.

See also:

  • Why does asserting on the result of Deref::deref fail with a type mismatch?

Note that all of the above is effectively true for Index and IndexMut as well.



Answered By - Shepmaster
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why is 'this' a pointer and not a reference?

 July 10, 2022     c++, c++-faq, pointers, reference, this     No comments   

Issue

I was reading the answers to this question C++ pros and cons and got this doubt while reading the comments.

programmers frequently find it confusing that "this" is a pointer but not a reference. another confusion is why "hello" is not of type std::string but evaluates to a char const* (pointer) (after array to pointer conversion) – Johannes Schaub - litb Dec 22 '08 at 1:56

That only shows that it doesn't use the same conventions as other (later) languages. – le dorfier Dec 22 '08 at 3:35

I'd call the "this" thing a pretty trivial issue though. And oops, thanks for catching a few errors in my examples of undefined behavior. :) Although I don't understand what info about size has to do with anything in the first one. A pointer is simply not allowed to point outside allocated memory – jalf Dec 22 '08 at 4:18

Is this a constant poiner? – yesraaj Dec 22 '08 at 6:35

this can be constant if the method is const int getFoo() const; <- in the scope of getFoo, "this" is constant, and is therefore readonly. This prevents bugs and provides some level of guarantee to the caller that the object won't change. – Doug T. Dec 22 '08 at 16:42

you can't reassign "this". i.e you cannot do "this = &other;", because this is an rvalue. but this is of type T*, not of type T const . i.e it's a non-constant pointer. if you are in a const method, then it's a pointer to const. T const . but the pointer itself is nonconst – Johannes Schaub - litb Dec 22 '08 at 17:53

think of "this" like this: #define this (this_ + 0) where the compiler creates "this_" as a pointer to the object and makes "this" a keyword. you can't assign "this" because (this_ + 0) is an rvalue. of course that's not how it is (there is no such macro), but it can help understand it – Johannes Schaub - litb Dec 22 '08 at 17:55

My question is, why is this a pointer a not a reference? Any particular reason for making it a pointer?


Some further arguments why this being a reference would make sense:

  • Consider Item 1 from More Effective C++ : use references when it is guaranteed that we have a valid object i.e. not a NULL (my interpretation).
  • Furthermore, references are considered safer than pointers (because we can't screw the memory up with a stray pointer).
  • Thirdly, the syntax for accessing references (.) is a little bit nicer and shorter than accessing pointers (-> or (*)).

Solution

When the language was first evolving, in early releases with real users, there were no references, only pointers. References were added when operator overloading was added, as it requires references to work consistently.

One of the uses of this is for an object to get a pointer to itself. If it was a reference, we'd have to write &this. On the other hand, when we write an assignment operator we have to return *this, which would look simpler as return this. So if you had a blank slate, you could argue it either way. But C++ evolved gradually in response to feedback from a community of users (like most successful things). The value of backward compatibility totally overwhelms the minor advantages/disadvantages stemming from this being a reference or a pointer.



Answered By - Daniel Earwicker
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get the value of flutter map by call by value

 July 10, 2022     dart, dictionary, flutter, reference     No comments   

Issue

I am developing a movie app using TMDB.

A total of 3 pieces of data are needed to create a reservation system.

1.MovieList's index

2.date's index

3.seat Satus

I've been trying to process this as a map.

//Seat Status total 200 Seat
List<bool> _seat = [];
for(int nIndex=0; nIndex<200; nIndex++){
      _seat.add(false);
    }

//Date index(total 7 days) + Seat status
Map _date = Map();
for(int nIndex=0; nIndex<7; nIndex++){
      _date[nIndex] = _seat.toList();
    }

//TMDB MovieList index
Map _movie = Map();
for(int nIndex=0; nIndex<MoviesList.length; nIndex++){
        _movie[nIndex] = _date;
    }

The value is entered normally as I want.

However, when one seat data is changed, all seat data in the map is changed.

I noticed that this is because the map and list references are input.

Do you know how to get a value by call by value rather than by call by reference?

 seat = List.filled(200, false, growable: true);
 date = List.generate(7, (_) => List.from(seat));
 movie = List.generate(length, (_) => List.from(date));

My code was like above.

for example

 movie[0][0][0] = false; // Change value
 print(movie[0][0][0]);  // result false
 print(movie[1][0][0]);  // result false

In this way, the values ​​change together.


Solution

In order to make a new list reference with the same values as the previous one, you can call List.from.

So like this:

_date[nIndex] = List.from(_seat);

you can use a similar syntax with a map

_movie[nIndex] = Map.from(_date);

EDIT

It seems like this solution actually does not work, dart can use .from to copy a list, or even to copy a list of lists, but copying a list of a list of lists? That's too much man! It can't handle that, it will only copy up one level. Thankfully, solving this is simple once you know why it happens:

var seat = List.filled(3, false, growable: true);
var date = List.generate(4, (_) => List.from(seat));
var movie = List.generate(5, (_) => List.from(date.map((v) => 
List.from(v))));

movie[0][0][0] = true; // Change value
print(movie[0][0][0]); // true
print(movie[1][0][0]); // false (default value)

For the last one, instead of creating a new list from seat, I am first using map to copy each of the lists on to a new list, and then I am copying those new lists into a new list.

I believe that fixes the issue we were encountering

PS

This is a recommendation, if you don't care, you can stop reading now:

if you want to generate a list of 200 false values, you can use this syntax instead:

List<bool> _seat = List.filled(200, false, growable: true);

which makes for a shorter and more readable way to do the same thing.

When declaring a map, this syntax is preferred:

Map<int, List<bool>> _date = {};
Map<int, Map<int, List<bool>>> _movie = {};

I know it looks a bit gross, but it makes sure you don't add the wrong types to your map

And finally, why are you using a map in the first place? Your map behaves the exact same as a list because the key is an index, and you could generate said list using the generate constructor instead of a for loop, like this:

//Date index(total 7 days) + Seat status
List<List<bool>> _date = List.generate(7, (_) => List.from(_seat));

//TMDB MovieList index
List<List<List<bool>>> _movie = List.generate(
  MoviesList.length, (_) => List.from(_date));

Again, the syntax looks gross, that's because of all of the nested lists, probably better off making a class that can store the values in a more neat and type-safe way, but I lack the information to show you how you would write such a class.



Answered By - h8moss
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to make a for loop to apply conditional formating?

 July 10, 2022     excel, for-loop, reference, vba     No comments   

Issue

I created a conditional formatting for the first set of columns (C:E) (see image 3).

Range("C1:E36").Select
Selection. Format Conditions. Add Type:=xlExpression, Formulal:="=$D6=""Sun"""
Selection. Format Conditions (Selection. FormatConditions. Count).SetFirstPriority
with Selection. Format Conditions (1). Interior
.Pattern = xlLightVertical
. PatternColor = 65535
.ColorIndex = xlAutomatic
.PatternTintAndShade = 0
End With

I am trying to create a for loop that it should apply to all twelve sets - each with 3 columns (see image 2). Additionally, it should run 3 times - starting at rows C6, C45,C84 - corresponding to the three year I am trying to display (see image 1). I am struggling with the for loop. And the relative abs reference on columns of $D6 in the conditional formatting and how to make that be $G6, $J6, $D84, $G84.

For o = 1 TO 3 Step 1
    For I = 1 To 12 Step 1
    Range (.Cells(6, I * 3), .Cells (36, I * 3 + 2)).Select
    Selection. Format Conditions. Add Type:=xlExpressionFormulal:="=$D6=""Sun"""
    Selection. Format Conditions (Selection. Format Conditions. Count).SetFirstPriority
    With Selection. Format Conditions (1). Interior
   .Pattern = xlLightvertical
   .PatternColor = 65535
   .ColorIndex = xlAutomatic
   .PatternTintAndShade = 0
    End With
    Next I
Next o
End Sub'


Solution

For copying formatting, I suggest .Copy and .PasteSpecial using xlPasteFormats. As for dynamically determining the ranges, since yours have a regular sizing and predictable location, its simplest to write a static For Loop to iterate the Row and Column numbers.

Sub Example()
    Dim r As Long, c As Long 
    For r = 6 To 84 Step 39
        For c = 3 To 36 Step 3
            Cells(r, "C").Resize(38, 3).Copy
            Cells(r, c).Resize(38, 3).PasteSpecial xlPasteFormats
        Next
    Next
End Sub

This code Copies formatting from "C6:E44" onto the adjacent columns. 12 Sets, each 3 columns wide (Eg "F6:H44","I6:K44"). Then it advances the row number from 6 to 45 and does it again, copying "C45:E83" onto "F45:H83" and the other 11 column sets. Then it advances from row 45 to row 84 and does this again.

In Response to your comments about applying a new/custom formatting for each range:

Sub Example()
    For r = 6 To 84 Step 39
        For c = 3 To 36 Step 3
            ApplyFormatting Cells(r, c).Resize(38, 3)
        Next
    Next
End Sub

Sub ApplyFormatting(InRange As Range)
    InRange.FormatConditions.Add Type:=xlExpression, Formula1:="=" & InRange.Cells(1, 2).Address(False, True) & "=""Sun"""
    InRange.FormatConditions(InRange.FormatConditions.Count).SetFirstPriority
    With InRange.FormatConditions(1).Interior
        .Pattern = xlLightVertical
        .PatternColor = 65535
        .ColorIndex = xlAutomatic
        .PatternTintAndShade = 0
    End With
End Sub

This procedure ApplyFormatting takes each range and uses the address as part of a new formatting formula applied to the whole range.



Answered By - Toddleson
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why aren't Java references not null by default?

 July 10, 2022     java, reference     No comments   

Issue

I've seen this question for other languages (C and C++). But I still don't get why it is like this in Java as well. Where could it be useful that a reference is declared but not set to null?


Solution

Thing ref;
if (someCondition)
   ref = oneThing;
else 
   ref = anotherThing;

There is no benefit in initializing 'ref' to null in the above code, at least not as long as neither assignment can throw an exception.

It's not "useful" that it is uninitialized, it's merely that there's no point in initializing it.

I wish it were not like that - I'd prefer initialization of local variables to work like member variables - but that is how it is.

I assume it's for efficiency reasons. If you don't have to initialize local variables, allocation is pretty much just an adjustment of the stack pointer.



Answered By - user16632363
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to return a reference in C++

 July 10, 2022     c++, reference     No comments   

Issue

If for example I create a new object in a function and I want to return its reference how can I do it?

Lets say I got an IntClass that has a 'int num' field in the private. So i want to create a new element of IntClass in the function and return the reference of that object. I've tried something like that but it seems illegal (from some reason when I do such thing the Binaries gets deleted when I compile the code although I get no errors from the compiler itself (ECLIPSE):

 IntClass* a = new IntClass(10);
 IntClass &ref = *a;
 return ref;

Any ideas how to return a reference then?

EDIT: It's allowed to "assume" that C++ uses a Garbage-Collection

As it's not clear to most of you WHY I "want" to do it so here is the full question:

I got this file (Not made by me and can't be edited):

poly_subtype.h:

#ifndef POLY_SUBTYPE_H
#define POLY_SUBTYPE_H
#include <iostream>
#include "cpu_add.h"
using std::cout;
using std::endl;

//Deriving classes definition
class IntClass;
class DoubleClass;

//The Virtual Number Class. IntClass and FloatClass will derive from this class.
class Number {
    public:
        //return a Number object that's the results of x+this, when x is DoubleClass
        virtual Number& addDouble(DoubleClass& x) = 0;

        //return a Number object that's the results of x+this, when x is IntClass
        virtual Number& addInt(IntClass& x) = 0;

        //return a Number object that's the results of x+this, when x is either
        //IntClass or DoubleClass
        virtual Number& operator+(Number& x) = 0;

        //Print the number stored in the object
        virtual void print_number() = 0;
};

class IntClass : public Number {
    private:
        int my_number;
    public:
        //Constructor
        IntClass(int n):my_number(n) {}

        //returns the number stored in the object
        int get_number()  {return my_number;}

        //print the number stored in the object
        void print_number() {cout << my_number << endl;}

        //return a DoubleClass object that's the result of x+this
        Number& addDouble(DoubleClass& x);

        //return an IntClass object that's the result of x+this
        Number& addInt(IntClass& x);

        //return a Number object that's the result of x+this.
        //The actual class of the returned object depends on x.
        //If x is IntClass, then the result if IntClass.
        //If x is DoubleClass, then the results is DoubleClass.
        Number& operator+(Number& x);
};

class DoubleClass : public Number {
    private:
        double my_number;
    public:
        //Constructor
        DoubleClass(double n):my_number(n) {}

        //returns the number stored in the object
        double get_number()  {return my_number;}

        //Print the number stored in the object
        void print_number() {cout << my_number << endl;}

        //return a DoubleClass object that's the result of x+this
        Number& addDouble(DoubleClass& x);

        //return a DoubleClass object that's the result of x+this
        Number& addInt(IntClass& x);

        //return a DoubleClass object that's the result of x+this.
        //This should work if x is either IntClass or DoubleClass
        Number& operator+( Number& x);
};

#endif

and I've got this file (again, not written by me and can't be edited - says I can use those functions but not the '+' operator.

cpu_add.h:

#ifndef CPU_ADD_H
#define CPU_ADD_H

double add_double_double(double a, double b) {return (a+b);}
double add_int_double(int a, double b) {return ((double)(a)+b);}
int   add_int_int(int a, int b) {return (a+b);}

#endif

My goal is to implement the next functions (which you can find their declarations and functionality in poly_subtype.h above):

Number& IntClass::addInt(IntClass& x);
Number& IntClass::addDouble(DoubleClass& x);
Number& IntClass::operator+(Number& x);
Number& DoubleClass::addInt(IntClass& x);
Number& DoubleClass::addDouble(DoubleClass& x);
Number& DoubleClass::operator+(Number& x);

I hope it's more clear now.

For example, AddInt:

Number& IntClass::addInt(IntClass& x){
 int num = add_int_int(my_number, x.get_number());
 IntClass* a = new IntClass(num);
 IntClass &ref = *a;
 return ref;
}

Solution

While you can do something like you wrote above, it is considered bad style. If a resource is allocated on the free-store you should return a pointer to it, not a reference. Even better, use a smart pointer of the appropriate kind: e.g. std::auto_pointer (or better std/boost::unique_ptr) if the resource is not held by the producer and std::shared_ptr if the opposite is the case. Your code example is legal, but the consumer of the returned reference does not (and cannot) know how to deal with the returned reference.

I can imagine returning a constant reference to an object in a scenario like this:

class Producer {
 std::shared_ptr<SomeObject> mObject;

public:
 Producer() : mObject(new SomeObject) {}

 const SomeObject& GetObject() const {
  return *mObject;
 }

};

You could however return a reference to an object with static duration, which has certain drawbacks though - you do not have (appropriate) control over the lifetime of the object, for example:

SomeObject& GetSomeObjectSingletonReference() {
 static SomeObject sInstance;
 return sInstance;
}

Cheers,

Paul



Answered By - Paul Michalik
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What changes to my code should I make so that my code would work?

 July 10, 2022     list, python, reference     No comments   

Issue

So I'm trying to implement a function ptt(L:List[int],k:int) that returns a nested list containing partitions of L where each element of the list is itself a list containing exactly k elements (except the last partition which may have fewer than k elements). For example, when L = [1,2,3,4,5,6,7] and k = 2, partition(L, k) returns [[1,2],[3,4],[5,6],[7]]. Here are a few more examples.

assert ptt([1,2,3],2) == [[1,2],[3]]
assert ptt([1,2,3],3) == [[1,2,3]]
assert ptt([1,2,3,4],1) == [[1],[2],[3],[4]]
assert ptt([1,2,3,4],2) == [[1,2],[3,4]]

Here is my attempt at the code...

def ptt(L, k):
    if (L == 0 or k == 0 or k > L):
        return 0
    if (k == 1 or k == L):
        return 1
    return (k * ptt(L - 1, k) +
                ptt(L - 1, k - 1))

However, this doesn't work at all... what changes to my code should I make to make sure it works??


Solution

This code is very different from your approach, but it produces the result you're looking for:

def partition(nums, k):
    result = []
    for i in range(0, len(nums), k):
        result.append(nums[i:i+k])
    return result


Answered By - Tyler Liu
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is __ext_vector_type__ and simd?

 July 10, 2022     c, c++, clang, reference, simd     No comments   

Issue

I'm playing with Apple Metal API along with so called simd library. There's such code in a header:

typedef __attribute__((__ext_vector_type__(3))) float vector_float3;

And I'm curious what it actually does and why the compiler doesn't allow references to vector_float3 in a function's argument or in the next manner:

vector_float3  v;
vector_float3& ref = v;

Solution

It appears to be a clang extension to GNU C vector extensions, where something like this would be normal:

typedef int v4si __attribute__ ((vector_size (16)));

Googling for ext_vector_type without the leading/trailing underscores found the Clang docs. (The underscores version is usable in headers even if some program had used #define on the non-underscores version of the token. But names with leading underscores in the global namespace are reserved for the implementation.)

My best guess is that it's a way to let the compiler know you only care about the value of the first 3 elements of a 4 element SIMD register. So it can potentially do optimizations that leave different garbage in the high element than the source would have.


why the compiler doesn't allow references to vector_float3

Works for me with clang3.8. Try a different compiler.

typedef __attribute__((__ext_vector_type__(3))) float vector_float3;

int foo(vector_float3 &arg) {
  vector_float3  v;
  vector_float3& ref = v;  // unused, but syntactically valid
  return arg[0];           // return the low element of the vector, converted to an integer.  GNU C vector-extensions syntax.
}

compiles to the following asm on the Godbolt compiler explorer

    # targeting x86-64 SystemV ABI (so the first integer/pointer arg is in rdi)
    cvttss2si       eax, dword ptr [rdi]
    ret


Answered By - Peter Cordes
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I mutate an enum and then return a reference to an enum variant?

 July 10, 2022     borrow-checker, enums, reference, rust     No comments   

Issue

I have an enum that can hold either an encoded type (i32) or a decoded type (String).

My goal is to write a function that converts the enum to the decoded state, and return a reference, but I can't do it: if I change the content of the enum first, I cannot return a reference.

enum Foo {
    A(i32),
    B(String),
}

use Foo::*;

impl Foo {
    fn get_string(&mut self) -> &str {
        match self {
            A(i) => {
                let s = i.to_string();
                *self = B(s);
                &s
            }
            B(string) => string,
        }
    }
}

I get

error[E0515]: cannot return value referencing local variable `s`
  --> src/lib.rs:10:9
   |
10 | /         match self {
11 | |             A(i) => {
12 | |                 let s = i.to_string();
13 | |                 *self = B(s);
14 | |                 &s
   | |                 -- `s` is borrowed here
15 | |             }
16 | |             B(string) => string,
17 | |         }
   | |_________^ returns a value referencing data owned by the current function

error[E0382]: borrow of moved value: `s`
  --> src/lib.rs:14:17
   |
12 |                 let s = i.to_string();
   |                     - move occurs because `s` has type `String`, which does not implement the `Copy` trait
13 |                 *self = B(s);
   |                           - value moved here
14 |                 &s
   |                 ^^ value borrowed here after move

Is what I want to do possible? If so, how can I do it?


Solution

The reference you return needs to point to the data inside Foo::B, not to your local variable s. It's easiest to do this in two steps – first do the conversion if necessary, then return the reference. After the first step it's guaranteed that *self is Foo::B, so we can mark the A branch in the match as unreachable!().

impl Foo {
    fn get_string(&mut self) -> &str {
        if let A(i) = *self {
            *self = B(i.to_string());
        }
        match *self {
            A(_) => unreachable!(),
            B(ref s) => s,
        }
    }
}

(Note that I changed pattern matching to not use "match ergonomics", since this tends to be less confusing.)



Answered By - Sven Marnach
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I get a mutable reference out of a vector?

 July 10, 2022     borrow-checker, reference, rust, self     No comments   

Issue

Both the run and send methods need a self object, and the send function also needs a mutable Packet reference:

struct Package {
    id: u32,
}

impl Package {
    fn new(id: u32) -> Package {
        Package { id }
    }
}

struct Manager {
    packages: Vec<Package>,
}

impl Manager {
    fn new() -> Manager {
        Manager {
            packages: vec![
                Package::new(1),
                Package::new(2),
                Package::new(3),
                Package::new(4),
            ],
        }
    }
    fn run(&mut self) {
        for package in self.packages.iter_mut() {
            if package.id == 1 {
                self.send(package);
            }
            println!("{}", package.id);
        }
    }
    fn send(&self, package: &mut Package) {
        package.id = 23;
    }
}

fn main() {
    let manager = Manager::new();
    manager.run();
}
error[E0502]: cannot borrow `*self` as immutable because it is also borrowed as mutable
  --> src/main.rs:29:17
   |
27 |         for package in self.packages.iter_mut() {
   |                        ------------------------
   |                        |
   |                        mutable borrow occurs here
   |                        mutable borrow later used here
28 |             if package.id == 1 {
29 |                 self.send(package);
   |                 ^^^^ immutable borrow occurs here

error[E0596]: cannot borrow `manager` as mutable, as it is not declared as mutable
  --> src/main.rs:41:5
   |
40 |     let manager = Manager::new();
   |         ------- help: consider changing this to be mutable: `mut manager`
41 |     manager.run();
   |     ^^^^^^^ cannot borrow as mutable

How I can refactor these two functions to get it working?

I don't want to copy the packet, since that would lead to lots of trouble with my original code.


Solution

Option 1: don't accept &self in send(). Just let it take the things from self that it needs, such as &mut Package and possibly other fields:

// call it with Self::send(package)
fn send(package: &mut Package) {
    package.id = 23;
}

Option 2: accept a package index instead of &mut Package:

fn run(&mut self) {
    for package_idx in 0..self.packages.len() {
        if self.packages[package_idx].id == 1 {
            self.send(package_idx);
        }
        println!("{}", self.packages[package_idx].id);
    }
}

fn send(&mut self, package_idx: usize) {
    self.packages[package_idx].id = 23;
}

Option 3: use interior mutability.

struct Manager {
    packages: Vec<RefCell<Package>>,
}

impl Manager {
    fn new() -> Manager { ... }

    fn run(&mut self) {
        for package in &self.packages {
            if package.borrow().id == 1 {
                self.send(package);
            }
            println!("{}", package.borrow().id);
        }
    }
    fn send(&self, package: &RefCell<Package>) {
        let package = package.borrow_mut();
        package.id = 23;
    }
}

Which option is right for you depends on your use case. All else being equal, I'd prefer option 1, then 2, then 3.



Answered By - user4815162342
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why use pointers and reference in codesys V3?

 July 10, 2022     automation, codesys, plc, pointers, reference     No comments   

Issue

My question is: what are the benefits of using pointers and reference to?

I am new to codesys and in my previous job, I programmed in TIA portal (Siemens) and Sysmac Studio (Omron) and never came across pointers or something similar. I think I understand how they work but not sure when I should be using them myself.

For example, I just received a function block from a supplier:

Example of FB with pointers and reference

Why don't they just have an array for input and output?


Solution

First of all, if you have ever used the VAR_IN_OUT declaration, then you have already used references, since that is equivalent to a VAR with REFERENCE TO.

As for the uses, there are mainly 4 that I can think of right now:

  1. Type Punning, which you can also achieve using a UNION, but you may not want to have to create a union for every single reinterpretation cast in your code.

  2. TL; DR: To save memory and copy execution time. Whenever you pass some data to a function/function block, it gets copied. This is not a big problem if your PLC has enough CPU power and memory, however if you are dealing with especially huge data on a low end PLC, then you may either exceed real time execution constraints, or run out of memory. When you pass a pointer/reference however, no matter how big the data is only the pointer/reference gets copied and passed, which is 4 bytes in 32 bit system, and 8 bytes in a 64 bit one.

  3. In C style languages you'd use pointers/references when you want a function to return multiple values without the hassle of creating a custom structure every time. You can do the same here to, however in CODESYS function can have multiple outputs, for example:

VAR_OUPUT
    out1 : INT; (*1st output variable *)
    out2 : INT; (*2nd output variable *)
    //...
END_VAR
  1. And finally, as I mentioned at the very beginning, when you want to pass some data that needs to be modified in the function itself, in other words, where you can use VAR_IN_OUT you can also use pointers/references. One Special case where you will have to use a pointer is if you have a Function Block that receives some data in the FB_Init (initialization/construction) function and stores it locally. In such case you would have a pointer as a local variable in the function block, and take the address of the variable in the FB_Init function. Same applies if you have a structure that needs to reference another structure or some data.

PS. There are probably some other uses I missed. One of the main uses in other languages is for dynamic memory allocations, but in CODESYS this is disabled by default and not all PLCs support it, and hardly anyone (that I know) uses it.

EDIT: Though this has been accepted, I want to bring a real life example of us using pointers:

Suppose we want to have a Function Block that calculates the moving average on a given number series. A simple approach would be something like this:

FUNCTION_BLOCK MyMovingAvg
VAR_INPUT
    nextNum: INT;
END_VAR
VAR_OUTPUT
    avg: REAL;
END_VAR
VAR
    window: ARRAY [0..50] OF INT;
    currentIndex: UINT;
END_VAR

However, this has the problem that the moving window size is static and predefined. If we wanted to have averages for different window sizes we would either have to create several function blocks for different window sizes, or do something like this:

FUNCTION_BLOCK MyMovingAvg
VAR CONSTANT
    maxWindowSize: UINT := 100;
END_VAR
VAR_INPUT
    nextNum: INT;
    windowSize: UINT (0..maxWindowSize);
END_VAR
VAR_OUTPUT
    avg: REAL;
END_VAR
VAR
    window: ARRAY [0..maxWindowSize] OF INT;
    currentIndex: UINT;
END_VAR

where we would only use the elements of the array from 0 to windowSize and the rest would be ignored. This however also has the problems that we can't use window sizes more than maxWindowSize and there's potentially a lot of wasted memory if maxWindowSize is set high.

There are 2 ways to get a truly general solution:

  1. Use dynamic allocations. However, as I mentioned previously, this isn't supported by all PLCs, is disabled by default, has drawbacks (you'll have to split you memory into two chunks), is hardly used and is not very CODESYS-like.
  2. Let the user define the array of whatever size they want and pass the array to our function block:
FUNCTION_BLOCK MyMovingAvg
VAR_INPUT
    nextNum: INT;
END_VAR
VAR_OUTPUT
    avg: REAL;
END_VAR
VAR
    windowPtr: POINTER TO INT;
    windowSize: DINT;
    currentIndex: UINT;
END_VAR
METHOD FB_Init: BOOL
VAR_INPUT
    bInitRetains: BOOL;
    bInCopyCode: BOOL;
END_VAR
VAR_IN_OUT // basically REFERENCE TO
    window_buffer: ARRAY [*] OF INT; // array of any size
END_VAR

THIS^.windowPtr := ADR(window_buffer);
THIS^.windowSize := UPPER_BOUND(window_buffer, 1) - LOWER_BOUND(window_buffer, 1) + 1;
// usage:
PROGRAM Main
VAR
    avgWindow: ARRAY [0..123] OF INT; // whatever size you want!
    movAvg: MyMovingAvg(window_buffer := avgWindow);
END_VAR

movAvg(nextNum := 5);
movAvg.avg;

The same principle can be applied to any function block that operates on arrays (for example, we also use it for sorting). Moreover, similarly you may want to have a function that works on any integer/floating number. For that you may use one of the ANY types which is basically a structure that holds a pointer to the first byte of the data, the size of the data (in bytes) and a type enum.



Answered By - Guiorgy
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] When does reference casting slice objects?

 July 10, 2022     c++, casting, object, reference     No comments   

Issue

Take a look at this piece of code:

#include <iostream>


class A{
public:
    int x;
    
    virtual void f(){std::cout << "A f\n";}
    
};

class B: public A
{
public:
    int y;
    
    void f() {std::cout << "B f\n";}
};



void fun( A & arg)
{
    std::cout << "fun A called" << std::endl;
    arg.f(); 
    // arg.y = 222; - this gives error, compiler's work?
    arg.x = 2223333;
}
void fun(B & arg){
    std::cout << "fun B called" << std::endl;
    arg.f();

}

int main()
{
    B b;
    b.y = 12;
    b.x = 32;

    fun(static_cast<A&>(b));
    
    std::cout << b.x << " " << b.y << std::endl;
    
    return 0;
}

What exactly happens when I reference cast b into A&? I'm guessing a reference to type A 'arg' is created in a funtion 'fun()' and now it's only compiler's work to differentiate types? Meaning no actual object was created and no slicing occurred and it's still the same object in memory, however compiler will treat it as type A? (meaning after function call I can safely use b as type B?)

I assumed that's true, because the vptr of the instance didn't change (arg of type A called B's virtual function override), but I'm not completely sure what's going on behind the scenes during reference casting.

Also, if I assign static_cast<A&>(b) to a new object of type A, I assume that's when the construction of a new object of type A and slicing occurres?


Solution

Yes, you seem to have got this. :-)

A B is also an A (by inheritance), so it can bind to either A& or B&. Nothing else happens, it is just a reference to the existing object.

The slicing happens if you assign a B object to an A object, like A a = b;, which will only copy the inherited A portion of b.



Answered By - BoP
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing