Connor Mills

Connor Mills

1566813750

Learn Svelte 3.0 - Svelte Tutorial for Beginners

Svelte.js is the new kid on the block to compete against the big 3 (Angular, Vue and React) in the frontend javascript framework space.

Let’s get started!

Installation

To get started, you will need Node.js with NPM installed. Visit http://nodejs.org to download and install it if it’s not on your machine yet. You can open up your terminal and type ‘node -v’ to determine if it’s installed.

Once node.js is installed, in your terminal, type:

> npx degit sveltejs/template svelte-project
> cd svelte-project
> npm install (or npm i)

This downloads Svelte, hops you into the new folder, and then installs the dependencies associated with Svelte.

Next, open up the new folder in your preferred code editor. If you’re using VSC (Visual Studio Code), you can type “code .” in the svelte folder via the terminal and it will open up VSC in that folder.

Finally, we’ll run the dev server by typing:

> npm run dev

You can visit your new Svelte app by visiting http://localhost:5000 in your browser!

Project Folder & File Structure

It’s worth taking a look at the files and folders found within your Svelte app.

> node_modules
> public
> src
.gitignore
package-lock.json
package.json
README.md
rollup.config.js

It’s surprisingly very simplistic upon first glance, as compared to the file and folder structure as found in competitors such as Angular and Vue.

At the bottom we see rollup.config.js which is a module bundler for JavaScript. Think of it as a competitor to Webpack and Parcel.

Next up, we have /src which includes main.js and App.svelte.

main.js is the starting/entry point of the app.

import App from './App.svelte';

const app = new App({
       target: document.body,
       props: {
              name: 'world'
       }
});

export default app;

As you can see, it imports the other file at the top, which is the starting component for the app. It also specifies a target, which specifies where the app output will go, and any properties in the form of a props object.

In App.svelte:

<script>
       export let name;
</script>

<style>
       h1 {
              color: purple;
       }
</style>

<h1>Hello {name}!</h1>

Here, we have the 3 basic building blocks of a modern Javascript framework:

  • The Logic
  • The Style
  • The HTML Template

Routing

Unfortunately, as of writing this, there is not an official Svelte router. There are numerous routers people have developed. We’re going to use one of these unofficial routers to help us navigate througout the different components of our Svelte app.

First, we need to install at in the terminal:

npm install --save svero

Here’s the github page for svero if you want to learn more.

After it’s installed, visit **App.svelte **and update it to match the following:

<script>

       import { Router, Route } from 'svero';

       import Header from './Header.svelte';
       import Index from './pages/Index.svelte';
       import About from './pages/About.svelte';

</script> 

<style>
       
</style>

<Header/>

<div class="container">
       <Router>
              <Route path="*" component={Index} />
              <Route path="/about" component={About} />
       </Router>
</div>

First, we’re importing the router at the top. Then, we’re importing a few files that don’t yet exist (we’ll create those in a second).

Then, we’re nesting a

element (It receives it’s name based on the filename), and beneath it, we’re defining our routes. In Angular, this is similar to the router outlet tag, except we also use it to define our paths and associated components.

Let’s create those files now.

<strong>/pages/About.svelte</strong>:

<script>
 export let router = {};

 // Those contains useful information about current route status
 router.path; // /test
 router.route; // Route Object
 router.params; // /about/bill/123/kansas { who: 'bill', where: 'kansas' }
</script>

<h1>About me</h1>

<p>This is my router path: {router.path}</p>

At the top here, we’re demonstrating how you can access various router properties with the router library that we’re using.

<strong>/pages/Index.svelte</strong>:

<h1>I'm homeee</h1>

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perspiciatis, laborum dignissimos? Ab blanditiis veniam a aspernatur autem, harum, quia dolor pariatur labore asperiores recusandae nihil dolorem exercitationem id itaque tempora?</p>

In this case, we’re only specifying the templating. If you don’t need logic or style, just omit those sections of the component.

<strong>/scr/Header.svelte</strong>:

<script>

   import {Link} from "svero"

</script>

<header>
   <Link href="/home" className="logo">Hello!</Link>
   <nav>
       <ul>
           <li><Link href="/home">Home</Link></li>
           <li><Link href="/about">About</Link></li>
       </ul>
   </nav>
</header>

Instead of using regular tags, we’re using Link from svero. Also, notice className instead of class, when we’re using the Link component.

If you save everything, it should be ready to rock! But it’s rather ugly, too.

Giving it some Style

This is all straight forward CSS stuff, with exception to one concept.

Visit App.svelte and specify the following within the style tags:

<style>

   :global(body) {
              /* this will apply to <body> */
              margin: 0;
              padding: 0;
       }

       .container { 
              width: 80%;
              margin: 4em auto;
       }

</style>

Notice :global(selector). If you’re referencing any CSS elements that aren’t present in the current component’s template as HTML tags, you can use this global selector format.

<strong>Header.svelte</strong>:

