The document describes performance testing of a password masking function. It identifies that regular expressions involving JSON keys take the most time (over 1 second) due to their complexity. The function is optimized by precompiling the regular expressions and testing them individually. This shows the slowest expressions involve JSON keys like 'adminPass' and the fastest take less than 0.001 seconds.
The document contains a list of 37 PHP interview questions and their answers. Some of the key questions covered include: how to find the number of days between two dates in PHP, how to define a constant, the difference between urlencode and urldecode, how to get uploaded file information, the difference between mysql_fetch_object and mysql_fetch_array, how to pass a variable by reference, how to submit a form without a submit button, how to extract a string from another string using a regular expression, and how to get browser properties using PHP.
This document discusses tuples in Python. It begins with definitions of tuples, noting that they are ordered, indexed and immutable sequences. It then provides examples of creating tuples using parentheses or not, and explains that a single element tuple requires a trailing comma. The document discusses tuple operations like slicing, comparison, assignment and using tuples as function return values or dictionary keys. It also covers built-in tuple methods and functions.
RSpec matchers allow for composable and custom matchers that make expectations more readable. Composable matchers can combine built-in matchers to check complex conditions with one expectation. Custom matchers can be defined to create new matchers tailored to a specific testing need. Chained matchers provide a fluent interface for expressing expectations across multiple matchers.
This document describes dynamic SQL and classes used in a client/server database application. It discusses how dynamic SQL statements are generated at runtime based on form controls and table names. Various classes are shown like clsSqlDbAccess for database access, clsWnd for windows, clsMdi for MDI forms, and clsTbl for tables. Methods are described for generating SQL statements, executing queries, and handling results based on messages between classes.
JavaScript Fundamentals with Angular and LodashBret Little
The purpose of this presentation is also largely to explain some of the fun parts of JavaScript (dynamic function invocation with reflection, dynamic arguments, etc). I don't necessarily encourage putting complex logic throughout your templates with lodash, though there may be times it is appropriate.
Lets talk about lodash and how it can easily be married to Angular. Using a six line filter, I will expose the power of lodash directly within angular templates. This will be an introduction to lodash, angular templates, and we'll talk about scope and reflection within JavaScript.
This document discusses building price models using data mining techniques. It describes creating a wine price dataset based on wine rating and age, with price determined by a wineprice function. The dataset is then used to test k-nearest neighbors (k-NN) algorithms and weighted k-NN algorithms for price estimation. Cross-validation and handling of non-homogeneous variables like bottle size and aisle location are also covered. Optimization techniques like hill climbing, simulated annealing, and genetic algorithms are applied to find optimal weight values for variables in the weighted k-NN algorithm.
Czym się różnie JMS od AMQP? Co to jest queue? Co to jest topic? Jak zlecać zadania w przyszłości używając kolejek? Jak się do tego podpiąć z Javy? Na te i inne pytania postaram się odpowiedzieć na mojej prezentacji.
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup itPROIDEA
Niektóre rzeczy trzeba dobrze przyprawić żeby były lepsze ... tak samo jest z pisaniem aplikacji na Androida. Jako programiści zaczynamy mieć czasami dość Javy i chcielibyśmy się przerzucić na coś lepszego i czytelniejszego. Takim rozwiązaniem może okazać się Kotlin. O zaletach języka i o tym jak może ułatwić pracę z Androidem dowiecie się podczas tego wykładu.
The document contains a list of 37 PHP interview questions and their answers. Some of the key questions covered include: how to find the number of days between two dates in PHP, how to define a constant, the difference between urlencode and urldecode, how to get uploaded file information, the difference between mysql_fetch_object and mysql_fetch_array, how to pass a variable by reference, how to submit a form without a submit button, how to extract a string from another string using a regular expression, and how to get browser properties using PHP.
This document discusses tuples in Python. It begins with definitions of tuples, noting that they are ordered, indexed and immutable sequences. It then provides examples of creating tuples using parentheses or not, and explains that a single element tuple requires a trailing comma. The document discusses tuple operations like slicing, comparison, assignment and using tuples as function return values or dictionary keys. It also covers built-in tuple methods and functions.
RSpec matchers allow for composable and custom matchers that make expectations more readable. Composable matchers can combine built-in matchers to check complex conditions with one expectation. Custom matchers can be defined to create new matchers tailored to a specific testing need. Chained matchers provide a fluent interface for expressing expectations across multiple matchers.
This document describes dynamic SQL and classes used in a client/server database application. It discusses how dynamic SQL statements are generated at runtime based on form controls and table names. Various classes are shown like clsSqlDbAccess for database access, clsWnd for windows, clsMdi for MDI forms, and clsTbl for tables. Methods are described for generating SQL statements, executing queries, and handling results based on messages between classes.
JavaScript Fundamentals with Angular and LodashBret Little
The purpose of this presentation is also largely to explain some of the fun parts of JavaScript (dynamic function invocation with reflection, dynamic arguments, etc). I don't necessarily encourage putting complex logic throughout your templates with lodash, though there may be times it is appropriate.
Lets talk about lodash and how it can easily be married to Angular. Using a six line filter, I will expose the power of lodash directly within angular templates. This will be an introduction to lodash, angular templates, and we'll talk about scope and reflection within JavaScript.
This document discusses building price models using data mining techniques. It describes creating a wine price dataset based on wine rating and age, with price determined by a wineprice function. The dataset is then used to test k-nearest neighbors (k-NN) algorithms and weighted k-NN algorithms for price estimation. Cross-validation and handling of non-homogeneous variables like bottle size and aisle location are also covered. Optimization techniques like hill climbing, simulated annealing, and genetic algorithms are applied to find optimal weight values for variables in the weighted k-NN algorithm.
Czym się różnie JMS od AMQP? Co to jest queue? Co to jest topic? Jak zlecać zadania w przyszłości używając kolejek? Jak się do tego podpiąć z Javy? Na te i inne pytania postaram się odpowiedzieć na mojej prezentacji.
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup itPROIDEA
Niektóre rzeczy trzeba dobrze przyprawić żeby były lepsze ... tak samo jest z pisaniem aplikacji na Androida. Jako programiści zaczynamy mieć czasami dość Javy i chcielibyśmy się przerzucić na coś lepszego i czytelniejszego. Takim rozwiązaniem może okazać się Kotlin. O zaletach języka i o tym jak może ułatwić pracę z Androidem dowiecie się podczas tego wykładu.
If you thought Monads are a mystery, then this demonstration would show you how to evolve your code towards a Monad without knowing about it. This demo will neither go into any Category Theory nor begin with monadic laws. Instead, we will start with typical code that you see in your daily life as a developer, attempt to DRY (Don't Repeat Yourself) it up and eventually use Monad to remove duplication and verbosity. You'll also see how Monads make your code more declarative and succinct by sequencing the steps in your domain logic.
Also, we know in Java8 Checked Exceptions + λ == Pain! To be more precise, we will evolve a Try<t> (exception handling monad) which is missing in Java8, similar to one found in Scala.
This document discusses functions, arrays, and structures in C++. It covers:
- Declaring and defining functions
- Passing arrays and structures as arguments to functions
- Returning arrays and structures from functions
- Using multidimensional arrays as function parameters
- Examples of functions that read/write arrays and structures
This document discusses new features in CakePHP version 2.2 related to view blocks, JSON and XML views, improved hashing performance, date/time utilities, and scoped logging. It provides examples of using view blocks to keep HTML DRY, creating JSON views, benchmarking hash performance improvements over sets, using the new CakeTime and CakeNumber utilities, and attaching loggers with scopes to filter log messages.
Specs2 is a Scala library for writing acceptance and unit tests. It uses a domain specific language (DSL) approach based on behavior-driven development (BDD). Specs2 specifications are structured, immutable, and control dependencies. Unit specs extend Specification and are mutable, while acceptance specs extend Specification and are functional. Specs2 provides matchers, mock objects, and forms to make assertions in tests. Tests can be run with JUnit or from SBT with different output formats.
This document contains definitions for several user-defined functions in SQL including functions to iterate through benefit plans, split strings, convert codes for country, marital status, race, suffixes, and dates. The functions take in various data types as parameters and return formatted results like concatenated strings or converted data types.
The document discusses C++ strings and the string class. It covers string formats, the string class in the C++ standard library, string constructors, assigning and comparing strings, and input/output with strings using the insertion and extraction operators. It also covers using the getline function to read entire lines of input into string variables.
The document discusses a software development team called Team-9 at SoftCorp that is developing a mobile email client application. The team wants to develop an email client that supports multimedia emails to address a limitation in their competitor's product, and covers topics like identifying security requirements and vulnerabilities. The team finds issues in code fragments that could lead to security threats and proposes solutions to address them. Design patterns like thin client and protected process are identified that could enhance security for the product.
The document discusses user-defined data types in C++ including defined constants (#define), defining own types (typedef), constants (const), enumerations (enum), scope of variables, and structures (struct). The key objectives are to understand how to create user-defined data types.
EventMachine is a toolkit for building event-driven applications using the reactor pattern. It allows non-blocking I/O and handling of thousands of concurrent connections without threads. EventMachine implements the reactor pattern by having a single-threaded event loop that dispatches incoming events to associated event handlers. This allows highly scalable I/O applications to be written without threads.
This document discusses arrays and functions. It covers various topics related to arrays including declaring and manipulating multidimensional arrays, array parameters in functions, and converting between array types. It also provides an overview of functions, describing them as subparts of a program for obtaining input, performing calculations, and displaying output. Examples are given throughout to demonstrate array and function concepts.
The document discusses classes and files in C++. It covers:
1) Classes in C++, including declaring classes, private, protected, and public members, and examples of classes.
2) Files in C++, including streams, reading from and writing to files, and the standard input/output streams.
3) Specific file classes in C++ - ifstream for input, ofstream for output, and fstream for both. It also covers opening files using the open() function.
This document provides an overview and examples of several design patterns in object-oriented programming with PHP, including Strategy, Factory, Abstract Factory, Adapter, Singleton, Iterator, and Observer patterns. The Strategy pattern allows making decisions on different cases more easily by encapsulating varying implementations of an algorithm. The Factory pattern hides object creation logic and allows for polymorphic object instantiation. The Abstract Factory pattern ensures all created objects conform to a common interface. The Adapter pattern allows incompatible interfaces to work together by wrapping an object to fit expected interfaces. The Singleton pattern ensures only one instance of a class is created. The Iterator pattern provides a way to access elements of an object sequentially without exposing its underlying representation. The Observer pattern allows objects to publish
Lenses and Prisms in Swift - Elviro Rocca - Codemotion Rome 2018 Codemotion
The concept of functional Lens has become pretty popular in functional programming circles, and there are already good contributions for applying lenses to other, traditionally imperative/OO contexts. I’d like to offer a more in depth view on why lenses can be useful in Swift, and also talk about an associated concept called Prism. Let’s consider some practical problems and confront an idiomatic/imperative approach to the one based on lenses and prisms.
This document provides an introduction to jRuby, which allows Ruby code to be run on the Java Virtual Machine. It discusses the history and creator of Ruby, Yukihiro "Matz" Matsumoto, and his goals for the language. It then provides a primer on Ruby syntax including booleans, strings, numbers, arrays, hashes, symbols, and classes. It demonstrates how Ruby code can interact with Java code when using jRuby, such as calling Java classes and methods from Ruby. It also discusses metaprogramming in Ruby and how jRuby enables cross-platform GUI development using Java libraries.
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFabio Collini
Kotlin is a first-class language for Android development since Google I/O 2017. And it’s here to stay!
Thanks to Android Studio it’s really easy to introduce Kotlin in an existing project, the configuration is trivial and then we can convert Java classes to Kotlin using a Alt+Shift+Cmd+K. But the new syntax is the just beginning, using Kotlin we can improve our code making it more readable and simpler to write.
In this talk we’ll see how to use some Kotlin features (for example data classes, collections, coroutines and delegates) to simplify Android development comparing the code with the equivalent “modern” Java code. It’s not fair to compare Kotlin code with plain Java 6 code so the Java examples will use lambdas and some external libraries like RxJava and AutoValue.
Groovy is a dynamic language for the Java platform that provides features inspired by languages like Python, Ruby and Smalltalk. It allows Java developers to use these features with a syntax that is very similar to Java. Groovy code can be compiled to Java bytecode and integrated with Java applications and libraries. It supports features like closures, metaprogramming, builders and templates to improve developer productivity.
The document discusses procedural abstraction and predefined functions in computer programming. It provides examples of for loops and nested for loops to iterate through ranges of values. The for loop examples demonstrate how the initialization, boolean expression, and update components work together to execute the loop body. Tracing is used to step through multiple iterations of the for loops.
This document describes a student project for a hotel billing system. It includes sections describing the project contents, aim to create bills based on booking numbers, table structure, program coding and output, merits like fast accessible records, and demerits like inability to recover deleted records. The conclusion states the project reduces manual work and automatically calculates totals.
This document provides examples of Python code snippets covering various topics like Python basics (print, variables, data types), conditional statements (if-else), loops (for, while), functions, object oriented programming (classes, inheritance), file handling, modules, database connectivity (MySQL, Redis), XML/HTML parsing and web scraping. It also shows code for installing and importing various third party Python libraries and modules.
The document provides an introduction to user experience (UX) and Asynchronous JavaScript and XML (Ajax). It discusses what UX and Ajax are, examples of Ajax in real world applications like Gmail, usability issues with Ajax, and ways to address those issues through workarounds and design principles. It also covers Ajax patterns that can provide a better user experience.
If you thought Monads are a mystery, then this demonstration would show you how to evolve your code towards a Monad without knowing about it. This demo will neither go into any Category Theory nor begin with monadic laws. Instead, we will start with typical code that you see in your daily life as a developer, attempt to DRY (Don't Repeat Yourself) it up and eventually use Monad to remove duplication and verbosity. You'll also see how Monads make your code more declarative and succinct by sequencing the steps in your domain logic.
Also, we know in Java8 Checked Exceptions + λ == Pain! To be more precise, we will evolve a Try<t> (exception handling monad) which is missing in Java8, similar to one found in Scala.
This document discusses functions, arrays, and structures in C++. It covers:
- Declaring and defining functions
- Passing arrays and structures as arguments to functions
- Returning arrays and structures from functions
- Using multidimensional arrays as function parameters
- Examples of functions that read/write arrays and structures
This document discusses new features in CakePHP version 2.2 related to view blocks, JSON and XML views, improved hashing performance, date/time utilities, and scoped logging. It provides examples of using view blocks to keep HTML DRY, creating JSON views, benchmarking hash performance improvements over sets, using the new CakeTime and CakeNumber utilities, and attaching loggers with scopes to filter log messages.
Specs2 is a Scala library for writing acceptance and unit tests. It uses a domain specific language (DSL) approach based on behavior-driven development (BDD). Specs2 specifications are structured, immutable, and control dependencies. Unit specs extend Specification and are mutable, while acceptance specs extend Specification and are functional. Specs2 provides matchers, mock objects, and forms to make assertions in tests. Tests can be run with JUnit or from SBT with different output formats.
This document contains definitions for several user-defined functions in SQL including functions to iterate through benefit plans, split strings, convert codes for country, marital status, race, suffixes, and dates. The functions take in various data types as parameters and return formatted results like concatenated strings or converted data types.
The document discusses C++ strings and the string class. It covers string formats, the string class in the C++ standard library, string constructors, assigning and comparing strings, and input/output with strings using the insertion and extraction operators. It also covers using the getline function to read entire lines of input into string variables.
The document discusses a software development team called Team-9 at SoftCorp that is developing a mobile email client application. The team wants to develop an email client that supports multimedia emails to address a limitation in their competitor's product, and covers topics like identifying security requirements and vulnerabilities. The team finds issues in code fragments that could lead to security threats and proposes solutions to address them. Design patterns like thin client and protected process are identified that could enhance security for the product.
The document discusses user-defined data types in C++ including defined constants (#define), defining own types (typedef), constants (const), enumerations (enum), scope of variables, and structures (struct). The key objectives are to understand how to create user-defined data types.
EventMachine is a toolkit for building event-driven applications using the reactor pattern. It allows non-blocking I/O and handling of thousands of concurrent connections without threads. EventMachine implements the reactor pattern by having a single-threaded event loop that dispatches incoming events to associated event handlers. This allows highly scalable I/O applications to be written without threads.
This document discusses arrays and functions. It covers various topics related to arrays including declaring and manipulating multidimensional arrays, array parameters in functions, and converting between array types. It also provides an overview of functions, describing them as subparts of a program for obtaining input, performing calculations, and displaying output. Examples are given throughout to demonstrate array and function concepts.
The document discusses classes and files in C++. It covers:
1) Classes in C++, including declaring classes, private, protected, and public members, and examples of classes.
2) Files in C++, including streams, reading from and writing to files, and the standard input/output streams.
3) Specific file classes in C++ - ifstream for input, ofstream for output, and fstream for both. It also covers opening files using the open() function.
This document provides an overview and examples of several design patterns in object-oriented programming with PHP, including Strategy, Factory, Abstract Factory, Adapter, Singleton, Iterator, and Observer patterns. The Strategy pattern allows making decisions on different cases more easily by encapsulating varying implementations of an algorithm. The Factory pattern hides object creation logic and allows for polymorphic object instantiation. The Abstract Factory pattern ensures all created objects conform to a common interface. The Adapter pattern allows incompatible interfaces to work together by wrapping an object to fit expected interfaces. The Singleton pattern ensures only one instance of a class is created. The Iterator pattern provides a way to access elements of an object sequentially without exposing its underlying representation. The Observer pattern allows objects to publish
Lenses and Prisms in Swift - Elviro Rocca - Codemotion Rome 2018 Codemotion
The concept of functional Lens has become pretty popular in functional programming circles, and there are already good contributions for applying lenses to other, traditionally imperative/OO contexts. I’d like to offer a more in depth view on why lenses can be useful in Swift, and also talk about an associated concept called Prism. Let’s consider some practical problems and confront an idiomatic/imperative approach to the one based on lenses and prisms.
This document provides an introduction to jRuby, which allows Ruby code to be run on the Java Virtual Machine. It discusses the history and creator of Ruby, Yukihiro "Matz" Matsumoto, and his goals for the language. It then provides a primer on Ruby syntax including booleans, strings, numbers, arrays, hashes, symbols, and classes. It demonstrates how Ruby code can interact with Java code when using jRuby, such as calling Java classes and methods from Ruby. It also discusses metaprogramming in Ruby and how jRuby enables cross-platform GUI development using Java libraries.
From java to kotlin beyond alt+shift+cmd+k - Droidcon italyFabio Collini
Kotlin is a first-class language for Android development since Google I/O 2017. And it’s here to stay!
Thanks to Android Studio it’s really easy to introduce Kotlin in an existing project, the configuration is trivial and then we can convert Java classes to Kotlin using a Alt+Shift+Cmd+K. But the new syntax is the just beginning, using Kotlin we can improve our code making it more readable and simpler to write.
In this talk we’ll see how to use some Kotlin features (for example data classes, collections, coroutines and delegates) to simplify Android development comparing the code with the equivalent “modern” Java code. It’s not fair to compare Kotlin code with plain Java 6 code so the Java examples will use lambdas and some external libraries like RxJava and AutoValue.
Groovy is a dynamic language for the Java platform that provides features inspired by languages like Python, Ruby and Smalltalk. It allows Java developers to use these features with a syntax that is very similar to Java. Groovy code can be compiled to Java bytecode and integrated with Java applications and libraries. It supports features like closures, metaprogramming, builders and templates to improve developer productivity.
The document discusses procedural abstraction and predefined functions in computer programming. It provides examples of for loops and nested for loops to iterate through ranges of values. The for loop examples demonstrate how the initialization, boolean expression, and update components work together to execute the loop body. Tracing is used to step through multiple iterations of the for loops.
This document describes a student project for a hotel billing system. It includes sections describing the project contents, aim to create bills based on booking numbers, table structure, program coding and output, merits like fast accessible records, and demerits like inability to recover deleted records. The conclusion states the project reduces manual work and automatically calculates totals.
This document provides examples of Python code snippets covering various topics like Python basics (print, variables, data types), conditional statements (if-else), loops (for, while), functions, object oriented programming (classes, inheritance), file handling, modules, database connectivity (MySQL, Redis), XML/HTML parsing and web scraping. It also shows code for installing and importing various third party Python libraries and modules.
The document provides an introduction to user experience (UX) and Asynchronous JavaScript and XML (Ajax). It discusses what UX and Ajax are, examples of Ajax in real world applications like Gmail, usability issues with Ajax, and ways to address those issues through workarounds and design principles. It also covers Ajax patterns that can provide a better user experience.
This document describes functional pattern matching in different programming languages like Haskell, Erlang, Python, and Prolog. It introduces a Python library called Patterns that implements pattern matching via function decoration and AST transformation. The library allows matching different patterns in function arguments and assigning or evaluating expressions based on the matched patterns.
This document discusses regular expressions (regex) in Python. It covers common regex patterns using metacharacters like [], {}, (), |, etc to match characters, repetitions, groups, alternatives. It explains functions like match(), search(), sub() in the re module to find/search/replace patterns in strings. It provides examples of case-insensitive searching and using capturing groups. Finally, it lists some common regex flags and provides tasks to use regex patterns and functions in Python programs.
This document provides an overview of regular expressions in Python. It discusses how regular expressions can be used to search, match, replace, and split strings. The syntax for common regular expression patterns is explained, including character classes, grouping, quantifiers, anchors, and more. Examples are given showing how to use the re module to compile patterns, search and match strings, and extract matched groups. Regular expressions in Python provide a powerful tool for manipulating text data.
This document summarizes an introduction to data analysis in Python using Wakari. It discusses why Python is a good language for data analysis, highlighting key Python packages like NumPy, Pandas, Matplotlib and IPython. It also introduces Wakari, a browser-based Python environment for collaborative data analysis and reproducible research. Wakari allows sharing of code, notebooks and data through a web link. The document recommends several talks at the PyData conference on efficient computing, machine learning and interactive plotting.
Regular expressions are a powerful tool for searching, matching, and parsing text patterns. They allow complex text patterns to be matched with a standardized syntax. All modern programming languages include regular expression libraries. Regular expressions can be used to search strings, replace parts of strings, split strings, and find all occurrences of a pattern in a string. They are useful for tasks like validating formats, parsing text, and finding/replacing text. This document provides examples of common regular expression patterns and methods for using regular expressions in Python.
The document discusses object-oriented programming concepts in Python including classes, objects, methods, encapsulation, inheritance, and polymorphism. It provides examples of defining a class with attributes and methods, instantiating objects from a class, and accessing object attributes and methods. It also covers the differences between procedure-oriented and object-oriented programming, and fundamental OOP concepts like encapsulation, inheritance, and polymorphism in Python.
This document discusses six Python packages that are useful to know:
1. First - A utility for selecting the first successful result from a sequence of functions.
2. Parse - A library for parsing Python format strings and extracting values.
3. Filecmp - A module for comparing files and directories.
4. Bitrot - A tool for detecting silent data corruption in files.
5. Docopt - A tool for generating command-line interfaces from a docstring.
6. Six - A library for writing code that is compatible with both Python 2 and Python 3.
The `Right way` of testing and refactoring is so ambiguous to put in the real world, Especially, Business situation.
Let's look in deep the testing and refactoring at the perspective of a developer who works for a business situation.
En vieux bourlingueur du langage Swift, Grégoire Lhotellier viendra nous présenter les séquences et les collections du nouveau langage d’Apple. Il nous briefera sur l’essentiel de ce qu’il faut en savoir et ce qu’elles changent par rapport à leurs équivalent Objective-C.
Creating Domain Specific Languages in PythonSiddhi
This document discusses domain specific languages (DSLs) and provides examples of creating DSLs in Python. It explains that DSLs allow users to work in specialized mini-languages tailored to specific problem domains. As examples, it discusses SQL as a DSL for databases and regular expressions as a DSL for patterns. It then demonstrates how to create an external DSL for defining forms using PyParsing and an internal DSL for the same using Python features like metaclasses. The document concludes that DSLs make code easier to read, write and maintain for non-programmers.
Detect Negative and Positive sentiment in user reviews using python word2vec ...Mamoon Ismail Khalid
detect Negative and Positive Sentiment in User Reviews_using Python word2vec model
libraries used:
Unsupervised training
from gensim.models.doc2vec import TaggedDocument
from gensim.models import Doc2Vec
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
import numpy as np
please code in c#- please note that im a complete beginner- northwind.docxAustinaGRPaigey
please code in c#.
please note that im a complete beginner.
northwind.mdf.
northwind_log.ldf
OrderDetailsMaintenance.zip
1. Include the two above files in the root of your OrderDetailsMaintenance project.
2. Make sure to mark them as "Content" and "Copy Always" or "Copy if newer" in the properties window of those two files.
3. Run the Scaffold-DbContext command to create a context class as well as a class to encapsulate the Orders objects from the associated table in the mdf file. Make sure to include the parameters for -Tables Customers (only worry about the attributes associated with the text boxes, you don't need to worry about any other rows from the table)
4. Once you have ran the command, include an app.config file and add a connection string element. Make sure to copy the connection string from your Context class to your app.config. Then edit your context to grab the connection string from the app.config (ConfigurationManager.ConnectionString["Northwind"].ConnectionString)
5. Code the Find button to Find the customer id and populate the details in the below text boxes.
1. If no order is found, display a message box.
6. Code the exit button
7. Code the Save button to update its attributes and call Update and SaveChanges() on that particular entity.
1. Note: If you close the program, reopen it, and search for the entity you recently updated. You may not see the changes depending on how you setup the mdf file in your project (because it copies a new version to the bin directory each time you run the program). So, if you don't see your changes, don't be alarmed.
============
HERE IS WHAT I HAVE SO FAR
frmCustomerMaintenance.cs
namespace OrderDetailsMaintenance
{
public partial class frmCustomerMaintenance : Form
{
public frmCustomerMaintenance()
{
InitializeComponent();
}
}
}
frmCustomerMaintenance.resx
<root>
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name".
- This document contains code for encrypting and decrypting data when communicating with a game server. It includes functions for generating encryption keys, encoding parameters and data using AES and RSA encryption, logging in a user by sending their encrypted username and password, and reading/writing configuration files to store login credentials. The code supports multiple regions/servers by country code and includes hardcoded encryption keys for each region.
Chapter 2 Python Language Basics, IPython.pptxSovannDoeur
The document outlines key concepts in Python including:
- Python is an interpreted language and runs code line by line using the Python interpreter.
- Python has various data types including integers, floats, strings, booleans, lists, tuples, and dictionaries.
- Control flow in Python uses conditional statements like if/else and loops like for and while to control program execution.
- Functions and methods allow calling and reusing code, while classes and objects are Python's way of modeling real-world items.
The document discusses various Python magic methods that can be overridden in classes to customize behavior. It provides examples of overriding __contains__, __getitem__, __len__, and __nonzero__ methods to change how membership testing, item access, length calculation, and truth value testing work for class instances. The examples demonstrate how these magic methods allow flexible, customized behavior compared to regular classes and built-in types.
Fundamentals of Cryptography - Caesar Cipher - Python Isham Rashik
Documentation of the cipher program that allows the letters in a raw text file to be ciphered - encrypted or decrypted. The program is implemented in Python 3.x. Code implementation followed by demonstration on how the program is to be used are outlined within this document.
This document discusses database functions and procedures in PostgreSQL. It begins with an overview of what functions and procedures are, when and where they are used. It then covers topics like:
- The basic syntax for creating functions and procedures
- Different types of parameters like IN, OUT, INOUT
- Calling user-defined functions
- Explaining queries using functions
- Transaction handling in functions and procedures
- Aggregate and custom aggregate functions
- Triggers and when they are used
- Database partitioning for performance optimization
The document provides examples of creating and using various types of functions, procedures and triggers in PostgreSQL. It also summarizes the differences between functions and procedures.
The presentation from SPb Python Interest Group community meetup.
The presentation tells about the dictionaries in Python, reviews the implementation of dictionary in CPython 2.x, dictionary in CPython 3.x, and also recent changes in CPython 3.6. In addition to CPython the dictionaries in alternative Python implementations such as PyPy, IronPython and Jython are reviewed.
This document discusses functions in Python including defining functions, calling functions, passing arguments to functions, default arguments, returning values from functions, and exception handling. It provides examples of defining functions using the def keyword, calling functions, passing positional and keyword arguments to functions, setting default values for arguments, and returning values. It also discusses exceptions, try/except blocks, and user-defined exceptions.
En esta charla veremos con detalle algunas de las construcciones más pythonicas y las posibilidades de expresar de forma clara, concisa y elegante cosas que en otros lenguajes nos obligarían a dar muchos rodeos.
A veces es fácil olvidar algunos recursos como que una función puede devolver varios valores, cómo manipular listas y diccionarios de forma sencilla, contextos, generadores... En esta charla veremos de forma entretenida y práctica cómo mejorar nuestro nivel de Python "nativo".
The document discusses various functions for working with semaphores in Unix/Linux systems:
- semget() is used to create or access a set of semaphores given a key and number of semaphores. It returns an identifier for the semaphore set.
- semctl() performs control operations on semaphores like deleting a set, getting/setting individual values, or getting/setting all values in a set atomically.
- semop() performs semaphore operations like incrementing/decrementing values in a way that ensures atomicity across multiple operations. It is used to synchronize access to shared resources.
R code can be used for various data manipulation tasks such as creating, recoding, and renaming variables; sorting and merging datasets; aggregating and reshaping data; and subsetting datasets. Specific R functions and operations allow users to efficiently manipulate data frames through actions like transposing data, calculating summary statistics, and selecting subsets of observations and variables.
R code can be used for various data manipulation tasks such as creating, recoding, and renaming variables; sorting and merging datasets; aggregating and reshaping data; and subsetting datasets. Specific R functions and operations allow users to efficiently manipulate data frames through actions like transposing data, calculating summary statistics, and selecting subsets of observations and variables.
Having issues with passing my values through different functions aft.pdfrajkumarm401
The document describes creating an EmployeeRecord class to store employee data including ID, name, department, and salary. It includes the class definition with private member variables and public getter/setter functions. The main() function demonstrates creating an EmployeeRecord object, passing values to the constructor, and calling printRecord() to output the data. Issues were encountered passing values through functions after construction. The solution comments out incorrect nulling of string pointers in the constructor, fixes the getter/setter functions to properly copy between members and parameters, and changes the salary input in main to not use a pointer.
The document discusses dependency injection containers and configuration in frameworks. It provides examples of configuring services like mail transport and mailers using different approaches like procedural code, object-oriented code, and XML configuration. It also discusses managing configuration for different environments and making components more flexible through inheritance and customization.
Reno: A new way to manage release notesdoughellmann
reno is a tool for managing release notes in projects that support multiple branches of development simultaneously. It lets you manage release notes within patches that fix bugs, and makes it easier to cherry-pick changes between branches for back- or forward-ports. This talk will cover the requirements, and constraints, that led us to design and build reno. I will also show how to use it to create notes, and publish them in your packages and via Sphinx-based documentation.
Reno A New Way to Manage Release Notesdoughellmann
reno is a tool for managing release notes in projects that support multiple branches of development, and releases, simultaneously. It solves the problem of managing release notes within patches that fix bugs, and makes it easier to cherry-pick changes between branches (allowing backports or forward ports).
How OpenStack Makes Python Better (and vice-versa)doughellmann
OpenStack is an open source stack that can be deployed on raw computing resources to privately or publicly present Infrastructure as a Service. It now consists of more than 4.5 million lines of code, 85% of which is Python. In this talk, Thierry Carrez and Doug Hellmann, both Python Software Foundation fellows and OpenStack Technical Committee members, look at the symbiotic relationship between OpenStack and Python.
We go back in history and explain why OpenStack originally picked Python as its main language 6 years ago, and explore what does Python bring to OpenStack. We dive into examples of OpenStack pushing Python libraries to their limits and exposing new bugs. We look into the massive cloud-based continuous integration system that OpenStack uses and explain how it exposes bugs in Python libraries in the minutes after they are published to PyPI. We look into Python libraries that were created by the OpenStack community and libraries that the OpenStack community took over. Finally we'll expose a few best practices that Python developers can follow to get the most of this symbiotic relationship.
How I Built a Power Debugger Out of the Standard Library and Things I Found o...doughellmann
Smiley demonstrates how to use Python's native tracing capabilities to monitor not just what parts of your program run, but the data flowing through the program as it runs. All of the data is recorded for study after the program exits, which means you can pass different inputs and then compare the results of the runs. In this presentation, I describe the evolution of Smiley, from concept through internal API changes as I worked on the implementation. I also talk about tracing Python programs in general, and explain how the trace code in Smiley can be used to send trace data to different output destinations.
Rolling with the Times: Using wheels, pbr, and Twine for Distributing and Ins...doughellmann
The document discusses different formats for distributing and installing Python packages, including sdist, eggs, and wheels. It describes how to build source distributions (sdists), eggs, and wheels. Wheels provide pre-built binaries and improve installation speed compared to sdists which require compiling. The pbr tool can automate package metadata and release file generation. Twine can be used to upload packages to PyPI. Caching wheels locally or in a wheelhouse can further speed up pip installations.
The document discusses changes to OpenStack release management under a "Big Tent" approach, including moving from a single time-based release model to allowing individual projects to release on their own schedules using semantic versioning and standardized practices. It describes establishing stable branches for projects to release bug fixes and developing tools to automate portions of the release process.
How I Built a Power Debugger Out of the Standard Library and Things I Found o...doughellmann
The document describes a Python debugger called Smiley that was built using the standard library and things found online. Smiley can record calls and data during program execution, enable remote monitoring and local analysis of runs, and browse run histories. It works by tracing program execution using a tracer class and publishing trace events to a publisher. Traces are stored in a SQLite database for later retrieval and replay.
Taking the Long View: How the Oslo Program Reduces Technical Debtdoughellmann
In the fast-paced world of OpenStack development, we often focus on short-term needs like bug fixes and new features. The Oslo Program takes a longer view of the health and sustainability of the project. Our mission is to make OpenStack more maintainable by addressing cross-project code reuse and architectural issues. In this presentation we will cover the origins of Oslo and the processes and tools the team uses to improve OpenStack from the bottom up, making it easier to deploy, more approachable for new contributors, and sustainable for long-term use.
Oslo Program Overview, OpenStack Atlantadoughellmann
The document summarizes the goals and work of the Oslo project, which aims to develop shared Python libraries for OpenStack projects. The Oslo team produces libraries containing common code that provide stable, consistent, and well-documented APIs. They have graduated several key libraries used across OpenStack, and continue to refine APIs and add new libraries while also working to port components to Python 3.
Dynamic Code Patterns: Extending Your Applications with Pluginsdoughellmann
Python makes loading code dynamically easy, allowing you to configure and extend your application by discovering and loading extensions at runtime. This presentation will discuss the techniques for dynamic code loading used in several well-known applications and weigh the pros and cons of each approach.
Better Documentation Through Automation: Creating docutils & Sphinx Extensionsdoughellmann
Sphinx is an incredibly useful tool for creating attractive documentation for your project, but if all you ever use it for is converting reStructuredText files to HTML you are barely scratching the surface of its power. This presentation shows how easy it is to extend Sphinx by defining new markup processors, allowing you to take your documentation to the next level.
PyCon 2013
Hidden Treasures of the Python Standard Librarydoughellmann
The standard library contains many hidden gems that are not widely used, either because they are not publicized enough or because they are deep in a module that programmers haven't had cause to study or use. This presentation covers a few selected topics of this nature in about 25 minutes (leaving time for a couple of questions). Demonstration code is included for every item.
The document discusses key principles of Python style and design according to the Zen of Python. It emphasizes that Python code should be beautiful, explicit, and simple rather than complex. It provides examples of simple expressions, boolean values, for loops, and defining a class in Python to illustrate these principles. The class definition example shows how to define a class with documentation, initialization, and methods that reference object attributes using self.
Artificia Intellicence and XPath Extension FunctionsOctavian Nadolu
The purpose of this presentation is to provide an overview of how you can use AI from XSLT, XQuery, Schematron, or XML Refactoring operations, the potential benefits of using AI, and some of the challenges we face.
What to do when you have a perfect model for your software but you are constrained by an imperfect business model?
This talk explores the challenges of bringing modelling rigour to the business and strategy levels, and talking to your non-technical counterparts in the process.
SMS API Integration in Saudi Arabia| Best SMS API ServiceYara Milbes
Discover the benefits and implementation of SMS API integration in the UAE and Middle East. This comprehensive guide covers the importance of SMS messaging APIs, the advantages of bulk SMS APIs, and real-world case studies. Learn how CEQUENS, a leader in communication solutions, can help your business enhance customer engagement and streamline operations with innovative CPaaS, reliable SMS APIs, and omnichannel solutions, including WhatsApp Business. Perfect for businesses seeking to optimize their communication strategies in the digital age.
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfVALiNTRY360
Salesforce Healthcare CRM, implemented by VALiNTRY360, revolutionizes patient management by enhancing patient engagement, streamlining administrative processes, and improving care coordination. Its advanced analytics, robust security, and seamless integration with telehealth services ensure that healthcare providers can deliver personalized, efficient, and secure patient care. By automating routine tasks and providing actionable insights, Salesforce Healthcare CRM enables healthcare providers to focus on delivering high-quality care, leading to better patient outcomes and higher satisfaction. VALiNTRY360's expertise ensures a tailored solution that meets the unique needs of any healthcare practice, from small clinics to large hospital systems.
For more info visit us https://valintry360.com/solutions/health-life-sciences
Hand Rolled Applicative User ValidationCode KataPhilip Schwarz
Could you use a simple piece of Scala validation code (granted, a very simplistic one too!) that you can rewrite, now and again, to refresh your basic understanding of Applicative operators <*>, <*, *>?
The goal is not to write perfect code showcasing validation, but rather, to provide a small, rough-and ready exercise to reinforce your muscle-memory.
Despite its grandiose-sounding title, this deck consists of just three slides showing the Scala 3 code to be rewritten whenever the details of the operators begin to fade away.
The code is my rough and ready translation of a Haskell user-validation program found in a book called Finding Success (and Failure) in Haskell - Fall in love with applicative functors.
UI5con 2024 - Boost Your Development Experience with UI5 Tooling ExtensionsPeter Muessig
The UI5 tooling is the development and build tooling of UI5. It is built in a modular and extensible way so that it can be easily extended by your needs. This session will showcase various tooling extensions which can boost your development experience by far so that you can really work offline, transpile your code in your project to use even newer versions of EcmaScript (than 2022 which is supported right now by the UI5 tooling), consume any npm package of your choice in your project, using different kind of proxies, and even stitching UI5 projects during development together to mimic your target environment.
Unveiling the Advantages of Agile Software Development.pdfbrainerhub1
Learn about Agile Software Development's advantages. Simplify your workflow to spur quicker innovation. Jump right in! We have also discussed the advantages.
Top 9 Trends in Cybersecurity for 2024.pptxdevvsandy
Security and risk management (SRM) leaders face disruptions on technological, organizational, and human fronts. Preparation and pragmatic execution are key for dealing with these disruptions and providing the right cybersecurity program.
Measures in SQL (SIGMOD 2024, Santiago, Chile)Julian Hyde
SQL has attained widespread adoption, but Business Intelligence tools still use their own higher level languages based upon a multidimensional paradigm. Composable calculations are what is missing from SQL, and we propose a new kind of column, called a measure, that attaches a calculation to a table. Like regular tables, tables with measures are composable and closed when used in queries.
SQL-with-measures has the power, conciseness and reusability of multidimensional languages but retains SQL semantics. Measure invocations can be expanded in place to simple, clear SQL.
To define the evaluation semantics for measures, we introduce context-sensitive expressions (a way to evaluate multidimensional expressions that is consistent with existing SQL semantics), a concept called evaluation context, and several operations for setting and modifying the evaluation context.
A talk at SIGMOD, June 9–15, 2024, Santiago, Chile
Authors: Julian Hyde (Google) and John Fremlin (Google)
https://doi.org/10.1145/3626246.3653374
Everything You Need to Know About X-Sign: The eSign Functionality of XfilesPr...XfilesPro
Wondering how X-Sign gained popularity in a quick time span? This eSign functionality of XfilesPro DocuPrime has many advancements to offer for Salesforce users. Explore them now!
UI5con 2024 - Bring Your Own Design SystemPeter Muessig
How do you combine the OpenUI5/SAPUI5 programming model with a design system that makes its controls available as Web Components? Since OpenUI5/SAPUI5 1.120, the framework supports the integration of any Web Components. This makes it possible, for example, to natively embed own Web Components of your design system which are created with Stencil. The integration embeds the Web Components in a way that they can be used naturally in XMLViews, like with standard UI5 controls, and can be bound with data binding. Learn how you can also make use of the Web Components base class in OpenUI5/SAPUI5 to also integrate your Web Components and get inspired by the solution to generate a custom UI5 library providing the Web Components control wrappers for the native ones.
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemPeter Muessig
Learn about the latest innovations in and around OpenUI5/SAPUI5: UI5 Tooling, UI5 linter, UI5 Web Components, Web Components Integration, UI5 2.x, UI5 GenAI.
Recording:
https://www.youtube.com/live/MSdGLG2zLy8?si=INxBHTqkwHhxV5Ta&t=0
2. def mask_password(message, secret="***"):
"""Replace password with 'secret' in message.
:param message: The string which includes security information.
:param secret: value with which to replace passwords.
:returns: The unicode value of message with the password fields masked.
"""
try:
message = six.text_type(message)
except UnicodeDecodeError:
# NOTE(jecarey): Temporary fix to handle cases where message is a
# byte string. A better solution will be provided in Kilo.
pass
# NOTE(ldbragst): Check to see if anything in message contains any key
# specified in _SANITIZE_KEYS, if not then just return the message since
# we don't have to mask any passwords.
if not any(key in message for key in _SANITIZE_KEYS):
return message
substitute = r'g<1>' + secret + r'g<2>'
for pattern in _SANITIZE_PATTERNS_2:
message = re.sub(pattern, substitute, message)
substitute = r'g<1>' + secret
for pattern in _SANITIZE_PATTERNS_1:
message = re.sub(pattern, substitute, message)
return message
4. def mask_password(message, secret="***"):
"""Replace password with 'secret' in message.
:param message: The string which includes security information.
:param secret: value with which to replace passwords.
:returns: The unicode value of message with the password fields masked.
"""
try:
message = six.text_type(message)
except UnicodeDecodeError:
# NOTE(jecarey): Temporary fix to handle cases where message is a
# byte string. A better solution will be provided in Kilo.
pass
# NOTE(ldbragst): Check to see if anything in message contains any key
# specified in _SANITIZE_KEYS, if not then just return the message since
# we don't have to mask any passwords.
if not any(key in message for key in _SANITIZE_KEYS):
return message
substitute = r'g<1>' + secret + r'g<2>'
for pattern in _SANITIZE_PATTERNS_2:
message = re.sub(pattern, substitute, message)
substitute = r'g<1>' + secret
for pattern in _SANITIZE_PATTERNS_1:
message = re.sub(pattern, substitute, message)
return message
5. _SANITIZE_KEYS = ['adminPass', 'admin_pass', 'password', 'admin_password',
'auth_token', 'new_pass', 'auth_password', 'secret_uuid']
# NOTE(ldbragst): Let's build a list of regex objects using the list of
# _SANITIZE_KEYS we already have. This way, we only have to add the new key
# to the list of _SANITIZE_KEYS and we can generate regular expressions
# for XML and JSON automatically.
_SANITIZE_PATTERNS_2 = []
_SANITIZE_PATTERNS_1 = []
# NOTE(amrith): Some regular expressions have only one parameter, some
# have two parameters. Use different lists of patterns here.
_FORMAT_PATTERNS_1 = [r'(%(key)ss*[=]s*)[^s^'^"]+']
_FORMAT_PATTERNS_2 = [r'(%(key)ss*[=]s*["']).*?(["'])',
r'(%(key)ss+["']).*?(["'])',
r'([-]{2}%(key)ss+)[^'^"^=^s]+([s]*)',
r'(<%(key)s>).*?(</%(key)s>)',
r'(["']%(key)s["']s*:s*["']).*?(["'])',
r'(['"].*?%(key)s['"]s*:s*u?['"]).*?(['"])',
r'(['"].*?%(key)s['"]s*,s*'--?[A-z]+'s*,s*u?'
'['"]).*?(['"])',
r'(%(key)ss*--?[A-z]+s*)S+(s*)']
for key in _SANITIZE_KEYS:
for pattern in _FORMAT_PATTERNS_2:
reg_ex = re.compile(pattern % {'key': key}, re.DOTALL)
_SANITIZE_PATTERNS_2.append(reg_ex)
for pattern in _FORMAT_PATTERNS_1:
reg_ex = re.compile(pattern % {'key': key}, re.DOTALL)
_SANITIZE_PATTERNS_1.append(reg_ex)
7. def mask_password(message, secret="***"):
"""Replace password with 'secret' in message.
:param message: The string which includes security information.
:param secret: value with which to replace passwords.
:returns: The unicode value of message with the password fields masked.
"""
try:
message = six.text_type(message)
except UnicodeDecodeError:
# NOTE(jecarey): Temporary fix to handle cases where message is a
# byte string. A better solution will be provided in Kilo.
pass
# NOTE(ldbragst): Check to see if anything in message contains any key
# specified in _SANITIZE_KEYS, if not then just return the message since
# we don't have to mask any passwords.
if not any(key in message for key in _SANITIZE_KEYS):
return message
substitute = r'g<1>' + secret + r'g<2>'
for pattern in _SANITIZE_PATTERNS_2:
message = re.sub(pattern, substitute, message)
substitute = r'g<1>' + secret
for pattern in _SANITIZE_PATTERNS_1:
message = re.sub(pattern, substitute, message)
return message
8. class timeit.Timer(stmt='pass', setup='pass', timer=<timer function>)
timeit(number=1000000)
t = timeit.Timer(
stmt="re.sub(pattern, r'g<1>***g<2>', payload)",
setup="""
import re
payload = '''%s'''
pattern = re.compile(r'''%s''')
""" % (input_str, pattern.pattern))
result = t.timeit(1)
9. #!/usr/bin/env python
from __future__ import print_function
import timeit
import strutils
# A moderately sized input (~50K) string
# http://paste.openstack.org/raw/155864/
infile = 'sample.json'
with open(infile, 'r') as f:
input_str = f.read()
print('payload has %d bytes' % len(input_str))
10. times = []
for pattern in strutils._SANITIZE_PATTERNS_2:
print('ntesting %s' % pattern.pattern)
t = timeit.Timer(
"re.sub(pattern, r'g<1>***g<2>', payload)",
"""
import re
payload = '''%s'''
pattern = re.compile(r'''%s''')
""" % (input_str, pattern.pattern))
result = t.timeit(1)
print(result)
times.append((result, pattern.pattern))
print('nslowest to fastest:')
times = reversed(sorted(times))
for t in times:
print(‘%s - %s’ % t)
print('ntesting all patterns')
t = timeit.Timer(
"strutils.mask_password('''" + input_str + "''')",
"import strutils",
)
print(t.timeit(1))
24. def mask_password(message, secret="***"):
"""Replace password with 'secret' in message.
:param message: The string which includes security information.
:param secret: value with which to replace passwords.
:returns: The unicode value of message with the password fields masked.
"""
try:
message = six.text_type(message)
except UnicodeDecodeError:
# NOTE(jecarey): Temporary fix to handle cases where message is a
# byte string. A better solution will be provided in Kilo.
pass
# NOTE(ldbragst): Check to see if anything in message contains any key
# specified in _SANITIZE_KEYS, if not then just return the message since
# we don't have to mask any passwords.
if not any(key in message for key in _SANITIZE_KEYS):
return message
substitute = r'g<1>' + secret + r'g<2>'
for pattern in _SANITIZE_PATTERNS_2:
message = re.sub(pattern, substitute, message)
substitute = r'g<1>' + secret
for pattern in _SANITIZE_PATTERNS_1:
message = re.sub(pattern, substitute, message)
return message
29. def mask_password(message, secret="***"):
"""Replace password with 'secret' in message.
:param message: The string which includes security information.
:param secret: value with which to replace passwords.
:returns: The unicode value of message with the password fields masked.
"""
try:
message = six.text_type(message)
except UnicodeDecodeError:
# NOTE(jecarey): Temporary fix to handle cases where message is a
# byte string. A better solution will be provided in Kilo.
pass
substitute1 = r'g<1>' + secret
substitute2 = r'g<1>' + secret + r'g<2>'
# NOTE(ldbragst): Check to see if anything in message contains any key
# specified in _SANITIZE_KEYS, if not then just return the message since
# we don't have to mask any passwords.
for key in _SANITIZE_KEYS:
if key in message:
for pattern in _SANITIZE_PATTERNS_2[key]:
message = re.sub(pattern, substitute2, message)
for pattern in _SANITIZE_PATTERNS_1[key]:
message = re.sub(pattern, substitute1, message)
return message
30. # NOTE(ldbragst): Let's build a list of regex objects using the list of
# _SANITIZE_KEYS we already have. This way, we only have to add the new key
# to the list of _SANITIZE_KEYS and we can generate regular expressions
# for XML and JSON automatically.
_SANITIZE_PATTERNS_2 = {}
_SANITIZE_PATTERNS_1 = {}
# NOTE(dhellmann): Keep a separate list of patterns by key so we only
# need to apply the substitutions for keys we find using a quick "in"
# test.
for key in _SANITIZE_KEYS:
_SANITIZE_PATTERNS_1[key] = []
_SANITIZE_PATTERNS_2[key] = []
for pattern in _FORMAT_PATTERNS_2:
reg_ex = re.compile(pattern % {'key': key}, re.DOTALL)
_SANITIZE_PATTERNS_2[key].append(reg_ex)
for pattern in _FORMAT_PATTERNS_1:
reg_ex = re.compile(pattern % {'key': key}, re.DOTALL)
_SANITIZE_PATTERNS_1[key].append(reg_ex)
31. >>> import strutils
>>> strutils._SANITIZE_PATTERNS_2
{'admin_pass': [<_sre.SRE_Pattern object at 0x7fbf4361d9b0>, <_sre.SRE_Pattern
object at 0x7fbf43620660>, <_sre.SRE_Pattern object at 0x7fbf43621200>,
<_sre.SRE_Pattern object at 0x7fbf43621ac0>, <_sre.SRE_Pattern object at
0x7fbf43627e70>, <_sre.SRE_Pattern object at 0x7fbf43629a30>, <_sre.SRE_Pattern
object at 0x7fbf4362a3f0>, <_sre.SRE_Pattern object at 0x7fbf43629fc0>],
'auth_password': [<_sre.SRE_Pattern object at 0x7fbf436322d0>, <_sre.SRE_Pattern
object at 0x7fbf436324a0>, <_sre.SRE_Pattern object at 0x7fbf43632640>,
<_sre.SRE_Pattern object at 0x7fbf43632800>, <_sre.SRE_Pattern object at
0x7fbf43631d60>, <_sre.SRE_Pattern object at 0x7fbf43633200>, <_sre.SRE_Pattern
object at 0x7fbf43633690>, <_sre.SRE_Pattern object at 0x7fbf43633e90>], …}
>>> strutils._SANITIZE_PATTERNS_2.keys()
['admin_pass', 'auth_password', 'adminPass', 'auth_token', 'secret_uuid',
'admin_password', 'new_pass', ‘password']
>>> strutils._SANITIZE_PATTERNS_2[‘admin_pass’]
[<_sre.SRE_Pattern object at 0x7fbf4361d9b0>, …]
32. times = []
for pattern in strutils._SANITIZE_PATTERNS_2['admin_pass']:
print('ntesting %s' % pattern.pattern)
t = timeit.Timer(
"re.sub(pattern, r'g<1>***g<2>', payload)",
"""
import re
payload = '''%s'''
pattern = re.compile(r'''%s''')
""" % (input_str, pattern.pattern))
result = t.timeit(1)
print(result)
times.append((result, pattern.pattern))
print('nslowest to fastest:')
times = reversed(sorted(times))
for t in times:
print('%s - %s ' % t)
print('ntesting all patterns')
t = timeit.Timer(
"strutils.mask_password('''" + input_str + "''')",
"import strutils",
)
print(t.timeit(1))