This set of Micro-controller Multiple Choice Questions & Answers (MCQs) focuses on “Introduction to Microcontroller”.
1. A microcontroller at-least should consist of:
a) RAM, ROM, I/O ports and timers
b) CPU, RAM, I/O ports and timers
c) CPU, RAM, ROM, I/O ports and timers
d) CPU, ROM, I/O ports and timers
View Answer
Answer: c
Explanation: A microcontroller at-least consists of a processor as its CPU with RAM, ROM, I/O ports and timers. It may contain some additional peripherals like ADC, PWM, etc.
2. Unlike microprocessors, microcontrollers make use of batteries because they have:
a) high power dissipation
b) low power consumption
c) low voltage consumption
d) low current consumption
View Answer
Answer: b
Explanation: Micro Controllers are made by using the concept of VLSI technology. So here, CMOS based logic gates are coupled together by this technique that consumes low power.
3. What is the order decided by a processor or the CPU of a controller to execute an instruction?
a) decode,fetch,execute
b) execute,fetch,decode
c) fetch,execute,decode
d) fetch,decode,execute
View Answer
Answer: d
Explanation: First instruction is fetched from Program Memory. After fetching, instruction is decoded to generate control signals to perform the intended task. After decoding, instruction is executed and the complete intended task of that particular instruction.
4. If we say microcontroller is 8-bit then here 8-bit denotes size of:
a) Data Bus
b) ALU
c) Control Bus
d) Address Bus
View Answer
Answer: b
Explanation: If we say a microcontroller is 8-bit it means that it is capable of processing 8-bit data at a time. Data processing is the task of ALU and if ALU is able to process 8-bit data then the data bus should be 8-bit wide. In most books it tells that size of data bus but to be precise it is the size of ALU because in Harvard Architecture there are two sets of data bus which can be of same size but it is not mandatory.
5. How are the performance and the computer capability affected by increasing its internal bus width?
a) it increases and turns better
b) it decreases
c) remains the same
d) internal bus width doesn’t affect the performance in any way
View Answer
Answer: a
Explanation: As the bus width increases, the number of bits carried by bus at a time increases as a result of which the total performance and computer capability increases.
6. Abbreviate CISC and RISC.
a) Complete Instruction Set Computer, Reduced Instruction Set Computer
b) Complex Instruction Set Computer, Reduced Instruction Set Computer
c) Complex Instruction Set Computer, Reliable Instruction Set Computer
d) Complete Instruction Set Computer, Reliable Instruction Set Computer
View Answer
Answer: b
Explanation: CISC means Complete Instruction Set Computer because in this a microcontroller has an instruction set that supports many addressing modes for the arithmetic and logical instructions, data transfer and memory accesses instructions. RISC means Reduced Instruction Set Computer because here a microcontroller has an instruction set that supports fewer addressing modes for the arithmetic and logical instructions and for data transfer instructions.
7. Give the names of the buses present in a controller for transferring data from one place to another?
a) data bus, address bus
b) data bus
c) data bus, address bus, control bus
d) address bus
View Answer
Answer: c
Explanation: There are 3 buses present in a microcontroller they are data bus (for carrying data from one place to another), address bus (for carrying the address to which the data will flow) and the control bus (which tells the controller to execute which type of work at that address may be it read or write operation).
8. What is the file extension that is loaded in a microcontroller for executing any instruction?
a) .doc
b) .c
c) .txt
d) .hex
View Answer
Answer: d
Explanation: Microcontrollers are loaded with .hex extension as they understand the language of 0’s and 1’s only.
9. What is the most appropriate criterion for choosing the right microcontroller of our choice?
a) speed
b) availability
c) ease with the product
d) all of the mentioned
View Answer
Answer: d
Explanation: For choosing the right microcontroller for our product we must consider its speed so that the instructions may be executed in the least possible time. It also depends on the availability so that the particular product may be available in our neighboring regions or market in our need. It also depends on the compatibility with the product so that the best results may be obtained.
10. Why microcontrollers are not called general purpose computers?
a) because they have built in RAM and ROM
b) because they design to perform dedicated task
c) because they are cheap
d) because they consume low power
View Answer
Answer: b
Explanation: Microcontrollers are designed to perform dedicated tasks. While designing general purpose computers end use is not known to designers.
Sanfoundry Global Education & Learning Series – Microcontroller.
To practice all areas of Microcontroller, here is complete set of 1000+ Multiple Choice Questions and Answers.
Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
This set of Micro-controller Multiple Choice Questions & Answers (MCQs) focuses on “Von Neumann and Harward Architectures”.
1. How many types of architectures are available, for designing a device that is able to work on its own?
a) 3
b) 2
c) 1
d) 4
View Answer
Answer: b
Explanation: There are basically two main types of architectures present, they are Von Neumann and Harvard architectures.
2. Which architecture is followed by general purpose microprocessors?
a) Harvard architecture
b) Von Neumann architecture
c) None of the mentioned
d) All of the mentioned
View Answer
Answer: b
Explanation: General purpose microprocessors make use of Von Neumann architecture as here a simpler design is offered.
3. Which architecture involves both the volatile and the non volatile memory?
a) Harvard architecture
b) Von Neumann architecture
c) None of the mentioned
d) All of the mentioned
View Answer
Answer: a
Explanation: In Harvard architecture, both the volatile and the non volatile memories are involved. This is done to increase its efficiency as both the memories are being used over here.
4. Which architecture provides separate buses for program and data memory?
a) Harvard architecture
b) Von Neumann architecture
c) None of the mentioned
d) All of the mentioned
View Answer
Answer: a
Explanation: Harvard Architecture provides separated buses for data and program memory to fetch program and data simultaneously. By doing this access time is reduced and hence performance is increased.
5. Which microcontroller doesn’t match with its architecture below?
a) Microchip PIC- Harvard
b) MSP430- Harvard
c) ARM7- Von Neumann
d) ARM9- Harvard
View Answer
Answer: b
Explanation: MSP430 supports Von Neumann architecture.
6. Harvard architecture has _____________
a) dedicated buses for data and program memory
b) pipeline technique
c) complex architecture
d) all of the mentioned
View Answer
Answer: d
Explanation: Harvard Architecture has dedicated buses for data and program memory and pipeline technique because of this architecture is complex.
7. Which out of the following supports Harvard architecture?
a) ARM7
b) Pentium
c) SHARC
d) All of the mentioned
View Answer
Answer: c
Explanation: SHARC supports harvard architecture for signal processing in DSP.
8. Why most of the DSPs use Harvard architecture?
a) they provide greater bandwidth
b) they provide more predictable bandwidth
c) they provide greater bandwidth & also more predictable bandwidth
d) none of the mentioned
View Answer
Answer: c
Explanation: Most of the DSPs use harvard architecture because they provide a wider predictable bandwidth.
9. Which of the following supports CISC as well as Harvard architecture?
a) ARM7
b) ARM9
c) SHARC
d) None of the mentioned
View Answer
Answer: c
Explanation: SHARC supports both the CISC and the Harvard architecture.
10. Which of the two architecture saves memory?
a) Harvard
b) Von Neumann
c) Harvard & Von Neumann
d) None of the mentioned
View Answer
Answer: b
Explanation: As only one memory is present in the Von Neumann architecture so it saves a lot of memory.
Sanfoundry Global Education & Learning Series – Microcontroller.
To practice all areas of Microcontroller, here is complete set of 1000+ Multiple Choice Questions and Answers.
Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
This set of 8051 Micro-controller Multiple Choice Questions & Answers (MCQs) focuses on “Architecture”.
1. 8051 microcontrollers are manufactured by which of the following companies?
a) Atmel
b) Philips
c) Intel
d) All of the mentioned
View Answer
Answer: d
Explanation: 8051 microcontrollers are manufactured by Intel, Atmel, Philips/Signetics, Infineon, Dallas Semi/Maxim.
2. AT89C2051 has RAM of:
a) 128 bytes
b) 256 bytes
c) 64 bytes
d) 512 bytes
View Answer
Answer: a
Explanation: It has 128 bytes of RAM in it.
3. 8051 series has how many 16 bit registers?
a) 2
b) 3
c) 1
d) 0
View Answer
Answer: a
Explanation: It has two 16 bit registers DPTR and PC.
4. When 8051 wakes up then 0x00 is loaded to which register?
a) PSW
b) SP
c) PC
d) None of the mentioned
View Answer
Answer: c
Explanation: When 8051 wakes up, Program Counter (PC) loaded with 0000H. Because of this in 8051 first opcode is stored in ROM address at 0000H.
5. When the microcontroller executes some arithmetic operations, then the flag bits of which register are affected?
a) PSW
b) SP
c) DPTR
d) PC
View Answer
Answer: a
Explanation: It stands for program status word. It consists of carry, auxiliary carry, overflow, parity, register bank select bits etc which are affected during such operations.
6. How are the status of the carry, auxiliary carry and parity flag affected if the write instruction
MOV A,#9C
ADD A,#64H
a) CY=0,AC=0,P=0
b) CY=1,AC=1,P=0
c) CY=0,AC=1,P=0
d) CY=1,AC=1,P=1
View Answer
Answer: b
Explanation: On adding 9C and 64, a carry is generated from D3 and from the D7 bit so CY and AC are set to 1. In the result, the number of 1’s present are even so parity flag is set to zero.
7. How are the bits of the register PSW affected if we select Bank2 of 8051?
a) PSW.5=0 and PSW.4=1
b) PSW.2=0 and PSW.3=1
c) PSW.3=1 and PSW.4=1
d) PSW.3=0 and PSW.4=1
View Answer
Answer: d
Explanation: Bits of PSW register are CY, AC, F0, RS1, RS0, OV, -, P so for selecting bank2 RS1=1 and RS0=0 which are fourth and third bit of the register respectively.
8. If we push data onto the stack then the stack pointer
a) increases with every push
b) decreases with every push
c) increases & decreases with every push
d) none of the mentioned
View Answer
Answer: a
Explanation: If we push elements onto the stack then the stack pointer increases with every push of element.
9. On power up, the 8051 uses which RAM locations for register R0- R7
a) 00-2F
b) 00-07
c) 00-7F
d) 00-0F
View Answer
Answer: b
Explanation: On power up register bank 0 is selected which has memory address from 00H-07H.
10. How many bytes of bit addressable memory is present in 8051 based microcontrollers?
a) 8 bytes
b) 32 bytes
c) 16 bytes
d) 128 bytes
View Answer
Answer: c
Explanation: 8051 microcontrollers have 16 bytes of bit addressable memory.
Sanfoundry Global Education & Learning Series – Microcontroller.
To practice all areas of Microcontroller, here is complete set of 1000+ Multiple Choice Questions and Answers.
Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
This set of 8051 Micro-controller Multiple Choice Questions & Answers (MCQs) focuses on “LCD Interfacing”.
1. How many rows and columns are present in a 16*2 alphanumeric LCD?
a) rows=2, columns=32
b) rows=16, columns=2
c) rows=16, columns=16
d) rows=2, columns=16
View Answer
Answer: d
Explanation: 16*2 alphanumeric LCD has 2 rows and 16 columns.
2. How many data lines are there in a 16*2 alphanumeric LCD?
a) 16
b) 8
c) 1
d) 0
View Answer
Answer: b
Explanation: There are eight data lines from pin no 7 to pin no 14 in an LCD.
3. Which pin of the LCD is used for adjusting its contrast?
a) pin no 1
b) pin no 2
c) pin no 3
d) pin no 4
View Answer
Answer: c
Explanation: Pin no 3 is used for controlling the contrast of the LCD.
4. For writing commands on an LCD, RS bit is
a) set
b) reset
c) set & reset
d) none of the mentioned
View Answer
Answer: b
Explanation: For writing commands on an LCD, RS pin is reset.
5. Which command of an LCD is used to shift the entire display to the right?
a) 0x1C
b) 0x18
c) 0x05
d) 0x07
View Answer
Answer: a
Explanation: 0x1C is used to shift the entire display to the right.
6. Which command is used to select the 2 lines and 5*7 matrix of an LCD?
a) 0x01
b) 0x06
c) 0x0e
d) 0x38
View Answer
Answer: d
Explanation: 0x38 is used to select the 2 lines and 5*7 matrix of an LCD.
7. Which of the following step/s is/are correct for sending data to an LCD?
a) set the R/W bit
b) set the E bit
c) set the RS bit
d) all of the mentioned
View Answer
Answer: d
Explanation: To send data to an LCD, RS pin should be set so that LCD will come to know that it will receive data which has to display on the screen. R/W pin should be reset as data has to be displayed (i.e. write to the LCD). High to low pulse must be applied to the E pin when data is supplied to data pins of the LCD.
8. Which of the following step/s is/are correct to perform reading operation from an LCD?
a) low to high pulse at E pin
b) R/W pin is set high
c) low to high pulse at E pin & R/W pin is set high
d) none of the mentioned
View Answer
Answer: c
Explanation: For reading operations, R/W pin should be made high and added to it, a low to high pulse is also generated at the E pin.
9. Which instruction is used to select the first row first column of an LCD?
a) 0x08
b) 0x0c
c) 0x80
d) 0xc0
View Answer
Answer: c
Explanation: 0x80 is used to select the first row first column of an LCD.
10. The RS pin is _________ for an LCD.
a) input
b) output
c) input & output
d) none of the mentioned
View Answer
Answer: a
Explanation: The RS pin is an input pin for an LCD.
Sanfoundry Global Education & Learning Series – Microcontroller.
To practice all areas of Microcontroller, here is complete set of 1000+ Multiple Choice Questions and Answers.
Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
This set of AVR Micro-controller Multiple Choice Questions & Answers (MCQs) focuses on “Architecture”.
1. Is the following instruction correct LDI R3,50?
a) Yes
b) No
c) Cant be said
d) None of the mentioned
View Answer
Answer: b
Explanation: If LDI Rd,k is written then the range of Rd varies from R16-R31, as R3 is less than R16 so this instruction will generate an error.
2. Registers R0-R31 are used for what type of works?
a) they are used for arithmetic and logic instructions
b) they are used for data copy
c) they are used for calculations
d) none of the mentioned
View Answer
Answer: a
Explanation: GPRs are used for implementing arithmetic and logic instructions in the controller. They do the same work as the accumulator does in the other microcontrollers and microprocessors.
3. The largest value that can be loaded in an 8 bit register is?
a) 11111111H
b) FH
c) FFH
d) 00H
View Answer
Answer: c
Explanation: The largest value that can be loaded in an 8 bit register is 11111111b or FFH.
4. The total space for the data memory available in the AVR based microcontroller is?
a) FFH
b) FFFH
c) FFFFH
d) FFFFFH
View Answer
Answer: c
Explanation: The maximum value that can be loaded in the code memory of an AVR based microcontroller is FFFFH.
5. Which of the following instructions affect the flags of the status register?
a) AND
b) INC
c) OR
d) All of the mentioned
View Answer
Answer: d
Explanation: AND, INC, OR could affect status register flags. All arithmetic and logical instructions affect status register flags except SER Rd instruction. SER Rd is used to SEt Register i.e. after the execution of this instruction Rd loaded with FFH value and no flag is affected.
6. What is the difference between the two given instructions?
 They both are used for assigning the hexadecimal values to the registers.
7. Which out of the following is not a directive?
a) .EQU
b) .DEVICE
c) .ORG
d) .LDI
View Answer
Answer: d
Explanation: .EQU, .DEVICE, .ORG all are the directives to the assembler whereas LDI is a command.
8. Is an assembly language a high level language?
a) Yes
b) No
c) Can’t be said
d) None of the mentioned
View Answer
Answer: b
Explanation: Assembly language is not high level language rather it is low level language because it deals directly with the internal structure of CPU. To program in assembly, the internal structure of the CPU must be known. Whereas in high level programming languages programmers don’t bother about the internal structure of the CPU because this is done by the compiler.
9. A 14-bit program counter can access __________ bytes of memory locations.
a) 4K
b) 8K
c) 16K
d) 64K
View Answer
Answer: c
Explanation: A 14-bit program counter can access 214 bytes of memory locations i.e. 16k bytes.
Calculation:
214 = 24 x 210
= 16K (210 = 1024 or 1K).
10. When AVR wakes up, then the value of PC becomes?
a) 00H
b) 000H
c) 0000H
d) 00000H
View Answer
Answer: d
Explanation: When an AVR wakes up, then the PC starts at the memory location 00000H.
Sanfoundry Global Education & Learning Series – Microcontroller.
To practice all areas of Microcontroller, here is complete set of 1000+ Multiple Choice Questions and Answers.
Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
This set of AVR Microcontroller Problems focuses on “Keyboard Interfacing”.
1. In reading the columns of a keyboard matrix, when no key is pressed then all the pins show?
a) 0
b) 1
c) F
d) 7
View Answer
Answer: b
Explanation: When no key is pressed, in a keyboard then all the pins will read 1 as they all are connected to the main power supply.
2. To see if any key is pressed, all rows are grounded.
a) true
b) false
c) can’t be said
d) depends on the conditions
View Answer
Answer: a
Explanation: To see that whether any key is pressed or not then all the rows are grounded so that columns can be read to deliver the better results.
3. Identify the row and the column for the following case when for the row D3-D0= 1110 and for the column D3-D0= 1101
a) first row and second column
b) first row and third column
c) second row and first column
d) second row and second column
View Answer
Answer: a
Explanation: To identify the key that is pressed from this particular combination, we obtain that the key belongs to the first row and the second column as the D0 bit of the row port and the D1 bit of the column port are zero.
4. What are the actual steps that are followed in identifying any key that is being pressed?
a) wait for the debounce time
b) identify the key that is pressed
c) initially no key should be pressed
d) all of the mentioned
View Answer
Answer: d
Explanation: In order to identify that which key is actually pressed form a particular format of a 3*3 matrix keyboard, we firstly ensure all initially all the keys are open, then we press a key and check that whether the key is actually pressed or not by waiting for a time span of 20mseconds, after this we identify the key that is pressed by masking the bits of the port. In this particular format, we can identify the key that is actually pressed.
5. To identify that the key is present in which row and the column
a) we ground the bits of the row one by one
b) we ground the bits of the column one by one
c) we connect the bits of the row to the logic level 1 one by one
d) we can connect the columns to the logic level 1 one by one
View Answer
Answer: a
Explanation: To determine that the pressed key is in which row and column, we ground the rows one by one to determine the column by masking the bits separately.
6. The key detection and the key identification are two different procedures?
a) true
b) false
c) depends on the circumstances
d) difficult to tell
View Answer
Answer: a
Explanation: The key detection and the key identification are the two different procedures, one is used to detect that whether any key is pressed or not and the other technique is used to find that the pressed key is located in which row and column.
7. What is described by the following command?
KCODE0<<1
a) load KCODE0 with 0
b) rotate the contents of the KCODE0 register to the right
c) rotate the contents of the KCODE0 register to the left
d) none of the mentioned
View Answer
Answer: b
Explanation: KCODE0<<1 means to rotate the contents of the KCODE0 register to the left after every loop.
8. If the pins of the keyboard are used as an interrupt, then these pins will cause an interrupt of what type?
a) External hardware interrupt
b) Timer interrupt
c) TI/RI interrupt
d) None of the mentioned
View Answer
Answer: a
Explanation: The pins of the keyboard act as an external hardware interrupt as some external pulse is helping in generating this interrupt.
9. What will happen if the two keys of the keyboard are pressed at a time?
a) both the keys will be displayed on the screen
b) the key which is being actually pressed(for more then 20microseconds) will be displayed
c) the key that is pressed first will be displayed
d) none of the mentioned
View Answer
Answer: b
Explanation: If two or more keys are pressed at a time, then the key that will be pressed for more then 20 microseconds will be displayed on the screen.
10. Why initially all keys are considered open before detecting the key pressed?
a) to make the task easy
b) to remove the errors caused by other pressing keys during detection
c) to remove the flow problems
d) none of the mentioned
View Answer
Answer: b
Explanation: Initially all keys are considered open in order to ensure the accuracy while identification of the pressed key.
Sanfoundry Global Education & Learning Series – Microcontroller.
To practice all areas of Microcontroller Problems, here is complete set of 1000+ Multiple Choice Questions and Answers.
Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
This set of MSP430 Micro-controller Multiple Choice Questions & Answers (MCQs) focuses on “Architecture”.
1. In MSP430, the size of the status register is ________
a) 1 byte
b) 2 bytes
c) 1 bit
d) 2 bit
View Answer
Answer: b
Explanation: In MSP430, the size of the status register is 2 bytes. The bits of the status register consists of the C flag, Z flag, N flag, GIE flag, CPU off, OSC off, SCG0, SCG1, V flag and 7 reserved bits.
2. Which of the following bit/s of the status register that allows the microcontroller to operate in its low power mode?
a) Z
b) Reserved
c) CPU off
d) N
View Answer
Answer c
Explanation: The CPU off bit, OSC off bit, SCG0 bit, SCG1 bit of the status register are used to allow the microcontroller to operate in its low power mode.
3. What is actually done to improve the efficiency of a RISC processor?
a) instructions are reduced
b) they have two or more processors inbuilt connected between
c) they have many instructions that are interrelated to each other
d) they have one or more registers hard wired to the commonly used values
View Answer
Answer: d
Explanation: To improve the efficiency of the RISC processor, the registers that are hard wired to commonly used values are used instead of other ones.
4. To improve the efficiency of an MSP430 based microcontroller, for one register
a) there is only one value for all addressing modes
b) there are two values for each addressing mode
c) there are 2 values for four addressing modes
d) there are 4 values for four addressing modes
View Answer
Answer: d
Explanation: In MSP430, there are namely 4 addressing modes. So the main advantage of this controller( which basically increases its efficiency )is that for one register their exists 4 different values for 4 different addressing modes of the controller.
5. Their are_______________ number of emulated instructions found in the MSP430?
a) 4
b) 8
c) 16
d) 24
View Answer
Answer: d
Explanation: The constants CG1 and CG2 are combined together to give 27 native instructions. These instructions are further converted into 24 emulated instructions. So, there are 24 emulated instructions found in an MSP430 based controller.
6. .w form is used for operations
a) that uses bytes
b) that uses words
c) that uses both
d) that uses none
View Answer
Answer: c
Explanation: .w form is used for operations, that uses both bytes and words for operations.
7. Pre increment addressing is available in MSP430?
a) true
b) false
c) cant be said
d) depends on the conditions
View Answer
Answer: b
Explanation: MSP430 supports only post increment addressing. For performing pre increment addressing, we require some special functions that accomplish that work.
8. Which out of the following is a correct emulated instruction?
a) ADC(.B) dst
b) ADD(.B) src,dst
c) ADDC(.B) src,dst
d) AND(.B) src,dst
View Answer
Answer: a
Explanation: “ADC(.B) dst” this is emulated to “ADDC.B #0,dst” hence this is an emulated instruction. The emulated instructions use core instructions combined with the architecture and implementation of the CPU for higher code efficiency and faster execution.
9. dadd instruction can act as _____________
a) valid BCD addition
b) valid adder with carry
c) all of the mentioned
d) none of the mentioned
View Answer
Answer: a
Explanation: Dadd instruction can act as a valid BCD addition instruction if the numbers are initially in BCD state(0-9).
10. Which of the following instructions don’t affect the status bits?
a) bis
b) bic
c) bis & bic
d) none of the mentioned
View Answer
Answer: c
Explanation: bis and bic don’t affect the bits of the status register.
Sanfoundry Global Education & Learning Series – Microcontroller.
To practice all areas of Microcontroller, here is complete set of 1000+ Multiple Choice Questions and Answers.
Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!
This set of MSP430 Microcontroller online quiz focuses on “TIMER_B”.
1. Why Timer_B is not considered as most suitable one for receiving asynchronous signals?
a) because of the absence of the TBOUTH input pin
b) because of the presence of the TBOUTH input pin
c) because of the absence of the SCCI bit
d) because of the presence of the SCCI bit
View Answer
Answer: c
Explanation: The SCCI bit is absent in the Timer_B which means that the sampling mode is absent in it that’s why it is considered as unsuitable for receiving asynchronous signals.
2. There is double buffering in the immediate mode?
a) true
b) false
c) cant be said
d) depends on the conditions
View Answer
Answer: b
Explanation: Immediate mode offers no double buffering condition. As here, values are copied to TBCLn as soon as they are written to TBCCRn.
3. Double buffering protects channel 0.
a) as it acts as the limit in the Up and up/down modes
b) it doesn’t actually protect it
c) as it does not accept the inputs
d) none of the mentioned
View Answer
Answer: a
Explanation: Double buffering protects channel 0 as it acts as the limit in the Up and Up/Down modes.
4. Timer_B has _________
a) three serial communication ports
b) seven LCD driver
c) seven compare/capture channels
d) three LED driver ports
View Answer
Answer: c
Explanation: Timer_B has seven compare/capture channels.
5. The capture/compare registers TBCCRn are double-buffered when used for compare events?
a) true
b) false
c) cant be said
d) depends on the conditions
View Answer
Answer: a
Explanation: The capture/compare registers TBCCRn are double-buffered when used for compare events.
6. The length of TBR can be programmed to be _________
a) 8 bits
b) 12 bits
c) 16 bits
d) all of the mentioned
View Answer
Answer: d
Explanation: The length of TBR can be programmed to be 8, 12, 16 or 10 bits long.
7. TBOUTH can pin can be used to _________
a) values are moved from one place to another
b) the length of the number of bits is selected by this register
c) it can be used to put all the outputs of the Timer_B register in the high impedance state
d) it can be used for outputting the input values of the timers
View Answer
Answer: c
Explanation: TBOUTH pin is used to put all the outputs of the Timer_B register in the high impedance state by a high external signal applied to this pin.
8. TBCLn provided in each channel is actually _________
a) a comparator
b) compare latch
c) controller
d) control logic
View Answer
Answer: b
Explanation: TBCLn is actually a compare latch that is provided in its every channel.
9. When TBR counts to zero?
a) TBCLn is updated from TBCCRn
b) CLLDx is updated to TBCCTLn
c) CLLDx is updated to TBCCRn
d) TBCLn is updated to CLLDx
View Answer
Answer: a
Explanation: When TBR counts to zero, TBCLn is updated from TBCCRn.
Sanfoundry Global Education & Learning Series – Microcontroller.
To practice all areas of Microcontroller for online Quizzes, here is complete set of 1000+ Multiple Choice Questions and Answers.
Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!


{% include header.html %} {{content}} Community Resources Feedback Contributing Code of Conduct W3C Community Group ↳ {% include footer.html %}


Name of queue dirs split accross subdirs
hash_queue_names
This parameter specifies the names of queue directories that are split across
multiple subdirectory levels. Hashing MUST NOT be used with a world-writable
maildrop directory. Hashing MUST be used for the defer logfile directory, or
mail system performance will suffer.
Unfortunately, hashing the incoming or deferred queue can actually
slow the mail system down (mailq with an empty queue can take
several seconds) so it should be done only in case of emergency.


Known and unknown security and performance issues in 2.x have not been addressed since the last update (29 June, 2012). It is highly recommended to upgrade to Express 3.x or to Express 4.x.
High performance, high class web development for Node.js
$ npm install express
or to access the express(1)
executable install globally:
$ npm install -g express
The quickest way to get started with express is to utilize the executable express(1)
to generate an application as shown below:
Create the app:
$ npm install -g express
$ express /tmp/foo && cd /tmp/foo
Install dependencies:
$ npm install -d
Start the server:
$ node app.js
To create an instance of the express.HTTPServer, simply invoke the createServer() method. With our instance app we can then define routes based on the HTTP verbs, in this example app.get().
var app = require('express').createServer();
app.get('/', function(req, res){
res.send('hello world');
});
app.listen(3000);
To initialize a express.HTTPSServer we do the same as above, however we pass an options object, accepting key, cert and the others mentioned in node’s https documentation.
var app = require('express').createServer({ key: ... });
Express supports arbitrary environments, such as production and development. Developers can use the configure() method to setup needs required by the current environment. When configure() is called without an environment name it will be run in every environment prior to the environment specific callback.
In the example below we only dumpExceptions, and respond with exception stack traces in development mode, however for both environments we utilize methodOverride and bodyParser. Note the use of app.router, which can (optionally) be used to mount the application routes, otherwise the first call to app.get(), app.post(), etc will mount the routes.
app.configure(function(){
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.static(__dirname + '/public'));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
var oneYear =<PHONE_NUMBER>0;
app.use(express.static(__dirname + '/public', { maxAge: oneYear }));
app.use(express.errorHandler());
});
For similar environments you may also pass several env strings:
app.configure('stage', 'prod', function(){
// config
});
For internal and arbitrary settings Express provides the set(key[, val]), enable(key), disable(key) methods:
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('views');
// => "/absolute/path/to/views"
app.enable('some feature');
// same as app.set('some feature', true);
app.disable('some feature');
// same as app.set('some feature', false);
app.enabled('some feature')
// => false
});
To alter the environment we can set the NODE_ENV environment variable, for example:
$ NODE_ENV=production node app.js
This is very important, as many caching mechanisms are only enabled when in production.
Express supports the following settings out of the box:
Express utilizes the HTTP verbs to provide a meaningful, expressive routing API.
For example we may want to render a user’s account for the path /user/12, this
can be done by defining the route below. The values associated to the named placeholders
are available as req.params
.
app.get('/user/:id', function(req, res){
res.send('user ' + req.params.id);
});
A route is simple a string which is compiled to a RegExp internally. For example when /user/:id is compiled, a simplified version of the regexp may look similar to:
\/user\/([^\/]+)\/?
Regular expression literals may also be passed for complex uses. Since capture
groups with literal RegExp’s are anonymous we can access them directly req.params
. So our first capture group would be req.params[0] and the second would follow as req.params[1].
app.get(/^\/users?(?:\/(\d+)(?:\.\.(\d+))?)?/, function(req, res){
res.send(req.params);
});
Curl requests against the previously defined route:
$ curl http://dev:3000/user
[null,null]
$ curl http://dev:3000/users
[null,null]
$ curl http://dev:3000/users/1
["1",null]
$ curl http://dev:3000/users/1..15
["1","15"]
Below are some route examples, and the associated paths that they may consume:
"/user/:id"
/user/12
"/users/:id?"
/users/5
/users
"/files/*"
/files/jquery.js
/files/javascripts/jquery.js
"/file/*.*"
/files/jquery.js
/files/javascripts/jquery.js
"/user/:id/:operation?"
/user/1
/user/1/edit
"/products.:format"
/products.json
/products.xml
"/products.:format?"
/products.json
/products.xml
/products
"/user/:id.:format?"
/user/12
/user/12.json
For example we can POST some json, and echo the json back using the bodyParser middleware which will parse json request bodies (as well as others), and place the result in req.body:
var express = require('express')
, app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(req, res){
res.send(req.body);
});
app.listen(3000);
Typically we may use a “dumb” placeholder such as “/user/:id” which has no restrictions, however say for example we are limiting a user id to digits, we may use ‘/user/:id([0-9]+)’ which will not match unless the placeholder value contains only digits.
We may pass control to the next matching route, by calling the third argument, the next() function. When a match cannot be made, control is passed back to Connect, and middleware continue to be invoked in the order that they are added via use(). The same is true for several routes which have the same path defined, they will simply be executed in order until one does not call next() and decides to respond.
app.get('/users/:id?', function(req, res, next){
var id = req.params.id;
if (id) {
// do something
} else {
next();
}
});
app.get('/users', function(req, res){
// do something else
});
The app.all() method is useful for applying the same logic for all HTTP verbs in a single call. Below we use this to load a user from our fake database, and assign it to req.user.
var express = require('express')
, app = express.createServer();
var users = [{ name: 'tj' }];
app.all('/user/:id/:op?', function(req, res, next){
req.user = users[req.params.id];
if (req.user) {
next();
} else {
next(new Error('cannot find user ' + req.params.id));
}
});
app.get('/user/:id', function(req, res){
res.send('viewing ' + req.user.name);
});
app.get('/user/:id/edit', function(req, res){
res.send('editing ' + req.user.name);
});
app.put('/user/:id', function(req, res){
res.send('updating ' + req.user.name);
});
app.get('*', function(req, res){
res.send('what???', 404);
});
app.listen(3000);
Middleware via Connect can be passed to express.createServer() as you would with a regular Connect server. For example:
var express = require('express');
var app = express.createServer(
express.logger()
, express.bodyParser()
);
Alternatively we can use() them which is useful when adding middleware within configure() blocks, in a progressive manor.
app.use(express.logger({ format: ':method :url' }));
Typically with connect middleware you would require(‘connect’) like so:
var connect = require('connect');
app.use(connect.logger());
app.use(connect.bodyParser());
This is somewhat annoying, so express re-exports these middleware properties, however they are identical:
app.use(express.logger());
app.use(express.bodyParser());
Middleware ordering is important, when Connect receives a request the first middleware we pass to createServer() or use() is executed with three parameters, request, response, and a callback function usually named next. When next() is invoked the second middleware will then have it’s turn and so on. This is important to note because many middleware depend on each other, for example methodOverride() checks req.body.method for the HTTP method override, however bodyParser() parses the request body and populates req.body. Another example of this is cookie parsing and session support, we must first use() cookieParser() followed by session()_.
Many Express applications may contain the line app.use(app.router), while this may appear strange, it’s simply the middleware function that contains all defined routes, and performs route lookup based on the current request url and HTTP method. Express allows you to position this middleware, though by default it will be added to the bottom. By positioning the router, we can alter middleware precedence, for example we may want to add error reporting as the last middleware so that any exception passed to next() will be handled by it, or perhaps we want static file serving to have low precedence, allowing our routes to intercept requests to a static file to count downloads etc. This may look a little like below
app.use(express.logger(...));
app.use(express.bodyParser(...));
app.use(express.cookieParser(...));
app.use(express.session(...));
app.use(app.router);
app.use(express.static(...));
app.use(express.errorHandler(...));
First we add logger() so that it may wrap node’s req.end() method, providing us with response-time data. Next the request’s body will be parsed (if any), followed by cookie parsing and session support, meaning req.session will be defined by the time we hit our routes in app.router. If a request such as GET /javascripts/jquery.js is handled by our routes, and we do not call next() then the static() middleware will never see this request, however if were to define a route as shown below, we can record stats, refuse downloads, consume download credits etc.
var downloads = {};
app.use(app.router);
app.use(express.static(__dirname + '/public'));
app.get('/*', function(req, res, next){
var file = req.params[0];
downloads[file] = downloads[file] || 0;
downloads[file]++;
next();
});
Routes may utilize route-specific middleware by passing one or more additional callbacks (or arrays) to the method. This feature is extremely useful for restricting access, loading data used by the route etc.
Typically async data retrieval might look similar to below, where we take the :id parameter, and attempt loading a user.
app.get('/user/:id', function(req, res, next){
loadUser(req.params.id, function(err, user){
if (err) return next(err);
res.send('Viewing user ' + user.name);
});
});
To keep things DRY and to increase readability we can apply this logic within a middleware. As you can see below, abstracting this logic into middleware allows us to reuse it, and clean up our route at the same time.
function loadUser(req, res, next) {
// You would fetch your user from the db
var user = users[req.params.id];
if (user) {
req.user = user;
next();
} else {
next(new Error('Failed to load user ' + req.params.id));
}
}
app.get('/user/:id', loadUser, function(req, res){
res.send('Viewing user ' + req.user.name);
});
Multiple route middleware can be applied, and will be executed sequentially to apply further logic such as restricting access to a user account. In the example below only the authenticated user may edit his/her account.
function andRestrictToSelf(req, res, next) {
req.authenticatedUser.id == req.user.id
? next()
: next(new Error('Unauthorized'));
}
app.get('/user/:id/edit', loadUser, andRestrictToSelf, function(req, res){
res.send('Editing user ' + req.user.name);
});
Keeping in mind that middleware are simply functions, we can define function that returns the middleware in order to create a more expressive and flexible solution as shown below.
function andRestrictTo(role) {
return function(req, res, next) {
req.authenticatedUser.role == role
? next()
: next(new Error('Unauthorized'));
}
}
app.del('/user/:id', loadUser, andRestrictTo('admin'), function(req, res){
res.send('Deleted user ' + req.user.name);
});
Commonly used “stacks” of middleware can be passed as an array (applied recursively), which can be mixed and matched to any degree.
var a = [middleware1, middleware2]
, b = [middleware3, middleware4]
, all = [a, b];
app.get('/foo', a, function(){});
app.get('/bar', a, function(){});
app.get('/', a, middleware3, middleware4, function(){});
app.get('/', a, b, function(){});
app.get('/', all, function(){});
For this example in full, view the route middleware example in the repository.
There are times when we may want to “skip” passed remaining route middleware, but continue matching subsequent routes. To do this we invoke next()
with the string “route” next('route')
. If no remaining routes match the request url then Express will respond with 404 Not Found.
We have seen app.get() a few times, however Express also exposes other familiar HTTP verbs in the same manor, such as app.post(), app.del(), etc.
A common example for POST usage, is when “submitting” a form. Below we simply set our form method to “post” in our html, and control will be given to the route we have defined below it.
<form method="post" action="/">
<input type="text" name="user[name]" />
<input type="text" name="user[email]" />
<input type="submit" value="Submit" />
</form>
By default Express does not know what to do with this request body, so we should add the bodyParser middleware, which will parse application/x-www-form-urlencoded and application/json request bodies and place the variables in req.body. We can do this by “using” the middleware as shown below:
app.use(express.bodyParser());
Our route below will now have access to the req.body.user object which will contain the name and email properties when defined.
app.post('/', function(req, res){
console.log(req.body.user);
res.redirect('back');
});
When using methods such as PUT with a form, we can utilize a hidden input named _method, which can be used to alter the HTTP method. To do so we first need the methodOverride middleware, which should be placed below bodyParser so that it can utilize it’s req.body containing the form values.
app.use(express.bodyParser());
app.use(express.methodOverride());
The reason that these are not always defaults, is simply because these are not required for Express to be fully functional. Depending on the needs of your application, you may not need these at all, your methods such as PUT and DELETE can still be accessed by clients which can use them directly, although methodOverride provides a great solution for forms. Below shows what the usage of PUT might look like:
<form method="post" action="/">
<input type="hidden" name="_method" value="put" />
<input type="text" name="user[name]" />
<input type="text" name="user[email]" />
<input type="submit" value="Submit" />
</form>
app.put('/', function(){
console.log(req.body.user);
res.redirect('back');
});
Express provides the app.error() method which receives exceptions thrown within a route, or passed to next(err). Below is an example which serves different pages based on our ad-hoc NotFound exception:
function NotFound(msg){
this.name = 'NotFound';
Error.call(this, msg);
Error.captureStackTrace(this, arguments.callee);
}
NotFound.prototype.__proto__ = Error.prototype;
app.get('/404', function(req, res){
throw new NotFound;
});
app.get('/500', function(req, res){
throw new Error('keyboard cat!');
});
We can call app.error() several times as shown below. Here we check for an instanceof NotFound and show the 404 page, or we pass on to the next error handler.
Note that these handlers can be defined anywhere, as they will be placed below the route handlers on listen(). This allows for definition within configure() blocks so we can handle exceptions in different ways based on the environment.
app.error(function(err, req, res, next){
if (err instanceof NotFound) {
res.render('404.jade');
} else {
next(err);
}
});
Here we assume all errors as 500 for the simplicity of this demo, however you can choose whatever you like. For example when node performs filesystem syscalls, you may receive an error object with the error.code of ENOENT, meaning “no such file or directory”, we can utilize this in our error handling and display a page specific to this if desired.
app.error(function(err, req, res){
res.render('500.jade', {
error: err
});
});
Our apps could also utilize the Connect errorHandler middleware to report on exceptions. For example if we wish to output exceptions in “development” mode to stderr we can use:
app.use(express.errorHandler({ dumpExceptions: true }));
Also during development we may want fancy html pages to show exceptions that are passed or thrown, so we can set showStack to true:
app.use(express.errorHandler({ showStack: true, dumpExceptions: true }));
The errorHandler middleware also responds with json if Accept: application/json is present, which is useful for developing apps that rely heavily on client-side JavaScript.
Route param pre-conditions can drastically improve the readability of your application, through implicit loading of data, and validation of request urls. For example if you are constantly fetching common data for several routes, such as loading a user for /user/:id, we might typically do something like below:
app.get('/user/:userId', function(req, res, next){
User.get(req.params.userId, function(err, user){
if (err) return next(err);
res.send('user ' + user.name);
});
});
With preconditions our params can be mapped to callbacks which may perform validation, coercion, or even loading data from a database. Below we invoke app.param() with the parameter name we wish to map to some middleware, as you can see we receive the id argument which contains the placeholder value. Using this we load the user and perform error handling as usual, and simple call next() to pass control to the next precondition or route handler.
app.param('userId', function(req, res, next, id){
User.get(id, function(err, user){
if (err) return next(err);
if (!user) return next(new Error('failed to find user'));
req.user = user;
next();
});
});
Doing so, as mentioned drastically improves our route readability, and allows us to easily share this logic throughout our application:
app.get('/user/:userId', function(req, res){
res.send('user ' + req.user.name);
});
View filenames take the form “<name>.<engine>”, where <engine> is the name of the module that will be required. For example the view layout.ejs will tell the view system to require(‘ejs’), the module being loaded must export the method exports.compile(str, options), and return a Function to comply with Express. To alter this behaviour app.register() can be used to map engines to file extensions, so that for example “foo.html” can be rendered by ejs.
Below is an example using Jade to render index.html, and since we do not use layout: false the rendered contents of index.jade will be passed as the body local variable in layout.jade.
app.get('/', function(req, res){
res.render('index.jade', { title: 'My Site' });
});
The new view engine setting allows us to specify our default template engine, so for example when using jade we could set:
app.set('view engine', 'jade');
Allowing us to render with:
res.render('index');
vs:
res.render('index.jade');
When view engine is set, extensions are entirely optional, however we can still mix and match template engines:
res.render('another-page.ejs');
Express also provides the view options setting, which is applied each time a view is rendered, so for example if you rarely use layouts you may set:
app.set('view options', {
layout: false
});
Which can then be overridden within the res.render() call if need be:
res.render('myview.ejs', { layout: true });
When an alternate layout is required, we may also specify a path. For example if we have view engine set to jade and a file named ./views/mylayout.jade we can simply pass:
res.render('page', { layout: 'mylayout' });
Otherwise we must specify the extension:
res.render('page', { layout: 'mylayout.jade' });
These paths may also be absolute:
res.render('page', { layout: __dirname + '/../../mylayout.jade' });
A good example of this is specifying custom ejs opening and closing tags:
app.set('view options', {
open: '{{',
close: '}}'
});
The Express view system has built-in support for partials and collections, which are “mini” views representing a document fragment. For example rather than iterating in a view to display comments, we could use partial collection:
partial('comment', { collection: comments });
If no other options or local variables are desired, we can omit the object and simply pass our array, which is equivalent to above:
partial('comment', comments);
When using the partial collection support a few “magic” locals are provided for free:
Local variables passed (or generated) take precedence, however locals passed to the parent view are available in the child view as well. So for example if we were to render a blog post with partial(‘blog/post’, post) it would generate the post local, but the view calling this function had the local user, it would be available to the blog/post view as well.
For documentation on altering the object name view res.partial().
NOTE: be careful about when you use partial collections, as rendering an array with a length of 100 means we have to render 100 views. For simple collections you may inline the iteration instead of using partial collection support to decrease overhead.
View lookup is performed relative to the parent view, for example if we had a page view named views/user/list.jade, and within that view we did partial(‘edit’) it would attempt to load views/user/edit.jade, whereas partial(‘../messages’) would load views/messages.jade.
The view system also allows for index templates, allowing you to have a directory of the same name. For example within a route we may have res.render(‘users’) either views/users.jade, or views/users/index.jade.
When utilizing index views as shown above, we may reference views/users/index.jade from a view in the same directory by partial(‘users’), and the view system will try ../users/index, preventing us from needing to call partial(‘index’).
Below are a few template engines commonly used with Express:
Sessions support can be added by using Connect’s session middleware. To do so we also need the cookieParser middleware place above it, which will parse and populate cookie data to req.cookies.
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
By default the session middleware uses the memory store bundled with Connect, however many implementations exist. For example connect-redis supplies a Redis session store and can be used as shown below:
var RedisStore = require('connect-redis')(express);
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));
Now the req.session and req.sessionStore properties will be accessible to all routes and subsequent middleware. Properties on req.session are automatically saved on a response, so for example if we wish to shopping cart data:
var RedisStore = require('connect-redis')(express);
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat", store: new RedisStore }));
app.post('/add-to-cart', function(req, res){
// Perhaps we posted several items with a form
// (use the bodyParser() middleware for this)
var items = req.body.items;
req.session.items = items;
res.redirect('back');
});
app.get('/add-to-cart', function(req, res){
// When redirected back to GET /add-to-cart
// we could check req.session.items && req.session.items.length
// to print out a message
if (req.session.items && req.session.items.length) {
req.flash('info', 'You have %s items in your cart', req.session.items.length);
}
res.render('shopping-cart');
});
The req.session object also has methods such as Session#touch(), Session#destroy(), Session#regenerate() among others to maintain and manipulate sessions. For more information view the Connect Session documentation.
Express 1.x developers may reference the Migration Guide to get up to speed on how to upgrade your application to work with Express 2.x, Connect 1.x, and Node 0.4.x.
Get the case-insensitive request header key, with optional defaultValue:
req.header('Host');
req.header('host');
req.header('Accept', '*/*');
The Referrer and Referer header fields are special-cased, either will work:
// sent Referrer: http://google.com
req.header('Referer');
// => "http://google.com"
req.header('Referrer');
// => "http://google.com"
Check if the Accept header is present, and includes the given type.
When the Accept header is not present true is returned. Otherwise the given type is matched by an exact match, and then subtypes. You may pass the subtype such as “html” which is then converted internally to “text/html” using the mime lookup table.
// Accept: text/html
req.accepts('html');
// => true
// Accept: text/*; application/json
req.accepts('html');
req.accepts('text/html');
req.accepts('text/plain');
req.accepts('application/json');
// => true
req.accepts('image/png');
req.accepts('png');
// => false
Check if the incoming request contains the Content-Type header field, and it contains the give mime type.
// With Content-Type: text/html; charset=utf-8
req.is('html');
req.is('text/html');
// => true
// When Content-Type is application/json
req.is('json');
req.is('application/json');
// => true
req.is('html');
// => false
Ad-hoc callbacks can also be registered with Express, to perform assertions again the request, for example if we need an expressive way to check if our incoming request is an image, we can register “an image” callback:
app.is('an image', function(req){
return 0 == req.headers['content-type'].indexOf('image');
});
Now within our route callbacks, we can use to to assert content types such as “image/jpeg”, “image/png”, etc.
app.post('/image/upload', function(req, res, next){
if (req.is('an image')) {
// do something
} else {
next();
}
});
Keep in mind this method is not limited to checking Content-Type, you can perform any request assertion you wish.
Wildcard matches can also be made, simplifying our example above for “an image”, by asserting the subtype only:
req.is('image/*');
We may also assert the type as shown below, which would return true for “application/json”, and “text/json”.
req.is('*/json');
Return the value of param name when present or default.
To utilize urlencoded request bodies, req.body should be an object. This can be done by using the _express.bodyParser middleware.
Get field’s param value, defaulting to ‘’ when the param or field is not present.
req.get('content-disposition', 'filename');
// => "something.png"
req.get('Content-Type', 'boundary');
// => "--foo-bar-baz"
Queue flash msg of the given type.
req.flash('info', 'email sent');
req.flash('error', 'email delivery failed');
req.flash('info', 'email re-sent');
// => 2
req.flash('info');
// => ['email sent', 'email re-sent']
req.flash('info');
// => []
req.flash();
// => { error: ['email delivery failed'], info: [] }
Flash notification message may also utilize formatters, by default only the %s string formatter is available:
req.flash('info', 'email delivery to _%s_ from _%s_ failed.', toUser, fromUser);
Also aliased as req.xhr, this getter checks the X-Requested-With header to see if it was issued by an XMLHttpRequest:
req.xhr
req.isXMLHttpRequest
Get or set the response header key.
res.header('Content-Length');
// => undefined
res.header('Content-Length', 123);
// => 123
res.header('Content-Length');
// => 123
Sets the charset for subsequent Content-Type
header fields. For example res.send()
and res.render()
default to “utf8”, so we may explicitly set the charset before rendering a template:
res.charset = 'ISO-8859-1';
res.render('users');
or before responding with res.send()
:
res.charset = 'ISO-8859-1';
res.send(str);
or with node’s res.end()
:
res.charset = 'ISO-8859-1';
res.header('Content-Type', 'text/plain');
res.end(str);
Sets the Content-Type response header to the given type.
var filename = 'path/to/image.png';
res.contentType(filename);
// Content-Type is now "image/png"
A literal Content-Type works as well:
res.contentType('application/json');
Or simply the extension without leading .
:
res.contentType('json');
Sets the Content-Disposition response header to “attachment”, with optional filename.
res.attachment('path/to/my/image.png');
Used by res.download()
to transfer an arbitrary file.
res.sendfile('path/to/my.file');
This method accepts an optional callback which is called when
an error occurs, or when the transfer is complete. By default failures call next(err)
, however when a callback is supplied you must do this explicitly, or act on the error.
res.sendfile(path, function(err){
if (err) {
next(err);
} else {
console.log('transferred %s', path);
}
});
Options may also be passed to the internal fs.createReadStream() call, for example altering the bufferSize:
res.sendfile(path, { bufferSize: 1024 }, function(err){
// handle
});
Transfer the given file as an attachment with optional alternative filename.
res.download('path/to/image.png');
res.download('path/to/image.png', 'foo.png');
This is equivalent to:
res.attachment(file);
res.sendfile(file);
An optional callback may be supplied as either the second or third argument, which is passed to res.sendfile(). Within this callback you may still respond, as the header has not been sent.
res.download(path, 'expenses.doc', function(err){
// handle
});
An optional second callback, callback2 may be given to allow you to act on connection related errors, however you should not attempt to respond.
res.download(path, function(err){
// error or finished
}, function(err){
// connection related error
});
The res.send() method is a high level response utility allowing you to pass objects to respond with json, strings for html, Buffer instances, or numbers representing the status code. The following are all valid uses:
res.send(); // 204
res.send(new Buffer('wahoo'));
res.send({ some: 'json' });
res.send('<p>some html</p>');
res.send('Sorry, cant find that', 404);
res.send('text', { 'Content-Type': 'text/plain' }, 201);
res.send(404);
By default the Content-Type response header is set, however if explicitly
assigned through res.send()
or previously with res.header()
or res.contentType()
it will not be set again.
Note that this method end()s the response, so you will want to use node’s res.write() for multiple writes or streaming.
Send a JSON response with optional headers and status. This method is ideal for JSON-only APIs, however res.send(obj) will send JSON as well, though not ideal for cases when you want to send for example a string as JSON, since the default for res.send(string) is text/html.
res.json(null);
res.json({ user: 'tj' });
res.json('oh noes!', 500);
res.json('I dont have that', 404);
Redirect to the given url with a default response status of 302.
res.redirect('/', 301);
res.redirect('/account');
res.redirect('http://google.com');
res.redirect('home');
res.redirect('back');
Express supports “redirect mapping”, which by default provides home, and back. The back map checks the Referrer and Referer headers, while home utilizes the “basepath” setting and defaults to “/”.
Sets the given cookie name to val, with options httpOnly, secure, expires etc. The path option defaults to the app’s “basepath” setting, which is typically “/”.
// "Remember me" for 15 minutes
res.cookie('rememberme', 'yes', { expires: new Date(Date.now() + 900000), httpOnly: true });
The maxAge property may be used to set expires relative to Date.now() in milliseconds, so our example above can now become:
res.cookie('rememberme', 'yes', { maxAge: 900000 });
To parse incoming Cookie headers, use the cookieParser middleware, which provides the req.cookies object:
app.use(express.cookieParser());
app.get('/', function(req, res){
// use req.cookies.rememberme
});
Clear cookie name by setting “expires” far in the past. Much like res.cookie() the path option also defaults to the “basepath” setting.
res.clearCookie('rememberme');
Render view with the given options and optional callback fn. When a callback function is given a response will not be made automatically, however otherwise a response of 200 and text/html is given.
The options passed are the local variables as well, for example if we want to expose “user” to the view, and prevent a local we do so within the same object:
var user = { name: 'tj' };
res.render('index', { layout: false, user: user });
This options object is also considered an “options” object. For example when you pass the status local, it’s not only available to the view, it sets the response status to this number. This is also useful if a template engine accepts specific options, such as debug, or compress. Below is an example of how one might render an error page, passing the status for display, as well as it setting res.statusCode.
res.render('error', { status: 500, message: 'Internal Server Error' });
Render view partial with the given options. This method is always available to the view as a local variable.
as Variable name for each collection or object value, defaults to the view name.
collection Array of objects, the name is derived from the view name itself. For example video.html will have a object video available to it.
The following are equivalent, and the name of collection value when passed to the partial will be movie as derived from the name.
partial('theatre/movie.jade', { collection: movies });
partial('theatre/movie.jade', movies);
partial('movie.jade', { collection: movies });
partial('movie.jade', movies);
partial('movie', movies);
// In view: movie.director
To change the local from movie to video we can use the “as” option:
partial('movie', { collection: movies, as: 'video' });
// In view: video.director
Also we can make our movie the value of this within our view so that instead of movie.director we could use this.director.
partial('movie', { collection: movies, as: this });
// In view: this.director
Another alternative is to “expand” the properties of the collection item into pseudo globals (local variables) by using as: global, which again is syntactic sugar:
partial('movie', { collection: movies, as: global });
// In view: director
This same logic applies to a single partial object usage:
partial('movie', { object: movie, as: this });
// In view: this.director
partial('movie', { object: movie, as: global });
// In view: director
partial('movie', { object: movie, as: 'video' });
// In view: video.director
partial('movie', { object: movie });
// In view: movie.director
When a non-collection (does not have .length) is passed as the second argument, it is assumed to be the object, after which the object’s local variable name is derived from the view name:
var movie = new Movie('Nightmare Before Christmas', 'Tim Burton')
partial('movie', movie)
// => In view: movie.director
The exception of this, is when a “plain” object, aka “{}” or “new Object” is passed, which is considered an object with local variable. For example some may expect a “movie” local with the following, however since it is a plain object “director” and “title” are simply locals:
var movie = { title: 'Nightmare Before Christmas', director: 'Tim Burton' };
partial('movie', movie)
For cases like this where passing a plain object is desired, simply assign it to a key, or use the object
key which will use the filename-derived variable name. The examples below are equivalent:
partial('movie', { locals: { movie: movie }})
partial('movie', { movie: movie })
partial('movie', { object: movie })
This exact API can be utilized from within a route, to respond with a fragment via Ajax or WebSockets, for example we can render a collection of users directly from a route:
app.get('/users', function(req, res){
if (req.xhr) {
// respond with the each user in the collection
// passed to the "user" view
res.partial('user', users);
} else {
// respond with layout, and users page
// which internally does partial('user', users)
// along with other UI
res.render('users', { users: users });
}
});
Get or set the given local variable name. The locals built up for a response are applied to those given to the view rendering methods such as res.render()
.
app.all('/movie/:id', function(req, res, next){
Movie.get(req.params.id, function(err, movie){
// Assigns res.locals.movie = movie
res.local('movie', movie);
});
});
app.get('/movie/:id', function(req, res){
// movie is already a local, however we
// can pass more if we wish
res.render('movie', { displayReviews: true });
});
Assign several locals with the given obj. The following are equivalent:
res.local('foo', bar);
res.local('bar', baz);
res.locals({ foo: bar, bar, baz });
Apply an application level setting name to val, or get the value of name when val is not present:
app.set('views', __dirname + '/views');
app.set('views');
// => ...path...
Alternatively you may simply access the settings via app.settings:
app.settings.views
// => ...path...
Enable the given setting name:
app.enable('some arbitrary setting');
app.set('some arbitrary setting');
// => true
app.enabled('some arbitrary setting');
// => true
Check if setting name is enabled:
app.enabled('view cache');
// => false
app.enable('view cache');
app.enabled('view cache');
// => true
Disable the given setting name:
app.disable('some setting');
app.set('some setting');
// => false
app.disabled('some setting');
// => false
Check if setting name is disabled:
app.enable('view cache');
app.disabled('view cache');
// => false
app.disable('view cache');
app.disabled('view cache');
// => true
Define a callback function for the given env (or all environments) with callback function:
app.configure(function(){
// executed for each env
});
app.configure('development', function(){
// executed for 'development' only
});
For use with res.redirect() we can map redirects at the application level as shown below:
app.redirect('google', 'http://google.com');
Now in a route we may call:
res.redirect(‘google’);
We may also map dynamic redirects:
app.redirect('comments', function(req, res){
return '/post/' + req.params.id + '/comments';
});
So now we may do the following, and the redirect will dynamically adjust to the context of the request. If we called this route with GET /post/12 our redirect Location would be /post/12/comments.
app.get('/post/:id', function(req, res){
res.redirect('comments');
});
When mounted, res.redirect() will respect the mount-point. For example if a blog app is mounted at /blog, the following will redirect to /blog/posts:
res.redirect('/posts');
Adds an error handler function which will receive the exception as the first parameter as shown below. Note that we may set several error handlers by making several calls to this method, however the handler should call next(err) if it does not wish to deal with the exception:
app.error(function(err, req, res, next){
res.send(err.message, 500);
});
Registers static view helpers.
app.helpers({
name: function(first, last){ return first + ', ' + last }
, firstName: 'tj'
, lastName: 'holowaychuk'
});
Our view could now utilize the firstName and lastName variables, as well as the name() function exposed.
<%= name(firstName, lastName) %>
Express also provides a few locals by default:
- `settings` the app's settings object
- `layout(path)` specify the layout from within a view
This method is aliased as app.locals().
Registers dynamic view helpers. Dynamic view helpers are simply functions which accept req, res, and are evaluated against the Server instance before a view is rendered. The return value of this function becomes the local variable it is associated with.
app.dynamicHelpers({
session: function(req, res){
return req.session;
}
});
All views would now have session available so that session data can be accessed via session.name etc:
<%= session.name %>
The app.lookup http methods returns an array of callback functions associated with the given path.
Suppose we define the following routes:
app.get('/user/:id', function(){});
app.put('/user/:id', function(){});
app.get('/user/:id/:op?', function(){});
We can utilize this lookup functionality to check which routes have been defined, which can be extremely useful for higher level frameworks built on Express.
app.lookup.get('/user/:id');
// => [Function]
app.lookup.get('/user/:id/:op?');
// => [Function]
app.lookup.put('/user/:id');
// => [Function]
app.lookup.all('/user/:id');
// => [Function, Function]
app.lookup.all('/hey');
// => []
To alias app.lookup.VERB(), we can simply invoke app.VERB() without a callback, as a shortcut, for example the following are equivalent:
app.lookup.get('/user');
app.get('/user');
Each function returned has the following properties:
var fn = app.get('/user/:id/:op?')[0];
fn.regexp
// => /^\/user\/(?:([^\/]+?))(?:\/([^\/]+?))?\/?$/i
fn.keys
// => ['id', 'op']
fn.path
// => '/user/:id/:op?'
fn.method
// => 'GET'
The app.match http methods return an array of callback functions which match the given url, which may include a query string etc. This is useful when you want reflect on which routes have the opportunity to respond.
Suppose we define the following routes:
app.get('/user/:id', function(){});
app.put('/user/:id', function(){});
app.get('/user/:id/:op?', function(){});
Our match against GET will return two functions, since the :op in our second route is optional.
app.match.get('/user/1');
// => [Function, Function]
This second call returns only the callback for /user/:id/:op?.
app.match.get('/user/23/edit');
// => [Function]
We can also use all() to disregard the http method:
app.match.all('/user/20');
// => [Function, Function, Function]
Each function matched has the following properties:
var fn = app.match.get('/user/23/edit')[0];
fn.keys
// => ['id', 'op']
fn.params
// => { id: '23', op: 'edit' }
fn.method
// => 'GET'
Assign a callback fn which is called when this Server is passed to Server#use().
var app = express.createServer(),
blog = express.createServer();
blog.mounted(function(parent){
// parent is app
// "this" is blog
});
app.use(blog);
Register the given template engine exports as ext. For example we may wish to map “.html” files to jade:
app.register('.html', require('jade'));
This is also useful for libraries that may not match extensions correctly. For example my haml.js library is installed from npm as “hamljs” so instead of layout.hamljs, we can register the engine as “.haml”:
app.register('.haml', require('haml-js'));
For engines that do not comply with the Express specification, we can also wrap their api this way. Below we map .md to render markdown files, rendering the html once since it will not change on subsequent calls, and support local substitution in the form of “{name}”.
app.register('.md', {
compile: function(str, options){
var html = md.toHTML(str);
return function(locals){
return html.replace(/\{([^}]+)\}/g, function(_, name){
return locals[name];
});
};
}
});
Bind the app server to the given port, which defaults to 3000. When host is omitted all connections will be accepted via INADDR_ANY.
app.listen();
app.listen(3000);
app.listen(3000, 'n.n.n.n');
The port argument may also be a string representing the path to a unix domain socket:
app.listen('/tmp/express.sock');
Then try it out:
$ telnet /tmp/express.sock
GET / HTTP/1.1
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 11
Hello World


