text:
---
layout: "unit"
title: "14.04.03: The Little Engines That Can!"
path: "/curriculum/units/2014/4/14.04.03.x.html"
unitTitle: "The Little Engines That Can!"
unitAuthor: "Carol Boynton"
---

Contents of Curriculum Unit 14.04.03:

Introduction

Rationale

Concepts/Content

Biology Fundamentals

Engineering and Movement

Strategies/Methods

Classroom Activities

Resources

Appendix

Notes

To Guide Entry

Introduction

Wally Piper's

The Little Engine That Could

is one of the greatest tales of motivation and the power of positive thinking ever told. In this well-loved classic, a little train carrying toys to all of the good boys and girls is confronted with a towering, seemingly impassable mountain.  This hard work does not go unrewarded, for the Little Engine does achieve its goal. My unit reaches out to students in this same positive way, first empowering them with knowledge of their bodies and biological systems and then positioning them as engineers who direct the movements their bodies make.  Just as the Little Blue Engine's mantra "I think I can--I think I can" keeps him going, my second graders will "know they can!"

The human body are organs intricately connected and functioning in unison and harmony.  The organs are made of even smaller units we call "cells".  The cell is made from even smaller units called molecules and the molecules are made from the tiniest of all substances we call atoms and the breakdown into even smaller and smaller features continues from there and it does not cease till we are no longer able to observe those individual units.  Thus, in a way, the smallest of all engines that we can observe, "the atom," manages to do some amazing things by working cooperatively and in unison with other atoms to build larger structures.  So these little engines can and do by following the principles of cooperative behavior and it is a critical element that I would like to demonstrate in this unit through objective lessons and activities.

Rationale

Edgewood School is an arts-integrated magnet school with a focus on providing a positive learning environment that encourages inquiry, self-discovery, and independent thinking.  This approach to learning inherently allows, supports and encourages cross-curricular teaching and embraces all types of learners.   Our neighborhood/magnet school setting is a rewarding environment, with students coming to school each day from a variety of home circumstances and with differences in academic levels.  As a result of these variables, the children have differing levels of background knowledge and life experiences.  Reaching students through inquiry and discovery opens doors and minds to learning opportunities.

Concepts/Content

Our students are fortunate that New Haven Public Schools had mandated recess in our district.  Each school day students from pre-school through eighth grade must have 20 minutes of physical activity in addition to Physical Education class.  This additional time for focus on health and exercise will allow me to incorporate my curriculum unit seamlessly into our day.  Many school days have inclement weather but students still need opportunities to be active during the day.  This unit will help offer variety and fun as students learn physics and engineering through their own actions.

This curriculum unit integrates science and physical activity and blends with a current district requirement for second grade –

The Michigan Model for Health

.  I intend to use my curriculum unit to introduce students to the basic structures and functions of the human body and how they relate to personal health. The instructional objectives are: students will learn the major organs in the body and their function; students will learn the major systems of the body; students will learn behaviors that will help protect the body structure.  Students will learn that these systems work as a team to support each other to keep our bodies healthy and strong.  Specifically, this unit will touch on the circulatory, digestive, immune and musculoskeletal systems to provide a framework for understanding that what we do with our body matters.   The culmination of the unit includes projects on our human biology as well as a focus on specific physical activity to take place throughout the school year, using yoga, calisthenics, and aerobics to demonstrate some of the physics of the human body.

Biology Fundamentals

Circulation and the Heart (Pumps and Fluid flow)

The heart and circulatory system, called thecardiovascular system, make up the network that delivers blood to the body's tissues. With each heartbeat, blood is sent throughout our bodies, carrying oxygen and nutrients to all of our cells.

Every day the approximately 10 pints (5 liters) of blood in your body travel many times through about 60,000 miles (96,560 kilometers) of blood vessels that branch and cross, linking the cells of our organs and body parts. From the hard-working heart, to our thickest arteries, to capillaries so thin that they can only be seen through a microscope, the cardiovascular system is our body's lifeline.

The circulatory system is composed of the heart and blood vessels, including arteries, veins, and capillaries. Our bodies actually have two circulatory systems: the pulmonary circulation is a short loop from the heart to the lungs and back again, and the systemic circulation (the system we usually think of as our circulatory system) sends blood from the heart to all the other parts of our bodies and back again.

The Heart

The heart is the key organ in the circulatory system. As a hollow, muscular pump, its main function is to push blood throughout the body. It usually beats from 60 to 100 times per minute, but can go much faster when necessary. It beats about 100,000 times a day, more than 30 million times per year, and about 2.5 billion times in a 70-year lifetime.

The heart gets messages from the body that tells it when to pump more or less blood depending on a person's needs. When we're sleeping, it pumps just enough to provide for the lower amounts of oxygen needed by our bodies at rest. When we're exercising or frightened, the heart pumps faster to get more oxygen to our bodies. Oxygen is carried by proteins called hemoglobin in the blood and give the blood its red color. These transport the oxygen to all parts of the body.  When something goes wrong with these or when we lose blood we are unable to distribute the oxygen effectively.

The heart has four chambers that are enclosed by thick, muscular walls. It is positioned between the lungs and just to the left of the middle of the chest cavity. The bottom part of the heart is divided into two chambers called the right and left ventricles, which pump blood out of the heart. The upper part of the heart is made up of the other two chambers of the heart, the right and left atria, receive the blood entering the heart.

The Role of Blood Vessels

Blood vessels carrying blood away from the heart are calledarteries. They are the thickest blood vessels, with muscular walls that contract to keep the blood moving away from the heart and through the body. In the systemic circulation, oxygen-rich blood is pumped from the heart into the aorta. This large artery curves up and back from the left ventricle, then heads down in front of the spinal column into the abdomen.Two coronary arteries branch off at the beginning of the aorta and divide into a network of smaller arteries that provide oxygen and nourishment to the muscles of the heart.

Unlike the aorta, the body's other main artery, the pulmonary artery, carries oxygen-poor blood. From the right ventricle, the pulmonary artery divides into right and left branches, on the way to the lungs where blood picks up oxygen.

Arterial walls are composed of three layers:  the endothelium is on the inside and provides a smooth lining for blood to flow over as it moves through the artery; the media is the middle part of the artery, made up of a layer of muscle and elastic tissue; the adventitia is the tough covering that protects the outside of the artery.  As they get farther from the heart, the arteries branch out into arterioles, which are smaller and less flexible.

Blood vessels that carry blood back to the heart are called veins. They are not as muscular as arteries, but they contain valves that prevent blood from flowing backward. Veins have the same three layers that arteries do, but they are thinner and less flexible. The two largest veins are the superior and inferior vena cavae. The terms superior and inferior do not mean that one vein is better than the other, but that they are located above (superior) and below (inferior) the heart.

A network of tiny capillaries connects the arteries and veins. Even though they are tiny, the capillaries are one of the most important parts of the circulatory system because it is through them that nutrients and oxygen are delivered to the cells.  All of these important body parts in collaboration allow us to stand, walk, run, exercise or just sit down.

Bones and What They Do

From our head to our toes, bones provide support for our bodies and help form our shape. The skull protects the brain and forms the shape of our face. The spinal cord is a passageway for messages between the brain and the body and protected by the backbone, or spinal column.

The ribs form a cage that shelters the heart, lungs, liver, and spleen, and the pelvis helps protect the bladder, intestines, and in women, the reproductive organs.  Although they are very light, bones are strong enough to support our entire weight.  The human skeleton has 206 bones, which begin to develop before birth. When the skeleton first forms, it is made of flexible cartilage, but within a few weeks it begins the process of ossification. Ossification is when the cartilage is replaced by hard deposits of calcium phosphate and stretchy collagen, the two main components of bone. It takes about 20 years for this process to be completed.

The bones of children are smaller than those of adults and contain "growing zones" called growth plates. These plates consist of columns of multiplying cartilage cells that grow in length, and then change into hard, mineralized bone. Because girls mature at an earlier age than boys, this process is completed at an earlier age.

2

Growing Bones

Bone-building continues throughout life, as the body constantly renews and reshapes the bones' living tissue. Bone contains three types of cells: osteoblasts, which make new bone and help repair damage; osteocytes, mature bone cells which help continue new born formation; and osteoclasts, which break down bone and help to sculpt and shape it.  Osteoclasts are very active in kids and teens, working on bone as it is remodeled during growth. They also play an important role in the repair of fractures.

Bones are made up of calcium, phosphorus, sodium, and other minerals, as well as the protein collagen. Calcium is needed to make bones hard, which allows them to support body weight. Bones also store calcium and release some into the bloodstream when it's needed by other parts of the body. The amount of certain vitamins and minerals that you eat, especially vitamin D and calcium, directly affects how much calcium is stored in the bones.

The soft bone marrow inside many of the bones is where most of the blood cells are made. The bone marrow contains stem cells, which produce the body's red blood cells and platelets, and some types of white blood cells. Red blood cells carry oxygen to the body's tissues, and platelets help with blood clotting when someone has a cut or wound. White blood cells help the body fight infection.

Bones are made up of two types of bone tissues:  compact bone is the solid, hard, outside part of the bone. This type of bone makes up the most of the human skeleton. It looks like ivory and is extremely strong. Holes and channels run through it, carrying blood vessels and nerves from the periosteum, the bone's outer membrane covering; cancellous bone, which looks like a sponge, is inside the compact bone. It is made up of a mesh-like network of tiny pieces of bone called trabeculae. This is where red and white blood cells are formed in the marrow.

Bones are fastened to other bones by long, fibrous straps called ligaments. Cartilage, a flexible, rubbery substance in our joints, supports bones and protects them where they rub against each other.

Muscles and What They Do

Bones don't work alone — they need help from the muscles and joints. Muscles pull on the joints, allowing us to move. They also help your body perform other functions so we can grow and remain strong, such as chewing food and then moving it through the digestive system.

The human body has more than 650 muscles, which make up half of a person's body weight. They are connected to bones by tough, cord-like tissues called tendons, which allow the muscles to pull on bones. If you wiggle your fingers, you can see the tendons on the back of your hand move as they do their work.

Humans have three different kinds of muscle:

Skeletal muscle is attached to bone, mostly in the legs, arms, abdomen, chest, neck, and face. Skeletal muscles are called striated because they are made up of fibers that have horizontal stripes when viewed under a microscope. These muscles hold the skeleton together, give the body shape, and help it with everyday movements (known as voluntary muscles because you can control their movement). They can contract (shorten or tighten) quickly and powerfully, but they tire easily and have to rest between workouts.

