#Write a c program to draw a rectangle
Explore tagged Tumblr posts
creamsicle-art · 9 months ago
Text
Game Development in Raylib - Week 1
Recently I've been getting into retro game development. I don't mean pixel art and PSX style game development, those are nice but they don't quite scratch the itch. I'm talking about developing games with retro tools. Because of this, I decided to give Raylib a try.
For those of you who don't know, Raylib is a C framework targeted at game developers. Unlike Godot, which I used for my previous project Ravager, Raylib is not a game engine, it doesn't offer physics, scene management, or any kind of graphics more complicated than drawing textures to the screen. Almost everything that makes a game a game, is something you have to do yourself. This makes it ideal to scratch that "retro" itch I've been feeling, where everything has to be made on my own, and a finalized game is a fine tuned engine entirely of my own creation. Raylib offers bindings for almost any language you can think of, but I decided to use it's native C.
Setting the Scene
Since Raylib is so barebones, there's no concept of how the game should be built, so the first thing I had to do was define my engine architecture. For this initial outing, I decided to build a simple Scene+Actor system, wherein at any given time the game has one Scene loaded, which contains multiple Actors. I settled on this mainly because it was simple, and my experience with the C language was very limited.
Since Raylib didn't have any concept of a Scene, naturally it had no way to build them. While I could just hardcode all the entities and graphics in a scene, that would be unmanageable for even a basic game. Because of this I was forced to invent my own way to load scenes from asset files. This gave me the opportunity to do one of my favorite things in programming, defining my very own binary file type. I won't get into it too much right here and right now, but in this format, I can define a scene as a collection of entities, each of which can be passed their very own long string of bytes to decode into some initial data.
The main drawback of using binary files instead of a plaintext format is that I can't write the level files by hand. This meant that I had to write my own level editor to go along with my custom engine. Funnily enough, this brought me right back to Godot. The Godot engine offers some pretty powerful tools for writing binary files, and it's editor interface automatically offers everything I need in the way of building levels. It's sort of ironic that my quest to get away from modern engines lead me to building yet another tool in Godot, but it sure as hell beats building a level editor in C, so I don't really mind all that much.
Getting Physical
After getting scene management out of the way, I moved on to the physics system. My end goal here is making a simple platforming game, so I wanted a simple yet robust system that allows me to have dynamic-static physics that allows for smooth sliding along surfaces, and dynamic-dynamic collisions for things like hitboxes. For the sake of simplicity (which seems like it's going to become my catchphrase here) I decided to limit physics to axis aligned rectangles. Ultimately I settled on a system where entities can register a collision box with the physics system and assign it to some given layers (represented by bit flags). Then entities can use their collision box to query the physics system about either a static overlap, or the result of sweeping a box through space.
Raylib offers built in methods for testing rectangle overlap, so I didn't have to worry much about overlap queries, but the rectangle sweeping method is something a little more special. The full algorithm honestly deserves it's own post, but I'll give the basics here. The core of the algorithm is a function that determines where along a movement a given rectangle touches another rectangle, and that edges of the rectangles touched. It makes use of the separating axis theorem to determine when the shapes will start and stop intersecting along each collision axis. If the last intersection happens before any have ended, then the shapes do collide, the axis they collide on is that final axis, and the time of collision is the time of the final intersection. Looking back I could easily extend this algorithm to any arbitrary shape, but that's for next time I do this.
Going Forwards
My plan for this game is to build a minimal metroidvania style game. The target playtime is probably going to only be around 30-45 minutes. In the following week I plan on building out my Godot level editor, and working out a system for scene transitions and managing sound effects. I hope to by done by the end of November.
11 notes · View notes
savagegardensprogramming · 1 month ago
Text
Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media Tumblr media
CodeBlock Maps - Introduction
Take a look at Exhibit A – Its what I call a Code Block-Map. This is my crown jewel. A graphical code construct suitable for management level programming. Sub-Level 2 of SavageGardens.
Exhibit B is the sketch programming language. Its what the bright minds at MIT are working on. Its a toy. Its impractical for professional use. I am well aware as to why. I conceived something similar almost 30 years ago. I bet I wasn’t the only one.
Exhibit C is the book I was first taught programming. This book takes the flow chart approach. It does not want you take write a single line of code until you’ve drawn a full flowchart of your program. Its a painstaking approach because it takes a long time to draw a flowchart compared to the functionality you get from it. Very good for learning flow of logic but impractical for professional uses. This is the reason why the sketch programming language is what it is. It sits on the same situation. It takes too long to draw. It also takes too long to drag and drop. Mind you in the future we will have eye tracking and dragging & dropping will be done at a fraction of a second. Still, this kind of language will remain impractical.
I been sitting on this situation for literally decades. My break thru was to break out of the box. Stop using graphics to represent details. Graphical code constructs are not suitable for representing details. Lets look at sketch again Exhibit B. You see how they mapped a graphical representation to individual code constructs. One graphical representation for the if statement. Another one for a repeat loop. Another one for an individual function call such as play, stop, set volume, etc. Those are details.
Stepping out of the box for me was when I realized that graphical code constructs are good for representing big pictures. Managing the big pictures. Metaphorically speaking. Step away from the forest and look at the landscape. At a higher level you can move a whole mountain from the right to the left, Put the lake right next to it. Have the river move down from the lake and curb to the left. Put a small town situated at the curb of river. And finally mark an X on the mountain where Smaug the dragon hangs out. The point is managing the big picture items as opposed little details.
If mind-maps and flowcharts got together. CodeBlock Maps would be their child. CodeBlock maps is basically a map of blocks of code. What it maps out is flow of logic. Let rectangles represent a block of code. The code can be it as simple as adding two numbers together. Or as complex an AI algorithm with millions of lines of code. Then interlink these rectangles indicating flow of logic. That is it. LISP is just commas and parenthesis. CodeBlock maps is just rectangles and lines.
Exhibit D CodeBlock Maps are made up of individual CodeBlock Cells. A rectangle is referred to as a cell. Anyways here are the individual parts of a code block cell. Most of it is verbiage. I would say the only thing that translates into code is the fact that its a cell, the interlinks and the type descriptor.
Exhibit E. There are different verbiage requirements depending on the situation. Here I have enumerated them all. But at the core they are all the same fundamental construct. A rectangle interlinked with lines.
Exhibit F is syntax diagrams represented as a code block map. Good for representing recursive descent graphically. Note that CodeBlock Maps are about making code look pretty. It turns out that beauty has a practical use in code comprehension. I suspect women will enjoy programming in SavageGardens.
In SavageGardens I have designated code block maps as a sub-language for code management but mind you its quite capable on its own. It is touring complete. As simple and powerful as LISP. Its good for encapsulation. Good for divide-n-conquer. Good for abstraction. It fullfills the goals I have set out for SavageGardens. It exploits the brain functions of memory recall. It is 2 dimensional. It is graphical in nature. Good for code comprehension. Good for code navigation. Does not hinder code efficiency. Not so good for code articulation but three out of four is not bad. It does work well with other languages. Hence good for management.
0 notes
edmtechproseo · 9 months ago
Text
AutoCAD Training - Edm Tech Pro
AutoCAD for Civil Architects Training & Certification Course
EDM's Autocad Civil Training Course in Jaipur is the first step towards a transforming civil engineering experience. Discover the world of AutoCAD with our extensive course, which is intended to provide you the tools you need to run an effective AutoCAD Civil program. This AutoCAD course provides a comprehensive overview of the program, covering everything from fundamental basics to sophisticated functionalities. The most widely used software for turning architectural and civil engineering concepts and specifications into blueprints, drawings, and models is AutoCAD-Civil/Architects.
Tumblr media
What is Autodesk & auto CAD ?
Utilize AutoCAD® software's automation, collaboration, and machine learning technologies to enhance your teams' creativity. AutoCAD is used by engineers, architects, and construction specialists to Create and annotate 3D models with mesh objects, solids, and surfaces as well as 2D geometry. Automate processes like scheduling, counting objects, swapping out blocks, comparing drawings, and more. Use add-on applications and APIs to customize your workspace and increase productivity.
Tumblr media
AutoCAD- Civil Course Syllabus
Note: More than five absent will not be allowed on the same batch due to better quality of Education.
Session 1 -   Introduction to AutoCAD, History, Exploring GUI & Workspaces
                    File Management - New, Display Control - Zoom In, Zoom out.
                    Line command-Draw simple letters from line command, In the class in front of student
Session 2 -   Draw commands- Circle(Radius /Diameter), File Management-Open, Save, Save as, Close
                    Editing commands – Trim, Extend
Session 3 -   Draw Command- Rectangle(Area/ Dimension/ Rotation) Object Selection Methods and                         Dynamic Input
Session 4 -    Editing commands – Move, Copy, Rotate,Offset ,Mirror.Difference CADD & CAD
                      Writing manner autoCAD
Session 5 -    Draw commands- Polygon ,Ellipse
Session 6 -    Draw Command- Arc, Editing commands –Erase, Undo, Redo.
Session 7 -    Editing commands – Circle(2point/3 Point/TTR/TTT),Rectangle(Chamfer,Fillet Width,                          Thickness, Elevation Creating Detail Drawing –Revcloud.
Session 8 -    Editing Command-Introduction of Array
                      1.Rectangular
                      2. Polar
                      3. Path
Session 9 -    Join, Solid, Donut, Fill, Explode, MOCORO(Move/Copy/Rotate/Scale/Base), Break.
Session 10 -  Isomectric ---i. Isometric views
                                            ii. Isoplane
Session 11-   Drafting Settings, Drawing settings – Units, Limits,Construction Line(X-Line), Ray,                              Polyline,Polyline Edit, Spline, Spline Edit Multiline, Multiline Style
Session 12-   Dimensions- Dimension - Linear, Aligned, Radius, Diameter, Angle, Arc length,                                      Continuous, Baseline,Dimension Break, ,Dimedit, Dimension Style Manage
Session 13-    Annotations -Text,TextEdit ,Mtext, Spell, Table, Tabledit.
Session 14-   "Types of lines & their uses Object Properties - Color, Linetype, Ltscale, Lineweight,                                Properties, Quick Properties, Matchprop."
Session 15-   Layer Management-Adding / Removing Layers, How to work with layers
Session 16-   Hatching utilities - Hatch, hatchedit, Superhatch
Session 17-   Tracing the Product/drawing:- Importing the photo/drawing (C) , trace the image with                              spline or other required draw tools
Session 18-   Mleader, Multileader style,region,boundary, Divide, Measure, Group, Group Edit,                                 Block, Wblock, Insert Block, Lengthen, AutoCAD Design Centre (DC),point style
Session 19-  StandardsParameters :- (standard properties of layers as per various use ie;- line                                     type,color, linetype scale etc),(Text style, size, color, font) & (Dimension style),                                       (Minimum room,kitechen, balcony & bathroom sizes) ,(dimension of doors, windows                            ,ventilators, beds,chair,sofa, tv stand etc) used by industrial experts
Session 20-  Creation of Elevation, Section with the help of given plan staircase concepts. Standard                             sizes of stairs.
Session 21-  Parametric Drawings-Workspace, Projections (First & Third angle)
Session 22-  Workspace Switching & Setting Primitives-Cylinder, box, torus, wedge, cone, frustum                            of cone,sphere,pyramid,helix.
Session 23-  Final Printing/Plotting:-Sheet sizes A0, A1, and A2…..,
                     Arranging/scaling the plan into Sheet Layout
                     Introduction to plotting, Page setup, Plot Styles
                      what to print, plotting scale, preview creating the pdf of final view.
Tumblr media
Layer Management In Auto CAD Civil
Tumblr media
Tumblr media
0 notes
w3codeworld · 5 years ago
Link
Codeblocks is an open-source integrated development environment for coding that can be used for various purposes like finding the third variable in c++ as well as programs like C program to print diamond pattern. The solution is entirely cost-free and is the design and developed around a plugged in architecture. The software is entirely expandable as well as modifiable with the look, feel, and operation across various platforms.
 The extensive software reinforces some exciting compilers like GCC, Clang, and C++. It helps to write a C++ program to convert binary numbers to their decimal form. It allows the users to expand any kind of functionality, such as compiling and debugging by installing any plugin or coding.
 Main features of code blocks
 There are several features of code blocks.
 l  It helps in debugging.
l  Allows the users to write a c++ program to check whether a character is in the the upper case or not.
l  Generation of inter-project dependencies.
l  Class browser as well as smart indent.
l  Multiple compilers and projects.
l  Build queues to find the third variable in c++ program.
l  Code folding and code completion.
l  Entire breakpoint support.
 Benefits of the software
 The software's main benefit is that it provides a user-friendly interface for the users to code easily. It provides the necessary tools to the software designers as well as the engineers to write a C program to print the diamond pattern. The software is an entirely open-source platform, shows that a large part of the functionalities can be done through plugins.
 The interface allows a switch for easy conversion to various coding platforms that is useful to write a c++ program. The code blocks offer an incredible framework for debugging like custom memory dumps, user-defined watches, and many more functions. It is an extensive platform for coding for professionals as well as beginners.
0 notes
scarletwillowtree · 6 years ago
Text
Game Night
Pairing: Bruce Banner x Reader
Warning: fluff, Nat being Nat
Word Count: 1,825
Summary: Working at Stark Industries had always been a dream of yours. But once you’re there, will you end up with a new addition to your dream?
A/N: The first of my requests is done! I recently moved and only just unpacked my laptop, so they should be uploaded periodically over the next two weeks. I really loved writing this piece for @pretendingandpreposterous, and it’s my first Bruce fic so I hope I did him justice!
Tumblr media
43. “I haven’t seen him this happy in a long time.”
55.“Sorry… your hair was in your face… thought I should move it so I could see you better.” 
Carpe diem had always been your personal motto. You knew that the only way to get what you wanted from life, you had to take that figurative, and sometimes literal, leap of faith. When you had just graduated from MIT with a degree in biomechanical engineering, you applied to Stark Industries as mostly a joke, but there was still that little voice in the back of your mind saying “what if?” 
So naturally, when you received an e-mail response from Pepper Potts herself stating you had the job, it took a few moments to get over the shock before spending the rest of the week feeling like you were in some kind of dream. You packed your most essential items, made plans to have the rest of your stuff shipped to New York once you’d found an apartment, and by the end of the month you were starting the next chapter of your life somewhere you never imagined you’d actually be. 
When filling out your application, you hadn’t paid much attention to the actual position, you just knew its requirements revolved around your new degree, so another shock came when on your first day Pepper’s assistant was showing you to your work station and she showed you into a massive lab lined with various Iron Man suits. 
“Mr. Stark usually spends the majority of his time here in this lab, along with his colleague Dr. Banner. They should be on their way back from lunch now, just wait here for them. Good luck!” 
The overly chipper woman left you alone in the quiet lab where you had to fight your instincts to start looking closely at everything like a child in a candy store. Eventually, your curiosity won and you began wandering around the wide-open room, taking in the various gadgets laying on the tables. At one certain item, you stopped and picked it up, the smooth metal feeling much heavier in your hand than it looked. Looking closely, you were guessing that it was one of the older models of Stark’s arc reactor, though the power had been depleted from the small device. 
Looking closely and after opening up the center compartment, you found a blackened rectangle inside, which looked strangely like half-melted palladium. It resembled the block you had used for a project involving lasers during your undergrad years. 
“This would’ve caused some serious blood poisoning, what the hell were you thinking Stark?” 
You had been so focused on the small device, you hadn’t heard the doors to the lab open nor had you noticed the two men who now stood behind you. 
“Well, at the time palladium was the only viable power source. I had to go and create my own element to bypass those nasty side effects, no big deal. You must be (Y/N), right?” 
You felt your spine straighten and your muscles tense before slowly turning to the two men, where one was smiling like a bird who just caught a bird while the other just looked exasperated by the antics of his friend. The one with a smirk on his face stepped forward, hand extended and introduced himself as Tony Stark, and introduced you to his friend Dr. Bruce Banner as well. While shaking Bruce’s hand, you found yourself wanting to linger, his dark eyes drawing you in. 
What a great way to start this new part of life. 
=============
Over the first few months working at Stark Industries, you had grown closer to both Tony and Bruce. At first, you were working closely with Tony on the programming and construction of his newest nanotechnology suit. You had been recruited to work out the kinks in the system that connected the suit to Tony’s nerves so that the fighting and mobility of the suit were seamless with what he intended. Originally that was all you’d been hired to do, but after seeing you in action you were hired permanently. Tony cited that he only did this because now that Bucky was in the tower they’d need you for maintenance and repairs to his arm, but you two had become friends over the weeks being cooped up in the lab together. 
You and Bruce, however, you had become extremely close, even through his fear of possibly hurting you by Hulking out. Your feelings for him were definitely no longer safely situated in the friend zone, but you kept that to yourself since you didn’t want to risk either your job or the friendship you had built with the quiet doctor. The two of you regularly worked together in silence while Tony was blasting his music, but when the music wasn’t drowning out the conversation you and Bruce talked nearly nonstop to each other about anything and everything. Soon enough you began eating lunch together, and while most days Tony dominated the conversation, other days you and Bruce would talk about everything outside of the world of science while Tony seemed to watch the two of you like a hawk. 
Today had been a quiet day in the lab, you and Bruce exchanging some groan-worthy science puns that had even Tony ready to leave the spacious area. About an hour before your usual quitting time, Tony finally acknowledged the two of you with an emotion other than annoyance. 
“Alright, not to end this horrifying joke session I’ve been subjected to, but I vote we head up to game night a little early tonight Banner. You coming this week (Y/N)?” 
You had refused going up to this point, nervous about meeting ‘Earth’s Mightiest Heroes’, but the look Bruce was giving you was the final tipping point. Letting out an over-exaggerated sigh, you pushed yourself off the stool and strolled over to men in the doorway. 
“Lead the way, gents.” 
=============
Loud laughter filled the air as Bucky pouted, heavily glaring at Steve as he drew four more of the brightly colored cards. The group had decided on Uno for the time being, and Steve had been pushing Bucky further and further from a possible victory. 
The team members had quickly warmed up to you after seeing you walk in with the resident super-geniuses, in fact, they barely batted an eye at your arrival in their private game night. 
You were standing by the bar area of the common area, having chosen to sit this round out and have a cocktail yourself like many of the people around the room. Turning back from watching the group with full intentions of grabbing your drink, the smile from your face fell quickly as an undignified squeak forced its way through your mouth. 
Right on the other side of the bar was Nat, who had been observing you rather closely all night. You had brushed it off as her being wary of new people, but at the look in her eyes, you knew it was more than that. 
“I haven’t seen him this happy in a long time.” 
“Who?” 
You looked at her with wide eyes, confused about what she was implying. Her smirk stretched wider as she gave a small shake of her head. 
“Banner. Are you trying to tell me you haven’t noticed?” 
My body felt like I had just slipped into a slightly too warm bath as my face bloomed with red.  
“It isn’t like that. We just work together, nothing more.” 
“Sweetheart, I read people’s body language for a living. He doesn’t see you as just a coworker.” 
With that last jibe, Nat sauntered off, back into the fray that had started as an innocent card game. You swept your eyes across the group and locked gazes with the one person you were looking for. He gave a soft smile before turning back to the conversation around the table. 
Turning back to the bar, you grabbed your drink and quickly downed it before gently setting your glass back. Pushing away from the bar, you started making your way to the balcony doors just off to the side, suddenly having a desperate need to feel the cool air of the fall evening against your burning skin. 
The lights of the city twinkled like stars, the air stinging against your rosy cheeks. Letting out a heavy sigh, you leaned against the railing, a soft breeze ruffling your hair as you closed your eyes. 
“(Y/N)?” 
Your eyes flew back open as you spun towards the soft voice coming from the doorway. Bruce looked hesitant as he stepped towards you, concern shining in his eyes in the low light. 
“Are you feeling okay? You ran out of there kinda fast.” 
“Oh, I just needed some fresh air, I was feeling a little warm.” 
Bruce walked over to you as another breeze passed over the balcony, some of your hair landing in your eyes this time around. Before you could move the (H/C) strands, his hand shot out and tucked the wandering pieces behind your ear. Your blush returned full force as your eyes met his again, this time an unreadable emotion behind his eyes. 
“Sorry… your hair was in your face… thought I should move it so I could see you better.” You felt your lips pull up into a soft smile as you continued to stare into Bruce’s eyes. After a moment of silence, he started leaning towards you slowly, giving you more than enough time to pull away if you wanted. But did you want to? Over your time here, Bruce had slowly become more than just your coworker, he had become your friend, your confidant, you knew he would be there whenever you needed him to be. 
Leaning in the last few centimeters, you felt your lips brush across his, barely a whisper of a touch. Then, Bruce was kissing you fiercely, a barely contained passion pouring through the kiss from him to you. 
You matched his passion, yet the kiss was still loving, full of all the unspoken feelings between the two of you. Finally, once your lungs began to scream for air, you parted. You both were breathing heavy as you looked back at each other. A large smile broke out across your face and a breathy giggle passed your lips as your joy bubbled over. 
“So, does this mean you’ll finally try that new Italian place with me?” 
He barked out a loud laugh before nodding his head, then leaning down to capture your lips in the next of many, many kisses the two of you would share.
58 notes · View notes
sprinkleshot · 3 years ago
Text
study journal~
Tumblr media
So, I’m gonna start making this a thing. I feel like writing out what I did each time kinda helps reinforce the concepts, annnnnd I need typing practice lol. 
So today I did a little review, and it made me want to die, so I moved on anyway! Woooo! Honestly the small amount of review I did actually did help. I was able to animate the drawings from the functions project which was super satisfying! I still wasn’t able to make them click into existence or be the cursor, but we’ll get there. 
So, yeah. I moved onto If statements. I animated a ball bouncing on the Y axis of the canvas, and wrote the if statement so that if the ball crossed 325 or 25 on the Y axis it would bounce back the other direction at the same speed. Yay! I’m struggling a bit with the coordinates on the canvas, and this was suuuper evident in one of the next project: buttons. 
Before buttons, though, was more mouse interaction! Definitely gonna go back to my fish tomorrow after reviewing this part. Basically I programmed the cursor to act as a brush as long as the mouse was clicking (more if statements!). It looks like this: 
draw = function() {    if(mouseIsPressed) {    noStroke();    fill(237, 164, 164);    ellipse(mouseX, mouseY, 20, 20);    } };
And THEN, Booleans. I.... Do not feel immensely confident with this concept lol. I THINK a Boolean expression evaluates if a thing stated in code is true or false. So like 
if(mouseIsPressed && mouseX < 325 && mouseX > 75 && mouseY < 250 && mouseY > 150){        fill(18, 119, 130);
is a boolean expression, saying that if the mouse is clicked, AND the mouse is over the given coordinates on the X and Y axes, the fill (color) of the object this code is about will change. This is the aforementioned button lmfaoooo
So, that’s confusing as fuck. Mostly because HOW? Like it just KNOWS. The AI are HERE and the future is nigh. 
Anyway so the project associated with Booleans was SUPER fun, mostly because it WORKS AHHHHH Like it WORKS its a functional THING and its so fucking cool. Basically it’s a text thing with a spot for a number and three options for what kind of number it is (positive, negative, or zero)  and then a box appears over one of the options depending on the number input. To be specific, the number has to be entered through the code and not the canvas, but one day. 
BUTTON TIIIIIIME So, the first button was just the whole upper half of the canvas cut off by a different color and black line, and I had to program it so that the button would only change color when clicked in the correct area. Since it was just the upper half of the screen it wasn’t so difficult. 
The second button had me pulling out my hair lmfaoooo. I had to ADD. MATH? IN *MY* CODE? I would literally never it’s not like this is a stem field lmfao
So, I did the first button and then I made myself a second button from scratch, and it worked. Here it is. 
draw = function() {
   fill(150, 150, 150);//start color        if(mouseIsPressed && mouseX < 325 && mouseX > 75 && mouseY < 250 && mouseY > 150){        fill(18, 119, 130); } rect(75, 150, 250, 100);
fill(227, 0, 0); textSize(22); text("PRESS ME!", 131, 179, 130, 155);//start text
};
The first coordinate for mouseX is the x position of the rectangle added to the width. The second mouseX coordinate is the same as the x position. The first mouseY is y position plus the width. The second mouseY position is, you guessed it, the y position. 
Could I tell you why this is? Nope. But, like a boolean expression, I can tell you that it IS. That’s it. That’s the code lmfao. I’m so good programming wow. 
But the important thing is that the button only changes color when it is clicked in the actual area of the button. I wanted to do changing text, but I couldn’t get the original text to disappear when the new text appeared. 
AND THATS WHAT I LEARNED AT SCHOOL TODAY YAAAAAAY Next lesson (probably tomorrow) is If/else statements! I’m excited. I’mm also feeling way less sick after just a day of antibiotics and I managed to actually sleep in a meaningful capacity last night. I get paid probably tomorrow and am buying Piofiore posthaste. 
0 notes
myprogrammingsolver · 3 years ago
Text
Assignment 1 Solution
In this assignment you will be writing a C++/SFML program which will read descriptions of shapes from a configuration file, and then drawing those shapes to the screen. Each shape will have a name, position, speed, color, as well as properties unique to each shape type. For example, a Rectangle will have width and height, and a circle will have a Radius. For this assignment, the position of a…
Tumblr media
View On WordPress
0 notes
the-firebird69 · 4 years ago
Text
There are several sheriffs who have been harassing me steadily they need to be arrested I'm calling on my people to do so I'm sick of hearing them all day and night I'm sick of Mac Daddy's threatening the s*** out of me he's not going to get anything and he's ruining his own plan he should be fired there's several people that need to be fired the ones that are doing the stupid project and owns the house you people are not going to have a program at all you think I'm just spewing you can't even read English properly and understand what it means you're going to have a huge problem everybody's going after you now do you understand that probably not huh. You've exposed yourselves into your threatening the thorium balls and people are just murdering you and shooting you and you're also dying for treason because you did so and you told me you sat here for years exposing it to me because you think it's going to help you when it's not and you want to make a big deal about my e-bike it was sold under false pretenses it's false advertising and the Chinese are killing you to keep the secret as well as Brian Girard and his and other people that have invested interest in selling the bicycle and all their motors are not 750 by the way it's just like their CC's they're all under they all under 50 they're 49. The output is what you measured by the actual wattage the output of mine is 80% of 750 which is less than 750 actually mine is about 70% because it's not buffeting it's a knockoff they use materials in it not as good quality so it cost less money to buy. So people can use this to keep me out of court and then seek you using it as a scam to kill you and take your money and stuff because you're lousy agents who should not be hired in the first place and you're not military grade people in any way you're running around me with these stupid ideas of threatening me for whatever you want nothing has come to you at all you've lost more stuff than people on earth have ever known as existed you've lost most of your businesses no probably about half to 5/8 or so if you can fathom for a moment what 5/8 means say all of your stuff is 1 in and you lost 5/8 out of that inch of all your stuff so you draw like this red line in like an empty rectangle all the way up to five Ace and then you have a bar graph or bar chart that shows you how much s*** you lost by being a f****** a****** to me and the people around me are the ones doing it too because you're all pushing each other to do it to be beautiful roses on your own grave it's too complicated for you to understand simple metaphors isn't it.
So when you have the grip in your hand it doesn't go more than 20 unless I'm going downhill with my face down on the steering wheel so there you got me right I should be able to go 50 and not be bothered because you're not supposed to be huge huge huge losers there's no such thing as this plan that George Herbert Walker Bush fed you so he's my protector and I'm supposed to do everything I can to get him back in service and I can't cuz you're all see c u n t s c**** your massive massive bleeding c****. For like 20 years you've been this huge ugly red-faced b**** in my face just complete a****** men all day and all night the women cannot do a damn thing about it and you're bitching and bitching and bitching and everyone f****** hates you and the stupid program shouldn't correct it God damn squares what a piece of s*** you people are you can't figure out what you're doing wrong and why you never get any thorium why don't we get any thorium because you sit there threatening it no one wants to trust you with you you f****** c***
Zues Hera
You're sitting here grilling and making him angry over the e-bike he had a good time on and you plan to do it because you're huge huge stinking assholes now you heard that China doesn't want you announcing it's not really a 750 watt motor it's like 5:50 and will and Bill can read it and so can the people in court it says 80% efficiency on a buffang which is like a really good one. So they're overstated the wattage in order to sell it can you dig it no so we're going to arrest you because it's set up to only go 20 miles an hour and you sat there all day long time to go faster all day and he did did he get killed your people died their bloods all over the brains are all over the cars everybody's laughing at you they're going to just keep taking your money higher up Scott killed too several lieutenants a couple kernels one general where wandering around behind him sniffing his ass trying to give him to go 21 mph cuz he'll get things
Thor Freya
This is where it's at this is what these people are like nitpicking finicky perfection is about things that they try and mess up and mess up on purpose and try and catch you in to do things that don't really work for them or you no we want them all dead because they're stupid as hell and we need them dead and we need them dead right now they're all writing these warrants for what he's saying and it's not illegal what you're saying in any way right now your fools we're ready warrants because you're writing warrants that are fake unjustified unwarranted and they're not written by people who are actual law enforcement agents we're going after you now and you know what who gives a s*** if you're a sheriff or Governor or whatever this is about money big money and Mac is pissed off as hell and so the max we were doing it and you're a bunch of lazy pieces of s*** trying to move off him and he's going to go around killing you dumb f****** assholes who want a penny for something and other people too the Emperor of China emperor of Japan they want weapons and stuff they don't want you whining kites and a lot of you Max are whining kites it's where so much money that the law shouldn't matter and you're going are you going 21 miles per hour and I can understand Dan you're frustrated but you do not understand your situation you don't you really have no clue cuz you're expressing it now you have stepped into a furnace and people go up like that without even trying it is worth so much money and nobody paid me at all so it looks stupid like you're trying to get slave labor for intellectual property it just won't happen at this level and that's what I'm saying for my husband because you people are dumb I'm going to drop napalm on you you pieces of s*** and use the condenser excuse you pieces of s*** tonight because it's worth it to us we don't care we're going to murder you
Hera
0 notes
faradayb-fmp-y1 · 4 years ago
Text
On Monday we we are instructed to complete any of our own independent work as the teachers completed our assessments for that half of the process. I spent my time going through my blog and writing about a few artists as well as completing some end of week reflections.
Tumblr media
Tuesday was more eventful as it was a digital workshop day, the teacher was absent for the first part of the lesson so we had to get started using our own initiative and the power points as well as video she’d left for us as guidance.
The task was to create multiple typography pieces on Adobe illustrator, First I signed in with my college account and then I created a ‘new document’ within the programme, size A4 with at least five art boards lined up together using ‘more settings’.
So that I had all of the tools specified in videos we were given I changed the layout of the program to essentials classic – the option to change this is next to the search bar.
I learned that when using the text tool ‘T’ to not draw a box with my mouse as it will be filled with preset words. Simply click and type, hold shift to upscale and down scale – this stops the sentence and or word from distorting.
Next I use the search bar ‘myriad pro’ to select a bold font– Preferably a bold/easily readable font as it will be altered later. I also used Dafont.com to find other more interesting options for my type.
To change the premade fonts from both the program and from the website are used the warp options changing the angles and the values of the type as well as the sizing to fit my preferences. An example of this being the ‘Arc’ option that curved the words in any direction I wanted.
Tumblr media Tumblr media
I was certain things about Adobe illustrator that I found to be easier than photoshop whilst certain things also more difficult than photo shop, such as the absence of certain features or the difference in those features.
Surprisingly there was no bucket to like there is in photo shop, so to find the option I needed to colour in my background so I selected the ‘rectangle tool’ creating a box over my canvas to achieve that result-Going to ‘re-colour’ for more colour options and a larger colour wheel, then using ‘arrange’, ‘send to back’, bringing my type to the forefront.
Tumblr media
I learnt to use ‘command C’ and ‘command V’ to copy and paste words multiple times, as well as using the ‘switch fill to stroke’ tool- And adjustable setting that could turn solid words into outlined words. These were both options that I ended up using in my work, I found them to be useful when creating my typography pieces.
I found this lesson to be a productive one and a very enjoyable one as I learnt to use a new program relatively quickly as well as completing all of the work in one session, which I find difficult to do usually in computer bass lessons. Overall I’m happy with my final five designs and I feel that they represent my topic as well as my ideas for their outcomes properly.
For the words used for the type I decided on singular words relating to both sides of my topic as well as the title of said topic for one of them.
1.) Artificial/Natural
Tumblr media
2.) Humanity
Tumblr media
3.) Glitch
Tumblr media
4.) Organic
Tumblr media
5.) Robot
Tumblr media
6.) The completed lineup
Tumblr media
0 notes
softsguideweb · 4 years ago
Text
Adobe Illustrator
In the event that you have chosen to learn Illustrator, you need to begin with the nuts and bolts. It's a truly incredible program, yet in addition a perplexing one. When you get comfortable with the interface, essential instruments, ranges and workspace, you will save a ton of time and nerves and your work process will appear to be smooth and lovely.
Types of Software Reviews Adobe Illustrator is a vector drawing program. It is frequently used to make logos, symbols, delineations, graphs, infographics, shirts, business cards, writing supplies, envelopes, bundling plan – and so on. All things considered, it is for the most part used to make high goal illustrations, which can later be printed too. In contrast to Photoshop, which stores picture data in spots, Illustrator utilizes numerical conditions when you draw shapes. What's that about?
Difference between System Software and Application Software
It implies that vector designs (like an Illustrator drawing) can be scaled or zoomed to any measure without losing quality, while raster pictures (like a picture altered in Photoshop) will pixelate as you scale: Alright, so you are as yet perusing this guide. That discloses to me that you truly need to draw nearer with Illustrator, so I am here to impart my insight to you. In this guide, I will acquaint you with the workspace, fundamental devices, shapes and we'll make our first logo utilizing this magnificent programming. If it's not too much trouble, note that I am utilizing Illustrator CS5 on Windows, so Mac clients should utilize somewhat unique key blends: Command key rather than Ctrl and Option rather than Alt. 2. The Illustrator Workspace Assuming you know about Photoshop, the Adobe Illustrator workspace will not shock you much, since the principle parts of it are essentially something very similar: You will fundamentally utilize the Tools board, since the entirety of the apparatuses that you need are there. To arrange a functioning device, you will utilize the Control board, where all alternatives for the current device are kept. Furthermore, obviously, the board docking zone – it keeps such significant ranges as Color Swatches, Layers, Stroke choices, Appearance, Gradient settings, and so on (everything ranges can be turned on or off in Windows menu). How about we look at the Tools board first. 2.1 Tools Panel There are numerous instruments accessible in the tool compartment, yet you don't need to remember everything. Only a couple of them will do the work. Here's a reference table (a few devices, similar to Rectangle, contain more instruments inside, which can be chosen by holding the apparatus symbol): I generally say that the most ideal method of learning is rehearsing. Along these lines, how about we gain proficiency with the essential instruments by really utilizing them. 3. Making a Logo in Illustrator I generally use Adobe Illustrator to make logos for my customers. For what reason don't we attempt one? How about we call our magnificent organization LimeWorks. We'll have to make a lime and put the name under it. Like this: Remember however, that we will make a straightforward logo, to make sure you get comfortable for certain instruments and strategies. How about we start with drawing lime sections. 3.1 Using Pen Tool We'll utilize the Pen apparatus, which is quite possibly the most utilized devices in Illustrator. It is utilized to make a wide range of shapes and articles. Select it by tapping on its symbol from the tool stash or utilize the P key. Utilizing the Pen apparatus, make your first triangle by clicking multiple times where you need the edges to be: Note: as you see, I use Grid (Ctrl+) to be more exact. To close the way, click on the main point: Presently it is fit to be loaded up with a tone. Ensure the triangle is chosen (click on it with Selection instrument, V) and pick a yellow tone: 3.2 Making Round Corners We need round corners to make our lime section (triangle) look smoother. We'll utilize the Round Corners impact: In the Round Corners discourse box, put something like 4 mm (I use millimeters as units) and snap OK to apply changes: Looks great. Presently we should add some surface, so it looks more sensible. 3.3 Adding Photoshop Effects In Adobe Illustrator, when you go to the Effects menu, you will see that there are Illustrator Effects and Photoshop Effects: We will utilize Stained Glass (Effects->Texture->Stained Glass). Yet, before that, we need a duplicate of our triangle over the first layer. 3.4 Copying Objects I'll show you some brisk tips on the most proficient method to effortlessly reorder objects over the current layer and beneath, while keeping the specific position. To glue a duplicate of a chose object over the first one in the specific position, first duplicate it (Ctrl+C) and afterward glue it utilizing Ctrl+F (in the event that you use Ctrl+V it will glue it in the screen). To glue it underneath the first item use Ctrl+B: Alright, so now you know the duplicate/glue stunts. Reorder our triangle directly before itself (Ctrl+F), and fill the stuck article with white tone: Open the Stained Glass discourse box and set as mine (Cell size=17; Border thickness=2; Light intensity=0): 3.5 Expand Appearance Extend Appearance is situated in the Object menu and is perhaps the main apparatuses in Illustrator. It might require a different manual for depict in detail, yet today we are just learning the essentials.
0 notes
siva3155 · 6 years ago
Text
300+ TOP iOS Interview Questions and Answers
iOS Interview Questions for freshers experienced :-
1.What is latest iOS version? The latest version of iOS is 13. 2. What is the output of the following Program? let numbers = let numberSum = numbers.reduce(0, { $0 + $1}) 10 3. Conversion of Error to optional Value is used as a method to handle Errors in Swift (True/False) True 4. Structures can be inherited(True/False) Flase 5. What is the Output of Following Program var randomly Array: = print (randomArray) Compilation Error (1 is an Int not object) 6. What is the Output Of Following Program class FirstClass { func doFunction() { print(“I am superclass”) }} class SecondClass: Firstclass { override func doFunction() { print(“I am subclass”) }} let object = SecondClass() object.doFunction() I am subclass 7. What is ARC? Automatic Reference Counting 8. What is ARWorld Map? An ARWorldMap object contains a snapshot of all the spatial mapping information that ARKit uses to locate the user’s device in real-world space. 9. How shared AR Experience is Created? Once the AR world map created from once device is transferred to the other device using P2P connectivity or some other reliable source, the other devices can also have the same AR experience similar to the first device. To create an ongoing shared AR experience, like placing an AR object, When one user taps in the scene, the app creates an anchor and adds it to the local ARSession, instead of sending the whole map we can serializes that ARAnchor using Data and sends it to other devices in the multipeer session. 10. What are the main UITableViewDataSource methods that are needed to display data in table view? numberOfSection, numberOfRowsInSection, cellForRowAtIndexPath
Tumblr media
iOS Interview Questions 11. What are the two basic things that are needed to create an NSFetchRequest in CoreData? EntityName, SortDescriptor/NSPredicate 12. What are Tuples in Swift? Tuples are Temporary container for Multiple Values. It is a comma-separated list of types, enclosed in parentheses. In other words, a tuple groups multiple values into a single compound value. 13. What are the Control Transfer Statements in swift? break, continue, fallthrough, return, throw 14. What are closures and write an example program for closure? Closures are self-contained blocks of functionality that can be passed around and used in code. var addClosure = { (a: Int, b: Int) in return a + b } let result = addClosure(1,2) print(result) 15. Briefly explain reference types and value types with examples? Classes are reference types and Structures are value types. When a class is assigned to variable and copied only the reference to the original value are passed and so any consecutive changes to the assigned values will also affect the original value. But in struct when it is assigned to another variable a copy is generated which will not have any effect on the original value when changed. 16. What are the features of Swift ? Variables are always initialized before use. Memory is managed automatically. Arrays and integers are checked for overflow. Switch function can be used instead of using “if” statement. It eliminates the classes that are in unsafe mode. 17. What is the significance of “?” in Swift? The question mark (?) is used during the declaration of a property can make a property optional. 18. What Is Initialization ? This process involves setting an initial value for each stored property on that instance and performing any other setup or it is required before the new instance is ready for use. e.g.: keyword: init() { // code initialization here. } 19. What is NSURL Session? NSURL Session is a replacement for NSURL Connection, and similarly it is both a distinct class and also a group of related APIs. 20. What are the Session Configuration? NSURL Session Configuration provides a few factory methods to create your session configuration. The methods are: Default Configuration – provides anccess to the global singleton storage and settings. Ephemeral Session Configuration – a private, in-memory only storage Background Session Configuration – out-of-process configuration that is keyed to the identifier string. 21. How to define kSomeConstant ? e.g.:let kSomeConstant: Int = 80 It is Implicitly defined as an integer. If you want to be more specific you can specify it like above e.g.. 22. Define hash value vs raw value ? HashValue:- If you had the enum as we had declared earlier without the type, there is no rawValue available but instead you get a member called hashValue. RawValue:- The rawValue on the other hand is a type value that you can assign to the enum members. 23. Define Static Binding and Dynamic Binding? Static Binding: It is resolved at “Compile time” Method overloading is an example of static binding. Dynamic Binding: It is virtual binding resolved at a “Run Time”. Method overriding is an example of Dynamic Binding. 24. What is Method Overloading? It defines a method with the same name many times with different arguments. These kind of feature is known as Method Overloading. 25. What is Method Overriding? If we define a method in a class, and we know that a subclass might need to provide a different version of the method. When a subclass provides a different implementation of the method defined in a superclass, with the same name, arguments and return type, that is called Overriding. The implementation in the subclass overwrites the code provided in the superclass. 26. What is QOS? QOS – Quality of Service QOS can applied all over iOS as well. One can Prioritize queues, thread objects, dispatch queues and POSIX threads.By assigning the correct priority for the work, iOS apps remain quick, snappy and responsive. 27. What is User Interactive? It works happened on the main thread, Immediately in order to provide a nice user experience. e.g run at while in Drawing and Ui animations. 28. What is User Initiated? It works when the user kicks off and should yield immediate results. It Performs asynchronously that are initiated from the UI This will get the mapped in to the high Priority Global Queue. This work must be complete for the user to continue. 29. What is DeadLock? A deadlock is a situation where two different programs or processed depend on one another for completion, either because both are using. It is the situation where a set of processes are blocked because each process is holding a resource and waiting for another resource acquired by some other process. 30. Define Run Loop? Run loop mode is a collection of input sources and times to be monitored and the collection of run loop observes to be notified. Become an iOS Expert with Certification in 25hours 31. What is iOS? iOS (intelligent Operating System) is a mobile operating system created and developed by Apple Inc. exclusively for its hardware with the help their own creating language called Objective C and Swift 32. What is the difference between the cocoa and cocoa Touch? Cocoa includes Foundation and AppKit frameworks for developing applications that run on Mac OS X. Cocoa Touch includes Foundation and UI framework for developing applications that run on iPhone ,iPod Touch and iPad. 33. What are the different property types? strong, weak, assign,copy,retain,atomic and non atomic. 34. Explain frame and bound of a View in ios? Bound is the rectangle that relative to its own coordinate system (0,0. Frame is the rectangle that relative to the superview . 35. What are the design patterns in ios? Singleton Delegate Model View Controller Observer Facade Command Template Method 36. Types of Dispatch Queues Serial :execute one task at a time in the sequential order Concurrent: execute one or more tasks concurrently. Main dispatch queue: executes tasks on the application’s main thread. 37. key value coding(KVC) and key value observing (KVO) Key-Value-Coding (KVC) : accessing a property or value using a string. Key-Value-Observing (KVO) : observe changes to a property or value. 38. Application life cycle application:willFinishLaunchingWithOptions application:didFinishLaunchingWithOptions applicationDidBecomeActive applicationWillResignActive applicationDidEnterBackground applicationWillEnterForeground applicationWillTerminate 39. Different states of application Not running Inactive Active Background Suspended 40. View life cycle loadView loadViewIfNeeded viewDidLoad viewWillAppear viewWillLayoutSubviews viewDidLayoutSubviews viewDidAppear viewWillDisappear viewDidDisappear 41. whats is delegate and notification Delegate: Creates the relationship between the objects. It is one to one communication. Notification: These are used if an object wants to notify other objects of an event. It is one to multiple communication. 42. What is the significance of “?” in Swift? The question mark (?) is used during the declaration of a property can make a property optional. If the property does not hold a value. 43.What are the Levels of Priority in QOS? User Interactive User Initiated Utility Background 44. How to write optional value in swift ? An optional that can hold either a value or no value. Optionals are written by appending a ‘?’ 45. How to unwrap the optional value in swift ? The simplest way to unwrap an optional value is to add a ‘!’ after the optional name. This is called “force unwrapping”. 46. Use of if -let statement in swift By using if- let ,we can unwrap an optional in safe way, otherwise nil it may crash the app sometimes. 47. What is id in Objective C? id is a type of any data type. It specifies a reference to any Objective-C object . 48. What is Categories in Objective C? Categories provide the ability to add functionality to an object without changing the actual object. 49. What is Extension in swift? Extension add new functionality to an existing class, structure, enumeration, or protocol type. Extensions are similar to categories in Objective-C. 50. Define Class methods and instance methods . An instance method accessed an instance of the class A class method accessed to the class itself. 51. How to add swift file to the existing Objective C project? If you add a new swift file to the existing project xcode will ask you to add Objective-C bridging header. 52. What is auto layout and why it uses? Auto Layout is a constraint-based layout system.By using this auto layout developers to create an adaptive interface that responds appropriately to changes in screen size and device orientation. 53.How many ways constraints can create programmatically? Three ways to creating constraints programmatically : layout anchors NSLayoutConstraint class Visual Format Language. 54. Is it possible to create multiple storyboards in single project. If yes how to switch from one storyboard to another? Yes, By using segue and Storyboard Reference we can switch from one storyboard to another storyboard. 55. What is let and var in swift? Let is immutable variable or a constant that means it cannot changed where as var is mutable variable meaning that it can be changed. 56. What is IBOutlet and IBAction in ios ? Interface Builder outlet(IBOutlet) is a variable which is a reference to a UI component. Interface Builder action(IBAction) is a function which is called when a specific user interaction occurs. 57. What is bundle in ios? A bundle is a directory in the file system that contains the all executable code and related resources such as images and sounds together in one place. 58. when will use deinit in swift? deinit can be used if you need to do some action or cleanup before deallocating the object. 59. what is the responsibility of URLSession? URLSession is responsible for sending and receiving HTTP requests. 60. what are the types of URLSessionTask? URLSessionDataTask URLSessionUploadTask URLSessionDownloadTask 61. Main difference between NSURLSession and NSURLConnection NSURLConnection: when our App goes to background mode or not running mode using NSURLConnection, everything we have received or sent were lost. NSURLSession: NSURLSession gives your app the ability to perform background downloads when your app is not running or app is suspended. 62. what is JSON? JSON ( JavaScript Object Notation) is a text-based, lightweight and easy way for storing and exchanging data. 63. what is JSONSerialization ? The built in way of parsing JSON is called JSONSerialization and it can convert a JSON string into a collection of dictionaries, arrays, strings and numbers . 64. Difference between core data and sqlite? Core Data is a framework that can be used for managing an object graph. Core Data is not a database.Core Data can use a SQLite database as its persistent store, but it also has support for other persistent store types, including a binary store and an in-memory store. SQLite is a lightweight relational database. 65. Difference between Keychain and NSUserDefaults? In Keychain: If user removed the app from device the saved UserName and Password still is there. In NSUserDefaults: If user removed the app from device the saved UserName and Password also removed. 66. what is app thinning. How to reduce app size? App thinning is concept of reducing the app size while downloading.Using the below methods we can reduce the app size App Slicing Bitcode On-Demand Resource 67. what is Bundle ID? The Bundle ID is the unique string that identifies your application to the system. 68. What are the types of certificates required for developing and distributing apps? Development and distributing certificates. Development certificate: used for development Distribution certificates: used for submitting apps to app store or in house 69. what are binaries required to install the app to device? .ipa, .app 70. what are the advantages of swift over Objective C? Readability Maintenance Safer Platform Less Code & Less Legacy Speed 71. What is latest xcode version and its features? Xcode latest version is 10.1 The Dark Mode instantly Swift Source Code Editor Debugging the Tools Playground for Machine Learning Source Control 72. What are new features in ios 12 for developers ? ARKit 2 Siri Shortcuts CarPlay for Navigation Apps Health Records Natural Language 73. How to pass data between view controllers Segue, in prepareForSegue method (Forward) Delegate (Backward) Setting variable directly (Forward) 74. What is the Output of the Following Program? class Cricket { var score = 100 } var player1 = Cricket() var player2 = player1 player2.score = 200 print((player1.score),(player2.score)) 200,200 iOS Questions and Answers Pdf Download Read the full article
0 notes
suzanneshannon · 6 years ago
Text
Types or Tests: Why Not Both?
Every now and then, a debate flares up about the value of typed JavaScript. "Just write more tests!" yell some opponents. "Replace unit tests with types!" scream others. Both are right in some ways, and wrong in others. Twitter affords little room for nuance. But in the space of this article we can try to lay out a reasoned argument for how both can and should coexist.
Correctness: what we all really want
It’s best to start at the end. What we really want out of all this meta-engineering at the end is correctness. I don’t mean the strict theoretical computer science definition of it, but a more general adherence of program behavior to its specification: We have an idea of how our program ought to work in our heads, and the process of programming organizes bits and bytes to make that idea into reality. Because we aren’t always precise about what we want, and because we’d like to have confidence that our program didn’t break when we made a change, we write types and tests on top of the raw code we already have to write just to make things work in the first place.
So, if we accept that correctness is what we want, and types and tests are just automated ways to get there, it would be great to have a visual model of how types and tests help us achieve correctness, and therefore understand where they overlap and where they complement each other.
A visual model of program correctness
If we imagine the entire infinite Turing-complete possible space of everything programs can ever possibly do — inclusive of failures — as a vast gray expanse, then what we want our program to do, our specification, is a very, very, very small subset of that possible space (the green diamond below, exaggerated in size for sake of showing something):
Tumblr media
Our job in programming is to wrangle our program as close to the specification as possible (knowing, of course, we are imperfect, and our spec is constantly in motion, e.g. due to human error, new features or under-specified behavior; so we never quite manage to achieve exact overlap):
Tumblr media
Note, again, that the boundaries of our program’s behavior also include planned and unplanned errors for the purposes of our discussion here. Our meaning of "correctness" includes planned errors, but does not include unplanned errors.
Tests and Correctness
We write tests to ensure that our program fits our expectations, but have a number of choices of things to test:
Tumblr media
The ideal tests are the orange dots in the diagram — they accurately test that our program does overlap the spec. In this visualization, we don’t really distinguish between types of tests, but you might imagine unit tests as really small dots, while integration/end-to-end tests are large dots. Either way, they are dots, because no one test fully describes every path through a program. (In fact, you can have 100% code coverage and still not test every path because of the combinatorial explosion!)
The blue dot in this diagram is a bad test. Sure, it tests that our program works, but it doesn’t actually pin it to the underlying spec (what we really want out of our program, at the end of the day). The moment we fix our program to align closer to spec, this test breaks, giving us a false positive.
The purple dot is a valuable test because it tests how we think our program should work and identifies an area where our program currently doesn’t. Leading with purple tests and fixing the program implementation accordingly is also known as Test-Driven Development.
The red test in this diagram is a rare test. Instead of normal (orange) tests that test "happy paths" (including planned error states), this is a test that expects and verifies that "unhappy paths" fail. If this test "passes" where it should "fail," that is a huge early warning sign that something went wrong — but it is basically impossible to write enough tests to cover the vast expanse of possible unhappy paths that exist outside of the green spec area. People rarely find value testing that things that shouldn't work don't work, so they don’t do it; but it can still be a helpful early warning sign when things go wrong.
Types and Correctness
Where tests are single points on the possibility space of what our program can do, types represent categories carving entire sections from the total possible space. We can visualize them as rectangles:
Tumblr media
We pick a rectangle to contrast the diamond representing the program, because no type system alone can fully describe our program behavior using types alone. (To pick a trivial example of this, an id that should always be a positive integer is a number type, but the number type also accepts fractions and negative numbers. There is no way to restrict a number type to a specific range, beyond a very simple union of number literals.)
Tumblr media
Types serve as a constraint on where our program can go as you code. If our program starts to exceed the specified boundaries of your program’s types, our type-checker (like TypeScript or Flow) will simply refuse to let us compile our program. This is nice, because in a dynamic language like JavaScript, it is very easy to accidentally create a crashing program that certainly wasn’t something you intended. The simplest value add is automated null checking. If foo has no method called bar, then calling foo.bar() will cause the all-too-familiar undefined is not a function runtime exception. If foo were typed at all, this could have been caught by the type-checker while writing, with specific attribution to the problematic line of code (with autocomplete as a concomitant benefit). This is something tests simply cannot do.
We might want to write strict types for our program as though we are trying to write the smallest possible rectangle that still fits our spec. However, this has a learning curve, because taking full advantage of type systems involves learning a whole new syntax and grammar of operators and generic type logic needed to model the full dynamic range of JavaScript. Handbooks and Cheatsheets help lower this learning curve, and more investment is needed here.
Fortunately, this adoption/learning curve doesn’t have to stop us. Since type-checking is an opt-in process with Flow and configurable strictness with TypeScript (with the ability to selectively ignore troublesome lines of code), we have our pick from a spectrum of type safety. We can even model this, too:
Tumblr media
Larger rectangles, like the big red one in the chart above, represent a very permissive adoption of a type system on your codebase — for example, allowing implicitAny and fully relying on type inference to merely restrict our program from the worst of our coding.
Moderate strictness (like the medium-size green rectangle) could represent a more faithful typing, but with plenty of escape hatches, like using explicit instances of any all over the codebase and manual type assertions. Still, the possible surface area of valid programs that don’t match our spec is massively reduced even with this light typing work.
Maximum strictness, like the purple rectangle, keeps things so tight to our spec that it sometimes finds parts of your program that don’t fit (and these are often unplanned errors in your program behavior). Finding bugs in an existing program like this is a very common story from teams converting vanilla JavaScript codebases. However, getting maximum type safety out of our type-checker likely involves taking advantage of generic types and special operators designed to refine and narrow the possible space of types for each variable and function.
Notice that we don’t technically have to write our program first before writing the types. After all, we just want our types to closely model our spec, so really we can write our types first and then backfill the implementation later. In theory, this would be Type-Driven Development; in practice, few people actually develop this way since types intimately permeate and interleave with our actual program code.
Putting them together
What we are eventually building up to is an intuitive visualization of how both types and tests complement each other in guaranteeing our program’s correctness.
Tumblr media
Our Tests assert that our program specifically performs as intended in select key paths (although there are certain other variations of tests as discussed above, the vast majority of tests do this). In the language of the visualization we have developed, they "pin" the dark green diamond of our program to the light green diamond of our spec. Any movement away by our program breaks these tests, which makes them squawk. This is excellent! Tests are also infinitely flexible and configurable for the most custom of use cases.
Our Types assert that our program doesn’t run away from us by disallowing possible failure modes beyond a boundary that we draw, hopefully as tightly as possible around our spec. In the language of our visualization, they "contain" the possible drift of our program away from our spec (as we are always imperfect, and every mistake we make adds additional failure behavior to our program). Types are also blunt, but powerful (because of type inference and editor tooling) tools that benefit from a strong community supplying types you don’t have to write from scratch.
In short:
Tests are best at ensuring happy paths work.
Types are best at preventing unhappy paths from existing.
Use them together based on their strengths, for best results!
If you’d like to read more about how Types and Tests intersect, Gary Bernhardt’s excellent talk on Boundaries and Kent C. Dodds’ Testing Trophy were significant influences in my thinking for this article.
The post Types or Tests: Why Not Both? appeared first on CSS-Tricks.
Types or Tests: Why Not Both? published first on https://deskbysnafu.tumblr.com/
0 notes
cgknowhow · 6 years ago
Text
GSoC Coding Phase - Part 1
Hello everyone!
A lot has happened since the GSoC results were declared! I’ve got quite a few things implemented in my project, I’ll be breaking the discussion of the first part of the coding phase into two or three parts. So lets get into it without further ado.
According to my proposal here, I had one week of community bonding, during which I had to make sure that I had everything I needed to begin with the project, and discuss with the mentors what i should be doing ahead of time. I received a mail from my mentors, Brad and Marc welcoming me to the program. After some discussion it was decided that I should modify my milestones a little bit. Swift for TensorFlow is being used in the Fast.ai course. And there’s a lot of interest in displaying plots in Jupyter notebooks, which is being driven by this. This was to be moved to the first milestone. I have never worked with Jupyter notebooks before let alone editing code that communicated with a Jupyter Kernel. Marc guided me through this. It was decided that for an initial implementation I could use the Swift-Python interoperability to display base64 images in a relatively straightforward manner. Once I implemented some of the planned plots I could work on a pure Swift implementation.
One of the most important parts of building a framework is that it functions as expected. There will definitely be many revisions and changes to the code later on. This warranted a need for the presence of some tests included in the project repository. This would help in making sure that new changes did not break the previously working plots. (I am really glad that we decided to include this in the first milestone itself. It helped me find a really important bug! We’ll come to it in later on)
I have been a little vague in my proposal about implementation of Sub Plots. For those who don’t know what Sub Plots are, they are multiple graphs included in a single display/image. They can be of any type(Line Graph, Bar Graph, etc.). It was necessary to include Sub Plots in the first milestone itself because each Plot would have to be coded in a way that it could be part of a Sub Plot. Implementing all the plots independently and later adding Sub Plot support would be a lot of extra work!
So this is what was decided. In the first milestone I would do the following:
Make a simple Line Chart implementation with Sub Plot support.
Setup tests that saves images.
Get a base64 encoded PNG and use it in Jupyter notebook. Later work on python free implementation.
Complete line chart implementation in the leftover time.
The rest of the stuff for the first milestone according to my proposal were to be moved to the second milestone.
It didn’t take long for me to complete the simple line chart. I used most of the code from the prototype I had made with a few changes.
Let’s look briefly at the LineGraph implementation. All the further discussion will be applicable to Linux (I am using Ubuntu 18.04 LTS) unless otherwise specified.
The first step was to set up the Swift Package. For absolute beginners, this is how you initialise a Swift Package using the Swift Package manager:
Execute this command in the terminal.
swift package init --type library
This will initialise a package that is primarily meant to be a library. If you want a package with an executable as the build product, you can change the type flag to executable.
Before implementing the plots I had to set up the renderers because they were the entities that would handle all the image generation. The plan was to have almost no plotting logic in the Renderers. They would just allow you to draw primitives such as Lines, Rectangles, Text, etc.
One of the Renderers part of the project is the Anti-Grain Geometry C++ library, developed by the late Maxim Shemanarev. I wrote some code to render simple primitives necessary for a Line Graph. Although Swift Package Manager can compile C++ code, C++ functions aren’t directly accessible from Swift code. So I had to write a bridging C-headers. You can call the C-functions from Swift directly which in turn call the C++ functions. You can find the implementation here.
One other aim of implementing different rendering backends was to facilitate adding more backends in the future. This required all the Renderers to have some main stuff in common. So I made a Renderer protocol that included the main functions that every Renderer must have. Each Renderer will have to conform to that protocol. 
The AGGRenderer worked fine apart from one thing. The plot dimensions and and therefore the buffer size were hard coded. This meant that the user couldn’t change the size of the image rendered. This was obviously a big handicap to the end user. But for the moment I decided to focus on implementing the plot and getting the basic structure up and running. I could deal with it later on.
The other Renderer I planned to implement was a simple SVGRenderer written in Swift. The implementation is pretty simple and straightforward just like the SVG format. It has a String variable that will describe the image. Whenever you need to draw a primitive you pass the data to the SVGRenderer and it concatenates the relevant tag to the String. In the end the Renderer saves the String into a .svg file. 
We’re talking about passing the plotting data to the Renderer, but how does that happen? I have defined a Point type which is a struct. It contains two Floats, x and y.  You can pass the plotting data to the Renderer in the form of Point variable, or Point arrays. But the end user need not worry about this. All this will be handled by the Plots. Which brings us to the LineGraph implementation.
What I noticed first was that each plot would have to have the support of being a SubPlot. Therefore the renderer would need each image and plot to have separate dimensions in case of a SubPlot.  Lets take an example of two SubPlots stacked horizontally. An easy way to go about it would be to do all the plot calculations of each plot in its own independent co-ordinate system and the shift the origin of each plot as required while drawing it.So what I did was create a Plot protocol with a PlotDimensions type that held the image size and the dimesions of the current plot being rendered, and two offset variables, xOffset and yOffset respectively. In this case the xOffset of the second SubPlot will be a positive number and the yOffset will be zero for both of them. The plot dimensions will be equal divisions of the net image space available to all the Sub Plots. The Renderer will just shift the origin of each SubPlot by (xOffset, yOffset). This did the job. 
Tumblr media
The Plot protocol has just one more method called drawGraph(). This was because each Plot had to have the functionality to just draw the plot in memory irrespective of what mode of output(like saving images in case of AGG, or displaying an image in a window in case an OpenGL implementation was written) the used Renderer would have. Also this facilitated drawing each SubPlot separately to the image before generating the final output. 
Then I took the plotting logic from my prototype and the basic Line Graph was done. 
The next step was to set up the tests. I created an examples directory with individual executable modules, each demonstrating a single feature. In this directory I made a Reference directory with two separate directories for AGG and SVG renders. So that anyone could run all the tests easily in one go, I made a simple bash script with the commands to run each example like so:
swift run <Executable Example Module Name>
Then came the time to let the users show the plots in a Jupyter Notebook. Initially the way I did this was, save the image as usual using the AGGRenderer, re read it from the disk encode it to base64 in C++ code, and send back the String to Swift code. But there was a better way that my mentors suggested. The library that I was using to encode PNGs, lodepng, allowed you to encode the image in memory and not save it to the disk. I could return a pointer to a buffer with the encoded bytes, to the Swift code and use some functions under Foundation to do the base64 encoding in Swift itself. This could come in handy sometime later if another Renderer could generate images that coudl be encoded to base64. I did the encoding using a function like this:
public func encodeBase64PNG(pngBufferPointer: UnsafePointer<UInt8>, bufferSize: Int) -> String {    let pngBuffer : NSData = NSData(bytes: pngBufferPointer, length: bufferSize)    return pngBuffer.base64EncodedString(options: .lineLength64Characters) }
To display the image in Jupyter I added these lines to the EnableIPythonDisplay.swift file in the swift-jupyter repository:
func display(base64EncodedPNG: String) {  let displayImage = Python.import("IPython.display")  let codecs = Python.import("codecs")  let imageData = codecs.decode(Python.bytes(base64EncodedPNG, encoding: "utf8"), encoding: "base64")  displayImage.Image(data: imageData, format: "png").display() }
To display the plot the only thing the user has to do is to include this file in their jupyter notebook, get the base64 image from the plot object and pass it to the display function.
This completed all the main stuff I had planned for my first milestone well before the deadline. By this time the official coding period hadn’t started yet. The first deadline was June 24 and I had almost a month left. I could cover a lot more stuff in my first milestone itself, so I decided to complete the Line Plot and keep at least the Bar Chart implementation in my first milestone.
You can find all the code here.
This post has already gotten pretty long, so I’ll sign off here. I’ll be discussing the rest of my Line Graph implementation, Bar Chart implementation and how setting up the tests beforehand helped me avoid a bug, all in my next post.
Stay tuned!
PS: Don’t forget to subscribe to the Swift for TensorFlow newsletter to stay up to date with the work being done and the happenings of the S4TF community!
Here’s the link: https://www.s4tfnews.com/
Tumblr media
PPS: Also recently a Swift for TensorFlow Special Interest Group has been announced to help steer the framework. Weekly meetings will be held discussion the progress and plan ahead. Anyone interested can sign up to the mailing list here.
0 notes
datacouncil11-blog · 8 years ago
Text
What is Java And Features of Java
DataCouncil
1. What IS JAVA :
JAVA is an object-oriented programming language developed by James Gosling at Sun      Microsystems  (Sun) in 1991 initially clad as an oak.
JAVA is a platform independent language -> The target of Java is to write a program once and then run this program on multiple operating systems.
The first publicly available version of Java (Java 1.0) was released in 1995. Sun Microsystems was acquired by the Oracle Corporation in 2010.
Oracle has now the statesmanship for Java. In  2006 Sun started to make Java available under the GNU General Public License (GPL). Oracle continues this project called OpenJDK.
The current version of Java is Java 1.8 which is also known as Java 8.
2. Features of Java:
1-Simple:
 JAVA is simple because it uses simple English language to write a  java program.It is based on c and c++ so it is easy and removed complex things such pointer and many symbolic notations whited used in c and c++    
2-Object-oriented :
JAVA is object oriented because it supports oops concepts.  
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object-
Any entity that has state and behavior is known as an object. for example. chair, pen, table, keyboard, bike etc.it can be physical and logical.
Class-
Collection of the object is called.it is a logical entity.Inheritance- When one object acquires all the properties and behavior of parent of parent object i.e. known as Inheritance .it provides code re-usability.
Polymorphism
-When one task is performed by different ways i.e. known as polymorphism. For example: to convince the customer differently, to draw something e.g. shape or rectangle etc.In Java, we use method overloading and method overriding to achieve polymorphism.Another example can be to speak something.
Tumblr media
Encapsulation-Binding (or wrapping) code and data together into a single unit are known as encapsulation. For example capsule, it is wrapped with different medicines.
Tumblr media
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here. Abstraction-Hiding internal details and showing functionality is known as abstraction. For example phone call, we don't know the internal processing.In Java, we use abstract class and interface to achieve abstraction.example: phone call, we don't know the internal processing.In Java, we use abstract class and interface to achieve abstraction. 3- Platform Independent: JAVA is a platform independent language -> The target of Java is to write a program once and then run this program on multiple operating systems. 
4- Secured: JAVA code get Convert into bytecode after compilation so bytecode is not able to read by human.JAVA does not use a pointer so no memory location gets trap Java run under JVM so it is secured. 
5- Robust: Robust means strong. Java uses effective memory management. There are no pointers in java that avoid a security problem. There is automatic garbage collection in java. There is exception handling and type checking mechanism in java All these points make java robust.  
  6- High-performance  Java is faster than traditional interpretation since bytecode is "close" to native code  .still somewhat slower than a compiled language.It also supports Multithreading it increases performance and it uses JIT it supports to execute program faster. 7- Java Support exception handling: It supports the exception handling so it is easy to handle exception which occurred at compile and run-time. So it makes easy to maintain the project .
8- Java Support Collection framework : It is a very important feature of java it provides interface and classes to store data and manage the data. 9- Java is dynamic: Because bytecode and source code is written in one platform, but some code will run on JDK that's why Java is considered as a dynamic language. because Java code is interpreted dynamically as per required machine.Java support garbage collection so it allocates memory dynamically. 10- Java has distributed : Language Means because the program of java is compiled onto one machine can be easily transferred to a machine and Executes them on another machine because facility of Bytes Codes So java is Specially designed For Internet Users which uses the Remote Computers For Executing their task.It supports RMI and EJB for it.
More details- https://www.datacouncil.in/java-classes-pune-java-training
0 notes
itbeatsbookmarks · 8 years ago
Link
(Via: Hacker News)
Monoids are a pretty interesting concept in software development. Monoids are everywhere. Monoids are simple yet powerful. And Monoids have a lot to teach us about software, in particular about composition and building powerful abstraction.
This post will take you through a small tour of what Monoids are and are for. We will first define what Monoids are and show some first examples. We will then discuss the benefits they can bring to your code, and illustrate it through a more involved example. As closing thoughts, we will step back and think about what Monoids can teach us about programming in general.
Disclaimer: Starting from the second part, we will use Haskell and C++ for our examples, but this post is written such that the knowledge of these languages is not strictly required to follow it.
  What is a Monoid
We will first review the basics of Monoids, by going through the formal definition and some classic examples. You are encouraged to skip this section if you are already familiar with Monoids.
  Definition (formal)
A Monoid can be defined a tuple (M, op, e) where:
M is a set of element
op is an associative binary operation on two elements of M, returning a new element of M
e is an element of M, neutral for op on both left and right side
Note: Depending on the field of Math considered, Monoids have several definitions. This one is not the most general one, but will do for the rest of this post.
  Definition (statically typed languages)
In a statically typed language, we can translate the notion of set into the notion of type. A Monoid consists of a type T and a function f obeying the following rules:
f takes two instances of T and returns a new instance of T
f is associative: for all a, b and c, we have f(f(a, b), c) == f(a, f(b, c))
f has a neutral element e: for all a, f(e, a) == a == f(a, e)
Some language like Haskell have an explicit interface for Monoids which a type can implement. Beware though that in general the same type T can participate in several Monoids.
  Classic examples
I listed below some of the very classic and general examples. Almost all of them are pretty easy to identify and are documented in many online resources:
Integers form a Monoid under addition with the neutral element zero
Integers form a Monoid under multiplication with the neutral element one
Sequential containers form a Monoid under concatenation (strings, vectors…)
Associative containers form a Monoid under union (maps, sets…)
You can find a bunch more listed in this Wikipedia page dedicated to Monoids.
  Monoids are everywhere
Here are some less classic examples, which I listed below to show that Monoids can be found in many different domains, and in many successful libraries:
C++ range-v3 ranges form a Monoid under view::concat with the empty range as neutral element
Money amounts define a Monoid under summation with the null amount as neutral element
Relative paths in a file system form a Monoid under appending
Access rights to files form a Monoid under intersection or union of rights
All of these examples are pretty close to the classic ones. Access rights are related to sets, ranges are related to sequential containers, money amounts are related to numbers (or to associative containers).
So an easy way to identify and recognise Monoids in your own code is simply to look at how the concept of your domain relate to the usual suspects.
  Why Monoids are useful
Monoids are a great way to build complex behaviour out of simple elements, without having to introduce new concepts in your software. This section will explain why. The next section will illustrate it with code.
  The closure gives composition, free of intellectual charge
Because the binary operation of a Monoid takes two values of a given type and returns a new value of the same type (closure property), this operation can be chained indefinitely.
We can compose simple elements into composite elements
These composite elements can be composed further, just as simple elements can
Since we stay in the same world, this process can continue for ever
In addition to this, and because we are only dealing with one type, we get composition for free: we do not have to introduce new types, and therefore new concepts in our code.
A Monoid gives us a way to build complexity out of simplicity, with no conceptual cost added.
  Associativity gives abstraction over the construction details
Let us imagine for a moment that the binary operation was not associative:
The outcome of combining several elements together would depend on the order in which we combine them (the more elements we have, the larger the number of outcomes)
So to get a desired outcome, we would have to care about this composition order, all the way down to the simplest elements we combine together
We would therefore have to distinguish primitive elements (not built by combination) from composite ones, and care about how many combination took place
In short, we would have to know all about the details of construction of a value. Instead, associativity abstracts away the details of construction. Given a value, we do not have to care how it was built, and whether it is a composite or not. We might not be even able to tell (*).
This abstraction has additional benefits as well: we can split work of constructing a value to different parts of the software, or to different threads even.
(*) In fact, we must not be able to tell or the abstraction is broken. Associativity requires this kind of information to be erased. This is the point of an abstraction: getting rid of unimportant details.
  A more involved example of Monoid
We will now illustrate how Monoids abstract away the details of creation of a value, to help us build powerful abstractions. To do so, we will create a small library to represent shapes in any number of dimensions.
We will give the examples in Haskell first, and translate them in C++ at the end of each section.
  Abstract definition of a shape
In the context of this example, we will define a shape as being a region of space, with an arbitrary number of dimension. For instance, a disk is a region of a 2D space. It contains all the points at a distance from the centre of the disk lower or equal than the radius.
Our goal is to write a small library to define and combine such shapes together into arbitrarily complex shapes. To do so, and in order to be agnostic to sampling issues, we will use an idea I first read about from Conal Elliott. We will represent shapes as functions from coordinates to a boolean, whose value indicates whether the point is part of the shape. A simple and beautiful idea.
  Shapes and coordinates
To define a shape in code, we will define a Shape type which wraps a function from a coordinate (any kind of coordinate, so we use a template parameter) to a boolean:
To define a shape in 2D, we define a type alias for coordinates in two dimensions. We then define a 2-dimentional shape as a type alias on a shape templated on a 2D coordinate:
Viewing shapes as function is a pretty interesting model. Thanks to it, we can for instance pretty easily define the complement of a shape. This new shape is such that it contains all the points that were not in the previous shape (and does not include any of the points of the previous shape).
We call the function which computes this complement outside. It simply negates the predicate of the input shape (note that this works in any number of dimensions, with any coordinate system):
Here is the equivalent code (up to the strong typing) in C++:
  Example of shapes
To define a shape, we only need to define a function which returns whether a coordinate is inside the shape or not. Here is how we would define a disk:
The disk function returns a shape that wraps a lambda function
The lambda takes a coordinates and returns whether it is in the disk
To do so, it computes the euclidian distance of the coordinate to the centre
A point is in the disk if its distance to the center is inferior to the radius
We can test our disk in the REPL, by asking whether a point is inside it:
Here is the equivalent code (up to the strong typing) in C++:
Now that we have the basics for a shape, let us see what kind of Monoid we can find here.
  Intersecting shapes
A shape forms a Monoid under the intersection of shapes. The intersection of two shapes is defined as another shape which contains only the coordinates that are in both input shapes:
We can even generalize this to define the intersection of an arbitrarily large number of shapes (the resulting code is available in this GitHub Gist).
We also need a neutral element. In the case of the intersection, it would be the shape that covers the whole space. We can define it as a shape which always returns that a coordinate is inside it:
Here is the equivalent code (up to the strong typing) in C++:
Finally, because the and operator is associative, our intersect function is associative as well. So we have a Monoid. Let us play with it.
Note: We can define another Monoid as well for the superposition of shapes: the full code is provided here. This intersection / union process can be generalised to any predicate (with the AND and the OR operators).
  Complex shapes out of simple shape
Using our intersection operation, we can build more complex shapes. We can for instance intersect a disk with a rectangle, giving us a shape like this:
******************* *********************** ************************* ************************* *********************** *******************
To build a ring-like shape, we can intersect the outside of a small disk with the interior of a big disk, both centered at the same point:
Using a small helper function, we can draw one in the console:
**** ******** ******** *** *** *** *** *** *** *** *** ******** ******** ****
Here is the equivalent code (up to the strong typing) in C++:
Nothing forbids us to compose these shapes even further, to intersect a ring with a rectangle for instance. There is no limit to our crazy imagination.
  Building a vocabulary of shapes
Since the output of a Monoid operator is also a shape, we can define complex shapes out of very simple shapes and keep on composing them. The details of construction of these new shapes are abstracted.
We are also unable to distinguish a composite shape from a primitive shape. Composite shapes behave, look and smell exactly like primitive shapes, enriching our vocabulary of primitive shapes at a low cost.
Finally, and thanks to the associative nature of the Monoid operator, we never have to care about the order in which these intersections take place. We can first intersect a rectangle with a disk and then a ring, or do it the other way around. It does not matter: given a shape, we never have to care how it was constructed.
EDIT: as u/carrutstick noted, the use of the “order” word in the sentence above might be misleading. It refers to the order of application of the associative binary operation, not the commutativity, that is to say intersect(intersect(rectangle, disk), ring) is the same as intersect(rectangle, intersect(disk, ring)).
  More advanced examples of Monoids
There are plenty more examples of Monoid we could talk about.
I have been lucky enough to participate to a training given by Cyrille Martraire, in which he gave us some more example on how to apply this notion to represent financial cashflows. French speakers might be interested in looking at his Monoid talk at the Devoxx 2015.
If you happen to attend the CppCon 2017, you might be interested in coming our presentation on How to apply Functional Programming ideas to build a HTTP router API. At this occasion, Jeremy Demeule and myself will be showing two more examples of Monoids.
  Closing thoughts: What Monoids teach us about software
We saw that Monoids have very good characteristics in terms of composition and abstraction, two very valuable characteristics to get in our code. By looking at how they achieve this, we can make some parallel with other good ways to achieve composition.
  Associativity & ordering
As we just saw, the associativity is a pretty important property of the Monoid operation. Had the binary operation not been associative, the whole abstraction would have collapsed.
Without associativity, we have to care about the order in which we combine the elements
This ordering provokes an combinatorial explosion of the possible outcomes
In fact, associativity is not as important as being ordering independent (it just so happens that associativity is sufficient to get this property for Monoids). In general, code whose outcome does not depend on its order of execution favours greater composition.
  Side effects and ordering
Let us think about the obvious kind of things that would instantaneously make us lose associativity (or alternatively, make the result of our program sensitive to ordering).
The obvious suspect is side effects. Any side effect (an action performed by a process, visible from the rest of the program) inside the binary operation of a Monoid would instantaneously break the associative property. For instance, a adding a print statement would result in different traces being emitted depending on the order of evaluation.
In general, any assignment to a variable aliased externally, or any IO effect, will introduce a dependency to ordering and time in our programs. It will make the program vulnerable to issues such as race conditions, but also greatly limit its composability.
  Side effects and composition
In general, there is a pretty strong correlation between our ability to compose program and the amount of side-effects this program relies on to perform its job.
If we see Monoids are a small laboratory to experiment with the consequences of side-effects on a whole program, we understand that limiting side effects to a limited scope in our software is key to build composable and leak-free abstractions.
Follow @quduval
Comments are closed.
0 notes
adamcrouchbct · 8 years ago
Text
Coding Blog Posts
Entry 11/05/2017
Today I began brainstorming my concept for the program in which I am going to code for the programming class using processing. I had thoughts about doing either games, interactive art or data visualisation. However, after playing around with in my processing classes with colours and shapes, I began creating an app which you could draw. So, this is where I am going to start my project.
My goal so far is to create an app which allows the user to change the colour, size & opacity of their brush.
So far, I have created a programme in which a circle follows your mouse and then when you click a circle is drawn, and this circle changes shape and colour randomly. Creating some very interesting art.
Tumblr media
 Entry 18/05/2017
I have started to fine tune my initial concept. I will have a window about 1000px by 1250px, on the left I will have a sidebar about 200px, and height of window and the remaining section will be the ‘artboard’. In the sidebar users can adjust the colour, size & opacity of their brush. I am going to use RGB for the colour selector and then have individual inputs for Red, Green & Blue to allow for greater customisation. On the right-hand side will be the artboard and this is where users will draw.
I need to work out a way to allow users to change the variables of colour, size & opacity and how to make it so users cannot draw over sidebar only on the artboard.
Tumblr media
Entry 25/05/2017
I have worked out I will user an external processing library called jControl which will allow me to easily code in sliders which I can use in the sidebar. So, I will have a slider for each red, green & blue and for opacity and size individually. I have also had a thought about adding in below the sliders a square which represents your current brush settings, so it will change colour, size and opacity based on your current selected settings, this is users can see their brush settings.
I have also made it so the sidebar is layered about the artboard, so you cannot draw on the sidebar. While using my app I realised I needed to have a clear option. To do this I decided I would just write ‘if’ ‘keyPressed’ command so when you press ‘C’ or ‘c’ it will clear your current art and replace it with fresh screen. However, this made the app blink black when you pressed it as it was putting the background over the sidebar. To fix this, I made the artboard and sidebar two separate rectangles that would-be a % of the width and height of the window. This then meant that rather than the background being cleared it only cleared the artboard and so the blinking error was fixed. It also meant that my programme could be scaled to any size window and would keep the same proportions.
 Entry 02/06/2017
My programme is coming to its final stage ready for submission. This past week, I have made all the sliders and elements of the programme use a % of width and height of window so that all the elements including text can be resized to fit any size window and everything will remain proportionate.
I have also started using the fullScreen(), function which means my programme will be going full screen rather than 1000px by 1250px.
Plus based on the lecturer’s advice I have added a SAVE function, so that users can save their work. The tricky bit here was finding a good save string structure for naming the saved files and to not capture the whole screen only the artboard. I solved these challenges firstly because my artboard was a % of the width and height of the window, I could code the capture image function to only take a % of the screen which meant it only captured the artboard. I also used a PNG file type for the image and a date/time string which meant the users image would be saved into the programs root folder as the date and time they saved it.
Tumblr media
Final Post
I have begun clearing up my code, formatting it and adding in necessary comments, ready for submission.
I have really enjoyed this project, and it has been a vast experience coding and learning a new language. The best bit for me, was the problem-solving aspect related to coding, which I found the most interesting part, as it got you thinking about different solutions and choosing the best one. While at the end of this process you get to use and see your actual code in a visual product.
Next time, I would like to look at adding a function which allowed the user to change the shape of their brush, so it could be square or triangle etc and not just a circle. I would also look at creating an option which allowed the user to change the background colour of the artboard, so it wasn’t just black. Also possibly adding in a random function, which my initial concept had, so that the colour and size of the brush could be random rather than always being selected by the user.
0 notes