Saturday, February 25, 2017

11. [Tutorial] How to Implement Android App with Node.js Server and MongoDB

Information
- I followed this tutorial: https://www.learn2crack.com/2014/04/android-login-registration-nodejs-server.html
- But that link is quite old (2014) and did not work right out of the box.
- I have updated the code so that it works in Feb 2017.
- The major problem is that you must now use HttpURLConnection as the other is now deprecated in his link.

Code
The following is the updated code for the RegisterActivity.java file.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package com.gerrycao.thething;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class RegisterActivity extends AppCompatActivity {

    EditText email, password;
    Button login, register;
    String emailtxt, passwordtxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        email = (EditText) findViewById(R.id.email);
        password = (EditText) findViewById(R.id.password);
        register = (Button) findViewById(R.id.registerbtn);
        login = (Button) findViewById(R.id.login);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent regactivity = new Intent(RegisterActivity.this, LoginActivity.class);
                startActivity(regactivity);
                finish();
            }
        });


        register.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                emailtxt = email.getText().toString();
                passwordtxt = password.getText().toString();

                try {
                    JSONObject json = new JSONObject();
                    json.put("email", emailtxt);
                    json.put("password", passwordtxt);

                    new AsyncHttpTask().execute(json);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    class AsyncHttpTask extends AsyncTask<JSONObject, Void, Integer> {

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected Integer doInBackground(JSONObject... params) {
            Integer result = 0;

            HttpURLConnection urlConn = null;

            JSONObject json = params[0];
            Log.d("postTask: JO", json.toString());
            try {
                URL url;

                // NOTE: When I tried localhost, 127.0.0.1, or 10.10.x.x, those did not work for me.
                // I had to use my exact IP address to do debugging/testing.
                String address = "http://192.168.0.3:8080/register";
                Log.d("sendPost", address);
                url = new URL(address);
                urlConn = (HttpURLConnection) url.openConnection();
                urlConn.setDoInput(true);
                urlConn.setDoOutput(true);
                urlConn.setUseCaches(false);
                urlConn.setRequestMethod("POST");
                urlConn.setChunkedStreamingMode(100);
                urlConn.setRequestProperty("Content-Type", "application/json");
                urlConn.connect();

                byte[] outputBytes = json.toString().getBytes("UTF-8");
                OutputStream os = urlConn.getOutputStream();
                os.write(outputBytes);

                os.close();

                result = urlConn.getResponseCode();

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (urlConn != null)
                    urlConn.disconnect();
            }
            return result;
        }
    }
}

More code snippets to come as I continue this app!

Contact
Please feel free to leave a comment or ask a question.

10. [Good Find] - How to Push Existing Code/Projects Into Brand New Repo on Bitbucket

Information
- Make the private or public repo on Bitbucket.
- Download SourceTree
- Follow the instructions on this link: https://confluence.atlassian.com/bitbucket/create-a-repository-for-your-existing-files-800695576.html

Screen
Do the exact steps in the screenshot below.

Thursday, February 23, 2017

9. [Tutorial] How to Perform a HTTP POST to upload an object as JSON to an online web server in React Native

Information
You will use the fetch networking API and is available in React Native by default.

The code highlighted in green will show you how to upload an object as a JSON file to an online web server using the fetch api. You will use the JSON.stringify(...) method to convert an object into a JSON.

During uploading, you will need to specify a PHP script on the server side to handle the POST request. The PHP script will take the JSON string you uploaded from the React Native side and save it as a JSON file (testFile.json) on your web server. The location where the testFile.json will be saved is the same location where your processjson.php file is located. You can change the location using relative path (ie. ../testFile.json will save the JSON file in the directory one up the current)

Here is my processjson.php file:
 <?php  
 $jsonString = file_get_contents("php://input");  
 $myFile = "testFile.json";  
 file_put_contents($myFile,$jsonString);  
 echo '{ "success": true }';  
 ?>  


Here is the React Native file. You can click a button or TouchableOpacity to trigger the uploading (POST request) of the JSON string:
 import React, {  
  AppRegistry,  
  Alert,  
  Component,  
  View,  
  Text,  
  AsyncStorage,  
  TouchableOpacity,  
  Navigator,  
  ScrollView,  
  Image,  
  Dimensions,  
  Animated,  
  PanResponder,  
  StatusBar,  
 } from 'react-native'  
   
 let {height, width} = Dimensions.get('window')  
   
 import Splash from './Splash'  
 import Element from './Element'  
   
 export default class App extends Component {  
  constructor(props){  
   super(props)  
   let appData = {  
    page1: {  
     type: 'View',  
     passProps: {style: {flex:1, backgroundColor: 'white'}},  
     children: [{  
      type: 'TouchableOpacity',  
      passProps: {onPress: ()=>this.navigate({pageName: 'page2', navFunction: 'push'}),   
 style: {flex:1, backgroundColor: '#6a6c94', alignItems: 'center', justifyContent: 'center',}},  
      children: {  
       type: 'Text',  
       passProps: {style: {color: 'white'}},  
       children: 'Navigate to Page 2'}  
      }, {  
      type: 'View',  
      passProps: {style: {flex:1, backgroundColor: '#dd4444', alignItems: 'center',   
 justifyContent: 'center',}},  
      children: {  
       type: 'Text',  
       passProps: {style: {color: 'white'}},  
       children: 'Page 1 Text'}  
      },  
     ],  
    },  
    page2: {  
     type: 'View',  
     passProps: {style: {flex:1, backgroundColor: 'white'}},  
     children: {  
      type: 'View',  
      passProps: {style: {flex:1, backgroundColor: '#6a6c94', alignItems: 'center',   
 justifyContent: 'center',}},  
      children: {  
       type: 'Text',  
       passProps: {style: {color: 'white'}},  
       children: 'Page2 first view'  
      }  
     }  
    },  
    page3: {  
     type: 'View',  
     passProps: {style: {flex:1, backgroundColor: 'white'}},  
     children: null,  
    },  
    page4: {  
     type: 'View',  
     passProps: {style: {flex:1, backgroundColor: 'white'}},  
     children: null,  
    },  
   }  
   let appDataString = JSON.stringify(appData, function(key, val) {  
   if (typeof val === 'function') {  
    return val + ''; // implicitly `toString` it  
   }  
   return val  
   })  
   appData = JSON.parse(appDataString)  
   this.state = {  
    splashScreen: true,  
    currentPage: 'page1',  
    isStructureMode: true,  
    structureFlexAnim: new Animated.Value(2),  
    styleFlexAnim: new Animated.Value(1),  
    isPlayMode: false,  
    dropZoneValues : null,  
    pan       : new Animated.ValueXY(),  
    appData: appData,  
   }  
   
   this.panResponder = PanResponder.create({  
     onStartShouldSetPanResponder  : () => true,  
     onPanResponderMove       : Animated.event([null,{  
       dx : this.state.pan.x,  
       dy : this.state.pan.y  
     }]),  
     onPanResponderRelease      : (e, gesture) => {  
       if(this.isDropZone(gesture)){  
        let appData = {...this.state.appData}  
        delete appData[e.dispatchMarker.slice(-5)]  
        this.setState({appData})  
       }  
       Animated.spring(  
         this.state.pan,  
         {toValue:{x:0,y:0}}  
       ).start()  
   
     }  
   })  
  }  
   
  export(){
   // replace the this.state.appData with  
   let str_json = JSON.stringify(this.state.appData)  
   
   // replace the URL with your PHP script to handle the JSON string you are uploading  
   fetch('http://gerrycao.com/drago/processjson.php', {  
    method: 'POST',  
    headers: {  
     'Accept': 'application/json',  
     'Content-Type': 'application/json',  
    },  
    body: str_json  
   }).then((response) =>  
    // you will get a response back after the POST  
    // you can execute anything you want after or do nothing  
   )  
  }  
   
   
  componentDidMount(){  
   setTimeout(()=>this.setState({  
    splashScreen: false  
   }), 2000)  
  }  
  render(){  
   if(this.state.splashScreen) {  
    // Load App here, and show Splash while we load the app.  
    return <Splash />  
   }  
   return (  
    <View style={{flex: 1, backgroundColor: '#404040'}}>  
     <StatusBar backgroundColor="black" />  
     <View style={{flexDirection: 'row', justifyContent:'flex-end', alignItems: 'center',   
 backgroundColor: '#212121'}}>  
      <TouchableOpacity onPress={this.export.bind(this)}>  
      <Image source={require('./img/upload.png')} style={{width: 50, height:50}}   
 resizeMode='contain'/>  
      </TouchableOpacity>  
   
      <TouchableOpacity onPress={this.downloadjson.bind(this)}>  
      <Image source={require('./img/download.png')} style={{width: 50, height:50}}   
 resizeMode='contain'/>  
      </TouchableOpacity>  
   
  {/*    <TouchableOpacity onPress={this.addobjecttoapp.bind(this)}>  
      <Text style={{color:'black'}}>Add Object to App</Text>  
      </TouchableOpacity>*/}  
     </View>  
   
   
     {/*<View style={{flex:1, backgroundColor: 'pink'}}>  
      <View style={{flex:1, backgroundColor: 'orange', alignItems: 'center',   
 justifyContent: 'center',}}>  
       <Text style={{color: 'blue'}}>Page2 first view</Text>  
      </View>  
     </View>*/}  
     <View style={{flex:1, flexDirection: 'row'}}>  
      <View style={{flex:2, flexDirection: 'column', marginRight: 12}}>  
       {/*<View style={{flex:65, borderLeftWidth: 18, borderColor: '#dd4444',   
 backgroundColor: '#514d4d', marginTop: 19, elevation: 25}}>  
        <ScrollView style={{marginTop: 4, marginBottom: 4}}>  
         {this.renderStyleElements()}  
        </ScrollView>  
       </View>*/}  
       <View style={{flex:65, borderLeftWidth: 18,   
 borderColor: this.state.isStructureMode?'#6a6c94':'#dd4444', backgroundColor: '#514d4d',   
 marginTop: 19, elevation: 12}}>  
        <ScrollView style={{marginTop: 4, marginBottom: 4}}>  
         { this.state.isStructureMode  
          ? this.renderViewElements()  
          : this.renderStyleElements()  
         }  
        </ScrollView>  
       </View>  
       <View style={{flex:12, marginTop: 8, marginBottom: 8,   
 flexDirection: 'row', elevation: 12}}>  
        <TouchableOpacity onPress={()=>{  
          if(this.state.isPlayMode) {  
           this.setState({isPlayMode: false})  
          } else {  
           this.setState({isPlayMode: true})  
          }  
         }}  
         style={{flex:1, borderLeftWidth: 18, borderColor: '#009688',   
 backgroundColor: '#514d4d', marginRight: 6, elevation: 12, alignItems: 'center', justifyContent: 'center'}}>  
         <Image source={this.state.isPlayMode?require('./img/icon_build.png'):require('./img/icon_preview.png')} style={{width: 80}} resizeMode='contain'/>  
        </TouchableOpacity>  
        <View onLayout={this.setDropZoneValues.bind(this)}  
         style={{flex:1, borderLeftWidth: 18, borderColor: '#009688',   
 backgroundColor: '#514d4d', elevation: 12, alignItems: 'center', justifyContent: 'center'}}>  
          <TouchableOpacity>  
           <Image source={require('./img/icon_delete.png')}   
 style={{width: 80}} resizeMode='contain'/>  
          </TouchableOpacity>  
        </View>  
       </View>  
       <View style={{flex:23, borderLeftWidth: 18, borderColor: '#6a6c94',   
 backgroundColor: '#514d4d', marginBottom: 12, justifyContent: 'center', elevation: 8}}>  
        <ScrollView contentContainerStyle={{margin: 8, flexDirection: 'row',   
 flexWrap: 'wrap'}} bounces={false}>  
         {this.renderPageThumbnails()}  
        </ScrollView>  
       </View>  
      </View>  
      <View style={{flex:3, marginTop: 12, marginBottom:6, width: (width*2)/3,   
 marginLeft: -24, marginRight: 36}}>  
       <Image style={{flex:1, width: (width*2)/3}} resizeMode='contain'   
 source={require('./img/phone_mockup.png')} >  
        <View style={{flex:1, margin: 70, marginTop: 139, marginBottom: 132}}>  
         <Navigator  
          ref='navigator'  
          initialRoute={{name: 'My First Scene', index: 0}}  
          renderScene={(route, navigator) =>  
           <Element {...this.state.appData[route.currentPage ||   
 this.state.currentPage]} navigator={navigator} route={route} />  
          }  
         />  
        </View>  
       </Image>  
      </View>  
     </View>  
   
     {/* --- Render bottom two buttons --- */}  
     <View style={{height: 44, flexDirection: 'row'}}>  
      <Animated.View style={{flex:this.state.structureFlexAnim}}>  
       <TouchableOpacity style={{flex:1}} onPress={()=>{  
         this.setState({isStructureMode: true})  
         Animated.timing( // Uses easing functions  
          this.state.structureFlexAnim, // The value to drive  
          {toValue: 2, duration: 200,} // Configuration  
         ).start()  
         Animated.timing( // Uses easing functions  
          this.state.styleFlexAnim, // The value to drive  
          {toValue: 1, duration: 200,} // Configuration  
         ).start()  
        }}>  
        <View style={{flex:1,   
 backgroundColor: this.state.isStructureMode?'#6a6c94':'#212121', alignItems: 'center',   
 justifyContent: 'center'}}>  
         <Text style={{color: 'white'}}>Structure</Text>  
        </View>  
       </TouchableOpacity>  
      </Animated.View>  
      <Animated.View style={{flex:this.state.styleFlexAnim}}>  
       <TouchableOpacity style={{flex:1}} onPress={()=>{  
         this.setState({isStructureMode: false})  
         Animated.timing( // Uses easing functions  
          this.state.styleFlexAnim, // The value to drive  
          {toValue: 2, duration: 200,} // Configuration  
         ).start()  
         Animated.timing( // Uses easing functions  
          this.state.structureFlexAnim, // The value to drive  
          {toValue: 1, duration: 200,} // Configuration  
         ).start()  
        }}>  
        <View style={{flex:1,   
 backgroundColor: this.state.isStructureMode?'#212121':'#dd4444', alignItems: 'center',   
 justifyContent: 'center'}}>  
         <Text style={{color: 'white'}}>Style</Text>  
        </View>  
       </TouchableOpacity>  
      </Animated.View>  
     </View>  
    </View>  
   )  
  }  
 }  
   
 AppRegistry.registerComponent('drago', () => App)  