Smooth, or involuntary, muscle is also made of fibers, but this type of muscle looks smooth, not striated. Generally, we can't consciously control our smooth muscles; rather, they are controlled by the nervous system automatically, the reason they are called involuntary. Examples of smooth muscles are the walls of the stomach and intestines, which help break up food and move it through the digestive system. Smooth muscle is also found in the walls of blood vessels, where it squeezes the stream of blood flowing through the vessels to help maintain blood pressure. Smooth muscles take longer to contract than skeletal muscles do, but they can stay contracted for a long time because they don't tire easily.

Cardiac muscle is found in the heart. The walls of the heart's chambers are composed almost entirely of muscle fibers. Cardiac muscle is also an involuntary type of muscle. Its rhythmic, powerful contractions force blood out of the heart as it beats.

Our Nonstop Muscles

Even as we sit perfectly still, muscles throughout our bodies are constantly moving. Muscles enable the heart to beat, the chest to rise and fall during breathing, and blood vessels to help regulate the pressure and flow of blood through the body. When we smile and talk, muscles help us communicate, and when we exercise, they help us stay physically fit and healthy.

The movements our muscles make are coordinated and controlled by the brain and nervous system. The involuntary muscles are controlled by structures deep within the brain and the upper part of the spinal cord called the brain stem. The voluntary muscles are regulated by the parts of the brain known as the cerebral motor cortex and the cerebellum.

When we decide to move, the motor cortex sends an electrical signal through the spinal cord and peripheral nerves to the muscles, causing them to contract. The motor cortex on the right side of the brain controls the muscles on the left side of the body and vice versa.

The cerebellum coordinates the muscle movements ordered by the motor cortex. Sensors in the muscles and joints send messages back through peripheral nerves to tell the cerebellum and other parts of the brain where and how the arm or leg is moving and what position it is in. This feedback results in smooth, coordinated motion.  When you run, the messages to the brain are more involved, because many muscles have to work together in rhythm.

Muscles move body parts by contracting and then relaxing. Muscles can pull bones, but they can't push them back to the original position so they work in pairs of flexors and extensors. The flexor contracts to bend a limb at a joint. When the movement is completed, the flexor relaxes and the extensor contracts to extend or straighten the limb at the same joint. For example, the biceps muscle, in the front of the upper arm, is a flexor, and the triceps, at the back of the upper arm, is an extensor. When you bend at your elbow, the bicep contracts. Then the biceps relaxes and the triceps contracts to straighten the elbow.

Joints and What They Do

Joints occur where two bones meet. They make the skeleton flexible — without them, movement would be impossible.  Joints allow our bodies to move in many ways. Some joints open and close like a hinge (such as knees and elbows), whereas others allow for more complicated movement — a shoulder or hip joint, for example, allows for backward, forward, sideways, and rotating movement.

Joints are classified by their range of movement. Immovable, or fibrous, joints don't move. The dome of the skull, for example, is made of bony plates, which must be immovable to protect the brain. Between the edges of these plates are links, or joints, of fibrous tissue. Fibrous joints also hold the teeth in the jawbone.

Partially movable, or cartilaginous, joints move a little. They are linked by cartilage, as in the spine. Each of the vertebrae in the spine moves in relation to the one above and below it, and together these movements give the spine its flexibility.

Freely movable, or synovial, joints move in many directions. The main joints of the body — found at the hip, shoulders, elbows, knees, wrists, and ankles — are freely movable. They are filled with synovial fluid, which acts as a lubricant to help the joints move easily.  Three kinds of freely movable joints play a big part in voluntary movement:

hinge joints allow movement in one direction, as seen in the knees and elbows; pivot joints allow a rotating or twisting motion, like that of the head moving from side to side; ball-and-socket joints allow the greatest freedom of movement. The hips and shoulders have this type of joint, in which the round end of a long bone fits into the hollow of another bone.

3

Immune System (The defense system: army navy marines)

The immune system, which is made up of special cells, proteins, tissues, and organs, defends people against germs and microorganisms every day. Generally, the immune system does a great job of keeping people healthy and preventing infections, but sometimes there are problems with the immune system that can lead to illness and infection.

4

The immune system is the body's defense against infectious organisms and other invaders. Through a series of steps called the immune response, the immune system attacks organisms and substances that invade body systems and cause disease.

The immune system is made up of a network of cells, tissues, and organs that work together to protect the body. The cells involved are white blood cells, or leukocytes, which come in two basic types that come together to seek out and destroy disease-causing organisms or substances.

Leukocytes are produced or stored in many locations in the body, including the thymus, spleen, and bone marrow. For this reason, they're called the lymphoid organs. There are also clumps of lymphoid tissue throughout the body, primarily as lymph nodes, that house the leukocytes.  The leukocytes circulate through the body between the organs and nodes via lymphatic vessels and blood vessels. In this way, the immune system works in a coordinated manner to monitor the body for germs or substances that might cause problems.

The two basic types of leukocytes are: phagocytes, cells that chew up invading organisms; and lymphocytes, cells that allow the body to remember and recognize previous invaders and help the body destroy them.  A number of different cells are considered phagocytes. The most common type is the neutrophil, which primarily fights bacteria. If doctors are worried about a bacterial infection, they might order a blood test to see if a patient has an increased number of neutrophils triggered by the infection. Other types of phagocytes have their own jobs to make sure that the body responds appropriately to a specific type of invader.

The two kinds of lymphocytes are B lymphocytes and T lymphocytes. Lymphocytes start out in the bone marrow and either stay there and mature into B cells, or they leave for the thymus gland, where they mature into T cells. B lymphocytes and T lymphocytes have separate functions: B lymphocytes are like the body's military intelligence system, seeking out their targets and sending defenses to lock onto them. T cells are like the soldiers, destroying the invaders that the intelligence system has identified.

5

When antigens, foreign substances that invade the body, are detected, several types of cells work together to recognize them and respond to them. These cells trigger the B lymphocytes to produce antibodies, specialized proteins that lock onto specific antigens.

Once produced, these antibodies continue to exist in a person's body, so that if the same antigen is presented to the immune system again, the antibodies are already there to do their job.  An immunization introduces the body to an antigen in a way that doesn't make someone sick, but does allow the body to produce antibodies that will then protect the person from future attack by the germ or substance that produces that particular disease.

Although antibodies can recognize an antigen and lock onto it, they are not capable of destroying it without help. That's the job of the T cells, which are part of the system that destroys antigens that have been tagged by antibodies or cells that have been infected or somehow changed. Some T cells are actually called "killer cells." T cells also are involved in helping signal other cells, like phagocytes, to do their jobs.

7

Antibodies also can neutralize toxins (poisonous or damaging substances) produced by different organisms. Lastly, antibodies can activate a group of proteins, called complement, that are also part of the immune system. Complement assists in killing bacteria, viruses, or infected cells. All of these specialized cells and parts of the immune system offer the body protection against disease. This protection is called immunity.

8

Proteins and Enzymes (cars and engines)

At any given moment, all of the work being done inside any cell is being done by enzymes or proteins. Enzymes have extremely interesting properties that make them little chemical-reaction machines. The purpose of an enzyme in a cell is to allow the cell to carry out chemical reactions very quickly. They do this by bringing two molecules that need to react in very close proximity so they shorten the time it takes for two or more reactants to find each other and form a product.  Enzymes are therefore catalysts of change in the body which is why they are extremely important.  These reactions allow the cell to build things or take things apart as needed. This is how a cell grows and reproduces.  When an enzyme is formed, it is made by stringing together between 100 and 1,000 amino acids in a very specific and unique order. The chain of amino acids then folds into a unique shape. That shape allows the enzyme to carry out specific chemical reactions -- an enzyme acts as a very efficient catalyst for a specific chemical reaction. The enzyme speeds that reaction up tremendously.

9

Engineering and Movement

Yoga

Yoga has been around for thousands of years.  Yoga is a practice that started in India and is now very popular in the United States and around the world.  The work yoga means

union

in Sanskrit, the ancient language of India.  Quite simply, yoga is the

union

, or coming together of mind (thoughts and feelings) and physical body.  Many people feel an overall sense of well-being when they practice yoga.

There are many aspects to yoga. In short, yoga is a system of physical exercises or postures called asanas. These asanas build strength, flexibility and confidence. Yoga is also about breathing, called pranayama, which helps calm and refresh the body and mind.

10

The practice of yoga often include a spiritual or religious connection.  For the purposes of this unit, yoga will be experienced only as physical exercise to benefit the body and to experience fun and enjoyment.

Calisthenics

Calisthenics are a form of exercise that increases body strength and flexibility using your own body weight for resistance, with movements such as bending, jumping, swinging, twisting. The word Calisthenics comes from the ancient Greek

kallos

, which means beauty, and

sthenos

meaning strength. Some of the more common calisthenic exercises include lunges, jumping jacks, sit-ups, push-ups, pull-ups and squats.

11

Aerobic Exercise

Aerobic exercise is movement that gets the blood pumping faster around the whole body. It makes the heart beat faster and requires the lungs take in more oxygen, causing a faster rate of breathing during the exercise.  The U.S. Department of Health and Human Services recommends that children get 60 minutes or more of physical activity each day. They advise that aerobic activity should make up most of those 60 minutes.  Research shows that children who exercise tend to have better heart and lung fitness, lower levels of body fat, stronger bones and muscles, fewer symptoms of depression and better chances of being healthy adults without chronic disease.

12

Strategies/Methods

This curriculum unit will vary to reflect the learning styles of all students.  Included will be:

Experiential Learning:

The major strategy for this unit is to engage the students in hands-on learning. I want them to be actively participating as scientists. The biology activities will be designed to be exploratory for the students so they are engaged in the enjoyment of the process as well as the products, visuals and charts for our classroom. Certainly the physical activity component of this unit will be focused in the arena of learning.

Differentiated Instruction:

The students will use a variety of approaches, working sometimes individually and sometimes in small groups, determined by the complexity of the activity. Because these are young children with variance in levels and background, guidance and pacing will need to be closely monitored, particularly moving about and learning new exercises.  Students will have opportunities teach others, either as individuals or in groups, leading a class as the exercise instructor.

Cooperative Learning:

The students will be given opportunities to work as cooperative groups to complete assignments and activities. This strategy will allow students to work collaboratively taking on various roles necessary to complete the work, with a focus on success for all. A culminating activity will include groups creating body system posters and demonstrating yoga stretches, strength building exercises, and endurance and aerobic movements.

Classroom Activities

The classroom activities are designed to be taught over many days.  Although they are separated into specific sessions, each session may actually take several days to complete.

Session One – Unit Introduction - Read-Aloud

Me and My Amazing Body

