#flatmap example
Explore tagged Tumblr posts
souhaillaghchimdev · 11 days ago
Text
Kotlin: 100 Simple Codes
Tumblr media
Kotlin: 100 Simple Codes
beginner-friendly collection of easy-to-understand Kotlin examples.
Tumblr media
Each code snippet is designed to help you learn programming concepts step by step, from basic syntax to simple projects. Perfect for students, self-learners, and anyone who wants to practice Kotlin in a fun and practical way.
Codes:
1. Hello World
2. Variables and Constants
3. If-Else Statement
4. When Statement (Switch)
5. For Loop
6. While Loop
7. Functions
8. Return Value from Function
9. Array Example
10. List Example
===
11. Mutable List
12. Map Example
13. Mutable Map
14. Class Example
15. Constructor with Default Value
16. Nullable Variable
17. Safe Call Operator
18. Elvis Operator
19. Data Class
20. Loop with Index
===
21. Lambda Function
22. Higher-Order Function
23. Filter a List
24. Map a List
25. String Interpolation
26. String Templates with Expressions
27. Read-Only vs Mutable List
28. Check Element in List
29. Exception Handling
30. Null Check with let
===
31. For Loop with Step
32. For Loop in Reverse
33. Break in Loop
34. Continue in Loop
35. Check String Empty or Not
36. Compare Two Numbers
37. Array Access by Index
38. Loop Through Map
39. Default Parameters in Function
40. Named Arguments
===
41. Range Check
42. Function Returning Unit
43. Multiple Return Statements
44. Chained Method Calls
45. Function Inside Function
46. Function Expression Syntax
47. Array Size
48. String to Int Conversion
49. Safe String to Int Conversion
50. Repeat Block
===
51. Sealed Class
52. Object Expression (Anonymous Object)
53. Singleton using Object Keyword
54. Extension Function
55. Enum Class
56. Use Enum in When Statement
57. Type Alias
58. Destructuring Declarations
59. Companion Object
60. Simple Interface Implementation
===
61. Abstract Class
62. Lateinit Variable
63. Initialization Block
64. Secondary Constructor
65. Nested Class
66. Inner Class
67. Generic Function
68. Generic Class
69. Custom Getter
70. Custom Setter
===
71. String Equality
72. Loop with Range Until
73. Using Pair
74. Triple Example
75. Check Type with is
76. Smart Cast
77. Type Casting with as
78. Safe Casting with as?
79. Loop Through Characters of String
80. Sum of List
===
81. Min and Max of List
82. Sort List
83. Reverse List
84. Count Items in List
85. All / Any Conditions
86. Check if List is Empty
87. Join List to String
88. Take and Drop
89. Zipping Lists
90. Unzipping Pairs
===
91. Chunked List
92. Windowed List
93. Flatten List
94. FlatMap
95. Remove Duplicates
96. Group By
97. Associate By
98. Measure Execution Time
99. Repeat with Index
100. Create Range and Convert to List
===
0 notes
javainspires · 1 year ago
Video
youtube
Java 8 FlatMap Example Java Inspires
0 notes
javatute673 · 2 years ago
Text
Java Stream flatMap()
Tumblr media
0 notes
lovecreat12345 · 6 years ago
Text
FlatMap In Angular
FlatMap In Angular
This Article is about FlatMap In Angular. Let’s say we wanted to implement an AJAX search feature in which every keypress in a text field will automatically perform a search and update the page with the results. How would this look? Well we would have an Observablesubscribed to events coming from an input field, and on every change of input we want to perform some HTTP…
View On WordPress
0 notes
qianglialee-blog · 6 years ago
Text
The Neurome Project
The Short Introduction of The Neurome Project
Project leader: Dr. Larry W. Swanson
Toward a Pan-Mammalian Neurome
The neurome project aim can be divided two parts:
'proximal' goal
Complete construction and network analysis of macroconnection subconnectomes for the mammalian forebrain.
'distal' goal
Achieve this for all major brain parts, and eventually the entire nervous system, leading to integration with other brain data (such as gene-expression) at multiple levels of spatial resolution.
Chapter 1 Connection
In the connection section, the project main collects three part of connection, they are Cerebral cortex, Cerebral nuclei, Hypothalamus. Here mammalian animal model is Rat.
Cerebral cortex: provides a searchable list of region-to-region (macroscale) collated published connection reports (macroconnections) for the cerebral cortex of the rat. Currently, these data include reports of macroconnections within the cerebral cortex, and between the cerebral cortex and cerebral nuclei (basal ganglia).
Cerebral nuclei: provides a searchable list of region-to-region (macroscale) collated published connection reports (macroconnections) for the cerebral nuclei (basal ganglia) of the rat. Currently, these data include reports of macroconnections within the cerebral nuclei, and between the cerebral nuclei and cerebral cortex.
Hypothalamus: provides a searchable list of region-to-region (macroscale) collated published connection reports (macroconnections) for the hypothalamus of the rat. Currently, these data include reports of macroconnections within the hypothalamus (intrahypothalamic macroconnections).
Region nomenclature follows an open access atlas for the rat brain (Brain Maps 4.0. Swanson, L. W. 2018). Part of figures see Appendix.
Chapter 2 Rat neurome project
Connectome
The term “connectome” was introduced by Olaf Sporns, Giulio Tononi, and Rolf Kötter in a 2005 paper, The human connectome: a structural description of the human brain, where they stated that “The connection matrix of the human brain (the human ��connectome’) represents an indispensable foundation for basic and applied neurobiological research.”
A complete connectome would include not just the brain, but the nervous system as a whole, along with the other systems of the body (muscular, endocrine, digestive, and so on) related to the nervous system (that is, providing inputs and receiving outputs)–a connection matrix that has been called a neurome (Bota et al., 2015, PNAS). Here is the general form of such a complete connectome, which, of course, is bilateral, representing the right and left halves of the body:
A series of flatmaps from the neural plate stage to the adult central nervous system.
Chapter 3 Flatmaps
Comparison of rat and human central nervous system flatmaps.
MAPPING CONNECTIONS ON STANDARD TEMPLATES
Since 1992, virtually all of the experimental pathway tracing analyses carried out by the Swanson group in rat have been mapped onto standard atlas and flatmap templates from the 3 editions of Brain maps: structure of the rat brain (Swanson, 1992, 1998, 2004). This approach greatly simplifies qualitative comparisons of connection patterns for different parts of the nervous system. The first example was for the connections of the posterior nucleus of the amygdala, and adjacent parts of the cortical nucleus of the amygdala (Canteras et al., 1992).
Online resources
Text for the first three print editions of the atlas (Swanson, 1992, 1993, 1998, 2004), and accompanying files for illustrations, are freely available under a Creative Commons BY‐NC 4.0 license at larrywswanson.com.
List of Larry’s papers on the behavioral neuroscience of motivation and emotion.
List of Larry’s publications on the nervous system as a network like the Internet rather than a hierarchy like the military.
List of Larry’s papers on the structural neuroscience of connections forming the circuitry underlying motivation and emotion.
List of Larry’s papers related to neuroanatomical methodology.
List of Larry’s papers on development of brain structural organization.
BRAIN MAPS 4.0 (2018): Online open access.
DEVELOPMENTAL BRAIN MAPS (1996): Atlas Levels for download
The Mouse Connectome Project: An online resource for extensive information about the mouse connectome project led by Hong-Wei Dong at the University of Southern California.
Golgi: A prototype “Google Maps for the Brain” website was developed by Ramsay Brown.
NeuARt II: This is a website for layering neuroanatomical or functional data over standard atlas levels of brain atlases. Its development began in the late 1990s and is currently on hold, although still under the careful watch of Gully Burns.
Appendix
1. Brain maps 4.0—Structure of the rat brain: An open access atlas with global nervous system nomenclature ontology and flatmaps
Abstract The fourth edition (following editions in 1992, 1998, 2004) of Brain maps: structure of the rat brain is presented here as an open access internet resource for the neuroscience community. One new feature is a set of 10 hierarchical nomenclature tables that define and describe all parts of the rat nervous system within the framework of a strictly topographic system devised previously for the human nervous system. These tables constitute a global ontology for knowledge management systems dealing with neural circuitry. A second new feature is an aligned atlas of bilateral flatmaps illustrating rat nervous system development from the neural plate stage to the adult stage, where most gray matter regions, white matter tracts, ganglia, and nerves listed in the nomenclature tables are illustrated schematically. These flatmaps are convenient for future development of online applications analogous to “Google Maps” for systems neuroscience. The third new feature is a completely revised Atlas of the rat brain in spatially aligned transverse sections that can serve as a framework for 3‐D modeling. Atlas parcellation is little changed from the preceding edition, but the nomenclature for rat is now aligned with an emerging panmammalian neuroanatomical nomenclature. All figures are presented in Adobe Illustrator vector graphics format that can be manipulated, modified, and resized as desired, and freely used with a Creative Commons license.
2.Neuroscience History
History of Neuroscience, Dr. Larry W. Swanson's Lecture at the 39th annual meeting of the Society for Neuroscience in Chicago (October 20, 2009).
Compelete poster(including images) link Here
References
Monro, A. secundus (1783). Observations on the Structure and Functions of the Nervous System: Illustrated with Tables (Creech & Johnson, Edinburgh).
Sporns, O., Tononi, G., Kotter, R. (2005). The human connectome: A structural description of the human brain. PLoS Comput Biol. 1, e42. doi: 10.1371/journal.pcbi.0010042
Bota, M., Sporns, O., Swanson, L.W. (2015). Architecture of the cerebral cortical association connectome underlying cognition. Proc Natl Acad Sci U S A. 112, E2093-2101. doi: 10.1073/pnas.1504394112
Swanson, L.W. & Lichtman, J.W. (2016). From Cajal to Connectome and Beyond. Annu Rev Neurosci. 39, 197-216. doi: 10.1146/annurev-neuro-071714-033954
Swanson, L.W. & Bota, M. (2010). Foundational model of structural connectivity in the nervous system with a schema for wiring diagrams, connectome, and basic plan architecture. Proc Natl Acad Sci U S A. 107, 20610-20617. doi: 10.1073/pnas.1015128107
Swanson, L.W. (2018). Brain Maps 4.0—Structure of the rat brain: An open access atlas with global nervous system nomenclature ontology and flatmaps. Swanson, L.W. (2018). J Comp Neurol. 526, 935-943. doi: 10.1002/cne.24381
Hahn, J.D. & Swanson, L.W. (2015). Distinct patterns of neural inputs and outputs of the dorsal and ventral zones of the juxtaventromedial region of the lateral hypothalamic area in the male rat. Front Syst Neurosci. 9. doi: 10.3389/fnsys.2015.00066
Jeub, L.G.S., Sporns, O., Fortunato, S. (2018). Multiresolution consensus clustering in networks. Sci Rep. 8:3259. doi: 10.1038/s41598-018-21352-7
Swanson, L.W., Sporns, O., Hahn, J.D. (2016). Network architecture of the cerebral nuclei (basal ganglia) association and commissural connectome. Proc Natl Acad Sci U S A. 113, E5972-E5981. doi: 10.1073/pnas.1613184113
Swanson, L.W., Hahn, J.D., Sporns, O. (2017). Organizing principles for the cerebral cortex network of commissural and association connections. Proc Natl Acad Sci U S A. 114, E9692-E9701. doi: 10.1073/pnas.1712928114
Swanson, L.W., Hahn, J.D., Jeub, L.G.S., Fortunato, S., Sporns, O. (2018). Subsystem organization of axonal connections within and between the right and left cerebral cortex and cerebral nuclei (endbrain). Proc Natl Acad Sci U S A. 115, E6910-E6919. doi: 10.1073/pnas.1807255115
Hahn, J.D., Sporns, O., Watts, A.G., Swanson, L.W. (2019). Macroscale intrinsic network architecture of the hypothalamus. Proc Natl Acad Sci U S A. (in press)
1 note · View note
proeduorganization · 2 years ago
Text
How to create Spark dataframe in different ways
How to create Spark Dataframe in multiple ways.
Hello Friends. In this post we will see several examples of how to create a Spark dataframe in different ways. You might also be interested in our RDD tutorials like map, flatmap, reduceByKey. Data Preparation First of all, we will create some sample data and read that as RDD. // Lets prepare some data. val records = List( ("Prakash", "30", "Male", "Uttrakhand"), ("Amit", "35", "Male",…
Tumblr media
View On WordPress
0 notes
js-functional-programming · 3 years ago
Video
youtube
Monads object with "of" and "chain" functions
💥Monads 💥 👉A monad is an object with "of" and "chain" functions. chain is like map except it un-nests the resulting nested object. 👉 A monad is an object with of and chain functions. chain is like map except it un-nests the resulting nested object. 👉 of is also known as return in other functional languages. 👉 Chain is also known as flatmap and bind in other languages. 👉 A monad applies wrapped function that returns wrapped value to the wrapped value. Example : Types are monads 👉Box 👉Either 👉Task 👉List
0 notes
swampcomputeremporium · 4 years ago
Text
Useful JavaScript things (or awful corner cases) that I’ve seen people not know
Enumerability and ownership of properties (the spread operator isn’t listed here, but only handles enumerable owned properties)
Prototypal inheritance
Labeled break/continue (useful for nested for/while loops)
IIFEs (mostly outdated now)
Array#flatMap() (which both map() and filter() can be implemented in terms of - I didn’t know this was a thing until last week)
Hoisting and block vs. function scope (grepping `var` in a sufficiently modern codebase will give you a list of neat scope tricks)
Private and protected members (outdated, but an example of a neat scope trick)
Automatic semicolon insertion ambiguity (more common in TypeScript - e.g. `let a = foo[1] \n (b as any)._enfuckerate(a)`)
0 notes
codezup · 4 years ago
Text
indexOf() & lastIndexOf() Array Methods in Javascript ES6 | Example
indexOf() & lastIndexOf() Array Methods in Javascript ES6 | Example
Hi, in this tutorial, we are going to talk about the indexOf() and lastIndexOf() array method in Javascript ES6 with an example. indexOf & lastIndexOf() Method in Javascript We have already discussed some array methods like reduce, filter, map, find, slice, splice, flatMap, concat, sort, and many more in the last few articles. So, we will continue the array methods discussion and today we will…
Tumblr media
View On WordPress
0 notes
felord · 4 years ago
Text
Adv LAB 5- SCALA FUNCTIONAL PROGRAMMING TECHNIQUES Solved
Adv LAB 5- SCALA FUNCTIONAL PROGRAMMING TECHNIQUES Solved
In this lab you will gain further practice in functional programming in Scala and learn how to create a simple menu-driven application in Scala. You will work with partial function application and currying, and see examples of the use of map, flatMap and for comprehensions. For this lab you should create an IntelliJ Scala project lab5project. Tasks 1 and 2 can be done with Scala worksheets, while…
Tumblr media
View On WordPress
0 notes
sparkbyexamples · 4 years ago
Text
Spark map() vs flatMap() with Examples
Spark map() vs flatMap() with Examples
What is the difference between Spark map() vs flatMap() is a most asked interview question, if you are taking an interview on Spark (Java/Scala/PySpark), so let’s understand the differences with examples? Regardless of an interview, you have to know the differences as this is also one of the most used Spark transformations. map() – Spark map() transformation applies a function to each row in a…
View On WordPress
0 notes
nirajmchauhan · 5 years ago
Text
Difference between Map & Flatmap | RXJava
RXJava can be very intimidating at first go. Reactive Extensions - RX is all about data streams & handling them and three important pillars for it are Observables, Operators & Schedulers.
Initially, while using operators I was very confused between map and flatMap. And this confusion still exists today with all beginners. So let me help you to clear this confusion.
Map
Map operator transforms the items from data stream by applying a function to each item. Lets look at below code which will output length of words.
Example:
String line = "Lorem Ipsum is simply dummy text"; List words = Arrays.asList(line.split(" ")); Observable.from(words) .map(w -> { return String.format("%s => %s", w, w.length()); }).subscribe(System.out::println);
Here we are passing list of words to map. For each word it formats it and return back to the stream.
Marble Diagram:
Tumblr media
FlatMap
FlatMap operator transforms the items from data stream into observables and then it flattens all observables into single observable. Lets look at below code which will output letters from words.
String line = "Lorem Ipsum is simply dummy text"; List words = Arrays.asList(line.split(" ")); Observable.from(words) .flatMap(w -> { return Observable.from(w.split("")); }).subscribe(System.out::println);
Confused??
In map when word Lorem was passed, it transformed it into Lorem => 5. But when we passed same word to flatMap, it transformed it into ["L","o","r","e","m"]. So flatMap can emit one or more than one values whereas map emits only one. Because its an array, flatMap flattens all values in a single stream.
Marble Diagram:
Tumblr media
0 notes
siva3155 · 5 years ago
Text
300+ TOP SCALA Interview Questions and Answers
SCALA Interview Questions for freshers experienced :-
1. What is Scala? Scala is a Java-based Hybrid programming language which is the fusion of both Functional and Object-Oriented Programming Language features. It can integrate itself with Java Virtual Machine and compile the code written. 2. How Scala is both Functional and Object-oriented Programming Language? Scala treats every single value as an Object which even includes Functions. Hence, Scala is the fusion of both Object-oriented and Functional programming features. 3.Write a few Frameworks of Scala Some of the Frameworks supported by Scala are as follows: Akka Framework Spark Framework Play Framework Scalding Framework Neo4j Framework Lift Framework Bowler Framework 4. Explain the types of Variables in Scala? And What is the difference between them? The Variables in Scala are mainly of two types: Mutable Variables We Declare Mutable Variables by using the var keyword. The values in the Mutable Variables support Changes Immutable Variables We declare Immutable Variables using the val keyword. The values in Immutable Variables do not support changes. 5. Explain Streams in Scala. In simple words, we define Stream as a Lazy list which evaluates the elements only when it needs to. This sort of lazy computation enhances the Performance of the program. 6. Mention the Advantages of Scala Some of the major Advantages of Scala are as follows: It is highly Scalable It is highly Testable It is highly Maintainable and Productive It facilitates Concurrent programming It is both Object-Oriented and Functional It has no Boilerplate code Singleton objects are a cleaner solution than Static Scala Arrays use regular Generics Scala has Native Tuples and Concise code 7. Explain the Operators in Scala The following are the Operators in Scala: Arithmetic Operators Relational Operators Logical Operators Bitwise Operators Assignment Operators 8. What is Recursion tail in Scala? ‘Recursion’ is a function that calls itself. For example, a function ‘A’ calls function ‘B’, which calls the function ‘C’. It is a technique used frequently in Functional programming. In order for a Tail recursive, the call back to the function must be the last function to be performed. 9. Explain the use of Tuples in Scala? Scala tuples combine a Finite number of items together so that the programmer can Pass a tuple around as a Whole. Unlike an Array or List, a tuple is Immutable and can hold objects with different Datatypes. 10. How is a Class different from an Object? Class combines the data and its methods whereas an Object is one particular Instance in a class.
Tumblr media
SCALA Interview Questions 11. Why do we need App in Scala? App is a helper class that holds the main method and its Members together. The App trait can be used to quickly turn Objects into Executable programs. We can have our classes extend App to render the executable code. object Edureka extends App{ println("Hello World") } 12. What are Higher-order functions? A Higher-order function is a function that does at least one of the following: takes one or more Functions as Arguments, returns a Function as its result. 13. Explain the scope provided for variables in Scala. There are three different scopes depending upon their use. Namely: Fields: Fields are variables declared inside an object and they can be accessed anywhere inside the program depending upon the access modifiers. Fields can be declared using var as well as val. Method Parameters: Method parameters are strictly Immutable. Method parameters are mainly used to Pass values to the methods. These are accessed inside a method, but it is possible to access them from outside the method provided by a Reference. Local Variables: Local variables are declared inside a method and they are accessible only inside the method. They can be accessed if you return them from the method. 14. What is a Closure? Closure is considered as a Function whose return value is Dependent upon the value of one or more variables declared outside the closure function. Course Curriculum Apache Spark and Scala Certification Training Instructor-led SessionsReal-life Case StudiesAssessmentsLifetime Access Example: val multiplier = (i:Int) => i * 10 Here the only variable used in the function body, i * 10 , is i, which is defined as a parameter to the function 15. Explain Traits in Scala. A Trait can be defined as a unit which Encapsulates the method and its variables or fields. The following example will help us understand in a better way. trait Printable{ def print() } class A4 extends Printable{ def print(){ println("Hello") } } object MainObject{ def main(args:Array){ var a = new A4() a.print() } } 16. Mention how Scala is different from Java A few scenarios where Scala differs from Java are as follows: All values are treated as Objects. Scala supports Closures Scala Supports Concurrency. It has Type-Inference. Scala can support Nested functions. It has DSL support Traits 17. Explain extend Keyword You can extend a base Scala class and you can design an Inherited class in the same way you do it in Java by using extends keyword, but there are two restrictions: method Overriding requires the override keyword, and only the Primary constructor can pass parameters to the base Constructor. Let us understand by the following example println("How to extend abstract class Parent and define a sub-class of Parent called Child") class Child=(name:String)extends Parent(name){ override def printName:Unit= println(name) } object Child { def apply(name:String):Parent={ new Child(name) } } 18. Explain implicit classes with syntax Implicit classes allow Implicit conversations with the class’s Primary constructor when the class is in scope. Implicit class is a class marked with the “implicit” keyword. This feature was introduced in with Scala 2.10 version. //Syntax: object { implicit class Data type) { def Unit = xyz } } 19. Explain the access Modifiers available in Scala There are mainly three access Modifiers available in Scala. Namely, Private: The Accessibility of a private member is restricted to the Class or the Object in which it declared. The following program will explain this in detail. class Outer { class Inner { private def f() { println("f") } class InnerMost { f() // OK } } (new Inner).f() // Error: f is not accessible } Protected: A protected member is only Accessible from Subclasses of the class in which the member is defined. The following program will explain this in detail. package p class Super { protected def f() { println("f") } } class Sub extends Super { f() } class Other { (new Super).f() // Error: f is not accessible } } Public: Unlike Private and Protected members, it is not required to specify Public keyword for Public members. There is no explicit modifier for public members. Such members can be accessed from Anywhere. Following is the example code snippet to explain Public member class Outer { class Inner { def f() { println("f") } class InnerMost { f() // OK } } (new Inner).f() // OK because now f() is public } 20. What is a Monad in Scala? A Monad is an object that wraps another object. You pass the Monad mini-programs, i.e functions, to perform the data manipulation of the underlying object, instead of manipulating the object directly. Monad chooses how to apply the program to the underlying object. 21. Explain the Scala Anonymous Function. In the Source code, Anonymous functions are called ‘Function literals’ and at run time, function literals are instantiated into objects called Function values. Scala provides a relatively easy Syntax for defining Anonymous functions. //Syntax (z:Int, y:Int)=> z*y Or (_:Int)*(_Int) 22. How do I Append data in a list? In Scala to Append into a List, We have the following methods: use “:+” single value var myList = List.empty myList :+= "a" 23. Why Scala prefers Immutability? Scala prefers Immutability in design and in many cases uses it as default. Immutability can help when dealing with Equality issues or Concurrent programs. 24. Give some examples of Packages in Scala The three important and default Packages in Scala are as follows: Java.lang._ : Java.lang._ package in Java. Provides classes that are fundamental to the design of the Java programming language. Java.io._ : Java.io._ Package used to import every class in Scala for input-output resources. PreDef: Predef provides type aliases for types which are commonly used, such as the immutable collection types Map, Set, and the List constructors 25. Why is an Option used in Scala? Option in Scala is used to Wrap the Missing value. 26. Mention the Identifiers in Scala. There are four types of Scala Identifiers: Alphanumeric identifiers Operator identifiers Mixed identifiers Literal identifiers //Scala program to demonstrate Identifiers in Scala. object Main { //Main method def main(args: Array) { //Valid Identifiers var 'name = "Hari"' var age = 20; var Branch = "Computer Science" println() println() println() } } 27. How do you define a function in Scala? def keyword is used to define the Function in Scala. object add { def addInt( a:Int, b:Int ) : Int = { var sum:Int = 0 sum = a + b return sum } } 28. How is the Scala code compiled? Code is written in Scala IDE or a Scala REPL, Later, the code is converted into a Byte code and transferred to the JVM or Java Virtual Machine for compilation. Big Data Training 29. Explain the functionality of Yield. Yield is used with a loop, Yield produces a value for each iteration. Another way to do is to use map/flatMap and filter with nomads. for (i "#FF0000", "azure" -> "#F0FFFF") 39. Explain Exception Handling in Scala Throw Exception: Throwing an exception looks the same as in Java. You create an exception object and then you throw it with the throw keyword as follows. Throw new IllegalArgumentException Catching an Exception: Scala allows you to try/catch any exception in a single block and then perform pattern matching against it using case blocks. Try the following example program to handle the exception. Example: import java.io.FileReader import java.io.FileNotFoundException import java.io.IOException object Demo { def main(args: Array) { try { val f = new FileReader("input.txt") } catch { case ex: FileNotFoundException ={ println("Missing file exception") } case ex: IOException = { println("IO Exception") } } } } So, with this, we finished some questions on the Intermediate Level. Now, Let us move to the next level of interview questions which happen to be the Advanced Level Interview Questions. 40. Explain Pattern Matching in Scala through an example A Pattern match includes a sequence of alternatives, each starting with the Keyword case. Each alternative includes a Pattern and one or more Expressions, Scala evaluates whenever a pattern matches. An arrow symbol => separates the pattern from the expressions. Try the following example program, which shows how to match against an integer value. object Demo { def main(args: Array) { println(matchTest(3)) } def matchTest(x: Int): String = x match { case 1 = "one" case 2 = "two" case _ = "other" } } 41. Explain Extractors in Scala Course Curriculum Apache Spark and Scala Certification Training Weekday / Weekend Batches An Extractor in Scala is an object that has a method called unapply as one of its members. The purpose of that unapply method is to match the value and take it apart. 42. What is the result of x+y*z and why? Similar to any other programming language, Scala also follows Presidency and Priority tables. According to the tables, Scala Performs the operations as follows. Scala evaluates y*z first. Then adds (y*z) with x 43. What is an Auxiliary constructor We use Auxiliary constructor in Scala for Constructor Overloading. The Auxiliary Constructor must call either previously defined auxiliary constructors or primary constructor in the first line of its body. 44. Explain recursion through a program def factorial_loop(i: BigInt): BigInt = { var result = BigInt(1) for (j- 2 to i.intValue) result *= j result } for (i - 1 to 10) format("%s: %sn", i, factorial_loop(i)) 45. Explain Que with example Queue is a Data Structure similar to Stack except, it follows First In First Out procedure for data processing. In Scala, to work with Queues, you need to import a library called, import scala.collection.mutable.Queue val empty = new Queue SCALA Questions and Answers Pdf Download Read the full article
0 notes
fishcodesuniverse-blog · 6 years ago
Text
RxAndroid Learnings.
RxAndroid is a library that handles any asynchronous data streams.
What r async data streams:
click event
push notifications
keyboard input
reading a file
database access
device sensor updates
They happen at anytime and outside of normal flow of program execution. 
Benefits of Rx:
Chaining
Abstraction
Threading
Non-blocking
Composable
avoid callbacks
data transformation 
Function map does data transformation.
Example of Observable with data transformation: 
Observable.just( 5, 6, 7 )              .map {  “;-) “.repeat(it) }              .subscribe { println(it) }
Result:
;-) ;-) ;-) ;-) ;-)  ;-) ;-) ;-) ;-) ;-) ;-)  ;-) ;-) ;-) ;-) ;-) ;-) ;-) 
Example of Observable with chaining:
Observable.just( 5, 6, 7 )             .map {  “;-) “.repeat(it) }             .filter {  it.length < 24 }             .subscribe { println(it) }
Result: 
;-) ;-) ;-) ;-) ;-)
E.g. kotlin collections
Example: 
listOf ( 5, 6, 7 )       .map { it * 5 }       .filter { it > 25 } 
Process: 
5  6  7   map into
25   30   35
filter into
30  35
Disadvantage: 
extra overhead 
blocking async manner
LAZY - will not create intermediate list with same result.
listOf ( 5, 6, 7 )       .asSequence()      .map { it * 5 }      .filter { it > 25 }      .toList() 
RxJava vs Kotlin
in Rx is ok to not have any data initially.  Rx is also lazy
Rx has flexible threading model.  Can choose thread to do the work on by using Schedulers. 
3 Basic of Rx (3o’s)
Observer
Observables
Operators
Observable
U can think of this as producing a stream of events that you are interested in knowing bout. 
Observable can be Hot or Cold manner Hot: Start doing work as soon as it gets created. It is not waiting for anyone else before getting “busy”.  Example: Click events
Cold: They dont work until someone shows interest. It doesnt work when it gets observable.  Example: Reading a file - dont needa do work until someone wants to read a file
Observable.create<Int> { subscriber -> }
Observable.just( item1, item2, item3 )
Observable.interval( 2, TimeUnit.SECODNS )
@Test fun testCreate_withNoSubscriber() {
        val observable = Observable.create<Int> { subscriber -> 
               Logger.log(”create”)                  subscriber.onNext(4)               subscriber.onNext(5)               subscriber.onNext(6)
              Logger.log(”complete”)
       }
       Logger.log(”done”) }