8. [Tutorial] How to Add Modal or Pop Up in React Native Tutorial

Information
- I found and used this tutorial: https://github.com/brentvatne/react-native-modal
- The green texts are the code snippets you will need to make pop ups or modals work in React Native.

- You will need to import the Modal.
- You will need an openModal() method.
- You will need a closeModal() method.
- You will need isModalOpen state variable to keep track of the open and close state of the modal.
- You will need the CSS for modal, container2, and innerContainer to make the modal look nice.

Code
import React, {
Component,
  DatePickerAndroid,
  Easing,
  View,
  Image,
  Text,
  TextInput,
  StyleSheet,
  LayoutAnimation,
  Dimensions,
  ScrollView,
  TouchableOpacity,
  StatusBar,
  Modal,
  Slider,
  Platform,
  DatePickerIOS,
} from 'react-native'
import {Actions} from 'react-native-router-flux'
const Accordion = require('react-native-collapsible/Accordion')
let {width, height} = Dimensions.get('window')
import MapView from 'react-native-maps'

const SECTIONS = [
  { type: 'Date' },
  { type: 'Colour' },
  { type: 'Mesh' },
  { type: 'Twine' },
  { type: 'Submit' },
]

export default class AccordionPage extends Component {
  constructor(props, context){
    super(props, context)
    this.state = {
      sliderValue: 125,
      date: 'Date',
      month: 'Month',
      year: 'Year',
      colour: 'Colour',
      isModalOpen: false,
      isModalOpen2: false,
   animated: true,
   transparent: false,
      meshSize: 'Size',
      mestTwine: 'Twine',
      region: {
        latitude: 49.30080957108101,
        longitude: -123.1337930524565,
        latitudeDelta: 0.0461,
        longitudeDelta: 0.0210,
      },
      geoPosition: {
        coords:{
          latitude: 49.30080957108101,
          longitude: -123.1337930524565,
        }
      },
      isUsingCustomPosition: false,
    }
    this.watchID = null
  }
  renderDateHeader(){
    return <View style={styles.header}>
      <View style={{flex:1, flexDirection: 'row', alignItems: 'center'}}>
        <Image style={{width: 40, height: 40, marginLeft: 20 }} source={require('../img/ic_date_range_white.png')} resizeMode='contain'/>
        <View style={styles.rowTextContainer}>
          <Text style={styles.firstText}>Date ghost gear discovered</Text>
          <Text style={styles.secondText}>{this.state.date + ' ' + this.state.month + ' ' + this.state.year}</Text>
        </View>
      </View>
    </View>
  }
  renderColourHeader(){
    return <View style={styles.header}>
    <View style={{flex:1, flexDirection: 'row', alignItems: 'center'}}>
      <Image style={{width: 40, height: 40, marginLeft: 20 }} source={require('../img/ic_color_lens_white_24dp.png')} resizeMode='contain'/>
        <View style={styles.rowTextContainer}>
          <Text style={styles.firstText}>Colour</Text>
          <Text style={styles.secondText}>{this.state.colour}</Text>
        </View>
      </View>
    </View>
  }
  renderMeshHeader(){
     var modalBackgroundStyle = {
      backgroundColor: this.state.transparent ? 'rgba(0, 0, 0, 0.5)' : '#f5fcff',
    };
    var innerContainerTransparentStyle = this.state.transparent
      ? {backgroundColor: '#fff', padding: 20}
      : null;

    return <View style={styles.header}>
      <View style={{flex:1, flexDirection: 'row', alignItems: 'center'}}>

      <Image style={{width: 40, height: 40, marginLeft: 20 }} source={require('../img/ic_rounded_corner_white.png')} resizeMode='contain'/>
        <View style={[styles.rowTextContainer, {flex: 0}]}>
          <Text style={styles.firstText}>Mesh Size Measurement</Text>
          <Text style={styles.secondText}>{Math.round(this.state.sliderValue) + ' mm'}</Text>
        </View>
       <TouchableOpacity style={{marginLeft: 8, marginTop: 10}} onPress={() => this.openModal()}>
        <Image style={styles.question} source={require('../img/question.png')}/>
        </TouchableOpacity>
      </View>
<Modal visible={this.state.isModalOpen} onRequestClose={() => {this.closeModal()}}
style={styles.modal}
animated={this.state.animated}
transparent={this.state.transparent}>

 <View style={[styles.container2, modalBackgroundStyle]}>
  <View style={[styles.innerContainer, innerContainerTransparentStyle]}>
   <Image
   style={styles.icon}
   source={require('../img/mesh_size_instruction.png')}
   />
   <Text style={styles.titleText}>
   {'The Net Kit uses the standard net measurement of stretched mesh size to determine the net\'s mesh size. Start by selecting a selection of the net that looks undamaged.\n\nStretch a square of net by two of the knots so that the other two knots meet in the middle. If the meshes do not meet, try using the other two knots of the same mesh. If the knots still do not meet evenly, this section of the net is damaged and another section should be used.\n\nMeasure the distance between the inside of the knots, this is the mesh size. Callipers, a 30cm ruler or a measuring tape can be used to take this measurement.'}
   </Text>
   <TouchableOpacity onPress={() => this.closeModal()}>
    <Text
    style={styles.modalCloseText}>
    OKAY
    </Text>
   </TouchableOpacity>
  </View>
 </View>

</Modal>

    </View>
  }
  renderTwineHeader(){
    var modalBackgroundStyle = {
     backgroundColor: this.state.transparent ? 'rgba(0, 0, 0, 0.5)' : '#f5fcff',
   };
   var innerContainerTransparentStyle = this.state.transparent
     ? {backgroundColor: '#fff', padding: 20}
     : null;
    return <View style={styles.header}>
    <View style={{flex:1, flexDirection: 'row', alignItems: 'center'}}>
      <Image style={{width: 40, height: 40, marginLeft: 20 }} source={require('../img/ic_expand_more_white_24dp.png')} resizeMode='contain'/>
      <View style={[styles.rowTextContainer, {flex: 0}]}>
        <Text style={styles.firstText}>Confirm</Text>
      </View>
      <TouchableOpacity style={{marginLeft: 8, alignSelf: 'center'}} onPress={() => this.openModal2()}>
        <Image style={styles.question} source={require('../img/question.png')}/>
      </TouchableOpacity>
      <Modal visible={this.state.isModalOpen2} onRequestClose={() => {this.closeModal2()}}
      style={styles.modal}
      animated={this.state.animated}
      transparent={this.state.transparent}>

        <View style={[styles.container2, modalBackgroundStyle]}>
        <View style={[styles.innerContainer, innerContainerTransparentStyle]}>
        <Image
        style={styles.icon2}
        source={require('../img/ghostgearhunter.png')}
        />
        <TouchableOpacity onPress={() => this.closeModal2()}>
        <Text
        style={styles.modalCloseText}>
        OKAY
        </Text>
        </TouchableOpacity>
        </View>
        </View>

      </Modal>
    </View>
    </View>
  }
  renderSubmitHeader(){
    return <TouchableOpacity style={{height: 60, backgroundColor: '#FF4366', marginBottom: 20}} onPress = {() => this.submitAll()}>
    <View style={{flex:1, flexDirection: 'row', alignItems: 'center'}}>
      <View style={[styles.rowTextContainer, {alignItems: 'center'}]}>
        <Text style={[styles.firstText, {fontSize: 17}]}>SUBMIT</Text>
      </View>
      </View>
    </TouchableOpacity>
  }
  submitAll(){
    console.log('weed');
    var imguri = this.props.img
    var body = new FormData()
    var guid = 'id' + Math.random()
    body.append('picture',
    {
        uri:imguri.toString(),
        type: "image/jpeg",
        name: guid + ".jpeg"
    });

    var req = new XMLHttpRequest();

    req.onreadystatechange = (e) => {
        if(req.readyState !== 4){
            return;
        }
        if(req.status === 200){
            console.log(req.response);
        }else{
            console.log('f');
            console.log(req.responseText);
        }
    }
    req.open('POST', "https://radiant-springs-15984.herokuapp.com/cool");
    //req.open('POST', "https://ghostgearhunter.azurewebsites.net/parse/classes/file");

    req.setRequestHeader("X-Parse-Application-Id","3f945af2-d32f-47cb-aa03-da745c50880d");
    req.setRequestHeader("X-Parse-REST-API-Key", "undefined");

    req.send(body);
  }
  _renderHeader(section) {
    switch(section.type){
      case 'Date':
        return this.renderDateHeader()
      case 'Colour':
        return this.renderColourHeader()
      case 'Mesh':
        return this.renderMeshHeader()
      case 'Twine':
        return this.renderTwineHeader()
      case 'Submit':
        return this.renderSubmitHeader()
    }
  }
  _renderContent(section) {
    switch(section.type){
      case 'Date':
      return (
        <View style={styles.content}>
          { Platform.OS === 'android'
            ? <TouchableOpacity style={{flex:1, justifyContent: 'center', alignItems: 'center',}} onPress={async ()=>{
              try {
                const {action, year, month, day} = await DatePickerAndroid.open({
                  // Use `new Date()` for current date.
                  // May 25 2020. Month 0 is January.
                  date: new Date(2020, 4, 25)
                });
                if (action !== DatePickerAndroid.dismissedAction) {
                  // Selected year, month (0-11), day
                }
              } catch ({code, message}) {
                console.warn('Cannot open date picker', message);
              }
            }}>
              <Text>Open Date Picker</Text>
            </TouchableOpacity>
            : <View style={{flexDirection: 'row'}}>
              <DatePickerIOS mode="datetime" date={new Date()} timeZoneOffsetInMinutes={(-1) * (new Date()).getTimezoneOffset() / 60}/>
            </View>
          }
      </View>
      )
      case 'Colour':
      return (<View style={styles.colorButtonContainer}>
        <TouchableOpacity style={[styles.colorButton, {backgroundColor:'#c6c6c6'}]} onPress={ () => this.setState({colour: 'Grey'})} ><View style={styles.colorButtonView}><Text style={styles.textCenter}>Grey</Text></View></TouchableOpacity>
        <TouchableOpacity style={[styles.colorButton, {backgroundColor:'#ffe401'}]} onPress={ () => this.setState({colour: 'Yellow'})} ><View style={styles.colorButtonView}><Text style={styles.textCenter}>Yellow</Text></View></TouchableOpacity>
        <TouchableOpacity style={[styles.colorButton, {backgroundColor:'#d2232a'}]} onPress={ () => this.setState({colour: 'Red'})} ><View style={styles.colorButtonView}><Text style={styles.textCenter}>Red</Text></View></TouchableOpacity>
        <TouchableOpacity style={[styles.colorButton, {backgroundColor:'#dd8200'}]} onPress={ () => this.setState({colour: 'Orange'})} ><View style={styles.colorButtonView}><Text style={styles.textCenter}>Orange</Text></View></TouchableOpacity>
        <TouchableOpacity style={[styles.colorButton, {backgroundColor:'#317a35'}]} onPress={ () => this.setState({colour: 'Green'})} ><View style={styles.colorButtonView}><Text style={styles.textCenter}>Green</Text></View></TouchableOpacity>
        <TouchableOpacity style={[styles.colorButton, {backgroundColor:'#9b471e'}]} onPress={ () => this.setState({colour: 'Brown'})} ><View style={styles.colorButtonView}><Text style={styles.textCenter}>Brown</Text></View></TouchableOpacity>
        <TouchableOpacity style={[styles.colorButton, {backgroundColor:'#0084ce'}]} onPress={ () => this.setState({colour: 'Blue'})} ><View style={styles.colorButtonView}><Text style={styles.textCenter}>Blue</Text></View></TouchableOpacity>
        <TouchableOpacity style={[styles.colorButton, {backgroundColor:'#000'}]} onPress={ () => this.setState({colour: 'Black'})} ><View style={styles.colorButtonView} ><Text style={styles.textCenter}>Black</Text></View></TouchableOpacity>
      </View>)
      case 'Mesh':
        return (
          <View>
            <View style={{flexDirection: 'row', alignItems: 'center', height: 60}}>
              <View style={{flex: 1}}>
                <Text style={{fontSize: 11, marginLeft: 10, textAlign: 'center'}}>Mesh Size (mm)</Text>
              </View>
              <View style={{flex:2, marginHorizontal: 10}}>
                <Slider
                  value={this.state.sliderValue}
                  onValueChange={(sliderValue)=>this.setState({sliderValue})}
                  onSlidingComplete={(sliderValue)=>{}}
                  maximumValue={250}
                  minimumValue={0}
                />
              </View>
            </View>
            <View style={styles.fingerButtonContainer}>
              <TouchableOpacity style={styles.fingerButton} onPress = {() => this.setState({sliderValue: 20}) }><Image style={styles.fingerButtonImg} resizeMode='contain' source={require('../img/f0.png')}/></TouchableOpacity>
              <TouchableOpacity style={styles.fingerButton} onPress = {() => this.setState({sliderValue: 33})} ><Image style={styles.fingerButtonImg} resizeMode='contain' source={require('../img/f1.png')}/></TouchableOpacity>
              <TouchableOpacity style={styles.fingerButton} onPress = {() => this.setState({sliderValue: 50})}><Image style={styles.fingerButtonImg} resizeMode='contain' source={require('../img/f2.png')}/></TouchableOpacity>
              <TouchableOpacity style={styles.fingerButton} onPress = {() => this.setState({sliderValue: 65})}><Image style={styles.fingerButtonImg} resizeMode='contain' source={require('../img/f3.png')}/></TouchableOpacity>
              <TouchableOpacity style={styles.fingerButton} onPress = {() => this.setState({sliderValue: 85})}><Image style={styles.fingerButtonImg} resizeMode='contain' source={require('../img/f4.png')}/></TouchableOpacity>
              <TouchableOpacity style={styles.fingerButton} onPress = {() => this.setState({sliderValue: 110})}><Image style={styles.fingerButtonImg} resizeMode='contain' source={require('../img/f5.png')}/></TouchableOpacity>
              <TouchableOpacity style={styles.fingerButton} onPress = {() => this.setState({sliderValue: 145})}><Image style={styles.fingerButtonImg} resizeMode='contain' source={require('../img/f6.png')}/></TouchableOpacity>
              <TouchableOpacity style={styles.fingerButton} onPress = {() => this.setState({sliderValue: 198})}><Image style={styles.fingerButtonImg} resizeMode='contain' source={require('../img/f7.png')}/></TouchableOpacity>
              <TouchableOpacity style={styles.fingerButton} onPress = {() => this.setState({sliderValue: 240}) }><Image style={styles.fingerButtonImg} resizeMode='contain' source={require('../img/f8.png')}/></TouchableOpacity>
            </View>
          </View>
        )
      case 'Twine':
        return this.renderTwineHeader()
      case 'Submit':
        return this.renderSubmitHeader()
    }

  }

