How to keep crash records of SUSI.AI Android with Crashlytics

At this stage of the development of SUSI.AI Android there are many changes and at times this results in inconsistencies and crashes of the app. One important questions we face is how to keep record of crashes so that we can improve our app. Using Crashlytics is a way keep record of crashes. The easiest way to add crashlytics in an app is to integrate the fabric plugin in Android Studio.

  • First create an account at fabric.
  • When you create account it will send you confirmation mail.
  • After clicking confirmation mail it will redirect you to fabric page.
  • It show you different platform option. Select android as platform.

  • For window/linux user select setting from file menu. For Mac user select Preferences from menu.
  • Select Plugins, click the Browse repositories button and search for “Fabric for Android”
  • Click install plugin button to download and install plugin.
  • You can see Fabric option in right side. Click on it and enter your credentials to sign in.
  • Select susi_android project and click next.
  • Fabric will list all the organizations you registered, so select the organization you want to associate the app with and click next. In my case organization is susi. 
  • Fabric will then list all of its kits.select Crashlytics and click  Next .
  •  Click the install button.It will add crashlytics in project.
  • Fabric wants to make changes in MainApplication  and AndroidManifest.xml files , so click the Apply button for the changes to happen.

  • Build and run your application to make sure that everything is configured properly. If your app was successfully configured, you will get an email sent instantly to the email address you used to sign up with fabric.
  • Now you can track crashes of your app on the dashboard of your  fabric account.
  • It will give you all details like 1.) How many users are affected and how many times app crashes with date. 2.) Details of  devices in which app crashes . 3.) Cause of errors

For more information use these links:

https://fabric.io/home

https://fabric.io/kits/android/crashlytics

Continue ReadingHow to keep crash records of SUSI.AI Android with Crashlytics

Data Scraping with Selenium

There still exists websites without any APIs. Scraping data from such sites can be very time-consuming and manual. I created samples for Open Event App generator. One of the samples that I created was for All Hands Hawaii 2016. This site didn’t have any API to enable easy data scraping.

How do we find out if a website is using an API or not?

Using Google Chrome, go to View → Developer → Developer Tools. Under the Network →XHR look for API endpoint with a bit of Hit and Trial method. (XHR stands for XMLHttpRequest)

However, what if there is no API being used in the site? How would you scrape data in that case? Will you now manually click onto every hyperlink on the site and visit every page to get the data by manually copying and pasting it? Could there be someone doing that manual job for you? Or better could there be “something” doing that job for you? Yes, It’s selenium.

Selenium Web Browser Automation

Selenium is a tool that automates the task of browsing through the internet. Although, technically it is used for web testing purposes but there is no restriction to it’s utility.

Let’s get started with basics of Selenium:-

INSTALLATION:
  1. Run the following command pip install selenium (Quick Tip: It is advised to use virtualenv)
  2. Selenium requires drivers to run. Different browsers use different drivers. Choose an appropriate driver for your browser. some common drivers are shown below (Source)-

Chrome: https://sites.google.com/a/chromium.org/chromedriver/downloads

Firefox: https://github.com/mozilla/geckodriver/releases

Safari: https://webkit.org/blog/6900/webdriver-support-in-safari-10/

BASIC FUNCTIONALITIES-SELENIUM:

Visit a page ( using the get() ):

 driver.get(urlofpage)

