this.setState is undefined

I keep seeing answers that say to use => or .bind(this) but neither of those solutions worked.
import React, { Component } from 'react';
import { View, Text, TextInput, StyleSheet } from 'react-native';

export default class MyWeatherApp extends Component {
  constructor(props) {
  super(props);

  this.state = {};
}

getInitialState() {
  return {
    zip: '',
    forecast: null,
  };
}

_handleTextChange(event) {
  var zip = event.nativeEvent.text;
  this.setState({zip: zip});
}
----Answers------------
1.
When you extend React.Component with ES2015 class syntax you need to bind your action handlers to a context of your class.
Try this: onChange={e => _handleTextChange(e)}
Generally, it's better not to use arrow functions or bind methods inside render as it generates a new copy of the function on any render call. Move function declaration to the class constructor.
I personally prefer to use arrow functions as class properties in this case
class MyClass extends React.Component {

  handleClick = () => {
    // your logic
  };

  render() {
    return (
      <button onClick={this.handleClick}>Click me</button>
    );
  }
}
It's not a part of ES2015 specification but babel stage-0 preset supports this syntax
You can read more about context binding in React in this article
2.
i hope the below code may give you the idea
import React, { Component } from 'react';
import { View, Text, TextInput, StyleSheet } from 'react-native';

export default class MyWeatherApp extends Component {
  constructor(props) {
    super(props);
    this.state = {
      zip: '',
      forecast: null
    };
   }

_handleTextChange(event) {
  var zip = event.nativeEvent.text;
  this.setState({zip: zip});
}

render() {
return (
   <button onChange={e => _handleTextChange(e)}>Click me</button>
  );
 }
}
 

Designing Data structure for Firebase

------Question-------
Warning: My query would be more theoretical (sorry programmers, please bear with me). I am trying to get some idea on how to define the database structure for use in Firebase.
I am exploring the use of Firebase as a backend for a Review app (in Android) I am trying to build.
The app provides product details and review for products of different kinds. So here is an example use case.
  1. The products displayed in the app are of same type (say smartphones). In this use case, defining the database structure is easier. For every phone, I simply need to save the phone specs to Firebase and retrieve them into my app.
Root
 |
 +--Smartphone
     |
     +--Manufacturer Name
     +--Screen Size
     +--Screen Density
     +--Processor
     +--RAM,...
  1. The products displayed in the app are of different type (say smartphones, Car, Book,...). In this use case, defining the database structure becomes complex. I can simply define the data structure like
Root
 |
 +--Product
     |
     +--Manufacturer Name
     +--Screen Size
     +--Screen Density
     +--Processor
     +--RAM
     +--Fuel type (Petrol/Diesel/Electric)
     +--Vehicle Type (Sedan/Hatchback)
     +--Vehicle Price,...
However, the problem with above data structure is, when I am trying to make a product review for a smartphone, the data related to Car will remain blank. Same will be the case for a product review of a Car.
This problem can be solved by using Flattening the data structure. This is where I am confused.
Root
 |
 +--Smartphone
 |   |
 |   +--Manufacturer Name
 |   +--Screen Size
 |   +--Screen Density
 |   +--Processor
 |   +--RAM
 |
 +--Car
     |
     +--Fuel type (Petrol/Diesel/Electric)
     +--Vehicle Type (Sedan/Hatchback)
     +--Vehicle Price,...
However, all product reviews will be displayed in a single activity/fragment. Hence, there will not be different activities/fragments for every product type. Could someone provide me a clear picture of using flattened data structures in my use case?
----Answers----
1.
You can structure your database like this:
products: {
    smartphones: {
        smartphone1: {
            name: "Best Phone",
            ram: "6 GB",
            screen: "5.5 inch"
            reviews: {
                review1: true,
                review2: true
            }
        }
    },
    cars: {
        car1: {
            name: "Lightning"
            reviews: {
                review3: true,
                review4: true,
                review5: true
            }
        }
    }
},
product-review: {
    review1: {
        submittedBy: "Conqueror",
        message: "Best phone at this price",
        timestamp: 1472405901
    },
    review2: {
        submittedBy: "Magic Blaster",
        message: "Pros: RAM, Cons: Everything else."
        timestamp: 1472405901
    },
    review3: {
       submittedBy: "Boss",
       message: "Excellent Car",
       timestamp: 1472405901
    },
    ...
}
Every product(smartphone1, car1 etc..) contains a reviews node, so you can easily load the linked reviews of a particular product.
2.
Here is the flattest database structure that I can think of. For the products node, you can also use the third structure in your question, it will only affect the logic on how to map the item in your app.
products: {
    item1: {
        type: "smartphone",
        manufacturer_name: "some value",
        screen_size: "some value",
        screen_density: "some value",
        processor: "some value",
        ram: "some value"
    },
    item2: {
        type: "car",
        fuel_type: "some value",
        vehicle_type: "some value",
        vehicle_price: "some value"
    }
},
users: {
    user1: {
        name: "some value",
        email: "some value"
    },
    user2: {
        name: "some value",
        email: "some value"
    },
},
products_reviews: {
    item1: {
        user1: ewview1,
        user2: review2
    },
    item2: {
        user2: review3
    }
},
users_reviews: {
    user1: {
        item1: review1
    },
    user2: {
        item1: review2,
        item2: review3
    }
},
reviews: {
    review1: {
        text: "this is my review",
        timestamp: 1472488486000
    },
    review2: {
        text: "this is my review",
        timestamp: 1472488486000
    },
    review3: {
        text: "this is my review",
        timestamp: 1472488486000
    }
}
Now you should be able to retrieve all reviews from each user and also retrieve all reviews for each product.
Comment here if you have questions, hope this helps :)

Is it possible to access (read only) the variables captured by a lambda?

Is it possible to access (read only) the variables captured by a lambda?
This doesn't work:
std::function<double  (const double)> plus (const double a) {
    return [a] (const double b) -> double {
        return a+b;
    };
}

auto plus5 = plus(5);
cout << plus5.a << endl;
----Answers------
1. 
auto plus( double a ) {
  using R = struct {
    double a;
    double operator()(double b)const{return b+a;}
  };
  return R{a};
}
live example.
Please note that a std::function is not a lambda, and lambda is not a std::function. They work with each other, but using one term to refer to the other is the opposite of helpful.
2.
This is not how a lambda should be used.
The interface of a lambda is its function signature. Its captures should be considered an implementation detail and not be visible to the user.
If you want explicit access to the captures, write your own function object and expose the respective data members accordingly:
struct MyPlus {
    double a;
    MyPlus(double x) : a(x) {}
    double operator()(const double b)
    {
        return a+b;
    }
};

auto plus5 = MyPlus(5);
std::cout << plus5.a;
 3.
Well let's relieve Yakk's karma; here's a proof of concept of a C++14 solution which you definitely don't want to let loose in the wild:
auto magic = [a, b](auto &&... args) mutable -> decltype(auto) {
    return makeOverload(

        // Capture access boilerplate
        [&](cap_<0>) -> auto& { return a; },
        [&](cap_<1>) -> auto& { return b; },

        // Actual function
        [&](int p) {
            return "[" + std::to_string(a) + ", " + b + "](" + std::to_string(p) + ")";
        }

    )(std::forward<decltype(args)>(args)...);
};
makeOverload takes any number of functors and blends them into a single one. I borrowed the idea from this blog post, with help from the comment section to make it actually work.
The resulting functor is used to tag-dispatch between the cap<N> tags and the actual parameters of the function. Thus, calling magic(cap<0>) causes it to spit out the corresponding captured variable, that is a. The actual behaviour of the function is, of course, still accessible with a normal call to magic(123).
As a bonus, the outer lambda is mutable, and the capture accessors return by reference: you actually have read-write access to the captured variables!
You can observe and interact with this creature in its natural habitat on Coliru right here.
 

Running nasm program on ARM linux

Question