  componentWillMount(){
    navigator.geolocation.getCurrentPosition(
      geoPosition=>{
        this.setState({ geoPosition, region: {...this.state.region, latitude: geoPosition.coords.latitude, longitude: geoPosition.coords.longitude} })
      },
      error => console.log(error),
      {enableHighAccuracy: true, timeout: 20000},
    )
    navigator.geolocation.watchPosition(
      geoPosition=>{
        if(this.state.isUsingCustomPosition){
          this.setState({ geoPosition })
        } else {
          this.setState({ geoPosition, region: {...this.state.region, latitude: geoPosition.coords.latitude, longitude: geoPosition.coords.longitude} })
        }
      },
      error => console.log(error),
      {enableHighAccuracy: true, timeout: 20000},
    )
  }
  onRegionChange(region) {
    this.setState({ region, isUsingCustomPosition: true })
  }
  onCenter(){
    let geoPosition = this.state.geoPosition
    this.setState({ region: {...this.state.region, latitude: geoPosition.coords.latitude, longitude: geoPosition.coords.longitude, isUsingCustomPosition: false} })
  }
  takePhoto(){
    Actions.tab5()
  }
  openModal2() {
this.setState({isModalOpen2: true});

}
 openModal() {
  this.setState({isModalOpen: true});
 }

  closeModal() {
    this.setState({isModalOpen: false});
  }
  closeModal2() {
    this.setState({isModalOpen2: false});
  }
  render() {
    var imageStyle = [styles.image, {width: Dimensions.get('window').width/2, height: 150 , padding: 0, margin: 0}];

    return (

      <ScrollView style={styles.container} contentContainerStyle={{marginBottom: 100}}>
        <StatusBar backgroundColor='#393593' barStyle="light-content" translucent={false}/>
        <View style={{alignItems: 'center', backgroundColor: '#EEEEEE'}} elevation={8}>
          { this.props.img
            ? <Image source = {{uri : this.props.img}} style = {imageStyle} />
            : <View style={{paddingHorizontal:20, paddingVertical: 34, backgroundColor: '#EEEEEE', paddingBottom: 60}}>
              <Text style={styles.text}>
                Ghost Gear Hunters! Please take a minute and help us to identify the ghost gear by taking a photo of the discovered gear and answering some questions!
              </Text>
              <Text style={[styles.text, {marginTop: 20}]}>
                Your action matters, numerous marine lives will be saved because of you!
              </Text>
              <TouchableOpacity style={{position: 'absolute', right: width / 2 - 25, bottom: 0, padding: 4}} elevation={8} onPress = {this.takePhoto}>
                <Image style={{width: 50, height: 50}} source={require('../img/camera_red.png')}/>
              </TouchableOpacity>
            </View>
          }
          { this.props.img
            ? <TouchableOpacity style={{position: 'absolute', right:  width / 2 - 25, bottom: 0, padding: 4}} elevation={8} onPress = {this.takePhoto}>
                <Image style={{width: 50, height: 50}} source={require('../img/camera_red.png')}/>
              </TouchableOpacity>
            : null
          }
        </View>

        <MapView style={{height: 200}}
          region={this.state.region}
          onRegionChange={(region)=>this.onRegionChange(region)}>
          <MapView.Marker
            coordinate={{latitude: this.state.region.latitude, longitude: this.state.region.longitude}}
          />
          <MapView.Marker
            coordinate={{latitude: this.state.geoPosition.coords.latitude, longitude: this.state.geoPosition.coords.longitude}}
          />
          {/*<TouchableOpacity style={styles.centerButton} onPress={()=>this.onCenter()}>
            <Text>Center</Text>
          </TouchableOpacity>*/}
        </MapView>

        <Accordion
          sections={SECTIONS}
          initiallyActiveSection = {0}
          duration = {350}
          renderHeader={this._renderHeader.bind(this)}
          renderContent={this._renderContent.bind(this)}
        />
        <View style={{height: 100}}/>
      </ScrollView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    paddingTop: 64,
  },
  header: {
    height: 60,
    backgroundColor: '#6161c2',
    marginVertical: 1,
    elevation: 8,
  },
  content: {
    height: 60,
    flexDirection: 'row',
    backgroundColor: 'white',
  },
  rowTextContainer: {
    flex:1,
    justifyContent: 'center',
    alignItems: 'flex-start',
    marginLeft: 20,
  },
  firstText: {
    fontSize : 14,
    color : '#fff',
  },
  secondText: {
    fontSize : 14,
    color : '#c5c5c5',
  },
  centerButton:{
    position: 'absolute',
    bottom: 30,
    right: 30,
  },
  text:{
    color: '#7C7C7C',
    fontSize: 14,
  },
  colorButtonContainer:{
    height: 200,
    marginTop: 50,
    marginLeft: 8,
    flexWrap: 'wrap',
    flexDirection: 'row',
    justifyContent: 'flex-start',
  },
  colorButton:{
    width: width*0.235,
    height: 70,
    borderWidth: 1,
    borderColor: '#BBBCBC',
    margin: 1,
    justifyContent:'flex-end'
  },
  colorButtonView:{
    height:25,
    backgroundColor:'white'
  },
  textCenter:{
    textAlign:'center'
  },

  fingerButtonContainer: {
    marginLeft: 8,
    marginBottom: 8,
    flexWrap: 'wrap',
    flexDirection: 'row',
    justifyContent: 'flex-start',
  },
  question: {
    width: 25,
 height: 25,
  },
  modal: {
 width: width - 20,
 height: height - 20,
 },
  icon: {
    width: width-40,
    height: 225,
  },
  icon2: {
    width: width-70,
    height: height - 70,
  },
  modalCloseText: {
    fontSize: 15,
    marginRight: 10,
 marginTop: 10,
    textAlign: 'right',
    color: '#2196F3',
  },
  container2: {
    flex: 1,
    justifyContent: 'center',
    padding: 20,
 margin: 10,
  },
  innerContainer: {
    borderRadius: 10,
  },
  fingerButton: {
    width: width*0.315,
    height: 115,
    borderWidth: 1,
    borderColor: '#BBBCBC',
    margin: 1,
  },
  fingerButtonImg: {
    width: width*0.310,
    height: 114,
  },
})

