Commit 9217074a authored by Thumula Rajapakse's avatar Thumula Rajapakse

Merge branch 'IT18030068' into 'master'

It18030068_Final_Merge

See merge request !1
parents f8266cee 29727127
{
"cells": [],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
This diff is collapsed.
Weater_Status,Wind_Speed,Average_Speed,Distance,Delay_time
Mostly_cloudy,3.22,54,84.437,-1
Mostly_cloudy,3.0107,60,120.737,4
Drizzle,8.05,25,6.873,9.32
partialy_cloudy,3.22,53,96.081,7.32
partialy_cloudy,2.9785,25,1.9,6.4
Sunny,3.22,60,109.446,-1
Mostly_cloudy,0,42,8.676,3.56
Sunny,3.1717,52,73.827,-0.3
Sunny,8.05,57,96.081,-0.05
partialy_cloudy,3.22,49,90.239,11.55
Sunny,4.6529,28,3.668,2.36
partialy_cloudy,5.6833,55,105.537,8.14
Sunny,7.6153,32,6.873,-0.23
Rainy,3.4615,51,109.446,14.52
Mostly_cloudy,9.4024,43,15.546,3.55
Drizzle,9.2414,45,73.827,5.5
Rainy,3.9767,47,90.239,15
partialy_cloudy,4.83,38,27.538,6.36
Sunny,9.2092,35,6.873,-0.56
Rainy,2.2379,52,114.851,15.58
Rainy,0.483,47,84.437,13.57
partialy_cloudy,4.9588,54,114.851,12.4
partialy_cloudy,0.483,41,37.478,6.53
Mostly_cloudy,0,46,22.522,2.69
Rainy,0,23,3.668,8.54
partialy_cloudy,3.1073,46,73.827,8.36
partialy_cloudy,1.6905,26,1.9,7.7
partialy_cloudy,0,52,109.446,8.49
partialy_cloudy,4.7978,40,37.478,7.35
Mostly_cloudy,0,33,6.873,3.48
partialy_cloudy,0,25,1.9,6.2
Mostly_cloudy,3.0268,29,6.873,0
partialy_cloudy,0,40,22.522,4.54
Mostly_cloudy,0,42,50.27,4.16
Drizzle,3.1556,52,109.446,9.55
partialy_cloudy,7.9695,37,22.522,3.57
Mostly_cloudy,3.381,30,6.873,0
Sunny,7.2933,45,8.676,3.36
partialy_cloudy,3.4293,31,6.873,0.55
Mostly_cloudy,2.9141,50,73.827,3.44
partialy_cloudy,1.7066,27,1.9,6.31
Rainy,4.0894,51,114.851,15.3
Sunny,7.6475,48,37.478,-0.2
Mostly_cloudy,9.7566,51,73.827,2.1
Mostly_cloudy,9.177,49,27.538,2.2
Rainy,9.1126,48,90.239,14.52
Drizzle,7.4543,24,1.9,8.4
Sunny,8.4203,56,101.069,2.15
partialy_cloudy,2.9302,27,6.873,8.52
Drizzle,5.0071,56,114.851,10
partialy_cloudy,14.007,50,90.239,8.25
partialy_cloudy,15.6331,40,50.27,4.4
Drizzle,16.5991,49,90.239,7.15
Sunny,16.5991,53,84.437,-0.25
partialy_cloudy,13.7333,58,114.851,4.45
partialy_cloudy,12.1555,50,84.437,6.05
Rainy,9.4507,43,73.827,14.33
Mostly_cloudy,9.3219,55,96.081,2.24
Rainy,10.3523,37,15.546,5.56
Rainy,10.9641,52,114.851,13.3
Drizzle,13.9587,36,27.538,5.3
Drizzle,13.7333,25,3.668,7.22
Rainy,12.4614,22,1.9,8.51
Rainy,12.397,50,109.446,9.52
partialy_cloudy,12.0106,55,105.537,7.2
partialy_cloudy,14.0231,40,37.478,5.15
Mostly_cloudy,12.1877,40,15.546,3.48
Sunny,11.7691,53,90.239,2.12
partialy_cloudy,12.3487,50,84.437,6.55
Rainy,9.4185,50,96.081,12.15
Mostly_cloudy,4.7495,52,90.239,0.5
Drizzle,9.66,26,1.9,7
Mostly_cloudy,6.5044,62,120.737,-1
partialy_cloudy,6.2307,49,96.081,6
Rainy,0.3703,45,73.827,11.55
Mostly_cloudy,0,61,120.737,3.2
Mostly_cloudy,2.0769,45,37.478,3.3
Rainy,0.3703,35,27.538,10.5
Rainy,0,26,6.873,9.43
Mostly_cloudy,3.0268,46,37.478,3.16
Rainy,0.3703,44,73.827,11.4
Drizzle,8.05,55,120.737,8.48
Rainy,4.9749,36,27.538,14.3
partialy_cloudy,4.7173,50,90.239,4.25
partialy_cloudy,4.8944,35,8.676,7.59
Mostly_cloudy,7.1162,41,22.522,0.8
Mostly_cloudy,9.3702,51,90.239,-0.1
Rainy,8.6618,30,8.676,9.34
Drizzle,8.7745,26,3.668,6.14
partialy_cloudy,4.8461,50,90.239,2.26
Sunny,11.0607,53,90.239,-0.11
Mostly_cloudy,9.5473,29,3.668,2.06
Rainy,7.8246,54,120.737,14.34
Drizzle,0.2576,51,96.081,7.35
Mostly_cloudy,1.9642,53,96.081,2.3
partialy_cloudy,0,41,37.478,4.15
Sunny,0,47,22.522,-0.2
partialy_cloudy,0.4186,53,105.537,9.5
Mostly_cloudy,0,55,96.081,3.29
from flask import *
import json, time
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import pickle
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.model_selection import cross_val_score
from flask_cors import CORS
data = pd.read_csv("Trains.csv")
def input_to_one_hot(data):
enc_input = np.zeros(8)
enc_input[0] = data['Wind_Speed']
enc_input[1] = data['Average_Speed']
enc_input[2] = data['Distance']
enc_input[3] = data['Weater_Status_Drizzle']
enc_input[4] = data['Weater_Status_Mostly_cloudy']
enc_input[5] = data['Weater_Status_Rainy']
enc_input[6] = data['Weater_Status_Sunny']
enc_input[7] = data['Weater_Status_partialy_cloudy']
return enc_input
num_cols = [col for col in data.columns if data[col].dtypes != 'O' and col not in "Id"]
print('Number of Numerical Variables: ', len(num_cols))
num_cols
X = data[['Weater_Status', 'Wind_Speed', 'Average_Speed', 'Distance']]
X.dropna(inplace=True)
Y = data.loc[:, data.columns != 'gps'].dropna().Delay_time
X = pd.get_dummies(data=X)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size = .20, random_state = 42)
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import r2_score
gbr =GradientBoostingRegressor()
gbr.fit(X_train, Y_train)
predicted = gbr.predict(X_test)
residual = Y_test - predicted
from sklearn.metrics import mean_squared_error
rmse = np.sqrt(mean_squared_error(Y_test, predicted))
scores = cross_val_score(gbr, X, Y, cv=12)
# save model to file
pickle.dump(gbr, open("gbr2.pickle.dat", "wb"))
loaded_gbr = pickle.load(open("gbr2.pickle.dat", "rb"))
app = Flask(__name__)
CORS(app, resources={r"/delay/*": {"origins": "*"}})
@app.route('/delay/', methods=['GET'])
def request_page():
user_input = {'Wind_Speed':float(request.args.get('wind')),
'Average_Speed':int(request.args.get('avg_speed')),
'Distance':float(request.args.get('distance')),
'Weater_Status_Drizzle':int(request.args.get('drizzle')),
'Weater_Status_Mostly_cloudy':int(request.args.get('m_cloudy')),
'Weater_Status_Rainy':int(request.args.get('rainy')),
'Weater_Status_Sunny':int(request.args.get('sunny')),
'Weater_Status_partialy_cloudy':int(request.args.get('p_cloudy')),
}
a = input_to_one_hot(user_input)
delay_pred = loaded_gbr.predict([a])
print(delay_pred[0])
data = str(delay_pred[0])
json_dump = json.dumps({"data":data})
return json_dump
if __name__ == '__main__':
app.run(host="127.0.0.1", port=7778,debug = True)
#using this type
# http://127.0.0.1:7778/delay/?wind=15.65&avg_speed=55&distance=225.25&drizzle=0&m_cloudy=0&rainy=1&sunny=0&p_cloudy=0
\ No newline at end of file
This diff is collapsed.
[android]
target = Google Inc.:Google APIs:23
[maven_repositories]
central = https://repo1.maven.org/maven2
> Why do I have a folder named ".expo" in my project?
The ".expo" folder is created when an Expo project is started using "expo start" command.
> What does the "packager-info.json" file contain?
The "packager-info.json" file contains port numbers and process PIDs that are used to serve the application to the mobile device/simulator.
> What does the "settings.json" file contain?
The "settings.json" file contains the server configuration that is used to serve the application manifest.
> Should I commit the ".expo" folder?
No, you should not share the ".expo" folder. It does not contain any information that is relevant for other developers working on the project, it is specific to your machine.
Upon project creation, the ".expo" folder is already added to your ".gitignore" file.
{
"expoServerPort": 19000,
"packagerPort": 19000,
"packagerPid": null,
"expoServerNgrokUrl": null,
"packagerNgrokUrl": null,
"ngrokPid": null,
"webpackServerPort": null,
"devToolsPort": 19002
}
{
"hostType": "lan",
"lanType": "ip",
"dev": true,
"minify": false,
"urlRandomness": null,
"https": false,
"scheme": null,
"devClient": false
}
* text=auto
*.css linguist-vendored
*.scss linguist-vendored
*.js linguist-vendored
CHANGELOG.md export-ignore
/node_modules
/public/hot
/public/storage
/storage/*.key
/vendor
.env
.env.backup
.phpunit.result.cache
Homestead.json
Homestead.yaml
npm-debug.log
yarn-error.log
import { createAppContainer } from 'react-navigation';
import { createStackNavigator} from 'react-navigation-stack';
import Welcome from './components/Welcome';
import Login from './components/Login';
import Register from './components/Register';
import Weather from './components/Weather';
import Profile from './components/Profile';
import Users from './components/Users';
import Map from './components/Map';
import Delay from './components/Delay';
import Driver from './components/Driver';
import AllUsers from './components/AllUsers';
import Stations from './components/Stations';
import DelayP from './components/DelayP';
import Details from './components/Details';
import UserStations from './components/UserStations';
import ForgotPassword from './components/ForgotPassword';
import { YellowBox } from 'react-native';
import _ from 'lodash';
console.disableYellowBox = true
YellowBox.ignoreWarnings(['Warning:']);
const _console = _.clone(console);
console.warn = message => {
if (message.indexOf('Setting a timer') <= -1) {
_console.warn(message);
}
};
const App = createStackNavigator({
Welcome: { screen: Welcome },
Login: { screen: Login },
Register: { screen: Register },
ForgotPassword: { screen: ForgotPassword },
Map: { screen: Map },
Weather: { screen: Weather },
Profile: { screen: Profile },
AllUsers: { screen: AllUsers },
Users: { screen: Users },
Delay: { screen: Delay },
DelayP: { screen: DelayP },
Stations: { screen: Stations },
Driver: { screen: Driver },
Details: { screen: Details },
UserStations: { screen: UserStations },
},
{
initialRouteName: 'Welcome',
}
);
export default createAppContainer(App);
\ No newline at end of file
# To learn about Buck see [Docs](https://buckbuild.com/).
# To run your application with Buck:
# - install Buck
# - `npm start` - to start the packager
# - `cd android`
# - `keytool -genkey -v -keystore keystores/debug.keystore -storepass android -alias androiddebugkey -keypass android -dname "CN=Android Debug,O=Android,C=US"`
# - `./gradlew :app:copyDownloadableDepsToLibs` - make all Gradle compile dependencies available to Buck
# - `buck install -r android/app` - compile, install and run application
#
load(":build_defs.bzl", "create_aar_targets", "create_jar_targets")
lib_deps = []
create_aar_targets(glob(["libs/*.aar"]))
create_jar_targets(glob(["libs/*.jar"]))
android_library(
name = "all-libs",
exported_deps = lib_deps,
)
android_library(
name = "app-code",
srcs = glob([
"src/main/java/**/*.java",
]),
deps = [
":all-libs",
":build_config",
":res",
],
)
android_build_config(
name = "build_config",
package = "com.sf",
)
android_resource(
name = "res",
package = "com.sf",
res = "src/main/res",
)
android_binary(
name = "app",
keystore = "//android/keystores:debug",
manifest = "src/main/AndroidManifest.xml",
package_type = "debug",
deps = [
":app-code",
],
)
apply plugin: "com.android.application"
import com.android.build.OutputFile
/**
* The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
* and bundleReleaseJsAndAssets).
* These basically call `react-native bundle` with the correct arguments during the Android build
* cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
* bundle directly from the development server. Below you can see all the possible configurations
* and their defaults. If you decide to add a configuration block, make sure to add it before the
* `apply from: "../../node_modules/react-native/react.gradle"` line.
*
* project.ext.react = [
* // the name of the generated asset file containing your JS bundle
* bundleAssetName: "index.android.bundle",
*
* // the entry file for bundle generation. If none specified and
* // "index.android.js" exists, it will be used. Otherwise "index.js" is
* // default. Can be overridden with ENTRY_FILE environment variable.
* entryFile: "index.android.js",
*
* // https://facebook.github.io/react-native/docs/performance#enable-the-ram-format
* bundleCommand: "ram-bundle",
*
* // whether to bundle JS and assets in debug mode
* bundleInDebug: false,
*
* // whether to bundle JS and assets in release mode
* bundleInRelease: true,
*
* // whether to bundle JS and assets in another build variant (if configured).
* // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
* // The configuration property can be in the following formats
* // 'bundleIn${productFlavor}${buildType}'
* // 'bundleIn${buildType}'
* // bundleInFreeDebug: true,
* // bundleInPaidRelease: true,
* // bundleInBeta: true,
*
* // whether to disable dev mode in custom build variants (by default only disabled in release)
* // for example: to disable dev mode in the staging build type (if configured)
* devDisabledInStaging: true,
* // The configuration property can be in the following formats
* // 'devDisabledIn${productFlavor}${buildType}'
* // 'devDisabledIn${buildType}'
*
* // the root of your project, i.e. where "package.json" lives
* root: "../../",
*
* // where to put the JS bundle asset in debug mode
* jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
*
* // where to put the JS bundle asset in release mode
* jsBundleDirRelease: "$buildDir/intermediates/assets/release",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in debug mode
* resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
*
* // where to put drawable resources / React Native assets, e.g. the ones you use via
* // require('./image.png')), in release mode
* resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
*
* // by default the gradle tasks are skipped if none of the JS files or assets change; this means
* // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
* // date; if you have any other folders that you want to ignore for performance reasons (gradle
* // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
* // for example, you might want to remove it from here.
* inputExcludes: ["android/**", "ios/**"],
*
* // override which node gets called and with what additional arguments
* nodeExecutableAndArgs: ["node"],
*
* // supply additional arguments to the packager
* extraPackagerArgs: []
* ]
*/
project.ext.react = [
enableHermes: false
]
apply from: '../../node_modules/react-native-unimodules/gradle.groovy'
apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/expo-updates/scripts/create-manifest-android.gradle"
/**
* Set this to true to create two separate APKs instead of one:
* - An APK that only works on ARM devices
* - An APK that only works on x86 devices
* The advantage is the size of the APK is reduced by about 4MB.
* Upload all the APKs to the Play Store and people will download
* the correct one based on the CPU architecture of their device.
*/
def enableSeparateBuildPerCPUArchitecture = false
/**
* Run Proguard to shrink the Java bytecode in release builds.
*/
def enableProguardInReleaseBuilds = false
/**
* The preferred build flavor of JavaScriptCore.
*
* For example, to use the international variant, you can use:
* `def jscFlavor = 'org.webkit:android-jsc-intl:+'`
*
* The international variant includes ICU i18n library and necessary data
* allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
* give correct results when using with locales other than en-US. Note that
* this variant is about 6MiB larger per architecture than default.
*/
def jscFlavor = 'org.webkit:android-jsc:+'
/**
* Whether to enable the Hermes VM.
*
* This should be set on project.ext.react and mirrored here. If it is not set
* on project.ext.react, JavaScript will not be compiled to Hermes Bytecode
* and the benefits of using Hermes will therefore be sharply reduced.
*/
def enableHermes = project.ext.react.get("enableHermes", false);
android {
compileSdkVersion rootProject.ext.compileSdkVersion
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId "com.sf"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 1
versionName "1.0"
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
signingConfigs {
debug {
storeFile file('debug.keystore')
storePassword 'android'
keyAlias 'androiddebugkey'
keyPassword 'android'
}
}
buildTypes {
debug {
signingConfig signingConfigs.debug
}
release {
// Caution! In production, you need to generate your own keystore file.
// see https://facebook.github.io/react-native/docs/signed-apk-android.
signingConfig signingConfigs.debug
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
}
}
packagingOptions {
pickFirst "lib/armeabi-v7a/libc++_shared.so"
pickFirst "lib/arm64-v8a/libc++_shared.so"
pickFirst "lib/x86/libc++_shared.so"
pickFirst "lib/x86_64/libc++_shared.so"
}
// applicationVariants are e.g. debug, release
applicationVariants.all { variant ->
variant.outputs.each { output ->
// For each separate APK per architecture, set a unique version code as described here:
// https://developer.android.com/studio/build/configure-apk-splits.html
def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
def abi = output.getFilter(OutputFile.ABI)
if (abi != null) { // null for the universal-debug, universal-release variants
output.versionCodeOverride =
versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
}
}
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
//noinspection GradleDynamicVersion
implementation "com.facebook.react:react-native:+" // From node_modules
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
}
debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
exclude group:'com.facebook.flipper'
}
addUnimodulesDependencies()
if (enableHermes) {
def hermesPath = "../../node_modules/hermes-engine/android/";
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
}
// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
\ No newline at end of file
"""Helper definitions to glob .aar and .jar targets"""
def create_aar_targets(aarfiles):
for aarfile in aarfiles:
name = "aars__" + aarfile[aarfile.rindex("/") + 1:aarfile.rindex(".aar")]
lib_deps.append(":" + name)
android_prebuilt_aar(
name = name,
aar = aarfile,
)
def create_jar_targets(jarfiles):
for jarfile in jarfiles:
name = "jars__" + jarfile[jarfile.rindex("/") + 1:jarfile.rindex(".jar")]
lib_deps.append(":" + name)
prebuilt_jar(
name = name,
binary_jar = jarfile,
)
{
"project_info": {
"project_number": "40691622619",
"firebase_url": "https://farmer-8ac2f.firebaseio.com",
"project_id": "farmer-8ac2f",
"storage_bucket": "farmer-8ac2f.appspot.com"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:40691622619:android:448c6c421fa7379f6422fe",
"android_client_info": {
"package_name": "com.farmer"
}
},
"oauth_client": [
{
"client_id": "40691622619-hrkmrsfm4v756h5bh24mduvihd2a2e5i.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyDdqhpP-AjhO2m0qiahQRJGC14hoBF9oi8"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "40691622619-hrkmrsfm4v756h5bh24mduvihd2a2e5i.apps.googleusercontent.com",
"client_type": 3
}
]
}
}
}
],
"configuration_version": "1"
}
\ No newline at end of file
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<application android:usesCleartextTraffic="true" tools:targetApi="28" tools:ignore="GoogleAppIndexingWarning" />
</manifest>
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* <p>This source code is licensed under the MIT license found in the LICENSE file in the root
* directory of this source tree.
*/
package com.sf;
import android.content.Context;
import com.facebook.flipper.android.AndroidFlipperClient;
import com.facebook.flipper.android.utils.FlipperUtils;
import com.facebook.flipper.core.FlipperClient;
import com.facebook.flipper.plugins.crashreporter.CrashReporterPlugin;
import com.facebook.flipper.plugins.databases.DatabasesFlipperPlugin;
import com.facebook.flipper.plugins.fresco.FrescoFlipperPlugin;
import com.facebook.flipper.plugins.inspector.DescriptorMapping;
import com.facebook.flipper.plugins.inspector.InspectorFlipperPlugin;
import com.facebook.flipper.plugins.network.FlipperOkhttpInterceptor;
import com.facebook.flipper.plugins.network.NetworkFlipperPlugin;
import com.facebook.flipper.plugins.react.ReactFlipperPlugin;
import com.facebook.flipper.plugins.sharedpreferences.SharedPreferencesFlipperPlugin;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.modules.network.NetworkingModule;
import okhttp3.OkHttpClient;
public class ReactNativeFlipper {
public static void initializeFlipper(Context context, ReactInstanceManager reactInstanceManager) {
if (FlipperUtils.shouldEnableFlipper(context)) {
final FlipperClient client = AndroidFlipperClient.getInstance(context);
client.addPlugin(new InspectorFlipperPlugin(context, DescriptorMapping.withDefaults()));
client.addPlugin(new ReactFlipperPlugin());
client.addPlugin(new DatabasesFlipperPlugin(context));
client.addPlugin(new SharedPreferencesFlipperPlugin(context));
client.addPlugin(CrashReporterPlugin.getInstance());
NetworkFlipperPlugin networkFlipperPlugin = new NetworkFlipperPlugin();
NetworkingModule.setCustomClientBuilder(
new NetworkingModule.CustomClientBuilder() {
@Override
public void apply(OkHttpClient.Builder builder) {
builder.addNetworkInterceptor(new FlipperOkhttpInterceptor(networkFlipperPlugin));
}
});
client.addPlugin(networkFlipperPlugin);
client.start();
// Fresco Plugin needs to ensure that ImagePipelineFactory is initialized
// Hence we run if after all native modules have been initialized
ReactContext reactContext = reactInstanceManager.getCurrentReactContext();
if (reactContext == null) {
reactInstanceManager.addReactInstanceEventListener(
new ReactInstanceManager.ReactInstanceEventListener() {
@Override
public void onReactContextInitialized(ReactContext reactContext) {
reactInstanceManager.removeReactInstanceEventListener(this);
reactContext.runOnNativeModulesQueueThread(
new Runnable() {
@Override
public void run() {
client.addPlugin(new FrescoFlipperPlugin());
}
});
}
});
} else {
client.addPlugin(new FrescoFlipperPlugin());
}
}
}
}
\ No newline at end of file
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.sf">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<!-- OPTIONAL PERMISSIONS, REMOVE WHATEVER YOU DO NOT NEED -->
<uses-permission android:name="android.permission.MANAGE_DOCUMENTS"/>
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.USE_FINGERPRINT"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS"/>
<!-- These require runtime permissions on M -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.READ_CALENDAR"/>
<uses-permission android:name="android.permission.WRITE_CALENDAR"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_SETTINGS"/>
<!-- END OPTIONAL PERMISSIONS -->
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="@style/AppTheme"
>
<meta-data android:name="expo.modules.updates.EXPO_UPDATE_URL" android:value="" />
<meta-data android:name="expo.modules.updates.EXPO_SDK_VERSION" android:value="42.0.0" />
<meta-data android:name="expo.modules.updates.EXPO_RELEASE_CHANNEL" android:value="default" />
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:theme="@style/Theme.App.SplashScreen"
>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity"/>
</application>
</manifest>
package com.sf;
import android.os.Bundle;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
import expo.modules.splashscreen.SplashScreen;
import expo.modules.splashscreen.SplashScreenImageResizeMode;
public class MainActivity extends ReactActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// SplashScreen.show(...) has to be called after super.onCreate(...)
// Below line is handled by '@expo/configure-splash-screen' command and it's discouraged to modify it manually
SplashScreen.show(this, SplashScreenImageResizeMode.CONTAIN, false);
}
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "main";
}
@Override
protected ReactActivityDelegate createReactActivityDelegate() {
return new ReactActivityDelegate(this, getMainComponentName()) {
@Override
protected ReactRootView createRootView() {
return new RNGestureHandlerEnabledRootView(MainActivity.this);
}
};
}
}
package com.sf;
import android.app.Application;
import android.content.Context;
import android.net.Uri;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.sf.generated.BasePackageList;
import org.unimodules.adapters.react.ReactAdapterPackage;
import org.unimodules.adapters.react.ModuleRegistryAdapter;
import org.unimodules.adapters.react.ReactModuleRegistryProvider;
import org.unimodules.core.interfaces.Package;
import org.unimodules.core.interfaces.SingletonModule;
import expo.modules.constants.ConstantsPackage;
import expo.modules.permissions.PermissionsPackage;
import expo.modules.filesystem.FileSystemPackage;
import expo.modules.updates.UpdatesController;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Nullable;
public class MainApplication extends Application implements ReactApplication {
private final ReactModuleRegistryProvider mModuleRegistryProvider = new ReactModuleRegistryProvider(
new BasePackageList().getPackageList()
);
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
List<ReactPackage> packages = new PackageList(this).getPackages();
packages.add(new ModuleRegistryAdapter(mModuleRegistryProvider));
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
@Override
protected @Nullable String getJSBundleFile() {
if (BuildConfig.DEBUG) {
return super.getJSBundleFile();
} else {
return UpdatesController.getInstance().getLaunchAssetFile();
}
}
@Override
protected @Nullable String getBundleAssetName() {
if (BuildConfig.DEBUG) {
return super.getBundleAssetName();
} else {
return UpdatesController.getInstance().getBundleAssetName();
}
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
if (!BuildConfig.DEBUG) {
UpdatesController.initialize(this);
}
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
}
/**
* Loads Flipper in React Native templates. Call this in the onCreate method with something like
* initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
*
* @param context
* @param reactInstanceManager
*/
private static void initializeFlipper(
Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("com.rndiffapp.ReactNativeFlipper");
aClass
.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
.invoke(null, context, reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
package com.sf.generated;
import java.util.Arrays;
import java.util.List;
import org.unimodules.core.interfaces.Package;
public class BasePackageList {
public List<Package> getPackageList() {
return Arrays.<Package>asList(
new expo.modules.constants.ConstantsPackage(),
new expo.modules.errorrecovery.ErrorRecoveryPackage(),
new expo.modules.filesystem.FileSystemPackage(),
new expo.modules.font.FontLoaderPackage(),
new expo.modules.imageloader.ImageLoaderPackage(),
new expo.modules.keepawake.KeepAwakePackage(),
new expo.modules.lineargradient.LinearGradientPackage(),
new expo.modules.location.LocationPackage(),
new expo.modules.permissions.PermissionsPackage(),
new expo.modules.splashscreen.SplashScreenPackage(),
new expo.modules.sqlite.SQLitePackage(),
new expo.modules.updates.UpdatesPackage()
);
}
}
<?xml version="1.0" encoding="utf-8"?>
<!--
This file was created by '@expo/configure-splash-screen' and some of it's content shouldn't be modified by hand
-->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/splashscreen_background"/>
</layer-list>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Below line is handled by '@expo/configure-splash-screen' command and it's discouraged to modify it manually -->
<color name="splashscreen_background">#FFFFFF</color>
</resources>
<resources>
<string name="app_name">sf</string>
</resources>
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="android:textColor">#000000</item>
</style>
<style name="Theme.App.SplashScreen" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Below line is handled by '@expo/configure-splash-screen' command and it's discouraged to modify it manually -->
<item name="android:windowBackground">@drawable/splashscreen</item>
<!-- Customize your splash screen theme here -->
</style>
</resources>
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
buildToolsVersion = "28.0.3"
minSdkVersion = 21
compileSdkVersion = 28
targetSdkVersion = 28
}
repositories {
google()
jcenter()
}
dependencies {
classpath("com.android.tools.build:gradle:3.5.3")
classpath ('com.google.gms:google-services:4.2.0')
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
mavenLocal()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
maven {
// Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist")
}
google()
jcenter()
maven { url 'https://www.jitpack.io' }
}
}
# Project-wide Gradle settings.
# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.
# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
# Version of flipper SDK to use with React Native
FLIPPER_VERSION=0.33.1
\ No newline at end of file
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-all.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=$((i+1))
done
case $i in
(0) set -- ;;
(1) set -- "$args0" ;;
(2) set -- "$args0" "$args1" ;;
(3) set -- "$args0" "$args1" "$args2" ;;
(4) set -- "$args0" "$args1" "$args2" "$args3" ;;
(5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
(6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
(7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
(8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
(9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=$(save "$@")
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
cd "$(dirname "$0")"
fi
exec "$JAVACMD" "$@"
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem http://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
rootProject.name = 'sf'
apply from: '../node_modules/react-native-unimodules/gradle.groovy'
includeUnimodulesProjects()
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle");
applyNativeModulesSettingsGradle(settings)
include ':app'
{
"expo": {
"name": "Train Travellers",
"icon": "./assets/icon_logo.png",
"version": "1.0.0",
"slug": "Train-Travellers",
"ios": {
"bundleIdentifier": "com.sliit.train",
"buildNumber": "1.0.0"
},
"android": {
"package": "com.sliit.train",
"versionCode": 1
},
"description": ""
}
}
module.exports = function(api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
};
};
import React from "react";
import { TextInput, View, Dimensions , ActivityIndicator , StyleSheet, TouchableOpacity, Text, Image, ScrollView , AsyncStorage } from "react-native";
import RadioForm from "react-native-simple-radio-button";
import AwesomeAlert from "react-native-awesome-alerts";
import axios from 'axios';
import LocalIP from './localIP';
import { DataTable } from 'react-native-paper';
const initialState = {
page:0,
npages: 0,
page1:0,
npages1: 0,
localUri: "",
Users:[],
details:"",
semail: "",
message: "",
showAlert: false,
loader: false,
title: "",
};
export default class AllUsers extends React.Component {
constructor(props) {
super(props);
}
state = initialState;
static navigationOptions = ({ navigation}) => {
return {
headerTitle: 'All Users',
headerStyle: { backgroundColor: '#9dffab' },
headerTintColor: '#000000',
headerLeft: () => {
return null;
}
}
};
componentDidMount = async() => {
const email = await AsyncStorage.getItem('email')
const url = 'http://'+LocalIP+':3500/user/getCount';
await axios.get(url,{
headers: {'Content-Type': 'application/json'}
})
.then(async(res) => {
var pages=Math.floor(res.data[0]['count']/5)
if(res.data[0]['count']%5==0){
}else{
pages=parseInt(pages)+1
}
this.setState({npages:pages})
const url = 'http://'+LocalIP+':3500/user/getQuarter';
const data = JSON.stringify({ start: this.state.page*5 , length: 5 });
await axios.post(url,data,{
headers: {'Content-Type': 'application/json'}
})
.then(res => {
this.setState({Users:res.data})
})
})
}
showAlert = () => {
this.setState({
showAlert: true,
});
};
pageChange = async(page) => {
this.setState({
page: page,
});
const url = 'http://'+LocalIP+':3500/user/getQuarter';
const data = JSON.stringify({ start: page*5 , length: 5 });
await axios.post(url,data,{
headers: {'Content-Type': 'application/json'}
})
.then(res => {
this.setState({Users:res.data})
})
};
pageChange1 = async(page) => {
this.setState({
page1: page,
});
const email = this.state.semail
const url = 'http://'+LocalIP+':3500/my/getQuarter';
const data = JSON.stringify({ email:email , start: page*5 , length: 5 });
await axios.post(url,data,{
headers: {'Content-Type': 'application/json'}
})
.then(res => {
this.setState({Courses:res.data})
})
};
hideAlert = () => {
this.setState({
showAlert: false,
message: "",
title: "",
});
};
onSubmit = async(email,details) => {
const url = 'http://'+LocalIP+':3500/my/getCount';
const data = JSON.stringify({ email:email });
await axios.post(url,data,{
headers: {'Content-Type': 'application/json'}
})
.then(async(res) => {
var pages=Math.floor(res.data[0]['count']/5)
if(res.data[0]['count']%5==0){
}else{
pages=parseInt(pages)+1
}
if(pages==0){
pages=1
}
if(parseInt(res.data[0]['count'])==0){
this.setState({page1:0,npages1:1})
}else{
this.setState({npages1:pages})
}
const url = 'http://'+LocalIP+':3500/my/getQuarter';
const data = JSON.stringify({ email:email , start: this.state.page*5 , length: 5 });
await axios.post(url,data,{
headers: {'Content-Type': 'application/json'}
})
.then(res => {
this.setState({Courses:res.data,details:details,semail:email})
})
})
};
onSubmit1 = async(id) => {
const url = 'http://'+LocalIP+':3500/my/'+id;
await axios.delete(url,{
headers: {'Content-Type': 'application/json'}
})
.then(res => {
this.componentDidMount()
if(res.data["err"]=="connection"){
this.setState({ title: "Error!", message: "Connection Error!" });
this.showAlert();
}else{
this.setState({title:"Success!",message:"Unenrolled!"})
this.showAlert()
}
})
};
render() {
const { showAlert , Users , Courses } = this.state;
return (
<ScrollView>
<View style={styles.container}>
<View style={styles.center}>
<Image source={require("./../assets/logo.png")} style={{ width: 300, height: 300 }} />
</View>
<DataTable>
<DataTable.Header>
<DataTable.Title>ID</DataTable.Title>
<DataTable.Title>First Name</DataTable.Title>
<DataTable.Title>Last Name</DataTable.Title>
<DataTable.Title>Email</DataTable.Title>
<DataTable.Title>Image</DataTable.Title>
</DataTable.Header>
{
Users.map((res) =>
<DataTable.Row>
<DataTable.Cell>{res.id}</DataTable.Cell>
<DataTable.Cell>{res.fname}</DataTable.Cell>
<DataTable.Cell>{res.lname}</DataTable.Cell>
<DataTable.Cell>{res.email}</DataTable.Cell>
<DataTable.Cell>
<Image source={{ uri: 'http://'+LocalIP+':3500/'+res.image }} style={{ width: 50, height: 50 }} />
</DataTable.Cell>
<DataTable.Cell>
<TouchableOpacity style={[styles.listButton, styles.editButton]} onPress={ () => this.onSubmit(res.email,"ID : "+res.id+" Name : "+res.fname+" "+res.lname)} >
{!this.state.loader ? (
<Text style={{ color: "#000000", fontWeight: "bold" }}>View</Text>
) : null}
{this.state.loader ? (
<ActivityIndicator size="large" color={"#ffffff"} />
) : null}
</TouchableOpacity>
</DataTable.Cell>
</DataTable.Row>
)}
<DataTable.Pagination
page={this.state.page}
numberOfPages={this.state.npages}
onPageChange={(page) => this.pageChange(page)}
label={this.state.page+1+" of "+this.state.npages}
/>
</DataTable>
<View style={styles.center} >
<Text style={{ color: "#000000", fontWeight: "bold" }}>{this.state.details}</Text>
</View>
<AwesomeAlert
show={showAlert}
title={this.state.title}
message={this.state.message}
closeOnTouchOutside={true}
closeOnHardwareBackPress={false}
showCancelButton={true}
cancelText="Close"
cancelButtonColor="#AEDEF4"
onCancelPressed={() => {
this.hideAlert();
}}
/>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ffffff',
width: 100+'%'
},
center:{
alignItems: 'center',
},
labelText:{
fontWeight: 'bold' ,
fontSize: 14 ,
marginLeft: 10+'%',
marginBottom: 10
},
firstLabelText:{
fontWeight: 'bold' ,
fontSize: 14 ,
marginLeft: 10+'%',
marginTop: 2+'%',
},
input: {
borderBottomWidth: 1,
width: 80 + '%',
height:45,
marginBottom:20,
flexDirection: 'row',
alignItems:'center',
borderBottomColor: '#c4c4c4',
color: '#000000'
},
TextInputStyleClass:{
borderBottomWidth: 1,
width: 80 + '%',
height:100,
marginBottom:20,
flexDirection: 'row',
alignItems:'center',
borderBottomColor: '#c4c4c4',
color: '#000000'
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom:10,
width: 80 + '%',
height: 40,
borderRadius: 60
},
loginButton: {
backgroundColor: "#9dffab",
},
registerButton: {
backgroundColor: "#000000",
},
listButton: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom:10,
width: 50,
marginTop:10,
height: 40,
borderRadius: 10
},
listButtonDelete: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom:10,
width: 65,
marginTop:10,
height: 40,
borderRadius: 10
},
profilePic: {
width: 350,
height: 350,
},
profilePicView:{
width: 350,
height: 350,
borderRadius: 350,
borderBottomColor: '#000000',
borderWidth: 2,
overflow: 'hidden'
},
editButton: {
backgroundColor: "#1cd92f",
},
deleteButton: {
backgroundColor: "#ed0537",
},
});
This diff is collapsed.
import React from "react";
import { TextInput, View, ActivityIndicator , Picker , StyleSheet, TouchableOpacity, Text, Image, ScrollView , AsyncStorage} from "react-native";
import AwesomeAlert from "react-native-awesome-alerts";
import axios from 'axios';
import LocalIP from './localIP';
const initialState = {
avg_speed: "",
distance: "",
wind: "",
weather: "",
hum: "",
message: "",
showAlert: false,
loader: false,
title: "",
delay: "",
pre: "",
};
export default class DelayP extends React.Component {
state = initialState;
static navigationOptions = ({ navigation}) => {
return {
headerTitle: 'Delay Prediction',
headerStyle: { backgroundColor: '#9dffab' },
headerTintColor: '#000000',
headerLeft: () => {
return null;
}
}
};
constructor(props) {
super(props);
}
showAlert = () => {
this.setState({
showAlert: true,
});
};
hideAlert = () => {
this.setState({
showAlert: false,
message: "",
title: "",
});
};
validation =()=>{
if (this.state.wind != "") {
if (this.state.avg_speed != "") {
if (this.state.distance != "") {
if (this.state.weather != "") {
return true;
} else {
this.setState({ title: "Required!", message: "Select weather!" });
this.showAlert();
}
} else {
this.setState({ title: "Required!", message: "Enter an Distance!" });
this.showAlert();
}
} else {
this.setState({ title: "Required!", message: "Enter an Average Speed!" });
this.showAlert();
}
} else {
this.setState({ title: "Required!", message: "Enter an wind!" });
this.showAlert();
}
return false;
}
onSubmit = async(e) => {
if(await this.validation()){
var s=0,p=0,r=0,m=0,d=0
if(this.state.weather==4){
s=1
p=0
r=0
m=0
d=0
}else if(this.state.weather==5){
s=0
p=1
r=0
m=0
d=0
}else if(this.state.weather==3){
s=0
p=0
r=1
m=0
d=0
}else if(this.state.weather==2){
s=0
p=0
r=0
m=1
d=0
}else if(this.state.weather==1){
s=0
p=0
r=0
m=0
d=1
}
const urls1="http://"+LocalIP+":3500/prediction/delay"
const data1 = JSON.stringify({ wind: this.state.wind , avg_speed: this.state.avg_speed , distance: this.state.distance , drizzle: d,m_cloudy: m,rainy: r,sunny: s,p_cloudy: p});
await axios.post(urls1,data1,{
headers: {'Content-Type': 'application/json'}
}).then( res =>{
this.setState({delay:res.data['data'],pre:"Predicted Delay"})
})
}
};
render() {
const { showAlert } = this.state;
return (
<ScrollView>
<View style={styles.container}>
<View style={styles.center}>
<Image
source={require("./../assets/logo.png")}
style={{ width: 350, height: 350 }}
/>
</View>
<View style={styles.center}>
<Text style={{ color: "#000000", fontWeight: "bold", fontSize: 20 }}>{this.state.pre}</Text>
<Text style={{ color: "#000000", fontWeight: "bold", fontSize: 15 }}>{this.state.delay}</Text>
</View>
<Text style={styles.firstLabelText}>Wind Speed:</Text>
<View style={styles.center}>
<TextInput
value={this.state.wind}
keyboardType = {'numeric'}
onChangeText={(wind) => this.setState({wind })}
placeholder={"Wind Speed"}
style={styles.input}
/>
</View>
<Text style={styles.firstLabelText}>Average Speed:</Text>
<View style={styles.center}>
<TextInput
value={this.state.avg_speed}
keyboardType = {'numeric'}
onChangeText={(avg_speed) => this.setState({avg_speed })}
placeholder={"Average Speed"}
style={styles.input}
/>
</View>
<Text style={styles.firstLabelText}>Distance:</Text>
<View style={styles.center}>
<TextInput
value={this.state.distance}
keyboardType = {'numeric'}
onChangeText={(distance) => this.setState({distance })}
placeholder={"Distance"}
style={styles.input}
/>
</View>
<Text style={styles.firstLabelText}>Weather:</Text>
<View style={styles.center}>
<View
style={{
borderBottomWidth: 1,
width: 80 + '%',
height:45,
marginBottom:20,
flexDirection: 'row',
alignItems:'center',
marginLeft: 4,
borderBottomColor: '#c4c4c4',
color: '#000000',
}}>
<Picker
selectedValue={this.state.weather}
style={{width: 100 + '%',
height:45}}
onValueChange={(itemValue, itemIndex) => this.setState({weather: itemValue})}
>
<Picker.Item label="Select Weather" value="" />
<Picker.Item label="Drizzle" value="1" />
<Picker.Item label="Most Cloudy" value="2" />
<Picker.Item label="Rainy" value="3" />
<Picker.Item label="Sunny" value="4" />
<Picker.Item label="Partialy Cloudy" value="5" />
</Picker>
</View>
</View>
<View style={styles.center}>
<TouchableOpacity style={[styles.buttonContainer, styles.loginButton]} onPress={this.onSubmit} >
{!this.state.loader ? (
<Text style={{ color: "#000000", fontWeight: "bold" }}>Test</Text>
) : null}
{this.state.loader ? (
<ActivityIndicator size="large" color={"#ffffff"} />
) : null}
</TouchableOpacity>
</View>
<AwesomeAlert
show={showAlert}
title={this.state.title}
message={this.state.message}
closeOnTouchOutside={true}
closeOnHardwareBackPress={false}
showCancelButton={true}
cancelText="Close"
cancelButtonColor="#AEDEF4"
onCancelPressed={() => {
this.hideAlert();
}}
/>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ffffff',
},
center:{
alignItems: 'center',
},
labelText:{
fontWeight: 'bold' ,
fontSize: 14 ,
marginLeft: 10+'%',
marginBottom: 10
},
firstLabelText:{
fontWeight: 'bold' ,
fontSize: 14 ,
marginLeft: 10+'%',
marginTop: 2+'%',
},
input: {
borderBottomWidth: 1,
width: 80 + '%',
height:45,
marginBottom:20,
flexDirection: 'row',
alignItems:'center',
borderBottomColor: '#c4c4c4',
color: '#000000'
},
TextInputStyleClass:{
borderBottomWidth: 1,
width: 80 + '%',
height:100,
marginBottom:20,
flexDirection: 'row',
alignItems:'center',
borderBottomColor: '#c4c4c4',
color: '#000000'
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom:10,
width: 80 + '%',
height: 40,
borderRadius: 60
},
loginButton: {
backgroundColor: "#9dffab",
},
registerButton: {
backgroundColor: "#000000",
}
});
import React, { Component } from 'react';
import { Alert, Button, Picker , ActivityIndicator , TextInput , View, StyleSheet, TouchableOpacity, Text, Image , AsyncStorage , Dimensions , ScrollView } from 'react-native';
import 'react-native-gesture-handler';
import AwesomeAlert from 'react-native-awesome-alerts';
import Constants from 'expo-constants';
import * as Location from "expo-location";
import axios from 'axios';
import LocalIP from './localIP';
export default class Details extends React.Component {
constructor(props) {
super(props);
this.state = {
message:'',
showAlert: false,
loader: false,
title:'',
details:[]
};
this.interval = setInterval(() => {
this.componentDidMount();
}, 1000);
}
loadData = async() =>{
const isLoggedIn = await AsyncStorage.getItem('isLoggedIn')
const userType = await AsyncStorage.getItem('userType')
if(isLoggedIn=='true'&&userType=="Users"){
this.props.navigation.navigate('Users')
}else if(isLoggedIn=='true'&&userType=="Driver"){
this.props.navigation.navigate('Driver')
}
}
static navigationOptions = ({ navigation}) => {
return {
headerTitle: 'All Details',
headerStyle: { backgroundColor: '#9dffab' },
headerTintColor: '#000000',
}
};
componentDidMount= async()=> {
const url="http://"+LocalIP+":3500/prediction/details"
await axios.get(url,{
headers: {'Content-Type': 'application/json'}
}).then( res =>{
this.setState({details:res.data})
})
}
logout = async() => {
AsyncStorage.clear();
this.props.navigation.navigate('Login')
}
loadData = async() =>{
const isLoggedIn = await AsyncStorage.getItem('isLoggedIn')
if(isLoggedIn!=='true'){
}
}
showAlert = () => {
this.setState({
showAlert: true
});
};
hideAlert = () => {
this.setState({
showAlert: false,
message: '',
title: ''
});
};
render() {
const {showAlert} = this.state;
const {details} = this.state;
return (
<ScrollView style={styles.scrollView}>
<View style={styles.container}>
<Image source={require('./../assets/logo.png')}
style={{width: 120, height: 120 ,marginBottom:20 , marginTop:10}} />
{
details.map((record) =>
<View style={{width: 80 + '%',flex: 1, flexDirection: 'row',marginBottom:5}}>
<View style={{width: 50 + '%',marginBottom:5,alignItems: 'center',justifyContent: 'center'}}>
<Text style={{color: '#000000', fontWeight: 'bold' ,fontSize: 20}}>{record.name}</Text>
</View>
<View style={{width: 50 + '%',marginBottom:5,alignItems: 'center',justifyContent: 'center'}}>
<Text style={{color: '#000000', fontWeight: 'bold' ,fontSize: 20}}>{record.value}</Text>
</View>
</View>
)}
<AwesomeAlert
show={showAlert}
title={this.state.title}
message={this.state.message}
closeOnTouchOutside={true}
closeOnHardwareBackPress={false}
showCancelButton={true}
cancelText="Close"
cancelButtonColor="#AEDEF4"
onCancelPressed={() => {
this.hideAlert();
}}
/>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ffffff',
},
map: {
width: "100%",
height: 600
},
button: {
margin: 8
},
input: {
borderBottomWidth: 1,
width: 80 + '%',
height:45,
marginBottom:20,
flexDirection: 'row',
alignItems:'center',
marginLeft: 4,
borderBottomColor: '#c4c4c4',
color: '#000000'
},
TextInputStyleClass:{
borderBottomWidth: 1,
width: 80 + '%',
height:100,
marginBottom:20,
flexDirection: 'row',
alignItems:'center',
marginLeft: 4,
borderBottomColor: '#c4c4c4',
color: '#000000'
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom:10,
width: 80 + '%',
height: 40,
borderRadius: 60
},
loginButton: {
backgroundColor: "#348ceb",
},
registerButton: {
backgroundColor: "#7b00ff",
}
});
\ No newline at end of file
import React, { Component } from 'react';
import { View, StyleSheet, TouchableOpacity, Text, Image , AsyncStorage } from 'react-native';
import 'react-native-gesture-handler';
import AwesomeAlert from 'react-native-awesome-alerts';
export default class Driver extends React.Component {
constructor(props) {
super(props);
this.state = {
message:'',
showAlert: false,
title:''
};
this.loadData()
}
loadData = async() =>{
const isLoggedIn = await AsyncStorage.getItem('isLoggedIn')
const userType = await AsyncStorage.getItem('userType')
if(isLoggedIn=='true'&&userType=="Users"){
this.props.navigation.navigate('Users')
}else if(isLoggedIn=='true'&&userType=="Driver"){
this.props.navigation.navigate('Driver')
}
}
static navigationOptions = ({ navigation}) => {
return {
headerTitle: 'Driver Page',
headerStyle: { backgroundColor: '#9dffab' },
headerTintColor: '#000000',
}
};
showAlert = () => {
this.setState({
showAlert: true
});
};
hideAlert = () => {
this.setState({
showAlert: false,
message: '',
title: ''
});
};
logout = async() => {
AsyncStorage.clear();
this.props.navigation.navigate('Login')
}
render() {
const {showAlert} = this.state;
return (
<View style={styles.container}>
<Image source={require('./../assets/logo.png')}
style={{width: 200, height: 200 ,marginBottom:50 }} />
<TouchableOpacity style={[styles.buttonContainer, styles.loginButton]} onPress={() => this.props.navigation.navigate('Profile')}>
<Text style={{color: '#000000', fontWeight: 'bold'}}>Profile Update</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.buttonContainer, styles.loginButton]} onPress={() => this.props.navigation.navigate('Map')}>
<Text style={{color: '#000000', fontWeight: 'bold'}}>Map</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.buttonContainer, styles.loginButton]} onPress={() => this.props.navigation.navigate('Delay')}>
<Text style={{color: '#000000', fontWeight: 'bold'}}>Delay & Weather</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.buttonContainer, styles.loginButton]} onPress={() => this.props.navigation.navigate('Weather')}>
<Text style={{color: '#000000', fontWeight: 'bold'}}>Weather Prediction</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.buttonContainer, styles.loginButton]} onPress={() => this.props.navigation.navigate('DelayP')}>
<Text style={{color: '#000000', fontWeight: 'bold'}}>Delay Prediction</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.buttonContainer, styles.loginButton]} onPress={() => this.props.navigation.navigate('Stations')}>
<Text style={{color: '#000000', fontWeight: 'bold'}}>Arrived Stations</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.buttonContainer, styles.loginButton]} onPress={ this.logout }>
<Text style={{color: '#000000', fontWeight: 'bold'}}>Logout</Text>
</TouchableOpacity>
<AwesomeAlert
show={showAlert}
title={this.state.title}
message={this.state.message}
closeOnTouchOutside={true}
closeOnHardwareBackPress={false}
showCancelButton={true}
cancelText="Close"
cancelButtonColor="#9dffab"
onCancelPressed={() => {
this.hideAlert();
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ffffff',
},
input: {
borderBottomWidth: 1,
width: 80 + '%',
height:45,
marginBottom:20,
flexDirection: 'row',
alignItems:'center',
marginLeft: 4,
borderBottomColor: '#9dffab',
color: '#000000'
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom:10,
width: 80 + '%',
height: 40,
borderRadius: 60
},
loginButton: {
backgroundColor: "#9dffab",
},
registerButton: {
backgroundColor: "#000000",
}
});
\ No newline at end of file
import React, { Component } from 'react';
import { Alert, Button, TextInput, View, StyleSheet, TouchableOpacity, Text, Image } from 'react-native';
import 'react-native-gesture-handler';
import AwesomeAlert from 'react-native-awesome-alerts';
export default class ForgotPassword extends React.Component {
static navigationOptions = ({ navigation}) => {
return {
headerTitle: 'Forgot Password',
headerStyle: { backgroundColor: '#9dffab' },
headerTintColor: '#000000',
headerLeft: () => {
return null;
}
}
};
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
message:'',
showAlert: false,
title:''
};
}
onSend = e => {
}
showAlert = () => {
this.setState({
showAlert: true
});
};
hideAlert = () => {
this.setState({
showAlert: false,
message: '',
title: ''
})
this.props.navigation.navigate('Login')
};
render() {
const {showAlert} = this.state;
return (
<View style={styles.container}>
<Image source={require('./../assets/logo.png')}
style={{width: 350, height: 350}} />
<TextInput
value={this.state.email}
onChangeText={(email) => this.setState({ email })}
placeholder={'Email'}
style={styles.input}
/>
<TouchableOpacity style={[styles.buttonContainer, styles.loginButton]} onPress={ this.onSend }>
<Text style={{color: '#000000', fontWeight: 'bold'}}>Send</Text>
</TouchableOpacity>
<AwesomeAlert
show={showAlert}
title={this.state.title}
message={this.state.message}
closeOnTouchOutside={true}
closeOnHardwareBackPress={false}
showCancelButton={true}
cancelText="Close"
cancelButtonColor="#AEDEF4"
onCancelPressed={() => {
this.hideAlert()
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ffffff',
},
input: {
borderBottomWidth: 1,
width: 80 + '%',
height:45,
marginBottom:20,
flexDirection: 'row',
alignItems:'center',
marginLeft: 4,
borderBottomColor: '#c4c4c4',
color: '#000000'
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom:10,
width: 80 + '%',
height: 40,
borderRadius: 60
},
loginButton: {
backgroundColor: "#9dffab",
},
registerButton: {
backgroundColor: "#000000",
}
});
\ No newline at end of file
import React, { Component } from 'react';
import { Alert, ActivityIndicator , TextInput, View, StyleSheet, TouchableOpacity, Text, Image , AsyncStorage } from 'react-native';
import 'react-native-gesture-handler';
import AwesomeAlert from 'react-native-awesome-alerts';
import axios from 'axios';
import LocalIP from './localIP';
import utf8 from 'utf8'
import base64 from 'base-64'
export default class Login extends React.Component {
static navigationOptions = ({ navigation}) => {
return {
headerTitle: 'Login',
headerStyle: { backgroundColor: '#9dffab' },
headerTintColor: '#000000',
headerLeft: () => {
return null;
}
}
};
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
message:'',
showAlert: false,
loader: false,
title:''
}
this.loadData()
}
loadData = async() =>{
const isLoggedIn = await AsyncStorage.getItem('isLoggedIn')
const userType = await AsyncStorage.getItem('userType')
if(isLoggedIn=='true'&&userType=="Users"){
this.props.navigation.navigate('Users')
}else if(isLoggedIn=='true'&&userType=="Driver"){
this.props.navigation.navigate('Driver')
}
}
onLogin = async(e) => {
this.setState({loader:true})
const url = 'http://'+LocalIP+':3500/user/login/';
const data = JSON.stringify({email: this.state.email , password: base64.encode(utf8.encode(this.state.password))});
console.log(data)
await axios.post(url,data,{
headers: {'Content-Type': 'application/json'}
})
.then(async(res)=>{
this.setState({loader:false})
if(res.data["err"]=="user_email"){
console.log("email")
this.setState({ title: "Error!", message: "This Email not has our database!" ,email:"" ,password:"" });
this.showAlert();
}else if(res.data["err"]=="connection"){
console.log("connection")
this.setState({ title: "Error!", message: "Connection Error!" });
this.showAlert();
}else if(res.data["err"]=="user_password"){
console.log("password")
this.setState({ title: "Error!", message: "Invalid Password!" });
this.showAlert();
}else{
if(res.data){
console.log(res.data)
if(res.data['userType']==1){
await AsyncStorage.setItem('isLoggedIn','true')
await AsyncStorage.setItem('userType',"Users")
await AsyncStorage.setItem('email',res.data['email'])
this.props.navigation.navigate('Users')
}else if(res.data['userType']==2 && res.data['access']==1){
await AsyncStorage.setItem('isLoggedIn','true')
await AsyncStorage.setItem('userType',"Driver")
await AsyncStorage.setItem('email',res.data['email'])
this.props.navigation.navigate('Driver')
}else if(res.data['userType']==3 && res.data['access']==1){
await AsyncStorage.setItem('isLoggedIn','true')
await AsyncStorage.setItem('userType',"Admin")
await AsyncStorage.setItem('email',res.data['email'])
this.props.navigation.navigate('Users')
}else {
this.setState({ title: "Error!", message: "no permission!" });
this.showAlert();
}
}
}
})
}
showAlert = () => {
this.setState({
showAlert: true
});
};
hideAlert = () => {
this.setState({
showAlert: false,
message: '',
title: ''
});
};
render() {
const {showAlert} = this.state;
return (
<View style={styles.container}>
<Image source={require('./../assets/logo.png')}
style={{width: 350, height: 350}} />
<TextInput
value={this.state.email}
onChangeText={(email) => this.setState({ email })}
placeholder={'Email'}
style={styles.input}
/>
<TextInput
value={this.state.password}
onChangeText={(password) => this.setState({ password })}
placeholder={'Password'}
secureTextEntry={true}
style={styles.input}
/>
<TouchableOpacity style={[styles.buttonContainer, styles.loginButton]} onPress={ this.onLogin }>
{!this.state.loader ? (
<Text style={{color: '#000000', fontWeight: 'bold'}}>Login</Text>
) : null}
{this.state.loader ? (
<ActivityIndicator size="large" color={"#000000"} />
) : null}
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.navigation.navigate('Register')} style={[styles.buttonContainer, styles.registerButton]}>
<Text style={{color: '#ffffff', fontWeight: 'bold'}}>Register</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.buttonContainer} onPress={() => this.props.navigation.navigate('ForgotPassword')}>
<Text>Forgot your password?</Text>
</TouchableOpacity>
<AwesomeAlert
show={showAlert}
title={this.state.title}
message={this.state.message}
closeOnTouchOutside={true}
closeOnHardwareBackPress={false}
showCancelButton={true}
cancelText="Close"
cancelButtonColor="#AEDEF4"
onCancelPressed={() => {
this.hideAlert();
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ffffff',
},
input: {
borderBottomWidth: 1,
width: 80 + '%',
height:45,
marginBottom:20,
flexDirection: 'row',
alignItems:'center',
marginLeft: 4,
borderBottomColor: '#c4c4c4',
color: '#000000'
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom:10,
width: 80 + '%',
height: 40,
borderRadius: 60
},
loginButton: {
backgroundColor: "#9dffab",
},
registerButton: {
backgroundColor: "#000000",
}
});
\ No newline at end of file
import React, { Component } from 'react';
import { Alert, Button, Picker , ActivityIndicator , TextInput , View, StyleSheet, TouchableOpacity, Text, Image , AsyncStorage , Dimensions , ScrollView } from 'react-native';
import 'react-native-gesture-handler';
import AwesomeAlert from 'react-native-awesome-alerts';
import MapView from 'react-native-maps';
import Constants from 'expo-constants';
import * as Location from 'expo-location';
export default class Map extends React.Component {
constructor(props) {
super(props);
this.state = {
message:'',
showAlert: false,
loader: false,
title:'',
latitude: '',
longitude: ''
};
this.loadData()
this.getLocationHandler()
}
loadData = async() =>{
const isLoggedIn = await AsyncStorage.getItem('isLoggedIn')
const userType = await AsyncStorage.getItem('userType')
if(isLoggedIn=='true'&&userType=="Users"){
this.props.navigation.navigate('Users')
}else if(isLoggedIn=='true'&&userType=="Driver"){
this.props.navigation.navigate('Driver')
}
}
static navigationOptions = ({ navigation}) => {
return {
headerTitle: 'Map',
headerStyle: { backgroundColor: '#9dffab' },
headerTintColor: '#000000',
}
};
componentDidMount() {
if (Platform.OS === 'android' && !Constants.isDevice) {
alert(
'Oops, this will not work on Sketch in an Android emulator. Try it on your device!'
);
} else {
(async () => {
let { status } = await Location.requestPermissionsAsync();
if (status !== 'granted') {
alert('Permission to access location was denied');
}
var location = await Location.installWebGeolocationPolyfill()
})();
}
}
logout = async() => {
AsyncStorage.clear();
this.props.navigation.navigate('Login')
}
loadData = async() =>{
const isLoggedIn = await AsyncStorage.getItem('isLoggedIn')
if(isLoggedIn!=='true'){
}
}
showAlert = () => {
this.setState({
showAlert: true
});
};
hideAlert = () => {
this.setState({
showAlert: false,
message: '',
title: ''
});
};
getLocationHandler = () => {
navigator.geolocation.getCurrentPosition(pos => {
this.setState({latitude:pos.coords.latitude,longitude:pos.coords.longitude})
},
err => {
console.log(err);
alert("Fetching the Position failed, please pick one manually!");
})
console.log(this.state.latitude+" "+this.state.longitude)
}
render() {
const {showAlert} = this.state;
const {diseaseArray} = this.state;
let marker = null;
if (this.state.locationChosen) {
marker = <MapView.Marker coordinate={this.state.focusedLocation} />;
}
return (
<ScrollView style={styles.scrollView}>
<View style={styles.container}>
<Image source={require('./../assets/logo.png')}
style={{width: 120, height: 120 ,marginBottom:20 , marginTop:10}} />
<MapView
initialRegion={this.state.focusedLocation}
region={!this.state.locationChosen ? this.state.focusedLocation : null}
style={{width: 80 + '%',
height: Dimensions.get('window').height*0.8 ,
borderWidth: 1,
marginBottom:10 ,
marginLeft: 4,
borderColor: '#c4c4c4',
}}
onLongPress={this.pickLocationHandler}
zoomEnabled={true}
pitchEnabled={true}
showsUserLocation={true}
followsUserLocation={true}
showsCompass={true}
showsBuildings={true}
showsIndoors={true}
ref={ref => this.map = ref}
>
{marker}
</MapView>
<AwesomeAlert
show={showAlert}
title={this.state.title}
message={this.state.message}
closeOnTouchOutside={true}
closeOnHardwareBackPress={false}
showCancelButton={true}
cancelText="Close"
cancelButtonColor="#AEDEF4"
onCancelPressed={() => {
this.hideAlert();
}}
/>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ffffff',
},
map: {
width: "100%",
height: 600
},
button: {
margin: 8
},
input: {
borderBottomWidth: 1,
width: 80 + '%',
height:45,
marginBottom:20,
flexDirection: 'row',
alignItems:'center',
marginLeft: 4,
borderBottomColor: '#c4c4c4',
color: '#000000'
},
TextInputStyleClass:{
borderBottomWidth: 1,
width: 80 + '%',
height:100,
marginBottom:20,
flexDirection: 'row',
alignItems:'center',
marginLeft: 4,
borderBottomColor: '#c4c4c4',
color: '#000000'
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom:10,
width: 80 + '%',
height: 40,
borderRadius: 60
},
loginButton: {
backgroundColor: "#348ceb",
},
registerButton: {
backgroundColor: "#7b00ff",
}
});
\ No newline at end of file
This diff is collapsed.
import React from "react";
import { TextInput, View, ActivityIndicator , StyleSheet, TouchableOpacity, Text, Image, ScrollView} from "react-native";
import RadioForm from "react-native-simple-radio-button";
import AwesomeAlert from "react-native-awesome-alerts";
import axios from 'axios';
import LocalIP from './localIP';
import utf8 from 'utf8'
import base64 from 'base-64'
const initialState = {
fname: "",
lname: "",
email: "",
password: "",
cpassword: "",
type: "",
message: "",
showAlert: false,
loader: false,
title: "",
};
var radio_props = [
{ label: "Passenger ", value: "1" },
{ label: "Driver", value: "2" },
];
export default class Register extends React.Component {
state = initialState;
static navigationOptions = ({ navigation}) => {
return {
headerTitle: 'Register',
headerStyle: { backgroundColor: '#9dffab' },
headerTintColor: '#000000',
headerLeft: () => {
return null;
}
}
};
constructor(props) {
super(props);
}
showAlert = () => {
this.setState({
showAlert: true,
});
};
hideAlert = () => {
this.setState({
showAlert: false,
message: "",
title: "",
});
};
validation =()=>{
if (this.state.email != "") {
if (this.state.fname != "") {
if (this.state.lname != "") {
if (this.state.password != "") {
if (this.state.cpassword != "") {
if (this.state.password == this.state.cpassword) {
var reg = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (reg.test(this.state.email) === true){
return true;
} else {
this.setState({
title: "Error!",
message: "Invalid Email!",
});
this.showAlert();
}
} else {
this.setState({
title: "Error!",
message: "Password & Confirm Password Not Equals!",
});
this.showAlert();
}
} else {
this.setState({
title: "Required!",
message: "Enter an Confirm Password!",
});
this.showAlert();
}
} else {
this.setState({ title: "Required!", message: "Enter an Password!" });
this.showAlert();
}
} else {
this.setState({ title: "Required!", message: "Enter an Last Name!" });
this.showAlert();
}
} else {
this.setState({ title: "Required!", message: "Enter an First Name!" });
this.showAlert();
}
} else {
this.setState({ title: "Required!", message: "Enter an Email!" });
this.showAlert();
}
return false;
}
onRegister = async(e) => {
if(await this.validation()){
this.setState({loader:true})
const url = 'http://'+LocalIP+':3500/user/';
const data = JSON.stringify({ fname: this.state.fname , lname: this.state.lname , email: this.state.email , password: base64.encode(utf8.encode(this.state.password)) , userType: this.state.type });
await axios.post(url,data,{
headers: {'Content-Type': 'application/json'}
})
.then(res => {
console.log(res.data["err"]);
this.setState(initialState)
if(res.data["err"]=="email"){
this.setState({ title: "Error!", message: "This Email Already Exists!" ,email:"" });
this.showAlert();
}else if(res.data["err"]=="connection"){
this.setState({ title: "Error!", message: "Connection Error!" });
this.showAlert();
}else if(res.data["err"]=="data"){
this.setState({ title: "Error!", message: "Invalid Data!" });
this.showAlert();
}else{
this.setState({title:"Success!",message:"Register Successful!"})
this.showAlert()
}
})
}
};
render() {
const { showAlert } = this.state;
return (
<ScrollView>
<View style={styles.container}>
<View style={styles.center}>
<Image
source={require("./../assets/logo.png")}
style={{ width: 350, height: 350 }}
/>
</View>
<Text style={styles.firstLabelText}>First Name:</Text>
<View style={styles.center}>
<TextInput
value={this.state.fname}
onChangeText={(fname) => this.setState({ fname })}
placeholder={"First Name"}
style={styles.input}
/>
</View>
<Text style={styles.firstLabelText}>Last Name:</Text>
<View style={styles.center}>
<TextInput
value={this.state.lname}
onChangeText={(lname) => this.setState({ lname })}
placeholder={"Last Name"}
style={styles.input}
/>
</View>
<Text style={styles.firstLabelText}>Email:</Text>
<View style={styles.center}>
<TextInput
value={this.state.email}
onChangeText={(email) => this.setState({ email })}
placeholder={"Email"}
style={styles.input}
/>
</View>
<Text style={styles.firstLabelText}>Password:</Text>
<View style={styles.center}>
<TextInput
value={this.state.password}
onChangeText={(password) => this.setState({ password })}
placeholder={"Password"}
secureTextEntry={true}
style={styles.input}
/>
</View>
<Text style={styles.firstLabelText}>Confirm Password:</Text>
<View style={styles.center}>
<TextInput
value={this.state.cpassword}
onChangeText={(cpassword) => this.setState({ cpassword })}
placeholder={"Confirm Password"}
secureTextEntry={true}
style={styles.input}
/>
</View>
<Text style={styles.firstLabelText}>User Type:{"\n"}</Text>
<View style={styles.center}>
<RadioForm
radio_props={radio_props}
formHorizontal={true}
labelHorizontal={true}
buttonColor={"#000000"}
selectedButtonColor={"#9dffab"}
animation={true}
buttonSize={15}
labelStyle={{ fontSize: 15 }}
style={{ marginBottom: 30 }}
initial={ this.state.type }
onPress={(value) => {
this.setState({ type: value });
}}
/>
</View>
<View style={styles.center}>
<TouchableOpacity style={[styles.buttonContainer, styles.loginButton]} onPress={this.onRegister} >
{!this.state.loader ? (
<Text style={{ color: "#000000", fontWeight: "bold" }}>Register</Text>
) : null}
{this.state.loader ? (
<ActivityIndicator size="large" color={"#ffffff"} />
) : null}
</TouchableOpacity>
<TouchableOpacity onPress={() => this.props.navigation.navigate("Login")} style={[styles.buttonContainer, styles.registerButton]} >
<Text style={{ color: "#ffffff", fontWeight: "bold" }}>Login</Text>
</TouchableOpacity>
</View>
<AwesomeAlert
show={showAlert}
title={this.state.title}
message={this.state.message}
closeOnTouchOutside={true}
closeOnHardwareBackPress={false}
showCancelButton={true}
cancelText="Close"
cancelButtonColor="#AEDEF4"
onCancelPressed={() => {
this.hideAlert();
}}
/>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ffffff',
},
center:{
alignItems: 'center',
},
labelText:{
fontWeight: 'bold' ,
fontSize: 14 ,
marginLeft: 10+'%',
marginBottom: 10
},
firstLabelText:{
fontWeight: 'bold' ,
fontSize: 14 ,
marginLeft: 10+'%',
marginTop: 2+'%',
},
input: {
borderBottomWidth: 1,
width: 80 + '%',
height:45,
marginBottom:20,
flexDirection: 'row',
alignItems:'center',
borderBottomColor: '#c4c4c4',
color: '#000000'
},
TextInputStyleClass:{
borderBottomWidth: 1,
width: 80 + '%',
height:100,
marginBottom:20,
flexDirection: 'row',
alignItems:'center',
borderBottomColor: '#c4c4c4',
color: '#000000'
},
buttonContainer: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
marginBottom:10,
width: 80 + '%',
height: 40,
borderRadius: 60
},
loginButton: {
backgroundColor: "#9dffab",
},
registerButton: {
backgroundColor: "#000000",
}
});
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment