Михаил расскажет, как писать на современном С++ простой, выразительный и эффективный код для решения повседневных задач. Приведет пример реального кода, с которым ему приходилось работать, и расскажет, как сделать его лучше с помощью ряда простых средств из STL и boost, а также за счёт применения хороших практик программирования. Доклад рассчитан на базовые знания языка.
Михаил Матросов, Повседневный С++: boost и STLSergey Platonov
The document discusses comparing bakeries based on their cookies. It describes collecting and sorting cookies from two bakeries into vectors. It then compares the cookies using iterators over the vectors to find differences and return whether the bakeries are equal. Functional programming techniques like using tuples for comparison are also discussed to improve the cookie comparison code.
В докладе будет рассмотрена система контроля качества с помощью снятия и анализа крэшдамп-файлов (применительно в первую очередь к системе Windows). Будет представлена архитектура и инструментарий для организации автоматического сбора и анализа крэшдамп-файлов, снимаемых в момент возникновения проблем в приложениях (падения, зависания, превышение потребления ресурсов – памяти, файловых дескрипторов и т.д.)
This document provides an overview of HTML5 and its capabilities for building interactive web applications. It discusses the history and development of HTML5, including the roles of the WHATWG and W3C. It also summarizes key HTML5 features such as JavaScript, Canvas, WebSockets, storage options, and emerging 3D capabilities. Throughout, it provides examples of how these features can be used to create games, multimedia experiences, and real-time applications on the modern web.
2014 yılının sonunda sonlandırılması beklenen HTML standardının 5. sürümü çoktandır tarayıcılar tarafından destekleniyor. HTML5 ile gelen Canvas, Websockets ve diğer özelliklerle nasıl daha canlı, daha Flash uygulamalarına benzer, web uygulamaları geliştirebileceğimizi inceledik.
The Ring programming language version 1.4.1 book - Part 18 of 31Mahmoud Samir Fayed
This document provides examples of creating a simple weight history application using Qt and Ring. It includes code to create a GUI with a table to display records, buttons to add and delete records, and functions to open and query a SQLite database. Records added through the GUI are inserted into a database table with date, time and weight fields. The table is populated by querying the database and records can be deleted by ID.
The document discusses moving content from Flash to HTML5. It begins by providing an overview of Flash file anatomy and ActionScript2/3. It then covers how ActionScript3 bytecode can be converted to JavaScript by analyzing the bytecode operations and reimplementing them in JavaScript. This allows ActionScript content to be run directly in the browser without Flash by translating the bytecode to an equivalent JavaScript format at runtime.
The Ring programming language version 1.10 book - Part 64 of 212Mahmoud Samir Fayed
This document discusses using RingOpenGL and RingFreeGLUT for 3D graphics development in Ring.
RingOpenGL provides bindings to the OpenGL graphics library and supports versions from OpenGL 1.1 to 4.6. RingFreeGLUT contains bindings to the FreeGLUT library for creating windows, handling events, etc.
The document provides a simple example of creating a window using RingFreeGLUT. It loads the FreeGLUT library, initializes GLUT, sets the display mode and window size/position, creates a window with a title, and enters the main loop to process events.
Mythbusting: Understanding How We Measure the Performance of MongoDBMongoDB
- The document discusses various ways that performance benchmarks of MongoDB can be misleading or inaccurate if not done properly.
- It highlights common traps in benchmarking like measuring object creation time, thread contention, and other non-database factors.
- The key is to focus benchmarks only on the aspects you want to measure, like database response time, and remove other influences like object synthesis or thread contention from random number generation.
Михаил Матросов, Повседневный С++: boost и STLSergey Platonov
The document discusses comparing bakeries based on their cookies. It describes collecting and sorting cookies from two bakeries into vectors. It then compares the cookies using iterators over the vectors to find differences and return whether the bakeries are equal. Functional programming techniques like using tuples for comparison are also discussed to improve the cookie comparison code.
В докладе будет рассмотрена система контроля качества с помощью снятия и анализа крэшдамп-файлов (применительно в первую очередь к системе Windows). Будет представлена архитектура и инструментарий для организации автоматического сбора и анализа крэшдамп-файлов, снимаемых в момент возникновения проблем в приложениях (падения, зависания, превышение потребления ресурсов – памяти, файловых дескрипторов и т.д.)
This document provides an overview of HTML5 and its capabilities for building interactive web applications. It discusses the history and development of HTML5, including the roles of the WHATWG and W3C. It also summarizes key HTML5 features such as JavaScript, Canvas, WebSockets, storage options, and emerging 3D capabilities. Throughout, it provides examples of how these features can be used to create games, multimedia experiences, and real-time applications on the modern web.
2014 yılının sonunda sonlandırılması beklenen HTML standardının 5. sürümü çoktandır tarayıcılar tarafından destekleniyor. HTML5 ile gelen Canvas, Websockets ve diğer özelliklerle nasıl daha canlı, daha Flash uygulamalarına benzer, web uygulamaları geliştirebileceğimizi inceledik.
The Ring programming language version 1.4.1 book - Part 18 of 31Mahmoud Samir Fayed
This document provides examples of creating a simple weight history application using Qt and Ring. It includes code to create a GUI with a table to display records, buttons to add and delete records, and functions to open and query a SQLite database. Records added through the GUI are inserted into a database table with date, time and weight fields. The table is populated by querying the database and records can be deleted by ID.
The document discusses moving content from Flash to HTML5. It begins by providing an overview of Flash file anatomy and ActionScript2/3. It then covers how ActionScript3 bytecode can be converted to JavaScript by analyzing the bytecode operations and reimplementing them in JavaScript. This allows ActionScript content to be run directly in the browser without Flash by translating the bytecode to an equivalent JavaScript format at runtime.
The Ring programming language version 1.10 book - Part 64 of 212Mahmoud Samir Fayed
This document discusses using RingOpenGL and RingFreeGLUT for 3D graphics development in Ring.
RingOpenGL provides bindings to the OpenGL graphics library and supports versions from OpenGL 1.1 to 4.6. RingFreeGLUT contains bindings to the FreeGLUT library for creating windows, handling events, etc.
The document provides a simple example of creating a window using RingFreeGLUT. It loads the FreeGLUT library, initializes GLUT, sets the display mode and window size/position, creates a window with a title, and enters the main loop to process events.
Mythbusting: Understanding How We Measure the Performance of MongoDBMongoDB
- The document discusses various ways that performance benchmarks of MongoDB can be misleading or inaccurate if not done properly.
- It highlights common traps in benchmarking like measuring object creation time, thread contention, and other non-database factors.
- The key is to focus benchmarks only on the aspects you want to measure, like database response time, and remove other influences like object synthesis or thread contention from random number generation.
Mythbusting: Understanding How We Measure the Performance of MongoDBMongoDB
Benchmarking, benchmarking, benchmarking. We all do it, mostly it tells us what we want to hear but often hides a mountain of misinformation. In this talk we will walk through the pitfalls that you might find yourself in by looking at some examples where things go wrong. We will then walk through how MongoDB performance is measured, the processes and methodology and ways to present and look at the information.
The document is a report on a Visual Programming Assignment (UAS) submitted by Andriyan Dwi P. It details two programming problems solved using C# and Windows Forms. Problem 1 involves creating patterned stars in the console or windows form. Problem 2 creates a database login system with forms for login, data entry, editing, deleting and viewing records from a MySQL database. Screenshots are included showing the outputs and database forms created.
The Ring programming language version 1.9 book - Part 50 of 210Mahmoud Samir Fayed
This document provides documentation on using cookies, URL encoding, templates, and various hash and encoding functions in Ring. It includes examples of setting and retrieving cookie values, URL encoding strings, using templates to combine Ring code and HTML, and functions for MD5, SHA1/256/384/512 hashing and encoding special characters. Screenshots are provided of the example applications.
Just a few years ago all software systems were designed to be monoliths running on a single big and powerful machine. But nowadays most companies desire to scale out instead of scaling up, because it is much easier to buy or rent a large cluster of commodity hardware then to get a single machine that is powerful enough. In the database area scaling out is realized by utilizing a combination of polyglot persistence and sharding of data. On the application level scaling out is realized by microservices. In this talk I will briefly introduce the concepts and ideas of microservices and discuss their benefits and drawbacks. Afterwards I will focus on the point of intersection of a microservice based application talking to one or many NoSQL databases. We will try and find answers to these questions: Are the differences to a monolithic application? How to scale the whole system properly? What about polyglot persistence? Is there a data-centric way to split microservices?
The Ring programming language version 1.6 book - Part 62 of 189Mahmoud Samir Fayed
This document provides documentation for Ring code related to a 3D tic-tac-toe game. It includes classes for:
1. Managing the game logic and checking for a winner (GameOver, CheckWinner)
2. Rendering the 3D cubes that make up the game board using OpenGL (GameCube)
3. Playing background music and sounds (GameSound)
4. Providing a base for graphics applications with event handling (GraphicsAppBase)
The Ring programming language version 1.5.1 book - Part 51 of 180Mahmoud Samir Fayed
This document provides instructions for building RingLibSDL games for Android. It outlines downloading the necessary requirements like the Android SDK and NDK. It describes the project folder structure, noting that source code and assets should be added to the assets folder. Finally, it provides the commands to build ("ndk-build") and create an APK package ("ant debug") from the project folder.
This document discusses using MongoDB as a log collector. It provides examples of storing log data from syslog-ng in MongoDB collections, including filtering and parsing logs. It also gives examples of analyzing the log data through map-reduce to find top IP addresses and provides ideas for other uses like CAPTCHAs, error localization, and analytics.
The Ring programming language version 1.5.4 book - Part 59 of 185Mahmoud Samir Fayed
This document describes the code for a 3D tic-tac-toe game written in Ring and Allegro. The code defines classes for the game logic, background, cubes, sounds, and interface. The main function initializes a TicTacToe3D object which loads resources and calls functions to draw the scene, handle mouse clicks, and check for a winner. The game interface class handles drawing the cubes on the game board and detecting mouse clicks on the cubes. The game logic class defines the game board data structure and functions for changing turns, detecting a winner, and refreshing the game.
This document contains code for a .NET class library that provides methods for generating hardware identification codes and license keys. It includes methods for retrieving hardware identifiers like the hard drive serial number, motherboard serial number, and CPU ID. It also contains encryption utilities for hashing, encoding, and generating cryptographic keys. The main purpose seems to be activating or validating software licenses based on hardware identifiers in a machine-specific way.
The Ring programming language version 1.5.2 book - Part 52 of 181Mahmoud Samir Fayed
This document describes code for a 3D game built using Ring and OpenGL. It includes functions for initializing OpenGL, drawing objects like cubes, handling input, and more. RingOpenGL provides bindings to the OpenGL graphics library that allow Ring programs to render 3D graphics. Sample code is based on OpenGL tutorials and shows how to create a simple 3D cube using RingOpenGL.
This Java program performs optical character recognition (OCR) on image files. It allows the user to open an image file, then perform line, word, and character segmentation on the image. The program displays the original image and overlay lines, words, and character boxes as each segmentation step is performed. It uses histograms and thresholding techniques on the pixel data to identify lines, words, and characters in the image.
The Ring programming language version 1.6 book - Part 66 of 189Mahmoud Samir Fayed
This document provides examples of using various Qt GUI widgets and classes in Ring. It includes examples of using QMediaPlayer to play multiple videos simultaneously, QFrame to create frames, QLabel to display images, creating a menubar and setting stylesheets, handling QLineEdit events and displaying QMessageBox, responding to signals from widgets like QProgressBar and QCheckBox, and using the QTimer class to update a label periodically.
Data analysis and visualization with mongo db [mongodb world 2016]Alexander Hendorf
MongoDB World, New York, June 29th
This talk will feature why MongoDB was the right choice and how one can visualize data via the MongoDB Connector for BI (e.g. with Tableau or open source libraries like bokeh) straight from MongoDB. We'll be building an application that offers real-time insights for the music industry.
The Ring programming language version 1.7 book - Part 57 of 196Mahmoud Samir Fayed
This document provides documentation for a Super Man game created with the Ring game engine. It includes the code for game objects like sprites, maps, and text displays. The player controls a Superman sprite to collect stars and keys while avoiding enemy sprites. The game ends if the player runs out of energy or reaches the exit.
The Ring programming language version 1.8 book - Part 59 of 202Mahmoud Samir Fayed
This document provides instructions for building RingLibSDL games for Android. The key steps are:
1. Download the Android SDK, NDK, Ant, and JDK for development. Update the Android SDK to the desired API level (e.g. API 19).
2. Set up the project folder structure with the game source code and assets.
3. Build the native code using the NDK build command (ndk-build).
4. Create the Android package (.apk) file using the Ant debug command (ant debug).
This allows games created with the Ring Game Engine to be packaged and run as Android applications. The sample project includes a ready-made Flappy Bird 3000
The Ring programming language version 1.5.1 book - Part 27 of 180Mahmoud Samir Fayed
- The document describes MySQL functions in Ring programming language for connecting to and interacting with MySQL databases. It provides examples and explanations of functions like MySQL_Connect(), MySQL_Query(), MySQL_Result(), MySQL_Insert_ID(), MySQL_Columns(), and others.
- It also demonstrates how to save and retrieve images from a database by encoding/decoding with MySQL_Escape_String(), and how to use transactions with MySQL_Autocommit(), MySQL_Commit(), and MySQL_Rollback().
The document contains C++ code that defines functions for displaying 3D objects using OpenGL. It initializes materials, lighting, and transforms for 10 objects. Keyboard inputs control animation and properties. Mouse clicks select an object and set rotation axes. The display function renders each object with the appropriate material and transform based on user input.
Operational Intelligence with MongoDB WebinarMongoDB
This document discusses using MongoDB for operational intelligence and real-time analytics of log and event data. It describes how MongoDB can ingest large volumes of data from multiple sources at high write volumes. Queries can then be performed rapidly to analyze the data and drill down into specific events. The aggregation framework is used to generate rollups and reports from the data on-demand or on a scheduled basis.
it is and slide contains Save to your mobile device with our new app
Don't have time to read now? Save SlideShares to read later or offline - anytime, anywhere.
dding more information (description, tags, category) makes it easier for others to find your content. The score increases as you add each item.
This document provides an introduction to creating Maya plugins using the C++ API. It discusses creating commands and nodes to integrate new functionality into Maya. Commands allow adding new tools through Python-like functions, while nodes add new node types to the dependency graph that perform computations. The document gives examples of defining a command class and node class to create and register new command and node types in Maya using the C++ API.
Mythbusting: Understanding How We Measure the Performance of MongoDBMongoDB
Benchmarking, benchmarking, benchmarking. We all do it, mostly it tells us what we want to hear but often hides a mountain of misinformation. In this talk we will walk through the pitfalls that you might find yourself in by looking at some examples where things go wrong. We will then walk through how MongoDB performance is measured, the processes and methodology and ways to present and look at the information.
The document is a report on a Visual Programming Assignment (UAS) submitted by Andriyan Dwi P. It details two programming problems solved using C# and Windows Forms. Problem 1 involves creating patterned stars in the console or windows form. Problem 2 creates a database login system with forms for login, data entry, editing, deleting and viewing records from a MySQL database. Screenshots are included showing the outputs and database forms created.
The Ring programming language version 1.9 book - Part 50 of 210Mahmoud Samir Fayed
This document provides documentation on using cookies, URL encoding, templates, and various hash and encoding functions in Ring. It includes examples of setting and retrieving cookie values, URL encoding strings, using templates to combine Ring code and HTML, and functions for MD5, SHA1/256/384/512 hashing and encoding special characters. Screenshots are provided of the example applications.
Just a few years ago all software systems were designed to be monoliths running on a single big and powerful machine. But nowadays most companies desire to scale out instead of scaling up, because it is much easier to buy or rent a large cluster of commodity hardware then to get a single machine that is powerful enough. In the database area scaling out is realized by utilizing a combination of polyglot persistence and sharding of data. On the application level scaling out is realized by microservices. In this talk I will briefly introduce the concepts and ideas of microservices and discuss their benefits and drawbacks. Afterwards I will focus on the point of intersection of a microservice based application talking to one or many NoSQL databases. We will try and find answers to these questions: Are the differences to a monolithic application? How to scale the whole system properly? What about polyglot persistence? Is there a data-centric way to split microservices?
The Ring programming language version 1.6 book - Part 62 of 189Mahmoud Samir Fayed
This document provides documentation for Ring code related to a 3D tic-tac-toe game. It includes classes for:
1. Managing the game logic and checking for a winner (GameOver, CheckWinner)
2. Rendering the 3D cubes that make up the game board using OpenGL (GameCube)
3. Playing background music and sounds (GameSound)
4. Providing a base for graphics applications with event handling (GraphicsAppBase)
The Ring programming language version 1.5.1 book - Part 51 of 180Mahmoud Samir Fayed
This document provides instructions for building RingLibSDL games for Android. It outlines downloading the necessary requirements like the Android SDK and NDK. It describes the project folder structure, noting that source code and assets should be added to the assets folder. Finally, it provides the commands to build ("ndk-build") and create an APK package ("ant debug") from the project folder.
This document discusses using MongoDB as a log collector. It provides examples of storing log data from syslog-ng in MongoDB collections, including filtering and parsing logs. It also gives examples of analyzing the log data through map-reduce to find top IP addresses and provides ideas for other uses like CAPTCHAs, error localization, and analytics.
The Ring programming language version 1.5.4 book - Part 59 of 185Mahmoud Samir Fayed
This document describes the code for a 3D tic-tac-toe game written in Ring and Allegro. The code defines classes for the game logic, background, cubes, sounds, and interface. The main function initializes a TicTacToe3D object which loads resources and calls functions to draw the scene, handle mouse clicks, and check for a winner. The game interface class handles drawing the cubes on the game board and detecting mouse clicks on the cubes. The game logic class defines the game board data structure and functions for changing turns, detecting a winner, and refreshing the game.
This document contains code for a .NET class library that provides methods for generating hardware identification codes and license keys. It includes methods for retrieving hardware identifiers like the hard drive serial number, motherboard serial number, and CPU ID. It also contains encryption utilities for hashing, encoding, and generating cryptographic keys. The main purpose seems to be activating or validating software licenses based on hardware identifiers in a machine-specific way.
The Ring programming language version 1.5.2 book - Part 52 of 181Mahmoud Samir Fayed
This document describes code for a 3D game built using Ring and OpenGL. It includes functions for initializing OpenGL, drawing objects like cubes, handling input, and more. RingOpenGL provides bindings to the OpenGL graphics library that allow Ring programs to render 3D graphics. Sample code is based on OpenGL tutorials and shows how to create a simple 3D cube using RingOpenGL.
This Java program performs optical character recognition (OCR) on image files. It allows the user to open an image file, then perform line, word, and character segmentation on the image. The program displays the original image and overlay lines, words, and character boxes as each segmentation step is performed. It uses histograms and thresholding techniques on the pixel data to identify lines, words, and characters in the image.
The Ring programming language version 1.6 book - Part 66 of 189Mahmoud Samir Fayed
This document provides examples of using various Qt GUI widgets and classes in Ring. It includes examples of using QMediaPlayer to play multiple videos simultaneously, QFrame to create frames, QLabel to display images, creating a menubar and setting stylesheets, handling QLineEdit events and displaying QMessageBox, responding to signals from widgets like QProgressBar and QCheckBox, and using the QTimer class to update a label periodically.
Data analysis and visualization with mongo db [mongodb world 2016]Alexander Hendorf
MongoDB World, New York, June 29th
This talk will feature why MongoDB was the right choice and how one can visualize data via the MongoDB Connector for BI (e.g. with Tableau or open source libraries like bokeh) straight from MongoDB. We'll be building an application that offers real-time insights for the music industry.
The Ring programming language version 1.7 book - Part 57 of 196Mahmoud Samir Fayed
This document provides documentation for a Super Man game created with the Ring game engine. It includes the code for game objects like sprites, maps, and text displays. The player controls a Superman sprite to collect stars and keys while avoiding enemy sprites. The game ends if the player runs out of energy or reaches the exit.
The Ring programming language version 1.8 book - Part 59 of 202Mahmoud Samir Fayed
This document provides instructions for building RingLibSDL games for Android. The key steps are:
1. Download the Android SDK, NDK, Ant, and JDK for development. Update the Android SDK to the desired API level (e.g. API 19).
2. Set up the project folder structure with the game source code and assets.
3. Build the native code using the NDK build command (ndk-build).
4. Create the Android package (.apk) file using the Ant debug command (ant debug).
This allows games created with the Ring Game Engine to be packaged and run as Android applications. The sample project includes a ready-made Flappy Bird 3000
The Ring programming language version 1.5.1 book - Part 27 of 180Mahmoud Samir Fayed
- The document describes MySQL functions in Ring programming language for connecting to and interacting with MySQL databases. It provides examples and explanations of functions like MySQL_Connect(), MySQL_Query(), MySQL_Result(), MySQL_Insert_ID(), MySQL_Columns(), and others.
- It also demonstrates how to save and retrieve images from a database by encoding/decoding with MySQL_Escape_String(), and how to use transactions with MySQL_Autocommit(), MySQL_Commit(), and MySQL_Rollback().
The document contains C++ code that defines functions for displaying 3D objects using OpenGL. It initializes materials, lighting, and transforms for 10 objects. Keyboard inputs control animation and properties. Mouse clicks select an object and set rotation axes. The display function renders each object with the appropriate material and transform based on user input.
Operational Intelligence with MongoDB WebinarMongoDB
This document discusses using MongoDB for operational intelligence and real-time analytics of log and event data. It describes how MongoDB can ingest large volumes of data from multiple sources at high write volumes. Queries can then be performed rapidly to analyze the data and drill down into specific events. The aggregation framework is used to generate rollups and reports from the data on-demand or on a scheduled basis.
it is and slide contains Save to your mobile device with our new app
Don't have time to read now? Save SlideShares to read later or offline - anytime, anywhere.
dding more information (description, tags, category) makes it easier for others to find your content. The score increases as you add each item.
This document provides an introduction to creating Maya plugins using the C++ API. It discusses creating commands and nodes to integrate new functionality into Maya. Commands allow adding new tools through Python-like functions, while nodes add new node types to the dependency graph that perform computations. The document gives examples of defining a command class and node class to create and register new command and node types in Maya using the C++ API.
Back to Basics, webinar 2: La tua prima applicazione MongoDBMongoDB
Questo è il secondo webinar della serie Back to Basics che ti offrirà un'introduzione al database MongoDB. In questo webinar ti dimostreremo come creare un'applicazione base per il blogging in MongoDB.
Conceptos básicos. Seminario web 2: Su primera aplicación MongoDBMongoDB
Este es el segundo seminario web de la serie Conceptos básicos, en la que se realiza una introducción a la base de datos MongoDB. En este seminario web mostraremos cómo construir una aplicación de creación de blogs en MongoDB.
The Ring programming language version 1.5.3 book - Part 15 of 184Mahmoud Samir Fayed
- Obtain Ring source code from GitHub and install dependencies
- Build Ring compiler/VM and extensions like RingODBC, RingMySQL, etc.
- Generate source code for extensions like RingAllegro, RingQt using code generators
- Build generated extension source code
- Install Ring binaries to make ring command available from any directory
The Ring programming language version 1.7 book - Part 48 of 196Mahmoud Samir Fayed
This document provides code examples and documentation for Ring's web library (weblib.ring). It describes classes and methods for generating HTML pages, forms, tables and other elements. This includes the Page class for adding common elements like text, headings, paragraphs etc., the Application class for handling requests, cookies and encoding, and classes representing various HTML elements like forms, inputs, images etc. It also provides an overview of how to create pages dynamically using View and Controller classes along with Model classes for database access.
QA Fes 2016. Ярослав Пернеровский. Не Jav'ой единой. Пример автоматизации тес...QAFest
Традиционно, на проектах где back-end писан на Java, фреймворк тестирования тоже строится на технологиях Java. С одной стороны это оправдано единообразием и уже готовым тулсетом у разработчиков. Но с другой стороны немного усложняет вход в автоматизацию для тестировщиков, не знакомых с тонкостями Java. Новичкам, конечно, можно посоветовать более простые для понимания варианты написания тестов на Ruby или Python, но это уже совсем другой мир, и совсем другой геморрой для DevOps. Очень неплохим вариантом в такой ситуации мне видится использование языка программирования Groovy в паре с тест фреймворком Spock. Эта связка позволяет писать понятные REST API тесты на базе уже существующей Java инфраструктуры.
В докладе на примерах посмотрим как это сделать и попытаемся для себя понять есть ли у такого подхода будущее или это просто баловство для ленивых.
This document provides tips for advanced testing practices. Some key tips mentioned include:
1. Give test names that indicate intention rather than just describing the code under test.
2. Remove unnecessary information from tests like setup/teardown methods to focus on the essential behavior.
3. Avoid reflection in tests and test private methods directly when possible.
4. Use frameworks like Spock that allow testing multiple scenarios in a single test through the use of tables.
The Ring programming language version 1.8 book - Part 74 of 202Mahmoud Samir Fayed
This document describes a Ring-based notepad application with the following key features:
- It includes buttons and menu options for common file operations like new, open, save, print.
- The interface contains a toolbar and main window for the text editor area.
- Additional features allow for text formatting, search/replace, and setting the font and colors.
- The application stores the open file name and can check if the user wants to save changes when closing.
Каждый день появляется по новому JavaScript фрeймворку или новой технологии. И каждый день мы задаемся вопросом, как за всем этим успеть? Константин даст Вам серебряную пулю. Вы будете знать, как быстро разобраться в React, PostCss, RxJS, Redux, CycleJs, Angular и даже в неизвестном супер фреймворке. Увидим, что стоит за трендами технологий 2016.
Подробнее: https://mavrin.github.io/pres-be-first/#1
The Ring programming language version 1.5 book - Part 8 of 31Mahmoud Samir Fayed
This document summarizes key classes and methods from the Ring web library (weblib.ring).
The Application class contains methods for encoding, decoding, cookies, and more. The Page class contains methods for generating common HTML elements and structures. Model classes like UsersModel manage data access and object relational mapping. Controller classes handle requests and coordinate the view and model.
This document discusses using a multi-model database like ArangoDB for microservices. It explains how ArangoDB can store different data models like key-value, documents, and graphs to support microservices that use different data structures. It provides examples of breaking up a monolithic application into microservices that use different parts of the database, and using Foxx to build REST APIs on top of ArangoDB to integrate microservices.
The Ring programming language version 1.6 book - Part 70 of 189Mahmoud Samir Fayed
This document describes a simple notepad application developed using the RingQt GUI library. The application contains menus, toolbars and dockable panels for file navigation, text editing and web browsing. Functions are defined to open, save and print files, cut/copy/paste text, set font/color and find/replace text. The file tree loads files from the file system and updates the text editor on selection. The status of unsaved changes is tracked and settings are restored on startup.
The Ring programming language version 1.7 book - Part 72 of 196Mahmoud Samir Fayed
This document describes a Ring-based notepad application with the following key features:
- It allows opening, saving, printing files and includes buttons for common editing functions like cut, copy, paste.
- The interface contains toolbars for file operations and menus for File, Edit, View, Help options. Shortcuts are also defined.
- Text editing functions like font selection, text coloring, search/replace are implemented through event handlers.
- The application stores settings like active file name, text/background colors, font and handles asking to save on close if needed.
This document discusses the different types of statements used in QuickTest Professional (QTP) test scripts, including declarations, comments, utility statements, object calls, flow control statements, function/action calls, checkpoints, output value statements, synchronization points, and VBScript statements. Declarations are used to define variables and constants. Comments explain parts of the test script. Utility statements launch applications and control program flow. Object calls interact with application objects. Flow control statements include if/else, select case, loops, and more. Functions and actions encapsulate reusable code. Checkpoints and output values verify test results. Synchronization waits ensure objects are ready. VBScript provides additional programming constructs.
The Ring programming language version 1.8 book - Part 49 of 202Mahmoud Samir Fayed
The document provides code examples of using Bootstrap classes and components to create buttons and modal dialog boxes in HTML. It defines CSS classes for different columns, button groups, and modal elements. Buttons are created with classname, text, and other attributes. The modal dialog box contains header, body, and footer sections with close buttons and content text. Screenshots are included of the rendered output.
The Ring programming language version 1.5.1 book - Part 64 of 180Mahmoud Samir Fayed
This document describes a simple notepad application developed using the RingQt GUI library. The application contains menus, toolbars and dockable panels for file navigation, text editing and web browsing. It allows opening, saving and printing text files, and includes features like font selection, text coloring and find/replace. The file tree and text editor are implemented using QTreeView and QTextEdit widgets, while a QWebView is used for the embedded web browser. Various signals and slots are used to handle user interactions and update the UI.
Back to Basics Webinar 2 - Your First MongoDB ApplicationJoe Drumgoole
How to build a MongoDB application from scratch in the MongoDB Shell and Python. How to add indexes and use explain to make sure you are using them properly.
Back to Basics Webinar 2: Your First MongoDB ApplicationMongoDB
The document provides instructions for installing and using MongoDB to build a simple blogging application. It demonstrates how to install MongoDB, connect to it using the mongo shell, insert and query sample data like users and blog posts, update documents to add comments, and more. The goal is to illustrate how to model and interact with data in MongoDB for a basic blogging use case.
C++ CoreHard Autumn 2018. Создание пакетов для открытых библиотек через conan...corehard_by
Использование сторонних библиотек в языке C++ никогда не было простым - необходимо было правильно собрать их, имея дело с различными системами сборки, но с появлением пакетного менеджера conan.io процесс стал намного проще, так что теперь осталось только сделать пакеты для нужным библиотек, и в этом поможет команда bincrafter-ов.
C++ CoreHard Autumn 2018. Actors vs CSP vs Tasks vs ... - Евгений Охотниковcorehard_by
На предыдущих конференциях C++ CoreHard автор доклада рассказывал про Модель Акторов и опыт ее использования в C++. Но Модель Акторов -- это далеко не единственный способ борьбы со сложностью при работе с многопоточностью. Давайте попробуем поговорить о том, что еще можно применить и как это может выглядеть в C++.
C++ CoreHard Autumn 2018. Знай свое "железо": иерархия памяти - Александр Титовcorehard_by
Если вам важна скорость работы ваших программ, то вы обязаны понимать, как работает ваше "железо". Современный процессор -- это сложное устройство, многие механизмы которого могут неочевидным образом влиять на скорость исполнения вашего кода. В докладе дается обзорное представление основных структур современного процессора и подробно рассматривается работа иерархии памяти. Будут освещены следующие темы: организация кэш-памяти, принцип локальности, предподкачка данных, нежелательное общее владение данными, а также программные техники для эффективной работы с памятью.
C++ CoreHard Autumn 2018. Информационная безопасность и разработка ПО - Евген...corehard_by
Информационная безопасность все больше из отдельной сферы плавно перетекает в разработку ПО. А значит «обычным» программистам приходится понимать те требования и терминологию, которые специалисты по безопасности уже давно знают и используют. CWE, CERT, MISRA, SAST– для «обычных» программистов это непонятные аббревиатуры. Поэтому в обзорном докладе мы попробуем рассказать простым языком об этих понятиях так, чтобы все разработчики начали уверенно ориентироваться в этой теме.
C++ CoreHard Autumn 2018. Заглядываем под капот «Поясов по C++» - Илья Шишковcorehard_by
Вот уже более двух лет мы создаём онлайн-специализацию по С++ на платформе Coursera. Её цель — обучить языку C++ с нуля до уровня, достаточного для решения практических задач, с которыми приходилось сталкиваться авторам в своей практике. В своём докладе я расскажу, как мы создаём наши онлайн-курсы, и уделю особое внимание техническим проблемам, которые нам пришлось решить в процессе создания автоматической системы проверки программ студентов.
C++ CoreHard Autumn 2018. Ускорение сборки C++ проектов, способы и последстви...corehard_by
В докладе обсуждаются способы улучшения времени сборки C++ проектов, опыт полученный в ходе ускорения сборки клиента и тулов World Of Tanks. Также описывается эффект, который они оказывают на организацию кодобазы (как позитивный, так и негативный) и затраты, которые необходимы для поддержки этих решений, т.к. не все они бесплатны. Методики, описываемые в докладе: ускорение линковки (Incremental Linking, Fastlink), ускорение компиляции(Include what you use, использование precompiled headers).
C++ CoreHard Autumn 2018. Метаклассы: воплощаем мечты в реальность - Сергей С...corehard_by
Доклад посвящён вопросам реализации пропозала Герба Саттера PR0707 (метаклассы в С++) за пределами компилятор - в виде отдельной утилиты. Будет продемонстрированы варианты использования метаклассов в реальной жизни, затронуты вопросы их реализации на базе Clang Frontend, а также возможные перспективы развития технологии и методики.
C++ CoreHard Autumn 2018. Что не умеет оптимизировать компилятор - Александр ...corehard_by
Все мы знаем, что компиляторы в настоящее время достаточно умные. И нам как программистам зачастую не нужно думать о каких-то незначительных оптимизациях - мы полагаемся на оптимизации компилятора. Что ж, настало время выяснить, действительно ли настолько компиляторы умны и узнать, в каких местах программист всё же (может быть) умнее.
C++ CoreHard Autumn 2018. Кодогенерация C++ кроссплатформенно. Продолжение - ...corehard_by
В докладе будет рассмотрена генерация кода при компиляции различных языковых конструкций, как простых, так и сложных, на различных платформах, как общераспространённых x86/x64, так и тех, которым уделяется меньше внимания: ARM, AVR. Также будут встречаться примеры для совсем экзотических процессоров вроде PowerPC и даже MicroBlaze. Основной упор будет делаться не на обработку данных, а именно на сопоставление различных конструкций кода с инструкциями целевых платформ.
C++ CoreHard Autumn 2018. Concurrency and Parallelism in C++17 and C++20/23 -...corehard_by
What do threads, atomic variables, mutexes, and conditional variables have in common? They are the basic building blocks of any concurrent application in C++, which are even for the experienced C++ programmers a big challenge. This massively changed with C++17 and change even more with C++20/23. What did we get with C++17, what can we hope for with C++20/23? With C++17, most of the standard template library algorithms are available in sequential, parallel, and vectorised variants. With the upcoming standards, we can look forward to executors, transactional memory, significantly improved futures and coroutines. To make it short. These are just the highlights from the concurrent and parallel perspective. Thus there is the hope that in the future C++ abstractions such as executors, transactional memory, futures and coroutines are used and that threads, atomic variables, mutexes and condition variables are just implementation details.
C++ CoreHard Autumn 2018. Обработка списков на C++ в функциональном стиле - В...corehard_by
Язык C++, претерпев долгую эволюцию, обрёл ряд черт, характерных для функциональной парадигмы: функции стали полноправными объектами, над которыми могут выполняться операции, а аппарат шаблонов позволяет проводить вычисления на типах на этапе компиляции. Математический фундамент этих двух главных аспектов составляют, соответственно, ламбда-исчисление и теория категорий. Расширение языка этими средствами способствовало реализации на языке C++ ряда инструментов, известных из функционального программирования. Некоторые из этих реализаций вошли в стандартную библиотеку (std::function, std::bind), другие - в сторонние библиотеки, в том числе в коллекцию библиотек Boost (functional, hana). Важную роль в арсенале функционального программирования играют операции свёртки и развёртки, которые очевиднее всего определяются для списков, но также естественным образом обобщаются на другие индуктивные и коиндуктивные структуры данных. Например, суммирование списка чисел можно представить себе как свёртку списка по операции сложения, а построение списка простых множителей заданного целого числа - как развёртку. Обобщения свёртки и развёртки известны как анаморфизмы и катаморфизмы. Также в функциональном программировании находит применение понятие гиломорфизма - композиция развёртки некоторого объекта в коллекцию с последующей свёрткой её в новый объект. В докладе продемонстрировано, что свёртки, развёртки и их композиции допускают довольно простую реализацию на языке C++.
C++ Corehard Autumn 2018. Обучаем на Python, применяем на C++ - Павел Филоновcorehard_by
Доклад посвящен часто используемому шаблону в моих проектах по анализу данных, когда обучение и настройка моделей происходят с использованием python, а вот их запуск в промышленное использование на языке C++. Предлагается рассмотреть несколько учебных примеров реализации такого подхода, от простой линейной регрессии до обработки изображений с помощью нейронных сетей.
C++ CoreHard Autumn 2018. Asynchronous programming with ranges - Ivan Čukićcorehard_by
This talk will be about the design and implementation of a reactive programming model inspired by ranges that allows easy implementation of asynchronous and distributed software systems by writing code that looks like a sequence of ordinary range transformations like filter, transform, etc. This programming model will be demonstrated along with the implementation of a simple asynchronous web service where the whole system logic is defined as a chain of range transformations.
C++ CoreHard Autumn 2018. Debug C++ Without Running - Anastasia Kazakovacorehard_by
The document discusses how an IDE can help debug tricky C++ code without running it by leveraging tools to understand macros, types, templates, and overloads. It describes how an IDE could show the step-by-step substitution of macros, substitute typedefs one step at a time, debug template instantiations and constant expressions, explain overload resolution, and profile includes to optimize header usage. The presenter argues that tools are needed to make powerful C++ abstractions more accessible.
C++ CoreHard Autumn 2018. Полезный constexpr - Антон Полухинcorehard_by
В C++11 добавили новое ключевое слово - constexpr. Выглядит оно весьма невзрачно, да и на первый взгляд кажется, что смысла в нём маловато... Для чего же оно нужно, какие у него есть тайные супер способности и какую роль оно сыграет в дальнейшем развитии языка C++ - обо всём об этом мы и поговорим.
C++ CoreHard Autumn 2018. Text Formatting For a Future Range-Based Standard L...corehard_by
This document discusses range-based text formatting and proposes replacing existing approaches with a range-based solution. It suggests representing text as ranges and using range algorithms and functions for concatenation and formatting. This would allow treating different string types uniformly and flexibly while avoiding issues with current formatting methods like iostream manipulation and format strings. The document provides examples of formatting numbers and dates as ranges and constructing containers like std::string from multiple ranges.
Исключительная модель памяти. Алексей Ткаченко ➠ CoreHard Autumn 2019corehard_by
Память в компьютере - это не только гигабайты оперативной памяти в слоте, но и занятная абстракция. В докладе мы рассмотрим, как можно эту абстракцию использовать необычным образом для моделирования других абстракций - регистровых файлов периферийных устройств. Доклад будет полезен не только embedded-разработчикам, но и, возможно, заставит переосмыслить свой взгляд на память.
Как помочь и как помешать компилятору. Андрей Олейников ➠ CoreHard Autumn 2019corehard_by
Как правило, можно положиться на то, что компилятор оптимизирует результирующий бинарный файл так, чтобы она работала максимально быстро. Но компилятор не знает на каких данных и на каком железе программа будет запущена. Плюс хотелось бы, чтобы компиляция занимала приемлемое время. Из-за этого результат может оказаться субоптимальным. Предлагаю на примерах для LLVM посмотреть как можно подсказать компилятору как оптимизировать программу и сделать результат лучше или хуже.
Мы напишем простейший веб-сервис из клиента и сервера на C++. На этом C++ часть закончится, и пойдет настройка окружения и инфраструктуры. Мы обеспечим детерминируемость сборки и прогона тестов. Облегчим последующее обновление зависимых библиотек. Автоматизируем статические проверки, верификацию кода, прогон тестов. Обеспечим доступность сервиса, настроим инфраструктуру, сбалансируем нагрузку, добавим автоматическое и ручное масштабирование. И под конец мы настроим continious delivery таким образом, что код будет на продакшене через 5 минут после реквеста, при этом даже невалидные изменения и ошибки программиста не смогут повлиять на его работу.
Your One-Stop Shop for Python Success: Top 10 US Python Development Providersakankshawande
Simplify your search for a reliable Python development partner! This list presents the top 10 trusted US providers offering comprehensive Python development services, ensuring your project's success from conception to completion.
Driving Business Innovation: Latest Generative AI Advancements & Success StorySafe Software
Are you ready to revolutionize how you handle data? Join us for a webinar where we’ll bring you up to speed with the latest advancements in Generative AI technology and discover how leveraging FME with tools from giants like Google Gemini, Amazon, and Microsoft OpenAI can supercharge your workflow efficiency.
During the hour, we’ll take you through:
Guest Speaker Segment with Hannah Barrington: Dive into the world of dynamic real estate marketing with Hannah, the Marketing Manager at Workspace Group. Hear firsthand how their team generates engaging descriptions for thousands of office units by integrating diverse data sources—from PDF floorplans to web pages—using FME transformers, like OpenAIVisionConnector and AnthropicVisionConnector. This use case will show you how GenAI can streamline content creation for marketing across the board.
Ollama Use Case: Learn how Scenario Specialist Dmitri Bagh has utilized Ollama within FME to input data, create custom models, and enhance security protocols. This segment will include demos to illustrate the full capabilities of FME in AI-driven processes.
Custom AI Models: Discover how to leverage FME to build personalized AI models using your data. Whether it’s populating a model with local data for added security or integrating public AI tools, find out how FME facilitates a versatile and secure approach to AI.
We’ll wrap up with a live Q&A session where you can engage with our experts on your specific use cases, and learn more about optimizing your data workflows with AI.
This webinar is ideal for professionals seeking to harness the power of AI within their data management systems while ensuring high levels of customization and security. Whether you're a novice or an expert, gain actionable insights and strategies to elevate your data processes. Join us to see how FME and AI can revolutionize how you work with data!
A Comprehensive Guide to DeFi Development Services in 2024Intelisync
DeFi represents a paradigm shift in the financial industry. Instead of relying on traditional, centralized institutions like banks, DeFi leverages blockchain technology to create a decentralized network of financial services. This means that financial transactions can occur directly between parties, without intermediaries, using smart contracts on platforms like Ethereum.
In 2024, we are witnessing an explosion of new DeFi projects and protocols, each pushing the boundaries of what’s possible in finance.
In summary, DeFi in 2024 is not just a trend; it’s a revolution that democratizes finance, enhances security and transparency, and fosters continuous innovation. As we proceed through this presentation, we'll explore the various components and services of DeFi in detail, shedding light on how they are transforming the financial landscape.
At Intelisync, we specialize in providing comprehensive DeFi development services tailored to meet the unique needs of our clients. From smart contract development to dApp creation and security audits, we ensure that your DeFi project is built with innovation, security, and scalability in mind. Trust Intelisync to guide you through the intricate landscape of decentralized finance and unlock the full potential of blockchain technology.
Ready to take your DeFi project to the next level? Partner with Intelisync for expert DeFi development services today!
In the rapidly evolving landscape of technologies, XML continues to play a vital role in structuring, storing, and transporting data across diverse systems. The recent advancements in artificial intelligence (AI) present new methodologies for enhancing XML development workflows, introducing efficiency, automation, and intelligent capabilities. This presentation will outline the scope and perspective of utilizing AI in XML development. The potential benefits and the possible pitfalls will be highlighted, providing a balanced view of the subject.
We will explore the capabilities of AI in understanding XML markup languages and autonomously creating structured XML content. Additionally, we will examine the capacity of AI to enrich plain text with appropriate XML markup. Practical examples and methodological guidelines will be provided to elucidate how AI can be effectively prompted to interpret and generate accurate XML markup.
Further emphasis will be placed on the role of AI in developing XSLT, or schemas such as XSD and Schematron. We will address the techniques and strategies adopted to create prompts for generating code, explaining code, or refactoring the code, and the results achieved.
The discussion will extend to how AI can be used to transform XML content. In particular, the focus will be on the use of AI XPath extension functions in XSLT, Schematron, Schematron Quick Fixes, or for XML content refactoring.
The presentation aims to deliver a comprehensive overview of AI usage in XML development, providing attendees with the necessary knowledge to make informed decisions. Whether you’re at the early stages of adopting AI or considering integrating it in advanced XML development, this presentation will cover all levels of expertise.
By highlighting the potential advantages and challenges of integrating AI with XML development tools and languages, the presentation seeks to inspire thoughtful conversation around the future of XML development. We’ll not only delve into the technical aspects of AI-powered XML development but also discuss practical implications and possible future directions.
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfChart Kalyan
A Mix Chart displays historical data of numbers in a graphical or tabular form. The Kalyan Rajdhani Mix Chart specifically shows the results of a sequence of numbers over different periods.
Monitoring and Managing Anomaly Detection on OpenShift.pdfTosin Akinosho
Monitoring and Managing Anomaly Detection on OpenShift
Overview
Dive into the world of anomaly detection on edge devices with our comprehensive hands-on tutorial. This SlideShare presentation will guide you through the entire process, from data collection and model training to edge deployment and real-time monitoring. Perfect for those looking to implement robust anomaly detection systems on resource-constrained IoT/edge devices.
Key Topics Covered
1. Introduction to Anomaly Detection
- Understand the fundamentals of anomaly detection and its importance in identifying unusual behavior or failures in systems.
2. Understanding Edge (IoT)
- Learn about edge computing and IoT, and how they enable real-time data processing and decision-making at the source.
3. What is ArgoCD?
- Discover ArgoCD, a declarative, GitOps continuous delivery tool for Kubernetes, and its role in deploying applications on edge devices.
4. Deployment Using ArgoCD for Edge Devices
- Step-by-step guide on deploying anomaly detection models on edge devices using ArgoCD.
5. Introduction to Apache Kafka and S3
- Explore Apache Kafka for real-time data streaming and Amazon S3 for scalable storage solutions.
6. Viewing Kafka Messages in the Data Lake
- Learn how to view and analyze Kafka messages stored in a data lake for better insights.
7. What is Prometheus?
- Get to know Prometheus, an open-source monitoring and alerting toolkit, and its application in monitoring edge devices.
8. Monitoring Application Metrics with Prometheus
- Detailed instructions on setting up Prometheus to monitor the performance and health of your anomaly detection system.
9. What is Camel K?
- Introduction to Camel K, a lightweight integration framework built on Apache Camel, designed for Kubernetes.
10. Configuring Camel K Integrations for Data Pipelines
- Learn how to configure Camel K for seamless data pipeline integrations in your anomaly detection workflow.
11. What is a Jupyter Notebook?
- Overview of Jupyter Notebooks, an open-source web application for creating and sharing documents with live code, equations, visualizations, and narrative text.
12. Jupyter Notebooks with Code Examples
- Hands-on examples and code snippets in Jupyter Notebooks to help you implement and test anomaly detection models.
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
Ivanti’s Patch Tuesday breakdown goes beyond patching your applications and brings you the intelligence and guidance needed to prioritize where to focus your attention first. Catch early analysis on our Ivanti blog, then join industry expert Chris Goettl for the Patch Tuesday Webinar Event. There we’ll do a deep dive into each of the bulletins and give guidance on the risks associated with the newly-identified vulnerabilities.
Skybuffer AI: Advanced Conversational and Generative AI Solution on SAP Busin...Tatiana Kojar
Skybuffer AI, built on the robust SAP Business Technology Platform (SAP BTP), is the latest and most advanced version of our AI development, reaffirming our commitment to delivering top-tier AI solutions. Skybuffer AI harnesses all the innovative capabilities of the SAP BTP in the AI domain, from Conversational AI to cutting-edge Generative AI and Retrieval-Augmented Generation (RAG). It also helps SAP customers safeguard their investments into SAP Conversational AI and ensure a seamless, one-click transition to SAP Business AI.
With Skybuffer AI, various AI models can be integrated into a single communication channel such as Microsoft Teams. This integration empowers business users with insights drawn from SAP backend systems, enterprise documents, and the expansive knowledge of Generative AI. And the best part of it is that it is all managed through our intuitive no-code Action Server interface, requiring no extensive coding knowledge and making the advanced AI accessible to more users.
3. "Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 3
С++17
С++11/14
С++98
С
High level
Expert level
Modern C++
4. “Within C++ is a smaller, simpler, safer
language struggling to get out”
Bjarne Stroustrup
"Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 4
5. High level:
Парадигма RAII и исключения (exceptions)
Алгоритмы и контейнеры STL и boost
Семантика перемещения
λ-функции
Классы и конструкторы
Простые шаблоны
"Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 5
Expert level:
Операторы new/delete, владеющие
указатели
Пользовательские операции копирования
и перемещения
Пользовательские деструкторы
Закрытое, защищённое, ромбовидное,
виртуальное наследование
Шаблонная магия, SFINAE
Все функции языка Си, препроцессор
«Голые» циклы
Классический слайд с телом и заголовком
6. "Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 6
bool doCompare(const Bakery* oldBakery, const Bakery* newBakery)
{
if (!oldBakery || !newBakery)
{
return false;
}
std::vector<Cookie> oldCookies;
std::vector<Cookie> newCookies;
std::vector<std::pair<Cookie, int>> diff;
collectCookies(*oldBakery, oldCookies);
collectCookies(*newBakery, newCookies);
std::sort(oldCookies.begin(), oldCookies.end(), compareCookies);
std::sort(newCookies.begin(), newCookies.end(), compareCookies);
auto oldIt = oldCookies.begin();
auto newIt = newCookies.begin();
while ((oldIt != oldCookies.end()) || (newIt != newCookies.end()))
7. "Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 7
bool doCompare(const Bakery* oldBakery, const Bakery* newBakery)
{
if (!oldBakery || !newBakery)
{
return false;
}
std::vector<Cookie> oldCookies;
std::vector<Cookie> newCookies;
std::vector<std::pair<Cookie, int>> diff;
collectCookies(*oldBakery, oldCookies);
collectCookies(*newBakery, newCookies);
std::sort(oldCookies.begin(), oldCookies.end(), compareCookies);
std::sort(newCookies.begin(), newCookies.end(), compareCookies);
auto oldIt = oldCookies.begin();
auto newIt = newCookies.begin();
while ((oldIt != oldCookies.end()) || (newIt != newCookies.end()))
{
if (compareCookies(*oldIt, *newIt))
{
diff.push_back(std::pair<Cookie, int>(*oldIt, 1));
++oldIt;
}
else if (compareCookies(*newIt, *oldIt))
{
diff.push_back(std::pair<Cookie, int>(*newIt, 2));
++newIt;
}
else
{
++oldIt;
++newIt;
}
}
if (oldIt != oldCookies.end())
{
for (; oldIt < oldCookies.end(); oldIt++)
{
diff.push_back(std::pair<Cookie, int>(*oldIt, 1));
}
}
if (newIt != newCookies.end())
{
for (; newIt < newCookies.end(); newIt++)
{
diff.push_back(std::pair<Cookie, int>(*newIt, 2));
}
}
for (const auto& item : diff)
{
std::cout << "Bakery #" << item.second <<
" has a different cookie "" << item.first.name <<
"" (weight=" << item.first.weight <<
", volume=" << item.first.volume <<
", tastiness=" << item.first.tastiness << ")." << std::endl;
}
if (diff.size() > 0)
return false;
return true;
}
bool doCompare(const Bakery& oldBakery, const Bakery& newBakery)
{
auto oldCookies = collectSortedCookies(oldBakery);
auto newCookies = collectSortedCookies(newBakery);
auto reportLost = [](const Cookie& cookie) {
std::cout << "We've lost a friend: " << cookie << "." << std::endl;
};
auto reportAppeared = [](const Cookie& cookie) {
std::cout << "We got a new friend: " << cookie << "." << std::endl;
};
boost::range::set_difference(oldCookies, newCookies,
boost::make_function_output_iterator(reportLost));
boost::range::set_difference(newCookies, oldCookies,
boost::make_function_output_iterator(reportAppeared));
return oldCookies == newCookies;
}
42. "Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 42
std::vector<Cookie> lostCookies;
std::set_difference(oldCookies.begin(), oldCookies.end(),
newCookies.begin(), newCookies.end(),
std::back_inserter(lostCookies));
std::vector<Cookie> appearedCookies;
std::set_difference(newCookies.begin(), newCookies.end(),
oldCookies.begin(), oldCookies.end(),
std::back_inserter(appearedCookies));
43. "Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 43
std::vector<Cookie> lostCookies;
boost::range::set_difference(oldCookies, newCookies,
std::back_inserter(lostCookies));
std::vector<Cookie> appearedCookies;
boost::range::set_difference(newCookies, oldCookies,
std::back_inserter(appearedCookies));
44. "Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 44
std::vector<Cookie> lostCookies;
boost::range::set_difference(oldCookies, newCookies,
std::back_inserter(lostCookies));
std::vector<Cookie> appearedCookies;
boost::range::set_difference(newCookies, oldCookies,
std::back_inserter(appearedCookies));
for (const auto& cookie : lostCookies)
{
std::cout << "We've lost a friend: " << cookie << "." << std::endl;
}
for (const auto& cookie : appearedCookies)
{
std::cout << "We got a new friend: " << cookie << "." << std::endl;
}
45. "Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 45
auto reportLost = [](const Cookie& cookie) {
std::cout << "We've lost a friend: " << cookie << "." << std::endl;
};
auto reportAppeared = [](const Cookie& cookie) {
std::cout << "We got a new friend: " << cookie << "." << std::endl;
};
boost::range::set_difference(oldCookies, newCookies,
boost::make_function_output_iterator(reportLost));
boost::range::set_difference(newCookies, oldCookies,
boost::make_function_output_iterator(reportAppeared));
46. "Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 46
bool doCompare(const Bakery& oldBakery, const Bakery& newBakery)
{
std::vector<Cookie> oldCookies = collectSortedCookies(oldBakery);
std::vector<Cookie> newCookies = collectSortedCookies(newBakery);
auto reportLost = [](const Cookie& cookie) {
std::cout << "We've lost a friend: " << cookie << "." << std::endl;
};
auto reportAppeared = [](const Cookie& cookie) {
std::cout << "We got a new friend: " << cookie << "." << std::endl;
};
boost::range::set_difference(oldCookies, newCookies,
boost::make_function_output_iterator(reportLost));
boost::range::set_difference(newCookies, oldCookies,
boost::make_function_output_iterator(reportAppeared));
return oldCookies == newCookies;
}
47. "Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 47
bool doCompare(const Bakery& oldBakery, const Bakery& newBakery)
{
auto oldCookies = collectSortedCookies(oldBakery);
auto newCookies = collectSortedCookies(newBakery);
auto reportLost = [](const Cookie& cookie) {
std::cout << "We've lost a friend: " << cookie << "." << std::endl;
};
auto reportAppeared = [](const Cookie& cookie) {
std::cout << "We got a new friend: " << cookie << "." << std::endl;
};
boost::range::set_difference(oldCookies, newCookies,
boost::make_function_output_iterator(reportLost));
boost::range::set_difference(newCookies, oldCookies,
boost::make_function_output_iterator(reportAppeared));
return oldCookies == newCookies;
}
48. "Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 48
bool doCompare(const Bakery* oldBakery, const Bakery* newBakery)
{
if (!oldBakery || !newBakery)
{
return false;
}
std::vector<Cookie> oldCookies;
std::vector<Cookie> newCookies;
std::vector<std::pair<Cookie, int>> diff;
collectCookies(*oldBakery, oldCookies);
collectCookies(*newBakery, newCookies);
std::sort(oldCookies.begin(), oldCookies.end(), compareCookies);
std::sort(newCookies.begin(), newCookies.end(), compareCookies);
auto oldIt = oldCookies.begin();
auto newIt = newCookies.begin();
while ((oldIt != oldCookies.end()) || (newIt != newCookies.end()))
{
if (compareCookies(*oldIt, *newIt))
{
diff.push_back(std::pair<Cookie, int>(*oldIt, 1));
++oldIt;
}
else if (compareCookies(*newIt, *oldIt))
{
diff.push_back(std::pair<Cookie, int>(*newIt, 2));
++newIt;
}
else
{
++oldIt;
++newIt;
}
}
if (oldIt != oldCookies.end())
{
for (; oldIt < oldCookies.end(); oldIt++)
{
diff.push_back(std::pair<Cookie, int>(*oldIt, 1));
}
}
if (newIt != newCookies.end())
{
for (; newIt < newCookies.end(); newIt++)
{
diff.push_back(std::pair<Cookie, int>(*newIt, 2));
}
}
for (const auto& item : diff)
{
std::cout << "Bakery #" << item.second <<
" has a different cookie "" << item.first.name <<
"" (weight=" << item.first.weight <<
", volume=" << item.first.volume <<
", tastiness=" << item.first.tastiness << ")." << std::endl;
}
if (diff.size() > 0)
return false;
return true;
}
bool doCompare(const Bakery& oldBakery, const Bakery& newBakery)
{
auto oldCookies = collectSortedCookies(oldBakery);
auto newCookies = collectSortedCookies(newBakery);
auto reportLost = [](const Cookie& cookie) {
std::cout << "We've lost a friend: " << cookie << "." << std::endl;
};
auto reportAppeared = [](const Cookie& cookie) {
std::cout << "We got a new friend: " << cookie << "." << std::endl;
};
boost::range::set_difference(oldCookies, newCookies,
boost::make_function_output_iterator(reportLost));
boost::range::set_difference(newCookies, oldCookies,
boost::make_function_output_iterator(reportAppeared));
return oldCookies == newCookies;
}
49. Код, использующий стандартные алгоритмы и контейнеры:
Короче
Проще
Надёжнее
Обычно эффективнее
Проще переиспользовать
Не привязан к конкретной платформе
"Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 49
50. И ещё немного
по теме…
"Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 50
51. "Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 51
struct Cookie
{
double weight;
double volume;
std::string name;
int tastiness;
auto rank() const
{
return std::tie(tastiness, weight, volume, name);
}
};
52. "Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 52
struct Cookie
{
double weight;
double volume;
std::string name;
int tastiness;
double density() const
{
return weight / volume;
}
auto rank() const
{
return std::tie(tastiness, density(), name); // Any problems here?..
}
};
53. "Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 53
struct Cookie
{
double weight;
double volume;
std::string name;
int tastiness;
double density() const
{
return weight / volume;
}
auto rank() const
{
return std::make_tuple(tastiness, density(), std::ref(name));
}
};
54. "Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 54
struct Cookie
{
double weight;
double volume;
std::string name;
int tastiness;
double density() const
{
return weight / volume;
}
auto rank() const // -> std::tuple<int, double, const std::string&>
{
return std::make_tuple(tastiness, density(), std::ref(name));
}
};
55. "Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 55
auto f = [](/* ... */) { /* ... */ };
boost::make_function_output_iterator(f) ->
boost::iterators::function_output_iterator<LambdaAnonymousType>
template <class UnaryFunction>
class function_output_iterator {
// ...
UnaryFunction m_f;
};
auto it1 = boost::make_function_output_iterator(f); // Not assignable
auto it2 = boost::make_function_output_iterator(std::ref(f)); // Assignable
56. Советы:
Мыслите на высоком уровне
Код должен ясно выражать намерение
Знайте свои инструменты и используйте их к месту
"Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016 56
// references
// auto variables
// auto function return type
// move semantics
// lambda functions
operator<();
std::make_tuple();
std::tie();
std::ref();
std::make_pair();
std::vector<T>::emplace_back();
std::vector<T>::empty();
operator<<();
std::back_inserter();
std::set_difference();
boost::range::set_difference();
boost::make_function_output_iterator();
57. Мыслите на высоком уровне
Код должен ясно выражать намерение
Знайте свои инструменты и используйте их к месту
"Повседневный С++: boost и STL", Михаил Матросов, CoreHard C++ Conf 2016
std::make_pair();
std::vector<T>::emplace_back();
std::vector<T>::empty();
operator<<();
std::back_inserter();
std::set_difference();
boost::range::set_difference();
boost::make_function_output_iterator();
Спасибо за внимание!
// references
// auto variables
// auto function return type
// move semantics
// lambda functions
operator<();
std::make_tuple();
std::tie();
std::ref();
57
Editor's Notes
Образ С++
По поводу фичей, взятых из boost: http://stackoverflow.com/q/8851670/261217
Исходный текст функции.
Цель
Посмотрим на указатели
Используем ссылки
Посмотрим на вызов collectCookies
Убедимся, что он инициализирует вектор печенек
Будем передавать его по значению
Посмотрим на два вызова std::sort
Посмотрим на два вызова std::sort
Устраним дублирование: уберём std::sort в collectCookies. Для наглядности переименуем его в collectSortedCookies.
Посмотрим на функцию compareCookies
Посмотрим на прототип функции compareCookies
Используем operator<. Никто не будет сравнивать значения с помощью вызова функции. Ну, если вы не пишете на Java.
Вернёмся к коду основной функции
Используем прямое сравнение
Вернёмся к оператору сравнения
Используем std::tuple для лексикографического сравнения
Посмотрим ещё раз на сам тип Cookie
Используем std::tie, чтобы не копировать std::string лишний раз
Кроме того, посмотрим по дублирование списка членов
Используем функцию rank(), чтобы не дублировать список членов
Добавим комментарий с явным типом возвращаемого значения
Объявим operator== по аналогии
Посмотрим на явный конструктор std::pair
Используем std::make_pair
Используем emplace_back()
Посмотрим на цикл вывода
Добавим оператора вывода в поток для печеньки
Посмотрим на конструкцию вывода
Заменим на эквивалентный вызов empty()
Начинаем догадываться, что всё это значит. По этому поводу пишем юнит-тесты. Находим баг.
Используем готовый алгоритм. Потом обращаем внимание, что неудобно писать много раз begin()/end().
Используем аналог из boost::range
Добавляем код с выводом. Свой вывод для пропавших и появившихся печенек. Понимаем, что вывод – это всё, что нам нужно.
Убираем промежуточный вектор хранения.
ToDo: тут непонятно, что куда переехало
Почти финальная форма. Понимаем, что нам не важно, вектор мы используем или что-то ещё.
Финальная форма! Нет привязки к конкретному типу последовательности.
Цель достигнута!
Сейчас ещё чуть-чуть кода и котик, чтобы вы не расстраивались.
Небольшой бонус относительно std::tie и std::make_tuple. Вспомним определение метода rank().
Что если в вычислении ранка будут участвовать не только поля класса? Код просто не скомпилируется.
Придётся вернуться к make_tuple(), но чтобы не копировать строку каждый раз, обернём её в std::reference_wrapper.
Явно укажем выведенный тип.
И ещё замечание о присваиваемости итератора, создаваемого с помощью make_function_output_iterator.