<style>

   header {
       display: flex;
       justify-content: space-between;
       background: rgb(0, 195, 255);
   }

   nav ul {
       display: flex;
       list-style-type: none;
       margin: 0;
   }

   :global(header a) {
       padding: 1em;
       display: block;
       color: white !important;
   }

   :global(.logo) { 
       font-weight: bold;
   }

</style>

Interpolation

Now, we’re going to cover some of the basic stuff in Svelte. Interpolation is simply displaying a variable of some sort in the template.

Open up Index.svelte and update it:

<script>

   let bro = 'Bro';

</script>

<h1>{bro}</h1>

As you can see, very, very simple.

Event Handling

Let’s create a method that’s called when a user clicks a button, and let’s make it do something:

<script>

   let bro = 'Bro';

   function clickEvent() {
       bro = 'Dude';
   }

</script>

<h1>{bro}</h1>

<button on:click={clickEvent}>Click me</button>

Easy, easy stuff! You can also change :click to other events, such as mouseover and it will work just the same.

If and Else

Update the component as follows:

<script>

   let person = {
       status: 'dude'
   }

</script>

{#if person.status == 'dude'}
   <h1>Dude!!</h1>
{/if}

If we want an else statement:

<script>

   let person = {
       status: 'bro'
   }

</script>

{#if person.status == 'dude'}
   <h1>Dude!!</h1>
{:else}
   <h1>{person.status}</h1>
{/if}

Once again, very simple to understand.

If you want else if, that’s easy too:

<script>

   let person = {
       status: 'woah'
   }

</script>

{#if person.status == 'dude'}
   <h1>Dude!!</h1>
{:else if person.status == 'bro'}
   <h1>bro!!</h1>
{:else}
   <h1>{person.status}</h1>
{/if}

Awesome!

Iteration

Many times, you need to iterate over an array of some sort. This is how you achieve that with Svelte:

<script>

   let persons = [
       { status: 'dude', tagline: 'Yo sup' },
       { status: 'bro', tagline: 'Gnarly, man' },
       { status: 'chick', tagline: 'Watchoo want boo?' },
   ]

</script>

<ul>
   {#each persons as {status, tagline }, i}
       <li>{i+1}: <strong>{status} </strong>({tagline})</li>
   {/each}
</ul>

So, we simply define an array (or an array of objects in our case), and we iterate over them in the template using #each.

This is a powerful concept to understand, as many times, you will be receiving data from a backend in the form of an array or an array of objects, and you will need to output the results to your template.

Bindings

Forms are a critical part of any app, so let’s discover how we can communicate form-based data to and from Svelte via 2 way data binding:

<script>
       let name = 'broseph';
</script>

<h1>{name}</h1>

<input bind:value={name}>

In this case, name is being set in the component logic, but it’s also something that can be set and updated in real time via the component template (the input textfield).

Another example of this reactivity in forms is with a checkbox:

<script>
       let status = false;
</script>

<label>
   <input type="checkbox" bind:checked={status}>
   Do you want to lear more svelte?
</label>

{#if status}
   <p>Of course I want to learn more</p>
{:else}
   <p>Nah, I want to keep being a newbie</p>
{/if}

Here, we’ve mixed what we learned with template conditionals with two-way data binding. Awesome!

Data Stores

Many times, you don’t want to store data at the component level. Rather, you want to store your data in a central location that your components can easily access.

To do this, create the file /src/stores.js with the following code:

import { writable } from 'svelte/store';

export const status = writable('dude');

Next, inside Index.svelte replace the previous code with:

<script>
   import { status } from '../stores.js';

   let the_status;
   
   const stat = status.subscribe(val => {
       the_status = val;
   })
</script>
 
<h1>{the_status}</h1>

As you can see, we must subscribe to status and then we can access the value as shown in the h1.

How about updating the property from our component?

Adjust the code to:

<script>
   import { status } from '../stores.js';

   let the_status;
   
   const stat = status.subscribe(val => {
       the_status = val;
   })

   function changeStore() {
       status.update(n => n = 'bro');
   }
</script>
 
<h1 on:mouseover={changeStore}>{the_status}</h1>

So, when you hover your mouse over the h1 element, we’re updating the status property as such.

Also, because we are subscribing to the property stat, to avoid memory issues, you should unsubscribe to the value on the lifecycle onDestroy().

<script>
   import { onDestroy } from 'svelte';
   import { status } from '../stores.js';

   let the_status;
   
   const stat = status.subscribe(val => {
       the_status = val;
   })

   function changeStore() {
       status.update(n => n = 'bro');
   }

   onDestroy(stat);

</script>
 
<h1 on:mouseover={changeStore}>{the_status}</h1>

Great!

Fetching Data

We can use modern browser’s fetch to grab data from an API. This could be from your own backend, or from a public test API in our case.

Visit Index.svelte and update it:

<script>
   import { onMount } from "svelte";

   let data = [];
   onMount(async function() {
       const response = await
fetch("https://jsonplaceholder.typicode.com/posts");
       const json = await response.json();
       data = json;
       console.log(data);
   });

</script>
 
<ul>
{#each data as {title}}
   <li><p>{title}</p></li>
{/each}
</ul>

Easy!

Deployment

To build out your Svelte app, run:

> npm run build

This outputs everything inside of the /public/ folder.

You can use the FTP to upload the contents of this folder to a web server and it will work. You can even install something like lite-server via NPM and launch it within the directory locally.

My current sponsor is Linode.com and I’m going to show you how to launch this static site using their service!

First, join up at Linode. Next, once logged in, click Create Linode:

Next for Distribution, choose Debian. Select a region, then choose a Nanode 1GB. Then, choose a password and click Create.

Wait for it to boot the server up. Once that’s done, click Launch Console. Wait until it prompts you for a localhost login. Choose “glish” at the top once it does.

Specify “root” for the login and your chosen password from earlier.

Once logged in, we need to install nginx which is an open source web server.

apt-get install nginx

Once it’s finished, we have to start it up:

systemctl start nginx

Now, in the linode dashboard, grab your site’s IP address and visit it in the browser. You will see a Welcome message, which means the server is now ready to rock!

Right now, that welcome message is being served by default from /var/www/html – but when we pull in our project, it’s going to be stored in a /public folder. So, we need to modify that root folder to: /var/www/html/public so that it serves from that folder.

To do this:
> cd /etc/nginx/sites-enabled
> nano default

Using your keyboard arrow keys, navigate to the area shown below in the picture and add /public:

Then hit CTRL-O and hit Enter. Then hit CTRL-X to exit out of nano.

Next, we have to restart the server:

> service nginx restart

Now, if you refresh the server IP in the browser, you will receive a 404 not found. That’s because we haven’t yet pulled in our project.

Let’s install git on our server:

> apt-get install git

Next, let’s hop into our html folder:

> cd /var/www/html

Great! Now, we have to push our local project using git on our local machine. Which means, we’ll first need to create a repo at github.com.

Once you do that, in your local console within the project folder we worked in, type:

> git init
> git add .
> git commit -m "first commit"
> git remote add origin [the origin github displayed after creating the repo]
> git push -u origin master

Now, back in our server’s console, type:

> rm /var/www/html/*
>
git clone https://github.com/[yourusername]/[yourreponame].git .

We need to install nodejs and npm:

>
curl -sL https://deb.nodesource.com/setup_12.x | bash -
> apt-get install -y nodejs

>
curl -L https://npmjs.org/install.sh | sudo sh

Next, run:

> npm i
> npm run build

Great! Now, check your browser and you should see the app working!

You can also set up a domain and all of that good stuff, but this tutorial is already long enough!

Conclusion

We only just scratched the surface here, but we covered a lot of ground already and it’s now worth going over it one more time to commit it to memory. Stay tuned, we just might cover more Svelte!

Thanks for reading

#javascript #angular #vue-js #reactjs #web-development

What is GEEK

Buddha Community

Learn Svelte 3.0 - Svelte Tutorial for Beginners

A Wrapper for Sembast and SQFlite to Enable Easy

FHIR_DB

This is really just a wrapper around Sembast_SQFLite - so all of the heavy lifting was done by Alex Tekartik. I highly recommend that if you have any questions about working with this package that you take a look at Sembast. He's also just a super nice guy, and even answered a question for me when I was deciding which sembast version to use. As usual, ResoCoder also has a good tutorial.

I have an interest in low-resource settings and thus a specific reason to be able to store data offline. To encourage this use, there are a number of other packages I have created based around the data format FHIR. FHIR® is the registered trademark of HL7 and is used with the permission of HL7. Use of the FHIR trademark does not constitute endorsement of this product by HL7.

Using the Db

So, while not absolutely necessary, I highly recommend that you use some sort of interface class. This adds the benefit of more easily handling errors, plus if you change to a different database in the future, you don't have to change the rest of your app, just the interface.

I've used something like this in my projects:

class IFhirDb {
  IFhirDb();
  final ResourceDao resourceDao = ResourceDao();

  Future<Either<DbFailure, Resource>> save(Resource resource) async {
    Resource resultResource;
    try {
      resultResource = await resourceDao.save(resource);
    } catch (error) {
      return left(DbFailure.unableToSave(error: error.toString()));
    }
    return right(resultResource);
  }

  Future<Either<DbFailure, List<Resource>>> returnListOfSingleResourceType(
      String resourceType) async {
    List<Resource> resultList;
    try {
      resultList =
          await resourceDao.getAllSortedById(resourceType: resourceType);
    } catch (error) {
      return left(DbFailure.unableToObtainList(error: error.toString()));
    }
    return right(resultList);
  }

  Future<Either<DbFailure, List<Resource>>> searchFunction(
      String resourceType, String searchString, String reference) async {
    List<Resource> resultList;
    try {
      resultList =
          await resourceDao.searchFor(resourceType, searchString, reference);
    } catch (error) {
      return left(DbFailure.unableToObtainList(error: error.toString()));
    }
    return right(resultList);
  }
}

I like this because in case there's an i/o error or something, it won't crash your app. Then, you can call this interface in your app like the following:

final patient = Patient(
    resourceType: 'Patient',
    name: [HumanName(text: 'New Patient Name')],
    birthDate: Date(DateTime.now()),
);

final saveResult = await IFhirDb().save(patient);

This will save your newly created patient to the locally embedded database.

IMPORTANT: this database will expect that all previously created resources have an id. When you save a resource, it will check to see if that resource type has already been stored. (Each resource type is saved in it's own store in the database). It will then check if there is an ID. If there's no ID, it will create a new one for that resource (along with metadata on version number and creation time). It will save it, and return the resource. If it already has an ID, it will copy the the old version of the resource into a _history store. It will then update the metadata of the new resource and save that version into the appropriate store for that resource. If, for instance, we have a previously created patient:

{
    "resourceType": "Patient",
    "id": "fhirfli-294057507-6811107",
    "meta": {
        "versionId": "1",
        "lastUpdated": "2020-10-16T19:41:28.054369Z"
    },
    "name": [
        {
            "given": ["New"],
            "family": "Patient"
        }
    ],
    "birthDate": "2020-10-16"
}

And we update the last name to 'Provider'. The above version of the patient will be kept in _history, while in the 'Patient' store in the db, we will have the updated version:

{
    "resourceType": "Patient",
    "id": "fhirfli-294057507-6811107",
    "meta": {
        "versionId": "2",
        "lastUpdated": "2020-10-16T19:45:07.316698Z"
    },
    "name": [
        {
            "given": ["New"],
            "family": "Provider"
        }
    ],
    "birthDate": "2020-10-16"
}

This way we can keep track of all previous version of all resources (which is obviously important in medicine).

For most of the interactions (saving, deleting, etc), they work the way you'd expect. The only difference is search. Because Sembast is NoSQL, we can search on any of the fields in a resource. If in our interface class, we have the following function:

  Future<Either<DbFailure, List<Resource>>> searchFunction(
      String resourceType, String searchString, String reference) async {
    List<Resource> resultList;
    try {
      resultList =
          await resourceDao.searchFor(resourceType, searchString, reference);
    } catch (error) {
      return left(DbFailure.unableToObtainList(error: error.toString()));
    }
    return right(resultList);
  }

You can search for all immunizations of a certain patient:

searchFunction(
        'Immunization', 'patient.reference', 'Patient/$patientId');

This function will search through all entries in the 'Immunization' store. It will look at all 'patient.reference' fields, and return any that match 'Patient/$patientId'.

The last thing I'll mention is that this is a password protected db, using AES-256 encryption (although it can also use Salsa20). Anytime you use the db, you have the option of using a password for encryption/decryption. Remember, if you setup the database using encryption, you will only be able to access it using that same password. When you're ready to change the password, you will need to call the update password function. If we again assume we created a change password method in our interface, it might look something like this:

class IFhirDb {
  IFhirDb();
  final ResourceDao resourceDao = ResourceDao();
  ...
    Future<Either<DbFailure, Unit>> updatePassword(String oldPassword, String newPassword) async {
    try {
      await resourceDao.updatePw(oldPassword, newPassword);
    } catch (error) {
      return left(DbFailure.unableToUpdatePassword(error: error.toString()));
    }
    return right(Unit);
  }

You don't have to use a password, and in that case, it will save the db file as plain text. If you want to add a password later, it will encrypt it at that time.

General Store

After using this for a while in an app, I've realized that it needs to be able to store data apart from just FHIR resources, at least on occasion. For this, I've added a second class for all versions of the database called GeneralDao. This is similar to the ResourceDao, but fewer options. So, in order to save something, it would look like this:

await GeneralDao().save('password', {'new':'map'});
await GeneralDao().save('password', {'new':'map'}, 'key');

The difference between these two options is that the first one will generate a key for the map being stored, while the second will store the map using the key provided. Both will return the key after successfully storing the map.

Other functions available include:

// deletes everything in the general store
await GeneralDao().deleteAllGeneral('password'); 

// delete specific entry
await GeneralDao().delete('password','key'); 

// returns map with that key
await GeneralDao().find('password', 'key'); 

FHIR® is a registered trademark of Health Level Seven International (HL7) and its use does not constitute an endorsement of products by HL7®

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add fhir_db

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  fhir_db: ^0.4.3

Alternatively, your editor might support or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:fhir_db/dstu2.dart';
import 'package:fhir_db/dstu2/fhir_db.dart';
import 'package:fhir_db/dstu2/general_dao.dart';
import 'package:fhir_db/dstu2/resource_dao.dart';
import 'package:fhir_db/encrypt/aes.dart';
import 'package:fhir_db/encrypt/salsa.dart';
import 'package:fhir_db/r4.dart';
import 'package:fhir_db/r4/fhir_db.dart';
import 'package:fhir_db/r4/general_dao.dart';
import 'package:fhir_db/r4/resource_dao.dart';
import 'package:fhir_db/r5.dart';
import 'package:fhir_db/r5/fhir_db.dart';
import 'package:fhir_db/r5/general_dao.dart';
import 'package:fhir_db/r5/resource_dao.dart';
import 'package:fhir_db/stu3.dart';
import 'package:fhir_db/stu3/fhir_db.dart';
import 'package:fhir_db/stu3/general_dao.dart';
import 'package:fhir_db/stu3/resource_dao.dart'; 

example/lib/main.dart

import 'package:fhir/r4.dart';
import 'package:fhir_db/r4.dart';
import 'package:flutter/material.dart';
import 'package:test/test.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();

  final resourceDao = ResourceDao();

  // await resourceDao.updatePw('newPw', null);
  await resourceDao.deleteAllResources(null);

  group('Playing with passwords', () {
    test('Playing with Passwords', () async {
      final patient = Patient(id: Id('1'));

      final saved = await resourceDao.save(null, patient);

      await resourceDao.updatePw(null, 'newPw');
      final search1 = await resourceDao.find('newPw',
          resourceType: R4ResourceType.Patient, id: Id('1'));
      expect(saved, search1[0]);

      await resourceDao.updatePw('newPw', 'newerPw');
      final search2 = await resourceDao.find('newerPw',
          resourceType: R4ResourceType.Patient, id: Id('1'));
      expect(saved, search2[0]);

      await resourceDao.updatePw('newerPw', null);
      final search3 = await resourceDao.find(null,
          resourceType: R4ResourceType.Patient, id: Id('1'));
      expect(saved, search3[0]);

      await resourceDao.deleteAllResources(null);
    });
  });

  final id = Id('12345');
  group('Saving Things:', () {
    test('Save Patient', () async {
      final humanName = HumanName(family: 'Atreides', given: ['Duke']);
      final patient = Patient(id: id, name: [humanName]);
      final saved = await resourceDao.save(null, patient);

      expect(saved.id, id);

      expect((saved as Patient).name?[0], humanName);
    });

    test('Save Organization', () async {
      final organization = Organization(id: id, name: 'FhirFli');
      final saved = await resourceDao.save(null, organization);

      expect(saved.id, id);

      expect((saved as Organization).name, 'FhirFli');
    });

    test('Save Observation1', () async {
      final observation1 = Observation(
        id: Id('obs1'),
        code: CodeableConcept(text: 'Observation #1'),
        effectiveDateTime: FhirDateTime(DateTime(1981, 09, 18)),
      );
      final saved = await resourceDao.save(null, observation1);

      expect(saved.id, Id('obs1'));

      expect((saved as Observation).code.text, 'Observation #1');
    });

    test('Save Observation1 Again', () async {
      final observation1 = Observation(
          id: Id('obs1'),
          code: CodeableConcept(text: 'Observation #1 - Updated'));
      final saved = await resourceDao.save(null, observation1);

      expect(saved.id, Id('obs1'));

      expect((saved as Observation).code.text, 'Observation #1 - Updated');

      expect(saved.meta?.versionId, Id('2'));
    });

    test('Save Observation2', () async {
      final observation2 = Observation(
        id: Id('obs2'),
        code: CodeableConcept(text: 'Observation #2'),
        effectiveDateTime: FhirDateTime(DateTime(1981, 09, 18)),
      );
      final saved = await resourceDao.save(null, observation2);

      expect(saved.id, Id('obs2'));

      expect((saved as Observation).code.text, 'Observation #2');
    });

    test('Save Observation3', () async {
      final observation3 = Observation(
        id: Id('obs3'),
        code: CodeableConcept(text: 'Observation #3'),
        effectiveDateTime: FhirDateTime(DateTime(1981, 09, 18)),
      );
      final saved = await resourceDao.save(null, observation3);

      expect(saved.id, Id('obs3'));

      expect((saved as Observation).code.text, 'Observation #3');
    });
  });

  group('Finding Things:', () {
    test('Find 1st Patient', () async {
      final search = await resourceDao.find(null,
          resourceType: R4ResourceType.Patient, id: id);
      final humanName = HumanName(family: 'Atreides', given: ['Duke']);

      expect(search.length, 1);

      expect((search[0] as Patient).name?[0], humanName);
    });

    test('Find 3rd Observation', () async {
      final search = await resourceDao.find(null,
          resourceType: R4ResourceType.Observation, id: Id('obs3'));

      expect(search.length, 1);

      expect(search[0].id, Id('obs3'));

      expect((search[0] as Observation).code.text, 'Observation #3');
    });

    test('Find All Observations', () async {
      final search = await resourceDao.getResourceType(
        null,
        resourceTypes: [R4ResourceType.Observation],
      );

      expect(search.length, 3);

      final idList = [];
      for (final obs in search) {
        idList.add(obs.id.toString());
      }

      expect(idList.contains('obs1'), true);

      expect(idList.contains('obs2'), true);

      expect(idList.contains('obs3'), true);
    });

    test('Find All (non-historical) Resources', () async {
      final search = await resourceDao.getAll(null);

      expect(search.length, 5);
      final patList = search.toList();
      final orgList = search.toList();
      final obsList = search.toList();
      patList.retainWhere(
          (resource) => resource.resourceType == R4ResourceType.Patient);
      orgList.retainWhere(
          (resource) => resource.resourceType == R4ResourceType.Organization);
      obsList.retainWhere(
          (resource) => resource.resourceType == R4ResourceType.Observation);

      expect(patList.length, 1);

      expect(orgList.length, 1);

      expect(obsList.length, 3);
    });
  });

  group('Deleting Things:', () {
    test('Delete 2nd Observation', () async {
      await resourceDao.delete(
          null, null, R4ResourceType.Observation, Id('obs2'), null, null);

      final search = await resourceDao.getResourceType(
        null,
        resourceTypes: [R4ResourceType.Observation],
      );

      expect(search.length, 2);

      final idList = [];
      for (final obs in search) {
        idList.add(obs.id.toString());
      }

      expect(idList.contains('obs1'), true);

      expect(idList.contains('obs2'), false);

      expect(idList.contains('obs3'), true);
    });

    test('Delete All Observations', () async {
      await resourceDao.deleteSingleType(null,
          resourceType: R4ResourceType.Observation);

      final search = await resourceDao.getAll(null);

      expect(search.length, 2);

      final patList = search.toList();
      final orgList = search.toList();
      patList.retainWhere(
          (resource) => resource.resourceType == R4ResourceType.Patient);
      orgList.retainWhere(
          (resource) => resource.resourceType == R4ResourceType.Organization);

      expect(patList.length, 1);

      expect(patList.length, 1);
    });

    test('Delete All Resources', () async {
      await resourceDao.deleteAllResources(null);

      final search = await resourceDao.getAll(null);

      expect(search.length, 0);
    });
  });

  group('Password - Saving Things:', () {
    test('Save Patient', () async {
      await resourceDao.updatePw(null, 'newPw');
      final humanName = HumanName(family: 'Atreides', given: ['Duke']);
      final patient = Patient(id: id, name: [humanName]);
      final saved = await resourceDao.save('newPw', patient);

      expect(saved.id, id);

      expect((saved as Patient).name?[0], humanName);
    });

    test('Save Organization', () async {
      final organization = Organization(id: id, name: 'FhirFli');
      final saved = await resourceDao.save('newPw', organization);

      expect(saved.id, id);

      expect((saved as Organization).name, 'FhirFli');
    });

    test('Save Observation1', () async {
      final observation1 = Observation(
        id: Id('obs1'),
        code: CodeableConcept(text: 'Observation #1'),
        effectiveDateTime: FhirDateTime(DateTime(1981, 09, 18)),
      );
      final saved = await resourceDao.save('newPw', observation1);

      expect(saved.id, Id('obs1'));

      expect((saved as Observation).code.text, 'Observation #1');
    });

    test('Save Observation1 Again', () async {
      final observation1 = Observation(
          id: Id('obs1'),
          code: CodeableConcept(text: 'Observation #1 - Updated'));
      final saved = await resourceDao.save('newPw', observation1);

      expect(saved.id, Id('obs1'));

      expect((saved as Observation).code.text, 'Observation #1 - Updated');

      expect(saved.meta?.versionId, Id('2'));
    });

    test('Save Observation2', () async {
      final observation2 = Observation(
        id: Id('obs2'),
        code: CodeableConcept(text: 'Observation #2'),
        effectiveDateTime: FhirDateTime(DateTime(1981, 09, 18)),
      );
      final saved = await resourceDao.save('newPw', observation2);

      expect(saved.id, Id('obs2'));

      expect((saved as Observation).code.text, 'Observation #2');
    });

    test('Save Observation3', () async {
      final observation3 = Observation(
        id: Id('obs3'),
        code: CodeableConcept(text: 'Observation #3'),
        effectiveDateTime: FhirDateTime(DateTime(1981, 09, 18)),
      );
      final saved = await resourceDao.save('newPw', observation3);

      expect(saved.id, Id('obs3'));

      expect((saved as Observation).code.text, 'Observation #3');
    });
  });

  group('Password - Finding Things:', () {
    test('Find 1st Patient', () async {
      final search = await resourceDao.find('newPw',
          resourceType: R4ResourceType.Patient, id: id);
      final humanName = HumanName(family: 'Atreides', given: ['Duke']);

      expect(search.length, 1);

      expect((search[0] as Patient).name?[0], humanName);
    });

    test('Find 3rd Observation', () async {
      final search = await resourceDao.find('newPw',
          resourceType: R4ResourceType.Observation, id: Id('obs3'));

      expect(search.length, 1);

      expect(search[0].id, Id('obs3'));

      expect((search[0] as Observation).code.text, 'Observation #3');
    });

    test('Find All Observations', () async {
      final search = await resourceDao.getResourceType(
        'newPw',
        resourceTypes: [R4ResourceType.Observation],
      );

      expect(search.length, 3);

      final idList = [];
      for (final obs in search) {
        idList.add(obs.id.toString());
      }

      expect(idList.contains('obs1'), true);

      expect(idList.contains('obs2'), true);

      expect(idList.contains('obs3'), true);
    });

    test('Find All (non-historical) Resources', () async {
      final search = await resourceDao.getAll('newPw');

      expect(search.length, 5);
      final patList = search.toList();
      final orgList = search.toList();
      final obsList = search.toList();
      patList.retainWhere(
          (resource) => resource.resourceType == R4ResourceType.Patient);
      orgList.retainWhere(
          (resource) => resource.resourceType == R4ResourceType.Organization);
      obsList.retainWhere(
          (resource) => resource.resourceType == R4ResourceType.Observation);

      expect(patList.length, 1);

      expect(orgList.length, 1);

      expect(obsList.length, 3);
    });
  });

  group('Password - Deleting Things:', () {
    test('Delete 2nd Observation', () async {
      await resourceDao.delete(
          'newPw', null, R4ResourceType.Observation, Id('obs2'), null, null);

      final search = await resourceDao.getResourceType(
        'newPw',
        resourceTypes: [R4ResourceType.Observation],
      );

      expect(search.length, 2);

      final idList = [];
      for (final obs in search) {
        idList.add(obs.id.toString());
      }

      expect(idList.contains('obs1'), true);

      expect(idList.contains('obs2'), false);

      expect(idList.contains('obs3'), true);
    });

    test('Delete All Observations', () async {
      await resourceDao.deleteSingleType('newPw',
          resourceType: R4ResourceType.Observation);

      final search = await resourceDao.getAll('newPw');

      expect(search.length, 2);

      final patList = search.toList();
      final orgList = search.toList();
      patList.retainWhere(
          (resource) => resource.resourceType == R4ResourceType.Patient);
      orgList.retainWhere(
          (resource) => resource.resourceType == R4ResourceType.Organization);

      expect(patList.length, 1);

      expect(patList.length, 1);
    });

    test('Delete All Resources', () async {
      await resourceDao.deleteAllResources('newPw');

      final search = await resourceDao.getAll('newPw');

      expect(search.length, 0);

      await resourceDao.updatePw('newPw', null);
    });
  });
} 

Download Details:

Author: MayJuun

Source Code: https://github.com/MayJuun/fhir/tree/main/fhir_db

#sqflite  #dart  #flutter 

Jeromy  Lowe

Jeromy Lowe

1599097440

Data Visualization in R with ggplot2: A Beginner Tutorial

A famous general is thought to have said, “A good sketch is better than a long speech.” That advice may have come from the battlefield, but it’s applicable in lots of other areas — including data science. “Sketching” out our data by visualizing it using ggplot2 in R is more impactful than simply describing the trends we find.

This is why we visualize data. We visualize data because it’s easier to learn from something that we can see rather than read. And thankfully for data analysts and data scientists who use R, there’s a tidyverse package called ggplot2 that makes data visualization a snap!

In this blog post, we’ll learn how to take some data and produce a visualization using R. To work through it, it’s best if you already have an understanding of R programming syntax, but you don’t need to be an expert or have any prior experience working with ggplot2

#data science tutorials #beginner #ggplot2 #r #r tutorial #r tutorials #rstats #tutorial #tutorials

Sival Alethea

Sival Alethea

1624305600

Learn Data Science Tutorial - Full Course for Beginners. DO NOT MISS!!!

Learn Data Science is this full tutorial course for absolute beginners. Data science is considered the “sexiest job of the 21st century.” You’ll learn the important elements of data science. You’ll be introduced to the principles, practices, and tools that make data science the powerful medium for critical insight in business and research. You’ll have a solid foundation for future learning and applications in your work. With data science, you can do what you want to do, and do it better. This course covers the foundations of data science, data sourcing, coding, mathematics, and statistics.
⭐️ Course Contents ⭐️
⌨️ Part 1: Data Science: An Introduction: Foundations of Data Science

  • Welcome (1.1)
  • Demand for Data Science (2.1)
  • The Data Science Venn Diagram (2.2)
  • The Data Science Pathway (2.3)
  • Roles in Data Science (2.4)
  • Teams in Data Science (2.5)
  • Big Data (3.1)
  • Coding (3.2)
  • Statistics (3.3)
  • Business Intelligence (3.4)
  • Do No Harm (4.1)
  • Methods Overview (5.1)
  • Sourcing Overview (5.2)
  • Coding Overview (5.3)
  • Math Overview (5.4)
  • Statistics Overview (5.5)
  • Machine Learning Overview (5.6)
  • Interpretability (6.1)
  • Actionable Insights (6.2)
  • Presentation Graphics (6.3)
  • Reproducible Research (6.4)
  • Next Steps (7.1)

⌨️ Part 2: Data Sourcing: Foundations of Data Science (1:39:46)

  • Welcome (1.1)
  • Metrics (2.1)
  • Accuracy (2.2)
  • Social Context of Measurement (2.3)
  • Existing Data (3.1)
  • APIs (3.2)
  • Scraping (3.3)
  • New Data (4.1)
  • Interviews (4.2)
  • Surveys (4.3)
  • Card Sorting (4.4)
  • Lab Experiments (4.5)
  • A/B Testing (4.6)
  • Next Steps (5.1)

⌨️ Part 3: Coding (2:32:42)

  • Welcome (1.1)
  • Spreadsheets (2.1)
  • Tableau Public (2.2)
  • SPSS (2.3)
  • JASP (2.4)
  • Other Software (2.5)
  • HTML (3.1)
  • XML (3.2)
  • JSON (3.3)
  • R (4.1)
  • Python (4.2)
  • SQL (4.3)
  • C, C++, & Java (4.4)
  • Bash (4.5)
  • Regex (5.1)
  • Next Steps (6.1)

⌨️ Part 4: Mathematics (4:01:09)

  • Welcome (1.1)
  • Elementary Algebra (2.1)
  • Linear Algebra (2.2)
  • Systems of Linear Equations (2.3)
  • Calculus (2.4)
  • Calculus & Optimization (2.5)
  • Big O (3.1)
  • Probability (3.2)

⌨️ Part 5: Statistics (4:44:03)

  • Welcome (1.1)
  • Exploration Overview (2.1)
  • Exploratory Graphics (2.2)
  • Exploratory Statistics (2.3)
  • Descriptive Statistics (2.4)
  • Inferential Statistics (3.1)
  • Hypothesis Testing (3.2)
  • Estimation (3.3)
  • Estimators (4.1)
  • Measures of Fit (4.2)
  • Feature Selection (4.3)
  • Problems in Modeling (4.4)
  • Model Validation (4.5)
  • DIY (4.6)
  • Next Step (5.1)

📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=ua-CiDNNj30&list=PLWKjhJtqVAblfum5WiQblKPwIbqYXkDoC&index=7
🔺 DISCLAIMER: The article is for information sharing. The content of this video is solely the opinions of the speaker who is not a licensed financial advisor or registered investment advisor. Not investment advice or legal advice.
Cryptocurrency trading is VERY risky. Make sure you understand these risks and that you are responsible for what you do with your money
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#data science #learn data science #learn data science tutorial #beginners #learn data science tutorial - full course for beginners

Sival Alethea

Sival Alethea

1624312800

Learn Java 8 - Full Tutorial for Beginners. DO NOT MISS!!!

Learn Java 8 and object oriented programming with this complete Java course for beginners.
⭐️Contents ⭐️

⌨️ (0:00:00) 1 - Basic Java keywords explained
⌨️ (0:21:59) 2 - Basic Java keywords explained - Coding Session
⌨️ (0:35:45) 3 - Basic Java keywords explained - Debriefing
⌨️ (0:43:41) 4 - Packages, import statements, instance members, default constructor
⌨️ (0:59:01) 5 - Access and non-access modifiers
⌨️ (1:11:59) 6 - Tools: IntelliJ Idea, Junit, Maven
⌨️ (1:22:53) 7 - If/else statements and booleans
⌨️ (1:42:20) 8 - Loops: for, while and do while loop
⌨️ (1:56:57) 9 - For each loop and arrays
⌨️ (2:14:21) 10 - Arrays and enums
⌨️ (2:41:37) 11 - Enums and switch statement
⌨️ (3:07:21) 12 - Switch statement cont.
⌨️ (3:20:39) 13 - Logging using slf4j and logback
⌨️ (3:51:19) 14 - Public static void main
⌨️ (4:11:35) 15 - Checked and Unchecked Exceptions
⌨️ (5:05:36) 16 - Interfaces
⌨️ (5:46:54) 17 - Inheritance
⌨️ (6:20:20) 18 - Java Object finalize() method
⌨️ (6:36:57) 19 - Object clone method. [No lesson 20]
⌨️ (7:16:04) 21 - Number ranges, autoboxing, and more
⌨️ (7:53:00) 22 - HashCode and Equals
⌨️ (8:38:16) 23 - Java Collections
⌨️ (9:01:12) 24 - ArrayList
📺 The video in this post was made by freeCodeCamp.org
The origin of the article: https://www.youtube.com/watch?v=grEKMHGYyns&list=PLWKjhJtqVAblfum5WiQblKPwIbqYXkDoC&index=9
🔥 If you’re a beginner. I believe the article below will be useful to you ☞ What You Should Know Before Investing in Cryptocurrency - For Beginner
⭐ ⭐ ⭐The project is of interest to the community. Join to Get free ‘GEEK coin’ (GEEKCASH coin)!
☞ **-----CLICK HERE-----**⭐ ⭐ ⭐
Thanks for visiting and watching! Please don’t forget to leave a like, comment and share!

#java #java 8 #learn java 8 #learn java 8 - full tutorial for beginners #beginners #java course for beginners.

Willie  Beier

Willie Beier

1596728880

Tutorial: Getting Started with R and RStudio

In this tutorial we’ll learn how to begin programming with R using RStudio. We’ll install R, and RStudio RStudio, an extremely popular development environment for R. We’ll learn the key RStudio features in order to start programming in R on our own.

If you already know how to use RStudio and want to learn some tips, tricks, and shortcuts, check out this Dataquest blog post.

Table of Contents

#data science tutorials #beginner #r tutorial #r tutorials #rstats #tutorial #tutorials