You slowly step through the dark, holding onto the wall for guidance. You start to hear the rats closing in, and within a few minutes they begin to take tentative bites at your feet. Before you can react, they swarm over you, tearing through clothes and flesh. You have fallen victim to the swarm!


My Favorite Thingies
These are a few of the things I like
People
Here are some of my favorite people.
John Carmack
John Romero
Brian Fargo
Tim Cain
Chris Avellone
Favorite Food
These are my three favorite foods
Shrimp Yakisoba.
Mushroom, Swiss, Avacado/Guacamole, Bacon Cheeseburger.
Soylent Green.
Thanks for reading this list!


| crashrpt | |
| A crash reporting system for Windows applications |
Defines | |
| #define | Install InstallA |
| Character set-independent mapping of InstallW() and InstallA() functions. | |
| #define | AddFile AddFileA |
| Character set-independent mapping of AddFileW() and AddFileA() functions. | |
| #define | crAddFile crAddFileA |
| Character set-independent mapping of crAddFileW() and crAddFileA() functions. | |
Functions | |
| LPVOID | InstallW (LPGETLOGFILE pfnCallback, LPCWSTR pszEmailTo, LPCWSTR pszEmailSubject) |
| Installs exception handlers for the current process. | |
| LPVOID | InstallA (LPGETLOGFILE pfnCallback, LPCSTR pszEmailTo, LPCSTR pszEmailSubject) |
| void | Uninstall (LPVOID lpState) |
| Uninstalls the exception filters set up by Install(). | |
| void | AddFileW (LPVOID lpState, LPCWSTR pszFile, LPCWSTR pszDesc) |
| Adds a file to the crash report. | |
| void | AddFileA (LPVOID lpState, LPCSTR pszFile, LPCSTR pszDesc) |
| void | GenerateErrorReport (LPVOID lpState, PEXCEPTION_POINTERS pExInfo) |
| Generates the crash report. | |
| int | crInstallToCurrentThread () |
| Installs exception handlers to the current thread. | |
| int | crAddFileW (LPCWSTR pszFile, LPCWSTR pszDesc) |
| Adds a file to crash report. | |
| int | crAddFileA (LPCSTR pszFile, LPCSTR pszDesc) |
| int | crExceptionFilter (unsigned int code, struct _EXCEPTION_POINTERS *ep) |
| Can be used as a SEH exception filter. |
| void AddFileA | ( | LPVOID | lpState, | |
| LPCSTR | pszFile, | |||
| LPCSTR | pszDesc | |||
| ) |
Adds a file to the crash report.
| [in] | lpState | State information returned from Install(), ignored and should be NULL. |
| [in] | pszFile | Fully qualified file name. |
| [in] | pszDesc | Description of the file, used by the Error Report Details dialog. |
pszFile should be a valid absolute path of a file to add to crash report.
pszDesc is a description of a file. It can be NULL.
Function fails if pszFile doesn't exist at the moment of function call.
AddFileW() and AddFileA() are wide-character and multibyte-character versions of AddFile(). The AddFile() macro defines character set independent mapping for these functions.
| void AddFileW | ( | LPVOID | lpState, | |
| LPCWSTR | pszFile, | |||
| LPCWSTR | pszDesc | |||
| ) |
Adds a file to the crash report.
| [in] | lpState | State information returned from Install(), ignored and should be NULL. |
| [in] | pszFile | Fully qualified file name. |
| [in] | pszDesc | Description of the file, used by the Error Report Details dialog. |
pszFile should be a valid absolute path of a file to add to crash report.
pszDesc is a description of a file. It can be NULL.
Function fails if pszFile doesn't exist at the moment of function call.
AddFileW() and AddFileA() are wide-character and multibyte-character versions of AddFile(). The AddFile() macro defines character set independent mapping for these functions.
| int crAddFileA | ( | LPCSTR | pszFile, | |
| LPCSTR | pszDesc | |||
| ) |
Adds a file to crash report.
| [in] | pszFile | Absolute path to the file to add. |
| [in] | pszDesc | File description (used in Error Report Details dialog). |
When this function is called, the file is marked to be added to the error report, then the function returns control to the caller. When crash occurs, all marked files are added to the report by the CrashSender.exe process. If a file is locked by someone for exclusive access, the file won't be included. Inside of LPGETLOGFILE crash callback, ensure files to be included are acessible for reading.
pszFile should be a valid absolute path of a file to add to crash report.
pszDesc is a description of a file. It can be NULL.
This function fails if pszFile doesn't exist at the moment of function call.
The crAddFileW() and crAddFileA() are wide-character and multibyte-character versions of crAddFile() function. The crAddFile() macro defines character set independent mapping.
| int crAddFileW | ( | LPCWSTR | pszFile, | |
| LPCWSTR | pszDesc | |||
| ) |
Adds a file to crash report.
| [in] | pszFile | Absolute path to the file to add. |
| [in] | pszDesc | File description (used in Error Report Details dialog). |
When this function is called, the file is marked to be added to the error report, then the function returns control to the caller. When crash occurs, all marked files are added to the report by the CrashSender.exe process. If a file is locked by someone for exclusive access, the file won't be included. Inside of LPGETLOGFILE crash callback, ensure files to be included are acessible for reading.
pszFile should be a valid absolute path of a file to add to crash report.
pszDesc is a description of a file. It can be NULL.
This function fails if pszFile doesn't exist at the moment of function call.
The crAddFileW() and crAddFileA() are wide-character and multibyte-character versions of crAddFile() function. The crAddFile() macro defines character set independent mapping.
| int crExceptionFilter | ( | unsigned int | code, | |
| struct _EXCEPTION_POINTERS * | ep | |||
| ) |
Can be used as a SEH exception filter.
EXCEPTION_EXECUTE_HANDLER
if succeeds, else EXCEPTION_CONTINUE_SEARCH
.| [in] | code | Exception code. |
| [in] | ep | Exception pointers. |
This function can be called instead of a SEH exception filter inside of __try{}__except(Expression){} statement. The function generates a error report and returns control to the exception handler block.
The exception code is usually retrieved with GetExceptionCode() intrinsic function and the exception pointers are retrieved with GetExceptionInformation() intrinsic function.
If an error occurs, this function returns EXCEPTION_CONTINUE_SEARCH
. Use crGetLastErrorMsg() to retrieve the error message on fail.
The following example shows how to use crExceptionFilter().
int* p = NULL; // pointer to NULL __try { *p = 13; // causes an access violation exception; } __except(crExceptionFilter(GetExceptionCode(), GetExceptionInformation())) { // Terminate program ExitProcess(1); }
| int crInstallToCurrentThread | ( | ) |
Installs exception handlers to the current thread.
The list of C++ exception/error handlers installed with this function:
set_terminate()
]set_unexpected()
]signal(SIGFPE)
]signal(SIGILL)
]signal(SIGSEGV)
]The crInstall() function automatically installs C++ exception handlers for the main thread, so no need to call crInstallToCurrentThread() for the main thread.
This function fails if calling it twice for the same thread. When this function fails, use crGetLastErrorMsg() to retrieve the error message.
Call crUninstallFromCurrentThread() to uninstall C++ exception handlers from current thread.
This function is deprecatd. The crInstallToCurrentThread2() function gives better control of what exception handlers to install.
| void GenerateErrorReport | ( | LPVOID | lpState, | |
| PEXCEPTION_POINTERS | pExInfo | |||
| ) |
Generates the crash report.
| [in] | lpState | State information returned from Install(), ignored and should be NULL. |
| [in] | pExInfo | Pointer to an EXCEPTION_POINTERS structure, can be NULL. |
The crash report contains the crash minidump, crash description in XML format and (optionally) additional files.
pExInfo defines the exception pointers for generating crash minidump file. If pExInfo is NULL, current CPU state is used to create exception pointers.
This function generates the error report and returns control to the caller. It doesn't terminate the caller process.
| LPVOID InstallA | ( | LPGETLOGFILE | pfnCallback, | |
| LPCSTR | pszEmailTo, | |||
| LPCSTR | pszEmailSubject | |||
| ) |
Installs exception handlers for the current process.
| [in] | pfnCallback | Client crash callback. |
| [in] | pszEmailTo | Email address to send crash report to. |
| [in] | pszEmailSubject | Subject of the E-mail message. |
pfnCallback defines the callback function that is called on crash. This parameter can be NULL.
pszEmailTo should be the valid email address of recipient.
pszEmailSubject is the email subject. If this parameter is NULL, the default subject is generated.
This function assumes that CrashSender.exe is located in the same directory as CrashRpt.dll loaded by the caller process. To specify different directory, use crInstall().
On crash, the error report is sent as E-mail message using address and subject passed to the function as pszEmailTo and pszEmailSubject parameters, respectively.
InstallW() and InstallA() are wide-character and multibyte-character versions of Install(). The Install() macro defines character set independent mapping for these functions.
| LPVOID InstallW | ( | LPGETLOGFILE | pfnCallback, | |
| LPCWSTR | pszEmailTo, | |||
| LPCWSTR | pszEmailSubject | |||
| ) |
Installs exception handlers for the current process.
| [in] | pfnCallback | Client crash callback. |
| [in] | pszEmailTo | Email address to send crash report to. |
| [in] | pszEmailSubject | Subject of the E-mail message. |
pfnCallback defines the callback function that is called on crash. This parameter can be NULL.
pszEmailTo should be the valid email address of recipient.
pszEmailSubject is the email subject. If this parameter is NULL, the default subject is generated.
This function assumes that CrashSender.exe is located in the same directory as CrashRpt.dll loaded by the caller process. To specify different directory, use crInstall().
On crash, the error report is sent as E-mail message using address and subject passed to the function as pszEmailTo and pszEmailSubject parameters, respectively.
InstallW() and InstallA() are wide-character and multibyte-character versions of Install(). The Install() macro defines character set independent mapping for these functions.
| void Uninstall | ( | LPVOID | lpState | ) |