================= main: done  ================= it only prints “done”
@Test fun testCreate_withSubscriber() {
       val observable = Observable.create<Int> { subscriber ->
             Logger.log(”create”)               subscriber.onNext(4)             subscriber.onNext(5)             subscriber.onNext(6)
            Logger.log(”complete”)
      }       observable.subscribe {  Logger.log( “next: $it” )  } 
      Logger.log(”done”) }
================= main: create main: next: 4 main: next: 5 main: next: 6 main: complete main: done ================= it only prints “done”
Observer
Observer is the abstraction that Rx java uses for listening to or observing the various items or events that the observable is producing. 
interface Observer <T> {
   fun onError( e: Throwable )
   fun Complete()
   fun onNext( t: T )
   fun onSubscribe( d: Disposable ) 
}
Tumblr media
Sometimes observer dont rly care bout other things.
interface Consumer <T> {        fun accept( t: T ) }
accept method is like the onNext method
Observers: have a lifecycle. Subscribe, Next, Error, Complete
Operator
Operators are what help you to transform and combine / create observable
map()
Tumblr media Tumblr media
Observable.just( 5, 6, 7)                    .map { “ ;-)   ”.repeat( it ) }                   .subscribe {  println( it )  }
function map expanded: 
Tumblr media
flatmap () 
flatmap transform an item into an Observable of different item for long running async task
e.g.  
Tumblr media
Flowable, Singles, Maybe, BackPressure, Completable, Disposable???
Should you use Rx?
do you like Function programming?
Process items asynchronously? 
Compose data?
Handle errors gracefully? 
If yes to most of this qns > it depends Rx java can be too complex to handle things u need.
src: https://www.youtube.com/watch?v=YPf6AYDaYf8 useful links: www.adavis.info
0 notes
ios-goodies · 8 years ago
Text
Week 188
A lot of ARKit demos are poping up, and some people started to open source some code. ARTetris is an open source ARKit project that uses SceneKit and ARKit for (you guess it) Tetris.
Articles
An aside about flatMap and monads, by @cocoawithlove
What’s New in Swift 4 by Example, by @KaramazovShogun
Modelling state in Swift, by @johnsundell
Reducers, by @chriseidhof
Errors On The Server, by @khanlou
Tools/Controls
PMSuperButton, by @pmusolino
bluejay, by apike
Business
Want your Product Team to get better? Start doing Retrospectives, by @Jicecream
The Only Time You Are Actually Growing is When You’re Uncomfortable, by @Alltopstartups
Enough, by @dhh
But can you sell water?, by @jasonfried
UI/UX
6 Animation Guidelines for UX Design, by @zecarlostorre
Gamification in 2017: Top 5 Key Principles, by @peteknudson
Predictive User Experience, by Alipta Ballav
Dropdown alternatives for better (mobile) forms, by @kollinz
From Zero to VR Design Hero, by @K_V_113
Videos
Bringing Machine Learning to your iOS Apps, by @meghafon
Credits
rbarbosa, LisaDziuba, KaramazovShogun, Codeido
2 notes · View notes
Text
Why Choose Swift Over Objective C?
Tumblr media
Dedicating 6 years in improving & using the Objective-C, Apple finally decided to snap another challenge to developers. Again, iOS developers will have to learn this new programming language – Swift.
In this article, we are going to look at some points of Swift compared to Objective-C. If you know Objective-C (at least the basics) then this tutorial is best suited to you and want to see what the equivalents are in Swift.
So let’s get into it!
Swift Language is Easier than the Objective-C: ~ Objective-C has been created using two languages: C and Smalltalk. hence, Objective-C has such a complex, Verbus Syntax. ~ Objective-C obtains its object syntax from Smalltalk while Syntax for the non-objective operations is similarly as C. ~ While the Swift Language is an option to the Objective-C language, the Swift Language is defined as “Objective-C without the C”. ~ Swift is a comparatively a new programming language. Apple started to work on Swift in 2010 and published it to the public in 2014. In 2015, Swift graced open source. It rejects the Smalltalk and C heritage and has all the features that modern programming languages have: generics, high-ordered functions, type interfaces, Optionals.
Swift Support Modern Programming Language Features
Swift rejects the Smalltalk and C Heritages and has all the Features that Modern Programming languages have:
Generics Generics code allows you to write adaptable, reusable functions and types that can work with any type, subject to requirements that you specify.
Optionals Optionals are dominant features in Swift Language which come to resolve the intricacy of non-existing value.
Type Interface Type interface refers to the automatic detection of the data type of an expression in a Programming Languages.
High-Order Functions High Order Functions is a function that you can pass arguments of other functions.
The Following Some High-order functions is: ✓Map ✓Filter ✓Reduce ✓FlatMap ✓Chaining
Swift is Faster than the Objective-C ~ iOS development with Swift is much faster than in Objective-C. ~ The Swift usage of generics and higher_order functions results in cleaner, more reusable code. ~ Optionals and type interface resulted in the responsibility for the code safety being transferred from the programmer to the compilation. ~ Let programmers write some lines of code with the similar effect as in Objective-C. ~ This helps to make the development process faster.
Swift is Safer ~ Because of its Features – generics, optionals, and type interference – all the apps being developed in Swift are less likely to have bugs or crash than other apps developed in Objective-C. ~ To present an anticipated behaviour Swift triggers a runtime crease if a nil optional variable is used. This crash provides consistent behaviour, which eases the bug-fixing method because it limits the programmers in fixing those issue right away. ~ The Swift runtime crash will halt on the line of code where a nil optional variable is used. ~ This indicates the bug will be fixed sooner or bypassed completely in Swift code.
Apple is focused on Swift ~ Apple continually develops these languages and providing continuous support to the Community. In every WWDC there are a bunch of amazing technical talks about Swift; the time indicating that Swift should be taken seriously.
Swift is easier to read ~ Objective-C suffers all moles you expect from a language built on C. ~ But in the Swift falls the legacy conversations. Therefore, you no longer need semicolons to end lines or punctuation to encircle conditional expressions inside if/else statements. ~ The Result is Cleaner and a more expressive language with a simplified syntax and grammar.
Easy to Maintain Codes ~ Swift code almost follows natural English, in addition to other modern programming languages. ~ And then it also very easy to understand the code and then make the necessary changes simple in Swift.
Swift requires less Code ~ Swift decreases the amount of code required for repeated statements and string manipulation. In Objective-C, working with text strings is very tedious and demands many steps to combine two pieces of information. Swift embraces modern programming language features like adding two strings together with a “+” operator, that is missing in Objective-C. ~ The type system in Swift decreases the intricacy of code statements — as the compiler can understand the types. As an example, Objective-C needs programmers to remember special string tokens (%s, %d, %@) and implement a comma-separated list of variables to replace each token.
Version History of Swift ✓ Swift 1.1 ✓ Swift 1.2 ✓ Swift 2.0 ✓ Swift 3.0 ✓ Swift 4.0 ✓ Swift 4.1 ✓ Swift 4.2
~ In a short span of time, Apple has invented many versions of Swift. It has features that are an easier language and provides good features for developing an iOS app. ~ The Apple is regularly updating the Swift Language and making it more easy for us to use each day.
Third Party Library ~ In day-to-day many third-party libraries are converting in Swift rather than the Objective-C.
Your popularity will increase with your developer’s team ~ According to a 2017 Stack OverFlow Developers Survey, Swift is at the forefront of the most favoured programming language, while the Objective-C is the most dreaded one. ~ Swift syntax is easier to understand for the developer’s team, they can easily understand each other’s codes.
Swift Support Dynamic Libraries ~ Powerful libraries had never been supported on iOS until the launch of Swift and iOS 8, despite powerful libraries were supported on Mac for a long time. These dynamic libraries are external to the app are executable but have been included within the app bundle downloaded from the App Store. It decreases the original size of an app as it is loaded into memory since the external code is linked only when used. ~ As a result, the executable is smaller and, because the code is loaded only when it is needed, the startup time is usually faster.
Conclusion If you are looking for iOS development with Swift then you can get in touch with us and we will provide you with the best. You can also hire iOS developers from us for your projects. If you any queries you can also write back to us on [email protected].
Source: 9series
0 notes