I am trying to teach myself assembly programming with NASM. However I only have a Chromebook with ARM processor. I have xubuntu running on it with crunton. However how can I setup a x86 emulation environment to get myself started? I also want to be able to use insight debugger.
Answers
1.
Try bochs or qemu.
If you're only on a chromebook probably without a lot of RAM, you probably just want to run a very minimal Linux system inside your emulated x86 environment. Not a full xubuntu GUI install inside the emulated x86 environment.
For learning x86, you should start with 32 or 64bit ASM, either for functions you call from C, or as a standalone program. (Either really standalone, where you don't link with the C standard runtime or library, and write your own _start in asm, and make your own system calls, or just write main in asm and end your program with a ret from main.)
bochs has a built-in debugger, but using it would be more appropriate for debugging the kernel, or boot-loader. IDK anything about the Insight debugger, but if it can remote-debug, running an ARM binary of it natively, connected to the target you want to debug, might make sense.
You could write x86 asm that you boot directly (instead of a Linux image), but then you'd only have BIOS calls available, and the CPU would start in 16bit real mode with segmented memory and all that crap that's basically useless to learn except for writing bootloaders.
2.
QEMU has a user mode emulation feature which can be used to run x86 Linux programs on ARM Linux, or any other combination of supported architectures.

Android studio add different size drawable and layout folder

how can i add those folders in my project in android studio
res/drawable-ldpi/
res/drawable-ldpi-v8/
res/drawable-ldpi-v11/
res/drawable-mdpi/
res/drawable-mdpi-v8/
res/drawable-mdpi-v11/
res/drawable-hdpi/
res/drawable-hdpi-v8/
res/drawable-hdpi-v11/
res/drawable-xhdpi/
res/drawable-xhdpi-v8/
res/drawable-xhdpi-v11/
res/drawable-xxhdpi/
res/drawable-xxhdpi-v8/
res/drawable-xxhdpi-v11/
res/layout-land
res/layout-small-port-v4
res/layout-sw600dp-v13
res/layout-w480dp-v13
res/layout-v11
res/layout-port
i just made new project and i cant see any folder of those in my project
this is image of my project folders
enter image description here
------Answers----
1.
you have to create new folder inside res folder
2.
In Android Studio, at the top right where you have your project structure and Android View is selected, choose "Project", and you will be able to see the full hierarchy of your project. From there you can achieve what you are trying to do.
3.
Since these are folders, you can always use Windows Explorer to add them.
In Android Studio, the Project Window is currently in the default Android View. If you want to see the physical directory structure, you need to change it to the Project View by clicking on the drop down menu at the top of the Project Window.
enter image description here
Now you can add folders any where you want similar to how you do in Windows Explorer.







Work around for re-rendering new state in react

      import React, {Component} from 'react';
      import Square from './components/board.js';

      const spaceArr = ()=> {
         const arr =[];
         for (var i=0; i<20; i++){
         arr.push(Math.floor(Math.random()*(400-0)));
         }
         return arr;
      };


      class App extends Component{

        constructor(){
          super();
          this.state={
            spaces: spaceArr(),
            array : new Array(400).fill(false)
          } ;
          var th = this;
          this.state.spaces.map(function(value){  
          th.state.array.splice(value, 1, true)});
            this.click= this.click.bind(this);
          }

          componentDidMount(){
            this.setState({array: this.state.array})
          }

          click(i, live) {  
            this.state.array[i]= !live;
            var array = this.state.array;
            this.setState({array: array}, function(){
             console.log(array[i]) 
          })
          }


         render(){

           var th = this;
          return (
             <div>
               <div className='backboard'>
               <div className='board'>
                 {this.state.array.map(function(live, index){

                   return <Square key={index} living={live} clicker=  
                     {th.click.bind(this, index, live)}/>
                   })

                  }
                </div>
             </div>
           </div>
           )
          }
         }

         export default App;
I am trying to figure out how to re-render the updated state change after setState. the click event is a handler that is passed to a child component. the updated array should re-render an updated rendering of child components.

-----Answers------

1. Try this.
 click(i, live) {  
      var array = this.state.array;
      array[i]=!live
      this.setState({array:array}, function(){
         console.log(this.state.array[i]) 
      })
  }
 2.
You shouldn't mutate this.state directly as mentioned in React docs. Use concat for getting a new array before setting the new state:
click(i, live) {  
  var newArray = this.state.array.concat();
  newArray[i]!=live
  this.setState({array: newArray}, function(){
     console.log(this.state.array[i]);
  })
}

3.

on your return it should be,
return (<Square key={index} living={live} 
  clicker= {th.click.bind(th, index, live)}/>
});
 

Resolving Promises Asynchronously in angularjs

My code:
$q(function (resolve) {
    var imageUploadResults = [];
    fileUploadService.uploadImage($scope.filesUpload, "/api/mailbox/uploadAttachFile", function (result) {
        console.log(result);
        imageUploadResults.push(result.LocalFilePath);
    });
    $scope.mail.Files = imageUploadResults;
    resolve($scope.mail);
}).then(function (mail) {
    console.log(mail);
    apiService.post("/api/mailbox/sendMail", mail, sendMailSucceed, sendMailFailed);
});
Expect:
I want to add value to mail.Files finish,then call apiService.post()
Actual:
But it execute apiService.post() with mail.Files value is [].
When apiService.post() execute finish mail.Files return value.length > 0.

------Answers-----

1.
Without knowing exactly which library you are actually using, it seems clear to me that fileUploadService.uploadImage() is asynchronous.
The function that you give as an argument is a callback and there is no guarantee that it would be executed "on time". In your case the path is added to imageUploadResults after the moment where you set $scope.mail.Files.
you should set $scope.mail.Files and call resolve in your callback function.
$q(function (resolve) {
    var imageUploadResults = [];
    fileUploadService.uploadImage($scope.filesUpload, "/api/mailbox/uploadAttachFile", function (result) {
        console.log(result);
        imageUploadResults.push(result.LocalFilePath);
        $scope.mail.Files = imageUploadResults;
        resolve($scope.mail);
    });
}).then(function (mail) {
    console.log(mail);
    apiService.post("/api/mailbox/sendMail", mail, sendMailSucceed, sendMailFailed);
});
2.
When you assigned $scope.mail.Files = imageUploadResults; and resolved resolve($scope.mail); there are no guarantee that fileUploadService.uploadImage finished request and saved imageUploadResults.push(result.LocalFilePath);
Possible solution is to add resolve($scope.mail); right after imageUploadResults.push(result.LocalFilePath); in function passed to fileUploadService.uploadImage
 

Popular Posts

Powered by Blogger.