All solutions of this exercise are corrected or at least there are
no solutions left for you to correct.
You may now select a different exercise to continue
correcting. Or maybe you want to take a break?
All solutions of this exercise are corrected or at least there are
no solutions left for you to correct.
You may now select a different exercise to continue
correcting. Or maybe you want to take a break?


Seed-based Correlation Analysis (SCA) and Dual Regression¶
Connectivity in the Brain¶
Brain connectivity can refer to multiple distinct concepts, and it is important to understand the differences between them. When referring to anatomy, connectivity may refer to physical connections between brain areas, such as the long-distance fiber tracts revealed through methods such as Diffusion Tensor Imaging. Another form of connectivity that is commonly discussed in the literature is “functional connectivity”, which is what we will be focusing on here.
What is Functional Connectivity?¶
Perhaps the most confusing thing to understand about functional connectivity is that in most cases, connectivity is never actually measured. This is because the term “functional connectivity” has come to refer to similarities in patterns of brain activity between regions. Two regions are said to be functionally connected if the time series of their activity is highly correlated. The reasoning behind this definition is that brain areas with similar activity patterns are likely to be communicating and sharing information.
Seed-based Correlation Analysis¶
Seed-based Correlation Analysis (SCA) is one of the most common ways to explore functional connectivity within the brain. Based on the time series of a seed voxel (or ROI), connectivity is calculated as the correlation of time series for all other voxels in the brain. The result of SCA is a connectivity map showing Z-scores for each voxel indicating how well its time series correlates with the time series of the seed. Below is an example connectivity map showing correlated voxels based on a seed in the precuneus.
Astute readers will note that the pattern of connectivity mapped above closely resembles the anatomy of the Default Network. Indeed, SCA may be used to explore functional networks that share similar patterns of activity.
 Dual Regression (Beckman et al, 2009; Filippini et al, 2009) allows researchers to investigate individual and group differences in the structure of these networks, as well as to identify subject-specific networks based on networks identified at the group level.