by Joan Sweeney

This fundamental and comprehensive introductory text will prepare the students with a foundation of human anatomy vocabulary.  After reading and discussing the book, create a chart that includes the new information and vocabulary for students to refer back to as they begin their work.  In small groups, students will make a body tracing on large butcher paper, white and/or brown.  Students can then begin to label parts of the body that they can see:  head, arm, leg, knee, elbow, hand, foot, etc.  These large charts are the beginning of what will become the anchor charts for reference as the students learn the systems of the body and the engineering that allows their bodies to work.

Session Two – Students will use construction paper cutouts add the skeleton and muscles to the interior of the body tracing as they start to build the engines that allow their bodies to work.  Using the charts from

Me and My Amazing Body

, the students, in their groups, will cut white construction paper to the approximate size and shape of the major bones of the body.  After gluing them into place on their body tracing charts, the students will add pink construction paper cutouts of the major muscles in the body.  Students should pay attention to the location of major joints – hips, knees, elbows and shoulders, wrists, ankles – and label them as the construct their musculoskeletal systems.

Session Three – Yoga Poses and Practicing on the Mats

This session is the beginning of the actual physical fitness and exercise portion of the unit which will be the foundation of options during the indoor recess component of the school day.  Because this is an open-ended activity, with continued learning occurring, there is no definite time frame to this session, meaning it may be repeated several times throughout the year to introduce new poses and review previously learned ones.

To prepare for the yoga lessons, students will need to have a mat, either their own from home or possibly purchased through donations from the school or parent committee.  The mats stay at school and should be labeled with the students' names.  Mats are helpful not only as support during exercises, but they define the space that each student has as their own, an important part of helping them maintain control.

Beginning on Page 70 of the text

Once Upon a Pose,

read the basic training section to prepare for the fundamentals for teaching the poses, including strategies for breathing and for counting while holding poses.  With the idea of mastery, each session should focus on five poses at most.  The initial choices are as follows: mountain, tree, child, cat, and warrior.  The session will end with the peaceful pose, with students initially lying still for one minute, but ultimately building that time to as much as five minutes.

As students master the initial poses, they can begin to include any new poses from the 28 choices taught in the text.  Each new pose should be learned with a partner (either of their choice or teacher choice) and then taught to two other students to ensure understanding and a beginning of expertise.  During the group sessions, the students who have mastered a new pose may teach it to the group.

Keeping reference books in the classroom for students to use as they practice teaching each other and working on poses themselves will encourage correct poses but also inform students of other options they might like to try.  Continue to encourage the strategies of counting through the poses and focusing on their breathing.

Session Four – Calisthenics and Aerobics Lesson

This session is intended as a review of what most students have learned in their Physical Education classes.  An opening lesson for the students could be a brainstorming chart of what movements might be included in this category.  Ideas they may easily come up with could be jumping jacks, sit-ups, and push-ups.  As they learn more throughout this session, this chart can be enhanced and more defined, such as what parts of the body are you using for each exercise, how many times can you repeat the movements before tiring.  Include the students in generating characteristics of the exercises.

This session is should include the objectives of building appropriate vocabulary, rules about spacing in the classroom, maintaining control of body and voice and doing your best.  Remind students may not choose to do this as their indoor choice but it is important that they are introduced to the process and understand the rules.  This will ensure everyone has equal choice.

As the students are practicing their movements, have them feel their hearts beating and notice their breathing rates.  They will like notice that that these exercises are more about getting blood pumping than flexibility.

Create a Venn diagram or similarities and difference chart as students learn the movements and actions.  This too will remain as reference and interactive as the unit continues, student may add new information as they gather it.

Session Five – Work out with combination of all three exercise categories

This portion of the unit begins the gradual release of the activities to now becoming the students' choice.  The goal of the last three sessions was to build knowledge and skill in the three areas of exercise.  At this point, now during the recess portion of the day, the students will act as instructors and lead small groups in exercise routines as they make the decisions on poses or movements.  With a 20-minute block of time, students may lead a session and "attend" a second session.  Each day can be identified as the Yoga Day, the Aerobics Day or the Calisthenics Day to help with any space issues that might occur if all three are happening at once.  One common activity will always be the cool down or peaceful pose to help students transition from recess to the next part of their day.  As an additional component of the session, there may be quiet classical music or nature sounds or classical music playing as the students relax for the last five minutes on their mats.

Resources

Centers for Disease Control and Prevention. "Physical Activity." Centers for Disease Control and Prevention. http://www.cdc.gov/ (accessed June 15, 2014).

Freeman, Donna. Once Upon a Pose. Victoria, BC, Canada. Trafford Publishers, 2009. A comprehensive guide and reference for teachers of students from Kindergarten to Sixth Grade.

Hanh, Thich Nhat, and Wietske Vriezen. Mindful Movements Ten Exercises for Well-Being.. New York: Parallax Press, 2008.   This text provides short, clear explanations of tens movements to help energize the mind and body.  The DVD that is included is incredibly helpful.

Janeway, Charles A.. "How the Immune System Recognizes Invaders." Scientific American 269, no. 3 (1993): 72-79.

Lorenzi, Natalie. "A Passion for Learning." Scholastic Parent & Child 19 (2011)

Marrack, Philippa, and John W. Kappler. "How the Immune System Recognizes the Body." Scientific American 269, no. 3 (1993): 80-89.

Purperhart, Helen. The Yoga Zoo Adventure. Alameda, CA. Hunters House Inc., Publishers, 2006.  This children's picture book uses postures and movements of zoo animals to teach yoga movements to children.

Reece, Jane B., and Neil A. Campbell. Campbell Biology Jane B. Reece ... [et al.].. 9th ed. Boston: Benjamin Cummings :, 2011.

Rockwell, Lizzy. The Busy Body Book: A Kid's Guide to Fitness. New York: Crown Publishers, 2004.  Designed for students Kindergarten to Third Grade, this book is great for expanding exercise and movement vocabulary and includes helpful illustrations.

Santangelo White, Laura. "Yoga for Children." Pediatric Nursing 35 (2009)

Satyanarayana, Megha. Kids Get Health Benefits From Yoga (Detroit Free Press, 2009)

Sweeney, Joan.  Me and My Amazing Body.  New York: Crown Publishers, 1999.  Great introductory picture book that explains human anatomy and physiology to young children

The Nemours Foundation. "KidsHealth - the Web's most visited site about children's health." http://kidshealth.org/accessed June 15, 2014)

Weissman, Irving L., and Max D. Cooper. "How the Immune System Develops." Scientific American 269, no. 3 (1993): 64-71.

"Yoga for Kids: A Good Idea?," Mayo Clinic, November 17. 2010, http://www.mayoclinic.com/health/yoga-for-kids/MY01401

Appendix

In this unit, I will be using the Engineering, Technology, and Application of Science (ETS), Next Generation Science Standards that our students must meet.

The first set of standards focus on asking questions and defining problems in K–2 that build on prior experiences and progress to simple descriptive questions.  The students will meet the following specific standards as the unit progresses through presentations on the human anatomy systems as students discover, though questioning and inquiry, how our bodies are engineered.

K-2-ETS1-1: Ask questions based on observations to find more information about the natural and/or designed world(s).

K-2-ETS1-1: Define a simple problem that can be solved through the development of a new or improved object or tool.

Students will also meet the standards on modeling in K–2.  This standard builds on prior experiences and progresses to include using and developing models (i.e., diagram, drawing, physical replica, diorama, dramatization, or storyboard) that represent concrete events or design solutions.  As the students build their own anchor charts that represent their learning, they are creating a model of their own bodies, what they can see and what they cannot see (internal systems).

K-2-ETS1-2: Develop a simple model based on evidence to represent a proposed object or tool.

Notes

1  htttp://kidshealth.org

2  htttp://kidshealth.org

3  htttp://kidshealth.org

4  Marack and Kappler, 81

5  Weissmann and Cooper, 65

6  htttp://kidshealth.org

7  Weissmann and Cooper, 66

8  htttp://kidshealth.org

9 http://science.howstuffworks.com/dictionary/chemistry-terms/enzymes-info.htm

10  Freeman, 1

11 www.oxforddictionaries.com

12 https://www.cdc.gov

gha_language: HTML


text:
#Flask-S3-Direct-Upload

Sets up S3 upload policies for you to directly upload from client side javascript to S3 bypassing your Flask server.

## Setup

Usage is straightforward. Just set the three S3 parameters `S3_UPLOAD_BUCKET`, `S3_UPLOAD_ACCESS_KEY`, and `S3_UPLOAD_SECRET_KEY` in your app config. While the example below reads these from your environment, feel free to choose a method that makes sense for your deployment.

```python
app = Flask(__name__)
app.config['S3_UPLOAD_BUCKET'] = os.environ.get('S3_UPLOAD_BUCKET')
app.config['S3_UPLOAD_ACCESS_KEY'] = os.environ.get('S3_UPLOAD_ACCESS_KEY')
app.config['S3_UPLOAD_SECRET_KEY'] = os.environ.get('S3_UPLOAD_SECRET_KEY')
s3upload = S3UploadPolicy(app)
```

## Usage

Once this is set, you'll automatically have a top level route setup for `/policy`. For instance, in your dev setup, this will likely be:

```
http://localhost:5000/policy
```

This will return a `JSON` blob which can be consumed via your javascript form post.

```json

{
  "AWSAccessKeyId": "<YOURKEY>",
  "expiry": "2014-08-23T12:15:000Z",
  "key": "uploads/user/<generated_code>",
  "policy": "<long_policy_string>",
  "s3Bucket": "<bucket string>",
  "s3BucketUrl": "http://<bucket_url>.s3.amazonaws.com/",
  "signature": "<hash>"
}

```

## AWS

You may have to tweak your AWS CORS policy setup to permit testing via localhost.

```xml

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <AllowedMethod>DELETE</AllowedMethod>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

</code>

```

In production, you will likely want to place some restrictions on the AllowedOrigin.

## See Also