7. [Tutorial] How to Make a Microsoft Chatbot and Link it with Microsoft LUIS Natural Language Processing Tutorial

Information
- I first did the Bot Connector tutorial: http://docs.botframework.com/connector/getstarted/
- And then I followed the C# Bot Builder tutorial: http://docs.botframework.com/sdkreference/csharp/

Code
- This is my MessagesController.cs file:
 using System;  
 using System.Linq;  
 using System.Net;  
 using System.Net.Http;  
 using System.Threading.Tasks;  
 using System.Web.Http;  
 using System.Web.Http.Description;  
 using Microsoft.Bot.Connector;  
 using Microsoft.Bot.Connector.Utilities;  
 using Newtonsoft.Json;  
 using Microsoft.Bot.Builder.Dialogs;  
 using Microsoft.Bot.Builder.Luis;  
 using System.Collections.Generic;  
 using Microsoft.Bot.Builder.FormFlow;  
 using Microsoft.Bot.Builder.FormFlow.Advanced;  
 using System.IO;  
 using Newtonsoft.Json.Linq;  
   
 namespace Bot_Application1  
 {  
   [BotAuthentication]  
   public class MessagesController : ApiController  
   {  
     static bool usingSandwichMode = false;  
   
     internal static IDialog<SandwichOrder> MakeRootDialog()  
     {  
       return Chain.From(() => FormDialog.FromForm(SandwichOrder.BuildForm));  
     }  
     public async Task<Message> Post([FromBody]Message message)  
     {  
       if (message.Type == "Message")  
       {  
                     // initiate making a sandwich chatbot  
         if (message.Text.ToLower().Contains("make a sandwich"))  
         {  
           return await Conversation.SendAsync(message, MakeRootDialog);  
         }  
   
         return await Conversation.SendAsync(message, () => new SimpleAlarmDialog());  
       }  
       else  
       {  
         return HandleSystemMessage(message);  
       }  
     }  
   
     private Message HandleSystemMessage(Message message)  
     {  
       if (message.Type == "Ping")  
       {  
         Message reply = message.CreateReplyMessage();  
         reply.Type = "Ping";  
         return reply;  
       }  
       else if (message.Type == "DeleteUserData")  
       {  
       }  
       else if (message.Type == "BotAddedToConversation")  
       {  
       }  
       else if (message.Type == "BotRemovedFromConversation")  
       {  
       }  
       else if (message.Type == "UserAddedToConversation")  
       {  
       }  
       else if (message.Type == "UserRemovedFromConversation")  
       {  
       }  
       else if (message.Type == "EndOfConversation")  
       {  
       }  
   
       return null;  
     }  
   }   
     
   [LuisModel("REPLACE_WITH_YOUR_LUIS_ID", "REPLACE_WITH_YOUR_LUIS_SECRET")]  
   [Serializable]  
   public class SimpleAlarmDialog : LuisDialog<object>  
   {  
     [LuisIntent("")]  
     public async Task None(IDialogContext context, LuisResult result)  
     {  
       string message = "![Avilynn](https:  
       message += "Hi! My name is Siri :) What can I help you with?\n";  
   
       await context.PostAsync(message);  
       context.Wait(MessageReceived);  
     }  
             
     [LuisIntent("ShowWifiPassword")]  
     public async Task ShowWifiPassword(IDialogContext context, LuisResult result)  
     {  
       string message = "Here you go! The wifi password for the happy network is 123456$";  
       await context.PostAsync(message);  
       context.Wait(MessageReceived);  
     }  
       
     public SimpleAlarmDialog(ILuisService service = null)  
       : base(service)  
     {  
     }      
   }  
   
   public enum SandwichOptions  
   {  
     BLT, BlackForestHam, BuffaloChicken, ChickenAndBaconRanchMelt, ColdCutCombo, MeatballMarinara,  
     OverRoastedChicken, RoastBeef,  
     [Terms(@"rotis\w* style chicken", MaxPhrase = 3)]  
     RotisserieStyleChicken, SpicyItalian, SteakAndCheese, SweetOnionTeriyaki, Tuna,  
     TurkeyBreast, Veggie  
   };  
   public enum LengthOptions { SixInch, FootLong };  
   public enum BreadOptions { NineGrainWheat, NineGrainHoneyOat, Italian, ItalianHerbsAndCheese, Flatbread };  
   public enum CheeseOptions { American, MontereyCheddar, Pepperjack };  
   public enum ToppingOptions  
   {  
     // This starts at 1 because 0 is the "no value" value  
     [Terms("except", "but", "not", "no", "all", "everything")]  
     Everything = 1,  
     Avocado, BananaPeppers, Cucumbers, GreenBellPeppers, Jalapenos,  
     Lettuce, Olives, Pickles, RedOnion, Spinach, Tomatoes  
   };  
   public enum SauceOptions  
   {  
     ChipotleSouthwest, HoneyMustard, LightMayonnaise, RegularMayonnaise,  
     Mustard, Oil, Pepper, Ranch, SweetOnion, Vinegar  
   };  
   [Serializable]  
   [Template(TemplateUsage.NotUnderstood, "I do not understand \"{0}\".", "Try again, I don't get \"{0}\".")]  
   [Template(TemplateUsage.EnumSelectOne, "What kind of {&} would you like on your sandwich? {||}", ChoiceStyle = ChoiceStyleOptions.PerLine)]  
   class SandwichOrder  
   {  
     [Prompt("What kind of {&} would you like? {||}")]  
     // [Prompt("What kind of {&} would you like? {||}", ChoiceFormat ="{1}")]  
     // [Prompt("What kind of {&} would you like?")]  
     public SandwichOptions? Sandwich;  
     [Prompt("What size of sandwich do you want? {||}")]  
     public LengthOptions? Length;  
     public BreadOptions? Bread;  
     // An optional annotation means that it is possible to not make a choice in the field.  
     [Optional]  
     public CheeseOptions? Cheese;  
     [Optional]  
     public List<ToppingOptions> Toppings  
     {  
       get { return _toppings; }  
       set  
       {  
         if (value.Contains(ToppingOptions.Everything))  
         {  
           _toppings = (from ToppingOptions topping in Enum.GetValues(typeof(ToppingOptions))  
                  where topping != ToppingOptions.Everything && !value.Contains(topping)  
                  select topping).ToList();  
         }  
         else  
         {  
           _toppings = value;  
         }  
       }  
     }  
     private List<ToppingOptions> _toppings;  
     [Optional]  
     public List<SauceOptions> Sauces;  
     [Optional]  
     [Template(TemplateUsage.NoPreference, "None")]  
     public string Specials;  
     public string DeliveryAddress;  
     [Optional]  
     public DateTime? DeliveryTime;  
     [Numeric(1, 5)]  
     [Optional]  
     [Describe("your experience today")]  
     public double? Rating;  
     public static IForm<SandwichOrder> BuildForm()  
     {  
       OnCompletionAsyncDelegate<SandwichOrder> processOrder = async (context, state) =>  
               {  
                 await context.PostAsync("We are currently processing your sandwich. We will message you the status.");  
               };  
       return new FormBuilder<SandwichOrder>()  
             .Message("Welcome to the sandwich order bot!")  
             .Field(nameof(Sandwich))  
             .Field(nameof(Length))  
             .Field(nameof(Bread))  
             .Field(nameof(Cheese))  
             .Field(nameof(Toppings))  
             .Message("For sandwich toppings you have selected {Toppings}.")  
             .Field(nameof(SandwichOrder.Sauces))  
             .Field(new FieldReflector<SandwichOrder>(nameof(Specials))  
               .SetType(null)  
               .SetActive((state) => state.Length == LengthOptions.FootLong)  
               .SetDefine(async (state, field) =>  
                 {  
                   field  
                     .AddDescription("cookie", "Free cookie")  
                     .AddTerms("cookie", "cookie", "free cookie")  
                     .AddDescription("drink", "Free large drink")  
                     .AddTerms("drink", "drink", "free drink");  
                   return true;  
                 }))  
             .Confirm(async (state) =>  
               {  
                 var cost = 0.0;  
                 switch (state.Length)  
                 {  
                   case LengthOptions.SixInch: cost = 5.0; break;  
                   case LengthOptions.FootLong: cost = 6.50; break;  
                 }  
                 return new PromptAttribute($"Total for your sandwich is ${cost:F2} is that ok?");  
               })  
             .Field(nameof(SandwichOrder.DeliveryAddress),  
               validate: async (state, response) =>  
               {  
                 var result = new ValidateResult { IsValid = true };  
                 var address = (response as string).Trim();  
                 if (address.Length > 0 && address[0] < '0' || address[0] > '9')  
                 {  
                   result.Feedback = "Address must start with a number.";  
                   result.IsValid = false;  
                 }  
                 return result;  
               })  
             .Field(nameof(SandwichOrder.DeliveryTime), "What time do you want your sandwich delivered? {||}")  
             .Confirm("Do you want to order your {Length} {Sandwich} on {Bread} {&Bread} with {[{Cheese} {Toppings} {Sauces}]} to be sent to {DeliveryAddress} {?at {DeliveryTime:t}}?")  
             .AddRemainingFields()  
             .Message("Thanks for ordering a sandwich!")  
             .OnCompletionAsync(processOrder)  
             .Build();  
     }  
   };  
 }  