The following steps are performed for each spatial map provided for Dual Regression:
- Spatial Regression: The spatial map is used as a spatial regressor in a GLM to find the time series associated with the voxels in that map.
- Temporal Regression: The time series found by spatial regression is then used as a temporal regressor to find the full set of voxels associated with that time series.
The result of these steps is a subject-specific spatial map based on the original spatial map.
The spatial maps used during Dual Regression can be generated any number of ways, but a common practice is to use Independent Component Analysis (Smith et al, 2009) or clustering algorithms (Yeo et al, 2011) to generate group-specific maps of large-scale brain networks.
Configuring C-PAC¶
Before SCA can be calculated, you must first extract a seed time series from which to calculate correlations. This is done by configuring and running Time Series Extraction. You will not be able to proceed in the GUI without first entering in an ROI Specification, and will receive an error if the specification is not defined.
Run Seed-based Correlation Analysis (SCA) - [Off, On]: For each extracted ROI Average and/or ROI Voxelwise time series, CPAC will generate a whole-brain correlation map. It should be noted that for a given seed/ROI, SCA maps for ROI Average and ROI Voxelwise time series will be the same.
- SCA ROI Paths - [path dialogue]: Clicking on the + icon to the right of the box here will bring up a dialog where you can define multiple paths to NifTIs containing ROI masks. You may add multiple ROIs to the box. Three columns within the box can be checked on and off to enable specific options for SCA/Dual Regression:
- Avg - Run seed-based correlation analysis using the average time series of each ROI.
- DualReg - Run dual regression for each ROI.
- MultiReg - Run a multiple regression SCA where C-PAC will enter all extracted time series from ROI Average TSE, ROI Voxelwise TSE, and Spatial Regression into a single multiple regression model and output a single correlation map.
Normalize Time Series (Dual Regression) - [True, False]: Normalize each time series before running Dual Regression.
Configuration Without the GUI¶
The following key/value pairs must be defined in your pipeline configuration YAML for C-PAC to run SCA:
| Key | Description | Potential Values |
|---|---|---|
| runSCA | Run seed-based correlation analysis. Must have defined roiSpecificationFileForSCA and maskSpecificationFileForSCA. | A list where ‘1’ represents ‘yes’ and ‘0’ represents ‘no’ (e.g., ‘[1]’). |
| sca_roi_paths | A list of paths to ROI masks. | Denote which analyses to run for each ROI path by listing 1s or 0s. For example, if you wish to run Avg and MultReg, you would enter: ‘/path/to/ROI.nii.gz’: 1,0,1 |
| drNorm | Normalize time series before running dual regression. | A boolean (‘True’ or ‘False’). |
References¶
C.F. Beckmann, C.E. Mackay, N. Filippini, and S.M. Smith. Group comparison of resting-state FMRI data using multi-subject ICA and dual regression . OHBM, 2009.
- Filippini, B.J. MacIntosh, M.G. Hough, G.M. Goodwin, G.B. Frisoni, S.M. Smith, P.M. Matthews, C.F. Beckmann and C.E. Mackay. Distinct patterns of brain activity in young carriers of the APOE-ε4 allele . PNAS, 106(17):7209-14, 2009.
Smith, S. M., Fox, P. T., Miller, K. L., Glahn, D. C., Fox, P. M., Mackay, C. E., et al. (2009). Correspondence of the brain’s functional architecture during activation and rest. Proceedings of the National Academy of Sciences of the United States of America, 106(31), 13040–13045. doi:10.1073/pnas.0905267106
Thomas Yeo, B. T., Krienen, F. M., Sepulcre, J., Sabuncu, M. R., Lashkari, D., Hollinshead, M., et al. (2011). The organization of the human cerebral cortex estimated by intrinsic functional connectivity. Journal of Neurophysiology, 106(3), 1125–1165. doi:10.1152/jn.00338.2011
External Resources¶
- mindhive - ConnectivityFAQ
- Brain Connectivity - Scholarpedia