You may want to use one of the handy [Jquery](http://blueimp.github.io/jQuery-File-Upload/basic-plus.html) or [Angular](http://blueimp.github.io/jQuery-File-Upload/angularjs.html) libraries to handle the direct S3 post.

branch_name: refs/heads/master

extension: md

license_type: permissive


text:
# Welcome

Welcome to the development home for the Peachtree Corners Veterans Monument WebVR experience. The development team is staffed by a rag-tag team of smart STEM-oriented high school students from Peachtree Corners area high schools.

# Team

## Developers

### Wesleyan School
* Stephen Dunlap, Senior

### Gwinnett School of Mathematics, Science, and Technology
* Jason Yu, Junior
* Abel Abraham, Junior
* Michelle Coker, Junior

### Norcross High School
* Ethan Howe, Senior
* Drake Howton, Sophomore
* Colin Ryan, Freshman

## Mentors

* [Sean Dunlap](https://www.linkedin.com/in/seandunlap/) - Broadcom Ltd.
* [Mark Treager](https://www.linkedin.com/in/mark-treager/) - Cornerstone Media Group

## Hosts

Our office space has been donated by [Atlanta Tech Park](https://www.atlantatechpark.com/), a curated Tech Accelerator in Peachtree Corners:

* [Nashlee Young](https://www.linkedin.com/in/nashlee-young-269297b/) - Emnovate / Atlanta Tech Park
* [Robin Beinfait](https://www.linkedin.com/in/mark-treager/) - Emnovate / Atlanta Tech Park

# Contributing

Interested in contributing? As an open source project, we'd appreciate any help
and contributions!

## Join the Team on Slack

1. [Invite yourself](https://ptcvets.slack.com/join/shared_invite/enQtMzYyNDM0MDI5NjUyLWE4MjA5OWFjZWJiNzk1ZTNmMTRhZjVkZDI4NGJhZmE0YjJjMDA3NWU3YjExMjI4NjhhM2MxZWJjYjJjNDZmNjU) to the PCVMA Slack channel.

## File an Issue or Change Request

1. Search the [issue tracker](https://github.com/Peachtree-Corners-Vetereans-Monument/WebVR/issues) for similar issues.
2. Specify information about your browser and system (e.g., "Firefox Nightly on OS X")
3. Describe the problem in detail (i.e., what happened and what you expected would happen).
4. If possible, provide a small test case with [CodePen](http://codepen.io), a link to your application, and/or a screenshot. You can fork this [sample pen](http://codepen.io/anon/pen/KVWpbb).

## Contribute Code

1. Have a [GitHub account](https://github.com/join) with [SSH keys][ssh] set up.
2. [Fork](https://github.com/Peachtree-Corners-Vetereans-Monument/WebVR/fork) the repository on GitHub.
3. Clone your fork of the repository locally (i.e., `git clone git@github.com:yourusername/WebVR`).
4. Run `npm install` to get dependencies and `npm run dev` to serve the test examples.
5. Create a branch to work in (i.e., `git checkout -b mybranch`).
6. Make changes to your fork of the repository, commit them, and push them (i.e., `git add -A . && git commit -m 'My Changes (fixes #1234)' && git push origin mybranch`).
7. If necessary, write [unit tests](tests/) ([guide][testing-guide]) and run with `npm test`.
8. [Submit a pull request][pr] to the master branch. If you head to the [master repository](https://github.com/Peachtree-Corners-Vetereans-Monument/WebVR/wiki/Home/_edit) after running `git push` from earlier, you should see a pop up to submit a pull request.
9. [Address review comments](http://stackoverflow.com/questions/9790448/how-to-update-a-pull-request) if any.

## On GitHub

1. Help respond to [newly-filed GitHub issues](https://github.com/Peachtree-Corners-Vetereans-Monument/WebVR/issues)
2. Redirect developers to [Stack Overflow][stackoverflow] if a question is filed rather than an issue.
3. For extra points, cross-post and answer the question on Stack Overflow after redirecting!

## Getting Started

There are two easy options for obtaining this A-Frame scene. It's then up to you to make it your own!

### Option 1: Download the ZIP kit 📦

[](https://github.com/aframevr/aframe-boilerplate/archive/master.zip)

After you have __[downloaded and extracted this `.zip` file](https://github.com/Peachtree-Corners-Vetereans-Monument/aframe-boilerplate/archive/master.zip)__ containing the contents of this repo, open the resulting directory, and you'll be have your scene ready in these few steps:

    npm install && npm start
    open http://localhost:3000/

### Option 2: Fork this Git repo 🍴🐙

Alternatively, you can __[fork this repo](https://github.com/Peachtree-Corners-Vetereans-Monument/aframe-boilerplate/fork)__ to get started, if you'd like to maintain a Git workflow.

After you have __[forked this repo](https://github.com/Peachtree-Corners-Vetereans-Monument/aframe-boilerplate/fork)__, clone a copy of your fork locally and you'll be have your scene ready in these few steps:

    git clone https://github.com/Peachtree-Corners-Vetereans-Monument/aframe-boilerplate.git
    cd aframe-boilerplate && rm -rf .git && npm install && npm start
    open http://localhost:3000/

> :iphone: **Mobile pro tip:** Upon starting the development server, the URL will be logged to the console. Load that URL from a browser on your mobile device. (If your mobile phone and computer are not on the same LAN, consider using [ngrok](https://ngrok.com/) for local development and testing. [Browsersync](https://www.browsersync.io/) is also worth a gander.)

### Option 3: Fork this CodePen example 🍴💾✒

Or, you can simply __[fork this CodePen example](https://codepen.io/seandunlap/full/mLKexe/)__ to dive right in. Enjoy!

## Publishing your scene

If you don't already know, GitHub offers free and awesome publishing of static sites through __[GitHub Pages](https://pages.github.com/)__.

To publish your scene to your personal GitHub Pages:

    npm run deploy

And, it'll now be live at __http://`your_username`.github.io/__ :)

To know which GitHub repo to deploy to, the `deploy` script first looks at the optional [`repository` key](https://docs.npmjs.com/files/package.json#repository) in the [`package.json` file](package.json) (see [npm docs](https://docs.npmjs.com/files/package.json#repository) for sample usage). If the `repository` key is missing, the script falls back to using the local git repo's remote origin URL (you can run the local command `git remote -v` to see all your remotes; also, you may refer to the [GitHub docs](https://help.github.com/articles/about-remote-repositories/) for more information).

## Still need Help?

### Installation

First make sure you have Node installed.

On Mac OS X, it's recommended to use [Homebrew](http://brew.sh/) to install Node + [npm](https://www.npmjs.com):

    brew install node

To install the Node dependencies:

    npm install

### Local Development

To serve the site from a simple Node development server:

    npm start

Then launch the site from your favourite browser:

[__http://localhost:3000/__](http://localhost:3000/)

If you wish to serve the site from a different port:

    PORT=8000 npm start

## License

This program is free software and is distributed under an [MIT License](LICENSE).

license: MIT

gha_license_id: MIT


text:
# Graph-chat protocol

A generic chat protocol for client applications that communicate via edge-messaging protocol

## Problems of the existing chat platforms and protocols

- Dependency on a single company/server to access and use chat. That creates implications for chat privacy, user profile resilience and data ownership.
- Visiblity of user profile information to chat system and other chat users. Chat users have limited control as to who can see and find their profile.
- Visibility of user contacts graph to chat server.
- [E2EE][1] can be compromised by [MITM][2] attack (see [edge-messaging protocol][3]).
- Identity related problems (also see [edge-messaging protocol][3]).

## Graph-chat protocol abstract

TODO

## Duplex connection

Majority of chat scenarios requires duplex (bi-directional) connections between participants. Graph-chat protocol uses multiple unidirectional connections (graph edges) created on multiple edge-messaging servers to implement duplex connections.

Each duplex connection consists of one or multiple, for redundancy, pairs of unidirectional connections to connect chat participants or devices of the same participant - it is used for "contacts", "devices", "group participants", etc. For practical purposes of redundancy, chat clients can use 2-4 pairs of unidirectional connections.

The process described below establishes a duplex connection between Alice and Bob that has `n` unidirectional connections `CAi` (where `1 <= i <= n`) from Bob to Alice (created by Alice on her servers) and `n` unidirectional connections `CBi` (where `1 <= i <= n`) from Alice to Bob (created by Bob on his servers).

The following symbols are used below:
- unidirectional edge-messaging connections:
  - `CAi` - Alice's edge-messaging connection number `i` (out of `n`) allowing Bob to send messages to Alice.
  - `CBi` - Bob's edge-messaging connection number `i` (out of `n`) allowing Alice to send messages to Bob.
- keys created for Alice's connections:
  - `EKAi` - Alice's assymetric key pair used:
    - by Bob to encrypt and by Alice to decrypt messages from Bob sent via `CAi`.
    - by Alice to sign and Bob to verify messages from Alice sent via `CBi`.
  - `IDAi` - client-generated ID of connection `CAi`
  - `RUAi` - server-generated recipient connection URI of `CAi` (to be used by Alice to retrieve messages).
  - `SUAi` - server-generated sender connection URI of `CAi` (to be used by Bob to send messages).
  - `RKAi` - Alice's recipient key of `CAi`.
  - `SKAi` - Bob's sender key of `CAi`.
- keys created for Bob's connections
  - `EKBi` - Bob's assymetric key pair used for:
    - Alice to encrypt and Bob to decrypt messages from Alice sent via `CBi`.
    - Bob to sign and Alice to verify messages from Bob sent via `CAi`.
  - `IDBi` - client-generated ID of connection `CBi`
  - `RUBi` - server-generated recipient connection URI of `CBi` (to be used by Bob to retrive messages).
  - `SUBi` - server-generated sender connection URI of `CBi` (to be used by Alice to send messages).
  - `RKBi` - Bob's recipient key of `CBi`.
  - `SKBi` - Alice's sender key of `CBi`.

### Creating duplex connection

To create a duplex connection initiated by Alice, Alice's and Bob's apps follow these steps:

1. Alice's app initiates duplex connection:
   1. it creates `n` unidirectional connections ("edges") `CAi` (step 1 in [edge-messaging][3]) that are defined by:
      - client-generated:
         - Alice's asymmetric key pairs `EKAi` to encrypt messages.
         - connection IDs `IDAi`.
         - recipient keys `RKAi`.
      - server-generated:
         - recipient URIs `RUAi`.
         - sender URIs `SUAi`.
   2. optionally, Alice's app subsribes to receive messages from these new connections `CAi` ([edge-messaging protocol implementation][4] defines protocol to be used for subscriptions).
2. Alice's app sends a secure message to Bob's app (step 2 in [edge-messaging][3]):
   1. it prepares the message with the information needed to establish all connections `CAi`, including all encryption keys `EKAi` and sender connection URIs (`SUAi`).
   2. depending on the communication scenario, Alice's app sends this message to Bob's app in one of available secure ways (either out-of-band or via available secure duplex connection(s) - see [Duplex connection security level](#TODO)), depending on communication scenario:
      - if Bob is a new contact, the information is presented as a visual code (e.g. QR code(s)) to Bob's app - as out-of-band message needed to establish connections `CAi` (see [edge-messaging protocol][3] and [Adding direct contact](#adding-direct-contact)).
      - if Bob is added to group chat with Alice by some contact of Alice or Bob, this information can be passed through all possible chains of contacts between Alice and Bob in the group (to minimise the risk of MITM attack) (see [Group chat](#TODO)).
      - if Alice adds Bob as a contact via Bob's trusted contact John, who also has Alice as a trusted contact, this information will be passed via John (who has secure duplex connections with both Alice and Bob), in the same way as with Group chat (see [Trusted contacts](#TODO)).
      - if Alice already has Bob as a contact, and she wants to create a separate off-the-record chat with him, this information will be passed via their existing connection (see [Off-the-record chat](#TODO)).
      - etc. In all cases, the protocol defines the most secure possible way to pass the out-of-band (from the point of view of the new connections) message required by [edge-messaging protocol][3] to create unidirectional connections.
3. Bob's app accepts duplex connection with Alice:
   1. it receives the message from Alice's app, in a way defined by a specific chat scenario.
   2. it interprets the received information as edge-messaging protocol out-of-band messages to accept all unidirectional connections `CAi`.
   3. it creates `n` new unidirectional connections `CBi` on Bob's servers defined by:
      - client-generated:
         - Bob's asymmetric key pairs `EKBi` to encrypt messages.
         - connection IDs `IDBi`.
         - recipient keys `RKBi`.
      - server-generated:
         - recipient URIs `RUBi`.
         - sender URIs `SUBi`.
   4. optionally, Bob's app subsribes to receive messages from these new connection `CBi` (see [edge-messaging protocol implementation][4]).
   5. it proceeds with accepting Alice's app connections `CAi` (step 3 in [edge-messaging protocol][3]).
   6. in response to each connection `CAi`, as optional information, Bob's app includes:
      - Bob's user profile (that is only stored in graph-chat client and not visible to any server)
      - information to establish connection `CBi`:
         - encryption key `EKBi`.
         - sender connection URIs (`SUBi`).
   7. his app now sends the unsigned requests to Alice's connections `CAi` (step 3.4 in [edge-messaging protocol][3]), to both confirm the connections `CAi` and to propose the new connections `CBi`. As each message is encrypted by the key `EKAi` of the connection `CAi` that only Alice can decrypt, it is safe to send it - from edge-messaging server point of view it is an out-of-band message.
4. Alice's app adds Bob's duplex connection:
   1. it receives the messages from Bob via connections `CAi` (step 4 in [edge-messaging protocol][3]).
   2. depending on chat scenario, Bob is identified and confirmed:
      - for new contact, Alice may visually identify Bob's user profile and accepts Bob as a contact.
      - for group participant, Alice's app will match known Bob's user profile ID with received user profile ID (that is only visible to the clients apps that have this profile).
   3. it secures the connections `CAi` with keys `SKAi` received from Bob - the connections are now established (step 5 in [edge-messaging protocol][3]).
   4. it accepts the connections `CBi`, including in the response to Bob's server Alice's user profile and (as the additional information) the confirmation that the connections `CAi` are secured and can be used (step 3 in [edge-messaging protocol][3]).
   5. it sends the unsigned messages via connections `CBi`.
   6. it adds Bob's duplex connection to the list of available duplex connections as "pending" (Alice cannot yet send messages to Bob, but Bob already can send messages to Alice). Possibly, the status of duplex connection can indicate that Bob already can send messages to Alice.
5. Bob's app adds duplex connection with Alice:
   1. it receives the initial messages via connections `CBi`.
   2. it secures the connections `CBi` - they are now established as well (step 5 in [edge-messaging protocol][3]).
   3. it adds duplex connection with Alice in the list of available duplex connections as "pending" (to indicate that Alice cannot yet send messages). Possibly, the status of duplex connection can indicate that Bob already can send messages to Alice.
   4. it sends a special message (message type "welcome") to Alice's app via duplex connection (i.e., via all connections `CAi`) to confirm that adding Alice's contact is completed (see [Sending messages via duplex connection](#TODO)).
6. Alice's app finalises adding duplex connection with Bob:
   1. it receives "welcome" message from Bob's app via duplex connection.
   2. it changes Bob's duplex connection status to "established".
   3. it sends a special "welcome" message to Bob's app via duplex connection.
7. Bob's app finalises adding duplex connection with Alice:
   1. it receives "welcome" message from Alice's app via duplex connection.
   2. it changes Alice's duplex connection status "established".

**Creating duplex connection between Alice and Bob:**

![Creating connection](/diagrams/graph-chat/duplex-creating.svg)

### Sending message via duplex connection

When Alice sends the message to Bob via the duplex connection, they follow these steps:

1. Alice sends the message to Bob in the app:
    1. her app prepares the message, including:
       - client-generated message ID (unique per duplex connection).
       - client timestamp.
       - message body.
    2. her app prepares a separate version of the message for each connection `CBi`, by signing each version of the message with the corresponding key `EKAi` and encrypting it with `EKBi`.
    3. her app sends all copies of the message to corresponding connections `CBi`.
2. Bob's app receives the message from Alice:
    1. it retrieves all versions of the message via all connections `CBi` (they can arrive at different time and possibly out of order with other messages).
    2. it decrypts each version with `EKBi` and verifies the signature with `EKAi`.
    3. the first successfully decrypted message version is added to the Bob's chat with Alice and notification can be shown to Bob; if message verification failed it is marked as "unverified" in the chat.
    4. all subsequently decrypted and verified copies are discarded.
       - if some of the decryptions or verifications fail, the corresponding connection is marked as "possibly compromised" and has to be replaced by the app with another connection.
       - if decryption or verification fails for all connections `CBi`, Alice's contact is marked as "compromised".
3. Bob's app sends "message received" to Alice's app:
    1. it prepares a special "message received" message, including:
       - client-generated message ID (unique per duplex connection).
       - correlation ID of the message received from Alice.
       - client timestamp of the message reception.
    2. it prepares a separate version of the message for each connection `CAi`, by signing each version of the message with the corresponding key `EKBi` and encrypting it with `EKAi`.
    3. it sends all copies of the message to corresponding connections `CAi`.
4. Alice's app receives "message received" from Bob's app:
    1. it retrieves all versions of the "message received" message via all connections `CAi` (they can arrive at different time and possibly out of order with other messages).
    2. it decrypts each version with `EKAi` and verifies the signature with `EKBi`.
    3. once the first version is successfully decrypted and verified, the previosly sent message in the Alice's chat with Bob is marked as delivered.
    4. all subsequently decrypted and verified copies are discarded.
       - if some of the decryptions or verifications fail, the corresponding connection is marked as "possibly compromised" and has to be replaced by the app with another connection.
       - if decryption or verification fails for all connections `CAi`, Bob's contact is marked as "compromised".

**Sending message from Alice to Bob via duplex connection:**

![Sending message](/diagrams/graph-chat/duplex-using.svg)

## Adding direct contact

"Direct contact" is a term used for a duplex connection with another chat user established directly, not via another user. Establishing contact requires sending an out-of-band message - "visual code" (e.g. QR code(s)) is used for this purpose.

For example, Alice and Bob want to have a conversation in chat app, exchanging messages with each other. They both have graph-chat client and access to several edge-messaging servers (see [edge-messaging protocol][3]) that they can use to receive messages, and their graph-chat clients are configured to use these servers.

To chat in the app Alice needs to add Bob as "direct contact" to her contacts in the app.

1. Alice initiates adding "direct contact" in her graph-chat client app.
2. Alice shares "visual code" (e.g. QR code(s)) with Bob:
   1. her app prepares secure message to establish duplex connection with Bob's app (step 1 in [Creating duplex connection](#creating-duplex-connection)).
   2. her app prepares and displays a visual code with this message (step 2 in [Creating duplex connection](#creating-duplex-connection)).
   3. Alice now can share this visual code with Bob, either in person or via a video call (see [edge-messaging protocol][3]).
3. Bob reads "visual code" that Alice prepared via his app:
   1. he initiates adding "direct contact" via visual code in his graph-chat client app.
   2. his app interprets this visual code as secure message required to accept duplex connection with Alice and proceeds with creating duplex connection (step 3 in [Creating duplex connection](#creating-duplex-connection)).
4. Alice's app adds Bob as "direct contact":
   1. it proceeds with creating duplex connection.
   2. once "pending" duplex connection with Bob's app is created in Alice's app, Bob is added as "direct contact" with the status "pending" in Alice's app (step 4 in [Creating duplex connection](#creating-duplex-connection)).
5. Bob's app adds Alice as "direct contact":
   1. it proceeds with creating duplex connection.
   2. once "pending" duplex connection with Alice's app is created in Bob's app, Alice is added as "direct contact" with the status "pending" in Bob's app (step 5 in [Creating duplex connection](#creating-duplex-connection)).
6. Alice's app finalises adding Bob as "direct contact":
   1. it finalises adding duplex connection with Bob's app (step 6 in [Creating duplex connection](#creating-duplex-connection)).
   2. it changes Bob's "direct contact" status to "established".
7. Bob's app finalises adding Alice as "direct contact":
   1. it finalises adding duplex connection with Alice's app (step 7 in [Creating duplex connection](#creating-duplex-connection)).
   2. it changes Alice's "direct contact" status to "established".

## Connection and message types used in graph-chat protocol

##### Duplex connections

TODO

- "contact" - can be of type "person", "bot", "device", "organisation".
- "group-participant" - connection to another group participant that was established via the chain of other contacts in the group.
- "broadcast" - duplex connection from broadcast subscriber to publisher; client apps should only allow to receive messages and send back control messages, but not the content messages. Profile of the subscriber is not shared with the publisher.
- "broadcast-subscriber" - duplex connection from broadcast publisher to subscriber.

##### Messages

Control messages:

- "welcome" - sent and recieved by both participants when duplex connection is being established.
- "receipt" - acknowledging message receipt.
- "contact: update" - changing "contact" profile .
- "profile" - changing "contact
- "gm: add" - sent to add unidirectional edge-messaging connection to graph-chat duplex connection.
- "gm: remove" - sent to remove unidirectional edge-messaging connection from graph-chat duplex connection.

Content messages:

- "text"
- "image"

[1]: https://en.wikipedia.org/wiki/Man-in-the-middle_attack
[2]: https://en.wikipedia.org/wiki/End-to-end_encryption
[3]: edge-messaging.md
[4]: edge-messaging-implementation.md

repository: gajus/protocol

repo_name: gajus/protocol


text:
---
title: Good & Bad Waste
category: archive
layout: post
tags:
 - startups
 - investing
 - venture capital
 - waste
 - principles
 - progress
---

I was speaking with a friend about venture the other day and the topic of waste came up. Venture capital is a game in which [quite a bit of money goes in](https://www.cbinsights.com/research/report/venture-capital-q4-2017/), but [not a lot comes out](https://www.quora.com/What-percentage-of-startups-fail). The vast majority of venture backed startups return nothing, and only a small handful of them generate all the returns.

The same is seen in startups. Each stage of a business is aimed at solving fundamental problems related to the business, ie things like PMF, distribution, retention, etc. And most of the ideas deployed in these pursuits end of producing little value. Ultimately it’s only a small handful of things that make the difference. The [pareto principle](https://en.wikipedia.org/wiki/Pareto_principle) at work.

It got me thinking — are we good at deploying money / resources? Could we achieve the same results with much less? Or is a certain amount of investment needed in order to find the things that ultimately provide the value?

In other words, is the money & time allocated to the "losers" considered waste or is itt necessary?

First off, let’s [define waste](http://www.dictionary.com/browse/waste):

> Waste is to consume, spend, or employ uselessly or without adequate return; use to no avail or profit; squander.

So waste is something that doesn’t provide an adequate return. An effort that does not contribute to the outcome.

As mentioned above, the majority of investments or ideas don't end up directly contributing to the outcome. And so the question is -- do we classify the losers as waste?

The answer isn’t as clear as it may seem. While an investment in startup X may not be a financial success, it may lead you to startup Y, which is the real winner. And so that investment in startup X isn’t a waste, it still contributed to the outcome of that fund (even if one level removed).

The problem with classifying decisions as good (helpful) and bad (not helpful) is that it’s usually easier ex-post and pretty hard ex-ante. In hindsight, it’s easier to attribute past decisions ([sometimes incorrectly](https://en.wikipedia.org/wiki/Fundamental_attribution_error)) to a positive outcome. And over a long enough timescale, you can likely attribute everything to positive outcomes. [Narrative fallacy](https://www.fs.blog/2016/04/narrative-fallacy/) can be a dangerous thing.

But there is clearly a spectrum. Every year thousands of venture firms with the same fund size are started. Most will go nowhere and a few will be good. But all of their portfolios will be largely comprised of duds. So regardless, most investing decisions are mistakes. But clearly some firms make better mistakes than others.

So then how do we classify good mistakes vs. bad mistakes? An easy way to think about good and bad is through the lens of ROI. If we use ROI, we want to optimize for a high return and a low investment. And if it was easy to assign the values in decisions ex-ante, then nobody would ever make mistakes. But it’s not easy. So maybe a quick definition is:

__Good mistake__: A time and energy bound experiment that is an effort to solve a particular problem.

__Bad mistake__: An unplanned effort in hope to solve a problem.

The main difference is intention. A good mistakes is more thoughtful than bad. When aiming to make high ROI decisions, you need to make sure you optimize for a large R (return) and a low investment (time & energy).

To ensure a high R, we have to start by making sure the outcome (result) is known. If you don’t know what you’re aiming for you won’t be able to scope the effort to make sure the ROI is sufficiently large. So start by making sure you know what the desired outcome is and to work backwards in planning out your effort. And then make sure that the effort is both time & energy bound so that you’re minimizing the I.

So it seems like — for anything that is measured on a long enough time scale, there is going to be inevitably going to be "waste". Our job is then to focus on producing good waste over bad waste.

repository: ChrisEYin/sustain

repo_name: ChrisEYin/sustain


text:
---
id: 10082
title: 6IX9INE
date: 2021-04-07T07:50:01+00:00
author: Laima
layout: post
guid: https://ukdataservers.com/6ix9ine/
permalink: /04/07/6ix9ine/
---

* some text
{: toc}

## Who is 6IX9INE

Rapper also known as Tekashi69 whose 2017 songs “Exodia,” “Go Crazy,” “Oweee” and “Zeta Zero 0.5” helped establish him as a rap artist. His song “Gummo” would go Platinum in 2017. He collaborated with Nicki Minaj on the hit song “FEFE” in 2018.

## Prior to Popularity

He found his first fanbase in Slovakia and many of his first songs were released under the Slovakian label FCK THEM.

## Random data

Famous Dex was featured on his single “Zeta Zero 0.5.” He took the pseudonym Tekashi from a tattoo artist he used to frequent in his neighborhood growing up. After his release from prison in May 2020, he broke the YouTube record for the biggest 24-hour debut in rap.

## Family & Everyday Life of 6IX9INE

His real name is Daniel Hernandez. He is from Brooklyn, New York. He has an older brother named Oscar Osiris. His stepfather was murdered when he was 13 years old. He had a daughter named Saraiyah Hernandez with Sara Molina. His second daughter, Briella Iris Hernandez, was born in November 2018. In 2018, he began dating OhSoYouJade, who has been featured in a number of his music videos.

## People Related With 6IX9INE

In summer 2018, he collaborated with Anuel AA on the song “BEBE.” The music video for the song has earned more than 1 billion views on YouTube.

branch_name: refs/heads/main


text:
ZIM - Zsh IMproved
==================

What is Zim?
------------
Zim is a Zsh configuration framework with [blazing speed][speed] and modular extensions.

Zim is very easy to customize, and comes with a rich set of modules and features without compromising on speed or functionality!

What does Zim offer?
 Check out the [available modules][modules]!

Below is a brief showcase of Zim's features.

### Speed
For a speed comparison between Zim and other frameworks, see [this wiki entry][speed].

### Themes

To preview some of the available themes, check the [themes wiki page][themes].

### Fish-shell History Navigation
![history-substring-search][fish_shell]

### Syntax Highlighting
![syntax-highlighting][syntax_highlighting]

### And much more!
Zim has many modules! Enable as many or as few as you'd like.

Installation
------------
Installing Zim is very easy. Just run this command:

```
git clone --recursive -j8 "https://github.com/Eriner/zim.git" "~/.zim" &&\
 sh -c "~/.zim/tools/zim_install"
```

That's all there is to it. Enjoy your Zsh IMproved! Take some time to read about the [available modules][modules] and personalize your `.zshrc` file.

Updating
--------

To update zim, run:

```
zmanage update
```

For more information about the `zmanage` tool, see the [meta module][meta-module] documentation.

Uninstalling
------------

The best way to remove zim is to manually delete `~/.zim`, `~/.zimrc`, and
remove the initialization lines from your `~/.zshrc`.

However, there are some **experimental** convenience functions to remove zim:

**NOTE: This functionality is experimental!**

To remove zim, run:
```
zmanage remove
```

**NOTE: This functionality is experimental!**

[fish_shell]: https://i.eriner.me/zim_history-substring-search.gif
[syntax_highlighting]: https://i.eriner.me/zim_syntax-highlighting.gif
[speed]: https://github.com/Eriner/zim/wiki/Speed
[modules]: https://github.com/Eriner/zim/wiki/Modules
[themes]: https://github.com/Eriner/zim/wiki/Themes
[meta-module]: https://github.com/Eriner/zim/tree/master/modules/meta

repository: foldback/zim

repo_name: foldback/zim


text:
# COMP248_A2-Q3
CellphoneHub is cellphone plan comparison service that helps user choose an appropriate phone plan in Canada. They currently provide details for three different plans and support 3 different cell phone models. The details are mentioned below.

Three cellphone models available are Google Pixel 3, Samsung Note 9 and iPhone X Max.

There are three family cell phone plans available (all of them are 2 year plans):

       (1) Plan A – (Canada wide calling with 4GB shared data)

       (2) Plan B – (Canada wide calling with 10GB shared data)

       (3) Plan C – (Canada wide calling with 12GB shared data)

You can add as many lines to the shared plan as you want and you will get $10 discount for each
added line. You also get $10 discount if you bring your own phone (BYOP). The details for cell
phone discounts with each plan and along with plan price tags are tabulated below.

![](images/phonePlan.png)

Write a program that helps a user decide which plan works better for him. The program should ask the user to enter the total number of phone lines and whether or not a phone needs to be purchased with each line.

Compare all three plan costs and provide the user with all his options.

Here are a few sample outputs to illustrate the expected behavior of your program:

![](images/example1.png)

![](images/example2.png)

gha_language: Java


text:
---
layout: post
title: BODMAS Interpreter
thumbnail: images/p1/cat_and_mouse.png
myjs:
  - libjs/anchor.min.js
  - myjs/anchor_init.js
---

Problem:

    - Write a program that can solve simple mathematical equations.

    - Program should be able to understand the following symbols:

        - ( ) + - * /
    - Supports negative numbers.

### Aims

Show how a string can be broken down into tokens and an AST.

Show how a computer can then easily evaluate the AST.

repository: AndrewJakubowicz/oldBlogContent

repo_name: AndrewJakubowicz/oldBlogContent


text:
# Test of E-mails Leaks
System to get statistics of leaks from e-mails list.

## Getting Started
These instructions will tell you what do you need to get a copy set and run on your system.

## Prerequisites
Things you need to install to run the script and how install them.
* [Python 3.6+](https://www.python.org/) - Used to run the script.
* [Selenium](https://www.seleniumhq.org/) - Library to automate task on browsers.
* [Matplotlib](https://matplotlib.org/) - Used to plot the leak graph.
* [Numpy](https://www.numpy.org/) - Used integrated with matplotlib.

### Install
To install **python**, in case that you don't have a Unix/Linux system go to the [downloads](https://www.python.org/downloads/) section.
To install **selenium** library, case you have [pip](https://pypi.org/project/pip/) on your system:

> pip install selenium

or with [Anaconda](https://www.anaconda.com/):

> conda install selenium

## How to run
Example without the plot:
> python main.py -i <input_file> -o \<output_file>

Example with the plot:
> python main.py -i <input_file> -o \<output_file> -p \<True>
## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details


text:
---
name: 'Bug report'
about: 'Report rax-app, components, documents and other issues'
title: ''
labels: ''
assignees: ''
---

## What is the current behavior?

<!--
If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem.
-->

## What is the expected behavior?**

## Any additional comments?

- **rax-app Version**：
- **build.json Configuration**：
- **Node Version**:
- **Platform**:

repository: alijk-fe/motor-rax-scripts

gha_language: JavaScript

repo_name: alijk-fe/motor-rax-scripts


text:
# Teleborg
A loose Telegram bot API for Rust based on the traiting system.

How to use the project
======================
Add this to your `Cargo.toml`
``` toml
[dependencies]
teleborg = "0.1.32"
```

An example
==========
Here we'll show you the bare minimum needed to register a command which sends a hardcoded reply when issued.

```Rust
extern crate teleborg;

use teleborg::{Dispatcher, Bot, Updater};
use teleborg::objects::Update;

fn main() {
    // Make sure you have your token
    let bot_token = "bot_token".to_string();
    // Creating a dispatcher which registers all the command and message handlers
    let mut dispatcher = Dispatcher::new();
    // Registering our command which we create below in the form as a function
    dispatcher.add_command_handler("test", test, false);
    // Start the updater, the Updater will start the threads, one of which will poll for updates
    // and send those to the Dispatcher's thread which will act upon it with the registered handlers
    Updater::start(Some(bot_token), None, None, None, dispatcher);
}

// Our first command handler
fn test(bot: &Bot, update: Update, _: Option<Vec<&str>>) {
    bot.reply_to_message(&update, "It works!").unwrap();
}
```

gha_language: Rust


text:
# MQTT v3 recommendation

Before [[[MQTT5]]] there were no extensibility metadata defined for the messages. Thus
this section is only a set of recommendations on how trace context can be
implemented, not the specification.

## JSON payload

It is common that MQTT message payloads are represented as a JSON string. In this case
it is recommended to set `traceparent` and `tracestate` fields as a fields on a
outermost JSON object.

For example, if original payload looks like following:

``` json
{
    "_type": "cmd",
    "action": "setConfiguration",
    "configuration": {
        "_type":"configuration",
        "settingA": "value A",
        "settingB": 42
        }
}
```

Payload with trace context configured will look like following:

``` json
{
    "_type": "cmd",
    "action": "setConfiguration",
    "configuration": {
        "_type":"configuration",
        "settingA": "value A",
        "settingB": 42
        },
    "traceparent": "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01",
    "tracestate": "congo=BleGNlZWRzIHRohbCBwbGVhc3VyZS4"
}
```

## Handling end-to-end encryption

TBD: Should there be a note that for e2e encryption one may decide to send trace
context un-encrypted while the rest of the message can be encrypted?

## Binary payload

For binary payload - [Trace Context: binary protocol](https://w3c.github.io/trace-context-binary/) may be used to
propagate trace context fields.


text:
# Simple Lovense API Wrapper
I decided to create a simple api wrapper for the lovense API.

## Install
Simply run
`npm install simple-lovense`

## Examples
You can find a simple use case in example.js

## Functions
### LovenseOBJ.apiLink()
Returns the api used to check for toys.
### LovenseOBJ.isDebug()
Returns true/false for the debug mode.
### LovenseOBJ.processData(data)
Takes the json response from the API with the toy data and changes it a touch.
**Only use this if you know why you should.**
### LovenseOBJ.listToys(domain)
Returns the toys for the domain you pass. If you leave it empty, it will return for the currently set domain.
### LovenseOBJ.listDomains()
Returns the domains it found.
### LovenseOBJ.setDomain(domain)
Sets the used domain to the one specified. Returns true if it can, otherwise false if the domain does not exist.
### LovenseOBJ.setToyID(toyid)
Sets the default toy as passed.
### LovenseOBJ.sendCommand(command, commandOptions, domain=this.domain, toyid=this.toyid)
Sends the command, with the command options to the specified domain and toy. If you pass undefined to either/or the domain or toy, it will use the currently set defaults. If you set toyid to '', it will send it to all toys that the command supports.
### LovenseOBJ.getCommands()
Returns an object with all comands and options, along with which toys it will work with
### LovenseOBJ.getDomain()
Returns currently set domain
### LovenseOBJ.getToyID()
Returns currently set toyid

repository: andreblue/simple-lovense

repo_name: andreblue/simple-lovense


text:
---
title: "Predicting NFL Injuries with Stan"
author: 'ryantravis.netlify.com'
date: '2018-04-15'
slug: predicting-nfl-injuries-with-s
link: http://ryantravis.netlify.com/post/predicting-nfl-injuries-with-stan/
categories:
- bloglink
tags:
  - modeling
  - ryantravisnetlifycom
---

Yesterday I wrote a post using Stan to fit simple one parameter models. These are boring, but helpful for learning the basics. Today, I’d like to start building a series of increasingly complicated regression models[... <i class="fas fa-external-link-alt"></i>](http://ryantravis.netlify.com/post/predicting-nfl-injuries-with-stan/)

repository: mkearney/data-scribers

repo_name: mkearney/data-scribers


text:
---
layout: post
title: Making a simple AI on a Raspberry Pi computer
date: 2014-02-05
comments: true
landing: true
tags: [ai, python, raspberry pi]
description: My experience with beginning web development and how to deal with high impact websites using load balancing.
---

Choose the hardware
===================

Here is the list of my hardware components (as of 02/05/14):

-   [Raspberry Pi
    Model](http://www.amazon.com/RASPBERRY-MODEL-756-8308-Raspberry-Pi/dp/B009SQQF9C)
-   [Raspberry Pi
    Camera](http://www.alliedelec.com/search/productdetail.aspx?SKU=70280250)
-   [USB
    microphone](http://www.amazon.com/gp/product/B0052SBAEU/ref=oh_details_o03_s00_i00?ie=UTF8&psc=1)
-   [CM19A RF
    Transceiver](http://www.amazon.com/X10-R-F-PC-Transceiver-CM19A/dp/B0027RMIAO/ref=sr_1_1?s=electronics&ie=UTF8&qid=1392036372&sr=1-1&keywords=cm19a)
-   8GB SD Card
-   USB 2.0 10-port Hub
-   [USB WIFI
    adaptor](http://www.newegg.com/Product/Product.aspx?Item=N82E16833315091)
-   Computer speakers
-   HDMI cable

And here is the explanation: I will be using a [Raspberry Pi Model
B](http://www.amazon.com/RASPBERRY-MODEL-756-8308-Raspberry-Pi/dp/B009SQQF9C)
for the “computer” and using [Raspbian linux](http://www.raspbian.org/)
for the OS. There are plenty of other places that show you [how to get
started](http://www.andrewmunsell.com/blog/getting-started-raspberry-pi-install-raspbian)
so I am going to skip that here. For visuals I am using the [Raspberry
Pi
Camera](http://www.alliedelec.com/search/productdetail.aspx?SKU=70280250)
which is nicely mounted in [a custom made
enclosure](http://www.storenvy.com/products/4062416-raspberry-pi-and-camera-enclosure).
For audio I am using a simple microphone ([this one is
nice](http://www.alliedelec.com/search/productdetail.aspx?SKU=70280250)because
it blinks when it is recording and you can turn it off - and it is
cheap!). I already have [X10
transcievers](http://www.amazon.com/X10-TM751-Wireless-Transceiver-Module/dp/B000BT7XUK/ref=sr_1_2?s=electronics&ie=UTF8&qid=1391605702&sr=1-2&keywords=cm19a)
and was planning on using my old CM15A until it just up and died almost
exactly two years after I bought it. Sidenote: X10 is terrible about
helping to fix these things and a replacement is not cheap to find, so
avoid X10 if you can. Since I am stuck using X10 I decided to get the
cheap [CM19A USB RF
transceiver](http://www.amazon.com/X10-R-F-PC-Transceiver-CM19A/dp/B0027RMIAO/ref=sr_1_1?s=electronics&ie=UTF8&qid=1391605702&sr=1-1&keywords=cm19a)which
works well although I can’t use power line codes with it. Note - if you
want cheap X10 stuff, check out
[eBay](http://www.ebay.com/sch/i.html?_sacat=0&_nkw=x10+transceiver&_frs=1).

Choosing the software
=====================

Given an Linux environment, there are many choices of a coding language.
I would normally choose of the following (ordered according to my
favorite): Perl, Java, C++, PHP, Basic. However, one must keep in mind
that the RPi is 700MHz processor with 512MB RAM.  Thus, to
alleviate heavy lifting I would turn to online APIs.

Thus, my choice of a programming language is one which has a number of
great APIs and wrappers available. Python was presented to me as a great
choice, so I went with that. There are many APIs available for Python.
However, everything I am about to show could just as easily been done
with Java. Also, I had never programmed with Python before so this was
going to be a good opportunity for me to learn.

See TTS and STT in action!
==========================

Now how does it work? Lets find out!

Text-to-speech
==============

I found two options for TTS:
[espeak](http://packages.debian.org/unstable/espeak) (from Debian) or
using the [Google
TTS](http://techcrunch.com/2009/12/14/the-unofficial-google-text-to-speech-api/).
First I tried using espeak, which was easy to get going. However it
suffers from a drawback that when it speaks long sentence it slows down
and sounds like a Dalek ([documented
here](http://www.raspberrypi.org/phpBB3/viewtopic.php?f=38&t=47942)).
Since I would be saying things that are \>100 words this was not a good
solution, but maybe useful for you. Google TTS works great and is easy
to get going, however it suffers from a drawback that you can only say
100 characters at a time. However the speech clarity is nice so I
decided to go with this. It is fairly simple to use, the main command is
just:

```bash
mpg123 -a hw:YOURALSANUMBER -q 'http://translate.google.com/translate_tts?tl=en&q=WORD1%20WORD2%ETC'
```

You'll have to install and configure mpg123 to work (there are other
places to figure that out, let me know if you need help). Essentially
the next part was to write some code that would split the sentences into
100 character sentences. This is accomplished below:

```python
def saySomething(txt,language):
    print "speaking " + language
    words = txt.split()
    numWords = len(words)
    sentences = ""
    curSentence = 0
    curCharacters = 0
    curWord = 0
    for word in words:
        if curCharacters+len(word)+1<100:
            sentences = sentences+'%20'+word
        else:
            curSentence = curSentence + 1
            sentences = sentences + "111" + word
            curCharacters = 0
        curCharacters = curCharacters + len(word)+1
        curWord = curWord + 1

    feedTxt = sentences.split("111")
    for sentence in feedTxt:
    sentence = sentence.replace("'","%27")
    print sentence
    os.system("mpg123 -a hw:1 -q 'http://translate.google.com/translate_tts?tl="+language+"&q=" + sentence + "'")
```

Speech-to-text
==============

The STT is pretty simple as it consists of three steps: activation,
acquisition, and translation. Activation can be accomplished via a "key
press" but I much rather use voice activation. Assuming you live in a
normally quiet atmosphere, it is perfectly practical (and easy) to
calculate the root mean square noise (RMS) and activate upon a given
threshold. You can set the threshold by acquiring a distribution and
looking at standard deviations, or you can just choose a number. Either
way you can look at typical RMS values for your given mic/environment
using the following:

```python
import audioop
import pyaudio
rms = []
for i in range(0,100):
    p = pyaudio.PyAudio()
    stream = p.open(format=pyaudio.paInt16,channels=1,rate=44100,input=True,frames_per_buffer=1024)
    data = stream.read(1024)
    rmsTemp = audioop.rms(data,2)
    print rmsTemp
stream.stop_stream()
stream.close()
p.terminate()
```

I've set my threshold to 1050 (an arbitrary value, you should find your
own). Now then the first major subroutine of the AI can be set - the
listening function. This will essentially run infinitely and its nice to
allow this to run as a thread (it may be needed later). This is the
basic code for the activation:

```python
import audioop
import pyaudio
def listenToSurroundings(threadName):
    try:
        print "Started listening on thread %s" % threadName
        chunk = 1024

        volumeThreshold = 1050

        while (1):
            print "Starting listening stream"
            rmsTemp = 0
            p = pyaudio.PyAudio()
            stream = p.open(format=pyaudio.paInt16,channels=1,rate=16000,input=True,frames_per_buffer=chunk)

            while rmsTemp < volumeThreshold
                data = stream.read(chunk)
                rmsTemp = audioop.rms(data,2)
            stream.stop_stream()
            stream.close()
            p.terminate()
            output = getUsersVoice(5)
            processInput(output)
    except:
        import traceback
                print traceback.format_exc()
```

The try/except block is to catch errors, especially useful for the debug
stage. The aquisition and translation stages are done in another
subroutine, `getUsersVoice`. This is a pretty simple code - it will
first beep to notify that aquisition has begun. Then it will use
`arecord` to record the audio for a given amount of time. It will beep
when finished. Then it will send the text to the Google Speech API. For
this last step I use a separate bash file, `parseVoiceText.sh` just
because there are so many quotations. Here is the code:

```python
def getUsersVoice(speakingTime):
    os.system("mpg123 -a hw:YOURALSAPLAYBACK YOURBEEPSOUND.mp3 > /dev/null 2>&1 ")
    os.system("arecord -D plughw:YOURALSARECORDING -f cd -t wav -d %d -r 16000 | flac - -f --best --sample-rate 16000 -o out.flac> /dev/null 2>&1 " % speakingTime)
    os.system("mpg123 -a hw:YOURALSAPLAYBACK YOURBEEPSOUND.mp3 > /dev/null 2>&1 ")
    os.system("./parseVoiceText.sh ")
    output = ""
    with open('txt.out','r') as f:
        output = f.readline()
    print "output:"
    print output[1:-2]
    theOutput = output[1:-2]
    return theOutput
```

And the bash file:

```bash
# parseVoiceText.sh
wget -O - -o /dev/null --post-file out.flac --header="Content-Type: audio/x-flac; rate=16000" http://www.google.com/speech-api/v1/recognize?lang=en | sed -e 's/[{}]/''/g'| awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]; exit }' | awk -F: 'NR==3 { print $3; exit }' > txt.out
```

As you probably noticed, I didn't tell you about processInput(). That's
going to be the main function to handle events. I am currently fleshing
that out and will post back when I have some more on that.

How to do facial recognition
============================

Now how does it work? Lets find out!

Once again, this will be short and sweet. The code here is the most
simple, it does not save any of the processed images. If people are
interested in that I can post code that will save images of the faces
with their features labeled, but I am excluding that now for clarity.
Here is the basic code:

```python
def recognizeFace():

        # Take picture and save to webserver
        filename = "/var/www/temp.jpg"
        subprocess.call("sudo raspistill -w "+ str(saveWidth) +" -h "+ str(saveHeight) + " -t 1 -n -vf -e " + fileType + " -q 15 -o %s" % filename, shell=True)
        print "Captured image: %s" % filename

        # Send the picture to the SkyBio Api
        theFileLocation =  "http://YOURPUBLICIP/temp.jpg"
        client = FaceClient(YOURSKYBIOAPI,YOURSKYBIOAPISECRET)
        photo = client.faces_recognize('all',theFileLocation, namespace = 'YOURSKYBIONAMESPACE')

        # Number of people in photo
        numFaces = len(photo['photos'][0]['tags'])
        print "Detected " + str(numFaces) + " faces."

        # Go through each face
        theSpeech = ""
        while iii2: # proxy for if something happened
                print theSpeech
                saySomething(theSpeech,"en")
```

Now for the explanation. Firstly, this code uses [this API which gives
5000 calls/month for free](https://www.skybiometry.com/) for facial
recognition. It works well if you train it well. I will defer the
explanation of the training to [others who wrote beautifully on
this](https://github.com/Liuftvafas/python-face-client).

For this API to work, though, you have to send the picture from a
location on the Web.  If you already
have a webserver you can just SCP it over your VPN network. I went for a
simpler solution. I hosted the image on my RPi using an apache webserver
- [instructions are
here](http://www.jeremymorgan.com/tutorials/raspberry-pi/how-to-raspberry-pi-web-server/).
Don’t forget to forward port 80. You can get your public IP address
[here](http://www.whatismyip.com/). Now you can use the /var/www/ as
your web server folder, and you can pass those images to SkyBio. *[Note:
I suggest password protecting your folder using
.htaccess](http://www.javascriptkit.com/howto/htaccess3.shtml)*

This code just finds each face. However, SkyBio tries to find all sorts
of other things like whether you have glasses or not. You can probe all
these things (and their confidence levels) with the following:

```python
skybio_metrics = ['eyes','sadness','mood','glasses']
for metric in skybio_metrics:
    val = photo['photos'][0]['tags'][iii]['attributes'][metric]['value']
    conf = photo['photos'][0]['tags'][iii]['attributes'][metric]['confidence']
    if conf > 20:
        # do something with metric
```

Does this work? See for yourself (this output comes from a slightly
modified version of above that prints the metric over the face):

Adding a face to the AI
=======================

Now how does it work? Lets find out!

How to add a face to an AI
==========================

So for a face, I thought I would try making some sort of realtime voice
animating system. I made a very very simple one in python. Here is an
example of what it looks like and sounds like:

The source code is very simple. Get the whole code at my [github
page](https://github.com/schollz/rpi_ai) (the following excludes the
saySomething function which is part of `mouth_function`. Basically the
following code opens a process to say something and at the same time
tries to animate it with an open/closing mouth. The timing between the
mouth open and mouth closed comes from an average timing I got from
recording the Google TTS and recording how much time it takes to say a
word and the amount of time between words. The other trick is to count
the number of syllables in a word.

Python has a fast way of doing this using `nltk` (coded below).

```python
import pygame, sys, time, random
from pygame.locals import *
from time import *
import curses
from curses.ascii import isdigit
import nltk
from nltk.corpus import cmudict
import os
import thread
import threading

d = cmudict.dict()

def nsyl(word):
        return [len(list(y for y in x if isdigit(y[-1]))) for x in d[word.lower()]]

pygame.init()
windowSurface = pygame.display.set_mode((500, 400), 0, 32)
pygame.display.set_caption("Bounce")

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255,255,0)

info = pygame.display.Info()
sw = info.current_w
sh = info.current_h
y = 0
phrase = "Hi there. How are you doing"
windowSurface.fill(WHITE)
pygame.draw.circle(windowSurface, YELLOW , (250,200), 80, 0)
pygame.draw.circle(windowSurface, BLACK,(280,170), 10, 0)
pygame.draw.circle(windowSurface, BLACK,(220,170), 10, 0)

pygame.draw.ellipse(windowSurface,BLACK,(225,230,50,10),0)
myfont = pygame.font.SysFont("ComicSans", 35)
pygame.display.update()
sleep(1)
paragraph =  str(sys.argv[1])
thread.start_new_thread( saySomething,(paragraph,"en",))
workingSentence = ""
sleep(0.26)
for phrase in paragraph.split("?"):
    for sentence in phrase.split("."):
        for word in sentence.split():
            windowSurface.fill(WHITE)
            pygame.draw.circle(windowSurface, YELLOW , (250,200), 80, 0)
            pygame.draw.circle(windowSurface, BLACK,(280,170), 10, 0)
            pygame.draw.circle(windowSurface, BLACK,(220,170), 10, 0)

            pygame.draw.ellipse(windowSurface,BLACK,(225,220,50,30),0)
            myfont = pygame.font.SysFont("ComicSans", 17)
            workingSentence += word + " "
            label = myfont.render(workingSentence, 1, BLACK)
            windowSurface.blit(label, (5, 5))
            pygame.display.update()
            syl = nsyl(word)
            syl = syl[0]
            sleep(0.185*float(syl))

            windowSurface.fill(WHITE)
            pygame.draw.circle(windowSurface, YELLOW , (250,200), 80, 0)
            pygame.draw.circle(windowSurface, BLACK,(280,170), 10, 0)
            pygame.draw.circle(windowSurface, BLACK,(220,170), 10, 0)

            pygame.draw.ellipse(windowSurface,BLACK,(225,230,50,10),0)
            myfont = pygame.font.SysFont("ComicSans", 17)
            label = myfont.render(workingSentence, 1, BLACK)
            windowSurface.blit(label, (5, 5))
            pygame.display.update()
            sleep(0.082)
        windowSurface.fill(WHITE)
        pygame.draw.circle(windowSurface, YELLOW , (250,200), 80, 0)
        pygame.draw.circle(windowSurface, BLACK,(280,170), 10, 0)
        pygame.draw.circle(windowSurface, BLACK,(220,170), 10, 0)

        pygame.draw.ellipse(windowSurface,BLACK,(225,230,50,10),0)
        myfont = pygame.font.SysFont("ComicSans", 17)
        label = myfont.render(workingSentence, 1, BLACK)
        windowSurface.blit(label, (5, 5))
        pygame.display.update()
        sleep(0.16)

sleep(1)
```

Adding personality
==================

This part is actually very easy - [there is a fantastic API already
available that does the
job](https://code.google.com/p/chatter-bot-api/). Use this API and then
all that needs to be done for the AI program is creating a function that
feeds in the query to the robot and gets the response:

```python
from chatterbotapi import ChatterBotFactory, ChatterBotType

def getAIresponse2(s):
    factory = ChatterBotFactory()
    bot2 = factory.create(ChatterBotType.CLEVERBOT)
    bot2session = bot2.create_session()
    response = bot2session.think(s)
    return response
```

In this example I use `CLEVERBOT` but there are certainly other bots to
choose from. A little later I will talk about the predicament to develop
a personalized chatterbot baesd on chat histories.

extension: markdown


text:
# Episporogoniella U. Braun GENUS

#### Status
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycotaxon 51: 41 (1994)

#### Original name
Episporogoniella U. Braun

### Remarks
null

repository: mdoering/backbone

repo_name: mdoering/backbone