Navigating to various elements on the visited/current webpage:

  1. BY ID: 
    WebElement element = driver.findElement(By.id(“ui_elementid”));
  2. BY CLASS NAME:
    List<WebElement> cheeses = driver.findElements(By.className(“cheese”));
  3. BY TAG NAME:
    WebElement tag = driver.findElement(By.tagName(“tag_name”));
  4. BY CSS: WebElement cs = driver.findElement(By.cssSelector(“#”));
  5. BY LINK TEXT:
    WebElement cheese = driver.findElement(By.linkText(“blog”));

    If the element href is something like urlofpage?q=blog.

  6. BY XPATH:
  7.  List<WebElement> xp = driver.findElements(By.xpath(“//input”))

 

We can also use JavaScript along with Selenium. This might be a helpful thread for the same.

Another really good link for the same is http://www.marinamele.com/selenium-tutorial-web-scraping-with-selenium-and-python

Continue ReadingData Scraping with Selenium

Testing User Interactions with Espresso

Espresso is a testing framework which provides the facility to write the tests for user interactions and unitary tests. Since the release of its version 2 it is now a part of Android Testing Support Library.

The android apps we build at FOSSASIA follow rigorous testing methods. See this simple UI test  in the Phimp.me app using espresso to check if button and bottom navigation are displayed in an activity. You can also find our other tests related to API and databases in the Open Event Android App.

In this blog we learn how to add this facility to your app and write a test for a simple app that takes the name of from the user and prints it on the other screen on button click.

Adding espresso support

  • Install android support repository if not already present. You do it by following Tools -> Android -> SDK Manager
Tools you need to download for testing
  • Add the following dependencies to your app’s build.gradle file
dependencies {
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support.test:rules:0.5'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'

}
  • Specify the test instrumentation runner in default config
android {

    defaultConfig {

        // ....

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

    }

}

Before we begin with writing our tests knowing some basic components will help in understanding the code better. Writing tests with espresso is easy as its construction is similar to English language.

The three major components are 

  • ViewActions        : Allows you to interact with views
  • ViewAssertions   : Allows you to assert the state of a view.
  • ViewMatchers     : Allows you to locate a view in the current view hierarchy.

Suppose we want to test if text is displayed in the view, we can do it by

onView(withId(R.id.textView))                              //ViewMatcher

 .perform(click())                                         //ViewAction

 .check(matches(isDisplayed()));                           //ViewAssertion

Example

Consider an app which takes a name from the user and displays it on the next screen on clicking the button.

To perform this kind of test we will write

//Locate the view with id "name" and type the text "Natalie"

onView(withId(R.id.name)).perform(typeText("Natalie"));

//Locate the view with id "next" and click on it

onView(withId(R.id.next)).perform(click());

//Locate the view with id "new_name" and check its text is equal with "Natalie"

onView(withId(R.id.new_name)).check(matches(withText("Natalie")));

You can run tests by right clicking on the class and selecting the “run test” option. If the interaction is not as expected then the message will be displayed.

Up until now unit test were in main focus but as we move towards the more complex apps where user interaction plays an essential role, UI testing becomes equally necessary.

References:

Continue ReadingTesting User Interactions with Espresso

ButterKnife for Open Event Android

Open Event Android, by FOSSASIA has been coded in a very clean and systematic manner. One of the great things used in it is the ButterKnife library. It has made increased the readability and understand ability of the app’s code.

ButterKnife, developed and maintained by Jake Wharton(Square Inc.) is an Android library designed to make Java code less complex and efficient. The library operates with the use of annotations and hence, binds classes to the relevant annotations in Java and do the job.

First off, here’s the very first thing that you want to do before starting to use ButterKnife — Adding it’s dependency in the build.gradle file of your project.

compile 'com.jakewharton:butterknife:8.6.0
annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'

At FOSSASIA, we have extensively used this amazing library to simplify the code for our Open Event Android application. I hope this blog will help newcomers in understanding our code base in a better way.

We have the famous @Bindview annotation by ButterKnife to bind views to Android components without having to call R.FindViewById() method for every view. The following is a code sample from Open Event Android about the same.

@BindView(R.id.toolbar) Toolbar toolbar;

@BindView(R.id.nav_view) NavigationView navigationView;

@BindView(R.id.progress) ProgressBar downloadProgress;

@BindView(R.id.layout_main) CoordinatorLayout mainFrame;

@BindView(R.id.drawer) DrawerLayout drawerLayout;

@BindView(R.id.appbar) AppBarLayout appBarLayout;

Similarly, the ButterKnife library also handles events in an Android application and has annotations like @onClick, @onLongClick among others. So while using ButterKnife for an event, choose the appropriate event and the corresponding annotation followed by the Java method that is to be executed. Here is an example for the same.

@OnClick(R.id.submit)

public void submit(View view) {

// TODO submit data to server...

}

The ButterKnife library also helps to bind resources in your project.

It simplifies the View holder pattern inside a list adapter as illustrated in the following example.

public class MyAdapter extends BaseAdapter {

@Override public View getView(int position, View view, ViewGroup parent) {

   ViewHolder holder;

   if (view != null) {

     holder = (ViewHolder) view.getTag();

   } else {

     view = inflater.inflate(R.layout.whatever, parent, false);

     holder = new ViewHolder(view);

     view.setTag(holder);

   }

   holder.name.setText("John Doe");

   // etc...

   return view;

 }

static class ViewHolder {

   @BindView(R.id.title) TextView name;

   @BindView(R.id.job_title) TextView jobTitle;

   public ViewHolder(View view) {

     ButterKnife.bind(this, view);

   }

 }

}

The above code sample has been taken from http://jakewharton.github.io/butterknife/ and you can visit the site for further in-depth knowledge on ButterKnife.

How ButterKnife works?

I will be talking a bit about the working of the ButterKnife library. Firstly, I would like to introduce annotations concept in Java briefly before proceeding.

“In the Java, computer programming language, an annotation is a form of syntactic metadata that can be added to Javasource code. Classes, methods, variables, parameters and packages may be annotated.” As it is rightly said, Annotations can be of various uses like Getting information for the compiler, Compile-time and deployment-time processing, Runtime processing. However, please note that annotations can NOT modify and edit the existing classes. They can simply make more classes.

With this, I’m gonna continue on the working of ButterKnife. From the above discussion it must be clear now that ButterKnife is not changing any of our classes. It makes new classes to handle the code.

ButterKnife goes through all the files in your project and identifies the ButterKnife annotations used, if any. It then creates new classes for every annotation encountered, based on the annotations used. These new classes contain the general methods that would have been used in a project without ButterKnife. When we finally call ButterKnife.inject(this) , the inject()of all the new classes made by ButterKnife are called which then perform the desired function during execution.

Finally, try to go through the complete documentation for Butterknife and Java annotations for more information. 

Continue ReadingButterKnife for Open Event Android

How to teach SUSI.AI skills using external API’s

A powerful feature of SUSI is, that it can use external API’s to learn new skills. The generic syntax used here is:

Question string
!console:constant answer string + answer variable
{
 "url" : "API to be called",
 "path" : "path from where answer will be fetched"
}
eol

I will try to explain this syntax with the help of some useful examples. Let’s start with a very basic example:

I want SUSI to be able to answer questions like “What is the date today?”.

Let’s try to tackle this step by step. As we can infer from the above-written syntax, to teach SUSI a skill involving external API call, we need to be clear about five things namely:

  1. Question string i.e. “What is the date today?” (in this case).
  2. Constant answer string i.e. “The date today is ”
  3. The API to be called i.e. “http://calapi.inadiutorium.cz/api/v0/en/calendars/default/today
  4. The path which contains our answer.

When we visit this API url, we get the result as follows:

{
  "date":"2017-05-16",
  "season":"easter",
  "season_week":5,
  "celebrations":[
    {
      "title":"",
      "colour":"white",
      "rank":"ferial",
      "rank_num":3.13
    }
  ],
  "weekday":"tuesday"
}

The whole JSON object is represented with the ‘$’ sign. As date is a property of this object, so date can be accessed with “$.date” – this string is referred to as the path.

  1.  The last one is the answer variable.

We can see that the result of API url contains many “key:value” pairs. Answer variable is the value of the last key variable(i.e. date) referred in path string. This value is stored in a variable named $object$.

So our answer variable turns out to be $object$.   

Now, as we have all the five things ready with us, we can make our SUSI skill:

What is the date today?
!console:$object$
{
  “url”:“http://calapi.inadiutorium.cz/api/v0/en/calendars/default/today”,
  “path” : “$.date”
}
eol

Kudos! But where to feed this skill and check if SUSI chat bot is able to answer “What is the date today?” appropriately.

To test the working of a skill:

  1. Open dream.asksusi.com, write whatever name you like for the pad and then click OK.

  2. Replace the data written on your pad with the skill code you created. You don’t need to save it, it is saved automatically. Now your page should look something like this:
  3. To check if this skill is working properly:
  • Visit SUSI chat bot.
  • In the textbox below, write dream followed by the name of your pad and then press Enter key. SUSI will reply with “dreaming enabled for YOUR-PAD-NAME”.
  • Now write the question string i.e. What is the date today? and you should be shown today’s date!

For more clarity, refer to this image:


Great, that you made it! You can now contribute skills by making a PR to
this repository and see those skills live on SUSI without enabling any dream! Just ask your question and get your own skilled answers.

Let’s learn more about skills by introducing some changes to this question. Let’s go through some variations of this question:

  • We want SUSI to answer the same when we ask “What is the date today?” or “today’s date”. To achieve this we can use ‘|’ symbol when writing our question.

The new syntax of our skill will be:

What is the date today? | today’s date?
!console:$object$
{
“url” : “http://calapi.inadiutorium.cz/api/v0/en/calendars/default/today”,
“path” : “$.date”
}
eol
  • We want SUSI to answer according to the question. To make it answer all the questions like today’s date?, tomorrow’s date? or yesterday’s date?

The new syntax of our skill will be:

*’s date?
!console:$object$
{
“url” : “http://calapi.inadiutorium.cz/api/v0/en/calendars/default/$1$”,
“path” : “$.date”
}
eol

Here * acts as a wildcard character. That means * will be “today” in “today’s date” and “tomorrow” in “tomorrow’s date”. $1$ is the variable which stores the value in *.

Let’s dive into more examples:

  1. Sometimes we may need 2 wildcard characters in our question:
* plot of * | * summary of *
!console:$object$
{
  "url":"http://api.tvmaze.com/singlesearch/shows?q=$2$",
  "path":"$.summary"
}
eol   

The api used above is to tell the plot of a tv show. We need to query this API with the name of the show.

For questions like “Tell me the plot of Game of Thrones” or “What is the plot of Game of Thrones”, we want to ignore the string before “plot of” and store the string after it. This string stored can be used to query the API later.

The naming of the variables for storing the values in * is done number wise. The value of the first * in the question is stored in $1$, for the second * it is in $2$ and so on…

Now the above-written skill should make sense to everyone. Let’s see the skill in action:

 

  1. What if we want two answers from the same API. Consider this question:
    We have a public API to check the details of a space agency. We need the abbreviation of the space agency and append that to the API.

For example, when we visit https://launchlibrary.net/1.2/agency/ISRO, we get the following as output:

We want SUSI to answer the full form of a space agency along with its country code.

The skill used for it:

what is the full form of * and its country code?
!console:Full form - $name$, Country code - $countryCode$
{
  "url":"https://launchlibrary.net/1.2/agency/$1$",
  "path":"$.agencies[0]"
}
eol

How this skill works?

Let’s breakdown the path variable and check what does it leads to. The ‘$’ will fetch the whole object.

Further, “$.agencies[0]” will fetch this -:

{
  "Id":31,
  "name":"Indian Space  Research Organization",
  "countryCode":"IND",
  "abbrev":"ISRO",
  "Type":1,
  "infoURL":"http:\/\/www.isro.org\/",
 "wikiURL":"http:\/\/en.wikipedia.org\/wiki\/Indian_Space_Research_Organiation",
  "infoURLs":["http:\/\/www.isro.org\/"]
}

To fetch values of any of the keys, we can use the key name enclosed in ‘$KEY_NAME$’. The  value of that key will be automatically stored in this variable i.e. $KEY_NAME$.

Hence we use $name$ and $countryCode$ in our skill, to get the required answer.

The skill in action:

The same way we can use other API’s and contribute new skills to SUSI. To help you get started, see the public API’s repository available here. As said before, you can contribute skills by making a PR to this repository and see those skills live in SUSI!

Continue ReadingHow to teach SUSI.AI skills using external API’s

The Pocket Science Lab Hardware

PSLab is a USB powered, multi-purpose data acquisition and control instrument that can be used to automate various test and measurement tasks via its companion android app, or desktop software. It is primarily intended for use in Physics and electronics laboratories in order to enable students to perform more advanced experiments by leveraging the powerful analytical and visualization tools that the PSLab’s frontend software includes.

Real time measurement instruments require specialized analog signal processors, and dedicated digital circuitry that can handle time critical tasks without glitches. The PSLab has a 64MHz processor which runs a dedicated state machine that accepts commands sent by the host software, and responds according to a predefined set of rules.

It does not deviate from this fixed workflow, and therefore can very reliably measure time intervals at the microsecond length scales, or output precise voltage pulses.

In contrast, a GHz range desktop CPU running an OS is not capable of such time critical tasks under normal conditions because a multitude of tasks/programs are being simultaneously handled by the scheduler, and delays of the order of milliseconds might occur between one instruction and the next in a given piece of software. The PSLab combines the flexibility and reliability of its dedicated processor, and the high computational and visualization abilities of the host computer/phone’s processor to create a very advanced end product.

And now, a flow diagram to illustrate the end product[1]:

An outline of how this state machine works

But first, you might be interested in the complete set of features of this instrument, and maybe screenshots from a few experiments . Here’s a link to a blog post by Praveen Patil outlining the oscilloscope, controls , and the data logger.

From the flow diagram above, it is apparent that the Hardware communicates to the host PC via a bidirectional communication channel, carries out instructions, and might even communicate to a secondary slave via additional communication channels.

The default state of the PSLab hardware is to listen to the host. The host usually sends a 2- byte header first, the first byte is a broad category classifier, and the second refers to a specific command. Once the header is received , the PSLab either starts executing the task , or listens for further data that may contain configuration parameters

An example for configuring the state of the digital outputs [These values are stored in header files common to the host as well as the hardware:

  • Bytes sent by the host :
    • Byte #1 : 8     #DOUT
    • Byte #2 : 1     #SET_STATE
    • Byte #3 : One byte representing the outputs to be modified, and the nature of the modification (HIGH / LOW ). Four MSB bits contain information regarding the  digital outputs SQR1 to SQR4 that need to be toggled, and four LSBs contain information regarding the state that each selected output needs to be set to.
  • Action taken by the hardware:
    • Move to the set_state routine
    • Set the output state of the relevant output pins (SQR1-4) if required.
    • Respond with an acknowledgement
    • Move back to listening state
  • Bytes Returned by the hardware:
    • Byte #1 : 254 ACKNOWLEDGE. SUCCESSFUL.

In a similar manner, instruments ranging from oscilloscopes, frequency counters, capacitance meters, data buses etc are all handled.

For function calls that are time consuming, the communication process might be split into separate exchanges for initialization, and data download. One such example is the Oscilloscope capture routine. The first information exchange sets the parameters for data acquisition, and the second occurs when the acquisition process is complete.

Host-Side Scripts and Software

The software running on the host runs either a dedicated script that sequentially acquires data or executes control tasks , or it runs an event loop where user inputs are used to determine the acquisition task to be executed.

An example of a pulse sensor designed with just the voltmeter and a digital output of the PSLab.

A photo transistor is connected to the SEN input of the PSLab, and the host software reads the voltage on SEN at fixed intervals.

The conductance of the photo transistor fluctuates along with the incident light intensity, and this is translated into a voltage value by the internal signal processor of the SEN input.

When the photo sensor is covered with a finger, and a bright light is passed through the finger, a time linked plot of these voltage fluctuations reflects the fluctuations in blood pressure, and therefore has the same frequency of the heart beat of the owner of this finger.

* The digital output is used to power a white LED being used as the light source here

Bibliography:

[1] : Original content developed for the SEELablet’s first revision, from which PSLab is derived.

Continue ReadingThe Pocket Science Lab Hardware

Sine Wave Generator

PSLab by FOSSASIA can generate sine waves with arbitrary frequencies. This is very helpful to teachers, students and electronic enthusiasts to study about different frequencies and how systems respond to them. In the device, it uses digital signal processing to derive a smooth sine wave. Except to digital implementation, there are conventional analog implementations to generate a sine wave.

Image from https://betterexplained.com/articles/intuitive-understanding-of-sine-waves/

sine_wave

The most famous method to generate a sine wave is the Wien Bridge Oscillator. It is a frequency selective bridge with a range of arbitrary frequencies. This oscillator has a good stability when it is functioning at its resonance frequency while maintaining a very low signal distortion.           Let’s take a look at this circuit. We can clearly see that there is a series combination of a resistor and a capacitor at A and a parallel combination of a resistor and a capacitor at B joining at the non-inverting pin of the OpAmp. The series combination of RC circuit is nothing but a high pass filter that allows only high frequency components to pass through. The parallel combination of RC circuit is a Low pass filter that allows only the low frequency components of a signal to pass through. Once these two are combined, a band pass filter is created allowing only a specific frequency component to pass through.

It is necessary that the resistor value and the capacitor values should be the same in order to have better performance without any distortion. Assuming that they are same, using complex algebra we can prove that the voltage at V+(3) is one third of the Voltage coming out from the pin (1) of OpAmp.

Using the resonance frequency calculation using RC values, we can determine the frequency of the output sine wave.

f=1/2RC

The combination of two resistors at the inverting pin of the Op Amp controls the gain factor. It is calculated as 1+R1/R2. Since the input to the non-inverting terminal is 1/3 of the output voltage, this gain factor should be maintained at 3. Values greater than 3 will cause a ramping behavior in the sine wave and values below 3 will show an attenuation. So the gain should be set preciously.

Equating 1+R1/R2 to 3, we can obtain a ratio for R1/R2 as 2. That implies R1 should be as twice the resistance of R2. Make sure these resistances are in the power of kilo Ohms. That is to ensure that the leakage current is minimum to the Op Amp. Let’s select R1 = 200K and R2 = 100K

This oscillator supports a range of frequencies. Let’s assume we want to generate a sine wave having 500 Hz. Using f=1/2RC, we can choose arbitrary values for R and C. Substituting values to the formula yields a value for RC = 318 x10e-6

Using practical values for R as 10k, C value can be approximated to 33nF. This oscillator is capable of generating a stable 500 Hz sinusoidal waveform. By changing the resistive and capacitive values of block A and B, we can generate a wide range of frequencies that are supported by the Op Amp because Op Amps have a limited bandwidth it can be functional inside.

It’s worth to note a few facts about generating sine waves using a digital implementation. In analog circuitry, the component values have a tolerance which makes the calculations not perfectly align with the real values. Due to this reason, the actual output will differ from the desired output. In our example to generate 500 Hz sine wave, the capacitors and resistors may have different values and they may have not matched. But with a digital implementation, we can achieve the accuracy and flexibility we require.

External Links:

 

Continue ReadingSine Wave Generator

Regulating Voltage in PSLab

Electronic components are highly sensitive to voltages and currents across them. Most of the devices in the current market work in the voltage levels of 3.3V, 5V, 12V and 15V. If they are provided with a different voltage than the one required by the vendor, they would not function. If the voltage supplied is higher, they might burn off. The PSLab device requires separate voltage levels such as 3.3V and 5V for its operation.

There are commercial voltage regulators available in the market designed with advanced feedback techniques and models. But we can create out own voltage regulator. In this blog post, I am going to introduce you to a few basic models capable of regulating voltage to a desired level.

Current implementation of PSLab device uses a voltage regulator derived using a zener-resistor combination. This type of regulators have a higher sensitivity to current and their operation may vary when the supplied or the drawn current is lower than the expected values. In order to have a stable voltage regulation, this combination needs to be replaced with a much stable transistor-zener combination.

Before go into much details, let’s get to know a few basic concepts and devices related to.

Zener Diode

Zener DiodeZener diode is a type of diode which has a different operational behavior than the general diode. General diodes allow current to flow only in one direction. If a current in the reverse is applied, they will break and become unusable after a certain voltage level known as Breakdown Voltage. But Zener diodes are specifically designed to function desirably once this break down voltage has been passed and unlike general diode, it can recover back to normal when the voltage is removed or reduced.

Transistor

This is the game changing invention of the 20th century. There are two types of Bipolar Junction Transistors (BJT) available in the market. They are known as NPN and PNP transistors. The difference is based on the polarity of diodes used.

An NPN transistor can be modeled as a combination of two diodes –[NP → PN]– and a PNP transistor can be modeled as –[PN → NP]– using two diodes.

There are three pins to take notice in BJTs. They are illustrated in the diagram shown here;

  1. Base
  2. Collector
  3. Emitter

The amazing fact about BJTs is that the amount of current provided to the Base terminal will control the flow of current going through Collector and Emitter. Also note that always there is a voltage drop across the Base terminal and the Emitter terminal. This typically takes a value of 0.7 V

Voltage Divider

This is the most basic type of voltage regulator. It simply divides the voltage supplied by the battery with the ratio R1:R2. In the following configuration, the output voltage can be calculated using the voltage division rule;

Which is equal to 12 * 100/(100+200) = 4 V

There is a huge drawback with this design. The above calculation is valid only if there is no load impedance is present at the output terminals.

Generally there will be a load impedance and the supplied voltage cannot be easily calculated as the load impedance is unknown to the regulator.

Resistor-Zener Voltage Regulator

Due to the load dependability of the previous model with the load, an improved model can be introduced as follows. This is the current implementation of voltage regulator in PSLab device.

Unlike the previous model, this model ensures that the output voltage will be maintained constant across the output terminals within a range of supply voltage values.

Let’s assume the supply voltage is increased. Then the current flow through the zener diode will increase in order to maintain a constant voltage across the output terminals. In case if the supply voltage drops, then the zener current will decrease and a stable voltage across the output terminals will be maintained.

This design also comes with a slight draw back. This can be explained using the characteristic curve of a zener diode. (Figure is taken from : http://www.electronics-tutorials. ws/diode/diode_7.html)

For a zener diode to maintain a constant voltage level across output terminals, there should be a minimum current flowing through the diode. If this current is not flowing in the zener, there won’t be a regulation. Assume there is a very low load impedance. Then the current supplied by the source will find an easier path to flow other than through the diode. This will affect the regulatory circuit and the desired voltage will not appear across the output terminals.

To compensate the drawback, a much improved design is available using transistors.

Transistor-Zener Voltage Regulator

This is the proposed improvement to the voltage regulatory circuit in PSLab device. In this model, the zener diode is taken away from the load circuit as the current to the load is supplied from the transistor directly. This avoids current limitations to the zener diode had in the previous model and transistor acts as a bridge.

A small current through the Base terminal (1) will support a higher current flow through the output terminal via Collector (2) and Emitter (3). This amplification ratio is in the range of few hundreds for a typical BJT.

A capacitor has been added to compensate ripples from the supply source. If a higher current flow is required through the output terminals, the NPN transistor can be replaced by a Darlington pair.

Using a 5.6 V zener diode and MMBT3904/6 transistors, this model has been implemented in the newest version of PSLab device. They will be supplying a constant voltage of +/- 5V to V+ and V- pins in the device.

External Links:

Continue ReadingRegulating Voltage in PSLab

Using Flexbox for Responsive Layout in Open Event Webapp

Recently, I tackled the issue of alignment of different buttons and input bar in the Open Event Webapp. The major challenge was to create a responsive design which adapts well on all the platforms: desktop, tablets and mobile. Doing it using grid layout provided by Bootstrap was rather tough and complicated and I solved the problem using the flexbox.

What is Flexbox?

Flexible Boxes, also called as Flexbox, is a new layout mode introduced in CSS3. The best part of using flexbox is that it ensures that the elements behave in a predictable manner when the page layout accommodates different screen sizes and display devices. In other words, it helps us in making a responsive design in a simpler manner. It is an alternative to block elements being floated and manipulated using media queries. Using Flexbox, a container and its children can be arranged in any direction: up, down or left and right. Size is flexible and elements inside the flexbox can grow or shrink to occupy unused space or prevent overflow respectively.

The difference with grid layouts?

There is a slight difference between flexbox and grid layouts which makes one suitable for creating a fully complete layout and the other not so much.

Ideally, grids (provided by Bootstrap for example) are used for creating an entire layout. Flexbox is suited for styling separate containers such as navbars for example.

flex_terms.png

                                 Structure of Flexbox Container

How did I solve it?

First I defined a container which acted as a wrapper for all the buttons and the search bar. Now, to convert this container into an actual flexbox, we have to add display: flex property to it.

.container {
 display: flex;
}

Did the issue got solved? It doesn’t look so. The container enclosed in the red border is the flexbox.

flexnogrow.png

As we can see from the picture itself, the elements are quite close to each other and a lot of space is wasted. Fortunately, flexbox provides us a handy property called flex-grow which deals with this type of problem. It defines the ability for a flex item to grow if necessary. That it, it tells how much amount of the available space inside the flex container the item is allowed to take. If all the items have flex-grow set to 1, then the remaining space in the container would be equally distributed to all the items. In a similar way, if an item has flex-grow set to 2, then it would occupy twice the amount of available space when compared to the other items.

So, I applied the flex-grow:1 on the items.

.list-btn {
   flex-grow: 1;
}

.search-filter {
   flex-grow: 1;
}
.starred-btn {
   flex-grow: 1;
}

.calendar-btn {
   flex-grow: 1;
}

How does it look now?

flexbox_initial.png

Much better. But is the problem solved now? No. There is one more thing that we haven’t checked yet. Yes. It’s the responsiveness. We haven’t yet checked how it displays on tablets and mobiles yet? Let’s test and check and what we see.

mobilenowrap.png

Ok. Something is not right. The items are squeezing together. That doesn’t look good. We don’t want the elements to wrap on a single line. What we actually want is that the items would stack on top of each other when the screen size is reduced. That would look much more neat and tidy.

To change this default behavior of wrapping of items, we use the flex-wrap property on the container. Specifying flex-wrap: wrap does the trick and the items wrap as needed.

mobilewrap2.pngmobilewrap1.png

 

.container {
   display: flex;
   flex-wrap: wrap;
}

The result looks much better now. The items wrap on a single line only when there is enough space available. Otherwise, they wrap up onto multiple lines from top to bottom.

Flexbox is a great tool for creating custom layouts for separate containers. Apart from the properties discussed here, there are a plethora of other options which can be used to customize the behavior of flexbox and the items contained inside it.  Check out the links below for more information!

Resources:

Continue ReadingUsing Flexbox for Responsive Layout in Open Event Webapp

How to add the Google Books API to SUSI AI

SUSI.AI is a Open Source personal assistant. You can also add new skills to SUSI easily. In this blog post I’m going to add Google’s Books API to SUSI as a skill. A complete tutorial on SUSI.AI skills is n the repository. Check out Tutorial Level 11: Call an external API here and you will understand how can we integrate an external API with SUSI AI.

To start adding book skills to SUSI.AI , first go to this URL http://dream.susi.ai/  > give a name in the text field and press OK.

 

Copy and paste above code to the newly opened etherpad.

Go to this url http://chat.susi.ai to test new skill.

Type “dream blogpost” on chat and press enter. Now we can use the skills we  add to the etherpad.

To understand  Google’s book API use this url.Your request url should be like this:

[code]https://www.googleapis.com/books/v1/volumes?q=BOOKNAME&amp;amp;amp;amp;amp;amp;amp;amp;key=yourAPIKey[/code]

 

you should replace APIKey with your API key.

To get started you first need to get an API key.

Go to this url > click GET A KEY button which is in right top > and select “Create a new project”

Add name to a project and click “CREATE AND ENABLE API” button

Copy your API key and replace the API Key part of request URL.

Paste request url on your browser address bar and replace BOOKNAME part with “flower” and go to the URL. It will give this JSON.

We need to get the full name of books which is in items array to that we have to go through this hierarchy
items array >first item>volumeInfo >title
Go to the etherpad we made before and paste the following code.


is there any book called * ?
!console:did you mean "$title$" ? Here is a link to read more: $infoLink$
{
"url":"https://www.googleapis.com/books/v1/volumes?q=$1$&key=AIzaSyCt3Wop5gN3S5H0r1CKZlXIgaM908oVDls",
"path":"$.items[0].volumeInfo"
}
eol

first line of the code “is there any book called *?” is the question user ask. *  is the variant part  of question. that part can be used in the code by $1$ , if there more variants we can add multiple asterisk marks and refer by using corresponding number Ex: $1$,$2$,$3$
  • In this code  “path” : “$.items[0].volumeInfo”
  • $  represents full JSON result.
  • items[0] for get first element
  • .volumeInfo is to refer  volumeInfo object
!console:did you mean “$title$” ?  Here is a link to read more: $infoLink$
this line produce the output.
  • $title$ this one is for refer the “title” part of data that comes from “path”
  • $infoLink$ this one gives link to more details

Now go to the chat UI and type again “dream blogpost”. And after it shows “dreaming enabled” type in”is there any book called world war?”. It will result in the following.

This  is a simple way to add any service to SUSI as a skill.

Continue ReadingHow to add the Google Books API to SUSI AI