Bits & Bytes Pizza
Order Now
Menu
Customize Your Pie:
What size pizza would you like?
---Choose a Size---
Small
Medium
Large
What toppings would you like to include?
No Sauce
Onions
Olives
Pepperoni
Sausage
Chicken
Prototype Sauce
Place Order
Order Summary:
×
Create Your Own Pizza
No sauce to our house made Prototype Sauce, the world is your oyster...err...pizza!


Id: 30
Name: Earth (Unknown dimension)
Type: Planet
Dimension: unknown
Residents: ['https://rickandmortyapi.com/api/character/94']
Url: https://rickandmortyapi.com/api/location/30
Created: 2017-12-01T11:49:43.923Z


ASTRO take you behind the scenes of 'Blue Flame' MV
by germainejASTRO have dropped the making of their music video for "Blue Flame"!
In the making-of video, the ASTRO members describe their latest track, poke fun at each other, and try to stay cool on set. "Blue Flame" is the title song of the group's sixth mini album of the same name, and it's about being instinctively attracted to someone.
Watch ASTRO's "Blue Flame" making-of video above and their MV here if you missed it!


-
The cost of a basic WordPress site
Stop me if you heard this one. A person walks up to a web developer and asks, “So how much would it cost for, like, a basic website?”” We’ve all been there and have tried to explain that “it depends” without coming off sounding like a shyster.
-
What is a CDN? A visual explanation
A CDN (Content Delivery Network) is becoming more and more commonplace in hosting plan offerings and a must for an business site. By hosting web content on servers that are spread across the globe, you can deliver content to any user faster by targeting servers that are relatively more local to them.
-
How to succeed when working remotely: Lessons learned from a Chinese buffet
Working from home can be an amazingly fulfilling career experience. Likewise, a trip to your local Chinese food buffet can be a culinary delight. But both can also be abjectly horrible. Here is my breakdown on how to succeed at working remotely without the debilitating pains of post-dumpling bloat.
-
The AUX of WP: Rethinking the WordPress writing experience
Before I was a web professional, before all the project management, front-end coding, and CMS rejiggering, I was an English major. My BA is in writing and, as such, I tend to approach most things I do from the stance of an author.
-
Seven things you can never say on project calls
The words we use communicate shades of meaning that we might not want. Here’s a list of seven words that I strive to not use when discussing a project with a client or with my team.
- Older posts Newer posts


