Undefined Method Add_To_Base

Undefined method add_to_base

add_to_base method was removed from rails 3. You should use errors[:base] << "error" instead.

Undefined index: google_analytics_json_key symfony 4

You are mixing services.yml with config.yml.
Check here carefully:

https://github.com/mediafigaro/google-analytics-api-symfony#configuration

google_analytics_api:
google_analytics_json_key: "%google_analytics_json_key%"

This part should be in config.yml, not services.yml (/app/config/config.yml)

"%google_analytics_json_key%" denotes a parameter you defined under parameters key, which can also be in your config.yml.

Try pasting this in newly created file config/packages/google_analytics_api.yaml

google_analytics_api:
google_analytics_json_key: "../data/analytics/client_secret.json"

Using inheritance in PHP to add data to array from multiple subclasses

When you extend the class and define the new property you are overriding the values set in the parent class. I would wind up removing the $meta_data array from all but Base. Then in your extending classes create a function similar to:

After solving it in a very simple way I wound up deciding I would go with something like the following in Base:

protected function addToMetaData(array $meta_data) {
$this->meta_data = array_merge($this->meta_data, $meta_data);
}

Then in your extending class constructors you just pass in an array of the values you want to add to Base::$meta_data.

2 ways to change a javascript object's prototype, what's the difference between them?

Imho the modern way to do related things is class and related keywords.

The two options you suggest produce different outcomes. See classical inheritance with Object.create. You are missing both the call to the super constructor and the reassignment of prototype.constructor to the proper value (which is also missing in the other case).

When doing inheritance with Object.create as described in the link, one difference compared to assigning new Base() is where the properties can be found:

function Base() { this.baseProp = "baseProp"; }function Sub() { this.subProp = "subProp"; }
Sub.prototype = new Base();Sub.prototype.constructor = Sub;
let obj = new Sub();console.log("obj.baseProp: " + obj.baseProp);console.log("Has baseProp on itself: " + obj.hasOwnProperty("baseProp"));

Can javascript calculate percentage?

JavaScript:

$(function() {
var rows = $(".row");
rows.each(function(index, row) {
var amount = parseFloat($(row).children(".amount").text());
var gst = parseFloat($(row).children(".gst").text());
var customTax = parseFloat($(row).children(".customTax ").text());
var tax = (isNaN(gst) ? (!isNaN(customTax) ? customTax : 0) : gst);
var totalSpan = $(row).children(".total");
console.log("Amount: ", amount);
console.log("Tax: ", tax);
totalSpan.html("Total: " + (amount + amount * (isNaN(tax) ? 0 : tax) / 100).toFixed(2));
});
});​

HTML:

<span id="row_1" class="row">
<span class="amount">123.45</span>
<span class="gst"></span>
<span class="customTax"></span>
<span class="total"><!-- # --></span>
</span>​

I have also posted this as a jsfiddle: http://jsfiddle.net/FHMrW/1/

Note: I have replaced the ids with class attributes, to support multiple rows.

EDIT: Included the code here, as per comment from @t-j-crowder, and added toFixed on total.

How can I set an HTML5 canvas ImageData from an XMLHttpRequest response?

Loading images via XMLHttpRequest

Image files are not pixel arrays

The data you get is not a pixel array it is image data. You can read the data directly and decode it but that is a lot of work, png has many different internal formats and compression methods. And why bother when all the code to do that is already available within the browser.

Normally I would I leave it up to the browser to do all the fetching but because there are no progress events on images and games can need a lot of image data I created this to handle the problem of loading with a meaningful progress display. It does the same as you are trying to do.

Once you have the data loaded you need to get the browser to decode it for you. To do that you need to convert the data you have to a DataURL. I do that in the function arrayToImage which converts the typed array to a data url with the appropriate image header.

Then it is just a matter of creating an image and setting the source to the data URL. It is rather ugly as it requires you to create the data buffer, then the url string, then the browser makes another copy to finally get the image. (way too much memory used) If you want it as an imageData array you need to render the image to a canvas and grab the data from there.

Example image loading with (real) progress events

Below is the code, it will fail if the image does not allow cross site access, and its only benefit is that you get progress events, which is included in the snippet.

// creates an image from a binary array// buf   : is the image as an arrayBuffer// type  : is the mime image type "png", "jpg", etc...// returns a promise that has the imagefunction arrayToImage(buf, type) {    // define variables    var url, chars, bWord, i, data, len, count, stream, wordMask, imagePromise;    // define functions    imagePromise = function (resolve, reject) { // function promises to return an image        var image = new Image(); // create an image        image.onload = function () { // it has loaded            resolve(image); // fore fill the promise        }        image.onerror = function () { // something rotten has happened            reject(image); // crossing the fingers        }        image.src = url; // use the created data64URL to ceate the image    }
wordMask = 0b111111; // mask for word base 64 word stream = 0; // to hold incoming bits; count = 0; // number of bits in stream; // 64 characters used to encode the 64 values of the base64 word chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
data = new Uint8Array(buf); // convert to byte array len = data.byteLength; // get the length; url = 'data:image/' + type.toLowerCase() + ';base64,'; // String to hold the image URL
// get each byte and put it on the bit stream for (i = 0; i < len; i++) { stream |= data[i]; // add byte to bit stream count += 8; // add the number of bits added to stream if (count === 12) { // if there are two 6bit words on the stream url += chars[(stream >> 6) & wordMask] + chars[stream & wordMask]; // encode both words and add to base 64 string stream = 0; // stream is empty now so just zero count = 0; // no bits on the stream } else { url += chars[(stream >> (count - 6)) & wordMask]; // encode top 6 bits and add to base64 string count -= 6; //decrease the bit count by the 6 removed bits stream <<= 8; // make room for next 8 bits } } if (count > 0) { // there could be 2 or 4 remaining bits url += chars[(stream >> (count + 2)) & wordMask]; // shift them back to B64 word size and encode } // data url constructed for image so lets promise to create it return new Promise(imagePromise); // return the promise}// loads an image via ajax providing progress data// WARNING cross domain images will fail if they have a CORS header prohibiting your domain from access// filename : url of the image file// progress : progress call back. This is called on progress events// returns a promise of an imagevar loadImage = function(filename,progress){ // declare variables var imagePromise; // declare functions imagePromise = function(resolve, reject){ // promise an image // decalare vars; var ajax, image, load, failed; // decalare functions failed = function (reason) { reject("Shit happens"); } // pass on the bad news load = function (e) { // handle load event // declare vars var type, loaded; // decalare functions loaded = function (image) { resolve(image);} // resolve the promise of an image
if(e.currentTarget.status !== 200){ // anything but OK reject the promise and say sorry reject("Bummer dude! Web says '"+e.currentTarget.status+"'"); }else{ type = filename.split(".").pop(); // ok we have the image as a binary get the type // now convert it to an image arrayToImage(e.currentTarget.response,type) // return a promise .then(loaded) // all good resolve the promise we made .catch(failed); // failed could be a bug in the soup. } }; ajax = new XMLHttpRequest(); // create the thingy that does the thing ajax.overrideMimeType('text/plain; charset=x-user-defined'); // no not an image. ajax.responseType = 'arraybuffer'; // we want it as an arraybuffer to save space and time ajax.onload = load; // set the load function ajax.onerror = failed; // on error ajax.onprogress = progress; // set the progress callback ajax.open('GET', filename, true); // point to the image url ajax.send(); // command the broswer to wrangle this image from the server gods } return new Promise(imagePromise);}

// the progress display. Something that looks profesional but still hates the status quo.var displayProgress = function(event){ // event is the progress event // decalre vars var w,h,x,y,p,str; w = ctx.canvas.width; // get the canvas size h = ctx.canvas.height; x = w/2-w/4; // locate the progress bar w /= 2; // make it in the center y = h/2-10; if(event.lengthComputable){ // does the progress know whats coming p = event.loaded/event.total; // yes so get the fraction found str = Math.floor(p*100)+"%"; // make it text for the blind }else{ p = event.loaded/1024; // dont know how much is comine so get number killobytes str = Math.floor(p) + "k"; // for the gods p /= 50; // show it in blocks of 50k }
ctx.strokeStyle = "white"; // draw the prgress bar in black and white ctx.fillStyle = "black"; ctx.lineWidth = 2; // give it go fast lines ctx.beginPath(); ctx.rect(x,y,w,20); // set up the draw ctx.fill(); // fill ctx.stroke(); // then stroke
ctx.fillStyle = "white"; // draw text in white ctx.font = "16px verdana"; // set the font ctx.textAlign = "center"; // centre it ctx.textBaseline = "middle"; // in the middle please ctx.fillText(str,x+w/2,y+10); // draw the text in the center
ctx.globalCompositeOperation = "difference"; // so the text is inverted when bar ontop ctx.beginPath(); ctx.fillRect(x+3,y+3,(p*(w-6))%w,14); // draw the bar, make sure it cycles if we dont know what coming
ctx.globalCompositeOperation = "source-over"; // resore the comp state}var canvas = document.createElement("canvas");canvas.width = window.innerWidth;canvas.height = window.innerHeight;document.body.appendChild(canvas);ctx = canvas.getContext("2d");
// The image name. var imageName = "https://upload.wikimedia.org/wikipedia/commons/thumb/c/cb/Broadway_tower_edit.jpg/800px-Broadway_tower_edit.jpg"; // lets load the image and see if all this actualy works. loadImage(imageName, displayProgress) .then(function (image) { // well what do you know it works ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height); // draw the image on the canvas to prove it }) .catch(function (reason) { console.log(reason); // did not load, that sucks! })

C++ object polymorphism issue

Consider the following:

struct Base {
int a;
};

struct Derived1 : public Base {
int d1Data[100];
};

struct Derived2 : public Base {
char d2Data[1500];
};

Now if we do the following:

Entity* e = new Entity;
Derived1* d1 = new Derived1;
Derived2* d2 = new Derived2;

std::cout << sizeof(*e) << ", " << sizeof(*d1) << ", " << sizeof(*d2) << '\n';

What will the output be? Hint: The numbers are not going to be the same.

So now what happens in each of the following cases?

*e = *(Entity*)d1;
*(Derived1*)e = *d1;
*(Derived2*)d1 = *d2;
*(Entity*)d1 = *(Entity*)(d2);
*(Derived1*)d2 = *d1;

None of these cases is particularly good. Your post makes it sound like you are setting yourself up for a bad case of object slicing.

DO NOT DO.

On the other hand, if what you are looking to do is to clone objects from a list:

std::vector<Base*> entities;
std::vector<Base*> copies;

entities.push_back(new Derived1);
entities.push_Back(new Derived2);

for (size_t i = 0; i < entities.size(); ++i) {
Base* clone = make_a_copy_of(entities[i]);
}

then the way to do this is to add a member function to Base.

struct Base {
int a;
virtual Base* clone() const = 0;
};

struct Derived1 : public Base {
int d1Data[100];
Base* clone() const override {
return new Derived1(*this);
}
};

struct Derived2 : public Base {
char d2Data[1500];
Base* clone() const override {
return new Derived2(*this);
}
};

int main() {
std::vector<Base*> entities;
std::vector<Base*> copies;

entities.push_back(new Derived1);
entities.push_Back(new Derived2);

for (size_t i = 0; i < entities.size(); ++i) {
Base* clone = entities[i]->clone();
}

// remember to delete all the objects we allocated,
// or wrap them with std::unique_ptr

return 0;
}

I will probably be scowled at for using raw pointers like this without using something like std::unique_ptr to ensure the objects have a lifetime, so here is a complete version using unique_ptr. I'm not using make_unique because neither my GCC (4.8.2) or MSVC appear to support it.

#include <iostream>
#include <vector>
#include <memory>

struct Base {
int m_a;
Base(int a) : m_a(a) {}
virtual ~Base() { std::cout << "Dtoring " << m_a << '\n'; }

virtual std::unique_ptr<Base> clone() const = 0;
};

struct Derived1 : public Base {
int d1Data[100];

Derived1(int a) : Base(a) {}
virtual ~Derived1() { std::cout << "D1 at " << (void*)this << " dtord\n"; }

std::unique_ptr<Base> clone() const override { return std::unique_ptr<Derived1>(new Derived1 (*this)); }
};

struct Derived2 : public Base {
char d2Data[10000];

Derived2(int a) : Base(a) {}
virtual ~Derived2() { std::cout << "D1 at " << (void*)this << " dtord\n"; }

std::unique_ptr<Base> clone() const override { return std::unique_ptr<Derived2>(new Derived2 (*this)); }
};

int main()
{
std::vector<std::unique_ptr<Base>> entities;
{
std::vector<std::unique_ptr<Base>> copies;

entities.emplace_back(new Derived1 (3));
entities.emplace_back(new Derived2 (5));

for (auto& ent : entities) {
copies.emplace_back(ent->clone());
}

std::cout << "copies going out of scope\n";
}

std::cout << "entities going out of scope\n";

return 0;
}

Live demo: http://ideone.com/lrgJun

---- EDIT ----

When you inherit a class, you also inherit it's data members into your overall structure. In this example, the effective structure of Derived1 is:

struct Derived1 {
int a; // from Base
int d1Data[100];
};

My implementation of clone is quietly relying on the copy constructor which is essentially doing a memory copy of src to dest, the equivalent of memcpy(this, src, sizeof(*this));. Because of this you don't need to chain calls to clone or anything like that, the magic is done in the copy constructor.

If you need to add instances of Base into your mix, we can implement the clone member in Base - but bear in mind that any "special" members you add to Base are going to be inherited in all the derived classes too.

I'll convolute the classes a little and show you what the copy constructors for Base and Derived1 effectively look like:

struct Base {
int m_int;
double m_double;
std::string m_name;
private:
unsigned int m_baseOnly;
...
};

struct Derived1 : public Base {
// inherited m_int, m_double and m_name
// also inherited m_baseOnly, we just can't access it.
std::array<int, 100> m_data;
std::string m_title;
std::shared_ptr<Base> m_buddy;
...
};

At this point, the actual in-memory structure of a Derived1 looks like this:

Derived1 {
int m_int;
double m_double;
std::string m_name;
unsigned int m_baseOnly;
std::array<int, 100> m_data;
std::string m_title;
std::shared_ptr<Base> m_buddy;
};

Given these definitions, unless we implement our own copy constructor or disable copy construction, this is effectively what the compiler will generate for us:

Base::Base(const Base& rhs) // Base copy constructor
: m_int(rhs.m_int)
, m_double(rhs.m_double)
, m_name(rhs.m_name)
, m_baseOnly(rhs.m_baseOnly)
{
}

Derived1::Derived1(const Derived1& rhs)
: Base(rhs) // copy-construct the Base portion
, m_data(rhs.m_data) // hence why I used std::array
, m_title(rhs.m_title)
, m_buddy(rhs.m_buddy)
{
}

My implementation of clone for Derived1

std::unique_ptr<Base> clone() const override
{
return std::unique_ptr<Derived1>(new Derived1 (*this));
}

or

std::unique_ptr<Base> clone() const override
{
const Derived1& rhs = *this; // Reference to current object.
Derived1* newClone = new Derived1(rhs);
return std::unique_ptr<Derived1>(newClone);
}

which is creating a new Derived1, invoking the new, empty, clone's copy-ctor with the current object as rhs and filling out the clone.



Related Topics



Leave a reply



Submit