Saturday, February 18, 2017

6. [Technical Interview] [Leetcode] - Minimum Path Sum

Key Points
- Any numbers not at the top row or left column of a int 2d array can be computed by taking the min of its top of left neighbour using this algorithmn from using dynamic programming: https://leetcode.com/discuss/17111/my-java-solution-using-dp-and-no-extra-space

Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.*;

public class HelloWorld{

    public static void main(String []args){
        int[][] multi = new int[][]{
          { 10, 10, 10},
          { 2, 2, 2},
          { 2, 2, 2},
        };
        System.out.println(minPathSum(multi));
    }
     
    public static int minPathSum(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        
        for (int i = 0; i < m; i++)
        {
            for (int j = 0; j < n; j++)
            {
                // this is our starting top left corner, no need to change number in place
                // set it back to what it was and we will never enter here again
                if (i == 0 && j == 0)
                {
                    grid[i][j] = grid[i][j];
                }
                // if we are looking at the top row of numbers, compute a new number
                // for the current grid[0][x] by adding the left neighbour grid[0][j - 1] with current
                // grid[0][x]
                else if (i == 0 && j != 0)
                {
                    grid[i][j] = grid[i][j] + grid[i][j - 1];
                }
                // if we are looking at the left column of numbers, compute a new number
                // for the current grid[x][0] by adding the top neighbour grid[i - 1][0] with current
                // grid[x][0]
                else if (i != 0 && j == 0)
                {
                    grid[i][j] = grid[i][j] + grid[i - 1][j];
                }
                // Else we are looking at the numbers not at the topmost row or leftmost column.
                // This means these numbers can be computer by adding the current grid[i][j] with the
                // minimum of its top grid[i][j - 1] or left grid[i - 1][j] neighbour.
                else
                {
                    grid[i][j] = grid[i][j] + Math.min(grid[i][j - 1], grid[i - 1][j]);
                }
            }
        }
        
        // finally after all the addition and modifying each number of the original grid
        // in place, the answer of the least sum for the path from top left corner to
        // bottom right corner will be at grid[m - 1][n - 1] and so return the sum as int
        return grid[m - 1][n - 1];
    }
}

5. [Technical Interview] [Leetcode] - Missing Number

Key Points
- Simply use XOR the numbers in the array with the indices in the array and you will get the missing number.

Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import java.util.*;

public class HelloWorld{

     public static void main(String []args){
         int[] nums = {0, 1, 2, 4, 5};
         
        System.out.println(missingNumber(nums));
     }
     
     public static int missingNumber(int[] nums)
     {
         int xor = 0, i = 0;
         for (i = 0; i < nums.length; i++)
         {
             xor = xor ^ i ^ nums[i];
         }
         
         return xor ^ i;
     }
}

11. [Tutorial] How to Implement Android App with Node.js Server and MongoDB

Information - I followed this tutorial:  https://www.learn2crack.com/2014/04/android-login-registration-nodejs-server.html - But that link...