Torque 2D - Whack-A-Mole Tutorial Part 5
Part 5 - If I had a Hammer...
Drag in your hammer
The last thing that is missing is the hammer. Drag the animHammerIdle animation from the Animated Sprites tab into your level. It looks just like the animHammer animation, so check the tooltip to be sure you have the right one. Select it and set it's Name property to moleHammer (this is found under the Edit->Scripting tab).
Then put the following function in moleLevel.cs:
function SceneWindow2D::onMouseMove(%this, %mod, %worldPosition) { moleHammer.setPosition(%worldPosition); }
Code Sample 5.1
This will make the hammer sprite follow the mouse cursor. Let's also hide the regular cursor. Add this line to startGame() in game.cs:
function startGame(%level) { //exec game scripts exec("./mole.cs"); exec("./molelevel.cs"); // Set The GUI. Canvas.setContent(mainScreenGui); Canvas.setCursor(DefaultCursor); // Hide the cursor Canvas.hideCursor(); moveMap.push(); // this has been added: sceneWindow2D.setUseObjectMouseEvents( true ); if( isFile( %level ) || isFile( %level @ ".dso")) sceneWindow2D.loadLevel(%level); moleGuiGameOver.visible = 0; }
Code Sample 5.2
...and when the game ends replace your old endGame function in game.cs with this one:
function endGame() { Canvas.showCursor(); sceneWindow2D.endLevel(); moveMap.pop(); }
Code Sample 5.3
And lastly we want the hammer to strike if a mole is hit. Modify mole::onMouseDown():
function mole::onMouseDown(%this, %modifier, %worldPosition, %mouseClicks) { if(%this.getAnimationName() $= ("animMoleComeOut" @ %this.moleColor) ) { %this.playAnimation( "animMoleWhacked" @ %this.moleColor ); //let the hammer strike, with animation auto-restore moleHammer.playAnimation( "animHammer", true ); } }
Code Sample 5.4
And now, at long last, we are finally finished! Test it out and enjoy!
Revision 2.1


Our main goals for this week will be to:
Here is very nice example of what can be done with HTML/CSS and PhoneGap:
The current release of Eclipse is called Juno. The URL for updates is:
If you choose Help | Install New Software from the Eclipse menu, you should be able to open the Word With drop down and see the following item:
If you select this item, and look through the available options, you will see a section on Web, XML, Java EE and OSGi Enterprise Development. Look down toward the bottom of the section Web Page Editor. Install it.
The JsHint install into Eclipse is covered here:
Summary:
http://github.eclipsesource.com/jshint-eclipse/updates/
In Eclipse:
Covered here:


# File lib/faraday_middleware/response/chunked.rb, line 25 def chunked_encoding?(headers) encoding = headers[TRANSFER_ENCODING] and encoding.split(',').include?('chunked') end


{% extends "base.html" %} {% block content %}
There seems to be no event names that match this.
You can make a new event by making a new post


--- title: What do Phonegap, Canvas and Urine have in Common? from PhoneGap Day EU 2012 author: Colene Chow format: html tags: - PhoneGap Day - Video ---
Thank you to everyone who attended PhoneGap Day EU and made it such a huge success. Here's the next highlight video for those of you who weren't able to attend.
Our next video is from Ian Jorgensen who intrigued the audience with his title "What do Phonegap, Canvas and Urine have in Common?". It turns out that the answer is "Quite a lot!". Ian participated in Health Hackday in Stockholm which is a 24-hour competition to create an app related to healthcare. Ian's talk covers how they used PhoneGap to create Piddle, an app that helps people with urine analysis.
There are no slides from Ian's presentation but view the recording from PhoneGap Day EU below and check out his app Piddle.


Click this button to add a payment manually. This was called an "R3" payment. Only a Financial Technician can add an over-the-counter payment. Refunds Sections workers can add "Prior Payment Recorded" records that are never treated as payments except for initial calculations. Receivables Technicians can add adjustments. Over-the-counter payment and adjustments must be approved by supervisors before taking effect.