text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
DevOps DevOps Interview Questions, From beginner to expert level DevOps Professional. These questions covers a wide range of topics any DevOps professional needed to know to nail an interview. Table of Contents: CHAPTER 1: DevOps Introduction CHAPTER 2: Gradle DevOps Interview Questions CHAPTER 3: Groovy DevOps Interview Questions CHAPTER 4: Maven DevOps Interview Questions CHAPTER 5: Linux DevOps Interview Questions CHAPTER 6: GIT DevOps Interview Questions CHAPTER 7: Continuous Integration Interview Questions CHAPTER 8: Amazon AWS DevOps Interview Questions CHAPTER 9: Splunk DevOps Interview Questions CHAPTER 10: Log4J DevOps Interview Questions CHAPTER 11: Docker DevOps Interview Questions CHAPTER 12: VmWare DevOps Interview Questions CHAPTER 13: DevOps Security Interview Questions CHAPTER 14: DevOps Testing Interview Questions CHAPTER 15: Summary CHAPTER 16: DevOps Interview Questions PDF Question: What Are Benefits Of DevOps? DevOps is gaining more popularity day by day. Here are some benefits of implementing DevOps Practice. Release Velocity: DevOps enable organizations to achieve a great release velocity. We can release code to production more often and without any hectic problems. Development Cycle: DevOps shortens the development cycle from initial design to production. Full Automation: DevOps helps to achieve full automation from testing, to build, release and deployment. Deployment Rollback: In DevOps, we plan for any failure in deployment rollback due to a bug in code or issue in production. This gives confidence in releasing feature without worrying about downtime for rollback. Defect Detection: With DevOps approach, we can catch defects much earlier than releasing to production. It improves the quality of the software. Collaboration: With DevOps, collaboration between development and operations professionals increases. Performance-oriented: With DevOps, organization follows performance-oriented culture in which teams become more productive and more innovative. Question: What Is The Typical DevOps workflow? The typical DevOps workflow is as follows: - Atlassian Jira for writing requirements and tracking tasks. - Based on the Jira tasks, developers checking code into GIT version control system. - The code checked into GIT is built by using Apache Maven. - The build process is automated with Jenkins. - During the build process, automated tests run to validate the code checked in by a developer. - Code built on Jenkins is sent to organization’s Artifactory. - Jenkins automatically picks the libraries from Artifactory and deploys it to Production. - During Production deployment, Docker images are used to deploy same code on multiple hosts. - Once a code is deployed to Production, we use monitoring tools like ngios are used to check the health of production servers. - Splunk based alerts inform the admins of any issues or exceptions in production. Question: DevOps Vs Agile? Agile is a set of values and principles about how to develop software in a systematic way. Where as DevOPs is a way to quickly, easily and repeatably move that software into production infrastructure, in a safe and simple way. In oder to achieve that we use a set of DevOps tools and techniques. Question: What Is The Most Important Thing DevOps Helps Us To Achieve? Most important aspect of DevOps is to get the changes into production as quickly as possible while minimizing risks in software quality assurance and compliance. This is the primary objective of DevOps. Question: What Are Some DevOps tools. Here is a list of some most important DevOps tools - Git - Jenkins, Bamboo - Selenium - Puppet, BitBucket - Chef - Ansible, Artifactory - Nagios - Docker - Monit - ELK –Elasticsearch, Logstash, Kibana - Collectd/Collect Question: How To Deploy Software? Code is deployed by adopting continuous delivery best practices. Which means that checked in code is built automatically and then artifacts are published to repository servers. On the application severs there are deployment triggers usually timed by using cron jobs. All the artifacts are then downloaded and deployed automatically. Gradle DevOps Interview Questions Question: What is Gradle? Gradle is an open-source build automation system that builds upon the concepts of Apache Ant and Apache Maven. Gradle has a proper programming language instead of XML configuration file and the language is called ‘Groovy’. Gradle uses a directed acyclic graph ("DAG") to determine the order in which tasks can be run. Gradle was designed for multi-project builds, which can grow to be quite large. It supports incremental builds by intelligently determining which parts of the build tree are up to date, any task dependent only on those parts does not need to be re-executed. Question: What Are Advantages of Gradle? Gradle provides many advantages and here is a list - Declarative Builds: Probably one of the biggest advantage of Gradle is Groovy language. Gradle provides declarative language elements. Which providea build-by-convention support for Java, Groovy, Web and Scala. - Structured Build: Gradle allows developers to apply common design principles to their build. It provides a perfect structure for build, so that well-structured and easily maintained, comprehensible build structures can be built. - Deep API: Using this API, developers can monitor and customize its configuration and execution behaviors. - Scalability: Gradle can easily increase productivity, from simple and single project builds to huge enterprise multi-project builds. - Multi-project builds: Gradle supports multi-project builds and also partial builds. - Build management: Gradle supports different strategies to manage project dependencies. - First build integration tool − Gradle completely supports ANT tasks, Maven and lvy repository infrastructure for publishing and retrieving dependencies. It also provides a converter for turning a Maven pom.xml to Gradle script. - Ease of migration: Gradle can easily adapt to any project structure. - Gradle Wrapper: Gradle Wrapper allows developers to execute Gradle builds on machines where Gradle is not installed. This is useful for continuous integration of servers. - Free open source − Gradle is an open source project, and licensed under the Apache Software License (ASL). -. Question: Why Gradle Is Preferred Over Maven or Ant? There isn't a great support for multi-project builds in Ant and Maven. Developers end up doing a lot of coding to support multi-project builds. Also having some build-by-convention is nice and makes build scripts more concise. With Maven, it takes build by convention too far, and customizing your build process becomes a hack. Maven also promotes every project publishing an artifact. Maven does not support subprojects to be built and versioned together. But with Gradle developers can have the flexibility of Ant and build by convention of Maven. Groovy is easier and clean to code than XML. In Gradle, developers can define dependencies between projects on the local file system without the need to publish artifacts to repository. Question: Gradle Vs Maven The following is a summary of the major differences between Gradle and Apache Maven: Flexibility: Google chose: - Incrementally:Gradle avoids work by tracking input and output of tasks and only running what is necessary. - Build Cache:Reuses the build outputs of any other Gradle build with the same inputs. - Gradle Daemon:A long-lived process that keeps build information "hot" in memory. User Experience Maven's. Question: What are Gradle Build Scripts? Gradle builds a script file for handling projects and tasks. Every Gradle build represents one or more projects. A project represents a library JAR or a web application. Question: What is Gradle Wrapper? The wrapper is a batch script on Windows, and a shell script for other operating systems. Gradle Wrapper is the preferred way of starting a Gradle build. When a Gradle build is started via the wrapper, Gradle will automatically download and run the build. Question: What is Gradle Build Script File Name? This type of name is written in the format that is build.gradle. It generally configures the Gradle scripting language. Question: How To Add Dependencies In Gradle? In order to make sure that dependency for your project is added, you need to mention the configuration dependency like compiling the block dependencies of the build.gradle file. Question: What Is Dependency Configuration? Dependency configuration comprises of the external dependency, which you need to install well and make sure the downloading is done from the web. There are some key features of this configuration which are: - Compilation: The project which you would be starting and working on the first needs to be well compiled and ensure that it is maintained in the good condition. - Runtime: It is the desired time which is required to get the work dependency in the form of collection. - Test Compile: The dependencies check source requires the collection to be made for running the project. - Test runtime: This is the final process which needs the checking to be done for running the test that is in a default manner considered to be the mode of runtime Question: What Is Gradle Daemon? Question: What Is Dependency Management in Gradle?. Gradle has built-in support for dependency management and lives up the task of fulfilling typical scenarios encountered in modern software projects. Question: What Are Benefits Of Daemon in Gradle 3.0 Here are some of the benefits of Gradle daemon - It has good UX - It is very powerful - It is aware of the resource - It is well integrated with the Gradle Build scans - It has been default enabled Question: What Is Gradle Multi-Project Build? Multi-project builds helps with modularization. It allows a person. Question: What Is Gradle Build Task? Gradle Build Tasks is made up of one or more projects and a project represents what is been done with Gradle. Some key of features of Gradle Build Tasks are: - Task has life cycled methods [do first, do last] - Build Scripts are code - Default tasks like run, clean etc - Task dependencies can be defined using properties like dependsOn Question: What is Gradle Build Life Cycle? Gradle Build life cycle consists of following three steps -Initialization phase: In this phase the project layer or objects are organized -Configuration phase: In this phase all the tasks are available for the current build and a dependency graph is created -Execution phase: In this phase tasks are executed. Question: What is Gradle Java Plugin? The Java plugin adds Java compilation along with testing and bundling capabilities to the project. It is introduced in the way of a SourceSet which act as a group of source files complied and executed together. Question: What is Dependency Configuration? A set of dependencies is termed as dependency configuration, which contains some external dependencies for download and installation. Here are some key features of dependency configuration are: Compile: The project must be able to compile together Runtime: It is the required time needed to get the dependency work in the collection. Test Compile: The check source of the dependencies is to be collected in order to run the project. Test Runtime: The final procedure is to check and run the test which is by default act as a runtime mode. Groovy DevOps Interview Questions Question: What is Groovy? Apache Groovy is a object-oriented programming language for the Java platform. It is both a static and dynamic language with features similar to those of Python, Ruby, Perl,. Groovy supports closures, multiline strings, and expressions embedded in strings. And much of Groovy's power lies in its ASTtransformations, triggered through annotations. Question: Why Groovy Is Gaining Popularity? Here are few reasons for popularity of Groovy - Familiar OOP language syntax. - Extensive stock of various Java libraries - Increased expressivity (type less to do more) - Dynamic typing (lets you code more quickly, at least initially) - Closures - Native associative array/key-value mapping support (you can create an associative array literal) - String interpolation (cleaner creation of strings displaying values) - Regex's being first class citizens Question: What Is Meant By Thin Documentation In Groovy Groovy is documented very badly. In fact the core documentation of Groovy is limited and there is no information regarding the complex and run-time errors that happen. Developers are largely on there own and they normally have to figure out the explanations about internal workings by themselves. Question: How To Run Shell Commands in Groovy? Groovy adds the execute method to String to make executing shells fairly easy println "ls".execute().text Question: In How Many Platforms you can use Groovy? These are the infrastructure components where we can use groovy: -Application Servers -Servlet Containers -Databases with JDBC drivers -All other Java-based platforms Question: Can Groovy Integrate With Non Java Based Languages? It is possible but in this case the features are limited. Groovy cannot be made to handle all the tasks in a manner it has to. Question: What are Pre-Requirements For Groovy? Installing and using Groovy is easy. Groovy does not have complex system requirements. It is OS independent. Groovy can perform optimally in every situation.There are many Java based components in Groovy,which make it even more easier to work with Java applications. Questions: What Is Closure In Groovy?. Question: What is ExpandoMeta Class In Groovy? Through this class programmers can add properties, constructors, methods and operations in the task. It is a powerful option available in the Groovy. By default this class cannot be inherited and users need to call explicitly. The command for this is “ExpandoMetaClass.enableGlobally()”. Question: What Are Limitations Of Groovy? Groovy has some limitations. They are described. Question: How To Write HelloWorld Program In Groovy The following is a basic Hello World program written in Groovy: class Test { static void main(String[] args) { println('Hello World'); } } Question: How To Declare String In Groovy? In Groovy, the following steps are needed to declare a string. - The string is closed with single and double qotes. - It contains Groovy Expressions noted in ${} - Square bracket syntax may be applied like charAt(i) Question: Differences Between Java And Groovy? Groovy tries to be as natural as possible for Java developers. Here are all the major differences between Java and Groovy. -Default imports importstatement to use them: - java.io.* - java.lang.* - java.math.BigDecimal - java.math.BigInteger - java.net.* - java.util.* - groovy.lang.* - groovy.util.* -Multi-methods -Array initializers { … }block is reserved for closures. That means that you cannot create array literals with this syntax: int[] arraySyntex = { 6, 3, 1} int[] arraySyntex = [1,2,3] -ARM blocks -GStrings GStringvalues, Groovy may fail with compile error or produce subtly different code if a class with Stringliteral containing a dollar character is compiled with Groovy and Java compiler. GStringand Stringif an API declares the type of a parameter, beware of Java APIs that accept an Objectparameter and then check the actual type. -String and Character literals String, and double-quoted result in Stringor GString, depending whether there is interpolation in the literal. assert 'c'.getClass()==String assert "c".getClass()==String assert "c${1}".getClass() in GString Stringto charonly when assigning to a variable of type char. When calling methods with arguments of type charwe) { } charthere' -Behaviour of == In Java == means equality of primitive types or identity for objects. In Groovy == translates to a.compareTo(b)==0, if they are Comparable, and a.equals(b) otherwise. To check for identity, there is is. E.g. a.is(b). Question: How To Test Groovy Application? The Groovy programming language comes with great support for writing tests. In addition to the language features and test integration with state-of-the-art testing libraries and frameworks. The Groovy ecosystem has born a rich set of testing libraries and frameworks. Groovy Provides following testing capabilities Junit Integrations Spock for specifications Geb for Functional Test Groovy also. Question: What Are Power Assertions In Groovy? Writing tests means formulating assumptions by using assertions. In Java this can be done by using the assertkeyword. But Groovy comes with a powerful variant of assertalso known as power assertion statement. assertdiffers from the Java version in its output given the boolean expression validates to false: def x = 1 assert x == 2 // Output: // // Assertion failed: // assert x == 2 // | | // 1 false java.lang.AssertionErrorthat is thrown whenever the assertion can not be validated successfully, contains an extended version of the original exception message. The power assertion output shows evaluation results from the outer to the inner expression. toString-enabled classes: def x = [1,2,3,4,5] assert (x << 6) == [6,7,8,9,10] // Output: // // Assertion failed: // assert (x << 6) == [6,7,8,9,10] // | | | // | | false // | [1, 2, 3, 4, 5, 6] // [1, 2, 3, 4, 5, 6] Question: Can We Use Design Patterns In Groovy? Design patterns can also be used with Groovy. Here are important points -) Question: How To Parse And Produce JSON Object In Groovy? Groovy comes with integrated support for converting between Groovy objects and JSON. The classes dedicated to JSON serialisation and parsing are found in the groovy.jsonpackage. Question: What Is Difference Between XmlParser And XmlSluper? XmlParser and XmlSluper are used for parsing XML with Groovy. Both have the same approach to parse an xml. Both come with a bunch of overloaded parse methods plus some special methods such as parseText, parseFile and others. XmlSlurper def text = ''' <list> <technology> <name>Groovy</name> </technology> </list> ''' def list = new XmlSlurper().parseText(text) assert list instanceof groovy.util.slurpersupport.GPathResult assert list.technology.name == 'Groovy' def text = ''' <list> <technology> <name>Groovy</name> </technology> </list> ''' def list = new XmlParser().parseText(text) assert list instanceof groovy.util.Node assert list.technology.name.text() == 'Groovy' XMLParserand XMLSlurperfirst: - Both are based on SAXso they both are low memory footprint - Both can update/transform the XML XmlSlurperevaluates the structure lazily. So if you update the xml you’ll have to evaluate the whole tree again. XmlSlurperreturns GPathResultinstances when parsing XML XmlParserreturns Nodeobjects when parsing XML - If you want to transform an existing document to another then XmlSlurperwill be the choice If you want to update and read at the same time then XmlParseris the choice. Maven DevOps Interview Questions Question: What is Maven? Maven is a build automation tool used primarily for Java projects. Maven addresses two aspects of building software: First: It describes how software is built. This local cache of downloaded artifacts can also be updated with artifacts created by local projects. Public repositories can also be updated. Question: What Are Benefits Of Maven? - One of the biggest benefit of Maven is that its design regards all projects as having a certain structure and a set of supported task work-flows. - Maven has quick project setup, no complicated build.xml files, just a POM and go - All developers in a project use the same jar dependencies due to centralized POM. - In Maven getting a number of reports and metrics for a project "for free" - It reduces the size of source distributions, because jars can be pulled from a central location - Maven lets developers get your package dependencies easily - With Maven there is no need to add jar files manually to the class path Question: What Are Build Life cycles In Maven? Build lifecycle is a list of named phases that can be used to Question: What Is Meant By Build Tool? like Maven, Gradle or ANT allows the build process to be more consistent. Question: What Is Dependency Management Mechanism In Gradle? Maven's dependency-handling mechanism is organized around a coordinate system identifying individual artifacts such as software libraries. Question: What Is Central Repository Search Engine? The Central Repository Search Engine, can be used to find out coordinates for different open-source libraries and frameworks. Question: What are Plugins In Maven? Most of Maven's functionality is in plugins. A plugin provides a set of goals that can be executed using the following syntax: mvn [plugin-name]:[goal-name] mvn compiler:compile. There are Maven plugins for building, testing, source control management, running a web server, generating Eclipse project files, and much more. Plugins are introduced and configured in a <plugins>-section of a pom.xmlfile. Some basic plugins are included in every project by default, and they have sensible default settings. Questions: What Is Difference Between Maven And ANT? Question: What is POM In Maven? by default. The Super POM provides default configuration, such as default source directories, default plugins, and so on. Question: What Is Maven Archetype? Archetype is a Maven project templating toolkit. An archetype is defined as an original pattern or model from which all other things of the same kind are made. Question: What Is Maven Artifact? In Maven artifact is simply a file or JAR that is deployed to a Maven repository. An artifact has -Group ID -Artifact ID -Version string. The three together uniquely identify the artifact. All the project dependencies are specified as artifacts. Question: What Is Goal In Maven? In Maven a goal represents a specific task which contributes to the building and managing of a project. It may be bound to 1 or many build phases. A goal not bound to any build phase could be executed outside of the build lifecycle by its direct invocation. Question: What Is Build Profile? In Maven a build profile is a set of configurations. This set is used to define or override default behaviour of Maven build. Build profile helps the developers to customize the build process for different environments. For example you can set profiles for Test, UAT, Pre-prod and Prod environments each with its own configurations etc. Question: What Are Build Phases In Maven? There are 6 build phases. -Validate -Compile -Test -Package -Install -Deploy Question: What Is Target, Source & Test Folders In Mavn? Target: folder holds the compiled unit of code as part of the build process. Source: folder usually holds java source codes. Test: directory contains all the unit testing codes. Question: What Is Difference Between Compile & Install? Compile: is used to compile the source code of the project Install: installs the package into the local repository, for use as a dependency in other projects locally.Design patterns can also be used with Groovy. Here are important points Question: How To Activate Maven Build Profile? A Maven Build Profile can be activated in following ways - Using command line console input. - By using Maven settings. - Based on environment variables (User/System variables). Linux DevOps Interview Questions Question: What is Linux? Linux is the best-known and most-used open source operating system. As an operating system, Linux is a software that sits underneath all of the other software on a computer, receiving requests from those programs and relaying these requests to the computer’s hardware. In many ways, Linux is similar to other operating systems such as Windows, OS X, or iOS operating system is consist of 3 components which are as below: - Kernel: Linux is a monolithic kernel that is free and open source software that is responsible for managing hardware resources for the users. - System Library: System Library plays a vital role because application programs access Kernels feature using system library. - System Utility: System Utility performs specific and individual level tasks. Question: What Is Difference Between Linux & Unix?. Question: What Is BASH? BASH stands for Bourne Again Shell. BASH is the UNIX shell for the GNU operating system. So, BASH is the command language interpreter that helps you to enter your input, and thus you can retrieve information. In a straightforward language, BASH is a program that will understand the data entered by the user and execute the command and gives output. Question: What Is CronTab? The crontab (short for "cron table") is a list of commands that are scheduled to run at regular time intervals on computer system. The crontab command opens the crontab for editing, and lets you add, remove, or modify scheduled tasks. The daemon which reads the crontab and executes the commands at the right time is called cron. It's named after Kronos, the Greek god of time. Command syntax crontab [-u user] file crontab [-u user] [-l | -r | -e] [-i] [-s] Question: What Is Daemon In Linux? A daemon is a type of program on Linux operating systems that runs. Question: What Is Process In Linux?:Interactive processes are run interactively by a user at the command line -Batch Question: What Is CLI In Linux? CLI (Command Line Interface) is a type of human-computer interface that relies solely on textual input and output. That is, the entire display screen, or the currently active portion of it, shows only characters (and no images), and input is usually performed entirely with a keyboard. Questions: What Is Linux). There are three types of Kernals Microkernel:A microkernel takes the approach of only managing what it has to: CPU, memory, and IPC. Pretty much everything else in a computer can be seen as an accessory and can be handled in user mode. Monolithic Kernel:Monolithic kernels are the opposite of microkernels because they encompass not only the CPU, memory, and IPC, but they also include things like device drivers, file system management, and system server calls Hybrid Kernel:Hybrid kernels have the ability to pick and choose what they want to run in user mode and what they want to run in supervisor mode.. Question: What Is Partial Backup In Linux? Partial backup refers to selecting only a portion of file hierarchy or a single partition to back up. Question: What Is Root Account? The root account a system administrator account. It provides you full access and control of the system. Admin can create and maintain user accounts, assign different permission for each account etc Question: What Is Difference Between Cron and Anacron? One of the main difference between cron and anacron jobs is that cron works on the system that are running continuously. While anacron is used for the systems that are not running continuously. - Other difference between the two is cron jobs can run every minute, but anacron jobs can be run only once a day. - Any normal user can do the scheduling of cron jobs, but the scheduling of anacron jobs can be done by the superuser. Question: What Is Linux Loader? Linux Loader is a boot loader for Linux operating system. It loads Linux into into the main memory so that it can begin its operations. Question: What Is Swap Space?. Question: What Are Linux Distributors? There are around six hundred Linux distributors. Let us see some of the important ones - UBuntu: It is a well known Linux Distribution with a lot of pre-installed apps and easy to use repositories libraries. It is very easy to use and works like MAC operating system. - Linux Mint: It uses cinnamon and mate desktop. It works on windows and should be used by newcomers. - Debian: It is the most stable, quicker and user-friendly Linux Distributors. - Fedora: It is less stable but provides the latest version of the software. It has GNOME3 desktop environment by default. - Red Hat Enterprise: It is to be used commercially and to be well tested before release. It usually provides the stable platform for a long time. - Arch Linux: Every package is to be installed by you and is not suitable for the beginners. Question: Why Do Developers Use MD5? MD5 is an encryption method so it is used to encrypt the passwords before saving. Question: What Are File Permissions In Linux? There are 3 types of permissions in Linux - Read: User can read the file and list the directory. - Write: User can write new files in the directory . - Execute: User can access and run the file in a directory. Question: Memory Management In Linux? It is always required to keep a check on the memory usage in order to find out whether the user is able to access the server or the resources are adequate. There are roughly 5 methods that determine the total memory used by the Linux. This is explained as below - Free command: This is the most simple and easy to use the command to check memory usage. For example: ‘$ free –m’, the option ‘m’ displays all the data in MBs. - /proc/meminfo: The next way to determine the the memory usage along with other details. Question: Granting Permissions In Linux? System administrator or the owner of the file can grant permissions using the ‘chmod’ command. Following symbols are used while writing permissions chmod +x Question: What Are Directory Commands In Linux? Here are few important directory commands in Linux -. Question: What Is Shell Script In Linux?. We have covered many shell features, but we have focused on those features most often used directly on the command line. The shell also provides a set of features usually (but not always) used when writing programs. Question: Which Tools Are Used For Reporting Statistics In Linux? Some of the popular and frequently used system resource generating tools available on the Linux platform are - vmstat - netstat - iostat - ifstat - mpstat. These are used for reporting statistics from different system components such as virtual memory, network connections and interfaces, CPU, input/output devices and more. Question: What Is Dstat In Linux? dstat is a powerful, flexible and versatile tool for generating Linux system resource statistics, that is a replacement for all the tools mentioned in above Question: Types Of Processes In Linux?. Question: Creatin. Question: Creation Of Processes In Linux?. Question: What Is Init Process Linux? lnit. It functions as an adoptive parent for all orphaned processes. You can use the pidof command to find the ID of a process: # pidof systemd # pidof top # pidof httpd Find Linux Process ID To find the process ID and parent process ID of the current shell, run: $ echo $$ $ echo $PPID Question: What Are Different States Of A Processes. Question: 3. glances – System Monitoring Tool glances is a relatively new system monitoring tool with advanced features: #glances Question: How To Control Process? Question: Can We Send signals To Processes In Linux? The fundamental way of controlling processes in Linux is by sending signals to them. There are multiple signals that you can send to a process, to view all the signals run: $ kill -l List All Linux Signals]. Question: How To Change Priority Of A Processes In Linux? List Linux Running Processes GIT DevOps Interview Questions Question:. By far, the most widely used modern version control system in the world today is Git. Git is a mature, actively maintained open source project originally developed in 2005 by Linus Torvald. Git is an example of a Distributed Version Control System, In Git, every developer's working copy of the code is also a repository that can contain the full history of all changes. Question: What Are Benefits Of GIT? Here are some of the advantages of using Git - Ease of use - Data redundancy and replication - High availability - Superior disk utilization and network performance - Only one .git directory per repository - Collaboration friendly - Any kind of projects from large to small scale can use GIT Question: What Is Repository In. - There is only one .git directory, in the root directory of the project. - The repository is stored in files alongside the project. There is no central server repository. Question: What Is Staging Area In GIT? Staging is a step before the commit process in git. That is, a commit in git is performed in two steps: -Staging and -Actual commit As long as a change set is in the staging area, git allows you to edit it as you like (replace staged files with other versions of staged files, remove changes from staging, etc.) Question: What Is GIT STASH?. Question: How To Revert Commit In GIT? Given one or more existing commits, revert the changes that the related patches introduce, and record some new commits that record them. This requires your working tree to be clean (no modifications from the HEAD commit). git-revert - Revert some existing commits SYNOPSIS git revert [--[no-]edit] [-n] [-m parent-number] [-s] [-S[<keyid>]] <commit>… git revert --continue git revert --quit git revert --abort Question: How To Delete Remote Repository In GIT? Use the git remote rm command to remove a remote URL from your repository. The git remote rm command takes one argument: - A remote name, for example, destination Questions: What. Question: What Is Difference Between GIT and Subversion? Here is a summary of Differences between GIT and Subversion - Git is a distributed VCS; SVN is a non-distributed VCS. - Git has a centralized server and repository; SVN does not have a centralized server or repository. - is distributed under GNU, and its maintenance overseen by Junio Hamano; Apache Subversion, or SVN, is distributed under the open source license. Question: What Is Difference Between GIT Fetch & GIT Pull? GIT fetch – It downloads only the new data from the remote repository and does not integrate any of the downloaded data into your working files. Providing a view of the data is all it does. GIT pull – It downloads as well as merges the data from the remote repository into the local working files. This may also lead to merging conflicts if the user’s local changes are not yet committed. Using the “GIT stash” command hides the local changes. Question: What is Git fork?. Question: What is difference between fork and branch? A fork is really a Github (not Git) construct to store a clone of the repo in your user account. As a clone, it will contain all the branches in the main repo at the time you made the fork. Question: What Is Cherry Picking In GIT? Cherry picking in git means to choose a commit from one branch and apply it onto another. This is in contrast with other ways such as merge and rebase which normally applies many commits onto a another branch. Make sure you are on the branch you want apply the commit to. git checkout master Execute the following: git cherry-pick <commit-hash> Question: What Language GIT Is Written In? Much of Git is written in C, along with some BASH scripts for UI wrappers and other bits. Question: How To Rebase Master In GIT?. Question: What is ‘head’ in git and how many heads can be created in a repository? There can be any number of heads in a GIT repository. By default there is one head known as HEAD in each repository in GIT. HEAD is a ref (reference) to the currently checked out commit. In normal states, it's actually a symbolic ref to the branch user has checked out. if you look at the contents of .git/HEAD you'll see something like "ref: refs/heads/master". The branch itself is a reference to the commit at the tip of the branch Question: Name some GIT commands and also explain their functions? Here are some most important GIT commands - GIT diff – It shows the changes between commits, commits and working tree. - GIT status – It shows the difference between working directories and index. - GIT stash applies – It is used to bring back the saved changes on the working directory. - GIT rm – It removes the files from the staging area and also of the disk. - GIT log – It is used to find the specific commit in the history. - GIT add – It adds file changes in the existing directory to the index. - GIT reset – It is used to reset the index and as well as the working directory to the state of the last commit. - GIT checkout – It is used to update the directories of the working tree with those from another branch without merging. - GIT Is tree – It represents a tree object including the mode and the name of each item. - GIT instaweb – It automatically directs a web browser and runs the web server with an interface into your local repository. Question: What is a “conflict” in GIT and how is it resolved? When a commit that has to be merged has some changes in one place, which also has the changes of current commit, then the conflict arises. The GIT will not be able to predict which change will take the precedence. In order to resolve the conflict in GIT: we have to edit the files to fix the conflicting changes and then add the resolved files by running the “GIT add” command; later on, to commit the repaired merge run the “GIT commit” command. GIT identifies the position and sets the parents of the commit correctly. Question: How To Migrate From Subversion To GIT? SubGIT is a tool for smooth and stress-free subversion to GIT migration and also a solution for a company-wide subversion to GIT migration that is: - It allows to make use of all GIT and subversion features. - It provides genuine stress-free migration experience. - It doesn’t require any change in the infrastructure that is already placed. - It is considered to be much better than GIT-SVN Question: What Is Index In GIT? The index is a single, large, binary file in under .git folder, which lists all files in the current branch, their sha1 checksums, time stamps and the file name. Before completing the commits, it is formatted and reviewed in an intermediate area known as Index also known as the staging area. Question: What is a bare Git repository? A bare Git repository is a repository that is created without a Working Tree. git init --bare Question: WHow. Question:. Question:: How To Setup A Script To Run Every Time a Repository Receives New Commits Through Push? To configure a script to run every time a repository receives new commits through push, one needs to define either a pre-receive, update, or a post-receive hook depending on when exactly the script needs to be triggered. Pre-receive hook in the destination repository is invoked when commits are pushed to it. Any script bound to this hook will be executed before any references are updated. This is a useful hook to run scripts that help enforce development policies. Update hook works in a similar manner to pre-receive hook, and is also triggered before any updates are actually made. However, the update hook is called once for every commit that has been pushed to the destination repository. Finally, post-receive hook in the repository is invoked after the updates have been accepted into the destination repository. This is an ideal place to configure simple deployment scripts, invoke some continuous integration systems, dispatch notification emails to repository maintainers, etc. Hooks are local to every Git repository and are not versioned. Scripts can either be created within the hooks directory inside the “.git” directory, or they can be created elsewhere and links to those scripts can be placed within the directory. Question: What Is Commit Hash?. Question: What Is Conflict In GIT?:. Question: What. Question: Question: What Is GIT reset command? Git reset command is used to reset current HEAD to a specific state. By default it reverses the action of git add command. So we use git reset command to undo the changes of git add command. Reference: Any reference to parent commit objects Question:. Continuos Integration Interview Questions Question: What is Continuos Integration?. Question: What Is Build Automation? Build automation is the process of automating the creation of a software build and the associated processes. Including compiling computer source code into binary code, packaging binary code, and running automated tests. Question: What Is. Question: How Continuous Integration Implemented? Different tools for supporting Continuous Integration are Hudson, Jenkins and Bamboo. Jenkins is the most popular one currently. They provide integration with various version control systems and build tools. Question: How Continuous Integration process does work? Whenever developer commits changes in version control system, then Continuous Integration server detects that changes are committed. And goes through following process - Continuous Integration server retrieves latest copy of changes. - It build code with new changes in build tools. - If build fails notify to developer. - After build pass run automated test cases if test cases fail notify to developer. - Create package for deployment environment. Question: What Are The Software Required For Continuous Integration process? Here are the minimum tools you need to achieve CI - Source code repository : To commit code and changes for example git. - Server: It is Continuous Integration software for example Jenkin, Teamcity. - Build tool: It builds application on particular way for example maven, gradle. - Deployment environment : On which application will be deployed. Question:. Questions: What is a Jenkins Pipeline? Jenkins Pipeline (or simply “Pipeline”) is a suite of plugins which supports implementing and integrating continuous delivery pipelines into Jenkins.. Question: What is the difference between Maven, Ant,Gradle and Jenkins ? Maven and Ant are Build Technologies whereas Jenkins is a continuous integration tool. Question: Why do we use Jenkins? Jenkins is an open-source continuous integration software tool written in the Java programming language for testing and reporting on isolated changes in a larger code base in real time. The Jenkins software enables developers to find and solve defects in a code base rapidly and to automate testing of their builds. Question: What are CI Tools?? - Jenkins - TeamCity - Travis CI - Go CD - Bamboo - GitLab CI - CircleCI - Codeship Question: Which SCM tools Jenkins supports?? Jenkins supports version control tools, including AccuRev, CVS, Subversion, Git, Mercurial, Perforce, ClearCase and RTC, and can execute Apache Ant, Apache Maven and arbitrary shell scripts and Windows batch commands. Question: Why do we use Pipelines in Jenkins? Pipeline adds a powerful set of automation tools onto Jenkins, supporting use cases that span from simple continuous integration to comprehensive continuous delivery continuous delivery requirements, including the ability to fork/join, loop, and perform work in parallel. - Extensible: The Pipeline plugin supports custom extensions to its DSL and multiple options for integration with other plugins. Question: How do you create Multibranch Pipeline in Jenkins? The Multi branch Pipeline project type enables you to implement different Jenkins files for different branches of the same project. In a Multi branch Pipeline project, Jenkins automatically discovers, manages and executes Pipelines for branches which contain a Jenkins file in source control. Question: What are Jobs in Jenkins?? Jenkins can be used to perform the typical build server work, such as doing continuous/official/nightly builds, run tests, or perform some repetitive batch tasks. This is called “free-style software project” in Jenkins. Question: How do you configuring automatic builds in Jenkins? Builds in Jenkins can be triggered periodically (on a schedule, specified in configuration), or when source changes in the project have been detected, or they can be automatically triggered by requesting the URL: Question: What is a Jenkins file? Jenkins file is a text file containing the definition of a Jenkins Pipeline and checks into source control. Amazon AWS DevOps Interview Questions Question: What is Amazon Web Services? Amazon Web Services provides services that help you practice DevOps at your company and that are built first for use with AWS. These tools automate manual tasks, help teams manage complex environments at scale, and keep engineers in control of the high velocity that is enabled by DevOps Question: What Are Benefits Of AWS for DevOps? There are many benefits of using Scalability: You can manage a single instance or scale to thousands using AWS services. These services help you make the most of flexible compute resources by simplifying provisioning, configuration, and scaling. Programmable: You have the option to use each service via the AWS Command Line Interface or through APIs and SDKs. You can also model and provision AWS resources and your entire AWS infrastructure using declarative AWS CloudFormation templates.. Question: How To Handle Continuous Integration and Continuous Delivery in AWS Devops? The AWS Developer Tools help in securely store and version your application’s source code and automatically build, test, and deploy your application to AWS. Question:. Question: What Are The Components Involved In Amazon Web Services? There are 4 components. Question: How is a. Questions:: What is AWS CodeBuild in AWS Devops?. Question: What is Amazon Elastic Container Service in AWS Devops? Amazon Elastic Container Service (ECS) is a highly scalable, high performance container management service that supports Docker containers and allows you to easily run applications on a managed cluster of Amazon EC2 instances. Question: What is AWS Lambda in AWS Devops? Splunk DevOps Interview Questions Question: What is Splunk? The platform of Splunk allows you to get visibility into machine data generated from different networks, servers, devices, and hardware. It can give insights into the application management, threat visibility, compliance, security, etc. so it is used to analyze machine data. The data is collected from the forwarder from the source and forwarded to the indexer. The data is stored locally on a host machine or cloud. Then on the data stored in the indexer the search head searches, visualizes, analyzes and performs various other functions. Question: What Are The Components Of Splunk? The main components of Splunk are Forwarders, Indexers and Search Heads.Deployment Server(or Management Console Host) will come into the picture in case of a larger environment. Deployment servers act like an antivirus policy server for setting up Exceptions and Groups so that you can map and create adifferent set of data collection policies each for either window based server or a Linux based server or a Solaris based server. plunk has four important components : - Indexer – It indexes the machine data - Forwarder – Refers to Splunk instances that forward data to the remote indexers - Search Head – Provides GUI for searching - Deployment Server –Manages the Splunk components like indexer, forwarder, and search head in computing environment. Question:: - Pre-result alerts : Most commonly used alert type and runs in real-time for an all- time span. These alerts are designed such that whenever a search returns a result, they are triggered. - Scheduled alerts : The second most common- scheduled results are set up to evaluate the results of a historical search result running over a set time range on a regular schedule. You can define a time range, schedule and the trigger condition to an alert. -. Question: What Are The Categories Of SPL Commands? SPL commands are divided into five categories: - Sorting Results – Ordering results and (optionally) limiting the number of results. - Filtering Results – It takes a set of events or results and filters them into a smaller set of results. - Grouping Results – Grouping events so you can see patterns. - Filtering, Modifying and Adding Fields – Taking search results and generating a summary for reporting. - Reporting Results – Filtering out some fields to focus on the ones you need, or modifying or adding fields to enrich your results or events. Question: What Happens If The License Master Is Unreachable? In case the license master is unreachable, then it is just not possible to search the data. However, the data coming in to the Indexer will not be affected. The data will continue to flow into your Splunk deployment. The Indexers will continue to index the data as usual however, you will get a warning message on top your Search head or web UI saying that you have exceeded the indexing volume. And you either need to reduce the amount of data coming in or you need to buy a higher capacity of license. Basically, the candidate is expected to answer that the indexing does not stop; only searching is halted Question: What are common port numbers used by Splunk? Common port numbers on which default services run are: Question: What Are Splunk Buckets? Explain The Bucket Lifecycle? A directory that contains indexed data is known as a Splunk bucket. It also contains events of a certain period. Bucket lifecycle includes following stages: - Hot – It contains newly indexed data and is open for writing. For each index, there are one or more hot buckets available - Warm – Data rolled from hot - Cold – Data rolled from warm - Frozen – Data rolled from cold. The indexer deletes frozen data by default but users can also archive it. - Thawed – Data restored from an archive. If you archive frozen data , you can later return it to the index by thawing (defrosting) it. Question: Explain Data Models and Pivot? Data models are used for creating a structured hierarchical model of data. It can be used when you have a large amount of unstructured data, and when you want to make use of that information without using complex search queries. On the other hand with pivots, you have the flexibility to create the front views of your results and then pick and choose the most appropriate filter for a better view of results. Question: What Is File Precedence In Splunk? File precedence is an important aspect of troubleshooting in Splunk for an administrator, developer, as well as an architect. All of Splunk’s configurations are written in .conf files. There can be multiple copies present for each of these files, and thus it is important to know the role these files play when a Splunk instance is running or restarted. To determine the priority among copies of a configuration file, Splunk software first determines the directory scheme. The directory schemes are either a) Global or b) App/user. When the context is global (that is, where there’s no app/user context), directory priority descends in this order: - System local directory — highest priority - App local directories - App default directories - System default directory — lowest priority - User directories for current user — highest priority - App directories for currently running app (local, followed by default) - App directories for all other apps (local, followed by default) — for exported settings only - System directories (local, followed by default) — lowest priority Question: Difference Between Search Time And Index Time Field Extractions? Search time field extraction refers to the fields extracted while performing searches. Whereas, fields extracted when the data comes to the indexer are referred to as Index time field extraction. You can set up the indexer time field extraction either at the forwarder level or at the indexer level. Another difference is that Search time field extraction’s extracted fields are not part of the metadata, so they do not consume disk space. Whereas index time field extraction’s extracted fields are a part of metadata and hence consume disk space. Question: What Is Source Type In Splunk? Question: What is SOS? - It has following purposes: - Diagnostic tool to analyze and troubleshoot problems - Examine Splunk environment performance - Solve indexing performance issues - Observe scheduler activities and issues - See the details of scheduler and user driven search activity - Search, view and compare configuration files of Splunk Question: What Is Splunk Indexer And Explain Its Stages? - Indexing incoming data - Searching indexed data Splunk indexer has following stages: Question: State The Difference Between Stats and Eventstats Commands? log4J DevOps Interview Questions Question: What is log4j?. Question: What Are The Features Of Log4j Log4j is widely used framework and here are features of log4j -. Question: What are the components of log4j? log4j has three main components - loggers: Responsible for capturing logging information. - appenders: Responsible for publishing logging information to various preferred destinations. - layouts: Responsible for formatting logging information in different styles. Question: How do you initialize and use Log4J ? public class LoggerTest { static Logger log = Logger.getLogger (LoggerTest.class.getName()); public void my logerMethod() { if(log.isDebugEnabled()) log.debug("This is test message" + var2); ) } } Question: What are Pros and Cons of Logging? Following are the Pros and Cons of Logging. Question:What Is The Purpose Of Logger Object? Logger Object − The top-level layer of log4j architecture is the Logger which provides the Logger object. The Logger object is responsible for capturing logging information and they are stored in a namespace hierarchy. Question: What is the purpose of Layout object? The layout layer of log4j architecture provides objects which are used to format logging information in different styles. It provides support to appender objects before publishing logging information. Questions: What is the purpose of Appender object? The Appender object is responsible for publishing logging information to various preferred destinations such as a database, file, console, UNIX Syslog, etc. Question: What Is The Purpose Of ObjectRenderer Object? The ObjectRenderer object is specialized in providing a String representation of different objects passed to the logging framework. This object is used by Layout objects to prepare the final logging information. Question: What Is LogManager object? The LogManager object manages the logging framework. It is responsible for reading the initial configuration parameters from a system-wide configuration file or a configuration class. Question: How Will You Define A File Appender Using Log4j.properties? Following syntax defines a file appender − log4j.appender.FILE=org.apache.log4j.FileAppender log4j.appender.FILE.File=${log}/log.out Question: What Is The Purpose Of Threshold In Appender? Docker DevOps Interview Questions Question: What is Docker? Docker provides a container for managing software workloads on shared infrastructure, all while keeping them isolated from one another.. Question:. Question:. Question: What Is Docker Container?. Question: What Is Docker Image? Docker image is the source of Docker container. In other words, Docker images are used to create containers.. Question: What. Question: Questions: What is Dockerfile used for? A Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image. Using docker build users can create an automated build that executes several command-line instructions in succession. Question: How is Docker different from other container technologies?. Question: How to create Docker container? We can use Docker image to create Docker container by using the below command: Question: How to stop and restart the Docker container? In order to stop the Docker container you can use the below command: Question: What is the difference between docker run and docker create? Question: What four states a Docker container can be in? - Running - Paused - Restarting - Exited Question:What Is Difference Between Repository and a Registry? Question: How to link containers? Question: What is the difference between Docker RUN, CMD and ENTRYPOINT? Question: How many containers can run per host? Question: What is Docker hub? VmWare DevOps Interview Questions Question: What is VmWare? VMware was founded in 1998 by five different IT experts. The company officially launched its first product, VMware Workstation, in 1999, which was followed by the VMware GSX Server in 2001. The company has launched many additional products since that time. VMware's desktop software is compatible with all major OSs, including Linux, Microsoft Windows, and Mac OS X. VMware provides three different types of desktop software: - VMware Workstation: This application is used to install and run multiple copies or instances of the same operating systems or different operating systems on a single physical computer machine. - VMware Fusion: This product was designed for Mac users and provides extra compatibility with all other VMware products and applications. - VMware Player: This product was launched as freeware by VMware for users who do not have licensed VMWare products. This product is intended only for personel use. - VMware ESX Server: This is an enterprise-level solution, which is built to provide better functionality in comparison to the freeware VMware Server resulting from a lesser system overhead. VMware ESX is integrated with VMware vCenter that provides additional solutions to improve the manageability and consistency of the server implementation. - VMware ESXi Server: This server is similar to the ESX Server except that the service console is replaced with BusyBox installation and it requires very low disk space to operate. - VMware Server: Freeware software that can be used over existing operating systems like Linux or Microsoft Windows. Question: What is Virtualization? The process of creating virtual versions of physical components i-e Servers, Storage Devices, Network Devices on a physical host is called virtualization. Virtualization lets you run multiple virtual machines on a single physical machine which is called ESXi host. Question: Question: What is Service Console? The service console is developed based up on Redhat Linux Operating system, it is used to manage the VMKernel Question:. Question: What is VMKernel? VMWare Kernel is a Proprietary kernel of vmware and is not based on any of the flavors of Linux operating systems. VMkernel requires an operating system to boot and manage the kernel. A service console is being provided when VMWare kernel is booted. Only service console is based up on Redhat Linux OS not VMkernel. Question. Question:). Questions: What is virtual networking? A network of VMs running on a physical server that are connected logically with each other is called virtual networking. Question: What is vSS? vSS stands for Virtual Standard Switch is responsible for communication of VMs hosted on a single physical host. it works like a physical switch automatically detects a VM which want to communicate with other VM on a same physical server. Question: What is VMKernal adapter and why it used? AVMKernel adapter provides network connectivity to the ESXi host to handle network traffic for vMotion, IP Storage, NAS, Fault Tolerance, and vSAN. For each type of traffic such as vMotion, vSAN etc. separate VMKernal adapter should be created and configured. Question:What are three port groups are configured in ESXi networking? - Virtual Machine Port Group – Used for Virtual Machine Network - Service Console Port Group – Used for Service Console Communications - VMKernel Port Group – Used for VMotion, iSCSI, NFS Communications Question: What are main components of vCenter Server architecture? - vSphere Client and Web Client: a user interface. - vCenter Server database: SQL server or embedded PostgreSQL to store inventory, security roles, resource pools etc. - SSO: a security domain in virtual environment Question: What is datastore? Question: How many disk types are in VMware? -. - What is Storage vMotion? Question: What is the use of VMKernel Port ? Question: What are different types of Partitions in ESX server? Question: Explain What Is VMware DRS? VMware DRS stands for Distributed Resource Scheduler; it dynamically balances resources across various host under cluster or resource pool. It enables users to determine the rules and policies which decide how virtual machines deploy resources, and these resources should be prioritized to multiple virtual machines. DevOps Testing Interview Questions Question: What is Continuous Testing? Continuous Testing is the process of executing automated tests to obtain immediate feedback on the business risks associated with in the latest build. In this way, each build is tested continuously, allowing Development teams to get fast feedback so that they can prevent those problems from progressing to the next stage of Software delivery life-cycle. Question: What is Automation Testing Automation testing is a process of automating the manual testing process. Automation testing involves use of separate testing tools, which can be executed repeatedly and doesn’t require any manual intervention. Question: What Are The Benefits of Automation Testing? Here are some of the benefits of using Continuous Testing; - Supports execution of repeated test cases - Aids in testing a large test matrix - Enables parallel execution - Encourages unattended execution - Improves accuracy thereby reducing human generated errors - Saves time and money Question: Why is Continuous Testing important for DevOps? Continuous Testing allows any change made in the code to be tested immediately. This avoids the problems created by having “big-bang” testing left to the end of the development cycle such as release delays and quality issues. In this way, Continuous Testing facilitates more frequent and good quality releases.” Question:. Question: What is the Difference Between Assert and Verify commands in Selenium? Assert command checks whether the given condition is true or false. Verify command also checks whether the given condition is true or false. Irrespective of the condition being true or false, the program execution doesn’t halts i.e. any failure during verification would not stop the execution and all the test steps would be executed. Summary DevOps refers to a wide range of tools, process and practices used by companies to improve their build, deployment, testing and release life cycles. In order to ace a DevOps interview you need to have a deep understanding of all of these tools and processes. Most of the technologies and process used to implement DevOps are not isolated. Most probably you are already familiar with many of these. All you have to do is to prepare for these from DevOps perspective. In this guide I have created the largest set of interview questions. Each section in this guide caters to a specific area of DevOps. In order to increase your chances of success in DevOps interview you need to go through all of these questions. Other Related Interview Questions: - AngularJs Interview Questions - Spring Interview Questions - Java MultiThreading Interview Questions - Phone Interview Questions DevOps Interview Questions PDF About The Author References - - - - - - - - - - - - - - - - - - - - - - - - - - -
http://www.codespaghetti.com/devops-interview-questions/
CC-MAIN-2019-30
refinedweb
9,973
56.45
Last Updated on April 30, 2021 The Pix2Pix GAN is a generator model for performing image-to-image translation trained on paired examples. For example, the model can be used to translate images of daytime to nighttime, or from sketches of products like shoes to photographs of products. The benefit of the Pix2Pix model is that compared to other GANs for conditional image generation, it is relatively simple and capable of generating large high-quality images across a variety of image translation tasks. The model is very impressive but has an architecture that appears somewhat complicated to implement for beginners. In this tutorial, you will discover how to implement the Pix2Pix GAN architecture from scratch using the Keras deep learning framework. Implement Pix2Pix GAN Models From Scratch With Keras Photo by Ray in Manila, some rights reserved. Tutorial Overview This tutorial is divided into five parts; they are: - What Is the Pix2Pix GAN? - How to Implement the PatchGAN Discriminator Model - How to Implement the U-Net Generator Model - How to Implement Adversarial and L1 Loss - How to Update Model Weights What Is the Pix2Pix GAN? comprised of a generator model for outputting new plausible synthetic images and a discriminator model that classifies images as real (from the dataset) or fake (generated). The discriminator model is updated directly, whereas the generator model is updated via the discriminator model. As such, the two models are trained simultaneously in an adversarial process where the generator seeks to better fool the discriminator and the discriminator seeks to better identify the counterfeit images. The Pix2Pix model is a type of conditional GAN, or cGAN, where the generation of the output image is conditional on an input, in this case, a source image. The discriminator is provided both with a source image and the target image and must determine whether the target is a plausible transformation of the source image. Again, the discriminator model is updated directly, and the generator model is updated via the discriminator model, although the loss function is updated. The generator is trained via adversarial loss, which encourages the generator to generate plausible images in the target domain. The generator is also updated via L1 loss measured between the generated image and the expected output image. This additional loss encourages the generator model to create plausible translations of the source image. The Pix2Pix GAN has been demonstrated on a range of image-to-image translation tasks such as converting maps to satellite photographs, black and white photographs to color, and sketches of products to product photographs. Now that we are familiar with the Pix2Pix GAN, let’s explore how we can implement it using the Keras deep learning library. Want to Develop GANs from Scratch? Take my free 7-day email crash course now (with sample code). Click to sign-up and also get a free PDF Ebook version of the course. Download Your FREE Mini-Course How to Implement the PatchGAN Discriminator Model The discriminator model in the Pix2Pix GAN is implemented as a PatchGAN. The PatchGAN is designed based on the size of the receptive field, sometimes called the effective receptive field. The receptive field is the relationship between one output activation of the model to an area on the input image (actually volume as it proceeded down the input channels). A PatchGAN with the size 70×70 is used, which means that the output (or each output) of the model maps to a 70×70 square of the input image. In effect, a 70×70 PatchGAN will classify 70×70 patches of the input image as real or fake. …. — Image-to-Image Translation with Conditional Adversarial Networks, 2016. Before we dive into the configuration details of the PatchGAN, it is important to get a handle on the calculation of the receptive field. The receptive field is not the size of the output of the discriminator model, e.g. it does not refer to the shape of the activation map output by the model. It is a definition of the model in terms of one pixel in the output activation map to the input image. The output of the model may be a single value or a square activation map of values that predict whether each patch of the input image is real or fake. Traditionally, the receptive field refers to the size of the activation map of a single convolutional layer with regards to the input of the layer, the size of the filter, and the size of the stride. The effective receptive field generalizes this idea and calculates the receptive field for the output of a stack of convolutional layers with regard to the raw image input. The terms are often used interchangeably. The authors of the Pix2Pix GAN provide a Matlab script to calculate the effective receptive field size for different model configurations in a script called receptive_field_sizes.m. It can be helpful to work through an example for the 70×70 PatchGAN receptive field calculation. The 70×70 PatchGAN has a fixed number of three layers (excluding the output and second last layers), regardless of the size of the input image. The calculation of the receptive field in one dimension is calculated as: - receptive field = (output size – 1) * stride + kernel size Where output size is the size of the prior layers activation map, stride is the number of pixels the filter is moved when applied to the activation, and kernel size is the size of the filter to be applied. The PatchGAN uses a fixed stride of 2×2 (except in the output and second last layers) and a fixed kernel size of 4×4. We can, therefore, calculate the receptive field size starting with one pixel in the output of the model and working backward to the input image. We can develop a Python function called receptive_field() to calculate the receptive field, then calculate and print the receptive field for each layer in the Pix2Pix PatchGAN model. The complete example is listed below. Running the example prints the size of the receptive field for each layer in the model from the output layer to the input layer. We can see that each 1×1 pixel in the output layer maps to a 70×70 receptive field in the input layer. The authors of the Pix2Pix paper explore different PatchGAN configurations, including a 1×1 receptive field called a PixelGAN and a receptive field that matches the 256×256 pixel images input to the model (resampled to 286×286) called an ImageGAN. They found that the 70×70 PatchGAN resulted in the best trade-off of performance and image quality. The 70×70 PatchGAN […] achieves slightly better scores. Scaling beyond this, to the full 286×286 ImageGAN, does not appear to improve the visual quality of the results. — Image-to-Image Translation with Conditional Adversarial Networks, 2016. The configuration for the PatchGAN is provided in the appendix of the paper and can be confirmed by reviewing the defineD_n_layers() function in the official Torch implementation. The model takes two images as input, specifically a source and a target image. These images are concatenated together at the channel level, e.g. 3 color channels of each image become 6 channels of the input. Let Ck denote a Convolution-BatchNorm-ReLU layer with k filters. […] All convolutions are 4× 4 spatial filters applied with stride 2. […] The 70 × 70 C64 layer. All ReLUs are leaky, with slope 0.2. — Image-to-Image Translation with Conditional Adversarial Networks, 2016. The PatchGAN configuration is defined using a shorthand notation as: C64-C128-C256-C512, where C refers to a block of Convolution-BatchNorm-LeakyReLU layers and the number indicates the number of filters. Batch normalization is not used in the first layer. As mentioned, the kernel size is fixed at 4×4 and a stride of 2×2 is used on all but the last 2 layers of the model. The slope of the LeakyReLU is set to 0.2, and a sigmoid activation function is used in the output layer. Random jitter was applied by resizing the 256×256 input images to 286 × 286 and then randomly cropping back to size 256 × 256. Weights were initialized from a Gaussian distribution with mean 0 and standard deviation 0.02. — Image-to-Image Translation with Conditional Adversarial Networks, 2016. Model weights were initialized via random Gaussian with a mean of 0.0 and standard deviation of 0.02. Images input to the model are 256×256. … we divide the objective by 2 while optimizing D, which slows down the rate at which D learns relative to G. We use minibatch SGD and apply the Adam solver, with a learning rate of 0.0002, and momentum parameters β1 = 0.5, β2 = 0.999. — Image-to-Image Translation with Conditional Adversarial Networks, 2016. The model is trained with a batch size of one image and the Adam version of stochastic gradient descent is used with a small learning range and modest momentum. The loss for the discriminator is weighted by 50% for each model update. Tying this all together, we can define a function named define_discriminator() that creates the 70×70 PatchGAN discriminator model. The complete example of defining the model is listed below. Running the example first summarizes the model, providing insight into how the input shape is transformed across the layers and the number of parameters in the model. We can see that the two input images are concatenated together to create one 256x256x6 input to the first hidden convolutional layer. This concatenation of input images could occur before the input layer of the model, but allowing the model to perform the concatenation makes the behavior of the model clearer.. The model is a binary classification model, meaning it predicts an output as a probability in the range [0,1], in this case, the likelihood of whether the input image is real or from the target dataset. The patch of values can be averaged to give a real/fake prediction by the model. When trained, the target is compared to a matrix of target values, 0 for fake and 1 for real. A plot of the model is created showing much the same information in a graphical form. The model is not complex, with a linear path with two input images and a single output prediction. Note: creating the plot assumes that pydot and pygraphviz libraries are installed. If this is a problem, you can comment out the import and call to the plot_model() function. Plot of the PatchGAN Model Used in the Pix2Pix GAN Architecture Now that we know how to implement the PatchGAN discriminator model, we can now look at implementing the U-Net generator model. How to Implement the U-Net Generator Model The generator model for the Pix2Pix GAN is implemented as a U-Net. The U-Net model is an encoder-decoder model for image translation where skip connections are used to connect layers in the encoder with corresponding layers in the decoder that have the same sized feature maps. The encoder part of the model is comprised of convolutional layers that use a 2×2 stride to downsample the input source image down to a bottleneck layer. The decoder part of the model reads the bottleneck output and uses transpose convolutional layers to upsample to the required output image size. … the input is passed through a series of layers that progressively downsample, until a bottleneck layer, at which point the process is reversed. — Image-to-Image Translation with Conditional Adversarial Networks, 2016. Architecture of the U-Net Generator Model Taken from Image-to-Image Translation With Conditional Adversarial Networks. Skip connections are added between the layers with the same sized feature maps so that the first downsampling layer is connected with the last upsampling layer, the second downsampling layer is connected with the second last upsampling layer, and so on. The connections concatenate the channels of the feature map in the downsampling layer with the feature map in the upsampling layer. Specifically, we add skip connections between each layer i and layer n − i, where n is the total number of layers. Each skip connection simply concatenates all channels at layer i with those at layer n − i. — Image-to-Image Translation with Conditional Adversarial Networks, 2016. Unlike traditional generator models in the GAN architecture, the U-Net generator does not take a point from the latent space as input. Instead, dropout layers are used as a source of randomness both during training and when the model is used to make a prediction, e.g. generate an image at inference time. Similarly, batch normalization is used in the same way during training and inference, meaning that statistics are calculated for each batch and not fixed at the end of the training process. This is referred to as instance normalization, specifically when the batch size is set to 1 as it is with the Pix2Pix model. At inference time, we run the generator net in exactly the same manner as during the training phase. This differs from the usual protocol in that we apply dropout at test time, and we apply batch normalization using the statistics of the test batch, rather than aggregated statistics of the training batch. — Image-to-Image Translation with Conditional Adversarial Networks, 2016. In Keras, layers like Dropout and BatchNormalization operate differently during training and in inference model. We can set the “training” argument when calling these layers to “True” to ensure that they always operate in training-model, even when used during inference. For example, a Dropout layer that will drop out during inference as well as training can be added to the model as follows: As with the discriminator model, the configuration details of the generator model are defined in the appendix of the paper and can be confirmed when comparing against the defineG_unet() function in the official Torch implementation. The encoder uses blocks of Convolution-BatchNorm-LeakyReLU like the discriminator model, whereas the decoder model uses blocks of Convolution-BatchNorm-Dropout-ReLU with a dropout rate of 50%. All convolutional layers use a filter size of 4×4 and a stride of 2×2. Let Ck denote a Convolution-BatchNorm-ReLU layer with k filters. CDk denotes a Convolution-BatchNormDropout-ReLU layer with a dropout rate of 50%. All convolutions are 4× 4 spatial filters applied with stride 2. — Image-to-Image Translation with Conditional Adversarial Networks, 2016. The architecture of the U-Net model is defined using the shorthand notation as: - Encoder: C64-C128-C256-C512-C512-C512-C512-C512 - Decoder: CD512-CD1024-CD1024-C1024-C1024-C512-C256-C128 The last layer of the encoder is the bottleneck layer, which does not use batch normalization, according to an amendment to the paper and confirmation in the code, and uses a ReLU activation instead of LeakyRelu. … the activations of the bottleneck layer are zeroed by the batchnorm operation, effectively making the innermost layer skipped. This issue can be fixed by removing batchnorm from this layer, as has been done in the public code — Image-to-Image Translation with Conditional Adversarial Networks, 2016. The number of filters in the U-Net decoder is a little misleading as it is the number of filters for the layer after concatenation with the equivalent layer in the encoder. This may become more clear when we create a plot of the model. The output of the model uses a single convolutional layer with three channels, and tanh activation function is used in the output layer, common to GAN generator models. Batch normalization is not used in the first layer of the encoder. After the last layer in the decoder, a convolution is applied to map to the number of output channels (3 in general […]), followed by a Tanh function […] BatchNorm is not applied to the first C64 layer in the encoder. All ReLUs in the encoder are leaky, with slope 0.2, while ReLUs in the decoder are not leaky. — Image-to-Image Translation with Conditional Adversarial Networks, 2016. Tying this all together, we can define a function named define_generator() that defines the U-Net encoder-decoder generator model. Two helper functions are also provided for defining encoder blocks of layers and decoder blocks of layers. The complete example of defining the model is listed below. Running the example first summarizes the model. The model has a single input and output, but the skip connections make the summary difficult to read. A plot of the model is created showing much the same information in a graphical form. The model is complex, and the plot helps to understand the skip connections and their impact on the number of filters in the decoder. Note: creating the plot assumes that pydot and pygraphviz libraries are installed. If this is a problem, you can comment out the import and call to the plot_model() function. Working backward from the output layer, if we look at the Concatenate layers and the first Conv2DTranspose layer of the decoder, we can see the number of channels as: - [128, 256, 512, 1024, 1024, 1024, 1024, 512]. Reversing this list gives the stated configuration of the number of filters for each layer in the decoder from the paper of: - CD512-CD1024-CD1024-C1024-C1024-C512-C256-C128 Plot of the U-Net Encoder-Decoder Model Used in the Pix2Pix GAN Architecture Now that we have defined both models, we can look at how the generator model is updated via the discriminator model. How to Implement Adversarial and L1 Loss The discriminator model can be updated directly, whereas the generator model must be updated via the discriminator model. This can be achieved by defining a new composite model in Keras that connects the output of the generator model as input to the discriminator model. The discriminator model can then predict whether a generated image is real or fake. We can update the weights of the composite model in such a way that the generated image has the label of “real” instead of “fake“, which will cause the generator weights to be updated towards generating a better fake image. We can also mark the discriminator weights as not trainable in this context, to avoid the misleading update. Additionally, the generator needs to be updated to better match the targeted translation of the input image. This means that the composite model must also output the generated image directly, allowing it to be compared to the target image. Therefore, we can summarize the inputs and outputs of this composite model as follows: - Inputs: Source image - Outputs: Classification of real/fake, generated target image. The weights of the generator will be updated via both adversarial loss via the discriminator output and L1 loss via the direct image output. The loss scores are added together, where the L1 loss is treated as a regularizing term and weighted via a hyperparameter called lambda, set to 100. - loss = adversarial loss + lambda * L1 loss The define_gan() function below implements this, taking the defined generator and discriminator models as input and creating the composite GAN model that can be used to update the generator model weights. The source image input is provided both to the generator and the discriminator as input and the output of the generator is also connected to the discriminator as input. Two loss functions are specified when the model is compiled for the discriminator and generator outputs respectively. The loss_weights argument is used to define the weighting of each loss when added together to update the generator model weights. Tying this together with the model definitions from the previous sections, the complete example is listed below. Running the example first summarizes the composite model, showing the 256×256 image input, the same shaped output from model_2 (the generator) and the PatchGAN classification prediction from model_1 (the discriminator). A plot of the composite model is also created, showing how the input image flows into the generator and discriminator, and that the model has two outputs or end-points from each of the two models. Note: creating the plot assumes that pydot and pygraphviz libraries are installed. If this is a problem, you can comment out the import and call to the plot_model() function. Plot of the Composite GAN Model Used to Train the Generator in the Pix2Pix GAN Architecture How to Update Model Weights Training the defined models is relatively straightforward. First, we must define a helper function that will select a batch of real source and target images and the associated output (1.0). Here, the dataset is a list of two arrays of images. Similarly, we need a function to generate a batch of fake images and the associated output (0.0). Here, the samples are an array of source images for which target images will be generated. Now, we can define the steps of a single training iteration. First, we must select a batch of source and target images by calling generate_real_samples(). Typically, the batch size (n_batch) is set to 1. In this case, we will assume 256×256 input images, which means the n_patch for the PatchGAN discriminator will be 16 to indicate a 16×16 output feature map. Next, we can use the batches of selected real source images to generate corresponding batches of generated or fake target images. We can then use the real and fake images, as well as their targets, to update the standalone discriminator model. So far, this is normal for updating a GAN in Keras. Next, we can update the generator model via adversarial loss and L1 loss. Recall that the composite GAN model takes a batch of source images as input and predicts first the classification of real/fake and second the generated target. Here, we provide a target to indicate the generated images are “real” (class=1) to the discriminator output of the composite model. The real target images are provided for calculating the L1 loss between them and the generated target images. We have two loss functions, but three loss values calculated for a batch update, where only the first loss value is of interest as it is the weighted sum of the adversarial and L1 loss values for the batch. That’s all there is to it. We can define all of this in a function called train() that takes the defined models and a loaded dataset (as a list of two NumPy arrays) and trains the models. The train function can then be called directly with our defined models and loaded dataset. Further Reading This section provides more resources on the topic if you are looking to go deeper. Official - API - Keras Datasets API. - Keras Sequential Model API - Keras Convolutional Layers API - How can I “freeze” Keras layers? Articles - A guide to receptive field arithmetic for Convolutional Neural Networks, 2017. - Question: PatchGAN Discriminator, 2017. - receptive_field_sizes.m Summary In this tutorial, you discovered how to implement the Pix2Pix GAN architecture from scratch using the Keras deep learning framework. Specifically, you learned: -. Do you have any questions? Ask your questions in the comments below and I will do my best to answer. Does this book cover tensorflow 2.0? No, tensorflow 2.0 is not released, it is still in beta. Good👍 Thanks! You are the best. Thanks! Let’s say that I want to save the best model. Which loss should I consider to save the model or even to do an early stopping? Ouch. Excellent question! Neither. Loss is not a good indicator of GAN generated image quality. WGAN loss can be, LS loss can be, but I would not rely on them in practice. Instead, save models all the time – like each cycle, use them to generate samples, and select models based on the quality of generated samples. Evaluate samples with humans or with metrics like incept score or FID (tutorials coming on this). Thanks for your great contribution. I want to ask that you say that unpack dataset. But I cannot figure out how to load the dataset. As far as I understand we should have two datasets, one is the source data that will be translated to the expected images, and the other one is the real images those are used for applying to the source images. But how do we load these datasets? # load image data dataset = … (should we type here both of the directories of the datasets?, but I cannot figure out how) sorry if my question is weird. Correct, the dataset contains paired images. I give a complete example with a real dataset here: When you set Trainable = False for the discriminator, doesn’t it remain untrainable for all future training batches? Shouldn’t you set Trainable to True every time you’re about to train the discriminator and change it to False every time you train the overall Gan model? Yes, but only in the composite model. The standalone discriminator is unaffected. Why batch size of GAN is mostly 1? Not always, but in this case because we update for each image. Where do you used lambda? I am unable to see that one parameter. Great question, in the loss_weights argument to compile(). Hi Adrian, Thanks for your great post. Is there any way to write the code through a negative loss weight for the discriminator rather than interchanging the labels? Yes, but I don’t have a worked example, sorry. Sorry , I was going to comment for “How to Code the GAN Training Algorithm and Loss Functions”. It was my fault. No problem. Dear Jason, Isn’t the effective receptive field of this discriminator that you wrote 142? because we’ve got 4 convolutional layers with kernel size 4 and stride 2, and two last layers with kernel size 4 and stride 1 which makes the receptive field 142. No, the worked example starts at the first conv, not the pixels. Dear Jason in ‘Image-to-Image Translation with Conditional Adversarial Networks’ paper: The 70 * 70 discriminator architecture is: C64-C128-C256-C512 After the last layer, a convolution is applied to map to a 1-dimensional output, followed by a Sigmoid function. but there are two C512 layer in your implementation i dont understant it … Thanks for your Great site Yes, the implementation matches the code they provided where the final C512 “interprets” the 70×70 output. Hi Jason, I have a question regarding the receptive field calculation. I still do not understand why there are 6 conv layers in the implementation code for the 70X70 PatchGAN, but when calculating the receptive field there are only 5 conv layers used. For what purpose one (filter size = 4, stride = 2) conv layer is missed? Can you give me an explanation in detail? Thanks. The final layer interprets the receptive field, matching the paper and official implementation. This is also noted in the code comments. Dear Jason, Thank you about this article. it is a very useful and i understand from here pix2pix model. IS there any article about Star GAN using keras? Thank you Thanks for the suggestion, I may cover it in the future. Hello Jason, thanks once again for an awesome tutorial. I was wondering if it is possible to save the state of the discriminator, generator and Gan, load them sometime later and continue training ? Could you point me in the right direction? Thank you Yes, you can use save() on each model: Hi Jason, thanks for your input. Do you have any code example of saving all three models, loading them and then training again. I tried saving and loading all three models but when attempting to train again the loss of the discriminator and generator was 0 and remained 0. I searched through a lot of forums but to no avail. Any examples available on this specific topic? I think it would help a great number of people I have an example of training, saving, loading and using the models here: In all examples the generator model is only saved and loaded AFTER training to predict / generate new images. Thanks for your tutorials anyway Jason. Dear Jason, Many thanks. It was so helpful. And what about pix2pixHD? Thanks! I hope to cover it in the future. Hello, Thank you for the great post! I have a query about this paragraph: .” -> How is it determined that the each value in 16×16 corresponds to a 70×70 pixel patch of input image? -> what should be the output size if I wanted to apply it for patches of 16×16 of input image? ->does input image mean the one with 256x256x6 (after concatenation) or the one before concatenation? Thanks a lot! Thanks. See the section titled “How to Implement the PatchGAN Discriminator Model” on how the patch gan is calculated. You can plug-in any numbers you wish. Hi, In your code, you only take 1 Input layer. How do you take 2 images A and B? I am unable to understand. I’ve been trying to make my own model and this is what I’m doing: self.discriminator = self.build_discriminator() self.discriminator.compile(loss=”binary_crossentropy”, optimizer=optimizer, loss_weights=[0.5]) print(“## DISCRIMINATOR ##”) self.discriminator.summary() # plot_model(self.discriminator, to_file=’discriminator.png’, show_shapes=True, show_layer_names=True) self.generator = self.build_generator() print(“## GENERATOR ##”) self.generator.summary() # plot_model(self.generator, to_file=”generator.png”, show_shapes=True, show_layer_names=True) lr = Input(shape=self.img_shape) hr = Input(shape=self.img_shape) sr = self.generator(lr) valid = self.discriminator([sr,hr]) self.discriminator.traininable = False self.combined = Model(inputs=[lr,hr], outputs=[valid,sr]) self.combined.compile(loss=[‘binary_crossentropy’,’mae’], loss_weights=[1,100], optimizer=optimizer) self.combined.summary() This is the summary of my GAN: Model: “model_2” __________________________________________________________________________________________________ Layer (type) Output Shape Param # Connected to ================================================================================================== input_4 (InputLayer) [(None, 512, 512, 3) 0 __________________________________________________________________________________________________ model_1 (Model) (None, 512, 512, 3) 54429315 input_4[0][0] __________________________________________________________________________________________________ input_5 (InputLayer) [(None, 512, 512, 3) 0 __________________________________________________________________________________________________ model (Model) (None, 32, 32, 1) 6968257 model_1[1][0] input_5[0][0] ================================================================================================== Total params: 61,397,572 Trainable params: 61,384,900 Non-trainable params: 12,672 I don’t understand how taking 2 Input layers is bad? Why is my discriminator not accepting trainable=False? Can you please clear my doubts? I’m eager to help, but I don’t have the capacity to debug your code. Perhaps the suggestions here will help: Thank you for this wonderful post. Is it necessary to feed images of 256x256x3 as input ?? Can we feed an image of different sizes like 480x480x3 ?? Instead of a square image can we feed a non-square image to the network?? Yes, but you will need to change the model. Please explain what and wherein model-network changes will be required for and square or non-square images. Sorry, I don’t have the capacity to customize the example for you. REALLY useful information! I’ve made one small change for my b/w dataset, based on the line: “After the last layer in the decoder, a convolution is applied to map to the number of output channels (3 in general […])” I’m training some b/w data, shape [256,256,1] and notice that there is one hard-coded “3” in define_generator at the end: g = Conv2DTranspose(3, (4,4), strides=(2,2), padding=’same’, kernel_initializer=init)(d7) You default to 3-channel images, but your input_shape can handle other variations with this modest change: g = Conv2DTranspose(input_shape[2], (4,4), strides=(2,2), padding=’same’, kernel_initializer=init)(d7) Thanks for making this Thanks! Great suggestion Scott. Hello, I would like to ask a question. I’m trying to reproduce pix2pix using pytorch, but when I’m going to implement the discriminator, if I consider the last two layers with kernel size = 4 and stride = 1, the output must be a 14×14 matrix (considering that padding = 1 in the official github project). I can’t understand how padding=’same’ make it keep 16×16. Perhaps use an existing pytorch implementation of the model? What is the purpose of concatenating the real and generated images when passed as input to the discriminator? To have both images types in the batch when updating weights. Hi Jason, I have a question about 70×70 PatchGAN receptive field. In the pix2pix paper, their architecture is C64-C128-C256-C512-C1, all convolution layer have 4×4 filter with stride 2 (page 16), which is a bit different from your implemetation. Following the receptive field calculation, I got: receptive_field(1, 4, 2) Out[3]: 4 receptive_field(4, 4, 2) Out[4]: 10 receptive_field(10, 4, 2) Out[5]: 22 receptive_field(22, 4, 2) Out[6]: 46 receptive_field(46, 4, 2) Out[7]: 94 Did they change the architecture? No, but if you check the code they use a patchgan and don’t include a block before the output layer in their paper description. The implementation I propose is based on the code they released. Dear author, I face difficult about load and save the GAN in doing my research. So Could you answer me about all type of GAN can save the model and load again.Thank you so much that you give me a chance to leave a Reply to u. You can see examples here: Can you share a link from where I can download this model (Github or Some online storage link). No. I do not share the trained model. My focus is on helping developers build the models and models like it. why your site ban Iran country ip? we are just eager students and your site is very helpful. Some governments have blocked access to my site, no idea why: How do we work with images that are larger than 256×256 and not necessarily square? Either scale the images to match the model or change the model to match the images. Hi Jason. Shouldn’t one use a custom loss function instead of mae in the section, How to Implement Adversarial and L1 Loss ? def L1(y_true, y_pred): x = K.abs(y_true – y_pred) return K.sum(x) Something like this instead of mae. Yes, we do this, see the “mae’ loss used in the composite model. We use L1 adversarial loss in this case, as is described in the paper. Alright, Thanks for clearing that up, Jason. Also, I noticed there isn’t anything specified for metrics in the compile functions. Are we supposed to leave that blank in GAN/ image generation problems ? Yes. Evaluating GANs is really really hard, doing it visually is the most reliable way: Hi Jason, how does the combined Model know on which output to perform which loss? Is it the order of the losses? So the first loss (“binary cross entropy”) will be calculated for the first argument of the output and mae will be calculated for the second? What do I do then if I want to calculate multiple losses for one of the outputs? We carefully constructed the model. Perhaps start with this simpler GAN to understand how the models are related: Hi Jason, Can you implement a Unpaired image to image translation using GAN in tensorflow using resnet block. As I wanted to learn this. Please if you can build a model from scratch it will be helpful. original paper: You can use a cyclegan for unpaired image to image translation: Hi Jason, Thanks for the informative tutorial. I am trying to use this for an image with size 81*81 instead of 256*256, but I am having a few problems. The most important issue is the inconsistent dimension for Conv2DTranspose. Are there any adjustments that should be done for this specific size? Thank you You will have to tune the model to the new size. It may require some trial and error. Hello Jason, I am trying to fit a UNet CNN to a task very similar to image to image translation. The input to the network is a binary matrix of size (64,256) and the output is of size (64,32). The accuracy on the training data is around 90% while the accuracy on the test is around 50%. By accuracy here, I mean the average percentage of correct entries in each image. Also, while training the validation loss increases while the loss decreases which is a clear sign of overfitting. I have tried most of the regularization techniques and also tried reducing the capacity of the model but this only reduces the training error while not improving the generalization error. Any advice or ideas? Intersting. Maybe some of the ideas here could be tried: Thanks a lot for the lesson. I tried to plot the composite (GAN) model without changing anything of your code but I got the following error: AttributeError: ‘ListWrapper’ object has no attribute ‘name’ Sorry to hear that, this might help: Hi Jason. I am trying to add gradient penalty, based on and Wasserstein loss ( from one of your articles). I am confused about how to modify the discriminator’s train_on_batch. Could you give me a few pointers? Sorry, I am not familiar with that article, perhaps ask the authors directly? . Very imp doubt. In section : How to Update Model Weights In the final code: def train (): g_loss, _, _ = gan_model.train_on_batch(X_realA, [y_real, X_realB]) . . Now in the gan_model(): model = Model(in_src, [dis_out, gen_out]) . . Its gen_out == its the output of the gen BUT in g_loss, _, _ = gan_model.train_on_batch(X_realA, [y_real, X_realB]) Its assigned as: gen_out = X_realB. this is puzzling me as X_realB is the “target” real img. . gen_out is output of the generator. In the train function X_fakeB is the “target” img generated by the generator. Then why is X_realB is used instead of X_fakeB ? . What is the problem you’re having exactly? Perhaps you can elaborate? Hi! Thanks for this wonderful post! I have a small confusion following this article and this next one: Here you’ve mentioned that the ‘patch_shape’ parameter in ‘generate_fake_samples’ and ‘generate_real_samples’ is to be passed as 16 in the section of ‘How to Update Model Weights’, but your other post passes a patch_shape of 1 for those functions. Could you clear out the difference in both examples please? Would be of great help. As far as I’ve understood, the architecture for the patch GAN discriminator is the same in both the posts. Patch_shape of 16 makes sense as you explain it here, but patch_shape of 1 is a bit confusing. You’re welcome. Perhaps the above example where we work through how the patch gan receptive field is calculated will help? Try working through that part of the tutorial. Yes, I did follow through that example calculation, but here I’m confused about what value does the ‘patch_shape’ parameter takes, in ‘generate_fake_samples’ and ‘generate_real_samples’ ? The output shape of 16×16 makes sense here in this article, but on your previous one here: You’ve taken the same patch_shape parameter as 1. ( in function summarize_performance(), 1st and 2nd line of code). Is there a difference that I’ve missed somewhere? No, they are the same I believe. Hi Jason. I reviewed almost all questions in different tutorials but didn’t find my answer. I want to use images of size 52*52*1 and can’t resize it to 256*256, so I guess I have to change the model itself. If I try to run it with only the input image size as changes, I’ve got some problem during concatenation: (None, 2, 2, 512) from one side and (None, 1, 1, 512) from the other. I think I have to remove some layers so this is what I tried naively and the same kind of error still remains until I only kept one encoding layer and one decoding layer. Is that the correct way to modify the model according to a smaller size of input images? What do I have to change as well? the “512” into the bottleneck? Thank you in advance for your reply as accurate as possible! Yes, you many (will!) need to customise the number and size of layers to achieve your desired inputs and outputs. I can’t thank you enough for these great tutorials. There is just a minor typo that i want to correct. while defining the the first block of decoder in the U-net generator, you said that “Batch normalization is not used in the first layer of the decoder.” However, batch normalization is used in the first layer of the decoder. I believe it should be encoder but not the decoder, because batch normalization is not used in the first layer of encoder C64. Thank you! Thanks, fixed!
https://machinelearningmastery.com/how-to-implement-pix2pix-gan-models-from-scratch-with-keras/
CC-MAIN-2021-31
refinedweb
6,772
54.42
Python. If you want to learn more about Python, I suggest you to follow the original documentation on Installation: Ubuntu: Type on the terminal: sudo apt update && upgrade sudo apt install python3 Windows: On windows you need to download the latest version of python from this page: and then you can install it easily following the instructions you see on the page. 1. Arithmetic Operators In python we use arithmetical operators to make common mathematical operations. >>> 5 + 5 #Addition 10 >>> 20 - 5 #Subtraction 15 >>>10 / 2 #Division 5.0 >>> 10 * 5 #Multiplication 50 >>> 2 ** 3 #Exponentiation 8 >>> 100 // 51 #Floor division 1 >>> 100 % 51 #Modulus 49 2. Variables and Strings We use variables to save informations. The process with wich we store an information is called “Variable assignement”. The Strings are characters one after another. To define a string in python we put the value between quotes “this is a sring”. animals = 15 # 15 print(animals) sentence = "the cat is on the table" #the cat is on the table print(sentence) 3. Data types The data types define what type of information the variable contains. If for example the variable contains an integer number, the type is “int”, if it’s text, the type is “str”. >>> bootles = 5 >>> type(bootles) int >>>>> type(sentence) str >>> minimumage = True >>> type(minimumage) bool 4. Boolean and Comparison Operators The boolean is a data type with 2 possible values: True or False. The comparison operators compare the values of two objects and return True or False. minimumage= 18 myage = 17 myage > minimumage # False myage < minimumage # True myage == minimumage # False myage != minimumage # True myage >= minimumage # False myage <= minimumage # True 5. If, Elif, Else We use the condition If, Elif, Else to make decisions. If executes the condition if it’s true. Elif executes the condition if none of the previous ones is true. Else executes teh condition if neither the If condition neither the Elif conditions are true. minimumage = 18 userage = 20 if userage > minimumage: print("You are too young") elif userage == minimumage: print("Just on time") else: print("Welcome you're old") 6. For Loop The For loop is used to iterate trough a list or a sequens so that we can access each single element individually. numbers = [2, 5, 87, 4, 3, 5, 9, 1] for n in numbers: print(n) 7. While Loop The while loop is a loop that only stops when the condition is not true anymore. count = 0 while 0 < 10: print(count) count += 1 print("Loop ended") 8. Break, Continue, Pass The Break statement breaks the loop. The Continue statement doesn’t execute the code that is after Continue if a certain condition is satisfied. The Pass statement does nothing. We use it only if we want to keep the syntax but we don’t want to do anything wiht a loop or a funcion. # Break count = 0 while 0 == 0: print(count) count += 1 if count == 10: break print("Loop ended") # Continue programming_languages = ["Python", "C++", "Java", "Javascript", "C#"] for p in programming_languages: print(p) if p == "Java" continue print("Extra Code") #Pass programming_languages = ["Python", "C++", "Java", "Javascript", "C#"] for p in programming_languages: pass 9. Functions The Function contains a block of code which will run only if it is called later. We can use functions to simplify the code for repetitive tasks. def calculate_mean(num1, num2 ): result = (num1 + num2) / 2 return result result = calculate_mean(51, 31 ) print(result) # 41.5 10. Standard Library Python has built-in a wide variety of functions and modules that can be user. These modules belong to the “Python Standard Library”. You can read more about it on the official documentation: import time time.sleep(5) print("Thanks for waiting") from math import sqrt print( sqrt(9) ) # 3.0 11. Project: Language Translator We’re going to build a Language Translator which translates english sentence into spanish in real time. eng_esp = {"hi": "hola", "fine": "bien", "thanks": "gracias", "how are you": "como estas"} print("Write a sentence and I'll translate it into Spanish for you:") print("type \"esc\" and press enter to quit") while True: sentence = input() sentence = sentence.lower() if sentence == "esc": break for word in eng_esp: translation = eng_esp.get(word) sentence = sentence.replace(word, translation) print
https://pysource.com/2020/06/11/python-beginners-course-tutorial-learn-python-from-scratch/?utm_source=rss&utm_medium=rss&utm_campaign=python-beginners-course-tutorial-learn-python-from-scratch
CC-MAIN-2020-29
refinedweb
705
63.9
- Committer: - leihen - Date: - 2013-06-23 - Revision: - 6:bba89618ee63 - Parent: - 5:30531f2121a2 - Child: - 7:dca20be3ef38 File content as of revision 6:bba89618ee63: /* Rtc_Ds1307.h */ /* Copyright (c) 2013 Henry Leinen (henry[dot]leinen [at] online [dot]TC_DS1307_H__ #define __RTC_DS1307_H__ /** Class Rtc_Ds1307 implements the real time clock module DS1307 * * You can read the clock and set a new time and date. * It is also possible to start and stop the clock. * Rtc_Ds1307 allows you to display the time in a 12h or 24h format */ class Rtc_Ds1307 { /** Structure which is used to exchange the time and date */ typedef struct { int sec; /*!< seconds [0..59] */ int min; /*!< minutes {0..59] */ int hour; /*!< hours [0..23] */ int wday; /*!< weekday [1..7, where 1 = sunday, 2 = monday, ... */ int date; /*!< day of month [0..31] */ int mon; /*!< month of year [1..12] */ int year; /*!< year [2000..2255] */ } Time_rtc; /** RateSelect specifies the valid frequency values for the square wave output */ typedef enum { RS1Hz = 0, RS4kHz = 1, RS8kHz = 2, RS32kHz = 3 } SqwRateSelect_t; I2C* m_rtc; static const char *m_weekDays[]; public: /** public constructor which creates the real time clock object * * @param sda : specifies the pin for the SDA communication line. * * @param scl : the pin for the serial clock * */ Rtc_Ds1307(PinName sda, PinName scl); ~Rtc_Ds1307(); /** Read the current time from RTC chip * * @param time : reference to a struct tm which will be filled with the time from rtc * * @returns true if successful, otherwise an acknowledge error occured */ virtual bool getTime(Time_rtc& time); /** Write the given time onto the RTC chip * * @param time : refereence to a struct which contains valid date and time information * * @param start : contains true if the clock shall start (or keep on running). * * @param thm : 12-hour-mode if set to true, otherwise 24-hour-mode will be set. * * @returns true if successful, otherwise an acknowledge error occured */ virtual bool setTime(Time_rtc& time, bool start, bool thm); /** Start started, false if a communication error occured */ bool startClock(); /** Stop stopped, false if a communication error occured */ bool stopClock(); /** Service function to convert a weekday into a string representation * * @param wday : day of week to convert (starting with sunday = 1, monday = 2, ..., saturday = 7 * * @returns the corresponding string representation */ const char* weekdayToString( int wday ) { return m_weekDays[wday%7]; } /** Enable Square Wave output. The function enables or disables the square wave output * of the module and sets the desired frequency. * * @param ena : if set to true, the square wave output is enabled. * * @param rs : rate select, can be either one of the four values defined by type /c RateSelect_t * * @return true if the operation was successful or false otherwise */ bool setSquareWaveOutput(bool ena, SqwRateSelect_t rs); private: bool read(int address, char* buffer, int len); bool write(int address, char* buffer, int len); static int bcdToDecimal(int bcd) { return ((bcd&0xF0)>>4)*10 + (bcd&0x0F); } static int decimalToBcd(int dec) { return (dec%10) + ((dec/10)<<4); } }; #endif // __RTC_DS1307_H__
https://os.mbed.com/users/leihen/code/RTC-DS1307/file/bba89618ee63/Rtc_Ds1307.h/
CC-MAIN-2021-10
refinedweb
475
57.71
I don't know how to convert an int to a sting in C++ and it is driving me nuts. I know this is easy. Can someone PLEASE help? This is a discussion on converting int to sting within the C++ Programming forums, part of the General Programming Boards category; I don't know how to convert an int to a sting in C++ and it is driving me nuts. I ... I don't know how to convert an int to a sting in C++ and it is driving me nuts. I know this is easy. Can someone PLEASE help? Code:#include <iostream> #include <sstream> using namespace std; int main () { int val; string mystr; stringstream ss (stringstream::in | stringstream::out); ss << "120 42 377 6 5 2000"; for (int n=0; n<6; n++) { ss >> val; cout << val*2 << endl; } return 0; } Now I really feel stupid...I have no clue what that bit of code does. Unless I'm totally wrong, that doesn't convert an int variable to a string. Specifically, I have to change the value 135 (or whatever) minutes into "2:15." I know there has to be an easy way to do this. I wish I could just use java...String.valueOf(int x). Oops, sorry about that, it's doing string to int. So you want int to string? PHP Code: #include <stringstream> #include <iostream> #include <string> using namespace std; string itos(int i) // convert int to string { stringstream s; s << i; // sent i to the stringstream return s.str(); } // return the contents of the stream // converted to a string int main() { int i = 127; string ss = itos(i); // Our function cout << ss << endl; // Print it } Last edited by Eibro; 10-13-2002 at 09:53 PM. thanks alot...that was what i was looking for. Code:#include <iostream.h> #include <stdlib.h> int main() { int num = 15; char string[10]; itoa(num, string, 10); return 0; } Is Stringstream not in VC++? #include <sstream>#include <sstream>Originally posted by Extol Is Stringstream not in VC++?
http://cboard.cprogramming.com/cplusplus-programming/26411-converting-int-sting.html
CC-MAIN-2014-52
refinedweb
341
81.83
Mar 08, 2009 11:06 AM|LINK I have never used the SqlCatalogProvider but presumably it has a number of tables in the DB all you would do is drag them onto the design surface of the dbml file you would need to provide you own custom logic to simulate the rest of the provider functionality (same for c# or VB) DD would then give you an admin tool to add data to any of the table ensuring relationships. Dynamic Data SqlCatalogProvider Mar 09, 2009 02:59 AM|LINK All right, cool, think I've found a way around the SqlCatalogProvider problem but now I get a Error 1 Too many arguments to 'Public Sub New()'. from: While r.Read() If TypeOf r("id") Is DBNull Or TypeOf r("visible") Is DBNull Or TypeOf r("title") Is DBNull Then Throw New InvalidOperationException(Messages.ItemRequiredAttributesMissing) End If curr = New Item(CStr(r("id")), CType(r("visible"), [Boolean]), CStr(r("title"))) curr.Description = Util.ReturnEmptyStringIfDbNull(r("description")) curr.NavigateUrl = Util.ReturnEmptyStringIfDbNull(r("navigateUrl")) curr.ImageUrl = Util.ReturnEmptyStringIfDbNull(r("imageUrl")) curr.ImageAltText = Util.ReturnEmptyStringIfDbNull(r("imageAltText")) list.Add(curr) End While Mar 09, 2009 11:27 AM|LINK Where's this code from? is it your code or some autogenerated code or from the Linq to SQL model code? Dynamic Data SqlCatalogProvider Mar 09, 2009 08:11 PM|LINK nbrglobalincThis code was taken out of the SqlCatalogProvider class. is that from the Small Business Kit of the DD Classes? Dynamic Data SqlCatalogProvider Mar 09, 2009 08:20 PM|LINK Yes, that is from the Small Business Kit. If I was able to attach my classes, I would definitely do that. My dbml has quite some code in it. Mar 09, 2009 10:35 PM|LINK nbrglobalincIf I was able to attach my classes, I would definitely do that. I think you may be able to put your business logic into an partial class for your dbml file, but that's not a trivial excecise. Dynamic Data Business Logic SqlCatalogProvider Mar 10, 2009 01:12 AM|LINK All right, after a couple days of tweaking and deleting several classes, I think I have found the problem, which to me seems to be the easiest after all the coding I did. When you move the tables and SPROCs from the SQL database into the Data.dbml, it will automatically take the id, visible, title, etc. so you can go ahead and delete the Item.vb(cs) class and the Category.vb(cs) class since the variables are declared in the data.dbml designer. Now in the Catalog.vb(cs), CatalogProvider.vb(cs), and SqlCatalogProvider.vb(cs) classes, I added an Import DataContext. The DataContext is found in the .dbml class file as part of the partial public class. And just to be on the safe side, I added it to the Messages, DataProvidersSection, ProviderSettingsValidation, and Util classes. And for the Items.aspx behind code, I also added the Import DataContext. When I go to run, it all works! :) [Yes]. So now instead of manually typing everything into an Xml file, I can just add it through Dynamic Data into my tables. Thanks to everyone for looking and responding! All-Star 15070 Points Microsoft Moderator Mar 10, 2009 01:26 AM|LINK Great job! Thanks for posting your results. 9 replies Last post Mar 10, 2009 01:26 AM by ricka6
http://forums.asp.net/p/1394270/2990700.aspx
CC-MAIN-2013-20
refinedweb
565
56.55
Oct 28, 2019 06:39 AM|binustrat|LINK Hi All, How can we retrieve data with subset data from sql server? I mean, when I take my personal information i want to get list of roles assigned to me in json format? For this purpose i am using 3 tables 1) User 2 Role 3 UserRole - Mapping user and role Below i am giving expecting result [{ "FirstName": "AAAA", "LastName": "PQR", "Roles": [ "RoleA", "RoleB", "RoleC" ] }] I am using FOR JSON PATH to get as json from sql Oct 28, 2019 08:12 AM|Yang Shen|LINK Hi binustrat, According to your description, i think what you really want is Json.NET. You can add it in your vs Nuget Package Management. After you get the data from your database, you just need to set them to a class User and one of its preperties is a string list. Please check below demo: using Newtonsoft.Json; using System; using System.Collections.Generic; class Program { static void Main(string[] args) { User user = new User(); user.FirstName = "John"; user.LastName = "Doe"; user.Roles = new List<string>(); user.Roles.Add("RoleA"); user.Roles.Add("RoleB"); user.Roles.Add("RoleC"); string json = JsonConvert.SerializeObject(user); Console.Write(json); } public class User { public string FirstName { get; set; } public string LastName { get; set; } public List<string> Roles { get; set; } } } Here's the result: Best Regard, Yang Shen Oct 28, 2019 12:55 PM|imapsp|LINK Hi, Try something like this: SELECT u.FirstName, u.LastName, json_query( '["' + (select string_agg(r.RoleName, '", "') from [UserRole] as ur inner join [Role] as r on r.IdRole = ur.IdRole where ur.IdUser = u.IdUser) + '"]') as Roles FROM [User] as u FOR JSON PATH Hope this help Oct 29, 2019 06:27 AM|Yang Shen|LINK Hi binustrat, Sorry for misunderstood your requirement before. binustrat[{ "FirstName": "AAAA", "LastName": "PQR", "Roles": [ "RoleA", "RoleB", "RoleC" ] }] The reason why @imapsp used string_agg is that he wants the create the Json-like format "Roles": ["RoleA","RoleB","RoleC"] manually since it's not the standard Json format which would be like "key" : "value" . The error 'STRING_AGG' is not a recognized built-in function name. is because that Visual Studio 2017 ships with SQL Server 2016 for LocalDb by default and therefore it does not support these new functions that exist in SQL 2017. You can solve it by upgrade your LocalDb version to SQL Server 2017 Express LocalDb, OR you can use STUFF combine with FOR XML PATH to replace it. You can refer to below code which is modified based on @imapsp's code: sql: create table #User ( UID int identity(1,1), FirstName varchar(50), LastName varchar(50) ) create table #Role ( RID int identity(1,1), RoleName varchar(50), ) create table #UserRole ( UID int, RID int ) insert into #User values('AAAA','PQR') insert into #User values('BBBB','SCF') insert into #Role values('RoleA') insert into #Role values('RoleB') insert into #Role values('RoleC') insert into #Role values('RoleD') insert into #UserRole values(1,1) insert into #UserRole values(1,2) insert into #UserRole values(1,3) insert into #UserRole values(2,1) insert into #UserRole values(2,4) SELECT u.FirstName, u.LastName, json_query( '["' + (select stuff((select ','+ r.RoleName from [#UserRole] as ur inner join [#Role] as r on r.RID = ur.RID where ur.UID = u.UID for xml path('')),1,1,'')) + '"]') as Roles FROM [#User] as u FOR JSON PATH You might need to update some places considering this demo is created without knowing the structure of your data tables. Here's the result of this demo: [{"FirstName":"AAAA","LastName":"PQR","Roles":["RoleA,RoleB,RoleC"]},{"FirstName":"BBBB","LastName":"SCF","Roles":["RoleA,RoleD"]}] You can see that's still not what you expected at first, if you won't accept this solution, you will need to upgrade your sql version. Best Regard, Yang Shen 5 replies Last post Oct 29, 2019 06:27 AM by Yang Shen
https://forums.asp.net/t/2161056.aspx?How+can+we+retrieve+data+with+subset+data+from+sql+server
CC-MAIN-2020-24
refinedweb
651
60.04
Introduction So I’ve been evaluating different ORM’s and I’ve decided to stick with Entity Framework. I’ve done some testing with NHibernate and discovered that it is very difficult to get running. I still need to spend more time to research NHibernate, but for now I think I’ll just run with Entity Framework. One of the positives of EF over NHibernate is the visual tool that makes it easy to setup the data objects. Our company is planning to employ interns starting in the Spring of 2014 and I’m thinking forward along the lines of using the KISS principle wherever I can. Later, when things are moving again, I can take another hard look at NHibernate and determine if we want to switch to that ORM over NHibernate. So Friday I began the tedious task of converting one of the LINQ-to-SQL subsystems to EF. Most of it went smoothly. We don’t currently have a lot of data access using an ORM, so now is the time to determine which tool we’re going to stick with. In order to get around the namespace weakness of EF, we are going to put our database access inside it’s own project or subdirectory. Our code will need to share tables that will be defined in one place. I think the ability to refactor will assist us in weeding out deprecated tables and fields in the future. One of my co-workers made me aware of an article called “Performance Considerations for Entity Framework 5″. This is quite lengthy and very detailed. I would recommend putting it on your “favorites” list and keep it handy when you’re ready to use EF. This article talks about EF version 5, but I’m sure they’ll update it for version 6 soon. Here’s an interesting side article for unit testing and mocking EF6: Testing with a mocking framework (EF6 onwards). So What’s the Point of Using an ORM? Speed is not necessarily the only reason for using a different data access model. In this case, the point is to catch SQL query mistakes at compile-time. In the good-old-days when queries were sent back to the database as a string, any errors in SQL were only detected when the query executed (i.e. run-time). ORM’s create objects that represent the tables, fields and other components of the database so that the developer can write a query directly in code (like C# or VB). The SQL statement written in code can have automatic syntax highlighting for errors and errors are detected at compile time. Of course, it’s still up to the software developer to write a correct query. At least this is one more step in reducing the amount of troubleshooting time a developer must take to get the software right. Unit Testing Unit testing is the latest new-hotness. Technically, unit testing has been around for some time (so it’s not new, but it’s still hot). In EF6 there is support for in-memory database mocking that can be used to test parts of your code. In the past I have used test databases that I generated in a local copy of MS SQL server. Using a test database means that I had to generate the tables and then tear them down when I was done. By creating data in memory, the whole process takes less time and resources. The reason why unit testing is so important in this instance is that many web applications are mostly database queries. I know that the software that at my current company contains mostly code to access and manipulate data. So unit tests that don’t test the queries that access the database are very limited. I’m currently looking at the unit testing and mocking of EF described here: Testing with a mocking framework (EF6 onwards). Specifically the “Testing query scenarios” section. If you’re using Moq, make sure you download the NuGet package for Moq (it’s not included in the base install of Visual Studio 2012). I’m hoping to be back with an example soon. Stay tuned…
http://blog.frankdecaire.com/2013/11/24/getting-the-show-on-the-road/
CC-MAIN-2018-05
refinedweb
701
70.53
Consider the case where we want to find the average test score of a class of students. Using individual variables: That’s a lot of variables and a lot of typing -- and this is just 5 students! Imagine how much work we’d have to do for 30 students, or 150. Plus, if a new student is added, a new variable has to be declared, initialized, and added to the totalScore calculation. Any time you have to modify old code, you run the risk of introducing errors. Using arrays offers a slightly better solution: This cuts down on the number of variables declared significantly, but totalScore still requires each array element be listed individually. And as above, changing the number of students means the totalScore formula needs to be manually adjusted. If only there were a way to loop through our array and calculate totalScore directly. Loops and arrays In a previous lesson, you learned that the array subscript doesn’t need to be a constant value -- it can be a variable. This means we can use a loop variable as an array index to loop through all of the elements of our array and perform some calculation on them. This is such a common thing to do that wherever you find arrays, you will almost certainly find loops! When a loop is used to access each array element in turn, this is often called iterating through the array. Here’s our example above using a for loop: This solution is ideal in terms of both readability and maintenance. Because the loop does all of our array element accesses, the formulas adjust automatically to account for the number of elements in the array. This means the calculations do not have to be manually altered to account for new students, and we do not have to manually add the name of new array elements! Here’s an example of using a loop to search an array in order to determine the best score in the class: In this example, we use a non-loop variable called maxScore to keep track of the highest score we’ve seen. maxScore is initialized to 0 to represent that we have not seen any scores yet. We then iterate through each element of the array, and if we find a score that is higher than any we’ve seen before, we set maxScore to that value. Thus, maxScore always represents the highest score out of all the elements we’ve searched so far. By the time we reach the end of the array, maxScore holds the highest score in the entire array. Mixing loops and arrays Loops are typically used with arrays to do one of three things: 1) Calculate a value (e.g. average value, total value) 2) Search for a value (e.g. highest value, lowest value). 3) Reorganize the array (e.g. ascending order, descending order) When calculating a value, a variable is typically used to hold an intermediate result that is used to calculate the final value. In the above example where we are calculating an average score, totalScore holds the total score for all the elements examined so far. When searching for a value, a variable is typically used to hold the best candidate value seen so far (or the array index of the best candidate). In the above example where we use a loop to find the best score, maxScore is used to hold the highest score encountered so far. Sorting an array is a bit more tricky, as it typically involves nested loops. We will cover sorting an array in the next lesson. Arrays and off-by-one errors One of the trickiest parts of using loops with arrays is making sure the loop iterates the proper number of times. Off-by-one errors are easy to make, and trying to access an element that is larger than the length of the array can have dire consequences. Consider the following program: The problem with this program is that the condition in the for loop is wrong! The array declared has 5 elements, indexed from 0 to 4. However, this array loops from 0 to 5. Consequently, on the last iteration, the array will execute this: But scores[5] is undefined! This can cause all sorts of issues, with the most likely being that scores[5] results in a garbage value. In this case, the probable result is that maxScore will be wrong. However, imagine what would happen if we inadvertently assigned a value to array[5]! We might overwrite another variable (or part of it), or perhaps corrupt something -- these types of bugs can be very hard to track down! Consequently, when using loops with arrays, always double-check your loop conditions to make sure you do not introduce off-by-one errors. Quiz time Question #1 Hint: You can use std::size (as of C++17) or the sizeof() trick (prior to C++17) to determine the array length. Show Solution Question #2 Ask the user for a number between 1 and 9. If the user does not enter a number between 1 and 9, repeatedly ask for an integer value until they do. Once they have entered a number between 1 and 9, print the array. Then search the array for the value that the user entered and print the index of that element. You can test std::cin for invalid input by using the following code: Question #3 Q2 answer..... Well. I tried. Is recursion bad? I also did a lot more input checking than I think was intended. I also used cpp reference to find a way to look ahead in the buffer. > Is recursion bad? Yes, use a loop - You don't need `newLine` and shouldn't use 10. You can use '\n' directly. - Triple duplicate code in `validateUserInput`. - Use ++prefix unless you need postfix++. Postfix++ is slower. - Hardcoding `array` in `printArrow` and `printIndex` made those functions non-reusable. Pass the array as a parameter. std::size() works for me even when I don't include the iterator header file...why?(I use visual studio community 2019) Includes are transitive Question #2 solution You tell me what's wrong - Line 7, 13 (Lesson 4.12) - Line 27, 36 (Lesson 5.4) - `searchElement` (Lesson 0.11) If you can't figure it out, let me know and I'll tell you Isn't this solution better in that there is one less iteration? Your idea only works if we know that `scores` has at least 1 element. For fixed-sized arrays, that's always the case, but we'll show other containers where this isn't true. Then there's always the question how far you'll take this. You could remove one more iteration if the array is large enough This game can be taken further and further. For that reason I usually keep it simple, even if it means looping once more. Anyway, good idea, works great for this quiz. My answers for the quiz: Q 2: Q 3: Looks good :) I've seen how dumb i was after seeing the solution for quiz 3 lol :) anyways here is how i managed to solve it. part of my solution to quiz 2 is to use a variable like this: What's wrong with using a variable in this manner? There isn't always a value that you can use to indicate an error. You now have a magic number, -1. (That's not a huge deal, because -1 is a common error code, but should be avoided). You can read lesson 14.1 (Don't worry about the high number, you should be able to understand what's relevant to you), which covers a very similar problem, for a more detailed explanation. Rather than using a magic value, you can use `std::optional` from. It's not covered on learncpp, so here's a small example hello,here is my solution for question #2: [code] #include "Header.h" #include<iterator> #include <iostream> int main() { int array[]{ 4, 6, 7, 3, 8, 2, 1, 9, 5 }; int numberOfElements{ static_cast<int>(std::size(array))}; for (int number{ 0 }; number < numberOfElements; ++number) { if (number == numberOfElements - 1) std::cout << array[number]<<".\n"; else std::cout << array[number] << " , "; } int inputNumber{}; while (std::cout << "Enter a number between 1 to 9 :" && (!(std::cin >> inputNumber)||(inputNumber>9))) { std::cin.clear(); std::cin.ignore(32757, '\n'); std::cout << "you have entered an invalid number please try again.\n"; } std::cout << "Your inputNumber is correct! wait a moment to search the array please...\n"; for(int number{0};number<numberOfElements;++number) if (inputNumber == array[number]) { std::cout << "the number is placed in index number \"" << number << "\"\n"; } system("pause"); } [\code] please look into the way I'm trying to validate user input.I asked you a question about it in last chapter if you remember it.is it a good way to do so ? I mean compared to cin.fail().I feel better about this one I used so wanna make sure both are equal and neat or not. also I would be thankful if you could tell me if my code is readable and I'm following best practices or not(since this is a small program I didn't add any comment to the code). thank you for your the effort you are putting into this website! Closing code tags use a forward slash (/). Your validation does unnecessary work (The check for `std::cout <<`, and clearing `std::cin` even if it's not erroneous) and is harder to understand. You noticed that yourself when you saw it on cppreference. There's nothing bad about using `std::cin >>` to get rid of the `std::cin.fail()` call, but don't use anything you don't need. - Don't use `std::system` if there's a way around it. It makes your code platform-dependent. If you're only using it for debugging, that's ok. 2 issues that were also present in the lesson (Updated now), these are the lesson's fault, not yours: - Use `constexpr` for compile-time constants. - If a loop's body exceeds 1 line, wrap it in curly braces. Is there a way to validate the integer user input, not the float one? Maybe you can try a modulus conditional statement? something like if (Number % 1 != 0). Hopefully more knowledgeable can help. In the examples above, why do we need to use static_cast<int> for numStudent? My compiler works just fine without it. This was previously asked by Robbas I still don't have a good reason to keep it, so I removed it from the lesson. For quiz 2, you are already iterating through the array so no need to do it again (i.e. find the appearance index in the same loop). The solution to third quiz replaces the maxScore with maxIndex variable to hold the index of maximum variable. The maxScore, however, should be kept together with the maxIndex, otherwise there won't be any way to find out what the max score is in the first place... You can get the maximum score by accessing the element and the maximum index, have a look at the solution. If access to the array was expensive, your solution would be better. I can't for the life of me find why std::size does not work in my function findIndex() - Any pointers as to what I have done wrong here are appreciated. The code compiles and works correctly if I just execute everything in main(). C-style arrays lose their size information when you pass them to functions, we talk about this later. You can add another parameter to `findIndex` to pass it the length, then call `std::size` in `main`. - Use ++prefix, you don't need postfix++. postfix++ is slower. - Enable compiler warnings, read them, fix them. `findIndex` is missing a `return`-statement (If the value isn't found). Quiz 1 and Quiz 2 Quiz 3 List initialization in line 42, the rest is brilliant :") Thank you! :) I'm not that new in C++;however, I have learned a lot more with this website. It seems I'm still use to assignment instead of brace initialization :p Hi Nascar and Alex. I was reviewing this lesson and I'd like a clarification about the std::size. Are we using the cast because std::size returns an unsigned value while we want a signed value, since we are using an int variable? Because, technically, for all the snippets in our cases this line is equivalent as a result to the one with the cast: So I just want to understand if this is the reason or there are other reasons for that. Thank you > Are we using the cast because std::size returns an unsigned value while we want a signed value, since we are using an int variable? Yes > for all the snippets in our cases this line is equivalent Yes that's right. I don't recall what made me add the casts. `std::size` runs at compile-time, which means the implicit conversion from unsigned to signed is allowed even in list initialization. I'll keep the casts for now. If I still can't remember why I added them the next time someone asks, I'll remove them. Ok perfect! Thank you so much Nascar. In question 3 the 'for' loop is initialised to 1. Since an array index starts at 0 (?) should it not be initialised to 0? maxIndex is set to 0 at the start, so the following line for student=0 will always be false: Yup. Got it!! Thanks My effort as follows. Nested the 'if' statement in main() for brevity. Any comments welcome. `arrayNum` is used uninitialized in line 41 if `userNum` wasn't found in `array`. This causes undefined behavior. The rest look good :) Thank you and, as ever, thanks for the hard work. :-)) My answer for question#3 Sorry, I think overdid it. :) Answer for question#1and2 I dont know if it's only on me or it also happen on somebody else, but in my case std::size seemingly didn't really need <iterator> directive to run. and Yes, i'm running on c++17 with maximum warning and error levels. Any idea why this is working? One of the other headers you included probably included the iterator header. You shouldn't rely on this, as implementation may differ across compilers. i'm using VSCode 2019 v6.1; my default cpp standard is set to C++20 & c standard to c11. but i cant use std::size(array) and it give me the following error: error: 'size' is not a member of 'std' int studentNum {static_cast<int>(std::size(score))}; is there any config i missed?? It doesn't matter which text editor you're using. You need to check which compiler you're using and look up if it supports C++17 (or C++20). The solution to Quiz 1 is "wrong" in terms of it doesn't correspond to the array asked in the question. I broke it during an update and didn't notice, it's fixed now. Thanks! This is my solution for quiz 2. I hope this is ok. - `std::size` returns a `std::size_t`, which is an unsigned integer type, but not necessarily `unsigned int`. - Use single quotation marks for characters (' ' instead of " "). Rest looks good :) I updated the code. Thank you very much! On code blocks 17.12 (also tried the 20191006 nightly): ||=== Build: Debug in 63 lesson (compiler: GNU GCC Compiler) ===| C:\Users\admin\Documents\cbprojects\63 lesson\main.cpp||In function 'int main()':| C:\Users\admin\Documents\cbprojects\63 lesson\main.cpp|7|error: 'size' is not a member of 'std'| ||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===| Defined in header <iterator> (since C++17) Pretty sure the compiler is configured as shown in the very first lessons, already checked twice. Even the example in cppreference shows the same error :( This is the setting you need to look for, but you need at least C++17. If C++17 isn't available, you need to update GCC. The compiler is configured exactly as shown, but the error was still occurring. Updating to MinGW-W64 GCC-8.1.0 (x86_64-posix-seh) fixed the issue. For those interested: The toolchain have to be configured manually in the compiler settings for the new binaries. Thanks for posting how you fixed it. I suppose you were using an old version of gcc and codeblocks didn't tell you that -std=c++17 was unsupported. For some reason, C::B is still using an old compiler (v5.1.x) with their IDE. You'll definitely have to upgrade your compiler to have C++17 capabilities. I'm using Qt 5.13.2 and it ships with MinGW 7.3.0 and is 100% C++17 compliant. Write a program that reads 10 scores of a student, then find a average 10 scores, a number of passing score and a number of failing score. Assume that possible score is 100 Passing score is 50 and above Failing score is 49 and below Where are you stuck? What have you tried? Why didn't it work? I tried to put numbers all together with int but, get did not work, can you show me how I should it be done, and thanks in advance. Show me your current code and mark what exactly you need help with. I won't do your homework for you. Here is my solution for Question #3 - Initialize your variables with brace initializers. - Compile-time constants should be `constexpr`. - Line 2: "C++14" :) fixed :) Name (required) Website Save my name, email, and website in this browser for the next time I comment.
https://www.learncpp.com/cpp-tutorial/63-arrays-and-loops/
CC-MAIN-2020-29
refinedweb
2,983
73.78
A friendly guide to what's moved in Umbraco 8 Many people (some might say hipsters…) were eager to start building sites with Umbraco 8 when it launched in February 2019. After what some might call a shaky start, with subsequent releases the product is rapidly improving. I’ve said on many occasions how it just feels so horrible using Umbraco 7 now I’ve worked with V8’s buttery-smooth interface! Umbraco 8 was a large rewrite of Umbraco, with many new concepts introduced. One of the biggest criticisms at launch was a lack of documentation of these changes, making it difficult to find the V8 equivalent of something in V7. We should all give the documentation team a massive #H5YR - they’ve been working their butts off for months gradually updating docs and adding detailed how-to guides! This article isn’t about what’s missing from the documentation per se, but some common things that have tripped me and others up along our V8 journeys so far. Backoffice The backoffice UI got a huge overhaul, with a new colour scheme and improved UX. Some standout changes are the sections bar moving from the left to the top, the removal of “tabs” on content items, the “Developer” section being combined with the “Settings” section, and “Packages” repository being moved its own section. Probably the biggest case of “moved cheese” in the backoffice is found in the context menus that appear when right clicking on a node in the content tree - something that will likely impact most CMS users, not just developers. If you’re trying to publish a content item directly from the tree, well now you can’t… It’s only possible to publish directly from a content item itself by using the “Save and Publish” button. I would assume this is to stop someone accidentally publishing something! This also means the “publish descendants” option has also disappeared from the tree - you will now find this under the small arrow next to the “Save and Publish” button on a content item. Publish descendants in Umbraco 8 A feature loved by many - “Change doctype”, the ability to change the doctype used for any node - has gone on vacation for a while… It might return at some point in the future, but it’s not on HQ’s priority list… It didn’t make it into the V8 release as the previous implementation was problematic in many cases. Previously the context menu at the root of the tree contained an option to “Republish entire site” which regenerated the XML cache - this behaviour has been moved into the “Published Status” dashboard under the “Settings” section. This makes a bunch of sense as it’s content editors who spend most of their time in the content tree whereas as this button in most likely for developers. Umbraco 8 cache refresh dashboard Events In Umbraco 7 you would use an ApplicationEventHandler class to hook into the events that the CMS triggered, for example, to tweak a value before it was saved or to register custom classes like Content Finders. Event Handlers are replaced by Composers which come in 2 different flavours and replace the familiar ApplicationStarting / ApplicationStarted methods from V7: - ApplicationStarting becomes **ICoreComposer **- runs while Umbraco is booting up - ApplicationStarted becomes **IUserComposer **- runs after Umbraco has fully booted up In 95% of cases you want to be using IUserComposer, as otherwise some Core Umbraco services that you depend upon may not have been initialised yet. Registering a custom content finder in V7: public class MyEventHandler : ApplicationEventHandler { protected override void ApplicationStarted(…) { ContentFinderResolver.Current.Insert<MyContentFinder>(); } } Registering a custom content finder in V8: public class MyComposer : IUserComposer { public void Compose(Composition composition) { composition.ContentFinders().Append<MyContentFinder>(); } } The composition parameter in a Composer can be used to register Components, Content Finders, Health Checks, Property Value Converters, Url Providers, Url Segment Providers, + much more - a move away from the Resolver pattern used in V7, and improving discoverability through intellisense. While the word “Composer” may sound scary, the examples above show how this is more a case of new terminology rather than a drastically new concept. There is in-depth documentation as well as a handy blog series by Stephan Gay explaining how it all works. Where's all the config? Umbraco 7 shipped with several XML config files used to configure the application: - Applications.config - configure CMS “sections” - Dashboards.config - configure CMS “dashboards” - ExamineIndexes.config - create Examine indexes and searchers - ExamineSettings.config - configure settings per Examine index - FileSystemProviders.config - configure which “file system” Umbraco should use - Trees.config - configure CMS “trees” - UmbracoSettings.config - generic Umbraco settings This was great - it was accessible! It was clear for those trying to find where something was or for those just getting started. In V8 only UmbracoSettings.config remains… So where has all this other stuff gone? How do you configure things now? A large amount of the config has moved into code. Config-as-code brings a lot of benefits you don’t get with traditional XML files, such as intellisense / autocomplete, and type safety. For Umbraco Core or package devs it can also mean not needing to write messy XML parsers for config files - winning! However this is at the cost of discoverability as the config files aren’t there for you to see. To configure something you likely need to be a C# developer, you need to know which C# classes to implement, and you would need to use Visual Studio to compile your config code. Furthermore in many cases an understanding some of the new concepts in Umbraco 8, such a Dependency Injection and Composition, is necessary too. It’s an interesting shift for a product that prides itself on being FRIENDLY and appealing to a broad group of developers, and there’s a fine line between doing things “right” and a solution working for users. Dashboards and Sections Gone are the days where you could manually add a bit of XML to the Dashboards.config file and it would appear in the Umbraco backoffice... Some may be upset, but I think this is a good thing. Too many times have I seen dashboards get wiped out by Umbraco upgrades or by installing packages. If you’re scrabbling around trying to work out how to create a dashboard in V8, well they can now be registered through a package.manifest file in the App_Plugins folder of your project, like this: { "dashboards": [ { "alias": "myCustomDashboard", "view": "/App_Plugins/myCustom/dashboard.html", "sections": [ "content", "settings" ], "weight": -10 } ] } If you prefer C# to JSON, they can also be configured in C# by implementing the IDashboard interface and adding a line like this into a composer: composition.Dashboards().Append<MyCustomDashboard>(); The same goes for custom sections which can also be configured in either JSON or C# - no more pesky XML files! The Umbraco documentation has fantastic articles with all you need to know about Dashboards, Sections and also Trees. File System Providers File System Providers are used to tell different parts of Umbraco, such as the media library, where to store your files. This could be on your local disk, a virtual path, or even a cloud storage service like Azure Blob Storage. Previously in Umbraco 7, you would configure your connection strings for the filesystem provider from within FileSystemProviders.config - each providers would be configured here using large amounts of confusing XML config. In Umbraco 8 this file is gone and these settings are now configured in appsettings in the web.config - this was an option in V7 too, but not the default. Arguably this implementation is actually friendlier than before, as all Umbraco configuration settings are kept in one place. It also makes it easier to store secure values, such as the Blob Storage connection string, in secure stores such as Azure Key Vault. One of the most popular packages is UmbracoFileSystemProviders.Azure from Jeavon Leopold, which enables you to store your Umbraco media files on Azure Blob Storage. At the time of writing v2.0.0-alpha-3 works on Umbraco 8 and it’s on NuGet, but you have to enable pre-release packages in your package manager to be able to install it. The package has now been split into 3: - UmbracoFileSystemProviders.Azure - UmbracoFileSystemProviders.Azure.Media - UmbracoFileSystemProviders.Azure.Forms Whereas for the V7 version of the package UmbracoFileSystemProviders.Azure would configure the media library to use Blob Storage, in V8 this purely contains the core file system provider needed to store anything on Azure. In order to configure media storage you must also install the UmbracoFileSystemProviders.Azure.Media library. I’ve seen many people get tripped up by this, installing the core package as they would have done in V7 and not knowing that the Media is also needed in order for it to work as before. It’s another small change to remember, but it makes things like the new UmbracoFileSystemProviders.Azure.Forms library for storing Umbraco Forms definitions possible. Examine In Umbraco 7 you could subscribe to an event called GatheringNodeData to populate values in Examine indexes, such as adding new fields or sanitizing values to make them searchable. In Umbraco 8 this event is called TransformingIndexValues. The event behaves in a very similar way, but the implementation differs slightly. I was pleased to see the search APIs had been cleaned up in V8, though it took a little while to find what I was looking for. ExamineManager.Instance.TryGetIndex("ExternalIndex", out var index); var searcher = index.GetSearcher(); var query = searcher.CreateQuery(); query = query.NodeTypeAlias("person").And().Field("nodeName", searchTerm) var results = query.Execute(); V7 had a method on UmbracoHelper called TypedSearch which returned results as IPublishedContent - you could also call the extension method ConvertSearchResultToPublishedContent directly on the result of a query. I spent hours trying to find an equivalent in Umbraco 8 as the feature is seemingly undocumented, but struck gold when I found ToPublishedSearchResults. Customising indexes Arguably 2 of the most config files in Umbraco 7, and the ones that caused most confusion, were ExamineIndexes.config and ExamineSettings.config - for creating indexes and searchers, as well as modifying the ones in core, plus defining which data and fields should be in an index. Much like other areas of the CMS, indexes are also configured in code in Umbraco 8 - by implementing IUmbracoIndexesCreator. The process for creating a custom index has some pretty clear documentation, and requires a bit more work than previously to get up-and-running, but offers a lot more power to control exactly how the index behaves which just wasn’t possible before. What about configuring settings of the Core indexes though? This was possible in V7, right? After a discussion with Examine-guru Ismail Mayat, it turned out a number of people were having difficulty with adjusting the config of Core Umbraco indexes (e.g. Internal / External / Media Index). When I dug deeper it transpired that it’s not possible to change any of these settings without using code - you would need to use dependency injection to replace Umbraco’s Core indexes and re-register them yourself. It seems crazy that anyone who wants to change one setting would have to do this each time, so I created a handy package to make this as FRIENDLY as possible 😉 Using Examine Config you can configure the types to include or exclude, and whether to include protected content items in any Core index directly from the web.config. Settings are configured as appsettings and follow a convention of: Umbraco.Examine.{INDEX-NAME}.{SETTING-NAME}. For example, to enable SupportProtectedContent for the "External" the name would be Umbraco.Examine.ExternalIndex.SupportProtectedContent. Debugging indexes For as long as I can remember (well, since the V4 days) Umbraco ran Lucene.NET v2.9.4.1 - which was released in December 2011! 🤯Because of the out-of-date Lucene version, we were also stuck with some pretty archaic tools for working with it. Those who have worked with Examine may be familiar with the tool Luke - a handy development and diagnostic tool for browsing Lucene indexes, checking a value exists or is what you expected, etc. With Lucene v2.9.1 you need to use Luke v0.9.9.1 (it’s so old, it’s on Google Code!)... Umbraco 8 takes us one step closer to the modern day, with a jump to Lucene.NET v3.0.3. If you try to open these indexes in Luke v0.9.9.1 you will get all kinds of fun errors. Thankfully I’ve been through this pain so you don’t have to! In order to use Luke with your new Lucene v3.0.3 indexes you need to install Luke v1.0.1 - so shiny and modern it was also released in 2011, but it works! Conclusion Amongst some of the more obvious changes, there’s still a handful of sneaky things that can trip you up on your first adventures with Umbraco 8 – from “missing” and moved features, incompatible tools, hidden configuration, and even “disappearing” Blob Storage media (trust me, I lost a whole day to this). The documentation is still THE place to go when you get stuck - it’s evolving constantly thanks to the tireless work of the awesome Documentation Creators and the friendly HQ team. It’s simply impossible to cover all of the different snags someone might come up against, but hopefully over time the cries of “how the hell do I do this?!” will diminish as Umbraco 8 matures and brave people like me experience (and share!) this pain first so others don’t have to ;-) Also in Issue No 54 Accessibility in an Umbraco Context by Jan Skovgaard
https://skrift.io/issues/who-moved-my-cheese/
CC-MAIN-2020-40
refinedweb
2,281
52.09
Logrus is a structured logger for Go (golang), completely API compatible with the standard library logger. on every build. Nicely color-coded in development (when a TTY is attached, otherwise just plain text): With log.Formatter = new(logrus.JSONFormatter), for easy parsing by logstash or Splunk: {"animal":"walrus","level":"info","msg":"A group of walrus emerges from the ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} {"level":"warning","msg":"The group's number increased tremendously!", "number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} {"animal":"walrus","level":"info","msg":"A giant walrus appears!", "size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} {"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", "size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} {"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, "time":"2014-03-10 19:57:38.562543128 -0400 EDT"} With the default log.Formatter = new(&log.TextFormatter{}) when a TTY is not attached, the output is compatible with the logfmt format: time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true exit status 1 The simplest way to use Logrus is simply the package-level exported logger: package main import ( log "github.com/Sirupsen/logrus" ) func main() { log.WithFields(log.Fields{ "animal": "walrus", }).Info("A walrus appears") } Note that it‘s completely api-compatible with the stdlib logger, so you can replace your log imports everywhere with log "github.com/Sirupsen/logrus" and you’ll now have the flexibility of Logrus. You can customize it all you want: package main import ( "os" log "github.com/Sirupsen/logrus" ) //") } For more advanced usage such as logging to multiple locations from the same application, you can also create an instance of the logrus Logger: package main import ( though logging fields instead of long, unparseable error messages. For example, instead of: log.Fatalf("Failed to send event %s to topic %s with key %d"), you should log the much more discoverable: log.WithFields(log.Fields{ "event": event, "topic": topic, "key": key, }).Fatal("Failed to send event") We‘ve found this API forces you to think about logging in a way that produces much more useful logging messages. We’ve been in countless situations where just a single added field to a log statement that was already there would've saved us hours. The WithFields call is optional. In general, with Logrus using any of the printf-family functions should be seen as a hint you should add a field, however, you can still use the printf-family functions with Logrus. You can add hooks for logging levels. For example to send errors to an exception tracking service on Error, Fatal and Panic, info to StatsD or log to multiple places simultaneously, e.g. syslog. Logrus comes with built-in hooks. Add those, or your custom hook, in init: import ( log "github.com/Sirupsen/logrus" "github.com/Sirupsen/logrus/hooks/airbrake" logrus_syslog ) } } Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic. log.Debug("Useful debugging information.") log.Info("Something noteworthy happened!") log.Warn("You should probably take a look at this.") log.Error("Something failed but I'm not quitting.") // Calls os.Exit(1) after logging log.Fatal("Bye.") // Calls panic() after logging log.Panic("I'm bailing.") You can set the logging level on a Logger, then it will only log entries with that severity or anything above it: // Will log anything that is info or above (warn, error, fatal, panic). Default. log.SetLevel(log.InfoLevel) It may be useful to set log.Level = logrus.DebugLevel in a debug or verbose environment if your application has that. Besides the fields added with WithField or WithFields some fields are automatically added to all logging events: time. The timestamp when the entry was created. msg. The logging message passed to {Info,Warn,Error,Fatal,Panic}after the AddFieldscall. E.g. Failed to send event. level. The logging level. E.g. info. Logrus has no notion of environment. If you wish for hooks and formatters to only be used in specific environments, you should handle that yourself. For example, if your application has a global variable Environment, which is a string representation of the environment you could do: import ( log "github.com/Sirupsen/logrus" ) init() { // do something here to set environment depending on an environment variable // or command-line flag if Environment == "production" { log.SetFormatter(&logrus.JSONFormatter{}) } else { // The TextFormatter is default, you don't actually have to do this. log.SetFormatter(&log.TextFormatter{}) } } This configuration is how logrus was intended to be used, but JSON in production is mostly only useful if you do log aggregation with tools like Splunk or Logstash.: zalgo: invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦. You can define your formatter by implementing the Formatter interface, requiring a Format method. Format takes an *Entry. entry.Data is a Fields type ( map[string]interface{}) with all your fields as well as the default ones (see Entries section above): type MyJSONFormatter struct { } log.SetFormatter(new(MyJSONFormatter)) func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { // Note this doesn't include Time, Level and Message which are available on // the Entry. Consult `godoc` on information about those fields or read the // source of the official loggers. serialized, err := json.Marshal(entry.Data) if err != nil { return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err) } return append(serialized, '\n'), nil } io.Writer Logrus can be transformed into an io.Writer. That writer is the end of an io.Pipe and it is your responsibility to close it. w := logger.Writer() defer w.Close() srv := http.Server{ // create a stdlib log.Logger that writes to // logrus.Logger. ErrorLog: log.New(w, "", 0), } Each line written to that writer will be printed the usual way, using formatters and hooks. The level for those entries is info. Log rotation is not provided with Logrus. Log rotation should be done by an external program (like logrotate(8)) that can compress and delete old log entries. It should not be a feature of the application-level logger.
https://chromium.googlesource.com/external/github.com/Sirupsen/logrus/+/refs/tags/v0.8.5/README.md
CC-MAIN-2020-05
refinedweb
1,152
51.14
I'm using Windows 7 Ultimate. I have set the built in firewall in outbound white list mode (block unless allowed by a rule). Now I'm trying to configure some outbound rules for the built in firewall. If I have C:\Dir\app.exe that tries to make outbound connections it gets blocked by default and if I add a rule specifically allowing it, it goes through. So far, perfectly fine. Everything works according to the fine manual. :) The problem is the filesystem structure that I use is a bit more complex (flexible): I have various disk drives aside from the one windows is installed on. Each volume (partition)(that Windows can read) is mounted under C:\mnt like this: C:\mnt\1 C:\mnt\2 C:\mnt\3 Then I use junctions (symlinks) from (for example): C:\Apps to C:\mnt\1\^W7_Apps C:\mnt\1\^W7_Apps has inside Network\Iron\Iron.exe so that makes C:\Apps\Network\Iron\Iron.exe a valid path (that is used to start that particular browser). This path is, for all intents and purposes (heh) as real a path as any. Windows Explorer sees it and is able to use it. Other file managers too. Back to the firewall. If I add a rule that allows C:\Apps\Network\Iron\Iron.exe to make outbound connections, it does not work. At all. If instead I add a rule that allows C:\mnt\1\^W7_Apps\Network\Iron\Iron.exe (shouldn't make a difference but hey) to make outbound connections, it also does not work. At all. I've installed Windows Firewall Notifier. This plugs into the Windows Firewall framework and adds some missing functionality. One missing function that it adds is notifications on outbound connection attempts from applications not already covered by a rule. When I then tested C:\Apps\Network\Iron\Iron.exe again, a popup asked me if I wanted to allow \device\harddiskvolume8\^w7_apps\network\iron\iron.exe to make that connection. BINGO! I thought. Internally, the firewall sees the path to the binary in that Object Manager namespace notation. Thank you fine manual for never mentioning this. But sadly, allowing that connection creates a rule that also doesn't work. Not sure if this question is best posted here on SuperUser or should it go to ServerFault or StackOverflow or to bugs@microsoft.com
https://superuser.com/questions/1030320/how-to-configure-windows-7-firewall-outbound-rules-for-symlinked-applications
CC-MAIN-2020-50
refinedweb
397
67.96
Feature #15836 [Proposal] Make Module#name and Symbol#to_s return their internal fstrings Description Why ?¶ In many codebases, especially Rails apps, these two methods are the source of quite a lot of object allocations. Module#name is often accessed for various introspection features, autoloading etc. Symbol#to_s is access a lot by HashWithIndifferentAccess other various APIs accepting both symbols and strings. Returning fstrings for both of these methods could significantly reduce allocations, as well as sligthly reduce retention as it would reduce some duplications. Also, more and more Ruby APIs are now returning fstrings. frozen_string_literalAFAIK should become the default some day, string used as hash keys are now automatically interned as well. Backward compatibilty¶ Of course this is not fully backward compatible, it's inevitable that some code in the wild is mutating the strings returned by these methods, but I do believe it's a rare occurence, and easy to fix. Implementation¶ I implemented it here: Updated by mame (Yusuke Endoh) over 1 year ago - Status changed from Open to Feedback Could you show us a benchmark, especially non-micro one? I believe that it is definitely required to discuss this proposal. Updated by Hanmac (Hans Mackowiak) over 1 year ago is the String returned by rb_sym2str not always frozen? how is the GC handling in case the Symbol was a dynamic generated one? wouldn't that remove the string that got returned from rb_sym2str too? Updated by chrisseaton (Chris Seaton) over 1 year ago how is the GC handling in case the Symbol was a dynamic generated one? It copies it - strings and symbols aren’t the same thing so it couldn’t jus return the symbol again. Updated by byroot (Jean Boussier) over 1 year ago mame (Yusuke Endoh) very good point. I'll try to run our app against that patch tomorrow. Updated by shevegen (Robert A. Heiler) over 1 year ago frozen_string_literalAFAIK should become the default some day Matz said that but it will not be for ruby 3.0 at the least. In my own code bases I am using frozen strings a lot, through the shebang; either "# frozen_string_literal: false" (initially) but these days more and more "# frozen_string_literal: true". I think other ruby users may be able to transition into frozen strings if enough time is given AND recommendations are given from the ruby core team in due time whenever there are (future) changes. string used as hash keys are now automatically interned as well. Although the use case for HashWithIndifferentAccess (I hate how long that name is ...) is probably not completely void, with strings being frozen it appears to me as if one use case (the speed factor) is nullified. There may be still other use cases probably, such as API design e. g. when people have to make a decision between "do I have to use a String or a Symbol here". Personally I like both strings and symbols, though; I think jeremy evans once gave a good explanation or wrote documentation to emphasis the distinction in the official doc (but I may misremember). Updated by byroot (Jean Boussier) over 1 year ago Matz said that but it will not be for ruby 3.0 at the least. I assumed it was due for 3.0, but good to know it isn't. I think other ruby users may be able to transition into frozen strings if enough time is given I contribute to many gems, and from what I can see # frozen_string_literal: true is extremely common. A good part is likely due to rubocop enforcing it, another is likely due to various article about how freezing strings made many codebases faster (sometimes oversold but that's another topic). with strings being frozen it appears to me as if one use case (the speed factor) is nullified I'm not 100% sure I understood your point correctly. What I meant by hash keys being frozen is: hash = {} string = :foo.to_s # One string allocated here hash[string] = true # A second string is allocated here because `Hash#[]=` apply: `-string.dup` If Symbol#to_s was to return it's internal fstring, the above snippet would save 2 string allocations. Updated by marcandre (Marc-Andre Lafortune) over 1 year ago Is HashWithIndifferentAccess the main rationale behind this request? I have doubts about the usefulness of HashWithIndifferentAccess today, now that Rails has protected parameters. Moreover, now that symbols are garbage collected, shouldn't its implementation use symbols for keys instead of strings? Updated by byroot (Jean Boussier) over 1 year ago Is HashWithIndifferentAccess the main rationale behind this request? No. It's simply the poster child of how common Symbol#to_s is in code bases. I shouldn't have mentioned HashWithIndifferentAccess because clearly lots of people have a feud with it, and now it's totally shifting the conversation. What the proposal is actually about¶ The question here, is wether Module#name and Symbol#to_s should return a new string on every call. My own understanding of why it's like this is because historically all strings were mutable, so the way to prevent them to be mutated was to duplicate them. But now that frozen strings are very common in code bases, and that fstring are a thing, IMHO getting a new string on every call is what is surprising. Updated by byroot (Jean Boussier) over 1 year ago mame (Yusuke Endoh) re benchmark So I decided to run this against redmine boot, using this branch: Eager loading is enabled so that the entire codebase is loaded, and it uses to measure allocations and retentions. Full benchmark output: Baseline (official 2.6.3): Total allocated: 121.11 MB (1234362 objects) Total retained: 24.86 MB (200539 objects) allocated memory by class ----------------------------------- 63.36 MB String allocated objects by class ----------------------------------- 980623 String With the patch (official 2.6.3 + this patch): Total allocated: 120.01 MB (1206699 objects) Total retained: 24.82 MB (199397 objects) allocated memory by class ----------------------------------- 62.25 MB String allocated objects by class ----------------------------------- 952953 String Diff: -27 663 allocations (-2.24%) -1.10MB allocations (-0.9%) -1 142 retentions (-0.57%) -0.4MB retentions (-0.16%) IMHO that is significant, especially for a small sized application like Redmine. However I can't say wether it outweigh the backward compatibility concern or not. Backward compatibility¶ One thing to note is that I had to patch because it was mutating the result of Symbol#to_s. Also running the Redmine test suite shows a couple breakage in the i18n gem. IMHO these are fairly simple to fix, but I would totally understand if that was considered as a no-go. Typical code benefiting from this change¶ - Rails autoloader and Zeitwerk would both benefit from the Module#namechange as they both keep references to class names as hash keys - Various parts of Rails would benefit as well since they use the class names extensively to derive other class names, as well as symbols belongs_to :post. def method_missingvery often call name.to_sto match the method name, hence would benefit from the Symbol#to_sas well. - Serialization of symbols into various formats, e.g. {foo: 42}.to_json. That pattern is fairly common IMO. Updated by ahorek (Pavel Rosický) over 1 year ago byroot (Jean Boussier) thanks for sharing the benchmark! IMO module names should be frozen even if it's easy to fix, this change could definitely break existing apps that depend on it, see Updated by duerst (Martin Dürst) over 1 year ago Isn't one main purpose of converting a Symbol to a String that you want to change the symbol string? This proposal would make that use case more tedious. Updated by matz (Yukihiro Matsumoto) over 1 year ago - Status changed from Feedback to Rejected The compatibility breakage from changing those methods (especially Symbol#to_s) is too big. Sorry. Maybe we should work on HashWithIndifferentAccess to improve (memory) performance. Matz. Also available in: Atom PDF
https://bugs.ruby-lang.org/issues/15836?tab=history
CC-MAIN-2020-40
refinedweb
1,318
63.09
On Tue, Jul 13, 2010 at 1:23 PM, KAMEZAWA Hiroyuki<kamezawa.hiroyu@jp.fujitsu.com> wrote:> On Tue, 13 Jul 2010 13:11:14 +0900> Minchan Kim <minchan.kim@gmail.com> wrote:>>> On Tue, Jul 13, 2010 at 12:19 PM, KAMEZAWA Hiroyuki>> <kamezawa.hiroyu@jp.fujitsu.com> wrote:>> > On Tue, 13 Jul 2010 00:53:48 +0900>> > Minchan Kim <minchan.kim@gmail.com> wrote:>> >>> >> Kukjin, Could you test below patch?>> >> I don't have any sparsemem system. Sorry.>> >>>> >> -- CUT DOWN HERE -->> >>>> >>.>> >> So in above case, pfn on 0x25000000 can pass pfn_valid's validation check.>> >> It's not what we want.>> >>>> >> The Following patch adds check valid pfn range check on pfn_valid of sparsemem.>> >>>> >> Signed-off-by: Minchan Kim <minchan.kim@gmail.com>>> >> Reported-by: Kukjin Kim <kgene.kim@samsung.com>>> >>>> >> P.S)>> >> It is just RFC. If we agree with this, I will make the patch on mmotm.>> >>>> >> -->> >>>> >> diff --git a/include/linux/mmzone.h b/include/linux/mmzone.h>> >> index b4d109e..6c2147a 100644>> >> --- a/include/linux/mmzone.h>> >> +++ b/include/linux/mmzone.h>> >> @@ -979,6 +979,8 @@ struct mem_section {>> >> struct page_cgroup *page_cgroup;>> >> unsigned long pad;>> >> #endif>> >> + unsigned long start_pfn;>> >> + unsigned long end_pfn;>> >> };>> >>>> >>> > I have 2 concerns.>> > 1. This makes mem_section twice. Wasting too much memory and not good for cache.>> > But yes, you can put this under some CONFIG which has small number of mem_section[].>> >>>>> I think memory usage isn't a big deal. but for cache, we can move>> fields into just after section_mem_map.>>> I don't think so. This addtional field can eat up the amount of memory you saved> by unmap.Agree.>>> > 2. This can't be help for a case where a section has multiple small holes.>>>> I agree. But this(not punched hole but not filled section problem)>> isn't such case. But it would be better to handle it altogether. :)>>>> >>> > Then, my proposal for HOLES_IN_MEMMAP sparsemem is below.>> > ==>> > Some architectures unmap memmap[] for memory holes even with SPARSEMEM.>> > To handle that, pfn_valid() should check there are really memmap or not.>> > For that purpose, __get_user() can be used.>>>> Look at free_unused_memmap. We don't unmap pte of hole memmap.>> Is __get_use effective, still?>>> __get_user() works with TLB and page table, the vaddr is really mapped or not.> If you got SEGV, __get_user() returns -EFAULT. It works per page granule.I mean following as.For example, there is a struct page in on 0x20000000.int pfn_valid_mapped(unsigned long pfn){ struct page *page = pfn_to_page(pfn); /* hole page is 0x2000000 */ char *lastbyte = (char *)(page+1)-1; /* lastbyte is 0x2000001f */ char byte; /* We pass this test since free_unused_memmap doesn't unmap pte */ if(__get_user(byte, page) != 0) return 0; /* * (0x20000000 & PAGE_MASK) == (0x2000001f & PAGE_MASK) * So, return 1, it is wrong result. */ if ((((unsigned long)page) & PAGE_MASK) == (((unsigned long)lastbyte) & PAGE_MASK)) return 1; return (__get_user(byte,lastbyte) == 0);}Am I missing something?-- Kind regards,Minchan Kim--To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
https://lkml.org/lkml/2010/7/13/42
CC-MAIN-2016-26
refinedweb
506
70.39
wcstombs - convert a wide-character string to a character string #include <stdlib.h> size_t wcstombs(char *s, const wchar_t *pwcs, size_t n); The wcstombs() function converts the sequence of wide-character codes that are in the array pointed to by pwcs into a sequence of characters that begins in the initial shift state and stores these characters into the array pointed to by s, stopping if a character would exceed the limit of n total bytes or if a null byte is stored. Each wide-character code is converted as if by a call to wctomb(), except that the shift state of wctomb() is not affected. The behaviour of this function is affected by the LC_CTYPE category of the current locale. No more than n bytes will be modified in the array pointed to by s. If copying takes place between objects that overlap, the behaviour is undefined. If s is a null pointer, wcstombs() returns the length required to convert the entire array regardless of the value of n, but no values are stored. function returns the number of bytes required for the character array.: - [EILSEQ] - A wide-character code does not correspond to a valid character. None. None. None. mblen(), mbtowc(), mbstowcs(), wctomb(), <stdlib.h>. Derived from the ISO C standard.
http://pubs.opengroup.org/onlinepubs/7990989775/xsh/wcstombs.html
CC-MAIN-2014-49
refinedweb
213
60.95
Chapter Output So up to this point, we've typed a lot of code, but we've never seen it really do anything yet. Programming is all about input and output, and writing code could be considered input in its own right. But we're not going to have any fun until we get some output. I held off on the output aspect because I didn't want introduce things out of order, but no more! We're ready, sort of! The Console Now that we have functions, we can start displaying our data in the console. The console is a program that allows us to run applications via typing commands; it also provides us a quick and easy way to get input from the user and write output on the screen. We'll use it for output in our case. If you're using try.purescript.org, you can bring up the console right in your browser by pressing ctrl shift J on linux/windows, or cmd option J on mac. This should work on any chrome-like browsers (Chrome, Chromium, Brave, Edge, etc) and firefox. Easy output with spy To get our first taste of writing output to the console, we're going to use a function called spy. This isn't the recommended way to really write output, but it will suffice for the time being. For our first example, we'll start by writing the values of simple variables to the console. module Main where import Prelude import Debug.Trace coolInt :: Int coolInt = spy "Cool num" 24 dumbBool :: Boolean dumbBool = spy "Dumb!" true Enter the above code into your code window and then open up the dev console. You should see Cool num: 24 Dumb!: true Imports So whats happening here? We have two new things we haven't really seen before. First, we have the line import Debug.Trace We haven't talked about imports yet, but heres a quick rundown. People all over the world are writing code. If they publish that code online, we can pull it into our own program. The code we pull in are called libraries. Libraries are comprised of 1 or more modules. Here, we import the Debug.Trace module from the library purescript-debug. (A listing of most published libraries can be found at pursuit.purescript.org). We'll take a deeper look into imports in a later chapter. Polymorphism and the spy function The next line of interest is: coolInt = spy "Cool num" 24 This isn't totally weird, whats happening here? As mentioned above spy is a function. Lets look at it's type declaration spy :: forall a. String -> a -> a Ah! Another new thing! Whats this weird forall a. line? This is called polymorphism, the term sounds scary, but the concept isnt. forall a. is a sort of type declaration that says: "We have some type called a, and we dont care what it is! You can use anything for a and we'll be ok!" What does it mean that a can be anything? Lets look at another example. Lets look at a function called identity identity :: forall a. a -> a identity x = x Can you guess what identity does? Its a function that takes one parameter. This parameter can be anything, and all it does is return that parameter back to you. Lets try it out! module Main where import Prelude coolNum = identity 40 -- coolNum = 40 someText = identity "hello" -- someText = "hello" youCanDoIt = identity true -- youCanDoIt = true That doesn't seem very useful... Well, I won't go into the explanation of how identity can be useful, but this gives a good demonstration of how polymorphism works. We used three different types of values on the identity function: An Int 40, a String "hello", and a Boolean true; and it happily accepted them. Contrast this with the following module Main where import Prelude numIdentity :: Int -> Int numIdentity x = x -- Compile error here someText = numIdentity "Hello" The above doesn't work because numIdentity needs it's first parameter to be an Int. This isn't the case with identity, identity says "You can give me anything and I'll still work"! We'll take a closer look at polymorphism later as well. Back to the spy So let's look at the type of spy again spy :: forall a. String -> a -> a I won't show the actual definition of spy, but essentially, it takes a String and an a (which can be anything); writes them to the console, and then returns the a parameter. So its sort of like identity, but with some hidden side effects. So hopefully our original block of code makes a little more sense now module Main where import Prelude import Debug.Trace coolInt :: Int coolInt = spy "Cool num" 24 dumbBool :: Boolean dumbBool = spy "Dumb!" true Spy the functions The way we used spy up above is not how its typically used. There's no need to use spy on plain old variables, it's more useful in functions. module Main where import Prelude import Debug.Trace doubleTheBank :: Int -> Int doubleTheBank money = spy "double the money is" (money * 2) johnBank :: Int johnBank = doubleTheBank 100 tobyBank :: Int tobyBank = doubleTheBank (400) Now we'll see in the console double the money is: 200 double the money is: 800 Each time doubleTheMoney is called, we'll get some output in the console. So there we go, here's our first taste of output. There's more official ways to get output, but we need to learn a bit more before we can tackle that task. Summary We can use the spy function to output the values of variables to the console. In the web browser, you can open the comsole by pressing ctrl shift J on linux/windows, or cmd option J on mac (for chrome based browsers and firefox) In order to use spy, you must import the module Debug.Trace spy uses a polymorphic parameter, meaning you can use any value for that parameter. Heres the type declaration for spy spy :: forall a. String -> a -> a Heres an example using spy module Main where import Prelude import Debug.Trace doubleNumber x = (spy "Doubling" x) * 2 jakesAge = doubleNumber 20 bensMoney = doubleNumber 4 The above example will output Doubling: 20 Doubling: 4 Self Practice Lets write a greeting function. Write a function that takes a string parameter and says hello to it before returning it. For example, if the string is "Mr.X", then in the console, we should see Hello: Mr.X Answer greeting :: String -> String greeting name = spy "Hello" name
https://book.vanceism7.ml/Output.html
CC-MAIN-2021-31
refinedweb
1,099
73.78
C program to print vowels in a string - C Program to calculate frequency of vowels in a String Learn C - C tutorial - C Program to calculate frequency of vowels in a string - C examples - C programs C program to print vowels in a string - C program to count number of vowels in a string For example, In the string "C programming" there are three vowels 'o', 'a' and 'i'. - In the program both lower and upper case are considered i.e 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O' and 'U'. - We undergoes checking every character in the input string, if it's a vowel then counter is incremented by one, consonants and others characters are ignored. #include <stdio.h> void main() { int a=1,e=1,i=1,o=1,u=1,sum=0; char c; while ((c=getchar())!=EOF) { if (c=='a'||c=='A') a=a+1; if (c=='e'||c=='E') e=e+1; if (c=='i'||c=='I') i=i+1; if (c=='o'||c=='O') o=o+1; if (c=='u'||c=='U') u=u+1; } sum=a+e+i+o+u; printf("\nFrequency of vowel 'a' is %d.",a); printf("\nFrequency of vowel 'e' is %d.",e); printf("\nFrequency of vowel 'i' is %d.",i); printf("\nFrequency of vowel 'o' is %d.",o); printf("\nFrequency of vowel 'u' is %d.",u); printf("\nsum of vowel frequeny %d.",sum); } Frequency of vowel 'a' is 1. Frequency of vowel 'e' is 1. Frequency of vowel 'i' is 1. Frequency of vowel 'o' is 1. Frequency of vowel 'u' is 1. sum of vowel frequeny 5.
https://www.wikitechy.com/tutorials/c-programming/c-program-to-print-vowels-in-a-string
CC-MAIN-2019-51
refinedweb
270
67.25
From: Matthias Troyer (troyer_at_[hidden]) Date: 2006-09-18 13:38:35 Hi Ian, On Sep 18, 2006, at 6:35 PM, Ian McCulloch wrote: >>> Really its only a name change - and "packed archive" is already >>> inside an >>> mpi namespace so its not a huge issue. BUT I'm wondering if the >>> idea of >>> rendering C++ data structures as MPI primitives should be more >>> orthogonal to >>> MPI prototcol itself. That is, might it not be sometimes >>> convenient to save >>> such serializations to disk? Wouldn' this provide a portable >>> binary format >>> for free? (Lots of people have asked for this but no one as been >>> sufficiently interested to actually invest the required effort). >> >> As Doug Gregor pointed out this is not possible since the format is >> implementation-defined, and can change from one execution to another. > > This is only true for MPI-1.1. MPI-2 supports multiple data > representations > and adds the functions MPI_Pack_external and MPI_Unpack_external to > convert > to/from the "external32" format defined in section 9.5.2 of the MPI-2 > standard. The intent of this is to be able to transfer data > between MPI > implementations. Also, as part of the file I/O interface, MPI-2 also > allows user-defined representations so in principle it would be > possible to > make some kind of adaptor to read a different archive format via > the MPI-2 > file I/O. Not that MPI file I/O seems to be used much anyway... The current library is based on MPI-1.1 only, which is reasonably stable. A future extension of the library to MPI-2 could indeed include the use of MPI-I/O to write portable binary archives. Matthias Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2006/09/110346.php
CC-MAIN-2021-25
refinedweb
302
57.06
Largest Divisor of a Number not divisible by a perfect square Given a positive integer N. Find the largest divisor of the given number that is not divisible by a perfect square greater than 1. Examples: Input : 12 Output : 6 Explanation : Divisors of 12 are 1, 2, 3, 4, 6 and 12. Since 12 is divisible by 4 (a perfect square), it can't be required divisor. 6 is not divisible by any perfect square. Input :97 Output :97 A simple approach is to find all the divisors of the given number N by iterating upto square root of N and keep them in sorted order(Descending) in a list. Here we are inserting them in a set in descending order to keep them sorted. Also, make a list of all perfect squares upto 1010 by iterating from 1 to 105. Now for each divisor starting from the greatest one check whether it is divisible by any perfect square in the list or not. If a divisor is not divisible by any perfect, simply return it as the answer. Below is the implementation of the above approach. C++ Python3 # Python3 Program to find the largest # divisor not divisible by any # perfect square greater than 1 MAX = 10 ** 5 # Function to find the largest # divisor not divisible by any # perfect square greater than 1 def findLargestDivisor(n): # set to store divisors in # descending order m = n s = set() s.add(1) s.add(n) for i in range(2, int(n ** (0.5)) + 1): # If the number is divisible # by i, then insert it if n % i == 0: s.add(n // i) s.add(i) while m % i == 0: m //= i if m > 1: s.add(m) # Vector to store perfect squares vec = [i**2 for i in range(2, MAX + 1)] # Check for each divisor, if it is not # divisible by any perfect square, # simply return it as the answer. for d in sorted(s, reverse = True): divi, j = 0, 0 while j < len(vec) and vec[j] <= d: if d % vec[j] == 0: divi = 1 break j += 1 if not divi: return d # Driver Code if __name__ == "__main__": n = 12 print(findLargestDivisor(n)) n = 97 print(findLargestDivisor(n)) # This code is contributed by Rituraj Jain [tabbyending] 6 97 An efficient approach is to divide n by i for every i such that (i * i) divides n. C++ Java Python3 C# PHP 6 97 Recommended Posts: - Largest number that is not a perfect square - Largest perfect square number in an Array - Largest factor of a given number which is a perfect square - Number of times the largest perfect square number can be subtracted from N - Smallest perfect square divisible by all elements of an array - Check if a number is perfect square without finding square root - number in an array that is not a perfect cube - Largest number with the given set of N digits that is divisible by 2, 3 and 5 - Largest number divisible by 90 that can be made using 0ivi_Aggarwal, Code_Mech, ChitraNayal, rituraj_jain
https://www.geeksforgeeks.org/largest-divisor-of-a-number-not-divisible-by-a-perfect-square/
CC-MAIN-2019-22
refinedweb
507
54.26
Java Generics Interview Questions (+Answers) Last modified: April 2, 2017 by baeldung Java If you’re working with Spring, check out "REST With Spring": >> CHECK OUT THE COURSE 1. Introduction In this article, we’ll go through some example Java generics interview questions and answers. Generics are a core concept in Java, first introduced in Java 5. Because of this, nearly all Java codebases will make use of them, almost guaranteeing that a developer will run into them at some point. This is why it’s essential to understand them correctly, and is why they are more than likely to be asked about during an interview process. 2. Questions Q1. What is a Generic Type Parameter? Type is the name of a class or interface. As implied by the name, a generic type parameter is when a type can be used as a parameter in a class, method or interface declaration. Let’s start with a simple example, one without generics, to demonstrate this: public interface Consumer { public void consume(String parameter) } In this case, the method parameter type of the consume() method is String. It is not parameterized and not configurable. Now let’s replace our String type with a generic type that we will call T. It is named like this by convention: public interface Consumer<T> { public void consume(T parameter) } When we implement our consumer, we can provide the type that we want it to consume as an argument. This is a generic type parameter: public class IntegerConsumer implements Consumer<Integer> { public void consume(Integer parameter) } In this case, now we can consume integers. We can swap out this type for whatever we require. Q2. What Are Some Advantages of Using Generic Types? One advantage of using generics is avoiding costs and provide type safety. This which is particularly useful when working with collections. Let’s demonstrate this: Let’s demonstrate this: List list = new ArrayList(); list.add("foo"); Object o = list.get(1); String foo = (String) foo; In our example, the element type in our list is unknown to the compiler. This means that the only thing that can be guaranteed is that it is an object. So when we retrieve our element, an object is what we get back. As the authors of the code, we know it’s a String, but we have to cast our object to one to fix the problem explicitly. This produces a lot of noise and boilerplate. Next, if we start to think about the room for manual error, the casting problem gets worse. What if we accidentally had an integer in our list? list.add(1) Object o = list.get(1); String foo = (String) foo; In this case, we would get a ClassCastException at runtime, as an Integer cannot be cast to String. Now, let’s try repeating ourselves, this time using generics: List<String> list = new ArrayList<>(); list.add("foo"); String o = list.get(1); // No cast Integer foo = list.get(1); // Compilation error As we can see, by using generics we have a compile type check which prevents ClassCastExceptions and removes the need for casting. The other advantage is to avoid code duplication. Without generics, we have to copy and paste the same code but for different types. With generics, we do not have to do this. We can even implement algorithms which apply to generic types. Q3. What is Type Erasure? It’s important to realize that generic type information is only available to the compiler, not the JVM. In other words, type erasure means that generic type information is not available to the JVM at runtime, only compile time. The reasoning behind major implementation choice is simple – preserving backward compatibility with older versions of Java. When a generic code is compiled into bytecode, it will be as if the generic type never existed. This means that compilation will: Replace generic types with objects Replace bounded types (More on these in a later question) with the first bound class Insert the equivalent of casts when retrieving generic objects. It’s important to understand type erasure. Otherwise, a developer might get confused and think they’d be able to get the type at runtime: public foo(Consumer<T> consumer) { Type type = consumer.getGenericTypeParameter() } The above example is a pseudo code equivalent of what things might look like without type erasure, but unfortunately, it is impossible. Once again, the generic type information is not available at runtime. Q4. If a Generic Type is Omitted When Instantiating an Object, will the Code Still Compile? As generics did not exist before Java 5, it is possible not to use them at all. For example, generics were retrofitted to most of the standard Java classes such as collections. If we look at our list from question one, then we will see that we already have an example of omitting the generic type: List list = new ArrayList(); Despite being able to compile, it’s still likely that there will be a warning from the compiler. This is because we are losing the extra compile time check that we get from using generics. The point to remember is that while backward compatibility and type erasure make it possible to omit generic types, it is bad practice. Q5. How Does a Generic Method Differ From a Generic Type? A generic method is where a type parameter is introduced to a method, living within the scope of that method. Let’s try this with an example: public static <T> T returnType(T argument) { return argument; } We’ve used a static method but could have also used a non-static one if we wished. By leveraging type inference (covered in the next question), we can invoke this like any ordinary method, without having to specify any type arguments when we do so. Q6. What is Type Inference? Type inference is when the compiler can look at the type of a method argument to infer a generic type. For example, if we passed in T to a method which returns T, then the compiler can figure out the return type. Let’s try this out by invoking our generic method from the previous question: Integer inferredInteger = returnType(1); String inferredString = returnType("String"); As we can see, there’s no need for a cast, and no need to pass in any generic type argument. The argument type only infers the return type. Q7. What is a Bounded Type Parameter? So far all our questions have covered generic types arguments which are unbounded. This means that our generic type arguments could be any type that we want. When we use unbounded parameters, we are restricting the types that can be used as generic type arguments. As an example, let’s say we want to force our generic type always to be a subclass of animal: public abstract class Cage<T extends Animal> { abstract void addAnimal(T animal) } By using extends, we are forcing T to be a subclass of animal. We could then have a cage of cats: Cage<Cat> catCage; But we could not have a cage of objects, as an object is not a subclass of an animal: Cage<Object> objectCage; // Compilation error One advantage of this is that all the methods of animal are available to the compiler. We know our type extends it, so we could write a generic algorithm which operates on any animal. This means we don’t have to reproduce our method for different animal subclasses: public void firstAnimalJump() { T animal = animals.get(0); animal.jump(); } Q8. Is it Possible to Declared a Multiple Bounded Type Parameter? Declaring multiple bounds for our generic types is possible. In our previous example, we specified a single bound, but we could also specify more if we wish: public abstract class Cage<T extends Animal & Comparable> In our example, the animal is a class and comparable is an interface. Now, our type must respect both of these upper bounds. If our type were a subclass of animal but did not implement comparable, then the code would not compile. It’s also worth remembering that if one of the upper bounds is a class, it must be the first argument. Q9. What is a Wildcard type? A wildcard type represents an unknown type. It’s detonated with a question mark as follows: public static consumeListOfWildcardType(List<?> list) Here, we are specifying a list which could be of any type. We could pass a list of anything into this method. Q10. What is an Upper Bounded Wildcard? An upper bounded wildcard is when a wildcard type inherits from a concrete type. This is particularly useful when working with collections and inheritance. Let’s try demonstrating this with a farm class which will store animals, first without the wildcard type: public class Farm { private List<Animal> animals; public void addAnimals(Collection<Animal> newAnimals) { animals.addAll(newAnimals); } } If we had multiple subclasses of animal, such as cat and dog, we might make the incorrect assumption that we can add them all to our farm: farm.addAnimals(cats); // Compilation error farm.addAnimals(dogs); // Compilation error This is because the compiler expects a collection of the concrete type animal, not one it subclasses. Now, let’s introduce an upper bounded wildcard to our add animals method: public void addAnimals(Collection<? extends Animal> newAnimals) Now if we try again, our code will compile. This is because we are now telling the compiler to accept a collection of any subtype of animal. Q11. What is an Unbounded Wildcard? An unbounded wildcard is a wildcard with no upper or lower bound, that can represent any type. It’s also important to know that the wildcard type is not synonymous to object. This is because a wildcard can be any type whereas an object type is specifically an object (and cannot be a subclass of an object). Let’s demonstrate this with an example: List<?> wildcardList = new ArrayList<String>(); List<Object> objectList = new ArrayList<String>(); // Compilation error Again, the reason the second line does not compile is that a list of objects is required, not a list of strings. The first line compiles because a list of any unknown type is acceptable. Q12. What is a Lower Bounded Wildcard? A lower bounded wildcard is when instead of providing an upper bound, we provide a lower bound by using the super keyword. In other words, a lower bounded wildcard means we are forcing the type to be a superclass of our bounded type. Let’s try this with an example: public static void addDogs(List<? super Animal> list) { list.add(new Dog("tom")) } By using super, we could call addDogs on a list of objects: ArrayList<Object> objects = new ArrayList<>(); addDogs(objects); This makes sense, as an object is a superclass of animal. If we did not use the lower bounded wildcard, the code would not compile, as a list of objects is not a list of animals. If we think about it, we wouldn’t be able to add a dog to a list of any subclass of animal, such as cats, or even dogs. Only a superclass of animal. For example, this would not compile: ArrayList<Cat> objects = new ArrayList<>(); addDogs(objects); Q13. When Would You Choose to Use a Lower Bounded Type vs. an Upper Bounded Type? When dealing with collections, a common rule for selecting between upper or lower bounded wildcards is PECS. PECS stands for producer extends, consumer super. This can be easily demonstrated through the use of some standard Java interfaces and classes. Producer extends just means that if you are creating a producer of a generic type, then use the extends keyword. Let’s try applying this principle to a collection, to see why it makes sense: public static void makeLotsOfNoise(List<? extends Animal> animals) { animals.forEach(Animal::makeNoise); } Here, we want to call makeNoise() on each animal in our collection. This means our collection is a producer, as all we are doing with it is getting it to return animals for us to perform our operation on. If we got rid of extends, we wouldn’t be able to pass in lists of cats, dogs or any other subclasses of animals. By applying the producer extends principle, we have the most flexibility possible. Consumer super means the opposite to producer extends. All it means is that if we are dealing with something which consumers elements, then we should use the super keyword. We can demonstrate this by repeating our previous example: public static void addCats(List<? super Animal> animals) { animals.add(new Cat()); } We are only adding to our list of animals, so our list of animals is a consumer. This is why we use the super keyword. It means that we could pass in a list of any superclass of animal, but not a subclass. For example, if we tried passing in a list of dogs or cats then the code would not compile. The final thing to consider is what to do if a collection is both a consumer and a producer. An example of this might be a collection where elements are both added and removed. In this case, an unbounded wildcard should be used. Q14. Are There Any Situations Where Generic Type Information is Available at Runtime? There is one situation where a generic type is available at runtime. This is when a generic type is part of the class signature like so: public class CatCage implements Cage<Cat> By using reflection, we get this type parameter: (Class<T>) ((ParameterizedType) getClass() .getGenericSuperclass()).getActualTypeArguments()[0]; This code is somewhat brittle. For example, it’s dependant on the type parameter being defined on the immediate superclass. But, it demonstrates the JVM has does have this type information. The new Certification Class of "REST With Spring" is finally out: >> CHECK OUT THE COURSE Learning to "Build your API with Spring"? >> Get the eBook
http://www.baeldung.com/java-generics-interview-questions
CC-MAIN-2017-26
refinedweb
2,317
63.59
From: Daniel Frey (daniel.frey_at_[hidden]) Date: 2002-06-25 07:35:59 Kostya Altukhov wrote: > > Daniel Frey wrote: > > >template< typename T, size_t N > > >const char (&sizer(const T(&)[N]))[N]; > > > You need to remove 'const' here. Then it obviously will not > work for types, but the following snippet works fine with > gcc 3.0.2, gcc 2.95.2, and online comeau: Meanwhile I was pointed to Dietmar's header array_traits.hpp and personally, I'm quiet satified with the implementation we have now - although it requires a bit more typing, it seems more natural to me (given __typeof is available). But without typeof, we could add namespace boost { namespace array { // Declaration only template< typename T, size_t N > const char (&static_size(T(&)[N]))[N]; } } and use V2 = sizeof( boost::array::static_size( x ) ) but leave V1 as it is. Probably the name should be better... Both can live side by side, although I'd prefer to have 'typeof'. > For typedefs such as "typedef int X[42];", a non-portable line that > works with mentioned compilers is "V1 = sizeof( sizer(*(X*)1 ))", > though I would not advise anybody to use that :-) We better forget that, right? ;)
https://lists.boost.org/Archives/boost/2002/06/30903.php
CC-MAIN-2021-43
refinedweb
195
62.78
Use the New Profiler in React Developer Tools to Generate Flame Charts and Interactions · Manorisms React version 16.5.0 has been released and one of the features that it supports is the new Profiler in the React Developer Tools. In the above video and following blog post, we will update an existing app to ⚛ React 16.5.0 and show off various features of the new Profiler. The tool can record a lot of information from your React App, but you can also add interaction tracking to help track user generated events. Installation Before you can utilize the new Profiler feature of the React Developer Tools, you’ll need two things… - React v16.5.0+ (Developer Build) - React Developer Tools v3.3.2+ NOTE: If you want to profile in production see the Profiling in Production gist from Brian Vaughn (@briandvaughn). Profiling Your Application For testing purposes, I’ve grabbed the Redux TodoMVC Example app from the redux repository to play around with. You can find the code for this video/post at github.com/elijahmanor/redux Empty Profiler Tab. Once you are satisfied with the data, then click the “Stop “button. Initial Flamegraph after Gathered Data Once you’ve gathered profile data, you’ll immediately seen Flamegraph data for the first render that occured (see following screenshot). For each render you can see what components were involved and which ones took the most time to complete. The gray items didn’t need to re-render at all (they could have been PureComponents or implemented shouldComponentUpdate manually). Single-Click to View a Component’s Details If you single-click on one of the components (like TodoTextInput for example) then the Flamegraph will zoom into that particular component tree (see following screenshot) and the right panel will give more detail about that component including its props and state. Double-Click to View a Comparison Across All Renders You can double-click on an item (like MainSection for example) and see a comparison graph of how long it took across all renders. And then you can drill into one of the instances by double-clicking on it to see which render that was related to. Ranked Flat View of Components You can also look at a ranked flat view of the components from top to bottom. The items at the top took the longest and items at the bottom took the least amount of time to render. This view can be helpful trying to make sense of all the data presented. Tracking User Interactions There is another view called “Interactions”, but it’ll probably be empty by default. You have to add some code to our app before anything will show up here. The point of interactions is to give meaningful names to user events. The idea is to associate a render in the Profiler based on the intent of what happened. For example, it’d be nice if we could see the render when a Todo item is being added or when one is being completed. There’s a nice gist describing the ins-and-outs of Interaction Tracking with React written by Brian Vaughn (@briandvaughn). Installation To begin, you’ll need to install the schedule package that contains the track function that we’ll need to invoke when manually tracking an interaction. npm install schedule NOTE: The scheduleAPI is unstable at the moment and could change slightly going forward. Manual Tracking Using the unstabletrack function from schedule/tracking, we can manually add calls around code that will kick off a render or re-render. For our Redux TodoMVC app, let’s update the TodoTextInput.js file and tweak the handleSubmit method below that’ll wrap our onSave and setState calls. /components/TodoTextInput.js /* ... more code ... */ import { unstabletrack as track } from "schedule/tracking"; export default class TodoTextInput extends Component { /* ... more code ... / handleSubmit = e => { const text = e.target.value.trim() if (e.which === 13) { track( "Add Todo", performance.now(), () => { this.props.onSave(text) if (this.props.newTodo) { this.setState({ text: '' }) } } ); } } / ... more code ... / } At this point, if we re-record Profile data from our app we’ll notice an entry in the Interactions tab. There is our “Add Todo” interaction! You can click on the entry for more details on the right panel, and you can also click to go straight to the associated render. Automatic Tracking of Redux Actions It could be quite cumbersome to manually add a bunch of track calls throughout your codebase. However, since this is a Redux app, let’s create a function instead that iterates over the actions and wraps them in a track call automatically! /containers/MainSection.js / ... more code ... / import { unstable_track as track } from "schedule/tracking"; / ... more code ... / const trackActions = object => Object.keys(object).reduce( (memo, name) => { const action = object[name]; memo[name] = (...args) => track(name, performance.now(), () => action(...args)); return memo; }, {} ); const mapDispatchToProps = dispatch => ({ actions: trackActions(bindActionCreators(TodoActions, dispatch)) }) / ... more code ... */ As before, we’ll need to re-record to gather new Profiler data. Once the data is retrived, we should see more interactions to investigate. In the following screenshot you can see the origional “Add Todo” track event and also two new track events that were a result from our Redux actions ( completeAllTodos and clearCompleted). Conclusion The ability to profile a React application is is very powerful and I’m super excited about having it in the React Developer tools. Thank you React team!
http://brianyang.com/use-the-new-profiler-in-react-developer-tools-to-generate-flame-charts-and-interactions-manorisms/
CC-MAIN-2020-50
refinedweb
902
55.24
Maximilien wrote:He was good slightly less incompetant in "Raising Arizona" and in "Snake Eyes". Maximilien wrote:Snake Eyes OriginalGriff wrote:Where is Kurt Gödel[^]? Ravel H. Joyce wrote:It reminds me a little of this[^] photo of the Solvay Conference of 1927, in sheer awesomeness. Jörgen Andersson wrote:Morphine was not a nice experience to me. delete this; Gary R. Wheeler wrote: It turns the pain off Jörgen Andersson wrote:I just didn't care anymore Gary R. Wheeler wrote:positive feedback loop Gary R. Wheeler wrote:oh how interesting... my brain is about to explode..." feeling Gary R. Wheeler wrote:Morphine is my drug of choice Gary R. Wheeler wrote:Morphine is my drug of choice Jörgen Andersson wrote:she specifically mentioned bacon as food to avoid *pre-emptive celebratory nipple tassle jiggle* - Sean Ewington "Mind bleach! Send me mind bleach!" - Nagy Vilmos My blog | My articles | MoXAML PowerToys | Mole 2010 - debugging made easier - my favourite utility public class Naerling : Lazy<Person>{ public void DoWork(){ throw new NotImplementedException(); } } Naerling wrote:she said I was too muddy for her taste and left....
http://www.codeproject.com/Lounge.aspx?msg=4161330
CC-MAIN-2015-18
refinedweb
183
59.3
*Updated 11.19.2015 for RC1: Two of the technology stacks that are at the forefront and making a lot of noise are Angular 2 and ASP.NET 5. Angular 2, for obvious reasons, this is the next rev of Google's SPA framework. And just to highlight a few points, from my perspective, why I'm paying attention. - Built with TypeScript - Performance gains - Browser support (IE 9 even there) - Mobile first thought ASP.NET 5, I have been talking, blogging and contributing to this project over the last 18+ months and I'm very excited of what it is already showing. - Rebuilt with Cloud in mind - Cross Platform - Linux, OS X, Windows - Middleware model - much like node.js - Huge speed improvements - much more.. At the Microsoft MVP Summit this November; Brad Green from Google presented on Angular 2, status of the framework, collaboration with Microsoft and things to come. Check out his presentation here. Next, Steve Sanderson from the ASP.NET team presented the Music Store application in Angular 2 and ASP.NET 5. Below is the full presentation from Channel 9. A Basic SPA Template Based on Steve's talk I put together a basic template to use. The code is available on GitHub (). Getting Setup Things you will need * ASP.NET 5 - docs.asp.net to install the latest version * Typescript - typescriptlang.org or npm install typescript -g from a terminal window * Node.js - nodejs.org or brew install node or for windows choco install nodejs These are the base items, a couple other tools used in the solution are nodemon and gulp. Install via terminal npm install nodemon gulp-cli -g. 1. Fork and clone the site 2. Run npm install 3. Open a terminal window and execute npm run tsc, this starts the TypeScript compiler 4. Open a second terminal window and execute npm start. This command runs the gulp build task, then starts nodemon for dnx web. The nodemon process will watch for any changes to the C# code and/or JavaScript files (transpiled from tsc) and restart then kestrel server. 5. Open App Structure The ASP.NET 5 application is nothing more than a simple web application, same format you could generate from the built in templates in Visual Studio (without Authentication chosen) or using the Yeoman generators. Views/Home/Index.cshtmlfile is the html file containing the host of the Angular application tag. Views/Shared/_Layout.cshtmlis the shell html file. Startup.cs- one piece that is important to call out here in relation to the Angular routing is the following: // 404 routing, or otherwise routing logic // if route is not found go Home routes.MapRoute("spa-fallback", "{*anything}", new { controller = "Home", action = "Index" }); Angular 2 Code All of the Angular 2 code is withing the wwwroot folder, due to the fact that all static content under ASP.NET 5 is to live in the location referenced in the webroot property defined in project.json file. Because this is a starter template, it is a simple structure. If you want add a new view to the site, it's pretty simple. Add the folder and view ( my/my.html) <div class="container"> <h1>My Page</h1> </div> Add the component ( my.ts) import * as ng from 'angular2/angular2'; @ng.Component({ selector: 'my', templateUrl: './app/my/my.html' }) export class My{ constructor() { } } Add the new route in routes.config.ts And finally add the link to the app.html page in the navigation portions of the template. <li><a [router-link]="[routes.my.as]">My</a></li> If you have the site still running, the tsc compiler and nodemon will pick up all of these changes and all you have to do is refresh. (as a note make sure that you have the dev tools open in Chrome and cache disabled). Opening the code in Visual Studio 2015 To open in VS you need to open using the git connector. Then open the project.json file. Be sure to have the ASPNET 5 file/project type selected. get the latest push of the code, I had to add a Before Build step to have the gulp tasks run and build/compile the typescript and angular 2 project portions if you are just going to F5. Summary Give this a look, comment, share. There is a need for a good SPA template for ASP.NET 5. If there are core features, let's put them in send a PR or submit an issue. Thanks!
http://tattoocoder.com/angular2-aspnet5-spa-template/
CC-MAIN-2017-09
refinedweb
750
74.69
[ ] He Xiaoqiao commented on HADOOP-16119: -------------------------------------- [~jojochuang] Thanks for your quick response. And sorry for fuzzy expression. {quote}Regarding delegation tokens – delegation tokens are stored in zookeeper, and after HADOOP-14445, delegation tokens are shared among KMS instances.{quote} My branch is based on branch-2.7 and not patch HADOOP-14445, it makes sense for me. If just consider community version (include branch trunk), It seems to offer local storage with Java KeyStore only and no other choice, Please correct me if I am wrong. Looking forward to CKTS open source. About part "HA", I means KMS instance adding/removing/fault is not transparent for client. title "HA" may mislead, I think this is also scalability issue and sorry for that.:) > KMS on Hadoop RPC Engine > ------------------------ > > Key: HADOOP-16119 > URL: > Project: Hadoop Common > Issue Type: New Feature > Reporter: Jonathan Eagles > Assignee: Wei-Chiu Chuang > Priority: Major > Attachments: Design doc_ KMS v2.pdf > > > Per discussion on common-dev and text copied here for ease of reference. > > {noformat} > Thanks all for the inputs, > To offer additional information (while Daryn is working on his stuff), > optimizing RPC encryption opens up another possibility: migrating KMS > service to use Hadoop RPC. > Today's KMS uses HTTPS + REST API, much like webhdfs. It has very > undesirable performance (a few thousand ops per second) compared to > NameNode. Unfortunately for each NameNode namespace operation you also need > to access KMS too. > Migrating KMS to Hadoop RPC greatly improves its performance (if > implemented correctly), and RPC encryption would be a prerequisite. So > please keep that in mind when discussing the Hadoop RPC encryption > improvements. Cloudera is very interested to help with the Hadoop RPC > encryption project because a lot of our customers are using at-rest > encryption, and some of them are starting to hit KMS performance limit. > This whole "migrating KMS to Hadoop RPC" was Daryn's idea. I heard this > idea in the meetup and I am very thrilled to see this happening because it > is a real issue bothering some of our customers, and I suspect it is the > right solution to address this tech debt. > {noformat} -- This message was sent by Atlassian JIRA (v7.6.3#76005) --------------------------------------------------------------------- To unsubscribe, e-mail: common-issues-unsubscribe@hadoop.apache.org For additional commands, e-mail: common-issues-help@hadoop.apache.org
http://mail-archives.apache.org/mod_mbox/hadoop-common-issues/201903.mbox/%3CJIRA.13216469.1550525450000.8361.1551939900313@Atlassian.JIRA%3E
CC-MAIN-2019-22
refinedweb
384
55.95
Why would I want to know this? As a young self-taught programmer, I often found myself writing tons and tons of boolean statements to determine if some event or action has happened. I listen to those events through Coroutines and other methods to return values. If you find yourself doing this as well, STOP IT! Welcome to Events… Intro Lately, I’ve been trying to improve on my C# programming skills and found myself lacking knowledge of the basic understand for Events. So, while looking through numerous tutorials on MSDN and other blogs, I found most tutorials to be over complicated and lush with convoluted code not pertinent to the core concept. I don’t want this to happen to you! With that said I will try to explain the basics of Events and how they are used in a project… Singleton? If you don’t know what a Singleton is, you probably should. A Singleton is a script that cannot be an Instanced or ‘Duplicated’. It is, well… Single. I recommend using Singletons for things that do not need to be copied multiple times during a game. Such as an Inventory System. Typically, the player only needs one Inventory, so we don’t want to call Instances of it, we only want one. And when we call it, we want to make sure it doesn’t get duplicated. There are many ways to create Singletons, but this method is often used because it’s simple… // This class sits on my camera and handles all the clicks I send with a Raycast public class Clicker : MonoBehaviour { // Singleton private static Clicker instance; // Construct private Clicker() {} // Instance public static Clicker Instance { get { if (instance == null) instance = GameObject.FindObjectOfType(typeof(Clicker)) as Clicker; return instance; } // Do something here, make sure this is public so we can access it through our Instance. public void DoSomething() { } ... Here, I have a class ‘Clicker’ that is attached to my Camera. This class handles all clicks that I send into 3D Space with a Raycast. To access my ‘DoSomething’ method from another script, I simply call… Clicker.Instance.DoSomething(); This eliminates the need to use a bunch of Static Method and Variable calls, plus gives us one instance only! Delegate and Event? A Delegate can be thought of as a reference pointer to an object/method. When it gets called, it notifies all methods that reference the delegate. So, first things first… Define a Delegate and the method that gets called when it fires… public class Clicker : MonoBehaviour { // Event Handler public delegate void OnClickEvent(GameObject g); public event OnClickEvent OnClick; The delgate called ‘OnClickEvent’ passes a ‘GameObject’ that we can use to define what game object it came from. Then, we defined an ‘event’ OnClick that gets called when the delegate is called. Now, in the same script, we need to call the delegate and pass it our GameObject. I’ve done this through a Raycast… public class Clicker : MonoBehaviour { // Event Handler public delegate void OnClickEvent(GameObject g); public event OnClickEvent OnClick; // Handle our Ray and Hit void Update () { // Ray Ray ray = Camera.mainCamera.ScreenPointToRay(Input.mousePosition); // Raycast Hit RaycastHit hit; if (Physics.Raycast(ray, out hit, 100)) { // If we click it if (Input.GetMouseButtonUp(0)) { // Notify of the event! OnClick(hit.transform.gameObject); } } } } As you can see, if the Ray has contact an Object in the scene and we Left-Mouse-Click, we call the event and pass the GameObject. The last thing we must do is reference the delegate from our other scripts that are listening to the call. For this I’ve created a class called ‘GoldPile’. public class GoldPile : MonoBehaviour { // Awake void Awake () { // Start the event listener Clicker.Instance.OnClick += OnClick; } // The event that gets called void OnClick(GameObject g) { // If g is THIS gameObject if (g == gameObject) { Debug.Log("Hide and give us money!"); // Hide gameObject.active = false; } } } In our Awake() method, we’ve defined our listening Event and assigned a local method that gets called ‘OnClick’. ‘OnClick’ does not need to be the same as our delegate method, but it can be. Note: In our previous post we added a Singleton to our Clicker class. This allows us to use Clicker.Instance As you can see, we’ve also created the OnClick() method that passes our GameObject we clicked on. Note: You must use if (g == gameObject), otherwise it will hide other instances of that method in the scene as well… This is why we pass the GameObject for reference! Now you are free to add this method to any other script in your game if needed. Don’t forget to define the method and delegate in your Awake(). You can download the complete project for your reference HERE. Enjoy! :) Thanks for the tutorial, appreciate it! "I found most tutorials to be over complicated and lush with convoluted code not pertinent to the core concept." Oh man, you and me both. Trying to learn this through those is agonizing to say the least. And the worst part is that this problem is not limited to the particular topic of delegates, events and singletons, but pretty much every goddamn programming tool. ******* hell. I am eternally grateful for this tutorial. @Reactorcore I'm glad you found this useful! Like you, I can't stand how SDK Documentation is overblown and hard as hell to figure out. I hope to keep bringing new tutorials like this to the DB Community. @"******* hell." A-men brother The overall professional opinion over singletons is bad. And from most standpoints, they're right :) An Inventory does not necessarily call for a singleton implementation. An Inventory should be a component of a parent Player or Character class. The only thing that could call for a singleton implementation is some sort of manager/controller that needs to be accessed from a lot of places. But that's a design flaw on its own. Also, is there really a need for you to make sure you only have one instance of a class? :) How many times did you accidentally declare random variables when doing a conditional check? Other than that, great article. I appreciate the points on events and delegates. Thanks for the tutorial!! Nice tutorial. Thanks a lot for the great explanation. I used that approach in my Game State Machine example @ Blog.i-evaluation.com" Singleton is perfect way to persist object and delegates are most elegant solution for handling events I have seen so far. The only question I would have is about destroying it. According to Unity spec Garbage Collector doesn't destroy object if there is an reference to it and so shouldn't we be subtracting handler while destroying an object? Whoa, buddy. You're misleading people here with that understanding of a singleton. It absolutely IS an instance, but the creation of it limits it to build certain properties of itself only once, setting them statically on the first pass. It's commonly used for things like database connections, third-party services, sockets, etc.... The idea is that you create the connection itself on the first use of the object and on subsequent instantiations, it reuses that static property. Thank you for tutorial. helped me a lot. By the way, do we need remove event listener on destroying or disabling object? Something like: void OnDisable { Clicker.Instance.OnClick -= OnClick; } Yes, best way is to use OnEnable/OnDisable: void OnEnable { Clicker.Instance.OnClick += OnClick; } void OnDisable { Clicker.Instance.OnClick -= OnClick; } Hi, I really like how your tutorial and how it made me think how to do similiar stuff in my Perliner game. I especially like the way you explain singletons and delegates. I'm not sure however if the example for delegates is the best one. If you have a 1000 gold piles in your level, each time a player clicks something, all 1000 gold piles will be notified. Why, if you already know which gold pile should be notified, that is the one stored in hit? you could just do hit.onClick() or something similar... This way there is only one call and not a thousand. Beside that, great thanks. I started thinking about refactoring my Perliner code and how to handle similar stuff. I would think I could have a ObjectClick on any clickable (or otherwise actionable) object, and use a Delegate pattern to attach any other component of the object to it. For example let's have an object enemy with ObjectClick component attached. I could also have an Enemy component attached to it, that would do: GetComponent<ObjectClick>().OnClick+=OnClick; The camera's Clicker class would do similar stuff to yours, but when a hit is found, it would do instead: hit.transform.gameObject.GetComponent<ObjectClick>.OnClick(); This way OnClick() of ObjectClick would call onClick of component Enemy. What do you think? Or am I doing something strange?. Hey! Good job on your article! Very informative and not enough people understand the advantage of using events to create clean code struture. I would be glad if you take the time to take a look at EpixEvents, a library I developed while working on several video games. I think it's the best library to use all the power of events without the drawback it could occure. You can get it here: Assetstore.unity3d.com Or get more info here: Epixeventspro.com Cheers buddy! Great article! Really helped me out, thanks! A good tutorial! Thanks a lot, these article can help me to improve my event manager Action Box ( Athagon.com ) Thanks for the tutorial! Helped me understand how I would go about applying OOP to Unity scripts. One thing I want to note is that in the Unity3D Scripting manual, it states that if you attempt to define a contstructor for script component, it would interfere with its normal operations (Unity instantiates its objects from the editor and does not take place at the start of the gameplay) and can cause major problems with the project. I think just by accessing that script from another script, you're guaranteed the one instance that's created at start up. Thanks. This comment is currently awaiting admin approval, join now to view. There are a couple issues you're going to run into with this solution The singleton doesn't clean up after itself - you need to make sure to clear the static variable on destroy of the singleton. If you reload the scene with this singleton in it, you're going to be attempting to access a destroyed version of it. You'll run into init order problems. You're accessing the singleton instance in awake. Awake should only be used for accessing things to do with yourself, you can't rely on the awake of your singleton to be called before GoldPile awake. I normally use static events when dealing with singletons. You just need to be careful any anyone attached to a static event is detached on destroy, or you can end up keeping GOs alive much longer than you expect them to be. This comment is currently awaiting admin approval, join now to view. I think there's an error in the singleton code example. I get the error "not all code paths return a value" on Clicker.Instance.get. Is anyone else seeing this? Hi there, Nice little summary, for a cleaner solution the event should check whether or not there are listener attached to it like this: if(OnClick != null) { OnClick(hit.transform.gameObject); } This comment is currently awaiting admin approval, join now to view. This comment is currently awaiting admin approval, join now to view.
http://www.moddb.com/groups/unity-devs/tutorials/delegates-events-and-singletons-with-unity3d-c
CC-MAIN-2016-26
refinedweb
1,939
65.22
Advertisement software engineer nice program ,to understand switch statement My Comment Through your website, I have search all of the posible information that I need for our Homework.... Thank You..... this coding is good i need calculator programm by using java,servlets ,jsp error in my program switch case program in java shows illegal start of type in this program . please guide . here the program - public class p1 { public void menu() { System.out.println("1.area of a rectangle"); System.out.println("2.Area of a square"); good example. vry well explained .. it cleared all my doubts regarding switch.. few things that even my stupid teacher did'nt tell .i got to know from here. i dont hav any java book ..still i cleared all my doubts from here.. pls help me! can u help me! example of switch! like words convert to numbers! pls reply java switch statement can you an give idea can get a check statement hi hi this my program ple salove me write a program eter cngumer no,name,lastmonth reading ,pmr,total units and find out the bill amount d/b/i using switch statement MCA/Software Engineer with 5 months of Experience in Development MCA/Software Engineer with 5 months of Experience in Development which purpose we are using run time class  : Software Developer Software Developer what is the java code to turn off my pc
http://www.roseindia.net/tutorialhelp/allcomments/3300
CC-MAIN-2015-48
refinedweb
233
66.23
:00025 ^3G.4b b 5 .TUIT2 STA-TES D 7.'.1T: IIT OF AG2ICULTLTE Bureau of Agricultural Econo;.tics '7as'iin-ton CS-5 "arch 3C, 1937 L lNIV Op ;L L! I OGLu^TS JP-__. ----------------------- S------------------------------------- WE.E COTTON SITUATION S OSITORY ST ",A'Y A ver' re.-id rise in snot cotton -rices bec.:-n a.t the end of Febra,-r,. Fron a Februmry avcre-e of 12.90 cents, the 10-n.rl-et -rice rose to 14.42 cents in the reek ene.ed lLarch 20. The letter -:as the hi host Lvcr-rc -:rico for any week since the wcok onded June 7, 1930. The receipt of requests for the release of '--roximD-tel: 973,000 blces Govermnent-financed cotton u. to M.arch 25 inc.icc.tes the *-rob-bility that while stocks of "free" cotton in the United St-tes :t the enc' of the 'resont scson will be smaller than in any recent season, with the exception of last year, they may be sli.htl: lparer than averv.o stocks in this country during the Inst half of the 1920s. Hill activity and cotton consur'tion in the United States continueC. at a record breeckinr level during FebruCry. Consun-tion in the 7 months s front Au:ust through Februrry was 28 -ercent r.ore than in the corresnonling -crioc. a yenr earlier. In forei-n countries, especially' in Japan, Chinn nr.' the Unitec! Xir.;L.omi, total utilization of raw cotton a.nd output of cotton textiles are extrelel:' hich. In those three countries and in foreign countries p.s a whole, .icrever, i..orts and xanrent consumption of A:.eric-n cotton .were bout 15 -ercent 'l-or in the 6 months An.ust throu- h January 1937 than in the correPsonin:- crieod ar year earlier. I - 2 - The total -.'orld consurmtion of all cottons -7-.s 8 percentt larger than in the first h-lf of l.st season. The !er:vy consurtion by mills in the United States ..lore th-n offset thle Occrcoseod consuntion of A.ieric'n in foreign countries, -nd v-orld consui.tion of Anericrn cotton in the first G months of this season sho-ed -.n increase of ..,ore thnn 300,000 bales, or 5 -ercent, over the corres-;ondiin: -'eriod last y.'ear. Total :.ill consui.ation of cotton in forcing countries vas 10,527,000 ba.les front Auiust throu."h January of this season, an increase of bct-een 2 and 3 -ercent over l?.st year and of 21 per- cent over the nvern.e for the 10 years ended 1932-33. This hih level of cons-..-ation resulted from the record hi. h -vorld utilization of foreir-. cotton mostlyy 1ll consumed. in foreign countries), which was 11 percent more than in the first half of 1935-33 and 58 percent more than the 10-year average. World consur.mticn of Indian cotton was 7 .ercont more than last season and 8 -ercent above the 10-year avcrare. '.orld consurmtion of Egyptian was sli htly lar er than in the first half of 1935-33 and was a record hi.h. The consun--tion of sun.lry cottons vws 15 -nercent above the corresponding period a year earlier anc. 118 -:ercent .:ore than the 10-year evera.e. Do-.estic Prices Fise Sharnly The -rice of M;iddlin, 7/3" cotton ?t the 10 markets averaged 12.90 cents in February, the `.i-hest February rvera.'e since the corres-ondinc ronth of 1930. About the end of the ,.ionth, h:orever, a very rar:id rise bean -:hich carried the 10-: .rket pverr-e to 13.57 cents in the rreek ended larch G, to 14.05 cents in the week: ended I'nrch 13, and to 14.42 cents in the weel ended :larch 20. The letter was the highest vvern-e -.rice for any week since the week ended June 7, 1930. Several ii.nort.nt factors have contributed to the advance in cotton prices. First, cotton consun-"tion and nill activity in the United States have continued at hi."-h levels. Second, ex-orts during : February and the first part of I-.rch were sli:htlyr larger than a year earlier, whereas in the first half of the season they were running ; considerably below the corresponding months a yenr earlier. Third, the su--'ly of cotton in trade channels in the United States is mlterially s.:,aller than in any recent year with the exce-tion of last season CS-5 CS-5 and, according to the New York Cotton Exchange Service, a considerable part of the extra nJill stock of "free" cotton in the United States is rather un- attractive to domestic spinners, because of location and quality, or because the boles have been co:mressed to high density for export. It is al-so reported thklt the supply of cotton actually available for sale is somewhat smaller than appears to be the case because of an unusually large forward sale by shippers for shipmt.:nts during the rer.ninder of the season. Fourth, the release of Govern-ent-fInanced cotton since January 1 has been, perhaps, more of a nrice- strengthening than a price-weakening f.ctor. while the supply of "free" cotton has been -.u.-.ented, the unexpectedly large quanticy released in the face of the stiff terms imposed by the Cornodity Credit Corporaticn i.Trressed the trade with the strength ur-nerlying the market and. has tended to stimula.te further the market for spot cotton. Finally, cotton prices undoubtedly have been affected to so..'e extent by the recent strength in raw material prices since January which has reflected the upward trend in world industrial pro- duction and ti:e continued heavy, and anticipated heavier, expenditures by certain foreir-n countries for an aments. The -rices of forei.nm cotton at Liverpool, expressed as a percentage of Anerican, did not show ?ny ir.-ortant changes in February nor in the first 3 weeks of 1March cor.pared with January. Enyptinn, Brazilian n'. Peruvian, especially Peruvian, strengthened somewhat relative to Anerican liid2lin,, while the average price of three types of Indian weakened as coMpared '-ith two types of American. 'Jith the exception of Indipn, -rices of fore-i".n cotton increased as :.2uch or .'.ore than Am.ericp.n during the --eriod of swiftly rising prices in the first helf of the nonth. C bst-ntia.l Qu.ntity of Government-Financed C..gtor. 'oves Irnto Trade Channels The Commodity Credit Corporation has announced thrt up to and including i.arch 25 requests for releases totalin: 973,000 bales of lonn cotton hrd been received. This is a considerably larger quantity thnr. the trade had expected would be released duri-.. the entire periodd from Febr 'ry 1 to April 1. The Conmodity Crudit Co-nora.tior's selling terms 'rovicde that the release prices on any r:iven c.y are to be based on the 10-n--rket avora'e prices for "'iddlinc spot on the previnur ,,v. S.-.les of loAn cotton u7 to the -.rese.t tir-o have undoubtedly been greatly stimulated by the fact thrt the n.ret has been ad- vancinC .ost of the time. Assu-..in- that do;iestic consun-'tion plus exrcrts for the entire season will bear the snn~e relation to the totpl for l1st year th-t consu-rtion and exports so f this season bore to those of the rorres'one-inr- r.:cnths 1.st year, total dor.estic consurn-tion plus exports for the 1932-37 season will enount to more than 1I,jCC,000 bales. The carry-over in the United States on Au-ust 1 would be about 4,500,000 bales. If it is assumed that arpproxiT.-tely 1,300,000 bales of loan-stock cotton are released under the -resent plnn, the o-eration of 'ihich is scheduled to end on April 1, and if it is further ,- -ied that no additional quantities of loan cotton are released, the stock of "fr n" cotton in the United States on Awaust 1 would amount to about 2,800B,0O bilo., This - i - CS-5 /4 - _ a woulF be considerably smaller stock of "free" cotton than has existed on the corros'ohL.in date in nnv recent year, with the exce-tion of last season, but it is sli.-h.ly 1cr-rer than the everar-e carry-over in the United States in the 5 years ended Au.ust 1, 1929. In the 5 years ended 1929-30, however, con- sumntion plus exports of Arierican cotton averaged about 15,000,000 bnles or about 2,000,000 bales .-ore than the anticipated total for this sr' son. According to the International Federation of Master Cotton Sminners' and 'Manufacturers' Associations, world r.ill stocks of all kinds of cotton on Febru.ary 1--5,891,000 bles---were 1,000,000 b-les or 21 percent -r,-er than on February 1 last year. About one-thir. of this increase took .lace in forei-n countries and about two-thirds occurred in the United States. Col.poring February 1, 1937, ,-ith Au.ust 1, 1935, there vas a co:npratively smnll increase in .mill stocks in forei.-n countries, but a rise of about 1,200,000 bales in mill stocks in the United States. ..orld nill stocks of A-merican cotton on February 1 -ere 500,000 bales lar-er than on February 1 last year and sli.:htly lrrer than February 1 stocks during the 10 years ended 1932-33. .:ill stocks of A.-;cric. n cotton in forei-n countries on February 1 v:ore 12 percent less than r o the corresnondin- date last year and 33 -ercent less thn the 10-yrer averr::e. The, -:-ere not -,prticularly s:.i'll, ho,-ever, in view of the lower level of forei-n consur.r'tion of Arcrican cotton this season as co.m-red. with lost year and vith the 10-year aver- e. I"ill stocks of foreign cotton, especially Sundries, on February 1 were rore than tvice as lar.re as in the 10 years ended 1932-33, but 'vere not out of line vith the increased consurmtion of this cotton by foreign nills. (See table at end of the report.) Zr->:rs front U:iited. States Irnrove Exoorts from India and Eryot Ver:' L-r:.e Sxmorts cf Am-erican cotton in February were 422,500 bales .r 14 -ercent lar cr than in February 193G. ::ost of the increase resulted fro- larger exports to the United KCin-do.- and to Japan, especially the latter. Exports to France, Italy an'. Ger.r.ny were smaller than in February 1933. Exports i. the 7 -.tonths from Au ust through Februi.ry were 3,898,000 bales or 12 percent less than in the corresponding period P ear earlier. ihile the ir.nrove:.ent in exorts in the first nart of 1937 over 1935 is a hopeful sian, it should not "ive rise to Irinue Ontimis'i. According to the NewI York Cotter. Exchange Service, foror.-rdinfs of A-ierican cotton to foreign nills in the 4 weeks ended :arch 13 totaled only 423,000 bales co.nared .rith 531,000 a year earlier. Furthermore, stocks of American cotton afloat to foreign countries and at forcif-n ports about i'arch 15 were 101,000 bales larger than a year earlier. These facts su, C:est the possibility thit the recent increase in exports !.ny be short liloa. cs-5 5- The 514,000 bales of cotton exported from India in January were 82 percent larger than last season and 4' percent above the January average in the 10 years ended 1932-33. This was the largest amount exported from India in any January on record and, with the exception of March 1925 and February 1926, was a record high for any nonth. For the most part this very large volume of exports resulted from the extremely heavy ship:,onts to Japan which were 21 times as large as in the corresponding month a year earlier and were the largest ship-ents of cotton from India to Japan in any nonth on record. Exports frou India to all countries of 1,458,700 balas in the 6 months August through January were the largest for any corresponding period since 1930-31. Exports of cotton from Egypt in February were 213,600 bales of approxi- nately 478 pounds net and were the largest exports for any February since 1914. In February 1936, exports from Egypt to all countries totaled 126,800 bales and in the 10 years ended 1932-33, 133,400 bales. Exports of 1,266,100 bales in the 7-month period ended February were a record high for the period, being 9 percent greater than shipments of 1,164,600 bales last season and 31 percent above the 10-year average of 960,300 bales. whilee exports to all important countries so far this season have been larger than the average for the period 1923-24 to 1932-33, they have been especially large to Japan. Shipments to Japan were 171,800 bales compared with 73,100 in the sa-e 7 months last season and thu 10-year average of 44,000 bales. The Tax ile Situation World consumption of cotton at record high level foreign aill consumption of American small According to consumption data recently reported by the International Federation of Master Cotton Spinners' and Manufacturers' Associations, world mill consumption of cotton in the 6 months ended January 31, 1937, amounted to 14,375,000 bales, _/ a larger consumption of all cotton than in any corre- sponding period on record. It is nearly 1,100,000 bales or 8 percent more than in the saro 6 months last season and 2,600,000 bales or 22 percent more than average consumption during the first half of the 10 sLasons 1923-24 to 1932-33. World utilization of American cotton fro:.. August through January of this season amounted to 6,509,000 bales compared with 6,101,00- bales in the corre- sponding period in 1935-36 and 6,747,000 in the 10 years endcd 1932-33. The increase compared with last season is due entirely to the very largo consumption in the United States. Consumption of .umorican in foreign countries amounted to only 2,742,000 bales, 15 percent less than last year and 27 percent less than the average for the 10 years 1923-24 to 1932-33. The quantity of American cotton used by nills in foreign countries in the first half of this season was the si.allest since 1923-24 when foreign ..ills used 2,700,C00 bnles or slightly more than this year. Total consu-med in forLign r.ills, howuvcr, increased 50 percent front 1923-24 so that thu proportion of A..uric.n to the total w-s quito different, averaging 44 percent for thu 10 acasons ended 12-1 1 percent in 1935-26j and 26 percent this season. (CSe tablo .t end of th. report.) j7/ nerioan and Srundrios in running balos; I'di-n ar.d Egypt l:n, running balos converted to bales of approximately 473 pounds nut by :.uliplyir.g by 0.6 and 1.5 respectively. (Soc t-iblI at end of report.) - 6 - World mill consumption of foreign cotton, nost of which takes place in foreign countries, was much larger during the 6 months from August through January than in any corresponding period on record. In the first half of the 10 seasons ended 1932-33, world nill consumption of foreign cotton averaged a little more than 5,000,000 bales. In 1935-36 it amounted to nearly 7,100,000 bales and in the first half of the present season (August to January) to nearly 7,903,000 bales or 58 percent more than the 10-year average. Con- sumption of all three major divisions of foreign cotton, Indian, Egyptian, and sundry growths, has been very heavy so far this year. World utilization of Indian cotton of 2,363,000 bales was 7 percent larger than in the first 6 months of 1935-36 and 8 percent higher than the 10-year average. World consumption of Egyptian cotton amounted to 883,r00 bales. This was slightly larger than consumption in the corresponding period last season and was a record high (consumption by 6-month periods available since 1923-24.) World ::ill consumption of sundries shows the most pronounced growth. In the first half of this year mill consumption of these growths totaled 4,620,000 bales, or 15 percent greater than last season and 118 percent larger than the 10-year average. In the 10 years ended 1932-33., the consumption of sundry growths by foreign mills was equivalent to 57 percent of their con- sumption of American and represented about 25 percent of their consumption of all kinds of cotton. So far this season, the quantity of sundries consumed by foreign mills amounted to about li tinos foreign consumption of American and represented approximately 40 percent of foreign consumption of all kinds of cotton. Domestic consumption continues at record levels Mill activity and cotton consumption in the United States have continued at exceptionally high levels. In February, domestic mills used 664,000 bales of cotton or 29 percent more than in February 1936. This was a record high consumption for the month. Consumption in the 7 months ended February amounted to 4,513,900 bales, nearly 1,000,000 bales or 28 percent more than in the corresponding period a year earlier. During most of the month of February, mill sales of goods lagged behind mill output but activity was well maintained on the basis of old orders. Early in March, a new wave of buying set in, and during the first half of the month sales were apparently in excess of current output. The continuation of the very large volume of unfilled orders makes it seem likely that activity will stay well up around present levels for at least the next few months. Mill margins (based on 17 constructions of grey cloth) averaged 17.86 cents in February, a slight decline from January's 18.22 cents, but with that exception wore the highest average monthly margins for any month since October 1925. In the first 3 wocks of March an advance on cloth prices kept margins comparatively high in spite of the sharp increase in raw cotton prices. Margins in the first 3 weeks of the month averaged 17.69 cents. CS-5 -7- Imports arnd consumption o' all kinds of cotton by European Countries very_ large in first half of present season 1/ United Kingdom. British uill takings of raw cotton so far this season foreshadow the largest year's business in a decade, yet American cotton is not sharing in this striking trade recovery. The takings of American cotton to date are the lowest in many years, except for the two very unfavorable seasons 1930-31 and 1934-35, but the heavy movement of other growths, notably Brazilian and Indian, has carried total takings to levels well above even the high figures for the first half of last season. These developments are attributable to keen demand in the United States, large supplies of co.-petitive cotton, and resultant adverse price relationships for ..nerican staples. During the six months August through January, total imports of i,753,000 bales of 478 pounds net were 6.4 percent higher than a year ago and the largest in several years. Imports from the United States, however, were less than last year, and, omitting long staple cotton, if any, were only 737,000 bales a decrease of 17 percent. On a weiLht basis, .American cotton constituted only 42 p~,cent of th3 total 6 monthss imports as com-pared with 54 percent a year iqo. .\ striking development in imports was the sharp rise in takings of short and medium staple cotton. Imports of short and omdium staple cotton from India amounted to 164,000 standard bales, or 40 percent :more than a year ago. The proportion of short staple cotton from India was higher than last year. Imports of Brazilian cotton of Liedium staple were 162,000 standard bales, an increase of 169 percent. From Egypt, iiaports of long staple decreased 12 percent, but imports of riedium staple increased 30 percent, bringing each of these fiFures 'o about 183,000 bales. The net result was that total imports of short :-'. le cotton (costly frou India) increased 31 percent and medium staple cotton 8 percent, while long staple cotton decreased 9 percent. Cotton cloth sales appear to have slackened somewhat during February, although the inquiry for goods is being well maintained. The home :..zrket continues strong and complaint is still heard of the inability of buy:.rs to obtain early delivery on new orders. In the export trade, however, new business is said to be generally for smaller lots than was usual a few weeks ago. There nevertheless appears to be enough business on the books to keep looms well occupied for several months ahead, and spinners find little difficulty in booking erw orders for nediuL and coarsn yarns, especially wtrp styles. Some idl- machinery has been started, and projects are krcr:n to be under considcerqtinn for resumption of operations in mills .v'hich have been closed fcr so..o tir.i. err x.ny. Both German imports and aill consumption of nrw cCLIton fell off during the first half of the 1936-37 cotton year. The drop in i:..corts was very heavy a iountir- to only 69 percent of those of a ye-r L'2rlier, Net imports .n the 6 ronth- oncl.n January 31 amounted to only 502,200 bilts of 478 pounds against 72o,200 bales of 473 pounds in the si;.:e pt-riod in 1935-36, 380,000 b-.les in 1934-35, 812,000 in 1933-34 and an avo. age cf L'2, 00C in the 5 yuars 1926--" to 1:j:-31. 1/ Prepared I .rgely frou a ruort fro..; Agriculturnl Attache loyd V.Str'vro at Berlin. CS-5 Mill consumption of raw cotton during the half-year also has declined, but to a less extent than have imports because of two reasons. First, there was a further reduction in inland stocks, and secondly, German re- exports of raw cotton from within customs boundaries have fallen to very negligible 'nounta The decline in total mill consumption of raw cotton in the half year ended January 31, 1937, compared with this 6-month period in the 2 previous years, has taken the form of a further drastic curtailment in the utilization of American cotton. Only 19 percent of total uerman raw cotton imports came from the United States during that period, compared with 33 percent a year earlier, 43 percent 2 years ago, and 79 percent in -the first half of 1932-33. The effects of the German currency situation and the relatively high price of American cotton in relation to other growths, have thus combined to reduce mill takings of American cotton, or rather to reduce purchase permits by the Supervisory Office, to a record low. Conversely, the utilization of cottons was driven up, for the rnme reasons, to a record high, and is estimated to nave reached 56 percent of total consumption in the first half of the present season, as against. only 2 percent in the first half of 1928-29. The fact, however, that total mill consumption of raw cotton by German spinners in the first half of the current season was the lowest recorded since the y-.-t-war stabilization-of the Rcichsmark, with the ex- ception of the crisis hal..-year ended January 31, 1931, is very misleading in me important respect. It does not mean that cotton mill activity has shown a corrpspondin- decline. On the contrary, German mills have heen in a position to maintain activity and output on high levels through greatl- increased utilization of substitute spinning materials. It may be Pstim.:t. tnat in the first half of 1936-37 spinners consumed almost 300,000 l-air of such materials, compared with only about 100,000 in the first half of 1932-33. Estimated total cotton mill consumption of spinning material, -932-33 to 1936-37 Spinning material Half-years, Aug-Jon. :1932-33 :1933-34 :1934-35 :1935-36 :1936-37 : 1,00C 1,0C0 1,r'O 1,000 1,x'0 :bales bales bales bales bales Raw cotton ..............: 576 745 578 610 562 Imported cotton waste,etc.: 40 20 106 60 97 Staple fiber .............: 2n 25 30 52 79 Domestically reclaimed ...: 50 69 60 90 10C (cc ton,etc) ____ Total ._.......... ... .686__ 850 774 812 838 Eales of 478 pounds. - 9 - A comparison of the replacement of American cotton in the first half of 1936-37 as against the first half of 1933-34, when total mill consumption figures for spinning material were about equal, gives the following picture: German mill consumption of cotton by growths, and other spinning materials, 1933-34 and 1936-37 : : : Ameri-:Indian :Egyp- : can : tian : : : :Sun- dries : :Import-: :Total : ed :Sta-ple :cotton:waste, :fiber : etc. : :Lomesti- :cally re- :claimed : cotton :1,900 1,000 1,000 1,00C 1,000 1,COC 1,0CO 1,COC :bales bales bales bales bales bales bales bales 1933-34 : 543 70 93 39 745 20 25 6C 1936-37 : 97 72 73 320 512 97 79 1CC Plus or : minus -446 + 2 -20 +281 -183 -77 +54 +4C Bales of 478 pounds. It may be said, therefore, that of a total displacement of 446,000 bales of American, about 65 percent was replaced by the substitution of exotic cottons, 25 percent by the substitution of imported cotton waste, etc., and domestically reclaimed cotton (from rags, etc.), but only about 10 percent by the substitution of staple fibers. The major factor in the reduction of German mill consumption of American cotton is thus seen to have been the increased utilization of exotic or sundries cottons, though the use of substitute spinning materials also has been of great importance. Exotic cotton, as well as most of the substitute imports of cotton waste, etc., have been available to Germany under bilateral trade agreements. Although actual figures are not published, mill stocks of raw cotton are estimated to have fallen to about 100,000 bales of 478 pounds on January 31, 1937, compared with an estimated 200,000 bales on Janu.ry 31 last year. Total inland stocks of raw cotton may be estimated tn have developed as follows: Location : Join. 31 S 1933 : 1934 : 1935 : 193F : 1937 : 1,000 1,000 1,00 1, 0 iI .C : bles bales bales ba.les b ces Mill stocks ..............: Other inland stocks ......: Total stocks ...........: 172 261 196 233 368 494 140 200 340 21i 165 2F5. Bales of 478 pounds. Half- years Aug.- Jan. CS-5 Czecho slov-akia.- SF-V1-i- occupation and output in the Czechoslovakinn cotton textile industry under oted.ly Ih?ve benefited from the substantial revival in general economic conditions evident in 1936, even though gains in exports of yarns .nd fabrics hve so far been rather moderate. A strong rise in prices of cotton manufactures, partly incident to devaluation, is complained of by the trade, and, after a period of active export selling, Czech cotton textile export prices are now spoken of as somewhat out of line. The Czech foreign trade figures for cotton in 1936 show good irm- provements over 1935. Imports of raw cotton and exports of cotton yarns in 1936 were higher than in 1935 because of improvement in the first half of the year; but in the second half of 1936, returns were again lower than in the second half of 1935. Exports rf fabrics in 1936 were only slightly above 1935, and it is significant to note that exports of cotton f-.brics, calculated on a weight basis, are now only about half as large as y:.rn exports, whereas, the relationship used to be about the reverse prior to 1929. Austria.- Favorable developments in the Austrian cotton textile situation have persisted until recently, despite occasional recessions in the yprn export business to Rumania. Mill activity in both spinning .nd weaving plants has remained relatively high, though, on the whole, some- what below the comparable perio' of last year, and it is said that the winter business of the industry has not been as good as last year. The recent formation of a weavers' cartel in Austria is being sharply criticized. FPices of cotton fabrics have been raised 18 to 35 percent with an indic-.te averagee of 30 to 32 percent. Weavers claim that they have been forced to the.e measures by the yarn prices demanded by the spinners' cartel. Proponents of consumer interests urge a loosening of import rc;triction:- a-. the reduction of import tariffs on yarns and fabrics. In any event the sale of cotton goods in Austria and, therefore, mill occupatioQ seem almost certain to be unfavorably affected by these price increases. The figures on Austrian foreign trade in cotton and cotton goods in 1936 are inco. .raging. Considerably higher imports of raw cotton than in 19.35 have coincided ri nh considerably higher exports of yarn, though in both cases the rise over 1935 was much more marked in the first half than in the second half of the year. Nevertheless, net imports of raw cotton in the half year ended January 31 were nearly as large -s the record imports in the corresponding period last season, and were 62 percent larger then net imports in the year 1929-30 to 1930-31. Pol- nd.- Polish imports of raw cotton so far this season (August- Lecember 1936) have amounted to 132,000 bales of 478 pounds or only slightly bdow the 136,000 brles in the same period last year. Mill activity also shows a slight drop from last year's early season figures, but the general level of occupation is well above the corresrnnding period in the critical seasons 1931-32 and 1332-33. CS-5 - it - CS-5 France.- The French cotton textile industry has played an important part in the favorable turn which economic conditions took in France in 1936. Occupation of both.spinning and weaving mills has risen appreciably during the ye-r; stocks on hand in the mills have declined, and unfilled orders have soared. Many mills are sold out for several months aheAd, some in Normandy even to the end of 1937. True, much of this reviv-l has been speculative, or at least of an advancee buying" character, in the face of currency devaluation, w-.ge increases and substantial rises in prices. But the refilling of goods stocks in tr-.de channels has long been overdue and need not result in a prolonged buying holiday later, since larger stocks will be required with an all-round speeding up in general economic activity. In view of the improvement in general business in Frnce there is every reason to view with confidence the underlying outlook for tne cotton industry, though a temporary reaction in business is not altogether improbLble. The intro- duction of the 40-hour week in the textile mills at the beginning of 1937 cannot but tend to bring about some temporary recession in cotton con- sumption and mill output. The further increase in prices which followed upon that measure the wages formerly paid for/48-hour week are now being paid for 40 hours may well cause, also, some pause in buying, yet these do not seriously impair the general outlook. French imports of raw cotton continue to show a steady rising tendency, compared with similar periods in recent years, total trkings in August-December 1936 amounting to 526,000 bales against 460,0C0 "nd 380,000 bales, respectively, in the snne period of 1934 and 1935. Imports, however, are still much below the average of 743,COO balos in August- December 1926-27 to 1930-31. l/ Italy.- In the absence of any official statistics on raw cotton imports (as well as on consumption) by Italy in 1936, reliance must be on rough approximations calculated by deducting estim-.ted shipments in transit to other countries from total estimated arriv:.ls of rr.-. cotton in Italy. The balance gives some indic-.tion of whr.t the country's retained raw cotton imports have been. Slightly more than 500,000 bales (including linters to the extent of about 10 percent) are obtained by this method for Italy's imports of cotton in 1936. nmerican cotton comprised about 66 percent of the total cotton shipments -.ssumeA to have been retained in Italy in 1936, Egyptian cotton around 13 percent, r-ad Indian cotton about 9 percent. Of tne rc.mainiag 12 percent a large part undoubtedly consisted of Brazilian auni Argentine cotton. From a comparison with official import data for 1935 it wouldd appear that tot4a 1936 cotton and linters imports by Italy weure about 25 percent blow the already much reduced importation of 1935. In prst Ood years Itrly used to import around one million b.lec. Estimated cotton imports in the half-yer.r Aa-ast-Juru: ry 19-6-37, were 270,0')00 bales of 478 pounds, of which 54 percent or 145,? '::'re Americ-n, 15 percent or 40,000 brles Indin, 19 percent or 51,CLC, -ies Egyptian, r.nd 12 percent or 34,Cl;0 b-les .uindrics cotton, l:.rgely Brnzilircn. I/ Br.scd on reports of the American Conul rte G-nenran at Mil.r-.. .- 11 - CS-5 12 - Mill consumption of raw cotton in the first half of 1936-37 may be placed at, roughly, 300,000 bales of 478 pounds, or half of the estimate for the total season 1935-36. Distribution by growths would appear to have been about in the proportions indicated above for imports from August through January. Mill stocks of cotton ire said to be very small, and at the end of January 1937, were probably bctwuen 20,000 and 40,000 bales compared with 200,000 to 300,000 in normal years. Mill Consur.ption and Output of Cotton Goods Very High in Japan and China Japanese Imports of American Below Last Year 1 Japan Yarn production in Japan in February amounted to 330,000 bales of approxiLmtely 400 pounds. This compares with 295,400 bales in February 1936, and is the largest yarn output for any month on record. The very large pro- duction of yarn in recent months has been accompanied by a core than propor- tionate increase in the production of nodiuu and fine counts. This increase in the absolute and relative importance of ;-iedium and fine yarn is in part the reflection of a larger demand for better quality cotton textiles by con- sumers as a result of improved world economic conditions and larger incomes. It also indicates, however, an increased technical skill on the part of the Japanese manufacturer and cotton operative with a consequent ability to produce profitably a higher quality goods in competition with the old and long estab- lished cotton industries of Europe and the United States. This upward trend in the production of the better quality cotton textiles by Japan has been in evidence for some years. It has been a very important influence tending to increase the proportion of total Japanese mill consumption represented by Am:erican cotton, since the longer stapled and better quality Acr.erican cotton is more suitable to the production of medium and fairly high quality yarns than is Indian cotton, the chief competitor of American cotton in Japan. In 1934-35 and 1935-36, however, the share of American in total constuption decreased in spite of a continued increase in the relative importance of medium and high quality yarn due to the high price of American cotton relative to foreign growths. Apparently the decline in the relative importance of Ar.erican cotton is continuing this season largely as a result of continued relatively low prices and increased supply of foreign cotton. Other factors have been partly responsible for the lesser importance of ;Aerican cotton in recent months, and they are related to some extent to the fact that the price of American has been relatively high. These are, a difficulty in obtaining desirable qualities of Auerican cotton because of the very brisk demand for these qualities by the textile industry in the United States, the shipping strike in the United States, and the operation of thu Japanese import licensing system. 1/ Prepared partly frou cables received from Agricultural Co:..iissioner D',.wson at Shinghai under date of March 12 and 20. - 13 - Imports of all kinds of cotton in February -ere 373,000 oales, com- -ared '?ith 390,000 bales in the correspondin.- month a y-ar earlier. Im- ports of American of 77,000 bales amounted to l.ss tian half of the imports in February 1936 and February 1935, --herees imports of all gro-ths other than American were one-thir. larger than in the corresponding month of the 2 preceding years. In the b months, September through February of this season, imr-orts of all kinis of cotton -ere 2,166,000 bales or 22 percent more than in the same period a year earlier. Imports of the principal kinds of cotton as a percentage of imports in the same 6 months of the preceding season were as follows: American 18 percent smaller, Indian 5g percent larger, Egyptian 80 percent larger, and Sundries 10S percent greater. China Arrivals of Chinese cotton at Shanghai -ere very large during Fet- ruary. Stocks in mills are estimated to be eqJ.al to 3 months' requirements. In site of heavy arrivals of Chinese cotton and comparatively larae stocks, it is estimated that stocks in the interior amount to one-'hir. of the present season's crop (crop no- estimated at 3,650,000 bales) Chinese mill activity has continued at an exceptionally high rate, and on the lasis of present prospects Chin-se mill consumption this season will amount to about 2,500,000 bales of 500 pounds, a record high. Mill consumption in the 10- year period ended 1932-33 averaged a little more than 2,000,0'C bales. Spinners' margins showed some decrease in Feb-uarr owing to a de- crease in yarn prices and a continued firmness in.the nrice of raw cotton. The fact that the price of Chinese cotton did not follow the rise whi?.. occurred in cotton prices in -orl1 markets nas resulted in the price of Chinese cotton being almost low enough to permit the export of considerable quantities of spinnable cotton. Exports to date, hto-ever, have bee.- com- paratively small. Some months ago it was anticipated that the br-::r Chinese crop would cause the price of Chinese -otton to fall belo- th proi.t -.-cre the tariff would be effe tive and that exports would be -ompartivel-" large as a result. To date, ho-ever, the price of Chinese cotton har bccr. eld above export levels by the unexpe-tedly heavy demands of the Chinese Cotton Manufacturing industry. Pro auction, Acreap.. and Crop Conditions United States The report of farJcrs' intentions to plnt, issued March Io, covered all major farn products except cotton. This crop is c..:ittc; because the Bureau of Ajgricultural r Eono:-ics is legally prohibited fre'.: c:.; i'.!i and publishing reports stating the intentionsof fain:.rs .s to the fcr-t-..-re to be planted& in cotton. The first official esti..-.te of acre.,:e of cottonn in cultivation will bu issued July G by the Crop RL'ortin. Pcaird. cs-5 - 14 - Egypt Ginnings up to March 1 totaled 1,770,000 bales of 478 pounds net, of which 90,000 bales were Sakellaridis and 1,630,100 bales other varieties (including 6carto). Total innings so far this year are 12 percent larger than innings up to the.saue date last year. Ginnings of Saks are 40 percent smaller and all other varieties 24 percent larger. Trade reports state with respect to the new crop that planting is in full swing in Upper Egypt and some early sowing has taken place in the Delta. Weather conditions are reported to be reasonably good, and while no acreage figures are available, the trade believes that Egyptian acreage will be as large as in 1936-37. Brazil Heavy rainfall is reported to have occurred in the cotton growing regions of Sao Paulo during Janurry, but apparently the new cotton crop has not been extensively damaged. It is also reported that several plant pests which had been expected to cause considerable damage have been less harmful than was expected. Generally favorable temperature and rainfall conditions and a small or moderate amount of damage fro.: insect pests indicate a com- paratively high yield per acre on an area which, judging from the seed dis- tributed for planting purposes, is considerably larger than last year. With favorable conditions for growing and maturing, this should nean a new record high production in Southern Brazil this year. On the basis of average growing conditions and the normal length of ti:e required to mature the cotton plant, the picking of cotton in Southern Brazil should have cozj-enced in late February or in early March. The State of Parana (Southern Brazil), which heretofore has not been an important cotton producing area, is reported to have increased its cotton acreage this season as a result of persistently low prices for coffee. Evidence of continued efforts of the various branches of the Government in Brazil to encourage cotton growing is given by a law of the State of Bahia on DeceLber 13, 1936, which provides that any new industry which may be established in the State after the passage of the law, and, in addition, all cotton presses baling cotton for export, will be exempted froL~ the State's industrial, professional, and-export taxes during the next 9 years. Chlma The cnoparatively large inco-e received this season by Chinese cotton growers as a result, on the one hand, of a large crop and, on the other, of an unexpectedly high price resulting fror a brisk demand for cotton by the Chinese cotton spinning industries gives prospect of result- ing in an increase in cotton acreage this spring. It is reported that deficient soil ,Loisture to date makes it doubtful whether there will be any increase in the cotton area in North China. It is believed, however, that some increase in acreage will take place in 1937 as compared with 1936 in the Yangtze Valley. While it is .:uch too early to :..ake any forecasts of the 1937 acreage figure, it seems likely that with average weather conditions acreage will be at least as large and probably larger than the record acreage of the 1936-37 crop. Cotton, world : I'ill stocks by grcwths, August 1, and February 1, average 1923-24 to 1932-33, 1 annual 1930-31 to 1936-37 oi Season : -merican Indian : Egyptian : Sundries : All kinds beCinning: World :Foreign countries: World : Wrld : World : World :Foreign countries August :Aug. l:Feb. 1: Aug. 1 : Feb. 1 :Aug. :Fe'. 1:Aug. l:Feb. l:Aug. 1:Feb. 1:Auc. 1:Feb. 1: Aug. 1 : Feb. 1 S1, 1,00 1,00 1,000 1,00 3 ,00 1,00 1,000 1,000 1,000 1,000 1,000 11.00 : raes bales bales bales bales bales bales ales bales 1ales bales bales bales bales IrrF r -rr -w/ -w ~7r -rr w -17 / -1 r 7- -r ~1 Avera -e 1923-24 t3 2,344 2,706 1,370 1,999 1,264 834 291 28.5 626 734 4,225 4,527 3,177 2,861 1932-23 1931)-1 : 1,985 2,429 937 907 1,364 989 325 28? 639 745 4,313 4,444 3,157 2,847 1I31-22 : 1,872 2,777 95) 1,194 1,274 8)2 392 300 660 637 4,108 4,516 3,122 2,884 1.32-33 : 2,542 2,703 1,379 1,248 835 587 328 298 660 803 4,365 4,491 3,154 2,999 1933-Z: : 2,557 2,877 1,259 1,320 1,221 977 346 355 730 941 4,854 5,150 3,511 3,552 1934-35 : 2,304 2,144 1,132 995 1,335 996 395 432 1,1)3 1,245 5,137 4,817 3,919 3,63) 1935-36 : 1,7)4 2,247 955 843 1,248 809 407 420 1,266 1,4)3 4,625 4,879 3,843 3,449 ' 1953-37 : 1,572 2,773 716 739 1,279 1,026 383 404 1,13 1,688 4,641 5,891 3,744 3,825 ' Cjmputod from data report( i by the International Federation of IFaster Cotton Spinners' and I'anufacturers' Assic- iati)ns except as fl)1ors: The Urited States, fr)n. *e-jorts of the E.:reau of the Census; China, from reports of the C' inese Cotton T:ill- awneras ssX .o...n; Germ.,:i-y for 1935-36 and Italy f)r 1935-36 and 1930-u7, estimates of the Bureau )f Agricul- tural Eccnrm)Tics. L/ Ar.'ri3rin ru-d inrijc n rrunilng bales; Indian and Egyptian in bales of approxin.-tely 5b)0 pounds, converted fr-. r'n"in, tbnl*s by c'nsiiering 1 Indian bale equal to 0.8 bale and 1 E;:yprtirn bale equal to 1.5 bales. Cotton: Mill consumption, by growths, average 1923-24 to 1932-33, annual 1930-31 to 156-37 cr erican Indian Eg yptian : Sundries : All kinds ,o rld Foren World world world World Foreign eason : countries : : ____ __ countries ginning: alf" 12 Half : 12 : Half : 12 :Half :12 Half 12 :Half : 12 ::lf august year :months :year :months: year :rionths: year :months: year :months: year :months : year :months : Aug.-: A Aug Au- g g.-: Aug.-: ug.- Aug.- Aug.-: Aug.-: Aug.- Aug.- : Aug.- : Au.- : Aug.- : Jan. : July : Jan. : July Jan. : uly : Jan. : July : Jan. : July : Jan. : July : Jan. : July : 1,000 1,000 1,000 ',000 1,000 ,000 1,)00 1,000 1,000 1,000 1,000 1,000 ],000 1,zj0)0 : bales bales bales bales balales ales ales bales bales bales baes bales bales bales Ti.. T _, YT T'--f ;- 17 1T -- iT 1 '"" " rage 33-24 to: 32-33 : 6,747 13,476 3,779 7,549 2,190 4,269 712 1,427 2,116 4,361 11,765 23,533 8,670 17,351 0-31 : 5,272 10,901 2,901 5,817 2,466 4,80S 592 1,260 2,479 4,862 10,809 21,831 8,349 16,568 51-32 6,112 12,316 3,549 7,572 2,317 3,925 710 1,431 2,113 4,234 11,252 21,900 8.626 17.040 Full Text xml version 1.0 encoding UTF-8 REPORT xmlns http: xmlns:xsi http: xsi:schemaLocation http: INGEST IEID EQQU2Y0GY_MNXD2V INGEST_TIME 2013-03-27T15:58:17Z PACKAGE AA00013000_00025 AGREEMENT_INFO ACCOUNT UF PROJECT UFDC FILES
https://ufdc.ufl.edu/AA00013000/00025
CC-MAIN-2020-40
refinedweb
7,964
63.29
This post if for when you need to export data in the form of XML from Microsoft Dynamics NAV. If you are not familiar with how to program with MSXML DOM, then it can take a lot of time and work to create even a simple XML document. The purpose of this post is to show a simple example, and to get you started programming with MSXML DOM from NAV. I have split this into two posts: "How to write" (this post), and "How to read" an XML Document (click here), since the methods and functions used are quite different. Why not just use XML-Ports? You can of course, but then you limit yourself to the functionality and limitations that exist in XML-Ports. An example of a limitation in XML-Ports is that they do not support namespaces. If you think that one day you may need functionality that is not supported by XML-Ports, and for which you have to use MSXML DOM anyway, then consider to just use MXSML DOM from the start. It is more complex to begin with, but once you have a set of functions to add / search etc elements in an XML document, then it does not have to be much more complex than using XML-Ports. Note that it is not possible to access an XML docuemnt via MSXML DOM from an XML-Port while the XML-Port is accessing it. The two methods are mutually exclusive. An XML document is organized as a heararchy of elements, and everything (elements and data) gets added piece by piece to existing elements. Let's get started with the simplest possible XML DOcument: Create a new codeunit with 3 variables: Name DataType Subtype Length XMLDoc Automation 'Microsoft XML, v4.0'.DOMDocument DOMNode Automation 'Microsoft XML, v4.0'.IXMLDOMNode DomTextNode Automation 'Microsoft XML, v4.0'.IXMLDOMText In this example I use MSXML version 4, but you can use version 5 or 6 if you prefer. Version 4 is mostly used because it most likely contains all the functionality you will need, and it will be backward compatible to more machines - even old ones. Initialize the document: OnRun() CREATE(XMLDoc); XMLDoc.async(FALSE); Unless you have specific reasons not to, set asynch = FALSE. Especially when you are reading an XML document. It means that it will load the whole document into memory before it starts reading through it. If you don't set this property, you may begin to process the document before it is completely loaded into memory. Now create a new node, and then add it to the document: DOMNode := XMLDoc.createNode(1,'NodeName',''); XMLDoc.appendChild(DOMNode); Then add some data. This is done in the same way as you add an element: Creat the element first, and then add it to the right place in the document: DOMTextNode := XMLDoc.createTextNode('NodeValue'); DOMNode.appendChild(DOMTextNode); You can add any additional elements like this: Creat the element of the type that you need (node, text, attribute etc), and then append it to the document. To see the document, save it to disk: XMLDoc.save('C:\XML\MyXML.xml'); Note: If you run on Vista, it might not allow you to save files on the root of the c: drive. So create a new folder, for example c:\XML\ Then run this codeunit. You should get a very simple document like this: <NodeName>NodeValue</NodeName> If you want to add further nodes to this document then repeat the steps above to create a new node, then append it to an existing node. For example, to add a new node: Create a new variable: NewDOMNode : 'Microsoft XML, v4.0'.IXMLDOMNode Initialize); Now, your xml document will look like this: Adding namespace and Attributes: You can add a name space either to the whole document, or to individual nodes. To add a name space to the document, go back to the relevant line above, and specify the 3rd parameter: DOMNode := XMLDoc.createNode(1,'NodeName','MyNameSpace'); Finally, adding an attribute to a node is similar to adding a text element: Initialize the Attribute, then add it to the relevant node. Use the function SetNamedItem to add attributes. Let's add an attribute called ID with the value 10000: Create a new Automation variable: XMLAttributeNode : 'Microsoft XML, v5.0'.IXMLDOMAttribute Initialize the attribute, then add it to the node: XMLAttributeNode := XMLDoc.createAttribute('ID'); XMLAttributeNode.value := '10000'; DOMNode.attributes.setNamedItem(XMLAttributeNode); The whole codeunit should now look like this: // Initialize the document CREATE(XMLDoc); // Create Node and attach it to the document. Use name space MyNameSpacefunction DOMNode := XMLDoc.createNode(1,'NodeName','MyNameSpace'); XMLDoc.appendChild(DOMNode); // Add data (text) to the node DOMTextNode := XMLDoc.createTextNode('NodeValue'); DOMNode.appendChild(DOMTextNode); // Add an attribute to the node XMLAttributeNode := XMLDoc.createAttribute('ID'); XMLAttributeNode.value := '10000'; DOMNode.attributes.setNamedItem(XMLAttributeNode); // Initialize); // Finally, save the document for viewing: XMLDoc.save('C:\XML\MyXML.xml'); Further references: MSXML is further documented in MSXML Software Development Kit (MSXMLSDK). I would recommend that you download this to have the online help available for all of the MSXML DOM functions. These postings are provided "AS IS" with no warranties and confer no rights. You assume all risk for your use. Lars Lohndorf-Larsen (Lohndorf) Microsoft Dynamics UK Microsoft Customer Service and Support (CSS) EMEA
https://blogs.msdn.microsoft.com/nav/2008/03/31/sample-of-how-to-write-a-simple-xml-document-using-msxml-dom-in-nav/
CC-MAIN-2017-39
refinedweb
883
54.73
My Training Period: xx hours. Before you begin, read some instruction here. The Windows MFC programming (GUI programming) for DLL can be found at MFC GUI Programming Step-by-step Tutorial. Abilities that supposed to be acquired:. An executable file links to (or loads) a DLL in one of two ways: Implicit linking. Explicit linking... With explicit linking, applications must make a function call to explicitly load the DLL at run time. To explicitly link to a DLL, an application must: Call LoadLibrary() (or a similar function) to load the DLL and obtain a module handle. Call GetProcAddress() to obtain a function pointer to each exported function that the application wants to call. Because applications are calling the DLL's functions through a pointer, the compiler does not generate external references, so there is no need to link with an import library. Call FreeLibrary() when done with the DLL. or if you are in the process of building an application, the following error message may be output: testdll.obj : error LNK2019: unresolved external symbol "int __cdecl mydll(char *)" (?mydll@@YAHPAD@Z) referenced in function _main Debug/mydlltest.exe : fatal error LNK1120: 1 unresolved externals re-link (assuming they are calling GetProcAddress() with a name of a function and not with an ordinal value), whereas applications using implicit linking must re-link.. The 32-bit edition of Visual C++ uses __declspec(dllimport) and __declspec(dllexport) to replace the __export keyword previously used in 16-bit versions of Visual C++. (PE) format is designed to minimize the number of pages that must be touched to fix imports. To do this, it places all of the import addresses for any program in one place called the Import Address Table. This allows the loader to modify only one or two pages when accessing these imports.: #define DllImport __declspec(dllimport) DllImport int j; DllImport void func(); Using __declspec(dllimport) is optional on function declarations, but the compiler produces more efficient code if you use this keyword. However, you must use __declspec(dllimport) in order which indicates whether you are building the DLL or building the client application. For example: (comes with your Visual Studio or you can try more powerful tool, PEBrowser). A. For example, a DLL that contains the code to implement a binary search tree might look like the following: LIBRARY BTREE EXPORTS Insert @1 Delete @2 Member @3 Min @4 If you use the MFC DLL Wizard will have to either place the decorated names in the .DEF file or define your exported functions with standard C linkage by using extern "C". If you need to place the decorated names in the .DEF file, you can obtain them by using the DUMPBIN tool or by using the linker /MAP (MFC), and exporting using a .DEF file, place the following code at the beginning and end of your header files that contain the exported classes: #undef AFX_DATA #define AFX_DATA AFX_EXT_DATA // <body of your header file> #undef AFX_DATA #define AFX_DATA may. In the 32-bit compiler version, you can export data, functions, classes, or class member functions from a DLL using the __declspec(dllexport) keyword. __declspec(dllexport) adds the export directive to the object file so you don't need to use. To export functions, the __declspec(dllexport) keyword must appear to the left of the calling-convention keyword, if a keyword is specified. For example: __declspec(dllexport) void __stdcall WilBeExportedFunctionName(void); And the real one may look something like this: __declspec(dllexport) int mydll(LPTSTR lpszMsg) To export all of the public data members and member functions in a class, the keyword must appear to the left of the class name as follows: class __declspec(dllexport) CExampleExport : public CObject { ... class definition ... };: #define DllExport __declspec(dllexport) __declspec(dllexport) stores function names in the DLL's export table. Initializing a DLL Typically, your DLL has initialization code (such as allocating memory) that must execute when your DLL loads. When using Visual C++, where you add code to initialize your DLL depends on the kind of DLL you are building. If you don't need to add initialization or termination code, there's nothing special you have to do when building your DLL. If you need to initialize your DLL, the following table describes where to add your code. In Win32, all DLLs may kind of DLL, either you should have a function called DllMain() in your source code or you should use the DllMain() provided in the MFC library. Because extension DLLs do not have a CWinApp-derived object (as do regular DLLs), you should add your initialization and termination code to the DllMain() function that the MFC DLL Wizard generates. The wizard provides the following code for extension DLLs. In the code portion below, PROJNAME is a placeholder for the name of your project. #include "stdafx.h" #include <afxdllx.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif static AFX_EXTENSION_MODULE PROJNAMEDLL = { NULL, NULL }; extern "C" int APIENTRY DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved) { if (dwReason == DLL_PROCESS_ATTACH) { TRACE0("PROJNAME.DLL Initializing!\n"); // extension DLL to export CRuntimeClass objects or resources to the client application. If you are going to use your extension DLL from one or more regular DLLs, you must export an initialization function that creates a CDynLinkLibrary object. That function must be called from each of the regular DLLs that use the extension DLL. An appropriate place to call this initialization function is in the InitInstance() member function of the regular DLL's CWinApp-derived object before using any of the extension DLL's exported classes or functions. In the DllMain() that the MFC DLL Wizard generates, the call to AfxInitExtensionModule captures the module's run-time classes (CRuntimeClass structures) as well as its object factories (COleObjectFactory objects) for use when the CDynLinkLibrary object is created. You should check the return value of AfxInitExtensionModule; if a zero value is returned from AfxInitExtensionModule, return zero from your DllMain() function. If your extension DLL will be explicitly linked to an executable (meaning the executable calls AfxLoadLibrary to link to the DLL), you should add a call to AfxTermExtensionModule on DLL_PROCESS_DETACH. This function allows MFC to clean up the extension DLL when each process detaches from the extension DLL (which happens when the process exits, or when the DLL is unloaded as a result of a AfxFreeLibrary call). If your extension DLL will be linked implicitly to the application, the call to AfxTermExtensionModule is not necessary. Applications that explicitly link to extension DLLs must call AfxTermExtensionModule when freeing the DLL. They should also use AfxLoadLibrary and AfxFreeLibrary (instead of the Win32 functions LoadLibrary() and FreeLibrary()) if the application uses multiple threads. Using AfxLoadLibrary and AfxFreeLibrary ensures that the startup and shutdown code that executes when the extension DLL is loaded and unloaded does not corrupt the global MFC state. Because the MFCx0.DLL is fully initialized by the time DllMain is called, you can allocate memory and call MFC functions within DllMain (unlike the 16-bit version of MFC). Extension DLLs can take care of multithreading by handling the DLL_THREAD_ATTACH and DLL_THREAD_DETACH cases in the DllMain() function. These cases are passed to DllMain() when threads attach and detach from the DLL. Calling TlsAlloc() when a DLL is attaching allows the DLL to maintain thread local storage (TLS) indexes for every thread attached to the DLL. Initializing Non-MFC DLLs To initialize non-MFC DLLs, your DLL source code must contain a function called DllMain(). The following code presents a basic skeleton showing what the definition of DllMain() might look like: BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { switch(ul_reason_for_call) { case DLL_PROCESS_ATTACH: ... case DLL_THREAD_ATTACH: ... case DLL_THREAD_DETACH: ... case DLL_PROCESS_DETACH: ... } return TRUE; }t's nothing special you have to do when building your DLL. If you need to initialize your DLL, where you add your code depends on the kind of DLL you are writing.. #include "horses.h" CHorse Equus(ARABIAN, MALE); CHorse Sugar(THOROUGHBRED, FEMALE); BOOL WINAPI DllMain(HANDLE hInst, ULONG ul_reason_for_call, LPVOID lpReserved) .... ------------------------------------End C Run –Time & Dynamic Link Library Part 1------------------------------------ Further reading and digging: Microsoft Visual C++, online MSDN.. Check the best selling C / C++ and Windows books at Amazon.com.
http://www.tenouk.com/ModuleBB.html
CC-MAIN-2014-52
refinedweb
1,363
51.07
Opened 2 years ago Last modified 5 weeks ago #27074 new enhancement Make .sage modules importable Description (last modified by ) It's relatively easy using import system hooks in Python to make new file types 'importable' using the standard import statement. E.g. a file like mymodule.sage could be imported as mymodule just as though it were mymodule.py. Importing a .sage module is of course just a thin layer over a normal Python module import, but to pass it through the Sage preparser. There are of course some risks to making .sage modules importable. For example, what if a user has both a foo.sage and an foo.py? Which one takes priority upon import foo? In particular it could introduce quite some surprises if a user has something like os.sage in their current directory. Unfortunately it's not possible to extend the syntax of import statements, which would be nice. But, while the "module name" portion of an import statement must be a valid identifier, we can still otherwise process it however we want. So maybe .sage module imports would be initiated only if .sage is used explicitly in the import statement. So for example, to import a sage module named foo.sage one would literally write: import foo.sage to distinguish it from a Python module named foo.py. Of course, if there is a Python package named foo that happens to have a sage sub-module there is still a conflict. But this is a bit unlikely for most cases. So in order to make such a feature available, while mitigating potential problems with it, I might suggest a few additional restrictions: - There would be a function to enable/disable .sageimport functionality on the fly. When first introduced this would be disabled by default, but we would certainly want to make the feature easily discoverable through the documentation, with all the caveats discussed. - In the off chance that there is a conflict between a .sagemodule an a plain Python module, the system should check for that. In that case the .sagemodule still takes priority (if .sageimports are enabled), but a warning about the conflict is shown. - This feature should be Python 3 only. That will make it easier to implement, due to the significant differences between the import systems, and it will also give a nice motivation, to anyone who wants the feature, to switch to Python 3. See also: Change History (19) comment:1 Changed 2 years ago by - Summary changed from Make `.sage` modules importable to Make .sage modules importable comment:2 Changed 2 years ago by - Owner changed from (none) to embray comment:3 follow-up: ↓ 4 Changed 2 years ago by comment:4 in reply to: ↑ 3 ; follow-up: ↓ file, a foo.pyc file, a foo.so and a foo/__init__.py file in the same directory: Python chooses a certain order to try these filenames and it doesn't seem to be a big problem in practice. So the .sage convention in the import statement seems strange and unneeded to me. comment:5 in reply to: ↑ 4 ; follow-up: ↓file, a foo.pycfile, a foo.soand a foo/__init__.pyfile in the same directory: Python chooses a certain order to try these filenames and it doesn't seem to be a big problem in practice. So the .sageconvention in the import statement seems strange and unneeded to me. Perhaps so. The idea there was just to make it less likely for it to shadow Python modules on sys.path that have absolutely nothing to do with Sage, and cause sudden strange breakage. But if the other mitigation strategies for that are employed, then perhaps we don't need to use that convention in the first place. Also, many stdlib libraries would likely be imported already by the time the import hooks necessary for supporting .sage imports are loaded. So for example, it's not likely that having an os.sage will cause import os to break because it will have already been imported (the downside to that is that then trying to import their local os.sage will quietly fail, but I think we can still consider this somewhat "intermediate usage" where one has to at least understand what Python imports are and not to name things the same as system libraries...) comment:6 in reply to: ↑ 5 ; follow-ups: ↓ 7 ↓ 8 Changed 2 years ago by comment:7 in reply to: ↑ 6 ; follow-up: ↓ 9 Changed 2 years ago by +100 to having this! Thanks Erik for starting this ticket (it has been on my todo list for a while now).). I agree with this. However the ability to import .sage files should be optional, and switchable at runtime, as Erik suggested. Otherwise it could break code that is now working. Still, if there's foo.py and foo.sage in the same dir, which should shadow which? I'd say foo.py takes priority. comment:8 in reply to: ↑ 6 Changed 2 years ago by). That's true about os; I've seen this more often with things like "string" or "logging". And I agree it's no different. My only point is that currently it does not work that way for .sage files, so if we implement this it has to be opt-in, at least at first, because suddenly producing side-effects based on files the user happens to have in their working directory is user-hostile. comment:9 in reply to: ↑ 7 Changed 2 years ago by Still, if there's foo.pyand foo.sagein the same dir, which should shadow which? I'd say foo.pytakes priority. It would, just as in Jeroen's analogy to .pyc files. Further, if all of foo.sage, foo.py, and foo.pyc exist it would be the .pyc file that takes precedence. However, if foo.py is newer than foo.pyc it will read that instead and recompile it. I think traditionally the import system would just compare mtimes here, but this is more recently complicated (I think since Python 3.7) by PEP-552. A similar approach could still be taken, if needed, for .sage -> .py compilation. comment:10 Changed 23 months ago by Per discussion with Luca, I found this prototype I worked on in #24681 which might be helpful here: I remember now that the context to that work was to make the source code for Cython modules findable on Python 3, so the idea was to add an import hook that could recognize imports of Cython-modules based on the presence of the actual .pyx file in the same path as the actual extension module being imported (it does not do anything like automatically interpret/compile the Cython code into binaries; it just recognized Cython modules as distinct from other extension modules). For importing .sage files the problem is a little different. But all the MetaFileFinder stuff I had to do was not in any way specific to Cython, but rather was necessary in order to extend the default PathFinder installed in sys.meta_hooks on Python 3. It turns out I didn't implement this for Python 2 after all. As I wrote on #24681 it used to be easier to make import <modname> for non-Python files work, much as in the "shelve importer" example on this pymotw post: I recall once in the past teaching a tutorial on this where I made something similar to import JSON files as Python modules (I'm not sure now where that tutorial is; it was years ago). I think for now we might as well ignore Python 2. On Python 3 I think it's now a little easier than it used to be to implement custom module loaders. But adding custom module finders is more of a problem. It's a kind of chicken/egg problem, where in Python 2 it was actually easier to override the default behavior with import hooks, because the default behavior was completely hard-coded in the interpreter. But now the default import system is bootstrapped on top of the same import hook system that is used to extend it, with the result that it's now harder to extend the default behavior while not also breaking/contradicting with the default import system. comment:11 follow-up: ↓ 13 Changed 17 months ago by [ ? comment:12 Changed 17 months ago by - Cc charpent added comment:13 in reply to: ↑ 11 Changed 17 months ago by - Cc nthiery added [ ? I'm afraid I don't see at all how that's related. This is just about making .sage files importable through the normal Python import system. Monkey-patching classes is a thing you can already do, having relatively little to do with how modules are imported. Nicolas worked on something like this with so you might want to ask him about it. comment:14 Changed 10 months ago by - Milestone changed from sage-wishlist to sage-9.2 Let's see if we can revive this idea now that the py3 transition is complete... I think it's a key to the recurring question "how to distribute user packages" -- for user packages that consist of a bunch of sage files comment:15 Changed 9 months ago by - Cc nbruin added comment:16 Changed 9 months ago by comment:17 Changed 9 months ago by - Milestone changed from sage-9.2 to sage-9.3 comment:18 Changed 3 months ago by - Milestone changed from sage-9.3 to sage-9.4 Setting new milestone based on a cursory review of ticket status, priority, and last modification date. comment:19 Changed 5 weeks ago by - Cc yzh added Do we need to worry about foo.pyshadowing foo.sage? The long-standing situation on this was that foo.sagewould generate foo.py- did this change at some point I missed?
https://trac.sagemath.org/ticket/27074
CC-MAIN-2021-21
refinedweb
1,649
74.29
* . This is an obvious requirement for the interrupt routine, which was forgotten and only surfaced when I used a timer callback started with multiplications in an innocent add-in. r0..r7 are saved automatically, which leaves pr, gbr, mach et macl susceptible to corruption by the interrupt handler. t6k11: use the gint array for variant detection r61524: use true triple buffering by default display: define DWIDTH and DHEIGHT display: add C_RGB(r,g,b) (0 ≤ r,g,b ≤ 31) [fxcg50] The return code -1 noted in the BFile_FindFirst or BFile_FindNext is from test, which mean it could be possibles that they are negative error code from functions failing and not meaning that no file have been found, to be sure, the value IML_FILEERR_ENUMERATEEND from filebios.h in the fxlib need to be checked (and maybe defined in gint with a more meaningful name for user interactivity) This macro used to protect the declaration of the [vram] variable of gint. This variable was short to keep drawing functions short but could clutter the namespace. That being said, it's even better to just [#define vram gint_vram] if you need. This change renames the variable to [gint_vram], exposes it whenever <gint/display.h> is included, and removes the GINT_NEED_VRAM macro altogether. This(). * Update TOTO list * Change the type of gint_vbr to comply with a new warning in GCC 9 * Add strcmp() Adds support for dma_memcpy(), and uses a proper ILRAM allocation scheme (static linking here) for the temporary buffer in dma_memset(). This change adds support for three sections .ilram, .xram and .yram, along with three macros GILRAM, GXRAM and GYRAM, that can be used to statically load data to on-chip memory. The IL memory is unavailable when the processor goes to sleep, causing any involved DMA transfer to stall. The dma_transfer_wait() normally sleeps to save battery power, but this causes the whole system to freeze and never wake up. This change lets dma_transfer_wait() decide dynamically whether to sleep or spinlock. There is no concrete improvement over dma_transfer_noint() when using IL memory, but it makes dma_transfer() fully generic. Obviously the same goes for X and Y memory. Currently there seems to be no DMA at all on fx9860g. Further investigation would be required, because this would be the first major difference between the SH7305's found in fx9860g and fxcg50 models. An automated peripheral register discovery strategy might help, but identifying discovered registers would be non trivial. Also use the pruning ability of the Makefile to avoid troublesome ifdef's in the code. This change introduces two new mechanismes for executing user code when an exception occurs. * This first is the custom panic message, which usually displays "System ERROR". The function that performs this task can now be user-defined. It is also run in user mode because the exception handler rte's into it, allowing it to execute any kind of interrupt-inducing task. The behavior is undefined if this function raises an exception. * The second is an exception-catching function, which (when set) is called every time an exception occurs, and is granted the chance of handling the exception to continue execution normally. It can be used in various ways, the most primitive of which is recording the exception and going back. It runs in interrupt mode and must not raise any kind of exception. Behave like Basic's Horizontal and Vertical commands. Internal dline() optimizations are renamed gint_dhline() and gint_dvline(). Also supports ghline() and gvline() in the gray engine. Optimization cases here are amost negligible due to limiting RAM access frequencies and the very limited amount of work accomplished in the functions. Code maintainability is prioritized by using dline(). May be useful later on for libraries such as libprof. This change introduces exception handlers that default to a fatal error with an on-screen description of the exception and some debugging information. It also adds the dprint() function as a definitely-needed helper and removes bootlog_unmapped() by using the exception handler for the fatal error display. (Also printf() is now required in all gint add-ins; this is sad, but space is not as much of a constraint as debugging.) Finally, the exception handler is used to handle an interrupt which is an exception in practice, the DMA address error. On fx-CG 50, additional DMA-related information is displayed on the screen. This is left out on fx-9860G as there is not enough space. This commit introduces bopti for fxcg50 with the first basic 16-bit formats. The performance is rather slow, especially for large images, and will need refinements and/or overclock to be really efficient in full-screen real-time applications. This commit introduces bopti for fx-CG 50. Currently the only interfaces are the bopti_render_{clip,noclip} functions, and the only supported formats are r5g6b5 and r5g6b5a. The algorithm for r5g6b5 is optimized to perform longword accesses using movua.l, whereas the algorithm for r5g6b5a uses plain word accesses because transparency checks feel more difficult than one more loop iteration. These algorithms are still slow for large surfaces and struggle to keep up 25 FPS in full-screen, so possible improvements with the DMA should definitely be tested before restorting to overclock. This change finally introduces gray image rendering with bopti. This is the final iteration of bopti v2 and certainly the fastest so far. All four profiles are supported, without change to the format. This revision includes the base gray engine with sensible starting defaults, gclear() and grect(), as well as gtext(). This commit introduces three timer driver changes: * Export the definitions of the timer structures to a detailed header at <gint/mpu/tmu.h>, and re-use them in the driver. This integration is still limited as the driver keeps its own address definitions and event codes. * Clean the timer stop routine that is used in the interrupt handler. Up until now the interrupt handler would only stop TSTR, which is not enough to cleanly leave the timer (need TCOR=TCNT=-1) and is not even sound with respect to gint's semantics as UNIE stays enabled so the timer is not made available again. The interrupt handler now calls into C code when the timer stop condition is met (callback returns non-zero) to keep this clean. This unsurprisingly solves problems that occurred in certain situations when a timer was used repeatedly. * Expose timer addresses using a timer_address() function, compensating for the lack of address definitions in <gint/mpu/tmu.h>. This interface is likely to evolve in the future to better integrate the address in the MPU headers and move them out of the driver. This makes it possible to write application code without specifying the target machine, which is especially useful for libraries. The first user of this system is libprof. Since Memallox's newlib port is currently unstable, gint has to provide some standard functions on its own. Instead of a single <gint/std.h> header, this commit makes a gint/std directory containing headers under standard names. Will be used in time for BFile. Also add a power interface (without driving code) and switch toolchain because the previous sh4eb-nofpu-elf toolchain was not completely FPU-free. * Now uses topti instead of fxlib for text (including MMU failure) * Fit .pretext into 4k for everything before MMU succeeds * A short version of sprintf() for dynamic messages * Support a driver function, status(), to allow early driver debug * Expose more useful platform information in <gint/mpu.h> * Expose the first of a few CASIOWIN syscalls Also transition the bootlog from fxlib to topti.
https://gitea.planet-casio.com/Lephenixnoir/gint/commits/branch/compat/include/gint
CC-MAIN-2020-29
refinedweb
1,263
53.92
A performance data collector gathers the current statistics of items such as the amount of space used in a file system. The data can be collected using either a script or an SNMP command. For our Filesystem data, we must create a new data collector called Filesystem (this is a special name) that will return a property called usedBlocks (another special name). If your operating system's MIB provides a usedBlocks (or something named like that) value, then we can make use of existing Zenoss infrastructure and just collect that data using SNMP. Otherwise, you need to create a script to take the total size of the filesystem (totalBlocks) and subtract the freeBlocks value. Unfortunately, AIX only provides freeBlocks, so we need to create a command. With the Zenoss 2.4 release, we can also create a command parser to gather our performance information. This new functionality allows you to write simple code to gather performance data and graph the results. Multiple collectors for different components of a system can be created, or one huge collectors for everything can be created. Smaller collectors are preferred for maintenance reasons. The following collector is for calculating file system free space, and would live in the libexec/ directory of your ZenPack. #!/usr/bin/env python """Gather used disk space statistics for AIX""" import sys import re from subprocess import * base_fs_table_oid= "1.3.6.1.4.1.2.6.191.6.2.1" def process_disk_stats( device, community, totalBlocks_oid, freeBlocks_oid ): """Gather OID info and sanitize it""" cmd= "snmpwalk -v1 -c %s -On %s %s %s" % ( community, device, \ totalBlocks_oid, freeBlocks_oid ) proc= Popen( cmd, shell=True, stdout=PIPE, stderr=PIPE ) # # Check to make sure that we don't have any hangups in # executing our smidump # if not proc.stdout: print "Couldn't open pipe to stdout for %s" % cmd return if not proc.stderr: print "Couldn't open pipe to stderr for %s" % cmd return ( line1, line2 )= proc.stdout.readlines() totalBlocks= line1.split()[-1] freeBlocks= line2.split()[-1] usedBlocks= totalBlocks - freeBlocks return totalBlocks, freeBlocks, usedBlocks if __name__ == "__main__": if len(sys.argv) < 4: print "Need device, community and fs_index arguments!" sys.exit(1) (device, community, fs_index )= sys.argv[1:] totalBlocks_oid= ".".join( base_fs_table_oid, 5, fs_index ) freeBlocks_oid= ".".join( base_fs_table_oid, 6, fs_index ) totalBlocks, freeBlocks, usedBlocks= process_disk_stats( device, \ community, totalBlocks_oid, freeBlocks_oid ) print "totalBlocks:%s freeBlocks:%s usedBlocks:%s" % ( totalBlocks, \ freeBlocks, usedBlocks ) sys.exit(0) Zencommand may be used to execute commands on remote hosts using the SSH protocol. This provides secure and flexible performance monitoring for Unix-style systems such as AIX, Solaris, OS X (Darwin) and Linux servers. When the remote host has commands that show data in a format already understood by Zencommand (such as Nagios or Cacti plugins), Zencommand can process the results and update the ZODB. However, if you are monitoring servers that have not had these commands installed, you need to extend Zencommand with new parsers to understand the results. The basic data flow for Zencommand is this: A collector starts Zencommand with a collector name, like localhostor collector2. Zencommand contacts zenhub and loads the commands to be run against the devices for that configuration. The command configuration includes details such as "use SSH" to run the command on the remote box and credentials to allow access to the remote host. The command configuration also includes a specification for the parser to use on the data that is returned by the command. Zencommand runs the command on the remote host, and when the command finishes, a parser is created and the results are passed to the processResults()method of the parser. The processResults()method is passed the command configuration fetched from ZenHub, and an object into which parsed results will be placed. The parser is also used to copy any data needed by Zencommand during the parsing. Zencommand takes the returned Python dictionary from the parser and updates the ZODB. Consider the Unix df command. It can be used to determine free disk space on a device's file systems. Here's a typical output format from Linux: Filesystem 1K-blocks Used Available Use% Mounted on /dev/sda6 57669700 34162636 20577616 63% / /dev/sda7 71133144 28824804 38694924 43% /home /dev/mmcblk1 3924476 536 3923940 1% /media/disk The Zenoss data modeler (zenmodeler) will have created components under this device for the file systems. The mapping of data to the component must use the mount point information. ZenHub must copy mount point information from the model data stored in the ZODB into the configuration for this command. To know what data may be needed for parsing, ZenHub creates the parser that will be used by Zencommand, and calls the dataForParser() method. Remember, this happens in ZenHub, and not Zencommand, and it happens before any command is run. The result of dataForParser() is a Python dictionary that is stored as data in the command configuration passed to Zencommand. When the parser is invoked in Zencommand, it will have access to this information. Note After the parser digests the results of running the command, it can produce performance information and events. The result object is a simple Python class that contains two lists, one called valuesand the other called events. The eventsitem contains a dictionary of string to value mappings which are turned into events. Zencommand will update the event with the device name, but the rest of the fields (such as component, severity, etc) are up to the parser to fill in. The valuesitem is a list of two-element tuples. The first element is the data point, and the second is a value, which is a Python number or None. Noneis always ignored. Every command run by Zencommand comes with a list of data points that correspond to that command. In our df example, the datapoints may include percentUsedand blocksFree, along with any thresholds or parser-specific data, such as mount point. Thresholds will be tested by Zencommand, and threshold events automatically generated. The command's exit code is available at parse time, too. Parsers will be available to Zenoss when they are placed in the $ZENHOME/Products/ZenRRD/parsers directory or in a ZenPack's $ZENHOME/ZenPacks. directory. Each parser should be a sub-class of the pkg. zpid- version_id-py2.4.egg/Zenpacks/ pkg/ zpid/parsers Products.ZenRRD.CommandParser.CommandParser class. A command like df is a very common case. Unix commands will often emit easily-parsed, line-oriented records. There are some useful subclasses of CommandParser that perform much of the parsing if you provide these parsers with the right details, such as regular expressions. They are: Let's examine what these values might be for our df command, and its example output. For the componentScanner, we want to find the mount-point data and extract it, so that we can match the Unix file separator ('/') to the component file system that has the id "_". We can use something like: % (?P<component>/.*)$ For the scanners, we'll use a tuple of regular expressions to pull out the numerical values we want: ( r' (?P<availableBlocks>\d+) +(?P<percentUsed>\d+)%' ) For the componentScanValue, we'll specify mountso that the mount point information is copied to the command configuration by ZenHub and matched against the componentvalue parsed by the componentScannerregular expression.
http://community.zenoss.org/docs/DOC-3827
CC-MAIN-2014-42
refinedweb
1,205
54.12
This is the third and final installment of the tutorial on Xtext. In Part 1, we demonstrated how to set up a simple DSL. Part 2 focused on writing a code generator in Xtend, Xtext's language for specifying generated output. In this article, we'll explain how to customize the Xtext infrastructure of your language. We'll use the examples from Part 1. If you have not done so yet, follow the steps to setup the Xtext project and the runtime configuration. You can start with the final grammar right away, but do not forget to run the workflow and to set the memory settings in the runtime configuration as indicated there. You should now be able to open a .dmodel file in a new project inside Eclipse. Getting and Outline View The outline view (Window &lgt; Show View > Outline) displays the structure of the underlying semantic model of the currently edited document. The default works fine. Try Link with Editor, Sort and double click, etc. However, good defaults do not always fit all use cases. There are some things Xtext could not guess, so the outline looks a bit odd: The root node belongs to an element of type Domainmodel, which does not have a name attribute so the label is '<unnamed>'. Furthermore, all elements have the same icon making it hard to distinguish between Imports, PackageImports, Entities and DataTypes. Also, as shown in Figures 1a and b, the panes can acquire a lot of clutter content. Domainmodeland Importand with different icons for the remaining types as shown in Figure 1b. Before we start customizing the outline, here is a bit of background information on the outline framework used in Xtext: The outline tree consists of IOutlineNodes, which usually correspond to model elements. The component responsible for the outline view of our language is the DomainmodelOutlineTreeProvider. Its superclass DefaultOutlineTreeProvider provides a couple of helper methods to control the structure and the appearance of the tree. This approach is a common idiom in the Xtext framework. You will usually find a fully working default implementation that is either generated or (more often) based on generic functionality of the Eclipse Modeling Framework. That is, there is no piece of code in your own code base but in the libraries of the framework that performs the job. However, for common customization scenarios, a stub implementation may be available in your language project. Polymorphic Dispatch Functions To calculate the children of a node, the DefaultOutlineTreeProvider looks for a method named _createChildren. Similar to the dynamic dispatch functions of Xtend2, the method that matches the types of the current node and the model element best is chosen at runtime. It employs Java's reflection mechanism internally. For example, if we want to skip the first visible node belonging to the Domainmodel, we have to implement _createChildren(DocumentRootNode, Domainmodel): public class DomainmodelOutlineTreeProvider extends DefaultOutlineTreeProvider { protected void _createChildren(DocumentRootNode parentNode, Domainmodel domainmodel) { for(AbstractElement element: domainmodel.getElements()) { createNode(parentNode, element); } } protected void _createNode(IOutlineNode parentNode, Import modelElement) { } } In this example, we avoided the creation of outline nodes for Import elements by adding another dispatch function _createNode(IOutlineNode,Import) with empty contents. That is all for the structural changes; let's continue with the appearance. Now that you are familiar with Xtext's concepts of polymorphic dispatch, you should not be surprised that you can choose the icons with another dispatch function _image(), which returns an Image for a model element. Managing images can be a bit tedious in SWT as they consume scarce OS resources. Xtext provides an interface, IImageHelper, that hides all these nifty details from the user. It expects images to be in a folder icons in the root of the project, so you have to create that folder in the project org.example.domainmodel.ui. Make sure this folder is also visible at runtime by checking it in the build.properties of the same project: source.. = src/,\ src-gen/ bin.includes = META-INF/,\ .,\ plugin.xml,\ icons/ Now get a grip on some fancy icons and copy them into the icons folder.
http://www.drdobbs.com/open-source/customizing-xtext/231902091
CC-MAIN-2017-22
refinedweb
679
53.92
State management is essentially a way to facilitate communication and sharing of data across widgets. It creates a tangible data structure to represent the state of your app that you can read from and write to. When it comes to managing state in a flutter application, there are many options, but I find myself relying on stateful widgets and these have a downfall as I have to observe the change of states and rebuild widgets. Flutter is fast, but we should be smart about what we ask Flutter to rebuild! The smartest way to solve this problem is by using state management tools like Bloc, Provider, and Momentum but today I would like to write how we can use Redux to manage states in our flutter application. While Redux is mostly used as a state management tool with React I found it quite easy to apply it in flutter projects I have contributed to so far. With redux & flutter_redux we can use Redux in our flutter applications, so the state of our application is kept in a store, and each widget can access any state that it needs from this store. StoreProvider- The base Widget. It will pass the given Redux Store to all descendants that request it. StoreBuilder- A descendant Widget that gets the Store from a StoreProvider and passes it to a Widget builder function. StoreConnector- A descendant Widget that gets the Store from the nearest StoreProviderancestor, converts the Storeinto a ViewModelwith the given converter function, and passes the ViewModelto a builder function. Any time the Store emits a change event, the Widget will automatically be rebuilt. No need to manage subscriptions! the main function or inside a // State object. This works better with Hot Reload than creating it directly // in the `build` function. final store = Store<int>(counterReducer, initialState: 0); runApp(FlutterReduxApp( title: 'Flutter Redux Demo', store: store, )); } class FlutterReduxApp extends StatelessWidget { final Store<int> store; final String title; FlutterReduxApp({Key key, this.store, this.title}) : super(key: key); Widget build(BuildContext context) { // The StoreProvider should wrap your MaterialApp or WidgetsApp. This will // ensure all routes have access to the store. return StoreProvider<int>( // Pass the store to the StoreProvider. Any ancestor `StoreConnector` // Widgets will find and use this value as the `Store`. store: store, child: MaterialApp( theme: ThemeData.dark(), title: title, home: Scaffold( appBar: AppBar( title: Text(title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center,! StoreConnector<int, String>( converter: (store) => store.state.toString(), builder: (context, count) { return Text( 'The button has been pushed this many times: $count', style: Theme.of(context).textTheme.display1, ); }, ) ], ), ), // Connect the Store to a FloatingActionButton. In this case, we'll // use the Store to build a callback that will dispatch an Increment // Action. // // Then, we'll pass this callback to the button's `onPressed` handler. floatingActionButton: StoreConnector<int, VoidCallback>( converter: (store) { // Return a `VoidCallback`, which is a fancy name for a function // with no parameters and no return value. // It only dispatches an Increment action. return () => store.dispatch(Actions.Increment); }, builder: (context, callback) { return FloatingActionButton( // Attach the `callback` to the `onPressed` attribute onPressed: callback, tooltip: 'Increment', child: Icon(Icons.add), ); }, ), ), ), ); } } NB: I wrote this article assuming that you have some experience with React-redux and you understand how actions, reducers, and dispatchers work in react-redux. Thank you for reading, and let's connect! Thank you for reading my blog. Feel free to subscribe to connect on Twitter
https://loktioncode.hashnode.dev/flutter-state-management-with-redux
CC-MAIN-2022-05
refinedweb
566
55.54
This. If you are looking for something else, try the advanced HTML> <li> the second list item <ul> <li>first nested item</li> <li>second nested item</li> </ul> </li> </body> </html> Note HTML 4.0 defines ™ for the trademark sign but this is not yet as widely supported as ™ There are a number of other entities you may find useful: em dash — — And then, there are entities for accented characters and miscellaneous symbols in the Latin-1 character set:   Ð Ð Ð ¡ ¡ ¡ Ñ Ñ Ñ ¢ ¢ ¢ Ò Ò Ò £ £ £ Ó Ó Ó ¤ ¤ ¤ Ô Ô Ô ¥ ¥ ¥ Õ Õ Õ ¦ ¦ ¦ Ö Ö Ö § § § × × × ¨ ¨ ¨ Ø Ø Ø © © © Ù Ù Ù ª ª ª Ú Ú Ú « « « Û Û Û ¬ ¬ ¬ Ü Ü Ü ­ ­ Ý Ý Ý ® ® ® Þ Þ Þ ¯ ¯ ¯ ß ß ß ° ° ° à à à ± ± ± á á á ² ² ² â â â ³ ³ ³ ã ã ã ´ ´ ´ ä ä ä µ µ µ å å å ¶ ¶ ¶ æ æ æ · · · ç ç ç ¸ ¸ ¸ è è è ¹ ¹ ¹ é é é º º º ê ê ê » » » ë ë ë ¼ ¼ ¼ ì ì ì ½ ½ ½ í í í ¾ ¾ ¾ î î î ¿ ¿ ¿ ï ï ï À À À ð ð ð Á Á Á ñ ñ ñ Â Â Â ò ò ò Ã Ã Ã ó ó ó Ä Ä Ä ô ô ô Å Å Å õ õ õ Æ Æ Æ ö ö ö Ç Ç Ç ÷ ÷ ÷ È È È ø ø ø É É É ù ù ù Ê Ê Ê ú ú ú Ë Ë Ë û û û Ì Ì Ì ü ü ü Í Í Í ý ý ý Î Î Î þ þ þ Ï Ï Ï ÿ ÿ ÿ. Linking into the middle of Web pages! Preformatted Text> Year Sales 2000 $18M 2001 $25M 2002 $36M Cell Spacing By contrast the cellspacing attribute sets the space between the cells. Setting the cell spacing to 10: <table border="1" cellpadding="10" cellspacing="10"> has the effect: Year Sales 2000 $18M 2001 $25M 2002 $36M Table Width: Year Sales 2000 $18M 2001 $25M 2002 $36M Text Alignment within Cells: Year Sales 2000 $18M 2001 $25M 2002 $36M. Empty Cells One quirk is the way browsers deal with empty cells, compare: Year Sales 2000 $18M 2001 $25M 2002 $36M 2003 with Year Sales 2000 $18M 2001 $25M 2002 Sales Year North South Total. Borderless tables These are commonly used for laying out pages in a gridded fashion. All you need to do is to add border="0" and cellspacing="0" to the table element: Year Sales 2000 $18M 2001 $25M 2002 $36M Year Sales 2000 $18M 2001 $25M 2002 $36M Year Sales 2000 $18M 2001 $25M Year Sales 2000 $18M 2001 $25M"> Specifying the relation between header and data cells: • row: The current cell provides header information for the rest of the row that contains it. • col: The current cell provides header information for the rest of the column that contains it.> ... function cycleAds() { if (document.images) { if (document.adBanner.complete) { if (++thisAd == adImages.length) thisAd = 0; document.adBanner.src = adImages[thisAd]; } } function gotoAd() { document.location.href = "http://" + adURLs[thisAd]; } </script> </head> <body onload="cycleAds()"> ... Chapter 2 CSS This is chapter 2 of the book Cascading Style Sheets, designing for the Web, by Håkon Wium Lie and Bert Bos (2nd edition, 1999, Addison Wesley, ISBN 0-201-59625-3) As we explained in the previous chapter, HTML elements enable Web page designers to mark up a document as to its structure. The HTML specification lists guidelines on how browsers should display these elements. For example, you can be reasonably sure that the contents of a strong element will be displayed bold-faced. the designer in the driver's seat. We devote much of the rest of this book to explaining what you can do with CSS. In this chapter, we begin by introducing you to the basics of how to write style sheets and how CSS and HTML work together to describe both the structure and appearance of your document. Rules and Style Sheets To start using CSS, you don't even have to write style sheets. Chapter 16 will tell you how to point to existing style sheets on the Web. There are two ways to create CSSs. You can either use a normal text editor and write the style sheets "by hand," or you can use a dedicated tool - for example a Web page design application - which supports CSS. The dedicated tools allow you to create style sheets without learning the syntax of the CSS language. However, in many cases the designer will want to tweak the style sheet by hand afterwards, so we recommend that you learn to write and edit CSSs by hand. Let's get started! H1 { color: green } What you see above is a simple CSS rule that contains one rule. A rule is a statement about one stylistic aspect of one or more elements. A style sheet is a set of one or more rules that apply to an HTML document. The rule above sets the color of all first-level headings (h1). Let's take a quick look at what the visual result of the rule could be: Figure 2.1 The selector is the link between the HTML document and the style. It specifies what elements are affected by the declaration. The declaration is that part of the rule that sets forth what the effect will be. In the example above, the selector is h1 and the declaration is "color: green." Hence, all h1 elements will be affected by the declaration, that is, they will be turned green. (The color property just affects the foreground text color, there are other properties for background, border, etc.) The above selector is based on the type of the element: it selects all elements of type "h1." This kind of selector is called type selector. Any HTML element type can be used as a type selector. Type selectors are the simplest kind of selectors. We discuss other kinds of selectors in See CSS selectors. , "CSS selectors." Anatomy of a declaration A declaration has two parts separated by a colon: • Property - that part before the colon • Value - that part after the colon The property is a quality or characteristic that something possesses. In the previous example, it is color. CSS2 (see separate box) defines around 120 properties and we can assign values to all of them. CSS specifications Cascading Style Sheets is formally described in two specifications from W3C: CSS1 and CSS2. CSS1 was issued in December 1996 and describes a simple formatting model mostly for screen-based presentations. CSS1 has around 50 properties (for example color and font-size). CSS2 was finalized in May 1998 and builds on CSS1. CSS2 includes all CSS1 properties and adds around 70 of its own, such as properties to describe aural presentations and page breaks. In this book we do not try to distinguish between CSS1 and CSS2 and use the term "CSS" unless the distinction is important. Most features described in the first four chapters are part of CSS1. If you would like to read the CSS specifications themselves, you can find them from: The value is a precise specification of the property. In the example, it is "green," but it could just as easily be blue, red, yellow, or some other color. The diagram below shows all ingredients of a rule. The curly braces ({ }) and colon (:) make it possible for the browser to distinguish between the selector, property, and value. Figure 2.2 Diagram of a rule. All three rules have exactly the same declaration - they set the font to be bold. (This is done using the font-weight property, which we discuss in See Fonts. .) Since all three declarations are identical, we can group the selectors into a comma-separated list and only list the declaration once, like this: H1, H2, H3 { font-style: bold } be green and to be centered on the canvas. (This is done using the text-align property, discussed in Chapter 5 .) But we can achieve the same effect faster by grouping the declarations that relate to the same selector into a semicolon-separated list, like this: H1 { color: green;. In order for the style sheet to have any effect you have to "glue" your style sheet to your HTML document. "Gluing" Style Sheets to the Document For any style sheet to affect the HTML document, it must be "glued" to the document. That is, the style sheet and the HTML document must be combined so that they can work together to present the document. This can be done in any of four ways: 1. Apply the basic, document-wide style sheet for the document by using the style element. 2. Apply a style sheet to an individual element using the style attribute. 3. Link an external style sheet to the document using the link element. 4. Import a style sheet using the CSS @import notation. In the next section, we discuss the first method: using the style element. We discuss using the style attribute in Chapter 4 , "CSS selectors," and using the link element and the @import notation in Chapter 16 , "External style sheets." Gluing by using the STYLE element You can glue the style sheet and.3 . <HTML> <TITLE>Bach's home page</TITLE> <STYLE> H1, H2 { color: green } <2>Historical perspective</H2> <P>Bach composed in what has been referred to as the Baroque period. </BODY> </HTML> Figure 2.3 The result of adding to a style sheet a rule to turn h1s green and then gluing the style sheet to the document using the style elements. (try it): green }" displayed on your screen; you see instead two h1 elements colored green. No rules have been added that affect any of the other elements, so those elements appear in the browser's default color. Browsers and CSS For an updated overview of available browsers, see the W3C overview page For CSS to work as described in this book, you must use a CSS-enhanced browser, that is, a browser that supports CSS. A CSS-enhanced browser will recognize the style element as a container for a style sheet and present the document accordingly. Most browsers that are distributed today support CSS, for example Microsoft Internet Explorer 4 (IE4), Netscape Navigator 4 (NS4) and Opera 3.5 (O3.5). Conservative estimates indicate that more than half the people on the Web use a CSS-enhanced browser, and the figures are steadily rising. Chances are that the people you communicate with have CSS-enhanced browsers. If not, give them a reason to upgrade! The best source for information on how different browsers support CSS is WebReview's charts Alas, not all CSS implementations are perfect. When you start experimenting with style sheets, you will soon notice that each browser comes with a set of bugs and limitations. In general, newer browsers behave better than older ones. IE4 and O3.5 are among the best, and Netscape's next offering - code-named Gecko - also promises much improved support for CSS. Those who don't use CSS-enhanced browsers can still read pages that use style sheets. CSS was carefully designed so that all content should remain visible even if the browser knows nothing about CSS. Some browsers, such as Netscape's Navigator version 2 and 3 don't support style sheets but they know enough about the style element to fully ignore it. Next to supporting style sheets, this is the correct behavior. However, other browsers that do not know the style element, such as Netscape's Navigator 1 and Microsoft Internet Explorer 2, will ignore the style tags but display the content of the style element. Thus, the user will end up with the style sheet printed on the top of the canvas. At the time of writing, only a few percent: green } --> </STYLE> <BODY> .. </BODY> </HTML> CSS also has its own set of comments that you can use within the style sheet. A CSS comment begins with "/*" and ends with "*/." (Those familiar with the C programming language will recognize these.) CSS rules inside a CSS comment will not have any effect on the presentation of the document. The browser also needs to be told that you are working with CSS style sheets. CSS is currently the only style sheet language in use with HTML documents and we don't expect this to change. For XML the situation might be different. But just as there is more than one image format (GIF, JPEG and PNG come to mind), there could be more than one style sheet language. So it's a good habit to tell browsers that they are dealing with CSS. (In fact, HTML requires you to.) This is done with the type attribute of the style element. The value of type indicates what type of style sheet is being used. For CSS, that value is "text/css." The following is an excerpt from our previous sample document that shows you how you would write this (in combination with the use of the HTML comment): <HTML> <TITLE>Bach's home page</TITLE> <STYLE TYPE="text/css"> <!-- H1 { color: green } --> </STYLE> <BODY> .. </BODY> </HTML> When the browser loads a document, it checks to see if it understands the style sheet language. If it does, it will try to read the sheet, otherwise it will ignore it. The type attribute (see Chapter 1 for a discussion on HTML attributes) on the style element is a way to let the browser know which style sheet language is being used. The type attribute must be included. as: Through inheritance, CSS property values set on one element will be transferred down the tree to its descendants. For example, our examples have up to now set the color to be green for h1 and h2 elements. Now, say, you would like to set the same color on all elements in your document. You could do this by listing all element types in the selector: <STYLE TYPE="text/css"> H1, H2, P, LI { color: green } </STYLE> However, most HTML documents are more complex than our sample document, and your style sheet would soon get long. There is a better - and shorter - way. Instead of setting the style on each element type, we set it on their common ancestor, the body element: <STYLE TYPE="text/css"> BODY { color: green } </STYLE> Since other elements inherit properties from the body element, they will all inherit the color green (Figure 2.4 ). Figure 2.4 The result of inheritance. (try it) As you have seen above, inheritance is a transport vehicle that will distribute stylistic properties to descendants of an element. Since the body element is a common ancestor for all visible elements, body is a convenient selector when you want to set stylistic rules for the entire document. Overriding Inheritance In the previous example, all elements were given the same color through inheritance. Sometimes, however, children don't look like their parents. Not surprisingly, CSS also accounts for this. Say you would like for h1 elements to be blue while the rest should be green. This is easily expressed in CSS: <STYLE TYPE="text/css"> BODY { color: green } H1 { color: navy } </STYLE> Since h1 is a child element of body : The reason why the second rule wins is that it is more specific than the first. The first rule is very general - it affects all elements on the canvas. The second rule only affects h1 elements in the document: navy } BODY { color: green } </STYLE> CSS has been designed to resolve conflicts between style sheet rules like the one above. Specificity is one aspect of that. You can find the details in Chapter 15 , "Cascading and inheritance." Properties that don't inherit As a general rule, properties in CSS inherit from parent to child elements as described in the previous examples. Some properties, however, don't inherit and there is always a good reason why. We will use the background property (described in Chapter 11)) white; color: black; } </STYLE> <BODY> <H1>Bach's <EM>home</EM> page</H1> <P>Johann Sebastian Bach was a prolific composer. </BODY> </HTML> The background property has a URL ("texture.gif") that points to a background image as value. When the image is loaded, the canvas looks like: There are a few noteworthy things in the above example: • The background image covers the surface like a wallpaper - also the backgrounds of the h1 and p element have been covered. This is not due to inheritance, but to the fact that unless otherwise set, all backgrounds are transparent. So, since we haven't set the backgrounds of the h1 or p element to something else, the parent element, body, will shine through. • In addition to the URL of the image, a color (white) has also been specified as the background. In case the image can't be found, you will see the color instead. • The color of the body element has been set to black. To ensure contrast between the text and the background, it is a good habit to always set a color when the background property is set. So, exactly why doesn't the background property inherit? Visually, the effect of transparency is similar to inheritance: it looks like all elements have the same backgrounds. There are two reasons: first, transparent backgrounds are faster to display (there is nothing to display!) than other backgrounds. Second, since background images are aligned relative to the element they belong to, you would otherwise not always end up with a smooth background surface. Common tasks with CSS Setting colors and backgrounds - as described above - are among the most common tasks performed by CSS. Other common tasks include setting fonts and white space around elements. This section gives you a guided tour of the most commonly used properties in CSS. Common tasks: fonts Let's start with fonts. If you have used desktop publishing applications in the past, you should be able to read this little style sheet: H1 { font: 36pt serif } The rule above sets the font for h1 elements. The first part of the value - 36pt - sets the font size to be 36 points. A "point" is an old typographic unit of measurement which has survived into the digital age. In the next chapter we will tell you why you should use the "em" unit instead of "pt" but for now we'll stick to points. The second part of the value - serif - tells the browser to use a font with serifs (the little hooks at the ends of the strokes, Chapter 5 will tell you all about them). The more decorated serif fonts suit Bach's home page well since the modern sans-serif fonts (fonts without serifs) weren't used in his time. Here is the result: The font property is a shorthand property for setting several other properties at once. By using it, you can shorten your style sheets and set values on all properties it replaces. If you choose to use the expanded version, you would have to set all of these to replace the example above: H1 { font-size: 36pt; font-family: serif; font-style: normal; font-weight: normal; font-variant: normal; line-height: normal; } Sometimes you only want to set one of these. For example, you may want to slant the text in some elements. Here is an example: UL { font-style: italic } The font-style property will not change the font size or the font family, it will only slant the existing font. When set on the ul element, the li elements inside will become slanted, since font-style is inherited. Here is the result when applied to the test page you know by now: (try it) Similarly, the font-weight property is used to change the weight - thickness - of the letters. You can further emphasize the list items by setting their ancestor to be bold: UL { font-style: italic; font-weight: bold; } Which yields: (try it) The last properties, font-variant and line-height, haven't been widely supported in browsers up to now and are therefore not as commonly used yet. Common tasks: margins Setting space around elements is a basic tool in typography. The headline above this paragraph has space above it and (slightly less) space below it. This paragraph, as printed in the book, has space on the left and (slightly less) on the right. CSS can be used to express how much space there should be around different kinds of elements. By default, your browser knows quite a bit about how to display the different kinds of elements in HTML. For example, it knows that lists and blockquote elements should be indented to set them apart from the rest of the text. As a designer, you can build on these settings while at the same time provide your own refinements. Let's use the blockquote element as an example. Here's a test document: <HTML> <TITLE>Fredrick the Great meets Bach</TITLE> <BODY> <P>One: <BLOCKQUOTE>"Gentlemen, old Bach is come." </BLOCKQUOTE> <P>The flute was now laid aside, and old Bach, who had alighted at his son's lodgings, was immediately summoned to the Palace. </BODY> </HTML> The screen-shot below is how a typical HTML browser would display the document: As you can see, the browser has added space on all sides of the quoted text. In CSS, this space is called "margins" and all elements have margins on all four sides. The properties are called: margin-top, margin-right, margin-bottom, and margin-left. You can change how the blockquote element is displayed by writing a little style sheet: BLOCKQUOTE { margin-top: 1em; margin-right: 0em; margin-bottom: 1em; margin-left: 0em; font-style: italic; } The "em" unit will be treated in detail in the next chapter, but we can already now reveal its secret: it scales relative to the font size. So, the above example will result in the vertical margins being as high as the font size (1em) of the blockquote, and horizontal margins having zero width. To make sure the quoted text can still be distinguished, it has been given an italic slant. The result is: Just like font is a shorthand property to set several font-related properties at once, margin is a shorthand property which sets all margin properties. The above example can therefore be written: BLOCKQUOTE { margin: 1em 0em 1em 0em; font-style: italic; } The first part of the value - 1em - is assigned to margin-top. From there it's clockwise: 0em is assigned to margin- right, 1em is assigned to margin-bottom, and 0em is assigned to margin-left. With the left margin set to zero, the quoted text needs more styling to set it apart from the rest of the text. Setting font- style to italic helps, and adding a background color further amplifies the quote: BLOCKQUOTE { margin: 1em 0em 1em 0em; font-style: italic; background: #EDB; } The result is: As expected, the background color behind the quote has changed. Unlike previous examples, the color was specified in red/green/blue (RGB) components. RGB colors are described in detail in Chapter 11 . One stylistic problem in the example above is that the background color barely covers the quoted text. The space around the quote - the margin area - does not use the element's background color. CSS has another kind of space, called padding, which uses the background color of the element. In other respects the padding properties are like the margin properties: they add space around an element. Let's add some padding to the quote: BLOCKQUOTE { margin: 1em 0em 1em 0em; font-style: italic; background: #EDB; padding: 0.5em; } The result of setting the padding is added space between the text and the rectangle that surrounds it: Notice that the padding property was only given one value (0.5em). Just like the margin property, padding could have taken 4 values which would have been assigned to the top, right, bottom and left padding respectively. However, when the same value is to be set on all sides, listing it once will suffice. This is true both for padding and margin (as well as some other border properties, which are described in See Space around boxes. ). Common tasks: links To make it easier for users to browse in hypertext documents, the links should have a style that distinguishes them from normal text. HTML browsers have often underlined hyperlink text. Also, various color schemes have been used to indicate if the user has previously visited the link or not. Since hyperlinks are such a fundamental part of the Web, CSS has special support for styling them. Here's a simple example: A:link { text-decoration: underline } The above example specifies that unvisited links should be underlined: The links are underlined, as we have specified, but they are also blue, which we have not. When authors do not specify all possible styles, browsers use default styles to fill in the gaps. The interaction between author styles, browser default styles and user styles (the user's own preferences) is another example of CSS's conflict resolution rules. It is called the cascade (the "C" of CSS). We will discuss the cascade below. The selector (A:link) deserves special mentioning. You probably recognize "A" as being an HTML element, but the last part is new. ":link" is one of several so-called pseudo-classes in CSS. Pseudo-classes are used to give style to elements based on information outside of the document itself. For example, the author of the document can't know if a certain link will be visited or not. Pseudo-classes are described in detail in Chapter 4, and we'll only give a few more examples here: A:visited { text-decoration: none } This rule gives style to visited links, just like A:link gave style to unvisited links. Here is a slightly more complex example: A:link, A:visited { text-decoration: none } A:hover { background: cyan } The last rule introduces a new pseudo-class :hover. Assuming the user is moving a pointing device (like a mouse), the specified style will be applied to the element when the user moves the pointer over ("hovers" over) the link. A common effect is to change the background color. Here is what it looks like: The :hover pseudo-class has an interesting history. It was introduced in CSS2 after the hover effect became popular among JavaScript programmers. The JavaScript solution requires complicated code compared to the CSS pseudo-class and this is an example of CSS picking up effects that have become popular among Web designers. A word about, because we realized that any single document could very likely end up with style sheets from multiple sources: the browser, the designer, and possibly the user. In the last set of examples you saw that the text color of the links turned blue without that being specified in the style sheet. Also, the browser knew how to format blockquote and h1 elements without being told so explicitly. Everything that the browser knows about formatting is stored in the browser's default style sheet and is merged with author and user style sheets when the document is displayed.. However, the user can say that a rule is very important and it will then override any author or browser styles. We go into details about cascading in Chapter 15, "Cascading and inheritance." Before that, there is much to learn about fonts, space and colors. CSS tutorial starting with HTML + CSS Contents • 1. The HTML • 2. Adding color • 3. Adding fonts • 4. A navigation bar • 5. Styling links • 6. Horizontal line • 7. External CSS • Further reading> <body> <!-- Sign and date the page, it's only polite! --> <address>Made 5 April 2004<br> by myself.</address> </body> </html> In fact, you don't have to type it: you can copy and paste it from this Web page into the editor. (If you are using TextEdit on the Mac, don't forget to tell TextEdit that the text is really plain text, by going to the Format menu and selecting “Make plain text”.) in there will be displayed, except for the the text inside <!-- and -->, which serves as a comment to ourselves. The browser will ignore it. Of the tags in the example, <ul> introduces an “Unordered List”, i.e., a list in which the items are not numbered. The <li> is the start of a “List Item.” The <p> is a “Paragraph.” And the <a> is an “Anchor,” which is what creates a hyperlink. If you want to know what the names in <…> mean, one good place to start is Getting started with HTML. But just a few words about the structure of our example HTML page. • The “ul” is a list with one hyperlink per item. This will serve as our “site navigation menu,” linking to the other pages of our (hypothetical) Web site. Presumably, all pages on our site have a similar menu. • The “h1” and “p” elements form the unique content of this page, while the signature at the bottom (“address”) will again be similar on all pages of the site. Note that I didn't close the “li” and “p” elements. In HTML (but not in XHTML), it is allowed to omit the </li> and </p> tags, which I did here, to make the text a little easier to read. But you may add them, if you prefer. Let's assume that this is going to be one page of a Web site with several similar pages. As is common for current Web pages, this one has a menu that links to other pages on the hypothetical site, some unique content and a signature. Now select “Save As…” from the File menu, navigate to a directory/folder where you want to put it (the Desktop is fine) and save the file as “mypage.html”. Don't close the editor yet, we will need it again. (If you are using TextEdit on Mac OS X before version 10.4, you will see an option Don't append the .txt extension in the Save as dialog. Select that option, because the name “mypage.html” already includes an extension. Newer versions of TextEdit will notice the .html extension automatically.) Next, open the file in a browser. You can do that as follows: find the file with your file manager (Windows Explorer, Finder or Konqueror) and click or double click the “mypage.html” file. It should open in your default Web browser. (If it does not, open your browser and drag the file to it.) As you can see, the page looks rather boring… Step 2: adding some colors You probably see some black text on a white background, but it depends on how the browser is configured. So one easy thing we can do to make the page more stylish is to add some colors. (Leave the browser open, we will use it again later.) for this step, we just keep everything in one file. We need to add a <style> element to the HTML file. The style sheet will be inside that element. So go back to the editor window and add the following five lines in the head part of the HTML file. The lines to add are shown in red (lines 5 to 9). <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <head> <title>My first styled page</title> <style type="text/css"> body { color: purple; background-color: #d8da3d } </style> </head> <body> [etc.] The first line says that this is a style sheet and that it is written in CSS (“text/css”). The second line says that we add style to the “body” element. The third line sets the color of the text to purple and the next line sets the background to a sort of greenish yellow. Style sheets in CSS are made up of rules. Each rule has three parts: 1. the selector (in the example: “body”), which tells the browser which part of the document is affected by the rule; 2. the property (in the example, 'color' and 'background-color' are both properties), which specifies what aspect of the layout is being set; 3. and the value ('purple' and '#d8da3d'), which gives the value for the style property. The example shows that rules can be combined. We have set two properties, so we could have made two separate rules: body { color: purple } body { background-color: #d8da3d } but since both rules affect the body, we only wrote “body” once and put the properties and values together. For more about selectors, see chapter 2 of Lie & Bos. The background of the body element will also be the background of the whole document. We haven't given any of the other elements (p, li, address…) any explicit background, so by default they will have none (or: will be transparent). The 'color' property sets the color of the text for the body element, but all other elements inside the body inherit that color, unless explicitly overridden. (We will add some other colors later.) Now save this file (use “Save” from the File menu) and go back to the browser window. If you press the “Reload” button, the display should change from the “boring” page to a colored (but still rather boring) page. Apart from the list of links at the top, the text should now be purple against a greenish yellow background. How one browser shows the page now that some colors have been added. Colors can be specified in CSS in several ways. This example shows two of them: by name (“purple”) and by hexadecimal code (“#d8da3d”). There are about 140 color names and the hexadecimal codes allow for over 16 million colors. Adding a touch of style explains more about these codes. Step 3: adding fonts Another thing that is easy to do is to make some distinction in the fonts for the various elements of the page. So let's set the text in the “Georgia” font, except for the h1 heading, which we'll give “Helvetica.” On the Web, you can never be sure what fonts your readers have on their computers, so we add some alternatives as well: if Georgia is not available, Times New Roman or Times are also fine, and if all else fails, the browser may use any other font with serifs. If Helvetica is absent, Geneva, Arial and SunSans-Regular are quite similar in shape, and if none of these work, the browser can choose any other font that is serif-less. In the text editor add the following lines (lines 7-8 and 11-13): <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <head> <title>My first styled page</title> <style type="text/css"> body { font-family: Georgia, "Times New Roman", Times, serif; color: purple; background-color: #d8da3d } h1 { font-family: Helvetica, Geneva, Arial, SunSans-Regular, sans-serif } </style> </head> <body> [etc.] If you save the file again and press “Reload” in the browser, there should now be different fonts for the heading and the other text. Now the main text has a different font from the heading. Step 4: adding a navigation bar The list at the top of the HTML page is meant to become a navigation menu. Many Web sites have some sort of menu along the top or on the side of the page and this page should have one as well. We will put it on the left side, because that is a little more interesting than at the top… The menu is already in the HTML page. It is the <ul> list at the top. The links in it don't work, since our “Web site” so far consists of only one page, but that doesn't matter now. On a real Web site, there should not be any broken links, of course. So we need to move the list to the left and move the rest of the text a little to the right, to make room for it. The CSS properties we use for that are 'padding-left' (to move the body text) and 'position', 'left' and 'top' (to move the menu). There are other ways to do it. If you look for “column” or “layout” on the Learning CSS page, you will find several ready-to-run templates. But this one is OK for our purposes. In the editor window, add the following lines to the HTML file (lines 7 and 12-16): < { position: absolute; top: 2em; left: 1em; width: 9em } h1 { font-family: Helvetica, Geneva, Arial, SunSans-Regular, sans-serif } </style> </head> <body> [etc.] If you save the file again and reload it in the browser, you should now have the list of links to the left of the main text. That already looks much more interesting, doesn't it? The main text has been moved over to the right and the list of links is now to the left of it, instead of above.. Step 5: Styling the links The navigation menu still looks like a list, instead of a menu. Let's add some style to it. We'll remove the list bullet and move the items to the left, to where the bullet was. We'll also give each item its own white background and a black square. (Why? No particular reason, just because we can.) We also haven't said what the colors of the links should be, so let's add that as well: blue for links that the user hasn't seen yet and purple for links already visited (lines 13-15 and 23-33): < } </style> </head> <body> [etc.] Traditionally, browsers show hyperlinks with underlines and with colors. Usually, the colors are similar to what we specificed here: blue for links to pages that you haven't visited yet (or visited a long time ago), purple for pages that you have already seen. In HTML, hyperlinks are created with <a> elements, so to specify the color, we need to add a style rule for “a”. To differentiate between visited and unvisited links, CSS provides two “pseudo-classes” (:link and :visited). They are called “pseudo-classes” to distinguish them from class attributes, that appear in the HTML directly, e.g., the class="navbar" in our example. Step 6: adding a horizontal line The final addition to the style sheet is a horizontal rule to separate the text from the signature at the bottom. We will use 'border-top' to add a dotted line above the <address> element (lines 34-37): < } </style> </head> <body> [etc.] Now our style is complete. Next, let's look at how we can put the style sheet in a separate file, so that other pages can share the same style. Step 7: putting the style sheet in a separate file We now have an HTML file with an embedded style sheet. But if our site grows we probably want many pages to share the same style. There is a better method than copying the style sheet into every page: if we put the style sheet in a separate file, all pages can point to it. To make a style sheet file, we need to create another empty text file. You can choose “New” from the File menu in the editor, to create an empty window. (If you are using TextEdit, don't forget to make it plain text again, using the Format Then cut and paste everything that is inside the <style> element from the HTML file into the new window. Don't copy the <style> and </style> themselves. They belong to HTML, not to CSS. In the new editor window, you should now have the complete style sheet: } Choose “Save As…” from the File menu, make sure that you are in the same directory/folder as the mypage.html file, and save the style sheet as “mystyle.css”. Now go back to the window with the HTML code. Remove everything from the <style> tag up to and including the </style> tag and replace it with a <link> element, as follows (line 5): <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <head> <title>My first styled page</title> <link rel="stylesheet" href="mystyle.css"> </head> <body> [etc.] This will tell the browser that the style sheet is found in the file called “mystyle.css” and since no directory is mentioned, the browser will look in the same directory where it found the HTML file. If you save the HTML file and reload it in the browser, you should see no change: the page is still styled the same way, but now the style comes from an external file. The final result The next step is to put both files, mypage.html and mystyle.css on your Web site. (Well, you might want to change them a bit first…) But how to do that depends on your Internet provider. Further reading For an introduction to CSS, see chapter 2 of Lie & Bos, or Dave Raggett's intro to CSS. Other information, including more tutorials, can be found on the learning CSS page. 1. Introduction XHTML Modularization provides a structure for the creation of new markup languages through the extension of the XHTML Core modules and the use of the XHTML Module Framework. In some instances, people will want to create complete, proprietary markup languages through these mechanisms. In other instances, people may wish to create new, reusable modules that will be used by their organization or by others in the definition of markup languages. In either case, the mechanics of the modules added and the markup language definition are the same. This document describes the manner in which such modules are defined, and the way in which modules should be combined to create new markup languages. 2. Terminology Markup Language A grammar (in this case, an XML grammar) that can be used to structure information. Once structured, the information can be processed in the context of the markup language. Such processing might include presentation to a user, extraction of key information, transformation into other forms, etc. Hybrid Markup Language A Markup Language that is made up of Modules from multiple Namespaces. Namespace A namespace is a collection of names that are delimited in some way. An XML Namespace is a W3C-defined mechanism for delimiting XML elements and attributes. XHTML-defined modules are all in the XHTML Namespace. XHTML-family modules are required to be in their own XML Namespace. XHTML Modularization defines a mechanism for declaring the XML Namespace of a module in a way that is compatible with XML DTDs and permits XML Validation of XHTML-family documents. XML Validation The XML Recommendation defines validation ensuring that a document is well-formed and that it conforms to the content model defined in the document's associated DTD. XHTML family documents are required to be XML Valid. Module In XHTML, a module is a collection of one or more files that define entities, elements, and/or attributes. A module may represent a complete, stand-alone markup language. It may also represent a small, incremental change to some other markup language or some other module. Regardless, modules can be combined with other modules using the XHTML Framework. With care, the elements defined by these modules can be combined into a complete content model for a markup language. DTD DTD is a grammar in which XML-based markup languages can be defined (there are others, but right now we are talking about DTDs). It is also a term commonly used to refer to the file in which a markup language definition can be found. In the context of XHTML Modules and Markup Languages, a DTD is actually a file that includes the XHTML-family modules that make up the markup language (along with some other helper files). In DTD parlance, this file can also be called a "DTD Driver" file. Qualified Name The combination of XML and XML Namespaces gives rise to a class of elements and attributes that have "qualified names". A qualified name consists of the element or attribute name, possibly prefixed with a namespace declarator (e.g. xhtml:p for paragraph). In XHTML, the qualified names for elements and attributes are defined in a Qname Module. 3. Module Construction XHTML Modules are made up of at least two modules - a Qname Module and a Declaration Module. In this section we will walk through building each of these. In the next section we will use this new module with another XHTML- family module and some XHTML Core modules to define a new markup language. 3.1. Defining the Qname Module An XHTML Qname Module should be constructed using the following process: 1. Define a parameter entity MODULE.prefixed that announces whether the elements in the module are being used with XML Namespace prefixed names or not. This parameter entity's default value should be "%NS.prefixed;". The NS.prefixed parameter entity is defined by the XHTML framework to be IGNORE by default, and can be used in a document instance to switch on prefixing for all included namespaces (see the prefixing example for more on this). 2. Define a parameter entity MODULE.xmlns that contains the namespace identifier for this module. 3. Define a parameter entity MODULE.prefix that contains the default prefix string to use when prefixing is enabled. 4. Define a parameter entity MODULE.pfx that is "%MODULE.prefix;:" when prefixing is enabled, and "" when it is not. 5. Define a parameter entity MODULE.xmlns.extra.attrib that contains the declaration of any XML Namespace attributes for namespaces referenced by this module (e.g., xmlns:xlink). When %MODULE.prefix is set to INCLUDE, this attribute should include the xmlns:%MODULE.pfx; declaration as well. 6. For each of the elements defined by the module, create a parameter entity of the form "MODULE.NAME.qname" to hold its qualified name. The value for this parameter entity must be "%MODULE.pfx;NAME". In this way, the parsed value will be "PREFIX:NAME" when prefixes are enabled, and "NAME" otherwise. For example: <!ENTITY % MODULE.myelement.qname "%MODULE.pfx;myelement" > If the module adds attributes to elements defined in modules that do not share the namespace of this module, declare those attributes so that they use the %MODULE.pfx prefix. For example: <ENTITY % MODULE.img.myattr.qname "%MODULE.pfx;myattr" > 4. DTD Construction Once you have defined your module(s), you are going to want to combine them with XHTML and other modules to create a new markup language. Since in this document we are talking about building these markup languages using DTDs, what you need to do is define a DTD that reflects the markup language. In the remainder of this section, we will explore the process for creating such a "hybrid markup language". 4.1. Define the Content Model as a 'Model Module' A Model Module is an XHTML Module that defines the content model for your new markup language. This module can be extremely complex, or it can be as simple as the declaration of a parameter entity and the inclusion of some other Model Module. Regardless, the purpose is the same: Define the structure of all of the elements in your markup language. 4.2. Define the qualified names collection Your markup language may include one or more additional XHTML-family Modules. Each of these Modules will have a Qname Module. The qualified names collection is a module in which all of the Qname Modules are instantiated, and the set of prefixed attributes are defined. Specifically, a qualified names collection module contains: 1. A reference to the Qname Module of each non-XHTML module included 2. A definition of the parameter entity XHTML.xmlns.extra.attrib to be the collection of the MODULE.xmlns.extra.attrib parameter entities, one from each included Module. 4.3. Define the Driver The driver is the actual file that is referenced by documents written in your new markup language. The driver may be complex or simple, depending upon the markup language. However, each XHTML-family markup language driver must contain the following elements in order to work well: 1. A definition of the parameter entity XHTML.version. This should be set to the Formal Public Identifier for your new markup language. 2. A definition of the parameter entity xhtml-qname-extra.mod. This must be set to the qualified names collection module defined above. It is fine to have this as only a SYSTEM identifier, since it is internal to the DTD. 3. A definition of the parameter entity xhtml-model.mod. This must be set to the Model Module defined above. It is fine to also have this as only a SYSTEM identified, since it is internal to the DTD. 4. A series of references to the modules that make up the DTD. This may be a reference to another DTD that you are incrementally modifying, or it may be an explicit list of the XHTML Modules that are being included, or some combination of the two. Regardless, the first thing that actually gets instantiated through this reference is the XHTML Modularization Framework Module. This Module takes care of incorporating all of the XHTML infrastructure, merging it with your specified qualified names and your content model via the parameter entities defined in steps 2 and 3. Don't forget to include your new Declaration Modules, since that is where your new markup languages elements and attributes are defined! Now you are ready to go. Your new Markup Language, defined via a DTD, can be referenced in the DOCTYPE declaration of a document, and that document can be validated against your new DTD using common commercial and free-ware tools. 5. Module Examples In the following sections, you will see examples of each type of module referred to in this document, as well as the components that make up two different markup language definitions. 5.1. Qname Modules This first qname module is for an inventory module. The second is for some extensions to the inventory module. 5.1.1. Inventory Qname Module <!-- ...................................................................... --> <!-- Inventory Qname Module ................................................... --> <!-- file: inventory-qname-1.mod xmlns:inventory="" ...................................................................... --> <!-- Declare the default value for prefixing of this module's elements --> <!-- Note that the NS.prefixed will get overridden by the XHTML Framework or by a document instance. --> <!ENTITY % NS.prefixed "IGNORE" > <!ENTITY % Inventory.prefixed "%NS.prefixed;" > <!-- Declare the prefix and any prefixed namespaces that are required by this module --> <![%Inventory.prefixed;[ <!ENTITY % Inventory.pfx "%Inventory.prefix;:" > <!ENTITY % Inventory.xmlns.extra.attrib "xmlns:%Inventory.prefix; %URI.datatype; #FIXED '%Inventory.xmlns;'" > ]]> <!ENTITY % Inventory.pfx "" > <!ENTITY % Inventory.xmlns.extra.attrib "" > xmlns:invext="" ...................................................................... --> <!-- Declare the default value for prefixing of this module's elements --> <!-- Note that the NS.prefixed will get overridden by the XHTML Framework or by a document instance. --> <!ENTITY % NS.prefixed "IGNORE" > <!ENTITY % Extension.prefixed "%NS.prefixed;" > <!-- Declare the prefix and any prefixed namespaces that are required by this module --> <![%Extension.prefixed;[ <!ENTITY % Extension.pfx "%Extension.prefix;:" > <!ENTITY % Extension.xmlns.extra.attrib "xmlns:%Extension.prefix; %URI.datatype; #FIXED '%Extension.xmlns;'" > ]]> <!ENTITY % Extension.pfx "" > <!ENTITY % Extension.xmlns.extra.attrib "" > xmlns:inventory="" ...................................................................... --> item sku desc price <!ELEMENT %Inventory.shelf.qname; ( %Inventory.item.qname; )* > <!ATTLIST %Inventory.shelf.qname; location CDATA #IMPLIED %Inventory.xmlns.attrib; > <!ELEMENT %Inventory.item.qname; ( %Inventory.desc.qname;, %Inventory.sku.qname;, %Inventory.price.qname;) > <!ATTLIST %Inventory.item.qname; location CDATA #IMPLIED %Inventory.xmlns.attrib; > SYSTEM "extension-1.mod" xmlns:invext="" ...................................................................... --> store aisle <!ELEMENT %Extension.store.qname; ( %Extension.aisle.qname; )* > <!ATTLIST %Extension.store.qname; name CDATA #IMPLIED %Extension.xmlns.attrib; > <!ELEMENT %Extension.aisle.qname; ( %Inventory.shelf.qname; )* > <!ATTLIST %Extension.aisle.qname; number CDATA #IMPLIED %Extension.xmlns.attrib; > SYSTEM "xhtml-invext-model-1.mod" ...................................................................... --> <!ENTITY % HeadOpts.mix "( %meta % Heading.class "%h1.qname; | %h2.qname; | %h3.qname; | %h4.qname; | %h5.qname; | %h6.qname;" > <!ENTITY % Blkphras.class "| %pre.qname; | %blockquote.qname; | %address.qname;" > xmlns:inventory="" <!-- Define the Content Model for the framework to use --> <!ENTITY % xhtml-model.mod SYSTEM "xhtml-invext-model-1.mod" > 7. Usage Examples 7.1. XHTML-Inventory with no prefixes This example uses the new markup language in its default form - with no prefixes being defined for any module. <!DOCTYPE html SYSTEM "xhtml-invext-1.dtd" > <html xmlns="" > <head> <title>An example using defaults</title> </head> <body> <p>This is content in the XHTML namespace</p> <shelf> <item> <desc> this is a description. </desc> <sku> this is the price. </sku> <price> this is the price. </price> </item> </shelf> </body> </html> Top of Form Bottom of Form While the most common scripting language ECMAscript (more widely known as JavaScript) is developed by Ecma, a great many of the APIs made available in browsers have been defined at W3C. What is scripting?. What scripting interfaces are available ?: • XMLHttpRequest makes it possible to load additional content from the Web without loading a new document, a core component of AJAX, • the Geolocation API makes the user’s current location available to browser-based applications, • several APIs make the integration of Web applications with the local file system and storage seamless. WAI ARIA offers mechanisms to ensure that this additional interactivity remains usable independent of devices and disabilities. Additional considerations apply to the development of Web applications for mobile devices. Beyond scripting; } Top of Form 255 #FFFFFF green: 255 blue: Bottom of Form Internationalization Quicktips Use Unicode wherever possible for content, databases, etc. Always declare the encoding of content.. Give me more background Character encodings for beginners explains some of the basic concepts about character encodings, and why you should care. Introducing Character sets and Encodings gives an gentle introduction to various aspects of the topic. So, how do I do this? HTML & CSS authors • Spec developers• Server setup Use characters rather than escapes (e.g. á á or á) whenever you can.. Give me more background Using character entities and NCRs provides additional information about the use of escapes in markup languages. In particular, note that entities (such as á) should be used with caution. So, how do I do this? HTML & CSS authors • Spec developers • SVG authors Declare the language of documents and indicate internal language changes. Information about the (human) language of content is already important for accessibility, styling, searching, editing, and other reasons. As more and more content is tagged and tagged correctly, applications that can detect language information will become more and more useful and pervasive. When declaring language, you may need to express information about a specific range of content in a different way from metadata about the document as a whole. It is important to understand this distinction. Give me more background Language on the Web gives an gentle introduction to various aspects of the topic. So, how do I do this? HTML & CSS authors • SVG authors • XML authors • Schema developers • Server setup Use style sheets for presentational information. Restrict markup to semantics.. Give me more background Read the talks slides from the 2007 @media conference presentation "Designing for International Users: Practical Tips". Check for translatability and inappropriate cultural bias in images, animations & examples.. Give me more background Read the talks slides from the 2007 @media conference presentation "Designing for International Users: Practical Tips". Use an appropriate encoding on both form and server. Support local formats of names/addresses, times/dates, etc.. So, how do I do this? HTML & CSS authors • HTML & CSS authors • Spec developers Use simple, concise text. Use care when composing sentences from multiple strings.. So, how do I do this? HTML & CSS authors On each page include clearly visible navigation to localized pages or sites, using the target language.'. So, how do I do this? HTML & CSS authors For XHTML, add dir="rtl" to the html tag for right-to-left text. Only re-use it to change the base direction. sets a base direction for the document which. Give me more background Creating (X)HTML Pages in Arabic & Hebrew provides a gentle introduction to the basics of handling right- to-left text in HTML. The principles are similar for other markup languages. What you need to know about the bidi algorithm and inline markup provides a gentle introduction to the basics of handling inline bidirectional text. So, how do I do this? HTML & CSS authors • SVG authors • XML authors • Schema developers Validate! Use techniques, tutorials, and articles at Accessibility: WCAG2. technologies.. To join the XHTML2 Working Group, see the instructions for joining. To enquire about the possibility of joining as an invited expert, please contact the HTML Activity Lead.: •. • Each applicable Recommendation will include fixed, unchanging versions of those implementations within the formal dated location for the Recommendation (/TR/YYYY/REC-whatever-YYYYmmdd/...). •. •: • The external interface to the module cannot change in any way that would break another module or markup language, either within or outside of the W3C. •. • XHTML 1.0 Strict - Use this when you want really clean structural mark-up, free of any markup associated with layout. Use this together with W3C's Cascading Style Sheet language (CSS) to get the font, color, and layout effects you want. •. •". The XML Events module defined in this specification provides XML languages with the ability to uniformly integrate event listeners and associated event handlers with Document Object Model (DOM) Level 2 event interfaces. The result is to provide an interoperable way of associating behaviors with document-level markup.: • RDFa • XForms • Access • Role • XML Events. Issue tracking There are two sets of issues being tracked: XHTML2 Issue Tracking System This database is dedicated to XHTML2 issues. Voyager Issue Tracking System This database contains issues for all other specs. Guidelines for authoring Here are some rough guidelines for HTML authors. If you use these, you are more likely to end up with pages that are easy to maintain, look acceptable to users regardless of the browser they are using, and can be accessed by the many Web users with disabilities. Meanwhile W3C have produced some more formal guidelines for authors. Have a look at the detailed Web Content Accessibility Guidelines 1.0. 1. A question of style sheets. For most people the look of a document - the color, the font, the margins - are as important as the textual content of the document. That way, not only is there a better chance of all browsers displaying your document properly, but also, if you want to change such things as the font or color, it's really simple to do so. See the Touch of style. 2. FONT tag considered harmful!. Yet some of these documents barely have a paragraph tag in sight! The problem comes when the content of pages needs to be updated, or given a new layout, or re-cast in XML (which is now to be the new mark-up language). With proper use of HTML, such operations are not difficult, but with a muddle of non-structural tags it's quite a different matter; maintenance tasks become impractical. To correct pages suffering from injudicious use of FONT, try the HTML Tidy program, which will do its best to put things right and generate better and more manageable HTML. 3. Make your pages readable by those with disabilities. The Web is a tremendously useful tool for the visually impaired or blind user, but bear in mind that these users rely on speech synthesizers or Braille readers to render the text. Sloppy mark-up, or mark-up which doesn't have the layout defined in a separate style sheet, is hard for such software to deal with. Wherever possible, use a style sheet for the presentational aspects of your pages, using HTML purely for structural mark-up. Also, remember to include descriptions with each image, and try to avoid server-side image maps. For tables, you should include a summary of the table's structure, and remember to associate table data with relevant headers. This will give non-visual browsers a chance to help orient people as they move from one cell to the next. For forms, remember to include labels for form fields. Do look at the accessibility guidelines for a more detailed account of how to make your Web pages really accessible. W3C Markup Validation Service To further promote the reliability and fidelity of communications on the Web, W3C has introduced the W3C Markup Validation Service at. Content providers can use this service to validate their Web pages against the HTML and XHTML Recommendations, thereby ensuring the maximum possible audience for their Web pages. It also supports XHTML Family document types such as XHTML+MathML and XHTML+MathML+SVG, and also other markup vocabularies such as SVG. Software developers who write HTML and XHTML editing tools can ensure interoperability with other Web software by verifying that the output of their tool complies with the W3C Recommendations for HTML and XHTML. HTML Tidy HTML Tidy is a stand-alone tool for checking and pretty-printing HTML that is in many cases able to fix up mark-up errors, and also offers a means to convert existing HTML content into well-formed XML, for delivery as XHTML. HTML Tidy was originally written by Dave Raggett, and it is now maintained as an open source project at SourceForge by a group of volunteers. There is an archived public mailing list html-tidy@w3.org. Please send bug reports / suggestions on HTML Tidy to this mailing list. Related W3C Work XML XML is the universal format for structured documents and data on the Web. It allows you to define your own mark-up formats when HTML is not a good fit. XML is being used increasingly for data; for instance, W3C's metadata format RDF. Style Sheets W3C's Cascading Style Sheets language (CSS) provides a simple means to style HTML pages, allowing you to control visual and aural characteristics; for instance, fonts, margins, line-spacing, borders, colors, layers and more. W3C is also working on a new style sheet language written in XML called XSL, which provides a means to transform XML documents into HTML. Document Object Model Provides ways for scripts to manipulate HTML using a set of methods and data types defined independently of particular programming languages or computer platforms. It forms the basis for dynamic effects in Web pages, but can also be exploited in HTML editors and other tools by extensions for manipulating HTML content. Internationalization HTML 4 provides a number of features for use with a wide variety of languages and writing systems. For instance, mixed language text, and right-to-left and mixed direction text. HTML 4 is formally based upon Unicode, but allows you to store and transmit documents in a variety of character encodings. Further work is envisaged for handling vertical text and phonetic annotations for Kanji (Ruby). Access for People with Disabilities HTML 4 includes many features for improved access by people with disabilities. W3C's Web Accessibility Initiative is working on providing effective guidelines for making your pages accessible to all, not just those using graphical browsers. XForms Forms are a very widely used feature in web pages. W3C is working on the design of the next generation of web forms with a view to separating the presentation, data and logic, as a means to allowing the same forms to be used with widely differing presentations. Mathematics Work on representing mathematics on the Web has focused on ways to handle the presentation of mathematical expressions and also the intended meaning. The MathML language is an application of XML, which, while not suited to hand-editing, is easy to process by machine. Handlers Offer an improved way to declare event listeners (eg. mouse and key events). Implementations Resources Allow you to load style-sheets and prefetch images, video, audio or any other content associated with the binding. <handlers>...</handlers> <resources>...</resources> </binding> </xbl> 1.6.2. The ‘binding‘ Property); } 1.6.3. Using the. 1.7.2.1. Event Filters> </handlers> There are several other filters that can be used. The following list is a subset of the available attributes for this purpose. These are expected to be the most commonly used filters because they cover the majority of mouse and keyboard event usage on the web today. button A space separated list of mouse buttons pressed by the user. e.g. button="0 2" matches either the left or right mouse buttons. click-count The number of times the user clicked. e.g. click-count="2" matches double clicks. text The text entered by the user. This is different from the key code because it matches the letter that was entered, regardless of the keys that were pressed. This is particularly important for languages that require several key presses to enter certain letters. modifiers key Matches against the keyIdentifier value defined in DOM 3 Events key-location For matching the location of the key that was pressed on the keyboard, including standard, left, right and numpad. 1.8. Templates. 1.8.1. Shadow Trees> </xbl> This will create the following shadow tree. Need a diagram 1.9. Implementing Interfaces. 1.10. Resources Resources include style sheets and additional files that are used by the binding, such as images, audio and video. The style sheets are used to add style to the binding’s template. This section is incomplete 1.11. Scripts> Fine Details Really for everyday use of events, that's all you need to know. There are however a few details that may occasionally come in useful. phase ("capture" | "default"*)> target.) propagate ("stop" | "continue"*). defaultAction ("cancel" | "perform"*).)
https://www.scribd.com/document/43741368/W3CRecommendations
CC-MAIN-2019-26
refinedweb
10,928
62.78
This question will be really annoying due to the fact it is for a class and we have a lot of restrictions on our code. The objective is to make a function to see if two lists (random ordered) have the same elements in them. So, if a=[2,5,4] b=[4,2,5] a==b true len() set() Is recursivity allowed ? That way, you don't have to modify existing lists in place. Obviously, not very efficient, but given your requirements this shouldn't really be an issue here... def are_items_equal(a, b): # First the guard clause: if the first list is empty, # return True if the second list is empty too, False otherwise if not a: return not b # There is now at least 1 item in list a # Perform a linear search in the b list to find a[0] # (could have used a "for" loop, but I assumed here this was # forbidden too) ib = 0; while ib < len(b): if a[0] == b[ib]: # At this point, we know that at index `ib` in list `b` # there is the same item as in `a[0]` # Both list match if the "rest" of those two lists match too # Check that by performing a recursive call to are_items_equal # (discarding the pair matched at this step) return are_items_equal(a[1:], b[:ib]+b[ib+1:]) ib += 1 # You only reach this point when `a[0]` was not found # in the `b` list. return False Testing: test_case = ( ([2,5,4], [4,2,5]), ([2, 2, 5, 4], [4, 5, 2, 5]), ([2,2,5,4], [4,2,5]), ([2,2,5,4],[4,2,5,2]), ) for a,b in test_case: print(are_items_equal(a, b), a, b) Producing: True [2, 5, 4] [4, 2, 5] False [2, 2, 5, 4] [4, 5, 2, 5] False [2, 2, 5, 4] [4, 2, 5] True [2, 2, 5, 4] [4, 2, 5, 2]
https://codedump.io/share/hfdJAlo4fT0A/1/how-to-make-a-function-which-tells-if-two-lists-are-equivalent-in-python
CC-MAIN-2017-51
refinedweb
322
56.15
[This is a preview of content found in the upcoming book, Dynamic Story Scripting with the ink Scripting Language, featured in Chapter 12 on the topic of procedural storytelling with ink + Unity.] Review of Storylets Storylets are an attractive narrative pattern for generating or managing dynamic narrative experience in interactive projects because they provide a way to pick the next available content to play next. Within such a system, there are three core aspects (Short, 2019): - Content. - Prerequisites. - Effect on state. Each storylet contains its content, what the prerequisites are for its availability, and how it effects the collection of values (state). Written out, this might appear as the following example: - Content: The princess escapes the tower. - Prerequisites: tower is in story; princess is in story; princess is in the tower - Effects: Tower is no longer in the story; princess is no longer in the tower In the above example, the storylet would become available to be used next in a story if its three prerequisites are met: the tower is in the story, the princess is in the story, and the princess is in the tower. Translated into pseudo-code, this same example might appear as the following (assuming story is an object containing properties tower, princess, and princess_in_tower): - Content: The princess escapes the tower - Prerequisites: story.tower == true && story.princess == true && story.princess_in_tower == true - Effects: story.tower = false; story.princess_in_tower = false Each ink story is a storylet ink does not provide a way to create complex data structures. That’s not its purpose. It is designed, and excels at, scripting narrative experiences. It is designed to provide tools to authors for creating branches of stories and managing how content is expressed to a user. However, when ink is used with Unity via the ink-Unity Integration plugin, this allows Unity to handle complex data in C# and allows ink to succeed at what it does best: scripting narratives. In ink, variables (created using the keyword VAR) and functions are global. This means they can be accessed by any connected code and, with variables, their values used in different places. With the application programming interface (API) provided by the ink-Unity Integration plugin, this means C# code can potentially access any variables in an ink story or call its functions to process a change or receive back some output. This effectively creates a bridge (via the API) where the ink story handles its internals, but exposes data to Unity. In storylet terms, this encapsulation of variables and functions within each ink story allows each be its own storylet. It has its own content and potentially changes values internally. However, as it comes to the last aspects of storylets, the effect on a state across multiple storylets, this poses a problem. How does an individual ink story let a data structure in C# know its values have changed? And, as a result of those changes, should the availability of an ink storylet also change? To start to address these issues requires understanding the ink-Unity Integration plugin provides an event-based interface for changes to variables following an observer model per ink story. Variables can be observed and, should their values change, a function will be notified. Using the API provided, each ink story can report its changes to a C# data structure in Unity: This begins to solve the first issue. As variables are changed, those changes are being saved to Unity, which now contains the state for the entire system. Immediately, this poses a new problem: how does an ink story know a global state value was changed? This requires knowing variables are global in ink and can be accessed by Unity via the API provided by the plugin. For each variable update reported by another story, all the other stories perform two checks and then potentially update their own value: - Do I have a variable by this name? - If so, is this new value reported by Unity different than its existing value? - If so, update the value reported from Unity internally! The first step in this process is important for a reason that may not be obvious. ink is a scripting language and, when run, variables either exist or they do not. Attempting to change the value of a variable that does not exist will cause an error in Unity! This means the first step is to check if the ink story contains the variable by its name. If it does, move to the next step. If no, move on to the next story. The second step in the above process flow prevents an endless loop from occurring. If it was not included, any variable update would trigger an endless chain of updates as individual update would trigger new updates across all stories until the project crashed. We need to make sure we are only ever overwriting a new value when it is different than the old one. In the new process, when a variable updates in one ink story, this triggers a check across all ink stories currently part of a collection. Each is then asked if it contains the variable and if its current value is different. If so, it updates: In the new process, Unity acts as an information exchange system between the various ink stories as part of a collection. When it detects a change in one story (via the event-based API), it relays the change to the other stories, potentially prompting them to update their values. Updates and Availability In the new system of waiting for events and relaying changes between stories, both the more global Unity state and individual ink stories are constantly synchronized with each other. Any one update to an observed variable changes all others using the same name in all other stories. However, there is one piece missing for the storylet set of aspects. How does Unity know if an individual ink story is available? How are its prerequisites expressed? Each storylet need only care about its own prerequisites. Translated into this system, each ink story would contain a function whose purpose is to report back a Boolean value. If the conditional expression is true, yes, the ink story is available. If not, no. In ink, this might look like the following example: VAR rose_relationship = 0 VAR geoff_relationship = 0 // Content here! == function available() ~ return (rose_relationship > 50 && geoff_relationship < 40) In the above code, the function available() compares the variables rose_relationship and geoff_relationship against its own prerequisites. If the conditional expression is true, based on the internal values as updated by Unity’s information exchange, the ink story is available for usage. Creating this simple function allows each ink story handle its own variables, story branching, and content. It need only contain a function for returning if it is available. All other work happens at the Unity level as it detects changes in variable values and updates other stories.
https://videlais.com/category/ink/page/3/
CC-MAIN-2022-21
refinedweb
1,150
61.67
Language in C Interview Questions and Answers Ques 51. How do I use function ecvt( ) in a program? Ans. The function ecvt( ) converts a floating-point value to a null terminated string. This function takes four arguments, such as, the value to be converted to string, the number of digits to be converted to string, and two integer pointers. The two-integer pointer stores the position of the decimal point (relative to the string) and the sign of the number, respectively. If the value in a variable, used to store sign is 0, then the number is positive and, if it is non-zero, then the number is negative. The function returns a pointer to the string containing digits. Following program demonstrates the use of this function. #include <stdlib.h> main( ) { char *str ; double val ; int dec, sign ; int ndig = 4 ; val = 22 ; str = ecvt ( val, ndig, &dec, &sign ) ; printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ; val = -345.67 ; ndig = 8 ; str = ecvt ( val, ndig, &dec, &sign ) ; printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ; // number with a scientific notation val = 3.546712e5 ; ndig = 5 ; str = ecvt ( val, ndig, &dec, &sign ) ; printf ( "string = %s dec = %d sign = %d\n", str, dec, sign ) ; } The output of this program would be string = 2200 dec = 2 sign = 0 string = 34567000 dec = 3 sign = 1 string = 35467 dec = 6 sign = 0 Ques 52. How to run DIR command programmatically? Ans. We can use the system( ) function to execute the DIR command along with its options. Following program shows how this can be achieved: // mydir.c main ( int argc, char *argv[ ] ) { char str[30] ; if ( argc < 2 ) exit ( 0 ) ; sprintf ( str, "dir %s %s", argv[1], argv[2] ) ; system ( str ) ; } If we run the executable file of this program at command prompt passing the command line arguments as follows: > mydir abc.c /s This will search the file 'abc.c' in the current directory. Ques 53. Suppose I have a structure having fields name, age, salary and have passed address of age to a function fun( ). How I can access the other member of the structure using the address of age? Ans. struct emp { char name[20] ; int age ; float salary ; } ; main( ) { struct emp e ; printf ( "\nEnter name: " ) ; scanf ( "%s", e.name ) ; printf ( "\nEnter age: " ) ; scanf ( "%d", &e.age ) ; printf ( "\nEnter salary: " ) ; scanf ( "%f", &e.salary ) ; fun ( &e.age ) ; } fun ( int *p ) { struct emp *q ; int offset ; offset = ( char * ) ( & ( ( struct emp * ) 0 ) -> age ) - ( char * ) ( ( struct emp* ) 0 ) ; q = ( struct emp * ) ( ( char * ) p - offset ) ; printf ( "\nname: %s", q -> name ) ; printf ( "\nage: %d", q -> age ) ; printf ( "\nsalary: %f", q -> salary ) ; } Ques 54. How to restrict the program's output to a specific screen region? Ans. A C function window( ) can be used to restrict the screen output to a specific region. The window( ) function defines a text-mode window. The parameters passed to this function defines the upper-left and lower-right corner of the region within which you want the output. In the following program, the string 'Hello!' gets printed within the specified region. To print the string we must use cprintf( ) function which prints directly on the text-mode window. #include <conio.h> main( ) { int i, j ; window ( 20, 8, 60, 17 ) ; for ( i = 0 ; i < 8 ; i++ ) for ( j = 0 ; j < 10 ; j++ ) cprintf ( "Hello!" ) ; } Ques 55. Sometimes you need to prompt the user for a password. When the user types in the password, the characters the user enters should not appear on the screen. A standard library function getpass( ) can be used to perform such function. Maximum number of characters that can be entered as password is 8. Ans. main( ) { char *pwd ; pwd = getpass ( "Enter Password" ) ; if ( strcmp ( pwd, "orgcity" ) ) printf ( "\nPassword %s is incorrect", pwd ) ; else printf ( "\nCorrect Password" ) ; }?
http://www.withoutbook.com/Technology.php?tech=11&page=11&subject=Interview%20Questions%20and%20Answers
CC-MAIN-2020-24
refinedweb
634
80.21
Ian Lynagh writes: > Some C libraries (curses is the one I have to hand) provide macros in > addition to functions in some cases for efficiency reasons. If you use > the FFI to import such a function thus: I was a bit confused by what Ian meant by this so, in case it helps others, here's an extract from curses.h. extern NCURSES_EXPORT(int) wstandend (WINDOW *); /* generated */ #define wstandend(win) (wattrset(win,A_NORMAL)) There seem to be a substantial number of these: $ grep generated /usr/include/curses.h | wc -l 117 As far as I can see, there is no conditional compilation to let you turn the macros off so you would have to write 117 individual #undefs, 117 stub functions or whatever.. For that reason I vote for: > Surrounding the function with parentheses so the macro doesn't match. > The offending line above would be > _ccall_result = ((wstandend)((_ccall_arg1))); where the decision to insert parens is decided by a command-line flag. (Ideally, this flag would affect foreign imports in that file but not any obtained from imported modules.) I like this approach because it means that we don't have to strip the parens off when using the other compilation techniques such as GHC's NCG or Hugs generating stub functions for everything. Alternatively add an appropriate set of #undefs for this particular file. The following comes close to doing the job. grep generated /usr/include/curses.h | perl -pe 's/^.*\)\s+(\w+).*/#undef \1/' Stick the result in a header file like this: curses_wrapper.h: #include "curses.h" #ifdef __GHC__ #undef macro1 ... #undef macro117 #endif and use curses_wrapper.h instead of curses.h in the Haskell code. -- Alastair Reid
http://www.haskell.org/pipermail/ffi/2004-April/001756.html
crawl-001
refinedweb
281
65.42
Home Screen Quick Actions for iOS: Getting Started Learn how to integrate Static and Dynamic Home Screen Quick Actions into your SwiftUI iOS app. Version - Swift 5.5, iOS 15, Xcode 13 Quick actions are a great way to provide your users fast access to your app’s common functionality within the home screen. iOS 13 introduced the concept of quick actions, where a user can touch and hold an app icon to display a set of shortcuts or actions to perform right from the home screen. All apps have quick actions to edit the home screen or delete the app by default: Developers can also provide their own quick actions to provide users with powerful shortcuts to common app functionality. The iOS Camera app has actions to take different types of photos or to record a video. A shopping app might let you jump directly to your orders or wishlist, and a messaging app might show your favorite contacts so you can easily access them. I’m sure you can think of ways that quick actions would benefit your users. In this tutorial you’re going to learn about: - Static quick actions, which are always available for your app. - Dynamic quick actions, which your app can define at runtime. - How to support both types of quick action in the sample project, a note-taking app called Note Buddy. Getting Started Download the starter project by clicking the Download Materials button at the top or bottom of the tutorial. Note Buddy is a note-taking app with some basic functionality: - Add, edit or delete notes with a title and body. - Favorite a note. - Store your notes between launches. - Auto-sort notes by last modified date. Open the project, then build and run. You’ll see this note page: To power Note Buddy’s functionality, you’ll find the Note model and its associated NoteStore class in the Models group. Moving on to SwiftUI, in the Views group, you have: NoteList: Shows a list of all your notes sorted by last modified date. NoteRow: The view for a note row within the note list. It shows the note’s title, body and whether the user marked it as a favorite. EditNote: An editor for modifying your note’s title, body or changing the favorite status. NavigationLink+Value: A helper extension to make programmatic navigation a little easier when you have an associated data model to push. Finally, AppMain describes your app with a reference to the NoteStore and a body which sets up the NoteList view within a WindowGroup and correctly injects the appropriate environment values. Before you dive in to coding, it’s time to take a closer look at what the two types of quick actions are, and how they work. Static vs. Dynamic Quick Actions There are two types of quick actions available to you: static and dynamic. You use static actions for actions that never change in your app, like the Mail app’s New Message action. Use dynamic actions if your actions might change under certain conditions or depend on specific data or state. For example, the Messages app will add quick actions for all of your pinned conversations. In both cases, you add code to handle a specific action that gets triggered. Since adding static quick actions is quicker, you’ll start with those. Creating Static Quick Actions Static quick actions are a great way to let your users create a new note. First, add model code to assist you in handling a triggered action. Right-click the Models group and then click New File… ▸ Swift File. Name your new file Action and click Create. Replace the contents of the file with: import UIKit // 1 enum ActionType: String { case newNote = "NewNote" } // 2 enum Action: Equatable { case newNote // 3 init?(shortcutItem: UIApplicationShortcutItem) { // 4 guard let type = ActionType(rawValue: shortcutItem.type) else { return nil } // 5 switch type { case .newNote: self = .newNote } } } // 6 class ActionService: ObservableObject { static let shared = ActionService() // 7 @Published var action: Action? } A lot is going on. Here’s what you added: - You create an enum called ActionTypebacked by a String. You’ll use the string values later to help identify different types of action your app will perform. The newNotecase will identify the action for creating a New Note. - You create another enum called Actionthat looks similar, but is just Equatable. This might look a little repetitive, but it’ll make sense when you add other actions later on. - Then you create a failable initializer that accepts an instance of UIApplicationShortcutItem. The system uses this type to describe different quick actions. - Here, you ensure that you’re creating an Actionfor a known ActionType, otherwise you return nil. - Switch on the different possible ActionTypevalues known to your app. You can then use the information available to describe the correct Action. - Define an ObservableObjectclass you can later pass into the SwiftUI environment as well as provide a singleton accessor for later when you work with UIKit code. - Define a @Publishedproperty that can represent an action your app should perform. The aim of the Action concept is for you to model quick actions your app supports and work with them safely when mapping between UIApplicationShortcutItem. Now, open AppMain.swift. Above noteStore, add a new property for ActionService: private let actionService = ActionService.shared Then update the body implementation to ensure that the service is injected into the view hierarchy and that NoteList can access it: var body: some Scene { WindowGroup { NoteList() .environmentObject(actionService) .environmentObject(noteStore) .environment(\.managedObjectContext, noteStore.container.viewContext) } } ActionService is available in the SwiftUI environment, and it’s time to use it. Open NoteList.swift in the Views group and add the following properties under noteStore: @EnvironmentObject var actionService: ActionService @Environment(\.scenePhase) var scenePhase Not only are you accessing the ActionService class, you’ll also need access to the ScenePhase, which is a property that notifies you when your app becomes active and when it enters the background. At the bottom of the view, add the following method: func performActionIfNeeded() { // 1 guard let action = actionService.action else { return } // 2 switch action { case .newNote: createNewNote() } // 3 actionService.action = nil } This method does three things: - Checks if there’s an action in the ActionService. - Switches on the type of action and invokes the createNewNote()action for Action.newNote. - Removes the action from the ActionServicesince it was performed. You need to trigger this code whenever your app becomes active. You’ll use the onChange(of:perform:) view modifier with the scenePhase property that you added earlier. Add the following code after the closing brace of the toolbar modifier: // 1 .onChange(of: scenePhase) { newValue in // 2 switch newValue { case .active: performActionIfNeeded() // 3 default: break } } Here, the code: - Adds a modifier to the Listthat will fire its closure whenever the scenePhasechanges. - Using the argument provided, it switches on the value. If it’s .active, it’ll call your new performActionIfNeeded()method. - Since you don’t care about the other states, such as .inactiveor .background, it doesn’t do anything. Modifying the Info Property List File You added logic to your code that handles the action. But before running the app, you still have to tell the system about your static action. This is simple to do. In the Resources group, open Info.plist. Right click Information Property List at the top and click Add Row. In the Key column, type Home Screen Shortcut Items and press return to finish editing. Xcode automatically sets the Type to Array and adds an item for you. Expand the elements by clicking the chevron and you’ll see two nested keys: Each item listed in this array represents a single static quick action that your app supports. Update the placeholder item with the following values: - Shortcut Item Type: NewNote - Title: New Note In addition to the default keys, you need to add one more. Hover over Title and click the + icon that appears. Type UIApplicationShortcutItemIconSymbolName (ignore the pop-up options for now, you have to type the full string) for the Key and square.and.pencil for the Value. Here’s a breakdown of each of these keys: - Shortcut Item Type: A string identifier that represents a unique type of action. You might notice that this matches the raw value of the ActionType.newNoteenum case you added earlier. That’s important. - Title: The user-friendly title that displays when the user taps and holds your app icon. - UIApplicationShortcutItemIconSymbolName: The SF Symbol to use for this action. You can also use UIApplicationShortcutItemIconFile for an icon file available in your bundle, or UIApplicationShortcutItemIconTypefor a set of pre-defined options available for quick actions. Icon file and icon type are selectable from the drop down list when editing the Info.plist entry, but the symbol option is not. There are additional keys available for shortcut items in your Info.plist that you can read about in the Apple documention. Building and Running Your App Build and run your app. Go back to the home screen and long-press the Note Buddy app icon to see your quick action now available in the list: Tap New Note to see what happens: Nothing?!? Well, that’s weird. You added a model to work with actions within the app and defined a static action in Info.plist. What’s wrong, then? The system tells your app when the user interacts with a quick action, but you’re not doing anything with the information yet. Time to do that! Handling Static Quick Actions SwiftUI doesn’t yet provide any native mechanisms to respond to launch events from quick actions. Therefore, you need to rely on UIKit for this part. Right-click AppMain.swift and select New File… ▸ Swift File. Name the file AppDelegate and click Create. Replace the contents of the file with: // 1 import UIKit // 2 class AppDelegate: NSObject, UIApplicationDelegate { private let actionService = ActionService.shared // 3 func application( _ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions ) -> UISceneConfiguration { // 4 if let shortcutItem = options.shortcutItem { actionService.action = Action(shortcutItem: shortcutItem) } // 5 let configuration = UISceneConfiguration( name: connectingSceneSession.configuration.name, sessionRole: connectingSceneSession.role ) configuration.delegateClass = SceneDelegate.self return configuration } } // 6 class SceneDelegate: NSObject, UIWindowSceneDelegate { private let actionService = ActionService.shared // 7 func windowScene( _ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void ) { // 8 actionService.action = Action(shortcutItem: shortcutItem) completionHandler(true) } } If you’re not too familiar with UIKit, don’t worry! Here’s an overview of the code above: - Import the UIKit framework to access the symbols and types you need in this file. - Create a class named AppDelegatethat inherits from NSObjectand conforms to the UIApplicationDelegateprotocol. - Implement application(_:configurationForConnecting:options:)to hook into an event triggered when the app is preparing to launch your main UI. - Unwrap shortcutItemprovided with the options. If it’s present, this indicates that the user is launching your app from a quick action. Use the initializer you added earlier to map the data to an Actionand assign it to the ActionService. - Fulfill the requirements of the method by creating the appropriate UISceneConfigurationobject and returning it. - Similar to step two, create another class that conforms to the UIWindowSceneDelegateprotocol. - Implement windowScene(_:performActionFor:completionHandler:)to hook into events that trigger when a user interacts with a quick action after your app has already launched, for example, when it’s in the background. - Similarly to step four, attempt to convert UIApplicationShortcutIteminto an Actionand pass it onto the ActionService. Finally, your SwiftUI app needs to use the new AppDelegate and SceneDelegate. So, in AppMain.swift, underneath the actionService, add the following property inside AppMain: @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate Time to build and run your app again. Head back to the home screen and try using your quick action again: Fantastic! You added your first static quick action. While this opens the door to many possibilities, you can’t customize it with information used at runtime. That’s where dynamic actions come in. Creating Dynamic Quick Actions If users want to edit their most recent note, they still have to open the app, scroll through the list to find it, tap it and then edit. It would be great to simplify and speed up the process! While static actions go in Info.plist, you add all dynamic actions in code. In the case of Note Buddy, and likely for many of your apps, these dynamic actions will be added when your scene’s phase changes to background. Thus, before heading to the home screen, you set up some actions to edit the most recent notes by the last modified date. Handling Dynamic Quick Actions To add dynamic actions, first add a new case to your ActionType and Action enums. Open Action.swift and add the following to ActionType: case editNote = "EditNote" Add the following new case to Action: case editNote(identifier: String) This is why ActionType and Action needed to be two separate enums. While ActionType represents the identifiers of different quick action types, Action represents the action itself. In some cases, like the case of .editNote, this can include other associated values. After adding the new enum cases, you’ll notice that the compiler has kindly told you that the switch statement in init?(shortcutItem:) is no longer exhaustive. Fix that by adding the following case to the switch: case .editNote: if let identifier = shortcutItem.userInfo?["NoteID"] as? String { self = .editNote(identifier: identifier) } else { return nil } Here you’ll check the shortcutItem‘s userInfo dictionary to get the ID of the note to edit. If successful, you initialize the action as .editNote with the associated value. Otherwise, the initializer just fails by returning nil. If you try to build the project now, you’ll see one more compile failure in NoteList.swift. Head over to it, and you’ll find that you also need to implement the new action handling inside performActionIfNeeded(). Add the following code to the switch statement: case .editNote(let identifier): selectedNote = noteStore.findNote(withIdentifier: identifier) Build and run your app. Then head to the home screen, long-press the Note Buddy icon and see the results: Once again…nothing? While you already made sure that quick actions pass to your app correctly, you still haven’t told your app to show any dynamic items. You’ll do that next. Adding Your Dynamic Quick Actions As mentioned earlier, a good place to add your dynamic actions is when the app goes into the background. At this point, you have all the information needed to run the code that determines what actions to add and then add them. Since you’re already observing the ScenePhase in NoteList, that’s a good place to update the actions. But before you do that, you need to create your own instances of UIApplicationShortcutItem that describe your dynamic action. Head to Note.swift and add the following import at the top of the file: import UIKit Inside the Note extension, add the following property: // 1 var shortcutItem: UIApplicationShortcutItem? { // 2 guard !wrappedTitle.isEmpty || !wrappedBody.isEmpty else { return nil } // 3 return UIApplicationShortcutItem( type: ActionType.editNote.rawValue, localizedTitle: "Edit Note", localizedSubtitle: wrappedTitle.isEmpty ? wrappedBody : wrappedTitle, icon: .init(systemImageName: isFavorite ? "star" : "pencil"), userInfo: [ "NoteID": identifier as NSString ] ) } Here’s a code breakdown: - You define a new computed property on Notecalled shortcutItem. The property is optional because you don’t need to represent every note as a quick action. - If the note doesn’t have a title or body, you return nilso that this note won’t be represented. - Then you initialize a new instance of UIApplicationShortcutItemand return it. - Use the type defined by ActionTypeso it matches the expected value when you read it back later. - Provide a user-friendly title, like you did in Info.plist. - To personalize the action some more, you include either the title or body of the note as the subtitle of the quick action. - Use an appropriate SF Symbol to represent if the item is a favorite or not. - Include the unique identifier of the Notein the userInfoso that you’ll know which note to edit when you respond to the quick action. Now that you created a property to expose the appropriate shortcut for a given Note, navigate back to NoteList.swift. Add the following method beneath performActionIfNeeded(): func updateShortcutItems() { UIApplication.shared.shortcutItems = notes.compactMap(\.shortcutItem) } Here you compact map the notes array to produce an array of just the non-nil UIApplicationShortcutItem‘s. This array is then assigned to the UIApplication‘s shortcutItems property which, in turn, becomes available alongside your static actions in the Home Screen Menu. Now, you just need to call this method whenever the app goes into the background. Scroll back up to the onChange(of: perform:) modifier that you added earlier and add the following inside of the switch statement: case .background: updateShortcutItems() Build and run. Then have a look to see which items are available: Yay! You’re done. Make some edits to your notes, favorite a few and repeat the process. The notes shown, as well as the order, stay perfectly in sync whenever you background the app: You may have noticed that not all of your notes show up. iOS limits the number of actions to only show those that fit on-screen. However, the documentation suggests you don’t specifically limit the count of dynamic actions. Instead, do it as you have for Note Buddy. With that, iOS will show all the quick actions it can fit. If future updates enable more, that’s fantastic as you don’t need to push out an app update to support adding more actions before you background the app. Where to Go From Here? Download the finished project by clicking Download Materials at the top or bottom of this tutorial. And there you have it: You’re equipped and ready to add quick actions to your apps and projects. If you’d like to know more, take a look at the Apple documentation for Menus and Shortcuts in UIKit, as well as the Human Interface Guidelines for Home Screen Quick Actions. What other cool uses of quick actions can you think of? Thanks for following along. Leave your implementations and ideas in the comments.
https://www.raywenderlich.com/29646799-home-screen-quick-actions-for-ios-getting-started
CC-MAIN-2022-21
refinedweb
3,020
56.96
Snippets are minimal stand-alone programs that demonstrate specific techniques or functionality. Often a small example is the easiest way to understand how to use a particular feature. Snippets also help isolate problems. The best way to report an SWT bug is to write your own snippet showing the problem and paste it into the bug report. For a snippet template, see the "Hello World" example. Note that the examples here are often edited for brevity rather than completeness. They are intended to guide the reader towards the correct solution, rather than be finished products. These snippets are tested against the HEAD stream and may sometimes reference new API or require bug fixes from there. To run a snippet, simply import SWT into your Eclipse workspace, create a new Java project that depends on SWT, copy the desired snippet to the clipboard, and paste it into a new snippet class. (If you are using eclipse 3.2 M1 or earlier, you need to create the class using the New Class wizard before pasting; but since 3.2 M1 you can simply select your project and paste, and the class is created for you). Run by selecting the class and then selecting Run > Run As > Java Application. To contribute a new snippet, enter a bug report. Thanks in advance for your contribution!
http://www.eclipse.org/swt/snippets/
crawl-001
refinedweb
221
65.22
Created on 2014-01-06 15:30 by torsten, last changed 2015-03-05 17:53 by davin. This issue is now closed. The behaviour of multiprocessing.Queue surprised me today in that Queue.get() may raise an exception even if an item is immediately available. I tried to flush entries without blocking by using the timeout=0 keyword argument: $ /opt/python3/bin/python3 Python 3.4.0b1 (default:247f12fecf2b, Jan 6 2014, 14:50:23) [GCC 4.6.3] on linux Type "help", "copyright", "credits" or "license" for more information. >>> from multiprocessing import Queue >>> q = Queue() >>> q.put("hi") >>> q.get(timeout=0) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/python3/lib/python3.4/multiprocessing/queues.py", line 107, in get raise Empty queue.Empty Actually even passing a small non-zero timeout will not give me my queue entry: >>> q.get(timeout=1e-6) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/torsten/opensrc/cpython/Lib/multiprocessing/queues.py", line 107, in get raise Empty queue.Empty Expected behaviour for me would be to return the item that is in the queue. I know that there is a kwarg *block* which gives me the desired behaviour: >>> q.get(block=False) 'hi' In my case the get call is embedded in my own module which does not currently expose the block parameter. My local solution is of course to update the wrapper: if timeout == 0: timeout = None block = False However I see a few smells here in the python standard library. First, everything else seems to accept timeout=0 as nonblocking: >>> import threading >>> lock = threading.Lock() >>> lock.acquire(timeout=0) True >>> from queue import Queue >>> q = Queue() >>> q.put("hi") >>> q.get(timeout=0) 'hi' Of special note is that queue.Queue behaves as I would have expected. IMHO it should be consistent with multiprocessing.Queue. Also note that queue.Queue.get() and queue.Queue.put() name their blocking flag "block", while everybody else uses "blocking". As a side note, I think the current approach is flawed in computing the deadline. Basically it does the following: deadline = time.time() + timeout if not self._rlock.acquire(block, timeout): raise Empty timeout = deadline - time.time() if timeout < 0 or not self._poll(timeout): raise Empty On my system, just taking the time twice and computing the delta takes 2 microseconds: >>> import time >>> t0 = time.time(); time.time() - t0 2.384185791015625e-06 Therefore calling Queue.get(block, timeout) with 0 < timeout < 2e-6 will never return anything from the queue even though Queue.get(block=False) would do that. This contradicts the idea that Queue.get(block=False) will return faster than with block=True with any timeout > 0. Apart from that, as Python does not currently support waiting on multiple sources, we currently often check a queue with a small timeout concurrently with doing other stuff. In case the system get really loaded, I would expect this to cause problems because the updated timeout may fall below zero. Suggested patch attached. We have a similar bug with Queue.get(). Queue.get(False) raises an exception Queue.Empty in the case when the queue is actually not empty! An example of the code is attached and is listed below just in case: ---------------------- import multiprocessing import Queue class TestWorker(multiprocessing.Process): def __init__(self, inQueue): multiprocessing.Process.__init__(self) self.inQueue = inQueue def run(self): while True: try: task = self.inQueue.get(False) except Queue.Empty: # I suppose that Queue.Empty exception is about empty queue # and self.inQueue.empty() must be true in this case # try to check it using assert assert self.inQueue.empty() break def runTest(): queue = multiprocessing.Queue() for _ in xrange(10**5): queue.put(1) workers = [TestWorker(queue) for _ in xrange(4)] map(lambda w: w.start(), workers) map(lambda w: w.join(), workers) if __name__ == "__main__": runTest() ---------------------- Hi! Are there any updates on the issue? This same issue came up recently in issue23582. Really, it should have been addressed in this issue here first and issue23582 marked as a duplicate of this one but these things don't always happen in a synchronous or apparently-linear fashion. Adding to what is captured in issue23582, specifically referring to the points raised here in this issue: 1. A call to put does not mean that the data put on the queue is instantly/atomically available for retrieval via get. Situations where a call to put is immediately followed by a non-blocking call to get are asking for a race-condition -- this is a principal reason for having blocking calls with timeouts. 2. A call to get resulting in an Empty exception of course does not mean that the queue is forevermore empty, only that the queue is empty at the moment the call to get was made -- the facility for trapping the Empty and trying again to get more data off the queue provides welcome flexibility on top of the use of blocking/non-blocking calls with/without timeouts. 3. A call to empty is, as indicated in the documentation, not to be considered reliable because of the semantics in coordinating the queue's state and data between processes/threads. 4. Alexei's contributions to this issue are very nearly identical to what is discussed in issue23582 and are addressed well there. 5. As to using a timeout value too small to be effective (i.e. < 2e-6), really this is one example of the larger concern of choosing an appropriate timeout value. In the proposed patch, ensuring that a call to self._poll is made no matter what might potentially buy additional time for the data to be synced and made available (admittedly a happy result, but a fragile, inadvertent win) but it does not address the rest of how get, put, and the others work nor will it necessarily solve the issue being raised here. In Alexei's example, changing the call to get from a non-blocking call to a blocking call with a reasonably small timeout will reliably ensure that everything put on the queue can and will be gotten back by the rest of that code. In multiprocessing, we have queues to help us make data available to and across processes and threads alike -- we must recognize that coordinating data across distinct processes (especially) takes a non-zero amount of time -- hence we have the tools of blocking as well as non-blocking calls both with or without timeouts to properly implement robust code in these situations.
https://bugs.python.org/issue20147
CC-MAIN-2018-34
refinedweb
1,097
66.23
08 August 2007 11:49 [Source: ICIS news] SINGAPORE (ICIS news)--Iran's Jam Petrochemical expects to achieve commercial production at its 300,000 tonne/year Assaluyeh high density polyethylene (HDPE) plant early in the fourth quarter, a source close to the project said on Wednesday. The planned launch would come before the the start-up of Jam's 1.32m tonne/year cracker at the same site. "The HDPE plant will probably use ethylene feedstock from the Arya Sasol cracker, as the Jam cracker is only expected to go on stream by the end of the year," the source added. Arya Sasol, a joint venture of ?xml:namespace> Jam, a subsidiary of NPC, will not start up its other derivative plants until the first quarter of 2008, the source said. Besides the HDPE unit, the cracker complex includes a HDPE/linear low density PE (LLDPE) unit and a polypropylene (PP) unit, each with
http://www.icis.com/Articles/2007/08/08/9051169/irans-jam-to-start-up-hdpe-in-q4-before-cracker.html
CC-MAIN-2014-42
refinedweb
154
67.69
This is the official Raspberry Pi blog for news and updates from the Raspberry Pi Foundation, education initiatives, community projects and more! GPIO Zero: a friendly Python API for physical computing, which he used as part of his beer brewing process. This allowed people to control GPIO pins from their Python programs, and became a hit both in education and in personal projects. We use it in many of our free learning resources. However, recently I’ve been thinking of ways to make this code seem more accessible. I created some simple and obvious interfaces for a few of the components I had lying around on my desk – namely the brilliant CamJam EduKits. I added interfaces for LED, Button and Buzzer, and started to look at some more interesting components – sensors, motors and even a few simple add-on boards. I got some great help from Dave Jones, author of the excellent picamera library, who added some really clever aspects to the library. I decided to call it GPIO Zero as it shares the same philosophy as PyGame Zero, which requires minimal boilerplate code to get started. This is how you flash an LED using GPIO Zero: from gpiozero import LED from time import sleep led = LED(17) while True: led.on() sleep(1) led.off() sleep(1) (Also see the built-in blink method) As well as controlling individual components in obvious ways, you can also connect multiple components together. Here’s an example of controlling an LED with a push button: from gpiozero import LED, Button from signal import pause led = LED(17) button = Button(2) button.when_pressed = led.on button.when_released = led.off pause() We’ve thought really hard to try to get the naming right, and hope people old and young will find the library intuitive once shown a few simple examples. The API has been designed with education in mind and I’ve been demoing it to teachers to get feedback and they love it! Another thing is the idea of minimal configuration – so to use a button you don’t have to think about pull-ups and pull-downs – all you need is the pin number it’s connected to. Of course you can specify this – but the default assumes the common pull-up circuit. For example: button_1 = Button(4) # connected to GPIO pin 4, pull-up button_2 = Button(5, pull_up=False) # connected to GPIO pin 5, pull-down Normally, if you want to detect the button being pressed you have to think about the edge falling if it’s pulled up, or rising if it’s pulled down. With GPIO Zero, the edge is configured when you create the Button object, so things like when_pressed, when_released, wait_for_press, wait_for_release just work as expected. While understanding edges is important in electronics, I don’t think it should be essential for anyone who wants to Here’s a list of devices which currently supported: - LED (also PWM LED allowing change of brightness) - RGB LED - Buzzer - Motor - Button - Motion Sensor - Light Sensor - Analogue-to-Digital converters MCP3004 and MCP3008 - Robot Also collections of components like LEDBoard (for any collection of LEDs), FishDish, Traffic HAT, generic traffic lights – and there are plenty more to come. There’s a great feature Dave added which allows the value of output devices (like LEDs and motors) to be set to whatever the current value of an input device is, automatically, without having to poll in a loop. The following example allows the RGB values of an LED to be determined by three potentiometers for colour mixing: from gpiozero import RGBLED, MCP3008 from signal import pause pause() Other wacky ways to set the brightness of an LED: from a Google spreadsheet – or according to the number of instances of the word “pies” on the BBC News homepage! Alex Eames gave it a test drive and made a video of a security light project using a relay – coded in just 16 lines of code. GPIO Zero Security Light in 16 lines of code Using GPIO Zero Beta to make a security light in 16 lines of code. See blog article here… If you like the look of the RasPiO Portsplus port labels board I’m using to identify the ports, you can find that here Yasmin Bey created a robot controlled by a Wii remote: Yasmin Bey on Twitter @ben_nuttall @RyanteckLTD pic.twitter.com/JEoSUlHtF6 Version 1.0 is out now so the API will not change – but we will continue to add components and additional features. GPIO Zero is now pre-installed in the new Raspbian Jessie image available on the downloads page. It will also appear in the apt repo shortly. Remember – since the release of Raspbian Jessie, you no longer need to run GPIO programs with sudo – so you can just run these programs directly from IDLE or the Python shell. GPIO Zero supports both Python 2 and Python 3. Python 3 is recommended! Let me know your suggestions for additional components and interfaces in the comments below – and use the hashtag #gpiozero to share your project code and photos! A huge thanks goes to Ben Croston, whose excellent RPi.GPIO library sits at the foundation of everything in GPIO Zero, and to Dave Jones whose contributions have made this new library quite special. See the GPIO Zero documentation and recipes and check out the Getting Started with GPIO Zero resource – more coming soon.
https://www.raspberrypi.org/?p=date/2013/04
CC-MAIN-2015-48
refinedweb
904
55.58
A Java source file is a plain text file containing Java source code and having .java extension. The .java extension means that the file is the Java source file. Java source code file contains source code for a class, interface, enumeration, or annotation type. There are some rules associated to Java source file. We should adhere to following rules while writing Java source code. publicclass per source code file. publicclass in a file, the name of the file must match the name of the publicclass. For example, a class declared as public class Dog { }must be in a source code file named Dog.java. packagestatement must be the first line in the source code file, before any importstatements that may be present. importstatements, they must go between the packagestatement (if there is one) and the class declaration. If there isn't a packagestatement, then the importstatement(s) must be the first line(s) in the source code file. If there are no packageor importstatements , the class declaration must be the first line in the source code file. importand packagestatements apply to all classes within a source code file. In other words, there's no way to declare multiple classes in a file and have them in different packages, or use different imports. Hope you have enjoyed reading Java source file declaration rules.
http://cs-fundamentals.com/tech-interview/java/what-are-java-source-file-declaration-rules.php
CC-MAIN-2017-17
refinedweb
222
65.22
Hey, I am looking for a way to change permissions to a saved search via splunk python SDK. I tried using the splunklib.client post method: import splunklib.client as client app = "app_name" cred = {"user": "admin", "password": "changeme", "port": 8089, "host": "localhost","owner":"admin"} service = client.connect(app=app,**cred) service.post('saved/searches/report_name/acl', sharing="app" ) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.6/site-packages/splunk_sdk-1.2.3-py2.6.egg/splunklib/binding.py", line 238, in wrapper return request_fun(self, *args, **kwargs) File "/usr/lib/python2.6/site-packages/splunk_sdk-1.2.3-py2.6.egg/splunklib/binding.py", line 62, in new_f val = f(*args, **kwargs) File "/usr/lib/python2.6/site-packages/splunk_sdk-1.2.3-py2.6.egg/splunklib/binding.py", line 657, in post response = self.http.post(path, all_headers, **query) File "/usr/lib/python2.6/site-packages/splunk_sdk-1.2.3-py2.6.egg/splunklib/binding.py", line 1089, in post return self.request(url, message) File "/usr/lib/python2.6/site-packages/splunk_sdk-1.2.3-py2.6.egg/splunklib/binding.py", line 1109, in request raise HTTPError(response) splunklib.binding.HTTPError: HTTP 404 Not Found -- In handler 'savedsearch': Could not find object id=report_name When i try using curl i get no problem: curl -k -u admin:changeme -d sharing=app Maybe i am doing something wrong? Or maybe there is other way to do it and i am missing it? Regards, Dori. You had the right idea to post to /acl, but you need to urlencode the parameters. The following creates a new EventType then changes the permissions afterwards. There does not appear to be a way to assign the roles with the initial create method. The "/acl" link can be derived from links in the returned Stanza object. from urllib.parse import urlencode newperms = { "perms.read": "role name 1,role name 2, role name 3", "perms.write": "role name 1, role name 2", "sharing": "app", "owner": "nobody" } newet = sdk.confs["eventtypes"].create("test_event_type",sharing="app",app="custom_app") sdk.post("%s/%s" % (newet.links["alternate"], "acl"), body=urlencode(newperms)). Thank you for your comment @dorilevy, however that example does indeed include the correct URL. "" % ("admin", ss) request = urllib2.Request( url ) It's important to remember the app context the saved search resides in otherwise you will run into an issue where the saved search is not found. For example if I had an app named "MYAPP" and a saved search named "MYSEARCH" the url should reflect that. Hey @flynt, You are correct. i missed the app context (my app is not search, that is why i thought it is mistake). Sorry about it, and again - thanks for the solution. Dori
https://community.splunk.com/t5/Getting-Data-In/How-to-change-saved-search-permissions-via-python-SDK/td-p/114567
CC-MAIN-2020-40
refinedweb
461
59.6
insdelln, winsdelln - delete or insert lines into a window #include <curses.h> int insdelln(int n); int winsdelln(WINDOW *win, int n); The insdelln() and winsdelln() functions perform the following actions: - If n is positive, these functions insert n lines into the current or specified window before the current line. The n last lines are no longer displayed. - If n is negative, these functions delete n lines from the current or specified window starting with the current line, and move the remaining lines toward the cursor. The last n lines are cleared. The current cursor position remains the same. Upon successful completion, these functions return OK. Otherwise, they return ERR. No errors are defined. deleteln(), insertln(), <curses.h>.
http://pubs.opengroup.org/onlinepubs/7990989775/xcurses/winsdelln.html
CC-MAIN-2014-52
refinedweb
118
59.9
fcntl.h - file control options #include <fcntl.h>. [XSI] The values used for l_whence, SEEK_SET, SEEK_CUR, and SEEK_END shall be defined as described in <unistd.h> - [SIO] Write according to synchronized I/O data integrity completion.Write according to synchronized I/O data integrity completion. - O_NONBLOCK - Non-blocking mode. - O_RSYNC - [SIO] Synchronized read I/O operations. [XSI] The symbolic names for file modes for use as values of mode_t shall be defined as described in <sys/stat.h>.The symbolic names for file modes for use as values of mode_t shall be defined as described in <sys/stat.h>. [ADV] Values for advice used by posix_fadvise() are as follows, ...); [ADV] int posix_fadvise(int, off_t, off_t, int); int posix_fallocate(int, off_t, off_t);int posix_fadvise(int, off_t, off_t, int); int posix_fallocate(int, off_t, off_t); [XSI] Inclusion of the <fcntl.h> header may also make visible all symbols from <sys/stat.h> and <unistd.h>.Inclusion of the <fcntl.h> header may also make visible all symbols from <sys/stat.h> and <unistd.h>. None. None. None. <sys/stat.h>, <sys/types.h>, <unistd.h>, the System Interfaces volume of IEEE Std 1003.1-2001, creat(), exec, fcntl(), open(), posix_fadvise(), posix_fallocate(), posix_madvise() First released in Issue 1. Derived from Issue 1 of the SVID. The DESCRIPTION is updated for alignment with the POSIX Realtime Extension. The following changes are made for alignment with the ISO POSIX-1:1996 standard: - O_DSYNC and O_RSYNC are marked as part of the Synchronized Input and Output option. The following new requirements on POSIX implementations derive from alignment with the Single UNIX Specification: - The definition of the mode_t, off_t, and pid_t types is mandated. The F_GETOWN and F_SETOWN values are added for sockets. The posix_fadvise(), posix_fallocate(), and posix_madvise() functions are added for alignment with IEEE Std 1003.1d-1999. IEEE PASC Interpretation 1003.1 #102 is applied, moving the prototype for posix_madvise() to <sys/mman.h>. IEEE Std 1003.1-2001/Cor 2-2004, item XBD/TC2/D6/18 is applied, updating the protoypes for posix_fadvise() and posix_fallocate() to be large file-aware, using off_t instead of size_t.
http://pubs.opengroup.org/onlinepubs/009695399/basedefs/fcntl.h.html
CC-MAIN-2017-13
refinedweb
350
60.21
. Table of contents Setting Up the Scene To begin, set up your TutorialApplication class like this: #include "BaseApplication.h" class TutorialApplication : public BaseApplication { public: TutorialApplication(); virtual ~TutorialApplication(); protected: virtual void createScene(); virtual bool frameRenderingQueued(const Ogre::FrameEvent& fe); private: bool processUnbufferedInput(const Ogre::FrameEvent& fe); }; #include "TutorialApplication.h" TutorialApplication::TutorialApplication() { } TutorialApplication::~TutorialApplication() { } void TutorialApplication::createScene() { mSceneMgr->setAmbientLight(Ogre::ColourValue(.25, .25, .25)); Ogre::Light* pointLight = mSceneMgr->createLight("PointLight"); pointLight->setType(Ogre::Light::LT_POINT); pointLight->setPosition(250, 150, 250); pointLight->setDiffuseColour(Ogre::ColourValue::White); pointLight->setSpecularColour(Ogre::ColourValue::White); Ogre::Entity* ninjaEntity = mSceneMgr->createEntity("ninja.mesh"); Ogre::SceneNode* ninjaNode = mSceneMgr->getRootSceneNode()->createChildSceneNode("NinjaNode"); ninjaNode->attachObject(ninjaEntity); } bool TutorialApplication::frameRenderingQueued(const Ogre::FrameEvent& fe) { bool ret = BaseApplication::frameRenderingQueued(fe); return ret; } bool TutorialApplication::processUnbufferedInput(const Ogre::FrameEvent& fe) { return true; } // MAIN FUNCTION OMITTED FOR SPACE In createScene, we've constructed a ninja Entity and placed a directional light. This should all be familiar by now. We will use this simple scene to demonstrate the use of unbuffered input and the FrameListener. The plan is to toggle the light on and off when the user clicks the left mouse button. We will also allow the user to rotate and move the ninja Entity with the IJKL keys. This will involve the use of unbuffered input. This means that we are not gathering up all of the input events and dealing with each one. Instead, we simply ask Ogre if a key is currently being pressed down at the time of our request. Buffered input will be covered in the next tutorial series. The FrameListener Class The concept of a listener class is used in many different programming situations. This class will be set up to receive notifications whenever certain events occur. The class is notified by the use of "callback methods". When an event the listener is registered for occurs, the application will "call back" to the listener class by calling a pre-defined method that was designed to handle the event. In Ogre, we can register a listener class to be notified during different stages in the frame rendering process. This class is called the FrameListener. The FrameListener declares three callback methods: If any of these methods returns false, then your application will exit its rendering loop. Make sure to return true when using any of these methods while you want your application to continue rendering. The FrameEvent struct contains two variables, but only timeSinceLastFrame is useful from the FrameListener. This variable keeps track of how many seconds have passed since the last call to frameStarted or frameEnded respectively. So if you check this variable in frameStarted, it will contain the time since the last call to frameStarted, and if you check it in frameEnded, it will contain the time since the last call to frameEnded. If you have multiple FrameListeners active in your scene, it is important to know you are not guaranteed they will be called in any particular order. If you need to ensure that things occur in a specific order, then you should use a single FrameListener and make all of the calls in the correct order. Which of these methods you should use depends on your particular needs. If you are doing normal per frame updates, then you should generally put those in frameRenderingQueued. This method is called right before the GPU begins to flip you rendering buffers. For performance reasons, you want to keep your CPU busy while the GPU does its work. The other methods are useful when you must set up things at a specific time during the rendering process. This kind of thing becomes more common when you add something like a physics library to your application. How the FrameListener Works To better understand how the listener process works, we will look at the Ogre::Root::renderOneFrame method: bool Root::renderOneFrame(void) { if(!_fireFrameStarted()) return false; if (!_updateAllRenderTargets()) return false; return _fireFrameEnded(); } You can see that this method fires the FrameStarted event before updating all of the render targets, and then fires the FrameEnded event afterwards. To understand when the FrameRenderingQueued event fires, we will look at an excerpt from the Ogre::Root::_updateAllRenderTargets method which is called in the previous example: bool Root::_updateAllRenderTargets(void) { mActiveRenderer->_updateAllRenderTargets(false); bool ret = _fireFrameRenderingQueued(); // thread is blocked for final swap mActiveRenderer->_swapAllRenderTargetBuffers( mActiveRenderer->getWaitForVerticalBlank()); ... You can see that it fires the FrameRenderingQueued event immediately after updating all of the render targets, but right before the thread is blocked so the GPU can swap all of the rendering buffers. Registering a FrameListener The good news is that our TutorialApplication class is already a FrameListener! It is derived from BaseApplication, which inherits from FrameListener. You can see this by looking at the header for BaseApplication: class BaseApplication : public Ogre::FrameListener, public Ogre::WindowEventListener, public OIS::KeyListener, public OIS::MouseListener, OgreBites::SdkTrayListener { ... As you can see, BaseApplication actually serves as a number of different listeners. BaseApplication implements createFrameListener and frameRenderingQueued, both of which we overrode in Basic Tutorial 3. For a listener to receive notifications, it has to register itself with our instance of Ogre::Root. This allows Ogre::Root to call the FrameListener's callback methods whenever a FrameEvent occurs. To register our FrameListener, we use the Ogre::Root::addFrameListener method. A FrameListener can ask to no longer be notified of FrameEvents by using removeFrameListener. If you look at BaseApplication, you can see that it uses this method in createFrameListener to register itself with Ogre::Root: mRoot->addFrameListener(this); This makes sure our frameRenderingQueued method will be called when appropriate. Processing Input We'll begin building our input processing method now. First, we are going to add some static variables we will use to control how the input works. Add the following to the beginning of processUnbufferedInput: static bool mouseDownLastFrame = false; static Ogre::Real toggleTimer = 0.0; static Ogre::Real rotate = .13; static Ogre::Real move = 250; The last two variables will be used for movement later. toggleTimer will be used to set how long the system waits before toggling the light again. mouseDownLastFrame will be used to keep track of whether the left mouse button was held down during the last frame. If we do not do this, then the unbuffered input would turn the light on and off many times whenever we clicked. This is because the user's click will almost assuredly last longer than one frame. So it would check the mouse every frame and quickly toggle the light. Sometimes this might be what you want. If you are using the input to move an Entity, then you would want to apply an acceleration to the Entity for every frame the input event is active. The variables are made static simply for convenience. They could have been class members as well, but they are only used in this method. The Object Oriented Input System (OIS) provides three primary classes for dealing with input: Keyboard, Mouse, and Joystick. These tutorials will cover the use of the Keyboard and Mouse. You can read through the Joystick class to understand how to get input from things like game controllers. In our case, the BaseApplication class is already capturing Keyboard and Mouse input in BaseApplication::frameRenderingQueued. It is accomplished with these two lines: mMouse->capture(); mKeyboard->capture(); Since this information is already being captured for us, we don't need to do anything else to access it. Add the following to processUnbufferedInput right after the static variables we just defined: bool leftMouseDown = mMouse->getMouseState().buttonDown(OIS::MB_Left); leftMouseDown will be true whenever the left mouse was held down during the last frame. You can see we use constants defined by OIS to identify the different mouse buttons. Next we are going to toggle the visibility of our light based on the two booleans we've just defined. if (leftMouseDown && !mouseDownLastFrame) { Ogre::Light* light = mSceneMgr->getLight("PointLight"); light->setVisible(!light->isVisible()); } First, we check to see if the left mouse button was held down and we make sure it was not held down last frame. This is going to help prevent the rapid toggling problem we mentioned earlier. The last thing we do is set our mouseDownLastFrame by assigning the current value of leftMouseDown. mouseDownLastFrame = leftMouseDown; This ensures that it will hold the correct value next frame. This is why mouseDownLastFrame had to be a static variable. It needed to persist between calls like a class member would. Calling the Input Function To get everything working, we need to make sure to call our processUnbufferedInput method each frame. As was mentioned before, the best place to do this is in frameRenderingQueued, because it needs to be done every frame. Add the following to frameRenderingQueued right after the call to BaseApplication::frameRenderingQueued: if(!processUnbufferedInput(fe)) return false; This makes sure that we only continue running the application if the input is processed successfully. Compile and run the application. You should now be able to turn the light on and off by clicking the left mouse button. The Camera controller should still work fine, because we are calling BaseApplication::frameRenderingQueued. Another Method to Avoid Rapid Toggling A drawback of our current method is that we would need to add a new boolean for every input event we wanted to keep track of. If we wanted to use the right mouse button, then we would need a rightMouseDownLastFrame variable as well. One way to get around this is by using a timer that resets after either mouse button has been pressed. We simply start the timer countdown after the first click and then only allow another click to affect the light if the timer has passed zero. This is what we'll use the toggleTimer variable for. The first thing we do is decrease the toggleTimer value by the amount of time that has passed since the last frame. Add the following to frameRenderingQueued right after our previous code: toggleTimer -= fe.timeSinceLastFrame; This will make sure toggleTimer is decreased each frame. Once it reaches zero, then we can reset the timer and allow another click to be processed. if ((toggleTimer < 0) && mMouse->getMouseState().buttonDown(OIS::MB_Right)) { toggleTimer = 0.5; Ogre::Light* light = mSceneMgr->getLight("PointLight"); light->setVisible(!light->isVisible()); } Compile and run your application. You should now be able to toggle the light with either the left or right mouse button. A side effect of our new method is that the light will slowly turn off and on if you continually hold the right mouse button. Moving the Ninja Now we are going to allow the user to move and turn the ninja using the keyboard. We will use the IJKL keys like the WASD keys are used for the Camera, and we will use U and O to turn the ninja. This one of the cases where we do not need to keep track of the event from the last frame, because we want the event to be processed every frame the keys are held down. The first thing we'll do is create a vector to hold the direction we want to move the ninja. Add the following to processUnbufferedInput right after the mouseDownLastFrame assignment: Ogre::Vector3 dirVec = Ogre::Vector3::ZERO; When the I key is pressed, we want the ninja to move straight forward. In the ninja's local coordinate frame, this would mean moving down the negative z-axis. if (mKeyboard->isKeyDown(OIS::KC_I)) dirVec.z -= move; For the K key, we do the same thing in the other direction to move the ninja backwards. if (mKeyboard->isKeyDown(OIS::KC_K)) dirVec.z += move; We will use the U and O keys for movement up and down. This will be along the ninja's y-axis. if (mKeyboard->isKeyDown(OIS::KC_U)) dirVec.y += move; if (mKeyboard->isKeyDown(OIS::KC_O)) dirVec.y -= move; For movement left and right, our ninja will move along its x-axis. We also want the user to be able to rotate the ninja if they are holding the left shift button. if (mKeyboard->isKeyDown(OIS::KC_J)) { if(mKeyboard->isKeyDown(OIS::KC_LSHIFT)) mSceneMgr->getSceneNode("NinjaNode")->yaw(Ogre::Degree(5 * rotate)); else dirVec.x -= move; } if (mKeyboard->isKeyDown(OIS::KC_L)) { if(mKeyboard->isKeyDown(OIS::KC_LSHIFT)) mSceneMgr->getSceneNode("NinjaNode")->yaw(Ogre::Degree(-5 * rotate)); else dirVec.x += move; } Keep in mind that these do need to be separate if statements for each key. This is because we want the user to be able to move forward and to the side at the same time. The last thing we need to do is apply this direction vector to our ninja's SceneNode. It may seem like the vector we have created will not correctly move our ninja, because surely as soon as the ninja turns a little, then his forward direction will no longer be along the z-axis, right? This is true in the coordinate system of our world coordinates (the coordinates of our root SceneNode), but it is not true for the local coordinate system of our ninja. This coordinate system moves along with the ninja so that its z-axis is always pointing straight ahead. By using this local coordinate system, we are able to translate the ninja correctly by using constant notions of direction. The SceneNode::translate method has a second parameter that allows us to choose which transformation space to use. We can choose from: TS_LOCAL, TS_PARENT, and TS_WORLD. If we use TS_LOCAL, then our direction vector will work almost perfectly. The one other thing we need to worry about is consistent movement. Different computers will render frames at different speeds. This means that any changes in our application that need to happen at a steady pace will speed up or slow down based on how fast the computer updates. This is one of the most well-known problems in graphics programming and it is solved in a large number of ways. If you want to know more, this article has become a somewhat famous discussion of the topic. To fix the problem for our application, we will simply multiply our direction vector by the amount of time that has passed since the last frame. mSceneMgr->getSceneNode("NinjaNode")->translate( dirVec * fe.timeSinceLastFrame, Ogre::Node::TS_LOCAL); This means if a relatively long period of time passes, then the ninja will be moved farther in that frame. This is what we want, because the ninja would need to make up for the longer frame time by moving a farther distance. This is one of the simplest ways of dealing with this problem, but if you read the Fix Your Timestep article, you'll learn it is not always the best idea. This becomes especially true when you are working with something like a physics engine, because when time speeds up or slows down it can really mess up your physics. Compile and run the application. You should now be able to move the ninja around with all of the keys we've defined. Conclusion This tutorial has introduced the use of unbuffered input. This is a form of input handling where the state of the input device is queried when the information is needed through the use of methods like isKeyDown. This differs from buffered input where the input events are stored in a buffer and then dealt with as a group. This type of input will be the topic of the next tutorial. The second important topic that was introduced in this tutorial was the notion of a listener class. In particular, we went into detail about Ogre's FrameListener class. After registering this class with our Ogre::Root object, its "callback methods" were automatically called every time a FrameEvent occurred. If performance is the main goal, then it is best to do updates in the frameRenderingQueued callback method, because we want our CPU to have things to do while our GPU blocks to swap all of the rendering buffers. Full Source The full source for this tutorial is here. Alias: Basic_Tutorial_4
https://wiki.ogre3d.org/tiki-index.php?page=Basic%20Tutorial%204
CC-MAIN-2022-05
refinedweb
2,658
54.52
Introduction to C# Introduction Overview of C# C#, pronounced c sharp, is a computer language used to give instructions that tell the computer what to do, how to do it, and when to do it. This is a universal language that, although currently mostly used on the Microsoft Windows operating system, will be also used on other operating systems like Linux, BeOS, Macintosh, etc. C# is one of the languages used in the Microsoft .NET Framework. The Microsoft .NET Framework is a library of objects that create or draw things on the computer. The C# language is used to create applications that display on a black window referred to as the DOS prompt or DOS window. Introduction to Objects An object, any object, is made of different parts. For example, a car is made of tires, doors, wires, belts, etc: In computer languages, such an object is called a class. In the C# language, everything is built as a class. Therefore, a program starts with the class keyword followed by a name. Here is an example: class Car The actual building of a class starts with an opening curly bracket "{" and ends with a closing curly bracket "}". Therefore, a class can be created as follows: class Car { } Because a class can be made of numerous parts, such as tires, doors, seats, etc, listed as sub-objects of a class, one line could become (too) crowded. Therefore, each curly bracket should be displayed on its own line: class Car { } The assignments of a program written in C# are carried in entities called methods. A method is simply a section of code that takes care of a particular detail for the functionality of the program. To create a method, you must specify its name, which starts with a letter or an underscore and can be followed by letters, digits, or underscores. The name of a method is followed by an opening and a closing parentheses. Here is an example: class Car { Drive() } A method's job is to carry a specific assignment within a program. As such, it could provide a value once the assignment has been carried. In Lesson 8, we will review the types of values that a method can provide. If on the other hand a method doesn't give back a value, then it is considered void. The type of value that a method can provide (or return) is written on the left side of the method name. An example would be: class Car { void Drive() } The assignment that a method carries is included between an opening curly bracket "{" and a closing curly bracket "}". Therefore, a method can be written as follows: class Car { void Drive() { } } Indentation is a technique of specifying where a line of code starts and where it ends. Although indentation is not part of the C# language, it makes the program easier to read. Therefore, the above lines of code can be written as follows: class Car { void Drive() { } } Note that this time, it is easier to know where the class starts and ends, and where the method starts and ends. In some occasions (we will see when and why), we will need to write a method as "static". The most regularly used method of a C# program is called Main. Therefore, the minimum you can write a program with, is as follows: class Car { static void Main() { } } A computer program is started in a regular computer file. A file for a C# program has the extension .cs. To make your programming fast, the C# language ships with many primary files that allow you to lay a foundation for your program. was released at the same time, bringing the now attractive "Windows" display). To create a program, a programmer entered the source code using a text editor (there was a text editor called EDIT; it was very cute, very basic, and very wonderful; pressed Enter (or Return). This caused the computer to produce C/C++, Pascal, Java, C#, etc, are still created and executed as if things were done at the Command Line. Command Line Understanding To be an effective programmer, it is important to know how the Command Line works because, as mentioned already, C# programs are compiled at the Command Prompt. If you know how the Command Line works, you. For example, the C# language provides a command called csc to compile a program at the command line. In the same way, when you create a program, particularly when you create a source file, you can use some options that would be used at the command prompt. other languages, C# is just a language that is used to give instructions to the computer. To make the computer understand these instructions, you need another, somehow more powerful, program. This program would receive the language's instructions in plain English and "translate" them in another language that the computer can understand. This program is. On this site, (because a program can contain as many files as necessary), .NET Framework is a program called csc. Like most other programs, it has the extension .exe. This csc name is not standard. This means that another C# compiler may have another name; csc.exe is just the name of the compiler we will use. Creating a Program On this site, we will use Microsoft Visual Studio .NET to create our programs. To use it, you have two main options. You can start from an empty project and add the necessary files, or you can create a console application using its Option. Practical Learning: Creating a Program class OrderProcessing { static void Main() { } } Namespaces. A namespace is a section of code that is identified by a specific name. The name could be anything such as somebody's name, the name of the company's department, or a city. To create a namespace, you start with the namespace keyword followed by the name of the section. Like a class, the section that is part of a namespace starts with an opening curly bracket "{" and ends with a closing curly bracket "}". Here is an example: namespace Jason { } Between the curly brackets, you can type anything that is part of the namespace. For example, you can create a class inside of a namespace. Here is an example: namespace Jason { class Airport { } } Practical Learning: Creating a Namespace namespace GeorgetownCleaners { class OrderProcessing { static void Main() { } } } Accessing Members of a Namespace After creating the necessary items in a namespace, you can use the period operator to access an item that is part of the namespace. To do this, in the desired location, type the name of the namespace, followed by a period, followed by the desired member of the namespace. Here is an example: namespace Accounting { class Departure { } } class MainClass { static void Main() { Accounting.Departure } } Namespace Nesting Imagine that you create a namespace called Accounting and many people from the Accounting department are asked to create their methods and objects only in the Accounting namespace and you may have asked the Accounting programmers not to create their methods and objects outside of the Accounting namespace. One thing you can do is to create other namespaces inside of the existing namespace. Creating a namespace inside of an existing namespace is referred to as nesting the namespace. The namespace inside of another namespace is nested. To create a namespace inside of another, simply type it as you would create another namespace. Here is an example: namespace Accounting { namespace Jason { } } In the example above, the Jason namespace is nested inside of the Accounting namespace. After creating the needed namespaces, nested or not, you can create the necessary methods and objects inside of the desired namespace. To access anything that is included in a nested namespace, you use the period operator before calling a member of a namespace or before calling the next nested namespace. Here is an example: namespace Accounting { class Payroll { } } namespace Personnel { namespace EmployeesRecords { class TimeSheet { } } namespace Benefits { class MedicalInsurance { } } } class MainClass { static void Main() { Accounting.Payroll Personnel.Benefits.MedicalInsurance Personnel.EmployeesRecords.TimeSheet } } A line of code such as Accounting.Payroll is called a statement. Every statement must be terminated with a colon. Therefore, this statement may be written as: Accounting.Payroll; The System Namespace To make programming in C# a little easier, many classes have already been created and stored in various namespaces. Each namespace in C# is used to provide a specify set of classes. The most regularly used namespace in the C# language is called System. Inside of the System namespace is a class called Console. The Console class is used to display things on the console screen also called the DOS window. The Console class contains assignments (called methods) to display information on the screen or to retrieve information from the user who types it in the DOS window. The method that is used to display text on the screen is called Write. To use the Write() method, inside of the parentheses, type the sentence between double-quotes. Here is an example: class Program { static void Main() { System.Console.Write("The Wonderful World of C# Programming"); } } Besides the Write() method, the Console class also provides a method called WriteLine(). The difference is that, after displaying something on the screen, the Write() method keeps the caret on the same line but WriteLine() transfers the caret the next line. We will see various examples of this behavior throughout our lessons. Practical Learning: Introducing Console Methods namespace GeorgetownCleaners { class OrderProcessing { static void Main() { System.Console.WriteLine("Georgetown Cleaning Services"); } } } The Using Keyword We saw that, to call an object or a method that is part of a namespace, you must "qualify" that method or object using the period operator. Instead of using this approach, if you already know the name of a namespace that exists or has been created in another file, you can use a special keyword to indicate that you are using a namespace that is defined somewhere. This is done with the using keyword. To do this, on top of the file (preferably), type using followed by the name of the namespace. With the using keyword, you can include as many external namespaces as necessary. Practical Learning: Using the Keyword using System; namespace GeorgetownCleaners { class OrderProcessing { static void Main() { Console.WriteLine("Georgetown Cleaning Services"); } } } Accessories for Coding A comment is a line or paragraph of text that the compiler would not consider when examining the by the compiler. Therefore, you can use this technique to span a comment on more than one line. Practical Learning: Creating Comments // Project Name: Exercise // Purpose: Used to process cleaning orders for customers using System; // Orders and business-related operations will be performed here namespace GeorgetownCleaners { class OrderProcessing { static void Main() { Console.WriteLine("Georgetown Cleaning Services"); } } } Command Line Options To see the name of the executable created for the above project, you can open Windows Explorer or My Computer, display the contents of the Exercise1 folder, followed by bin, and followed by debug. You would find a program called exercise1.exe By default, Microsoft Visual C# uses the name of the project to create the name of the executable of a project. In some cases, you may want to use a different name. To specify this information, you can open the properties of the project. To do this, you can click Project -> ProjectName Properties... from the main menu. Alternatively, in the Solution Explorer, you can right-click the name of the project and click Properties. Once in the properties, change the name of the Assembly Name. Practical Learning: Specifying the Name of the Executable Unsafe Code When C# was invented, one of its biggest goals was to avoid some of the difficulties of C/C++. Among them was the use of pointers for people who couldn't stand them or those who don't like or can't stand their intricacies. C/C++ uses pointers to refer to the area in memory where a value is located. C# highly avoids pointers and takes over memory management as opposed to letting the programmer take care of that aspect of an application. You can still use pointers in C# in extreme cases. To compile the application, you must indicate that you are using unsafe code. To do that, use the /unsafe modifier.
http://www.functionx.com/vcsharp2003/csharp/Lesson01.htm
CC-MAIN-2015-18
refinedweb
2,043
61.56
All Articles | Submit Article | IntroductionC# Code reviews using stylecopComparing FXCOP with StyleCopIssue of Code review using FXCOPStyleCop Code parsing logicMaking the custom rules classLet us do something practically on . Any feedbacks the below link . If you click on the downloads section you will see three setups one is the StyleCop setup which actually installs the software and the other two are CHM help files. One help file talks about the rules and other about the API exposed by StyleCop. Once you install StyleCop nothing will be seen as in start menu. When you open any project of C# and right click on the project you should see two menus in the project as shown in figure below. One which helps us select the rules i.e. the Style cop settings menu and the other which run these rules on the C# project. If you just run the style cop you should see broken rules in output window as shown in below figure Currently I can only think about two differences if any one knows more let me know so that I can update this. Many people are asking for a comparison table for these two codes review tools. FXCOP works on the actual compiled DLL. For instance a switch method shown below can be compiled to dictionary of string by the .NET compiler. Due to this we can notfor C#. StyleCop has two important concepts one is the document and the other the elements. Document is the file and elements are everything inside the file. For instance below is a simple source code which has two methods, properties and variables. So stylecop treats every thing inside the document as an element. Now let’s understand how stylecop browses through the document by implementing a custom rule in stylecop. The first thing is to import stylecop namespaces. Please ensure to give references from c:\Program files\Microsoft Style Cop folder. using Microsoft.StyleCop.CSharp; using Microsoft.StyleCop; All style cop custom rule classes should inherit from ‘SourceAnalyzer’ class. [SourceAnalyzer(typeof(CsParser))] public class MyRules : SourceAnalyzer When the style cop starts running it first hits the ‘analyzedocument’ method. So override the method and let’s put our logic in this. public override void AnalyzeDocument(CodeDocument document) {} In the analyze document we type cast the document in to CsDocument class. As we had previously said that stylecop walks through the document and then walks through each element. This it achieves by using delegates and visitor pattern. The ‘WalkDocument’ method visits the ‘VisitElement’ for every element in the source code. In case you are curios about visitor pattern you can always read the same from this article CsDocument document2 = (CsDocument)document; if (document2.RootElement != null && !document2.RootElement.Generated) { document2.WalkDocument(new CodeWalkerElementVisitor<object>(this.VisitElement), null, null); } The ‘VisitElement’ defined in the ‘WalkDocument’ method is a delegate. So we need to also define that delegate. You can see in the below code how we have defined the delegate and used the element object to check whether its method or not. If the element is a method then you can perform some logic. If there is any violation we need to add the same in to the violation collection using ‘AddViolation’ method as shown in the below snippet. private bool VisitElement(CsElement element, CsElement parentElement, object context) { if (element.ElementType == ElementType.Method) { this.AddViolation(parentElement, "MyCustomRule", "BlockStatementsShouldNotBeEmpty"); } } One of the values we pass to the rule is ‘MyCustomRule’ value. This is nothing but the XML file. Below is a sample of a GOTO sample rule. When you compile the DLL you need to ensure that this XML file is compiled as an embedded resource. <SourceAnalyzer Name="Custom ules"> “C:\Program Files\Microsoft StyleCop 4.3\” folder. If every thing is fine you should see the rules in the rules dialog box as shown in below figure. So let’s take up something practically. Let’s say we want to check if any connection object is opened it should be closed. So let’s write some good logic in the “VisitElement” delegate.The first thing we will do is define two variables ‘boolFoundConnectionOpen’ which states that the connection object is opened. Second ‘boolFoundConnectionClosed’ which indicates that the connection object is closed. bool boolFoundConnectionOpen=false; bool booFoundConnectionClosed=false; In the ‘VisitElement’ delegate we type cast the element document in to ‘CsDocument’ type and read the source in to a ‘TextReader’. CsDocument document3 = (CsDocument)element.Document; System.IO.TextReader objReader = document3.SourceCode.Read(); Ok now we look through the reader object and start reading the code. If we find a “.Open” we set the ‘boolFoundConnectionOpen’ to true. If we find a corresponding close we set ‘boolFoundConnectionClosed’ to"); } Submit Article
http://www.dotnetfunda.com/articles/article178.aspx
crawl-002
refinedweb
781
57.27
The Future of Google Chrome CmdrTaco posted more than 5 years ago | from the didn't-safari-just-poach-their-best-features dept. ... (5, Funny) Anonymous Coward | more than 5 years ago | (#26997019) Re:I know the future... (0, Troll) wisty (1335733) | more than 5 years ago | (#26997069) I can't even uninstall it, since it's Windows only (AFAIK). Re:I know the future... (0) Anonymous Coward | more than 5 years ago | (#26997155) Re:I know the future... (3, Funny) Anonymous Coward | more than 5 years ago | (#26997167) Then how did you install it in the first place? Very carefully. . . Re:I know the future... (0) Anonymous Coward | more than 5 years ago | (#26997533) Re:I know the future... (4, Insightful) Kagura (843695) | more than 5 years ago | (#26997715)... (3, Insightful) cyclocommuter (762131) | more than 5 years ago | (#26998021) Re:I know the future... (1, Insightful) crf00 (1048098) | more than 5 years ago | (#26998035)? The source code of Chromium is available freely under BSD right? I thought open source is all about the freedom to take any source code and modify until it suites you? Re:I know the future... (1) Demiansmark (927787) | more than 5 years ago | (#26998241) I used to think the same way but I think I use way too many extensions most completely for productivity and work purposes and have found the resulting performance of Firefox lacking. I've even found myself opening up IE to watch BSG or Hulu because there's an annoying skip in FF likely caused by some extension. I'm not so sure that it wouldn't make sense for me to use a browsing browser (chrome) and a production browser (FF + extensions). Of course I'm sure my situation is not really widespread among the larger internet using population and there are a number of extensions I use heavily that I'd want in my 'browsing browser' (foxmarts, twitterfox, etc). But just making the point that extensions come with a performance price and maybe there's room to actively use more than one browser. As we've seen. (4, Insightful) stonedcat (80201) | more than 5 years ago | (#26997063) As we've seen with Windows and IE.... the distinction between browser and and OS matters quite a bit. That is if you don't want to get accused of being and evil monopoly. Re:As we've seen. (4, Interesting) elrous0 (869638) | more than 5 years ago | (#26997251) Re:As we've seen. (4, Insightful) fuzzyfuzzyfungus (1223518) | more than 5 years ago | (#26997429):As we've seen. (2, Interesting) MrNaz (730548) | more than 5 years ago | (#26997661) computing" and "online OS" don't change the fact that this is not a paradigm shift so much as a widespread misperception. The so-called "browser is the OS" paradigm is simply a use case where the majority of a user's tasks are performed in a browser. Cloud computing really just describes people who use a PC for Facebook more than they use the PC for productive work with a word processor. I know what you're thinking. Yes, you, thinking "it's just a matter of time until word processors get implemented in JavaScript". Please, I beg you, go and get a vasectomy. For the sake of mankind. Re:As we've seen. (1, Insightful) Anonymous Coward | more than 5 years ago | (#26997837) It is just a matter of time. Granted, a very long time - you might be able to get away with in around five years or so, assuming you don't care about IE (which might have just caught up with where every other browser is right now). JavaScript runtimes are getting faster, as are CPUs, and browsers are becoming more and more capable. Word hasn't substantially changed since Word 97, which was 12 years ago now. It's not like the word processors of 10 years from now will have some amazing new feature that won't be possible to replicate in a web browser 10 years from now. Whether you'd actually want to do this or not is another matter entirely. Muddy-soft waters... (1) geekmux (1040042) | more than 5 years ago | (#26997847) ..:Muddy-soft waters... (1) berwiki (989827) | more than 5 years ago | (#26998041) I enjoyed that integration actually. Maybe the overhead wasn't worth it, but I thought it was convenient and pretty cool. Flame me if you must. Re:As we've seen. (4, Insightful) elrous0 (869638) | more than 5 years ago | (#26998043):As we've seen. (1) D Ninja (825055) | more than 5 years ago | (#26998285) These days it would be suicide for anyone to release an OS without built-in web capability right out of the box. ...I'm looking at you, Gentoo! Re:As we've seen. (1) kkamrani (882365) | more than 5 years ago | (#26997567) Re:As we've seen. (1) cunamara (937584) | more than 5 years ago | (#26997971) annoyed (-1) Anonymous Coward | more than 5 years ago | (#26997079) Re:annoyed (2, Insightful) bsdaemonaut (1482047) | more than 5 years ago | (#26997141) Re:annoyed (4, Insightful) Stormwatch (703920) | more than 5 years ago | (#26997159) That is UK-English, it seems TechRadar is a British site. I agree, it sounds really strange and illogical if you are used to US-English. Re:annoyed (4, Funny) daybot (911557) | more than 5 years ago | (#26997295):annoyed (3, Funny) Anonymous Coward | more than 5 years ago | (#26997359) Re:annoyed (4, Insightful) john.wingfield (212570) | more than 5 years ago | (#26997801) To be fair, we've butchered Latin as well as German. Re:annoyed (0, Insightful) Anonymous Coward | more than 5 years ago | (#26997417) Re:annoyed (0) Anonymous Coward | more than 5 years ago | (#26997703) Re:annoyed (1) john.wingfield (212570) | more than 5 years ago | (#26997783) It's a *pair* of trousers. I can't recall ever seeing anyone wearing just the one trouser, mind. Re:annoyed (5, Funny) m.ducharme (1082683) | more than 5 years ago | (#26997853) incidentally, you may be unaware of the distinction made in the UK between pants and trousers, i.e. that pants are what one wears under trousers. Re:annoyed (5, Funny) teh kurisu (701097) | more than 5 years ago | (#26998251) This is why Superman dresses as he does. He landed in America, and was told to wear his pants on the outside. Re:annoyed (3, Funny) coopaq (601975) | more than 5 years ago | (#26998343) (1) beelsebob (529313) | more than 5 years ago | (#26997873) No, but you do say "the integers are infinite", similarly, you don't say "the company google are ..." but you do say "google are ..." Re:annoyed (0) Anonymous Coward | more than 5 years ago | (#26998305) No. You don't. Singular nouns are singular. You say the integers are infinite because the "the integers" is a plural noun. Google is a singular noun so you say "the company, Google, is..." You could say "the workers at Google are..." because then you're talking about many instead of one. Re:annoyed (1) $0.02 (618911) | more than 5 years ago | (#26998139) Re:annoyed (4, Funny) fuzzyfuzzyfungus (1223518) | more than 5 years ago | (#26997457) Don't worry, nothing bad could possibly happen next. Re:annoyed (2, Funny) daybot (911557) | more than 5 years ago | (#26997789) We're gonna tax your coffee, you freeloaders! Re:annoyed (2, Interesting) Stormwatch (703920) | more than 5 years ago | (#26997511) I like how the Japanese do it: year/month/day. Re:annoyed (3, Insightful) MrNaz (730548) | more than 5 years ago | (#26997753) YES! YYYY/MM/DD makes so much more sense, as it means that you get sane sorting when ordering using a computer. DD/MM/YYYY results in a mess of dates, whereas YYYY/MM/DD always orders dates in chronological order. Re:annoyed (1) MightyYar (622222) | more than 5 years ago | (#26997885) say it that way? Americans almost always say the month first. Re:annoyed (1) socsoc (1116769) | more than 5 years ago | (#26998047) Re:annoyed (1) ultrafunkula (547970) | more than 5 years ago | (#26998073) Re:annoyed (2, Insightful) MightyYar (622222) | more than 5 years ago | (#26998253) Well, mystery solved! I love it when it is that easy :) I guess the American way is slightly lazier... "February second, two-thousand and nine" is 2 fewer words. Is that lazier or more optimized? Re:annoyed (1) smallfries (601545) | more than 5 years ago | (#26997779) It totally makes up for all that tentacle porn... Re:annoyed (0) Anonymous Coward | more than 5 years ago | (#26997825) I use that format for log-files and things like that. Easily sortable. Re:annoyed (2, Insightful) buchner.johannes (1139593) | more than 5 years ago | (#26998255) ISO standard is YYYY-MM-DD which I use for documents when I need it. Good for sorting. Re:annoyed (1) Abcd1234 (188840) | more than 5 years ago | (#26997917):annoyed (1) DSmith1974 (987812) | more than 5 years ago | (#26998113) Re:annoyed (4, Funny) hahiss (696716) | more than 5 years ago | (#26997981) Right. The US-English would render it: "Them thar Googles done been fixin' to. . . " Re:annoyed (1) Robmonster (158873) | more than 5 years ago | (#26997369) I is. Re:annoyed (1) MilesAttacca (1016569) | more than 5 years ago | (#26997439) The whole point of Chrome (5, Insightful) LeDopore (898286) | more than 5 years ago | (#26997117) (1) wlt (1367531) | more than 5 years ago | (#26997283) Re:The whole point of Chrome (5, Interesting) Aladrin (926209) | more than 5 years ago | (#26997335) (1) MrNaz (730548) | more than 5 years ago | (#26997785) If that's all they want then why don't they just re-write the Firefox JS engine and push it upstream? Isn't that what open source is all about? Nope, that explanation doesn't quite make sense to me. Re:The whole point of Chrome (3, Insightful) m.ducharme (1082683) | more than 5 years ago | (#26997995) (5, Interesting) Deag (250823) | more than 5 years ago | (#26997389):The whole point of Chrome (1) wumpus188 (657540) | more than 5 years ago | (#26997755) There used to be no debugger at all... alert(), anyone? Re:The whole point of Chrome (2, Informative) Canazza (1428553) | more than 5 years ago | (#26997891) good luck using Alert when you get an infinite loop... Re:The whole point of Chrome (0) Anonymous Coward | more than 5 years ago | (#26998165) or print() for that matter in other languages Re:The whole point of Chrome (0) Anonymous Coward | more than 5 years ago | (#26998053) Have a look at 280atlas.com Obj-j IDE built on top of AppKit/Cappuccino. I'm hoping they'll release a beta fairly soon.. guessing they want the tableview finished first. Re:The whole point of Chrome (0) Anonymous Coward | more than 5 years ago | (#26998089) IntelliJ IDEA 8 (which is actually a JAVA IDE so may be overkill for you) has full Javascript support with code completion, syntax checking and even debugging. Re:The whole point of Chrome (4, Informative) Artifex33 (932236) | more than 5 years ago | (#26998137):The whole point of Chrome (2, Informative) Anonymous Coward | more than 5 years ago | (#26998157) Try NetBeans, it has javascript autocompletion, support for popular libraries, like jQuery and various other goodies. Re:The whole point of Chrome (0) Anonymous Coward | more than 5 years ago | (#26998193) code completion, syntax checking... is slow to start up, but otherwise great for Javascript. Re:The whole point of Chrome (0) Anonymous Coward | more than 5 years ago | (#26998215) Exactly what I think. Re:The whole point of Chrome (1) LWATCDR (28044) | more than 5 years ago | (#26998243) Well I thin Chrome is part of Android. I often wonder if Google is getting too myopic. I am not sure that Browser Apps will ever replace all native apps. Maybe Google doesn't as well but their supporters really do. How Many People Even Use Chrome? (1) Logical Zebra (1423045) | more than 5 years ago | (#26997135) I ask, because I don't know of many. Additionally, it is viewed as "unsafe" for corporate use. My company will not allow us to use Chrome on our computers, but we are allowed to use IE and FireFox with impunity. Re:How Many People Even Use Chrome? (1) MightyYar (622222) | more than 5 years ago | (#26997243):How Many People Even Use Chrome? (1) john.wingfield (212570) | more than 5 years ago | (#26997849) But isn't it nice to have the choice? For a while back in the browser dark ages, on Windows you had a choice of bloated Netscape Communicator and broken Internet Explorer. Re:How Many People Even Use Chrome? (1) MightyYar (622222) | more than 5 years ago | (#26998183) No argument there... my windows box has 4 browsers currently, and while I mostly use Firefox I do fire up all of them at various times. Since I'm one of those perverse Mac users, I even occasionally use Safari :) Re:How Many People Even Use Chrome? (1) dayjn (942897) | more than 5 years ago | (#26997265) Re:How Many People Even Use Chrome? (0) Anonymous Coward | more than 5 years ago | (#26997421) i use it at my company.. screw the overzealous Windows IT guys. p.s. Having a password change policy of once every 3 months and not being able to use any of the last 24 passwords is dumb fyi. It causes sticky note passwords which is 1000x more insecure. I do (2, Insightful) ConanG (699649) | more than 5 years ago | (#26997569) I use it as my main browser. I've got a portable Firefox and (of course) IE, but I only fire them up when something isn't working right in Chrome. This is happening less and less. Re:How Many People Even Use Chrome? (5, Informative) jitterman (987991) | more than 5 years ago | (#26997963). Google sees what future web is heading to (1) Frozen Void (831218) | more than 5 years ago | (#26997143) and executed inside the content. basic distinction between the OS and the browser (1) wiredog (43288) | more than 5 years ago | (#26997153). Re:basic distinction between the OS and the browse (0) Anonymous Coward | more than 5 years ago | (#26998345) Yes, people tend to use OS as a synonym for the shell (graphical or text) or the packaging environment, where the OS is normally just the kernel and maybe its modules. <script type="text/python"> (4, Interesting) PetoskeyGuy (648788) | more than 5 years ago | (#26997175) I would rather have the browser guys work on getting something OTHER than javascript into the browsers. Javascript is getting better, but you only polish a turd so much. Re: (2, Interesting) Sir Groane (1226610) | more than 5 years ago | (#26997345), javascript is superficially pretty but deeply broken (namespaces? proper, native OO? etc.) Re: (2, Insightful) gnud (934243) | more than 5 years ago | (#26997409) The problem with javascript is still browser incompabilities, and that would not lessen with other scriping languages. I disagree (4, Informative) brunes69 (86786) | more than 5 years ago | (#26998087) The problem is people still fail to grasp the difference between Javascript and DOM and CSS manipulation.... All Javascript engines have been ECMA compliant for 5 years now. Javascript incomparability is not the problem, it is the DOM and CSS incompatabilities. Re: (1) robthebloke (1308483) | more than 5 years ago | (#26997411) Re: (0) Anonymous Coward | more than 5 years ago | (#26997915) That would be far too awesome to ever happen on this side of the mirror. Re: (0) Anonymous Coward | more than 5 years ago | (#26998341) Hey, I hate Javascript like any other, but Python? Ugh. You ain't serious, are you? JavaScript assembly language (5, Interesting) radarsat1 (786772) | more than 5 years ago | (#26997201):JavaScript assembly language (1) Samschnooks (1415697) | more than 5 years ago | (#26997293) Re:JavaScript assembly language (0) Anonymous Coward | more than 5 years ago | (#26997547) Re:JavaScript assembly language (2, Interesting) Anonymous Coward | more than 5 years ago | (#26997687) tracing). LuaJIT 2 with tracing is supposed to be out at some point here and that will probably blow the doors off everything else. Re:JavaScript assembly language (3, Funny) abigsmurf (919188) | more than 5 years ago | (#26997951) If the browser is the OS... (4, Insightful) MobyTurbo (537363) | more than 5 years ago | (#26997329) Re:If the browser is the OS... (0) Anonymous Coward | more than 5 years ago | (#26997521) And how come it can only be compiled as 32-bit code? Do they not expect 64-bit CPUs to catch on? From Re:If the browser is the OS... (2, Insightful) noob749 (1285846) | more than 5 years ago | (#26998045). Re:If the browser is the OS... (1) toQDuj (806112) | more than 5 years ago | (#26998267) because they are taking the time to do it right ...and then to release it as Beta. Oh the irony.. Re:If the browser is the OS... (0) Anonymous Coward | more than 5 years ago | (#26998125) um.. (1) $1uck (710826) | more than 5 years ago | (#26997355) Wanting it to be so and it being so are two entirely different things. Noscript - Missing Chrome feature. (0) Anonymous Coward | more than 5 years ago | (#26997639) If Google REALLY wants to help people out, they'd provide Chrome with native support for the functions that the noscript plugin gives to Firefox. Forget Javascript for a moment (1) Alzheimers (467217) | more than 5 years ago | (#26997905): (2, Insightful) circletimessquare (444983) | more than 5 years ago | (#26998111) ] Google "are"? (0) Anonymous Coward | more than 5 years ago | (#26998221) Me fail English? That's unpossible. Google is a company. "Google" is a single noun, just like "group", "family", "staff", etc. The staff is ready to work. My family is going on a picnic. The group is going to be late. Google is working on Chrome.
http://beta.slashdot.org/story/114835
CC-MAIN-2014-15
refinedweb
2,938
80.41
When I create multiple buttons for the same form in Rails, I can use the value of param[:commit] to figure out which button was pushed. How do I create multiple submit buttons for the same form in Rails? However, I have a search results page where a user can further refine the search, updating the results by selecting or deselecting facets, changing date filters, etc. I'd like to be able to trigger a form.submit() using javascript when a facet checkbox is checked/unchecked, for example. How do I pass a parameter (such as the param[:commit] mechanism) to my controller so that I know which user action triggered the refresh. I don't want to make everything a button. $('.facet').on('change', function(e) { // Do some stuff var $form = $(this).closest('form'); $form.submit(); // I want to pass in a "facet-selected" here so I know what triggered the submit }); With a controller method that looks like this def refresh_search if params[:commit] == 'facet-selected' # Do something elsif params[:commit] == 'date-range-changed' # Do something else end end Thanks so much in advance. Christy I suppose you should change form a bit, add hidden input same name as submit buttons and set it value when submit form by JS. E.g. <form> <input type="hidden" name="commit" /> <input type="submit" name="commit" value="date-range-changed" /> </form> Script var $form = $(this).closest('form'); $form.find(':hidden').val('facet-selected'); $form.submit();
http://m.dlxedu.com/m/askdetail/3/acf95b88aa9527c066932c130c042973.html
CC-MAIN-2019-04
refinedweb
244
60.55
public class Paycheck { //member varible private String name; private double hourlywage; private double hoursworked; //constructor public Paycheck(){ }//end Paycheck //methods //returns name public String getName(){ return name; }//end getName() //returns hourly wage public double getHwage(){ return hourlywage; }//end getHwage() //returns hours worked public double getHworked(){ return hoursworked; }//end getHworked //compute wage public double computeWage(){ if (hoursworked <= 40.0) return hoursworked*hourlywage; else return (hourlywage*40.0)+((hoursworked-40.0)*(hourlywage*1.5)); }//end compute wage //toString method public String toString(){ return "Name "+name+" Hours worked "+hoursworked+" Rate of pay "+hourlywage+" Amount of Paycheck "+computeWage(); }//end toString }//end PayCheck and this is my test class import java.util.Scanner; public class PaycheckTest{ public static void main (String [] args) { //create new paychecka Paycheck paychecka = new Paycheck(); // instantiate a Scanner object Scanner in = new Scanner(System.in); //add name to paycheck System.out.print("Workers Name: "); String name = in.next(); //add hourly wage to paycheck System.out.print("hourly wage: "); double hourlywage = in.nextDouble(); //add hours worked to paycheck System.out.print("hours worked: "); double hoursworked = in.nextDouble(); //print out worker info paychecka.toString(); System.out.println(paychecka.toString()); }//end main () }//end PaycheckTest i'm pretty sure i'm missing something after String name = in.next();[ but i've allready spent a couple hours on it and can't figure out what. When I run it as is I can key in the info but it the string returns null, 0.0, 0.0 I would apprecaite any pointers someone could give me. This post has been edited by grifter8875: 23 March 2009 - 01:16 PM
http://www.dreamincode.net/forums/topic/94856-reading-in-information/
CC-MAIN-2016-40
refinedweb
263
57.27
Swift 4.1 is the first minor release of Swift 4, bringing with it some useful improvements such as automatically synthesized equatable and hashable, conditional conformances, a smarter way to detect the simulator environment, and more. Make sure you have Xcode 9.3 or later then create a new playground. Let’s take a look at the top new features for this release… by hand can be annoying. Consider this code: struct Person { var firstName: String var lastName: String var age: Int var city: String } If you have two instances of Person and want to make sure they are identical, you need to compare all four of its for us – it can generate an == method automatically, which will compare all properties in one value with all properties in another, just like above. So, all you have to do now is add Equatable as a protocol for your type, and Swift will do the rest: struct Person: Equatable { var firstName: String var lastName: String var age: Int var city: String }) }(someObject): import Foundation. The introduction of conditional conformance has enabled the Swift team to take out a fair amount of code while also promoting stability, and automatic Equatable and Hashable support will definitely make our lives easier. Swift 4.2 introduces a variety of further enhancements, including derived collections of enum cases, warning and error diagnostic directives, and dynamic member look up – click here to learn what's new in Swift 4.2. There are still other big proposals on the way, including SE-0192: Non-Exhaustive Enums. But as important as those features are, this is the year Apple will, we hope, deliver ABI stability for Swift, and that’s going to be huge. Fingers crossed!.
https://www.hackingwithswift.com/articles/50/whats-new-in-swift-4-1?utm_campaign=Revue%20newsletter&utm_medium=Newsletter&utm_source=AppCoda%20Weekly
CC-MAIN-2019-30
refinedweb
286
51.82
: Final Preview In the first part of the series we created the user interface. In this second part we will implement drawing on the canvas and choosing colors. In the final part of the series we will introduce the ability to erase, to create new drawings and to save a drawing to the gallery on the user device. We will look at options you can use to enhance this app in future tutorials, including pattern fills, opacity and interaction other than touchscreen. Premium Option If you want to find a ready-made Android drawing app, with the full source code for you to look through, check out Android Drawing or other drawing apps and app templates on Envato Market. Or you could hire an Android developer on Envato Studio to create something unique for you according to your own specifications. 1. Prepare for Drawing Step 1 Last time we created a class named "DrawingView" which is a custom View for the drawing functions to take place in. We created the outline of the class declaration and a method named "setupDrawing" - we will implement this now. In your DrawingView class, add the following import statements: import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.view.MotionEvent; Next add some instance variables at the top of the class: //drawing path private Path drawPath; //drawing and canvas paint private Paint drawPaint, canvasPaint; //initial color private int paintColor = 0xFF660000; //canvas private Canvas drawCanvas; //canvas bitmap private Bitmap canvasBitmap; When the user touches the screen and moves their finger to draw, we will use a Path to trace their drawing action on the canvas. Both the canvas and the drawing on top of it are represented by Paint objects. The initial paint color corresponds to the first color in the palette we created last time, which will be initially selected when the app launches. Finally we declare variables for the canvas and bitmap - the user paths drawn with drawPaint will be drawn onto the canvas, which is drawn with canvasPaint. Step 2 In the setupDrawing method, let's instantiate some of these variables now to set the class up for drawing. First instantiate the drawing Path and Paint objects: drawPath = new Path(); drawPaint = new Paint(); Next set the initial color: drawPaint.setColor(paintColor); Now set the initial path properties: drawPaint.setAntiAlias(true); drawPaint.setStrokeWidth(20); drawPaint.setStyle(Paint.Style.STROKE); drawPaint.setStrokeJoin(Paint.Join.ROUND); drawPaint.setStrokeCap(Paint.Cap.ROUND); We will alter part of this code in the next tutorial when we implement the ability to choose brush sizes, for now we set an arbitrary brush size. Setting the anti-alias, stroke join and cap styles will make the user's drawings appear smoother. Complete the setupDrawing method by instantiating the canvas Paint object: canvasPaint = new Paint(Paint.DITHER_FLAG); This time we set dithering by passing a parameter to the constructor. Step 3 We need to override a couple of methods to make the custom View function as a drawing View. First, still inside the DrawingView class, override the onSizeChanged method, which will be called when the custom View is assigned a size: @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { //view given size } Inside this method, first call the superclass method: super.onSizeChanged(w, h, oldw, oldh); Now instantiate the drawing canvas and bitmap using the width and height values: canvasBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); drawCanvas = new Canvas(canvasBitmap); Step 4 To allow the class to function as a custom drawing View, we also need to override the onDraw method, so add it to the class now: @Override protected void onDraw(Canvas canvas) { //draw view } Inside the method, draw the canvas and the drawing path: canvas.drawBitmap(canvasBitmap, 0, 0, canvasPaint); canvas.drawPath(drawPath, drawPaint); We have not yet implemented the ability for the user to draw the Path using the drawing Paint, but once we do this will present it in the View. Each time the user draws using touch interaction, we will invalidate the View, causing the onDraw method to execute. 2. Facilitate Drawing Step 1 When the drawing View is on the app screen, we want user touches on it to register as drawing operations. To do this we need to listen for touch events. In your drawingView class, add the following method: @Override public boolean onTouchEvent(MotionEvent event) { //detect user touch } Inside the method, retrieve the X and Y positions of the user touch: float touchX = event.getX(); float touchY = event.getY(); Step 2 The MotionEvent parameter to the onTouchEvent method will let us respond to particular touch events. The actions we are interested in to implement drawing are down, move and up. Add a switch statement in the method to respond to each of these:; } Take a moment to look over this code. When the user touches the View, we move to that position to start drawing. When they move their finger on the View, we draw the path along with their touch. When they lift their finger up off the View, we draw the Path and reset it for the next drawing operation. Step 3 After the switch statement, complete the method by invalidating the View and returning a true value: invalidate(); return true; Calling invalidate will cause the onDraw method to execute. 3. Choosing Colors Step 1 Let's now implement the ability for the user to choose colors from the palette. In the app's main Activity, add the following imports: import android.view.View; import android.widget.ImageButton; import android.widget.LinearLayout; Add the following instance variable to the class: private DrawingView drawView; This represents the instance of the custom View that we added to the layout. Inside onCreate, after the existing code, instantiate this variable by retrieving a reference to it from the layout: drawView = (DrawingView)findViewById(R.id.drawing); We now have the View that is displayed in the Activity on which we can call the methods in the DrawingView class. Step 2 We set the initial paint color in the drawing View class, let's now set the user interface up to reflect and manage that. In the main Activity class, add another instance variable to represent the paint color button in the palette: private ImageButton currPaint; Inside onCreate, we now want to retrieve the first paint color button in the palette area, which is initially going to be selected. First retrieve the Linear Layout it is contained within: LinearLayout paintLayout = (LinearLayout)findViewById(R.id.paint_colors); Get the first button and store it as the instance variable: currPaint = (ImageButton)paintLayout.getChildAt(0); We will use a different drawable image on the button to show that it is currently selected: currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed)); Add this file to your app's drawables now, giving it the name "paint_pressed.xml" and entering the following shape: <layer-list xmlns: <item> <shape android: <stroke android: <solid android: <padding android: </shape> </item> <item> <shape xmlns: <stroke android: <solid android: <corners android: </shape> </item> </layer-list> This is very similar to the "paint.xml" drawable we created last time, but with a darker color around the paint. Step 3 Now we can let the user choose colors. When we created the layout last time, we listed an onClick attribute for the color palette buttons - add the method to your main Activity class now: public void paintClicked(View view){ //use chosen color } Inside this method, first check that the user has clicked a paint color that is not the currently selected one: if(view!=currPaint){ //update color } Inside the if block, retrieve the tag we set for each button in the layout, representing the chosen color: ImageButton imgView = (ImageButton)view; String color = view.getTag().toString(); We need to use the custom View class to set the color. Move to the DrawingView class now and add the following method: public void setColor(String newColor){ //set color } Inside the method, start by invalidating the View: invalidate(); Next parse and set the color for drawing: paintColor = Color.parseColor(newColor); drawPaint.setColor(paintColor); Back in your main Activity, in the paintClicked method after retrieving the color tag, call the new method on the custom drawing View object: drawView.setColor(color); Now update the UI to reflect the new chosen paint and set the previous one back to normal: imgView.setImageDrawable(getResources().getDrawable(R.drawable.paint_pressed)); currPaint.setImageDrawable(getResources().getDrawable(R.drawable.paint)); currPaint=(ImageButton)view; Conclusion You can now run the app and draw on the canvas, choosing colors to draw with. You should see the color palette buttons reflect the currently chosen color. In this tutorial we have worked through the essential features of any touch-drawing app for Android, so you should now have the basic skills to implement your own drawing functions in other apps. In the final part of the series we will implement erasing, choosing brush and eraser sizes, saving drawings and starting new drawings. ><<
https://code.tutsplus.com/tutorials/android-sdk-create-a-drawing-app-touch-interaction--mobile-19202
CC-MAIN-2021-39
refinedweb
1,497
51.07
bambu-analytics 2.0.1 Provides a simple, pluggable system for analytics in Django Provides a simple, pluggable system for analytics About Bambu Analytics Bambu Analytics provides a simple system for implementing analytics tools like Google Analytics into your Django projects, so you can track page views, goals and events. By default it supports Google’s Universal Analytics programme, but you interact with the package within JavaScript via the bambu.analytics namespace. This way, you can change analytics providers (or write your own) without changing the code within the rest of your site. This is massively a work-in-progress._analytics rather than bambu.analytics. Installation Install the package via Pip: pip install bambu-analytics Add it to your INSTALLED_APPS list: INSTALLED_APPS = ( ... 'bambu_analytics' ) Next, install the tracking middleware: MIDDLEWARE_CLASSES = ( ... 'bambu_analytics.middleware.AnalyticsMiddleware', ... ) Finally, set your Google Analytics ID: ANALYTICS_SETTINGS = { 'UniversalAnalyticsProvider': { 'ID': 'UA-XXXXXXXX-XX' } } Or, use the shortcut setting: GOOGLE_ANALYTICS_IDS = ('UA-XXXXXXXX-XX',) (This is a legacy setting that will be deprecated in a future release) Usage By default, all page views will be tracked once you include the tracking template tag in your base HTML template, like so: <!DOCTYPE html> <html> ... <body> ... {% load analytics %}{% tracking %} </body> </html> Tracking events are gathered by the middleware, as it allows trackable events to be defined server-side. For example, when you submit an enquiry form, you can add an event that will be tracked once the user is redirected to the ‘thank you’ page. The workflow - The user requests a URL - The analytics middleware adds a page-view event to its tracking list - The view for that URL is rendered, and the script containing the analytics setup code and the tracked event from step 2 is rendered - The user submits a form on the page - The view for that form calls bambu_analytics.track_event - An HTTP redirect is issued - The middleware reads the redirect and stores the tracking event in a session variable - The user’s browser is redirected to a ‘thank you’ page - When the ‘thank you’ page is rendered, the tracking event stored in the session variable are read into JavaScript and rendered All of this sounds complex, but actually means you can track events more easily and in a pluggable, product-agnostic way. It also provides the option for server-side analytics events to be tracked. In Google Analytics, the practical upshot is that it uses events rather than goals, meaning you don’t have to manually define them in your Analytics property. Tracking an event Let’s say you have a contact form. In the view that receives the form data, you want to track the successful submission of form data and then redirect the user to a page thanking them for getting in touch. from bambu_analytics import track_event, events def enquiry_form(request): # Handle submission of form data track_event(request, events.EVENT, category = u'Enquiry', action = u'Submit' ) Here, events.EVENT is a constant meaning ‘a standard event’. If you’re using a client-side analytics library (like Google Analytics), you should only track events in this way if you’re going to redirect the user back to a page that will load and render the tracking template tag. Otherwise the event will be stored in the user’s session cookie, but won’t be tracked by your provider. If you’re using a server-side provider - or you’ve written one, a: please let me know! but b: - this method should work fine. Trackable events There are four types of trackable event within Bambu Analytics, but not all of them are setup to work with Google’s Universal Analytics just yet. - events.PAGE: a page view (this is handled automatically by middleware) - events.EVENT: something of note happening on the site, that you want to measure - events.TRANSACTION: a monetary transaction - events.TRANSACTION_ITEM: part of an order (an item in someone’s shopping cart) The last two haven’t been properly hooked up to Google’s new system, but you can use the legacy provider (see below). Changing analytics provider Bambu Analytics supports the legacy (ua.js) and new (analytics.js) scripts as provided by Google. ecommerce is setup to work with the old style (ua.js), so if you need to track ecommerce events, you should change the provider via your Django settings file: ANALYTICS_PROVIDER = 'bambu_analytics.providers.google.GoogleAnalyticsProvider' Writing your own provider It’s pretty easy to write your own provider. Start by taking a look at the two classes in bambu_analytics.providers.google to see how they’re hooked up. Essentially the job of a provider is to take Python objects that refer to events and turn them into JavaScript objects and function calls that your analytics library can understand. Each provider needs to render a string. For client-side analytics tools this should contain HTML with a <script> tag. The first thing inside that tag should be: {% include 'analytics/bambu.inc.js' %} This exposes the bambu.analytics namespace. After all the code needed to hook up the analytics tool and track basic events, your provider should bind to the track event within bambu.analytics like this: bambu.analytics.on('track', function(e) { // e.event contains the name of the event, which you can compare // against the constants in the bambu.analytics namespace (they're) // the same as the ones within the Python package. // e.args contains a dictionary of arguments that you can use to map // the Python-defined keyword args (like 'category' or 'option_value') // to arguments that your specific analytics library understands. See // the templates/analytics/universal.inc.html file for an idea of // how this works. } ); This way you can write an analytics provider that works on all sites that use Bambu Analytics. Both of them! Writing a server-side provider If you want to track your own events or you have a server-side analytics tool that you want to hook into, you’ll write a provider that focuses on teh back- rather than front-end. You’ll still need to render something, but this can be an empty string, or some sort of tracking pixel if that’s the route you want to go down. AJAX and client-side tracking If you want to track events client-side, or you’re running a site that uses a lot of AJAX (like Poddle.fm), you’ll get automatic access to the bambu.analytics namespace within JavaScript, and you can call track() to handle client-side events or AJAX page updates (ie: via window.pushstate). Here’s an example event used on Poddle.fm when a user clicks the Play button on an episode of a podcast: <script> $('a.btn-play').on('click', function() { // Play the audio ... // Track the click event bambu.analytics.track( bambu.analytics.EVENT, { category: 'Audio', action: 'play' } ); } ); </script> Todo - Implement ecommerce into the Universal Analytics provider Questions or suggestions? Find me on Twitter (@iamsteadman) or visit my blog. - Author: Steadman - Categories - Package Index Owner: iamsteadman - DOAP record: bambu-analytics-2.0.1.xml
https://pypi.python.org/pypi/bambu-analytics/2.0.1
CC-MAIN-2016-50
refinedweb
1,165
54.63
(Relevant code below, .cpp and .h attached) Funny title, I know, but that's what it seems to be doing. OK, explanation: I'm supposed to read in a fictitious list of teachers from a text file, which contains: name, availability and courses they are qualified to teach. I also create an array of binary search trees, each one representing a subject. I put the teachers' names in an array names[], sort the array, then insert the int corresponding to the names array in the subjects[] array if they are qualified for that course. So far, so good, I think. The problem is two-fold: 1) When I traverse the trees and cout the node->key values, it turns out that they are a bit off. For example, the key values are initially 3 4 6 |0 3 6 7| 1 3 7 9| 0 1 2 5 9| 0 3 4 5 7 8| 0 2 4 5 7 8 9 , then when using traversal to find them (inorder traversal, MorrisInorder, to be specific), they become (no bars here for separation, because I don't know what it is doing) 3 4 6 6 4 3 7 6 3 0 9 7 3 1 9 5 2 1 0 8 7 5 4 3 0 9 8 7 5 4 2 0. Not only that, after applying my break-it-down-into-an-array-and-send-it-back function, they are a tiny bit more off. Maybe I did some fuzzy math with the multiplication and modulus division? Looks right to me. Which brings me to the second problem: 2) I broke the elements off of the tree into an array because I need to balance the tree, and in order to do that, need to put the elements in an array. I have a nice balance() function from my textbook, but it doesn't give details about the function. Specifically: what do the ints 'first' and 'last' represent? I can pass it the array easily enough, but what the heck are the other two arguments?: Function for putting node->keys in an array and deciphering on the other end w/modulus divisionFunction for putting node->keys in an array and deciphering on the other end w/modulus divisionCode:template<class T> void BST<T>::balance(T data[], int first, int last) { if (first <= last) { int middle = (first + last)/2; insert(data[middle]); balance(data,first,middle-1); balance(data,middle+1,last); } } and here's how I decipher it when it comes back as a big int:and here's how I decipher it when it comes back as a big int:Code:template<class T> int BST<T>::MorrisInorder() { char myArr[50]; char b[2]; BSTNode<T> *p = root, *tmp; static int y = 1; static int total = 0; while (p != 0) if (p->left == 0) { cout << p->key; p->key *= y; p = p->right; } else { tmp = p->left; while (tmp->right != 0 &&// go to the rightmost node of tmp->right != p) // the left subtree or tmp = tmp->right; // to the temporary parent of p; if (tmp->right == 0) { // if 'true' rightmost node was tmp->right = p; // reached, make it a temporary p = p->left; // parent of the current root, } else { cout << p->key << " "; // else a temporary parent has been p->key *= y; y *= 10; total += y; // found; visit node p and then cut tmp->right = 0; // the right pointer of the current p = p->right; // parent, whereby it ceases to be } // a parent; } return (total); system("PAUSE"); } I've tried program tracing, but I can't tell where the error is, or why it happens. Any help would be greatly appreciated.I've tried program tracing, but I can't tell where the error is, or why it happens. Any help would be greatly appreciated.Code:int myIntArray[50]; for(int z = 0; z < 6; z++) { int v = 0; int w = 0; int aa = 10; int myInt = subject[z].MorrisInorder();//combined with balance function while(aa < 10*myInt) { myIntArray[w] = myInt%aa; myInt = myInt%aa; aa *= 10; w++; v++; //balance.myIntArray()?????????? //insert myIntArray el's int ab = 0; while(myIntArray[ab] >= 0 && myIntArray[ab] <= 9) { subject[z].insert(myIntArray[ab]); ab++; } } } Thanks, -Patrick
http://cboard.cprogramming.com/cplusplus-programming/85969-tree-traversal-eating-creating-elements.html
CC-MAIN-2015-06
refinedweb
706
64.24
Downloading Java with Java - the Longest Journey I want to share my experiences on downloading JDK with Java from Oracle.com. Yes, I needed to automatize the site navigation a user needs to do to download Java - there are several scenarios, some of which require logging into Oracle account. The title may sound provocative, and it was not funny at all, but in the end I managed to download the JDK with Java and the result is shared at GitHub. The whole process of installing Java apps has always been annoying for both a developer and an end user, and the goal of this article is to show less painful approach to auto install the JDK. It is by the way used in author's remote automation tool Bear. When downloading the latest stable version of JDK from Oracle.com, a user will require only two clicks: In this article I will only highlight the most interesting moments of solving this task with Java, if you have any question, leave them in the comment section below and I will answer and update the article. The result are a few lines of code to download the JDK: import static bear.fx.DownloadFxApp.*; public static void main(String[] args){ version = "7u51"; tempDestDir = new File("."); miniMode = false; // mini-mode hides the browser window launchUI(); DownloadFxApp downloadFxApp = getInstance().awaitDownload(1, TimeUnit.HOURS); DownloadFxApp.DownloadResult r = downloadFxApp.downloadResult.get(); downloadFxApp.stop(); System.out.println("Downloaded to: " + r.file.getPath()); } There are no publicly available JDK archives on the net, because Oracle's license prohibits it, though Java is considered being an open platform. Which is a strange thing, Oracle. This article contains a small portion of criticism for Oracle which is initially meant to be constructive. Being a Java Developer for 8+ years already, I really want to avoid any sort of confrontation when I highlight Oracle misses. Which Approach or Technology to Choose? I found two existing open source solutions which download JDK from Oracle's site: - (Ruby) capistrano-jdk-installer - (Java) JDKInstallerin Jenkins Sources The first approach is in Ruby which I tried to mimic by using both HttpClient and Mechanize. This approach has a dependency on a pre-populated list of JDKs urls placed on Jenkins site. And you also need to login into Oracle's site to download older releases. While implementing this I had issues with SSL certificates support and not being logged in for sequential request. From my practice such solutions usually just don't work or require too much maintainence, so I decided to move on with something less confusing. Which is browser emulation. Of course! You can always download a file as if it was a user download who browsed the site, entered his data, filled the forms, read the yadayada. -1 to Oracle for filling out the forms, the UI of 90s and really messy experience while downloading JDK of a previous version. Another -1 Oracle receives for blocking my account. :-) Don't worry, this most probably won't happen to you - I just had too many debug sessions. Updating in time is nice, but in most situations is not the case when your code goes live. Selenium WebDriver is fine and stable, but gives a lot of dependencies and might not be an option for a project which is not using it. So my choice was WebView from JavaFX 2. Using WebView WebView is a simple component in JavaFX which is based on WebKit browser and can be used to browse web pages. In Java 8 WebView received a new fast JavaScript engine called Nashorn which is up to x20 times faster than Rhino from Java 7, so the whole browsing experience is very smooth and indistinguishable from a regular browser like Chrome or Firefox. (Ok, +5 to Oracle for Nashorn, -1 for lacking JSR-221 integration in a WebView out-of-the box) My thoughts on WebView vs JavaFX? Nowadays desktop apps seem a bit outdated, so I'm confused with Oracle updating Swing to JavaFX 2. Why can't they use WebView to render modern web UI technologies like Backbone or AngularJS and bind them to the app? For example, Bear uses JavaFX to render a local web page UI, so instead of using JavaFX 2 components, it uses AngularJS and Twitter Bootstrap. When this becomes a mainstream and desktop/web apps are transparent for the developer (i.e. you write your UI app for a server and this code could also be run locally), why would anyone want to hire a JavaFX developer to create some crazy FXML forms when he could build his app based on a more productive JavaScript UI stack? How many times this would be cheaper? 2, 5, 10? I really hope Oracle would consider focusing on the modern web which grows so rapidly. The algorithm Below is the workflow scheme for traversing the download pages and filling registration forms. The entry point is a page The Latest JDK Version Page or Oracle Java Archive. Some of the elements of this scheme are described below in more detail. SimpleBrowser I developed a SimpleBrowser component which is a wrapper for WebView. At the moment SimpleBrowser adds the following features to WebView: useFirebug- embed Firebug Lite panel useJQuery- embed jQuery when loading a page load(url, callback)- opens a page and runs a callback when it is ready getHTML()- get HTML of a current page createWebView- WebView is an optional visual component, this enables a WebEngine-only mode. In Java 8 however one is still required to start the stage and there is a feature request in JavaFX tracker to make JavaFX available for headless environment waitFor()- waits for a jQuery condition to become true, i.e. an element to appear - Logging via JavaScript's alert()'s Getting links from a web page This is simple when you have jQuery - just add a function which uses jQuery selectors to visit DOM tree nodes and return the link found: browser.getEngine().executeScript( scriptText() + "\n " + // adds function definitions "downloadIfFound('" + version + "', true, 'linux');" ); The source of the scriptText() is at the GitHub. Note that this script is quite long and it is not really efficient to compile it for each Java-to-JS call, but it's ok for less demanding tasks or demonstration purposes. Clicking a link I copied code from this Stackoverflow.com answer: How to simulate a click with JavaScript? clickIt would click a result of a jQuery selector, which would spawn navigation events for WebEngine. var clickIt = function($el){ var el = $el[0]; var etype = 'click'; clickDom(el, etype); } var clickDom = function(el, etype){ if (el.fireEvent) { el.fireEvent('on' + etype); } else { var evObj = document.createEvent('Events'); evObj.initEvent(etype, true, false); el.dispatchEvent(evObj); } } Embedding jQuery To embed jQuery (or any other library) into existing page one requires only to add a <script ...> entry to the <head ...> node, which is easy with JavaScript. The problem is that this script is loaded asynchronously, so I needed to provide a Java callback which is called from JavaScript when the script loads. There could also be a problem of too frequent sequential loads, so there is a queue which would store callbacks with their eventIds and fire them when the script loads inside a web page for a given initial eventId. A short version of a page load schema is shown below. Note: this is all hidden for the user of SimpleBrowser. void SimpleBrowser::load(url, Runnable onLoad) { int eventId = random.nextInt(); webEngine.load(url); whenPageLoaded({ jQueryLoads.put(eventId, load); if(useJQuery) embedJQuery(eventId); } as Runnable); } void SimpleBrowser::embedJQuery(int eventId){ webEngine.executeScript("insertNode($eventId);"); }; //JavaScript: var insertNode = function(eventId){ var scriptNode = ...; // inserts a script node scriptNode.onload = function(){ // run a callback on a Java side window.simpleBrowser.jQueryReady(eventId); } } Following redirects WebView does this for you, however I don't know if it's a bug, but I was unable to wait for a page to load after a redirect in a normal way. So I added SimpleBrowser::waitFor which waits in a separate Thread for element to appear based on jQuery condition, i.e. $('#id').length > 0. Logging I found two ways to log JavaScript and both at the moment are more of a joke, -1 to WebView (+10 to WebView for otherwise great and unique technology). The first one is to use 3rd-party FirebugLite's console. Though this extension is awesome, I didn't like working with it at all in conjunction with WebView. The latest 1.4 version just didn't work for me, in some cases you spend a couple of hours almost crying "Firebug panel, please come back!", -1 to Oracle for emotional abuse. Oh, just kidding. The other one is to define an alert event handler for WebEngine and use alert() to log in JS. It works well, but guys, seriously? Downloading a file Download starts when there is a location property change event for WebEngine, which provides the download location. I use Apache's HttpClient library and I also start a separate thread to download JDK. A bar shows the download progress: Points of Interest In this article I showed how to work with WebView to load pages, embed external JS libraries into a page, click links and wait for content to appear. One of the messiest thing in this process was debugging the states of WebView, understanding the states of WebEngine to load the pages and finding problems when having heap dumps. I.e. in situations when you make something illegal - like calling a Java method with a bad argument in JavaScript or weird bugs like calling a method of GC-ed object (this is my guess for the type of bugs I did not understand). Pieces of this code could be used as a basis for a library which could be built upon WebView. I am really happy that in the end I was able to simplify such a challenging task as downloading Java with Java.
http://chaschev.github.io/blog/downloading-java-with-java/
CC-MAIN-2019-47
refinedweb
1,666
61.56
_________________________________________________________________ Name,Name (in) Name of command. Tcl Last change: 8.0 1 Tcl_ObjCmdProc *proc (in) Implementation of the new com- mand: proc will be called when- ever com- mand, returned by previous call to Tcl_CreateObjCommand. The command must not have been deleted. Tcl_CmdInfo *infoPtr (in/out) Pointer to structure con- taining various information about a Tcl com- mand. Tcl_Obj *objPtr (in) Object contain- ing the name of a Tcl command. _________________________________________________________________ Tcl_CreateObjCommand defines a new command in interp and associates it with procedure proc such that whenever name is invoked as a Tcl command (e.g., via a call to Tcl_EvalObjEx) Tcl Last change: 8.0 2 command, objc giving represen- tation Tcl Last change: 8.0 3 the command, and in the case of TCL_ERROR this gives an error message. Before invoking a command procedure, Tcl_EvalObjEx sets interpreter's result to point to an object representing an empty string, so simple commands can return an empty result by doing nothing. However, if the existing command was created by a previous call to Tcl_CreateCommand, Tcl_CreateObj inter- preter. Once the call completes, attempts to invoke cmdName in interp will result in errors. If cmdName is not bound as a command in interp then Tcl_DeleteCommand does nothing and returns -1; otherwise it returns 0. There are no restric- tions on cmdName: it may refer to a built-in command, an application-specific command, or a Tcl procedure. nothing and returns -1; otherwise it returns 0. Tcl Last change: 8.0 4 Tcl_GetCommandInfo checks to see whether its cmdName argu- ment_CreateObjCommand was called to register the command; it is 0 if only Tcl_CreateCommand was called. It allows a pro- gram- Data hold information about the string-based command pro- cedure that implements the command. If Tcl_CreateCommand; other- wise, Tcl Last change: 8.0 5. Other- wise, different is. Tcl_GetCommandFromObj returns a token for the command speci- fied by the name in a Tcl_Obj. The command name is resolved relative to the current namespace. Returns NULL if the com- mand is not found. Tcl_CreateCommand, Tcl_ResetResult, Tcl_SetObjResult bind, command, create, delete, namespace, object Tcl Last change: 8.0 6
http://uw714doc.xinuos.com/cgi-bin/man?mansearchword=Tcl_DeleteCommand&mansection=3tcl&lang=en
CC-MAIN-2020-29
refinedweb
355
57.57
I'm having some problems with a piece of python work. I have to write a piece of code that is run through CMD. I need it to then open a file the user states and count the number of each alphabetical characters it contains. So far I have this, which I can run through CDM, and state a file to open. I've messed around with regular expressions, still can't figure out how to count individual characters. Any ideas? sorry if I explained this badly. import sys import re filename = raw_input() count = 0 datafile=open(filename, 'r') I'd stay away from regexes. They'll be slow and ugly. Instead, read the entire file into a string, and use the built-in string method count to count the characters. To put it together for you: filename = raw_input() datafile=open(filename, 'r') data = datafile.read() datafile.close() # Don't forget to close the file! counts = {} # make sure counts is an empty dictionary data = data.lower() # convert data to lowercase for k in range(97, 123): # letters a to z are ASCII codes 97 to 122 character = chr(k) # get the ASCII character from the number counts[character] = data.count(character) Then, you have a dictionary counts containing all the counts. For example, counts['a'] gives you the number of as in the file. Or, for the entire list of counts, do counts.items(). The Counter type is useful for counting items. It was added in python 2.7: import collections counts = collections.Counter() for line in datafile: # remove the EOL and iterate over each character #if you desire the counts to be case insensitive, replace line.rstrip() with line.rstrip().lower() for c in line.rstrip(): # Missing items default to 0, so there is no special code for new characters counts[c] += 1 To see the results: results = [(key, value) for key, value in counts.items() if key.isalpha()] print results If the file is small enough to be read all at once, it's very easy indeed: from collections import Counter filename = raw_input() with open(filename) as f: data = f.read() counter = Counter(data.lower()) print('\n'.join(str((ch, counter[ch])) for ch in counter if ch.isalpha())) If you want to use regular expressions, you can do as follows: pattern = re.compile('[^a-zA-Z]+') # pattern for everything but letters only_letters = pattern.sub(text, '') # delete everything else count = len(only_letters) # total number of letters For counting the number of distinct characters, use Counter as already adviced. Regular expressions are useful if you want to find complex patterns in a string. Because you want to count (as opposed to find) simple (just single alphabetic characters) “patterns”, regular expressions are not the tool of choice here. If I understand correctly what you are trying, the most transparent way to solve this is to iterate over all lines, and to iterate over all characters in that line, and if that character is alphabetic, add 1 to a corresponding dictionary entry. In code: filename=raw_input() found = {} with open(filename) as file: for line in file: for character in line: if character in "abcdefghijklmnopqrstuvxyz": # Checking `in (explicit string)` is not quick, but transparent. # You can use something like `character.isalpha()` if you want it to # automatically depend on your locale. found[character] = found.get(character, 0)+1 # If there is no dictionary entry for character yet, assume default 0 # If you need e.g. small and capital letters counted together, # "Normalize" them to one particular type, for example using # found[character.upper()] = found.get(character, 0)+1 After this loop has run through the file, the dictionary found will contain the number of occurences for each character.
http://www.dlxedu.com/askdetail/3/7e629a16c7c4db4dbf42b2160df4bb79.html
CC-MAIN-2018-39
refinedweb
616
65.52
By default, the LoopBack User model manages all users in a global namespace. It does not isolate different applications. In some cases, you may want to partition users into multiple namespaces so that different applications have separate users. LoopBack uses realms to support: - Users and applications belonging to a single global realm (or no realm). - Distributing users and applications to multiple realms. A user or application can belong to only one realm. Each realm can have many users and many applications. - Each application is a unique realm and each user belongs to an application (via a realm). Each application or user instance still has a unique ID across realms. When an application/user is signed up, it can be assigned to a realm. The User.login() function: - Honors the realm property from the user credential. - Allows the realm to be extracted from the prefix of username/email. Two settings in the User model control the realms: realmRequired(Boolean): Default is false. realmDelimiter(string): If configured, the email or username can be prefixed as <realm><realmDelimiter><username or email>, for example, myRealm:johnor myRealm:john@sample.com. If not present, no prefix will be checked against username or email. For example, server/model-config.json "User": { "dataSource": "db", "options": { "realmRequired": true, "realmDelimiter": ":" } }, When realms are enabled, you must provide a realm property when you call User.create(), for example: User.create({ realm: 'myRealm', username: 'john', email: 'john@sample.com', password: 'my-password' }, callback); To login a user within a realm, the credentials should include the realm property too. User.login({ realm: 'myRealm', username: 'john', password: 'my-password' }, callback); If the realmDelimiter is configured (for example, to “:”), the login allows the realm to be passed in as prefix to the username or email. User.login({ username: 'myRealm:john', password: 'my-password' }, callback);
https://loopback.io/doc/en/lb3/Partitioning-users-with-realms.html
CC-MAIN-2021-31
refinedweb
300
58.79
Charles Brian Quinn One of the things that excites me the most about Swift is the additional toolset it provides to write code with fewer bugs. This is not just pie-in-the-sky thinking: earlier today, I fixed a bug (that I had introduced) in an app written in Objective-C; that bug would not have been possible to introduce in the first place with the stronger static typing of Swift. There are a lot of features in Swift that fall into this camp: typed arrays and dictionaries, optionals and more. But perhaps even more intriguing are the possibilities that we can build on top of those features to change “things I have to worry about” in Objective-C into “things I can let the compiler worry about” in Swift. Let’s tackle something that’s always messy: thread safety. Suppose we’re writing a class that includes, among other things, an array of things ( Array<T>) and a timestamp ( NSDate) of when that array was last modified. For the sake of brevity, let’s limit the class to just “append an item to the array” and “get the last-modified timestamp”: class ArrayTracker<T> { private var things: [T] = [] private var lastModified: NSDate? // ... various other properties // Append an item to the array, returning a tuple of the modification // time we just saved and a count of the number of things in the // array. func appendToThings(item: T) -> (NSDate, Int) { things.append(item) lastModified = NSDate.date() return (lastModified, things.count) } // Get the timestamp of when last modified the array. // Returns nil if the array has never been modified. func lastModifiedDate() -> NSDate? { return lastModified } // ... various other methods } This covers the basic interface of our array tracker: we can append something to the array (getting back the new “last modified” time and the new number of things in the array), and we can get the “last modified” time (if there is one). You could imagine several other interesting things: get the last item in the array (doesn’t change lastModified), remove an item from the array (does change lastModified), etc. But now here’s the catch: We want ArrayTracker to be thread-safe, and to allow multiple concurrent readers, but only one writer at a time (and a writer should get exclusive access—all readers are blocked while a writer is active). First up, we need a lock. We want a readers-writer lock, which is a lock that can be acquired by multiple readers simultaneously, but can only be acquired by a single writer. There are lots of different ways to implement such a lock (on top of GCD, or using low-level atomics, or a variety of other means), but let’s not get bogged down in the details—that can be left as an exercise for you, dear reader. Instead, we’ll define a protocol that describes the interface we want our lock to satisfy. Sticking with the theme of letting the compiler do things for us, let’s avoid having lock() and unlock() methods that we have to remember to call at the right times, and instead have the lock implementation run a block that we provide: protocol ReadWriteLock { // Get a shared reader lock, run the given block, and unlock mutating func withReadLock(block: () -> ()) // Get an exclusive writer lock, run the given block, and unlock mutating func withWriteLock(block: () -> ()) } These functions are marked as mutating because one could imagine some particular lock implementation being a struct with some internal state that needed to be modified in order to take and release locks. Assuming we have a lock implementation that satisfies this protocol (we’ll call it MyLock), what does our thread-safe version of ArrayTracker look like? Omitting things that haven’t changed: class ArrayTracker<T> { // ... existing properties private var lock: ReadWriteLock = MyLock() func lastModifiedDate() -> NSDate? { var date: NSDate? // withReadLock runs the block its given synchronously, so we // don't need to capture self - use unowned lock.withReadLock { [unowned self] in date = self.lastModified } return date } func appendToThings(item: T) -> (NSDate, Int) { // we know we're going to set these before we return them, but we // don't have a reasonable default value; we'll use // implicitly-unwrapped optionals var date: NSDate! var count: Int! lock.withWriteLock { [unowned self] in self.things.append(item) self.lastModified = NSDate.date() date = self.lastModified count = self.things.count } return (date, count) } // ... rest of class } So far, so good. Now our two methods (plus many more that have been elided—you’re still keeping them in mind, right?) are thread-safe. However, the implementations look a little messy: in both, we have to create local variables, assign to them from inside the block, then return them. There’s got to be a better way. Everything we’ve done so far could have been done almost exactly the same way in Objective-C (aside from items being a generic array), but now let’s move on to something we can’t do. Instead of having to capture values within the “lock blocks,” what if we give those blocks the ability to return arbitrarily-typed things? Let’s modify our lock protocol: protocol ReadWriteLock { // Get a shared reader lock, run the given block, unlock, and return // whatever the block returned mutating func withReadLock<T>(block: () -> T) -> T // Get an exclusive writer lock, run the given block, unlock, and // return whatever the block returned mutating func withWriteLock<T>(block: () -> T) -> T } Now we can clean up our class: func lastModifiedDate() -> NSDate? { // return the result of the call to withReadLock... return lock.withReadLock { [unowned self] in // ... which is the date that we want return self.lastModified } } func appendToThings(item: T) -> (NSDate, Int) { return lock.withWriteLock { [unowned self] in self.things.append(item) self.lastModified = NSDate.date() return (self.lastModified!, self.things.count) } } Much better! We no longer have to declare local variables before the “lock blocks,” set them inside and then return them. Now we have a nice, clean way of protecting access to data behind a lock. That’s great—there’s a lot to be said for readable code, and our thread-safe versions of these methods are only two lines longer than the original, unsafe versions (and one of those lines is just an extra closing brace). However, let’s go back to what we really want to accomplish: how can we get the compiler to enforce things that, in Objective-C, we typically have to reason out ourselves? Having pretty locking mechanisms are great, but we still have to worry about the locking. We have to make sure we never access things or lastModified outside of a lock. If the class is big or has a lot of other moving parts, that can become difficult to keep track of. What we really want is to get the compiler to enforce that we only access those data while we are holding the lock. We want to make lastModified and things impossible to access without locking, which will require moving them out of ArrayTracker and into something else. Let’s define that something else: // Protector holds onto an item of type T, and only allows access to it // from within a "lock block" class Protector<T> { private var lock: ReadWriteLock = MyLock() private var item: T // initialize an instance with an item init(_ item: T) { self.item = item } // give read access to "item" to the given block, returning whatever // that block returns func withReadLock<U>(block: (T) -> U) -> U { return lock.withReadLock { [unowned self] in return block(self.item) } } // give write access to "item" to the given block, returning whatever // that block returns func withWriteLock<U>(block: (inout T) -> U) -> U { return lock.withWriteLock { [unowned self] in return block(&self.item) } } } Whew! Let’s unpack the signature of withReadLock: withReadLock<U>is a generic method inside of a generic class. That means there are two generic types involved: Tfrom our class, and Ufrom this method. (block: (T) -> U)means withReadLocktakes as its sole parameter a block that takes a T(in particular, our protected item) and returns anything at all. -> Usays that the return type is U; that is, we return whatever the block returns. This is the same trick we used in Step 2 above, to get our lock protocol to return whatever the block we give it returns. withWriteLock is the almost the same, with the difference that the argument to block is inout, meaning the block is allowed to modify it. Time to replace lastModified and things with a protected version: // Let's define a struct to hold our protected data. This should probably // be embedded inside ArrayTracker, but that doesn't build in Beta 4. private struct Protected<T> { var lastModified: NSDate? var things: [T] = [] init() { } } class ArrayTracker<T> { // Put an instance of our protected data inside a Protector private let protector = Protector(Protected<T>()) // ... other properties, but no longer "lock", "lastModified", // or "things" func lastModifiedDate() -> NSDate? { return protector.withReadLock { protected in return protected.lastModified } } func appendToThings(item: T) -> (NSDate, Int) { return protector.withWriteLock { protected in protected.things.append(item) protected.lastModified = NSDate.date() return (protected.lastModified!, protected.things.count) } } // ... rest of class } Now we’ve freed up some mental space! It’s no longer possible for us to accidentally access lastModified or things without obtaining the lock, so we don’t have to think about it at all. Not only that, but because Protected is a struct (and therefore has value semantics), it’s now a compile-time error to try to modify the protected item inside of a read lock: // WRONG: Incorrectly try to append to things with just a read lock func appendToThingsWithReadLock(item: T) { protector.withReadLock { protected -> () in // This line fails to compile: // "Immutable value of type [T] only has mutating members // named 'append'" protected.things.append(item) // This line refuses to compile too: // "Cannot assign to 'lastModified' in 'protected'" protected.lastModified = NSDate.date() } } The protection against incorrectly using a read lock and modifying the protected value isn’t perfect. If Protected were a class instead of a struct, the last example would build without complaint (but be thread-unsafe). If Protected were a struct but contained properties that were instances of classes (i.e., reference types), we could call methods on those properties that might modify them (which would also be thread-unsafe). However, we’ve at least significantly reduced the things we have to manage ourselves. One of the most difficult problems we have as software developers is managing complexity, and Swift gives us a lot of tools to lean on the compiler for help. In this example, we could have followed most of the same steps in Objective-C, but without generics, the most natural way of writing the Protector class would have tied it tightly to ArrayTracker. Swift, much more than Objective-C, is going to reward careful, considered API design. It’s exciting to be on the ground floor: making full use of the language is going to require unlearning some patterns we’re used to, and figuring out idiomatic replacements is going to take some time and creativity. Charles Brian Quinn Daniel Ra Aaron Hillegass John Daub John Daub
https://www.bignerdranch.com/blog/locking-in-swift-helping-protect-me-from-myself/
CC-MAIN-2018-05
refinedweb
1,859
52.49
Cheers, Martin Hi Martin, We investigated the issue and I would like to mention that it can be obtained only when running the transformation from oXygen. The issue is related to the option that adds the default attributes values when parsing an XML document with a RelaxNG schema associated. When this option is enabled, the XML reader that it is provided by Oxygen to the Saxon transformer does not emmit the namespace events properly. I will add an issue to our bug tracking tool and we'll try to resolve it in Oxygen 15.2 which will be released at the beginning of 2014. Meanwhile, to avoid this problem you can disable the option 'Add default attribute values' by opening the application Options -> Preferences dialog and selecting the 'XML / XML Parser / RELAX NG' options page. Regards, Radu Radu Pisoi <oXygen/> XML Editor, Schema Editor and XSLT Editor/Debugger On 12/23/2013 18:16, Martin Holmes wrote:Hi all, I'm doing an identity transform with Saxon 9.5.1.2 (HE, PE and EE all do the same) on a TEI file with embedded examples in the Examples namespace: <TEI xmlns="" version="5.0"> [...] <div> <egXML xmlns="" valid="true"> For more information, consult the <ref target="mol:linking#linking_graphics"> guide to linking graphic content</ref>.</egXML> </div> [...] </TEI> In the output, Saxon generates unwanted namespace prefixes, like this: <_0:egXML xmlns: For more information, consult the <_0:ref guide to linking graphic content</_0:ref>.</_0:egXML> This is even though I have exclude-result-prefixes="#all", and it happens whether or not I define a prefix in the root stylesheet element for the Examples namespace. What am I missing? How would I get output that looks exactly like the input? Cheers, martin
http://www.oxygenxml.com/archives/xsl-list/201312/msg00145.html
CC-MAIN-2018-39
refinedweb
294
50.67
This action might not be possible to undo. Are you sure you want to continue? 0 The Snort Project January 6, . . . . . . Config . . . . .1 1. . . . . . . . Preprocessors . . . . . . . . . . . .12 ARP Spoof Preprocessor . . . . . . . .1 2. . . . . . . . . . . . . . . . . SSH . . . . . . . . . . . . . . . . . . .9 Frag3 . . . .1 2. . . . . . . . . . . . . . . . . . . .1 2. .2. . . . . . HTTP Inspect . . . . . . . . .10 More Information . . . . 23 23 24 24 24 25 26 26 26 26 29 37 38 41 46 51 52 55 66 69 76 77 78 80 80 94 96 99 1. . . .4 Configuring . . . . SMTP Preprocessor . . . 101 Event Filtering . . . . . . . . . . . . . . . . 2. . . . . . . . . .5. . .2. . . . . . . . . . . . . . . . . . . . . . . . .3 Decoder and Preprocessor Rules . Specifying Multiple-Instance Identifiers . . . . . . . . .14 Sensitive Data Preprocessor . . . . . . . . . . . . . . . . . . . . . . .7 2. . . . . . . . . .1. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 1. . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . 107 2. . . . . . . . . . . . 2. . . . . . . . . . . . . .5 2. . . . . . . . . . . . . . . . . FTP/Telnet Preprocessor . . . . . . . . . . . . . . . . . . .2. . . . . . .1. . .2 Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 3 . RPC Decode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8 2. . . . . . . . . . . . . . . . . . . . . . . .9. . . . . . .1. . .10 DNS . . . . 2. . . .13 DCE/RPC 2 Preprocessor . . . . . . . . . . 2. .3. . . . . . . . . . 2. . . . . . . . . . 2 Configuring Snort 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 2. . . . . . . . . . . . . . . . . . . . . . . . .2 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4. . . . . . . . . . . . . . . . . . . . . . . .5. .9. . . . . . . . . . . . . . . . . . . . .4 1. . . . . . . . 101 2. . . . . . . . . . . . . . . . . . . . . . 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. .2. 107 Preprocessor Profiling . . . . . . . . Performance Monitor . . . . . . . . . . . . . . . . . . . . . Snort Modes . . . . . . . . 2.2 1. . . . . . 2. . . . . . . . . . . . . . . . . . . . 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 2. . . . . . . . . . . . . . . . . . . . . . . . . . .4. . . . . . . .3. . . . . . . . . . . . . . . . .4. . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . Obfuscating IP Address Printouts . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . .2 2. . 100 Reverting to original behavior . . . . . . . . . . . . . . . . . . . . . . . .9. . . . . . . . . . . . . . . . . . .4 2. . . .3 2. . . .3 2. . . . . . 105 Event Logging . . . . . . . . .2. . . . . . . . . . . . . . .4. . . . . . . . . . . . . . . . . . .2. 2. . .11 SSL/TLS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . .1 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15 Normalizer . .9. . 103 Event Suppression . . . . . . . . . . . . . . . . . .9. Running in Rule Stub Creation Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Performance Profiling . . . . . . . . . . . . . . . . Stream5 .2 2. . . . . . . . . . . . . . . . . . . . . . . .2 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 2. . . . . . . . . . . . . . . . . . . . . . .5 Running Snort as a Daemon . .2. . . . . . . . . . . . . . . . . . . .1 2. .1. . . . . . . .4 Rate Filtering . . . . . . . . . . . . . . . . . . .2. . . .1 Includes . . . . . Variables . .2 Rule Profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 Event Processing . . . . . .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . sfPortscan . . . . . . 7. . . . . . . . . . . . . . . . . . .6. . . . 127 2. . . . . . . . . . . . . . . .1 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13 Log Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7 2. . . . . . . . . . . . . . . . . . .2 2. . . . . . . . . . .4 2. . . . . . . . . . . . . . . . . . . 116 alert unixsock . . . . . . . . . .2 2. . . . . . . . . . . . .12 alert aruba action . . . . . . . . . . .1 Creating Multiple Configurations . . . . . . . . . . . . . . . . . . . . . . . . . .7. . . . .6. . . . . . . . .6. . . . . . . . . .6 2. . . . 133 2. . . . . . . . . . .3 2. . . . . . . . . . . .6. . . . . . . . . .2 2. . . . . . . . . . . . . . . . . . . . .2 Configure Sniping . . . . . . . . . . . . .1 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 2. . . . . . . . . .6 Packet Performance Monitoring (PPM) . . . . . . . . . . . . . . . .1 2. . . . . . . . . . . . . .10. . . .2 Configuration Specific Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 2. . . . . . . . . . . 111 Output Modules . . . . . 127 Directives . . . . . . . . . . . . . . . . .10 alert prelude . . . . . . . 130 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133 2. . . . . . . . .10. . . . . . . . . . . . .2 Format . . . . . . . . . . . . . . . . . . . 121 2. . . . . . . . . . . . . . . . . . .6. . . . . . .11. . .11. . . . . . . . . .6. . . .1 Enabling Active Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6. . . . .6. . . . . . . 117 csv . . . . .8. . . . . . 134 4 . . . . . 125 Dynamic Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 unified 2 . . . . . . . .6. . . .8 2. . . . . . . . . . . . . . . . . . . . . . . . . .9. . . . . . . . . . . . . . . . . . . . . .7 Host Attribute Table .3 How Configuration is applied? . . . . . . .9. . . . . . . . . . . . . . . . . 130 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 alert fast . . . . . . . .9. . . . . . . . . .9 alert syslog . . . . . . . . . . . . . .6. . . . . . . . . . . . . . . . . . . . . . . . . . . .11. 119 unified . . . 133 2. .2. . . . . .8 Configuration Format . . . . . . .3 Flexresp . . . .1 2. . . . . . . . . .11 Active Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116 alert full . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 2. . . . 123 2. . . . . . . . . . . . . . . . . . .8. . . . . . . .4 React .6. . . . . . . . . . . . . .5. . . . . . . . .11 log null . . . . 130 2. . . . . . . .11. . . . . . . . . .9 Reloading a Snort Configuration . . . . . . . . . . . . . . . . . . . . 122 2. . . . . . . . . . . 128 Reloading a configuration . . . 120 2. . . .6. .7. . . . . 127 2.3 2. .3 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 log tcpdump . . . . . . .10. . . . 122 2. . 127 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 2. . . . . . . . . . . . . . . . . . . . .6. . . . . . . . . . . . . . . . . . . . . 128 2. 117 database . . . .10 Multiple Configurations . . . 128 Non-reloadable configuration options . . . . . . . . . . . . . . . . . . . .11. . . . . 123 Attribute Table File Format . . . . . . . . . . . . . 123 Attribute Table Example . . 132 2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Rule Actions . . . . . . . . . . . . . . . . . . . .3 Enabling support . . . . . . . . . . . . . . . . . .2 135 The Basics . . . .4 3. . . . .5 3. . . . . . . . . . . . . . . . . . .3 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145 depth . . .5. .2 3. . . . . . . . . . . . . . . . . . . .4. . . . . . . . .5. . . . . . . . . . . . . . . . . . . . .4 Rule Options . . .5. . . . . . . . . . . . . . .2 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5. . . 136 Port Numbers . . . . . 148 3. .2. . . . . . . . . . . . . . . . . . . . . 150 3. . . . . . . . . . . . . . . . . . . . . . . . . 147 http client body . . . . . . . . . . . . .4. . . . . . . . . . . . . . . . . . . . 139 3. . . . . . . . 150 3. . . .7 3. . . . . .6 3. . . . . . . . . . . . . . . . . . . . . . .15 http raw uri . .12 http raw header . . . . . . . . . . . . . . . . .8 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 3. . . . . . . . . .5. . . . . . . . . . . . . .5. . . . . . . . . . . . . . . . 142 metadata . . . . . . . . . . . . . . . . . 143 General Rule Quick Reference .4. . . . . . . . . . . . 147 within . . . 140 sid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7 3. . . . . . . . . . . . .2. . 135 Rules Headers . . . . . . . .3 Writing Snort Rules 3. . . . . . . . . . . . . . . . . . . . . . . 144 3. . . . .2. . . . . . . . . . . . . . . . . 143 3. . . . . . . 149 3. . 152 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4. . . . . . . . . . .2. . . . . . . . . . . . . . . . . . . . . . 140 rev . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138 General Rule Options . . . . . . . . . . . . . . . .4 3. . . . . . . . . . . . . . . . .5. . . 150 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141 priority . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . .5 Payload Detection Rule Options . .2 3. . 136 IP Addresses . . . . . . .3 3. . . . . . . . . . . . . . . . . . . . . .3 3. . . . . . . . . . . . . . . . . . . . . .4. . . . . . 137 Activate/Dynamic Rules . .2. . . . . . . . . . . . . . . . . . . . . . . 151 3. . . . . . . . .4. . . . 135 3. . . 145 rawbytes . . . . . .11 http header . . . . . . . . . . . . . . 146 distance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 3. . . .5. . . . . . . . . . . . . . . . . . . . . 146 offset . . . . . .5. . . . . . . . . . . . . . . . .14 http uri . .3 3. . . . . . . . . . . . . .5. . . . . . . . . . . . . 149 3. . . . . . . . . . . . . . . . . . . . . . . . . . 152 3. . . . . . . . 141 classtype . . . . . . . . . . . . 139 gid . . . . . . . . . . . . . . . .16 http stat code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151 3. . .4. . . . . . . . . . . . . . . . . . . . . . .10 http raw cookie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18 http encode . .5. . . . . . . . . . . . . . . . .5. . . . . . . . . . . . . . . . . . . . . .6 Rule Actions . . . . . . . . . . . . .5 3. . . . . . . . . .4. . . . . 137 The Direction Operator . . . . . . . . . .1 3. . . . . . . . . .9 content . . .5. . . . . . . . . . . . .9 msg . . . . . . . .5 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4 3. . . . . . . 144 nocase . . . . . . . . . . . . . . . . . . . . . . .13 http method . . . . . . .5. . . . . . . . . . . . . . . . . . . . . . . . . .5. . . . 139 reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 3. . .1 3. . . .5. . . . . . . . . . .17 http stat msg . . . . . . 148 http cookie . . . . . . . . 138 3. . . . . . . . .5. . . . . . . . . . . .4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135 Protocols . . . . . . . . . . . . . . . . . . . .5. . . . . . . . . . . . . . . . . .23 pcre . . . . . .38 Payload Detection Quick Reference . . . . . . . . . . . . . . . . . . . . . . . .6. . . . . . . . . . . . . . . . . . . . .6. . 156 3. . . . . . . . . . . . . . . 169 3. . . . . . . . . . . . . . . . . .33 dce iface . . . . . . . . . . . . 165 tos . . . . . . . . . . . . . . . . . . . . . .12 ack . . . . . . . .15 icode . . . . . . . . . . . 164 3. . . . . . . . . . . . . . . . . . 170 3. . . 154 3. . . . .14 itype . . . . . . . .11 seq . 164 3. . . . . . . . . . . 171 3. . . . . . . . . . . . . . . . 168 flow . . . . . . . . 164 3. . . .5. . . . . . . . . . . . . . 158 3. . . . . . . . . . . . 164 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156 3. . . . . . . .5. . . .5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6 3. . . . . . . . . . . 164 3. . . . .5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 3. . . . . . . . . . . . 160 3. . . .30 ftpbounce . . . . . . . . . . . . . . . . . . . . . . . . . . . .19 fast pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171 3. . . . . . . . .6. . . .16 icmp id . . . . . . . . . . . . . . . .5. . . . .6. . . . . . . . . . . . . .29 byte extract . . . . . . . . . . . . . . . . . . 166 ipopts . . . . . .5. . . . . . . . . . . .6. . . . . . . . . . . . . . . . . . . . . . . . . .5 3. .6. . . . . . . . . . . . . . . . . . . 155 3.5. . . . . . . . . . .21 urilen . . . . . . . . . . . . . . . . . . . . . 161 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7 3. . . . . . . . . . . . . . . . 165 3. . 159 3. . . . . . . . . . . . . . . . .2 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5. . . . . . . 153 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5. . . . . . . . . . . . . . . . . . . . 169 3. . . . . . . .5. . . . . . . . . . . . . . . . . . . . . . . . . 166 id . . . . . . .35 dce stub data . .3. . . . 170 3. . . . . . . . . . . . . . . . . . .36 ssl version . . . . .5. . . . . . . . . . . .5. . .6. . . . . . . 167 dsize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 3. . . . . . . 165 ttl . . . . . . .13 window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6. . . . . . . . . . . . . . .5. . . . .6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27 byte test . . . . . . . . . . .37 ssl state . . . . . . . . . . 162 3. . . . . . . . . .6. . . .6. . . . . . . . . . . . . . . . . 171 3. . . . . . . . . 163 3. . . .5. . . . . . . . . . . .5. . . . .5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .22 isdataat . . . . . . . . . . . .5. . . .6 Non-Payload Detection Rule Options . . . . . . . . . . . . . . . . . . . . 164 3. . . . . . . . . . . . . . . .20 uricontent . . . . . . . . . . . . . . . . . . . . . . .5. . . . . . . . .10 flowbits .6. . . . . . . . . . . . . . . . . . .9 fragoffset . . . . . . . . . . . .4 3. . . . . . . 163 3. . . . . . . . . .17 icmp seq .6. . 172 6 . . . . . .6.32 cvs . . . . . .26 base64 data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6. . .5.28 byte jump . . . . . .6. .34 dce opnum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5. . . . 168 flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18 rpc . . . . . . . . . . .6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24 file data . . . . . . . . . . 164 3. . . . . . . . . . . . . . . . . . . . . 170 3. . . . . . . . 157 3. . . . . . . . . . . . . . . . . . . . 171 3. . . . . . . . . . . . . . . . . . . . . . . .8 3. . . . . . .25 base64 decode . . . . . . . . . . . . . . . . .31 asn1 . . . . .6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167 fragbits . . . . . . . 175 react . . . . . . . . . . . .22 stream size . . . . . . . . . . . . . 172 3. .2. . . . . . . . . . . . . . . 176 replace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174 3. . . . .19 ip proto . . . . . . . . . . . . . . . . . . . . . . . .5 4 Content Matching . . . . . . . . . 172 3. .2. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176 activated by . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9. . . . .4 3. . . . . . . .7. .1 4. . . . . . . . . . .6. . . . . . . . . . . . . . . . . . 173 3. . . . . . . . . . . . . . . . . .7. . . . . . . . . .9. . . . . . . . . . . .7. 174 resp . . . . . . .2 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11 Post-Detection Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . 175 tag . . . . . . . . . . . . . . . . . . . . . . . . .10 detection filter . . . . . . . . . . . . . . . . . . . . . . . 174 session . . . . . . . . .1. .2 4. . . . . . . . . . .2 Required Functions . . . . . . . . . . . . . . . . . . . . . . . . 190 Detection Engine . 183 DynamicPreprocessorData . . . . . . . . . . . . . . . . . . 176 3. . . . . . . . . . . . . . . . . . .9. . . . . . . . . . . . . . . . . . . . . . . . . . .4 3. . . . . . . . . . . .3. 177 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7. . . 178 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 3. . . . . . . 183 DynamicEngineData . . . . . . . . . . . .3. . . . . . 176 3. . . . . . . . . . . . . . . . .3 Preprocessors . .5 3. . . Not the Exploit . . . 173 3. . . . . . . . . . . . . . . .2 3. .4 4. . . . . . . . . . . . . . 193 7 . .7.1 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . 184 SFSnortPacket . . . . .7. . 191 4. . . 178 Catch the Vulnerability. . . . . . . .3. . . . . . . . . .6. . . .1 4. . . . . . . . .3 3. . . . . . . . . .6. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9. . . . . . . . . . . . . . . . . . . . . . . . . . . .7 3. . . . . . . . . . . . . . . . . . . 191 4. . . . . . . . . . . . . . . . . . .1 Data Structures . . . . . . . . . . . . . . . . . . . .8 3. . . . . . . . . . . . . . . . 176 count . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . . . . 183 4. . . . . . . . . . . . . . . . . . . . . . . . . . . .1. . . . . . . . . . . . . . . . . . 180 183 Dynamic Modules 4. . . . . .2 Preprocessor Example .6. . . . . .6. . . . . . . . . . . . . . . . . . . . 190 Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7. . . . . . . . . . . . . . . . . . . . . . 178 Catch the Oddities of the Protocol in the Rule . . . . . . . .7. . . . . . . . . . . . . . .9 logto . . .1 4. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177 Writing Good Rules . . . . .2 4. .9. . . . . .1. . . . . . . 184 Dynamic Rules . . . .20 sameip . . . . . .2. . . . . . . . . . . . .7. . . . . . . . . . . . . .9 Rule Thresholds . . . . . . . . . .21 stream reassemble .1 3. . . . . . . 191 Rules . . . . . . . . . . . . . . . . . . . . . . . . . . .7. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178 Optimizing Rules . . . . . 184 4. . . . . . . . . . . 179 Testing Numerical Values . .7 Post-Detection Rule Options . . . . . . . . . . .5 DynamicPluginMeta . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173 3. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23 Non-Payload Detection Quick Reference .6 3. . .8 3. . . . . . . . . . . . . . . . . . .7. . . . . . 189 4. . . . . . . . . . . . . . . .3 4. . . . . . . . . . . . . . . 175 activates . . . . . . . . . . . . . . .3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3 The Snort Team . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1 5. . . . . . . . . . . . . 196 5. . . . . .1 5. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5 Snort Development 5. . . . . 197 8 . .2. 196 Detection Plugins . .2 196 Submitting Patches . . . . . . . . .3 Preprocessors . . . . . . . . . . . . . . 196 Snort Data Flow . 196 5. . . . . . . . .2 5. . . . . . . . . . 196 Output Plugins . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .2. . . . . . . . . . . . . . .2. . . If you would like to submit patches for this document. try the following: .2 Sniffer Mode First.Chapter 1 Snort Overview This manual is based on Writing Snort Rules by Martin Roesch and further work from Chris Green <cmg@snort. If you want an even more descriptive display./snort -v This command will run Snort and just show the IP and TCP/UDP/ICMP headers. the most complex and configurable configuration.1 Getting Started Snort really isn’t very hard to use. If you want to see the application data in transit.org>./snort -vd This instructs Snort to display the packet data as well as the headers. 1. do this: 9 .org> and now is maintained by the Snort Team. • Network Intrusion Detection System (NIDS) mode. which simply reads the packets off of the network and displays them for you in a continuous stream on the console (screen). 1. but there are a lot of command line options to play with. you can find the latest version of the documentation in LTEX format in the Snort CVS repository at /doc/snort_manual.e. If you have a better way to say something or find that something in the documentation is outdated. It was then maintained by Brian Caswell <bmc@snort. try this: . Small documentation updates are the easiest way to help out the Snort Project. there are a few basic concepts you should understand about Snort. nothing else. sniffer mode).tex. showing the data link layer headers. which logs the packets to disk. Snort can be configured to run in three modes: • Sniffer mode. Before we proceed. • Packet Logger mode. and it’s not always obvious which ones go together well. which allows Snort to analyze network traffic for matches against a user-defined rule set and performs several actions based upon what it sees. If you just want to print out the TCP/IP packet headers to the screen (i. This file aims to make using Snort easier for new users. drop us a line and we will update A it. let’s start with the basics. All incoming packets will be recorded into subdirectories of the log directory. the source address.. which puts it into playback mode. We don’t need to specify a home network any longer because binary mode logs everything into a single file. they are logged to a directory Note that if with a name based on the higher of the two port numbers or. these switches may be divided up or smashed together in any combination. If you just specify a plain -l switch. Packets from any tcpdump formatted file can be processed through Snort in any of its run modes. you don’t need to run in verbose mode or specify the -d or -e switches because in binary mode the entire packet is logged.168.0 class C network./log -b Note the command line changes here. not just sections of it. you may notice that Snort sometimes uses the address of the remote computer as the directory in which it places packets and sometimes it uses the local host address. you can try something like this: 10 . you need to specify a logging directory and Snort will automatically know to go into packet logger mode: . In order to log relative to the home network.) 1. The last command could also be typed out as: .0/24 This rule tells Snort that you want to print out the data link and TCP/IP headers as well as application data into the directory . you need to tell Snort which network is the home network: ./snort -dev -l . ! △NOTE both the source and destination hosts are on the home network. which eliminates the need to tell it how to format the output directory structure. Binary mode logs the packets in tcpdump format to a single binary file in the logging directory: . if you wanted to run a binary log file through Snort in sniffer mode to dump the packets to the screen./log. but if you want to record the packets to the disk. you can read the packets back out of the file with any sniffer that supports the tcpdump binary format (such as tcpdump or Ethereal). Once the packets have been logged to the binary file. Snort can also read the packets back by using the -r switch. this assumes you have a directory named log in the current directory.3 Packet Logger Mode OK.1) host. all of these commands are pretty cool. Snort will exit with an error message. If you don’t./log -h 192..1. you should consider logging in binary mode. When Snort runs in this mode.168. For example.1./snort -d -v -e and it would do the same thing. in the case of a tie. with the directory names being based on the address of the remote (non-192. and you want to log the packets relative to the 192./snort -vde (As an aside. Additionally. it collects every packet it sees and places it in a directory hierarchy based upon the IP address of one of the hosts in the datagram.168./snort -l ./snort -dev -l ./log Of course. If you’re on a high speed network or you want to log the packets into a more compact form for later analysis. There are seven alert modes available at the command line: full. Generates “cmg style” alerts. There are several other alert output modes available at the command line.conf in plain ASCII to disk using a hierarchical directory structure (just like packet logger mode). If you don’t specify an output directory for the program.conf where snort. as well as with the BPF interface that’s available from the command line./log -h 192. This will apply the rules configured in the snort. as well as two logging facilities. too.conf This will configure Snort to run in its most basic NIDS form. read the Snort and tcpdump man pages./snort -dv -r packet. It’s also not necessary to record the data link headers for most applications.conf is the name of your snort configuration file. The screen is a slow place to write data to. and packets can be dropped while writing to the display./log -c snort. Six of these modes are accessed with the -A command line switch. alert message. cmg./snort -dev -l . fast. 11 .log You can manipulate the data in the file in a number of ways through Snort’s packet logging and intrusion detection modes. The full alert mechanism prints out the alert message in addition to the full packet headers. This is the default alert mode and will be used automatically if you do not specify a mode. it will default to /var/log/snort.0/24 -l . For example.log icmp For more info on how to use the BPF interface. simply specify a BPF filter at the command line and Snort will only see the ICMP packets in the file: . One thing to note about the last command line is that if Snort is going to be used in a long term way as an IDS./snort -dvr packet./snort -d -h 192.1. console. Sends alerts to a UNIX socket that another program can listen on. Turns off alerting. if you only wanted to see the ICMP packets from the log file. so you can usually omit the -e switch.0/24 -c snort. Full alert mode. Sends “fast-style” alerts to the console (screen). the -v switch should be left off the command line for the sake of speed. The default logging and alerting mechanisms are to log in decoded ASCII format and use full alerts.1 NIDS Mode Output Options There are a number of ways to configure the output of Snort in NIDS mode.168. source and destination IPs/ports. socket. logging packets that trigger rules specified in the snort. .. 1. 1.conf file to each packet to decide if an action based upon the rule type in the file should be taken. Alert modes are somewhat more complex. syslog. These options are: Option -A fast -A full -A -A -A -A unsock none console cmg Description Fast alert mode.4 Network Intrusion Detection System Mode To enable Network Intrusion Detection System (NIDS) mode so that you don’t record every single packet sent down the wire. try this: .1.4. Writes the alert in a simple format with a timestamp.168. and none. /snort -b -A fast -c snort.168. In this case. See Section 2. For example. use the following command line to log to default (decoded ASCII) facility and send alerts to syslog: . For example: . This allows Snort to log alerts in a binary form as fast as possible while another program performs the slow actions.Packets can be logged to their default decoded ASCII format or to a binary log file via the -b command line switch.3 High Performance Configuration If you want Snort to go fast (like keep up with a 1000 Mbps connection).2 Understanding Standard Alert Output When Snort generates an alert message.conf. The third number is the revision ID.conf 12 . 1. this tells the user what component of Snort generated this alert. but still somewhat fast. For a list of preprocessor SIDs.1. we know that this event came from the “decode” (116) component of Snort.conf -A fast -h 192. If you want a text file that’s easily parsed. try using binary logging with the “fast” output mechanism. such as writing to a database.6.1. it will usually look like the following: [**] [116:56:1] (snort_decoder): T/TCP Detected [**] The first number is the Generator ID. use the following command line to log to the default facility in /var/log/snort and send alerts to a fast alert file: . The second number is the Snort ID (sometimes referred to as Signature ID). In this case. This will log packets in tcpdump format and produce minimal alerts. For output modes available through the configuration file. use the output plugin directives in snort. 56 represents a T/TCP event. as each rendition of the rule should increment this number with the rev option. you need to use unified logging and a unified log reader such as barnyard.4.168./snort -c snort. ! △NOTE Command line logging options override any output options specified in the configuration file./log -h 192. use the -s switch. The default facilities for the syslog alerting mechanism are LOG AUTHPRIV and LOG ALERT.0/24 1. see Section 2. To disable packet logging altogether.conf -l . please see etc/gen-msg. This number is primarily used when writing signatures. For a list of GIDs.map.4.0/24 -s As another example.6. If you want to configure other facilities for syslog output. please read etc/generators in the Snort source. This allows debugging of configuration issues quickly via the command line./snort -c snort. To send alerts to syslog. Rule-based SIDs are written directly into the rules with the sid option.1 for more details on configuring syslog output. use the -N command line switch. etc. The Pass rules are applied first.5. This allows use of an inline policy with passive/IDS mode. you can run Snort just as you always did for file readback or sniffing an interface.9 introduces the DAQ.5 Packet Acquisition Snort 2. • --alert-before-pass option forces alert rules to take affect in favor of a pass rule. in which case you can change the default ordering to allow Alert rules to be applied before Pass rules. then the Drop rules. ! △NOTE Sometimes an errant pass rule could cause alerts to not show up. Several command line options are available to change the order in which rule actions are taken. in that the event processing is terminated when a pass rule is encountered. or Data Acquisition library. you can select and configure the DAQ when Snort is invoked as follows: . only the events for the first action based on rules ordering are processed. The DAQ replaces direct calls to PCAP functions with an abstraction layer that facilitates operation on a variety of hardware and software interfaces without requiring changes to Snort. then the Alert rules and finally. However. 1. rather then the normal action. for packet I/O. It is possible to select the DAQ type and mode when invoking Snort to perform PCAP readback or inline operation. while taking the actions based on the rules ordering. For more information. The sdrop rules are not loaded.1. 1. Without this option (default case).4. please refer to the --alert-before-pass option. ! △NOTE Pass rules are special cases here. Log rules are applied.4 Changing Alert Order The default way in which Snort applies its rules to packets may not be appropriate for all installations. . regardless of the use of --process-all-events. • --process-all-events option causes Snort to process every event associated with a packet.1 Configuration Assuming that you did not disable static modules or change the default DAQ type. • --treat-drop-as-alert causes drop and reject rules and any associated alerts to be logged as alerts. You may include as many variables and directories as needed by repeating the arg / config. These are equivalent: . if configured in both places. the mode defaults to passive. Note that if Snort finds multiple versions of a given library. . the command line overrides the conf. If the mode is not set explicitly. DAQ type may be specified at most once in the conf and once on the command line. and attributes of each. This applies to static and dynamic versions of the same library. mode. libpcap will automatically use the most frames possible. but -Q and any other DAQ mode will cause a fatal error at start-up. 1. -Q and –daq-mode inline are allowed. and if that hasn’t been set. this ends up being 1530 bytes per frame.gov/cpw/. On Ethernet. Phil Woods (cpw@lanl.gov) is the current maintainer of the libpcap implementation of the shared memory ring buffer. if snort is run w/o any DAQ arguments. as this appears to be the maximum number of iovecs the kernel can handle. Once Snort linked against the shared memory libpcap./snort [--daq-list <dir>] The above command searches the specified directory for DAQ modules and prints type.2 PCAP pcap is the default DAQ. and if that hasn’t been set. The shared memory ring buffer libpcap can be downloaded from his website at. By using PCAP FRAMES=max. -Q will force it to inline. since there is no conflict./snort --daq pcap --daq-mode passive -i <device> . This feature is not available in the conf.<mode> ::= read-file | passive | inline <var> ::= arbitrary <name>=<value> passed to DAQ <dir> ::= path where to look for DAQ module so’s The DAQ type. Also. a modified version of libpcap is available that implements a shared memory ring buffer. variable. According to Phil./snort --daq pcap --daq-var buffer_size=<#bytes> Note that the pcap DAQ does not count filtered packets. Instead of the normal mechanism of copying the packets from kernel memory into userland memory. version. enabling the ring buffer is done via setting the environment variable PCAP FRAMES. by using a shared memory ring buffer. for a total of around 52 Mbytes of memory for the ring buffer alone. This change speeds up Snort by limiting the number of times the packet is copied before Snort gets to perform its detection upon it./snort -i <device> . libpcap is able to queue packets into a shared buffer that Snort is able to read directly. MMAPed pcap On Linux. 14 . it will operate as it always did using this module. the maximum size is 32768. -r will force it to read-file. PCAP FRAMES is the size of the ring buffer. and directory may be specified either via the command line or in the conf file./snort --daq pcap --daq-mode read-file -r <file> You can specify the buffer size pcap uses with: ./snort -r <file> .lanl. the most recent version is selected.5. default is 0 <qlen> ::= 0. 15 ./snort --daq nfq \ [--daq-var device=<dev>] \ [--daq-var proto=<proto>] \ [--daq-var queue=<qid>] \ [--daq-var queue_len=<qlen>] <dev> ::= ip | eth0. 4. default is ip4 <qid> ::= 0.65535.5./snort --daq afpacket -i <device> [--daq-var buffer_size_mb=<#MB>] [--daq-var debug] If you want to run afpacket in inline mode.. default is 0 Notes on iptables are given below. 2. etc. here’s why. we need 84733 / 2 = 42366 blocks. 3. The smallest block size that can fit at least one frame is 4 KB = 4096 bytes @ 2 frames per block. you must set device to one or more interface pairs. default is IP injection <proto> ::= ip4 | ip6 | ip*.3 AFPACKET afpacket functions similar to the memory mapped pcap DAQ but no external library is required: . As a result.. the afpacket DAQ allocates 128MB for packet memory. You can change this with: --daq-var buffer_size_mb=<#MB> Note that the total allocated is actually higher. 1.1. Actual memory allocated is 42366 * 4 KB = 165. 5.4 NFQ NFQ is the new and improved way to process iptables packets: . the numbers break down like this: 1.65535.5. The frame size is 1518 (snaplen) + the size of the AFPacket header (66 bytes) = 1584 bytes. Assuming the default packet memory with a snaplen of 1518.5 MB. The number of frames is 128 MB / 1518 = 84733. where each member of a pair is separated by a single colon and each pair is separated by a double colon like this: eth0:eth1 or this: eth0:eth1::eth2:eth3 By default. ./configure --enable-ipfw / -DGIDS -DIPFW This command line argument is no longer supported: ./configure --enable-inline / -DGIDS Start the IPQ DAQ as follows: . etc. Furthermore.5 IPQ IPQ is the old way to process iptables packets./snort -J <port#> Instead. You can optionally specify a different name. default is ip4 Notes on iptables are given below. .5.65535./snort -r <pcap> -Q --daq dump --daq-var load-mode=read-file ../snort --daq ipq \ [--daq-var device=<dev>] \ [--daq-var proto=<proto>] \ <dev> ::= ip | eth0. default is IP injection <proto> ::= ip4 | ip6.9 versions built with this: . Note that the dump DAQ inline mode is not an actual inline mode./snort -i <device> -Q --daq dump --daq-var load-mode=passive 16 .6 IPFW IPFW is available for BSD systems./snort -r <pcap> --daq dump By default a file named inline-out. It replaces the inline version available in pre-2. you will probably want to have the pcap DAQ acquire in another mode like this: .7 Dump The dump DAQ allows you to test the various inline mode features available in 2.pcap will be created containing all packets that passed through or were generated by snort./snort --daq dump --daq-var file=<name> dump uses the pcap daq for packet acquisition. It replaces the inline version available in pre-2./snort -i <device> --daq dump .5.1. start Snort like this: ./snort --daq ipfw [--daq-var port=<port>] <port> ::= 1. It therefore does not count filtered packets. 1. 1.9 versions built with this: . default is 8000 * IPFW only supports ip4 traffic.5.9 Snort like injection and normalization. Print a line saying what pcap is currently being read. The action stats show ”blocked” packets instead of ”dropped” packets to avoid confusion between dropped packets (those Snort didn’t actually see) and blocked packets (those Snort did not allow to pass).6 Reading Pcaps Instead of having Snort listen on an interface.5. eg TCP resets. however. without this option. Snort will read and analyze the packets as if they came off the wire.e. reset snort to post-configuration state before reading next pcap. Note. that specifying --pcap-reset and --pcap-show multiple times has the same effect as specifying them once. i. eg due to a block rule. The default. • Blacklist packets that caused Snort to block a flow from passing.1 Command line arguments Any of the below can be specified multiple times on the command line (-r included) and in addition to other Snort command line options.pcap $ snort --pcap-single=foo. File that contains a list of pcaps to read. • Replace packets Snort modified. Reset to use no filter when getting pcaps from file or directory. • Allow packets Snort analyzed and did not take action on. • Block packets Snort did not forward. Option -r <file> --pcap-single=<file> --pcap-file=<file> --pcap-list="<list>" --pcap-dir=<dir> --pcap-filter=<filter> Description Read a single pcap. • Ignore packets that caused Snort to allow a flow to pass w/o inspection by this instance of Snort. is not to reset state. Shell style filter to apply when getting pcaps from file or directory. Sorted in ASCII order. 1. A directory to recurse to look for pcaps. Use --pcap-no-filter to delete filter for following --pcap-file or --pcap-dir arguments or specify --pcap-filter again to forget previous filter and to apply to following --pcap-file or --pcap-dir arguments. If reading multiple pcaps. • Whitelist packets that caused Snort to allow a flow to pass w/o inspection by any analysis program. Same as -r.6.8 Statistics Changes The Packet Wire Totals and Action Stats sections of Snort’s output include additional fields: • Filtered count of packets filtered out and not handed to Snort for analysis. Added for completeness. A space separated list of pcaps to read. This filter will apply to any --pcap-file or --pcap-dir arguments following. • Injected packets Snort generated and sent.6. --pcap-no-filter --pcap-reset --pcap-show 1. Can specify path to pcap or directory to recurse to get pcaps.pcap 17 . 1.1. you can give it a packet capture to read.2 Examples Read a single pcap $ snort -r foo. This can be useful for testing and debugging Snort. txt” (and any directories that are recursed in that file).pcap” will only be applied to the pcaps in the file ”foo.cap” will be applied to files found under /home/foo/pcaps2.pcap" --pcap-dir=/home/foo/pcaps The above will only include files that match the shell pattern ”*. so only files ending in ”.pcap.cap” will be included from that directory. in other words.pcap foo2.pcap" This will read foo1. $ snort --pcap-filter="*.pcap foo2. $ snort --pcap-filter="*.txt foo1. the first filter will be applied to foo. the first filter will be applied to foo.pcap foo3.txt.pcap and all files under /home/foo/pcaps.cap" --pcap-dir=/home/foo/pcaps In the above. then the filter ”*.pcap.pcap”. then no filter will be applied to the files found under /home/foo/pcaps. then no filter will be applied to the files found under /home/foo/pcaps. The addition of the second filter ”*. foo2.pcap --pcap-file=foo.pcap foo2.txt \ > --pcap-no-filter --pcap-dir=/home/foo/pcaps In this example. foo2.pcap /home/foo/pcaps $ snort --pcap-file=foo.pcap and foo3. any file ending in ”.pcap --pcap-file=foo. so all files found under /home/foo/pcaps will be included.pcap”.txt $ snort --pcap-filter="*.Read pcaps from a file $ cat foo.pcap --pcap-file=foo. 18 . Using filters $ cat foo.txt \ > --pcap-filter="*.pcap" --pcap-file=foo.txt foo1. Read pcaps under a directory $ snort --pcap-dir="/home/foo/pcaps" This will include all of the files under /home/foo/pcaps. the first filter ”*.txt \ > --pcap-no-filter --pcap-dir=/home/foo/pcaps \ > --pcap-filter="*. $ snort --pcap-filter="*. Read pcaps from a command line list $ snort --pcap-list="foo1.txt.txt This will read foo1. so all files found under /home/foo/pcaps will be included.pcap.cap" --pcap-dir=/home/foo/pcaps2 In this example.cap” will cause the first filter to be forgotten and then applied to the directory /home/foo/pcaps. Note that Snort will not try to determine whether the files under that directory are really pcap files or not.pcap /home/foo/pcaps $ snort --pcap-filter="*. • Injected packets are the result of active response which can be configured for inline or passive modes. Snort will be reset to a post-configuration state. in which case it is shown per pcap.856509 seconds Snort processed 3716022 packets.7. • Filtered packets are not shown for pcap DAQs. but after each pcap is read.7. For each pcap.000%) 19 . unless you use –pcap-reset. Example: =============================================================================== Packet I/O Totals: Received: 3716022 Analyzed: 3716022 (100. the totals are for all pcaps combined. etc. This does not include all possible output data. Many of these are self-explanatory.7 Basic Output Snort does a lot of work and outputs some useful statistics when it is done. and only shown when non-zero. statistics reset.1 Timing Statistics This section provides basic timing statistics. • Outstanding indicates how many packets are buffered awaiting processing. 1. If you are reading pcaps. It includes total seconds and packets as well as packet processing rates. The way this is counted varies per DAQ so the DAQ documentation should be consulted for more info. etc. Snort ran for 0 days 0 hours 2 minutes 55 seconds Pkts/min: 1858011 Pkts/sec: 21234 =============================================================================== 1. The rates are based on whole seconds.Resetting state $ snort --pcap-dir=/home/foo/pcaps --pcap-reset The above example will read all of the files under /home/foo/pcaps. it will be like Snort is seeing traffic for the first time..2 Packet I/O Totals This section shows basic packet acquisition and injection peg counts obtained from the DAQ. The others are summarized below. minutes. 1. meaning all buffers will be flushed. just the basics. • S5 G 1/2 is the number of client/server sessions stream5 flushed due to cache limit.000%) IP6/IP6: 0 ( 0.3 Protocol Statistics Traffic for all the protocols decoded by Snort is summarized in the breakdown section.000%) IP4/IP6: 0 ( 0. session timeout.000%) ICMP-IP: 0 ( 0.850%) IP6 Ext: 1787327 ( 48. This traffic includes internal ”pseudo-packets” if preprocessors such as frag3 and stream5 are enabled so the total may be greater than the number of analyzed packets in the packet I/O section.166%) Frag6: 3839 ( 0.511%) Teredo: 18 ( 0.817%) 20 . session reset.773%) TCP6: 1619633 ( 43.044%) UDP6: 140446 ( 3.Dropped: 0 ( 0.000%) GRE IPX: 0 ( 0.000%) IP4/IP4: 0 ( 0.000%) Outstanding: 0 ( 0.103%) ICMP: 38860 ( 1.000%) GRE IP4: 0 ( 0.511%) IP6: 1781159 ( 47.000%) GRE VLAN: 0 ( 0.000%) IP4: 1782394 ( 47.000%) IP6/IP4: 0 ( 0.000%) EAPOL: 0 ( 0.016%) IP6 Opts: 6168 ( 0.005%) GRE ARP: 0 ( 0. • Other includes packets that contained an encapsulation that Snort doesn’t decode.685%) TCP: 1619621 ( 43.884%) Frag: 3839 ( 0.7.044%) UDP: 137162 ( 3.000%) GRE IP6: 0 ( 0.000%) GRE PPTP: 202 ( 0. Example: =============================================================================== Breakdown by protocol (includes rebuilt packets): Eth: 3722347 (100.000%) Filtered: 0 ( 0.000%) GRE Loop: 0 ( 0.005%) GRE Eth: 0 ( 0.000%) VLAN: 0 ( 0.000%) GRE IP6 Ext: 0 ( 0.000%) MPLS: 0 ( 0.103%) ICMP6: 1650 ( 0. • Disc counts are discards due to basic encoding integrity flaws that prevents Snort from decoding the packet.000%) GRE: 202 ( 0.000%) ARP: 104840 ( 2.000%) Injected: 0 =============================================================================== 1. This is the case when a block TCP rule fires. • Replace = packets Snort modified. due to normalization or replace rules. no further packets will be seen by Snort for that session.000%) S5 G 1: 1494 ( 0. and reject actions. • Ignore = packets that caused Snort to allow a flow to pass w/o inspection by this instance of Snort.037%) Other: 57876 ( 1. this is done by the DAQ or by Snort on subsequent packets. • Whitelist = packets that caused Snort to allow a flow to pass w/o inspection by any analysis program. • Block = packets Snort did not forward.000%) IP4 Disc: 0 ( 0. and Verdicts Action and verdict counts show what Snort did with the packets it analyzed.044%) Total: 3722347 =============================================================================== 1. and block actions processed as determined by the rule actions. for example. The default is 8. Verdicts are rendered by Snort on each packet: • Allow = packets Snort analyzed and did not take action on. log setting. • Blacklist = packets that caused Snort to block a flow from passing.IPX: 60 ( 0. Limits. snort will block each packet and this count will be higher.040%) S5 G 2: 1654 ( 0.4 Actions. • Log Limit counts events were not alerted due to the config event queue: • Event Limit counts events not alerted due to event filter limits. This can only happen in inline mode with a compatible DAQ. alert. Limits arise due to real world constraints on processing time and available memory.863%) Bad TTL: 0 ( 0. drop.000%) TCP Disc: 0 ( 0.000%) IP6 Disc: 0 ( 0. this is done by the DAQ or by Snort on subsequent packets. If not.000%) UDP Disc: 1385 ( 0. • Alerts is the number of activate. Like blacklist. 21 . If the DAQ supports this in hardware. eg due to a block rule. max queue events max queue • Queue Limit counts events couldn’t be stored in the event queue due to the config event queue: setting. ”Block” is used instead of ”Drop” to avoid confusion between dropped packets (those Snort didn’t actually see) and blocked packets (those Snort did not allow to pass). The default is 5.000%) All Discard: 1385 ( 0. These indicate potential actions that did not happen: • Match Limit counts rule matches were not processed due to the config detection: setting. This information is only output in IDS mode (when snort is run with the -c <conf> option).002%) Eth Loop: 0 ( 0. The default is 3. Here block includes block.000%) Eth Disc: 0 ( 0. Like blacklist.037%) ICMP Disc: 0 ( 0.7.555%) Bad Chk Sum: 32135 ( 0. 000%) Blacklist: 0 ( 0.8.000%) Match Limit: 0 Queue Limit: 0 Log Limit: 0 Event Limit: 0 Verdicts: Allow: 3716022 (100.000%) Replace: 0 ( 0. only the encapsulated part of the packet is logged.1 Multiple Encapsulations Snort will not decode more than one encapsulation./configure --enable-ipv6 1. e. IP in IP and PPTP.000%) Block: 0 ( 0. 1. an extra configuration option is necessary: $ .000%) Passed: 0 ( 0.2 Logging Currently. Eth IP1 GRE IP2 TCP Payload gets logged as Eth IP2 TCP Payload 22 .000%) Ignore: 0 ( 0.8./configure --enable-gre To enable IPv6 support. one still needs to use the configuration option: $ .000%) Whitelist: 0 ( 0.Example: =============================================================================== Action Stats: Alerts: 0 ( 0.000%) Logged: 0 ( 0.g.000%) =============================================================================== 1. Scenarios such as Eth IPv4 GRE IPv4 GRE IPv4 TCP Payload or Eth IPv4 IPv6 IPv4 TCP Payload will not be handled and will generate a decoder alert. To enable support.8 Tunneling Protocol Support Snort supports decoding of GRE. 9. is not currently supported on architectures that require word alignment such as SPARC.9.1 Running Snort as a Daemon If you want to run Snort as a daemon. you might need to use the –dump-dynamic-rules option. These rule stub files are used in conjunction with the shared object rules. you must specify the full path to the Snort binary when you start it. 1. /usr/local/bin/snort -c /usr/local/etc/snort. The PID file will be locked so that other snort processes cannot start. Snort PID File When Snort is run as a daemon .0/24 \ -l /var/log/snortlogs -c /usr/local/etc/snort. the --create-pidfile switch can be used to force creation of a PID file even when not running in daemon mode. The path can be relative or absolute. 1.6.conf -s -D Relative paths are not supported due to security concerns.9 Miscellaneous 1. 23 .and Eth IP1 IP2 TCP Payload gets logged as Eth IP2 TCP Payload ! △NOTE Decoding of PPTP. the --pid-path command line switch causes Snort to write the PID file in the directory specified. In Snort 2. the daemon creates a PID file in the log directory. Please notice that if you want to be able to restart Snort by sending a SIGHUP signal to the daemon.conf \ --dump-dynamic-rules=/tmp This path can also be configured in the snort. which utilizes GRE and PPP. you can the add -D switch to any combination described in the previous sections.2 Running in Rule Stub Creation Mode If you need to dump the shared object rules stub to a directory. Additionally. Use the --nolock-pidfile switch to not lock the PID file.168. 3 Obfuscating IP Address Printouts If you need to post packet logs to public mailing lists.168.conf: config dump-dynamic-rules-path: /tmp/sorules In the above mentioned scenario the dump path is set to /tmp/sorules. you could use the following command to read the packets from a log file and dump them to the screen./usr/local/bin/snort -c /usr/local/etc/snort.1. 1.4 Specifying Multiple-Instance Identifiers In Snort v2. you might want to use the -O switch.9.4. either on different CPUs. it acts as an IPS allowing drop rules to trigger.conf \ --dump-dynamic-rules snort. inline. This is handy if you don’t want people on the mailing list to know the IP addresses involved.9.168. obfuscating only the addresses from the 192. useful if you don’t care who sees the address of the attacking host. 1. This switch obfuscates your IP addresses in packet printouts. and inline-test. Snort can be configured to passive mode using the snort config option policy mode as follows: config policy_mode:tap • Inline-Test Inline-Test mode simulates the inline mode of snort. You can also combine the -O switch with the -h switch to only obfuscate the IP addresses of hosts on the home network./snort -d -v -r snort. allowing evaluation of inline behavior without affecting traffic. Each Snort instance will use the value specified to generate unique event IDs.9.0/24 class C network: . Drop rules are not loaded (without –treat-drop-as-alert).5 Snort Modes Snort can operate in three different modes namely tap (passive). it acts as a IDS.log -O -h 192. Snort can be configured to run in inline-test mode using the command line option (–enable-inline-test) or using the snort config option policy mode as follows: 24 . This is also supported via a long option --logid. the -G command line option was added that specifies an instance identifier for the event logs. Users can specify either a decimal value (-G 1) or hex value preceded by 0x (-G 0x11). This option can be used when running multiple instances of snort. For example. Snort policies can be configured in these three modes too.1. or on the same CPU but a different interface. The drop rules will be loaded and will be triggered as a Wdrop (Would Drop) alert. Explanation of Modes • Inline When Snort is in Inline mode.0/24 1. The Snort manual page and the output of snort -? or snort --help contain information that can help you get Snort running in several different modes. ! △NOTE In many shells. 25 .net provide informative announcements as well as a venue for community discussion and support. The Snort web page (. a backslash (\) is needed to escape the ?.snort --enable-inline-test config policy_mode:inline_test ! △NOTE Please note –enable-inline-test cannot be used in conjunction with -Q.10 More Information Chapter 2 contains much information about many configuration options available in the configuration file.theaimsgroup. so you may have to type snort -\? instead of snort -? for a list of Snort command line options.com/?l=snort-users at snort-users@lists.org) and the Snort Users mailing list:..snort. so sit back with a beverage of your choosing and read the documentation and mailing list archives. There’s a lot to Snort. 10.0/24] alert tcp any any -> $MY_NET $MY_PORTS (flags:S.1024:1050] ipvar MY_NET [192.) include $RULE_PATH/example. or portvar keywords as follows: var RULES_PATH rules/ portvar MY_PORTS [22.2 for more information on defining and using variables in Snort config files.1.1 Includes The include keyword allows other snort config files to be included within the snort. Without IPv6 support.168. ipvar.0/24. 2.conf indicated on the Snort command line.80.1. Note: ’ipvar’s These are simple substitution variables set with the var. See Section 2.1. It works much like an #include from the C programming language.1. msg:"SYN packet".1 Format include <include file path/name> ! △NOTE is no semicolon at the end of this line.1.. use a regular ’var’.1.Chapter 2 Configuring Snort 2.2 Variables Three types of variables may be defined in Snort: • var • portvar • ipvar ! △NOTE are only enabled with IPv6 support. 2.rule 26 . 1.0 to 2. but it will be deprecated in a future release.2.0/8. IP lists.2.sid:3.2.sid:2.0.1.2.x and earlier.1 and IP from 2. Also.1.2.1.1. IP variables should be specified using ’ipvar’ instead of ’var’. Using ’var’ for an IP variable is still allowed for backward compatibility. See below for some valid examples if IP variables and IP lists.0/24. sid:1.![2.!1.1.!1.0/24] any -> any any (msg:"Example".0/24.2 and 2.2. such as in: [10:50. The following example list will match the IP 1.2. Negation is handled differently compared with Snort versions 2.0.3]] The order of the elements in the list does not matter. as a CIDR block.sid:3.1. ranges. [1.) alert tcp [1. If IPv6 support is enabled.1. negated IP ranges that are more general than non-negated IP ranges are not allowed.1. Lists of ports must be enclosed in brackets and port ranges may be specified with a ’:’.1. Variables.2.1.1. but ’!any’ is not allowed. ipvar EXAMPLE [1.0/16] Port Variables and Port Lists Portlists supports the declaration and lookup of ports and the representation of lists and ranges of ports.2.2.2.3.2. and CIDR blocks may be negated with ’!’.2.2.0.255.2. each element in a list was logically OR’ed together.3]] alert tcp $EXAMPLE any -> any any (msg:"Example".2.2. although ’!any’ is not allowed.2.1.1. or lists may all be negated with ’!’. IP lists now OR non-negated elements and AND the result with the OR’ed negated elements.2.1. Valid port ranges are from 0 to 65535. Also.1] Nonsensical negations: ipvar EXAMPLE [1.0/24.) Logical contradictions: ipvar EXAMPLE [1.7.888:900] 27 .) The following examples demonstrate some invalid uses of IP variables and IP lists.!1. The element ’any’ can be used to match all IPs. in a list.2. or any combination of the three.1.IP Variables and IP Lists IPs may be specified individually.) Different use of !any: ipvar EXAMPLE !any alert tcp $EXAMPLE any -> any any (msg:"Example". ’any’ will specify any ports.2.2. with the exception of IPs 2. Use of !any: ipvar EXAMPLE any alert tcp !$EXAMPLE any -> any any (msg:"Example".2.2.![2.1.1. IPs.2.2. Previously. sid:2. The use of ’var’ to declare a port variable will be deprecated in a future release.!80] Ports out of range: portvar EXAMPLE7 [65536] Incorrect declaration and use of a port variable: var EXAMPLE8 80 alert tcp any $EXAMPLE8 -> any any (msg:"Example".9999:20000] (msg:"Example". as described in the following table: 28 . For backwards compatibility. sid:1. These can be used with the variable modifier operators ? and -.) Port variable used as an IP: alert tcp $EXAMPLE1 any -> any any (msg:"Example".) Variable Modifiers Rule variable names can be modified in several ways. sid:4. sid:5.) alert tcp any 90 -> any [100:1000. portvar EXAMPLE1 80 var EXAMPLE2_PORT [80:90] var PORT_EXAMPLE2 [1] portvar EXAMPLE3 any portvar EXAMPLE4 [!70:90] portvar EXAMPLE5 [80.100:200] alert tcp any $EXAMPLE1 -> any $EXAMPLE2_PORT (msg:"Example".Port variables should be specified using ’portvar’. sid:3.) Several invalid examples of port variables and port lists are demonstrated below: Use of !any: portvar EXAMPLE5 !any var EXAMPLE5 !any Logical contradictions: portvar EXAMPLE6 [80. You can define meta-variables using the $ operator.) alert tcp any $PORT_EXAMPLE2 -> any any (msg:"Example".91:95. provided the variable name either ends with ’ PORT’ or begins with ’PORT ’. a ’var’ can still be used to declare a port variable. The following examples demonstrate several valid usages of both port variables and port lists. port variables can be defined in terms of other port variables.1. variables can not be redefined if they were previously defined as a different type.168.90] Likewise. Here is an example of advanced variable usage in action: ipvar MY_NET 192. but old-style variables (with the ’var’ keyword) can not be embedded inside a ’portvar’. Replaces the contents of the variable var with “default” if var is undefined. types can not be mixed.0/24 log tcp any any -> $(MY_NET:?MY_NET is undefined!) 23 Limitations When embedding variables. Replaces with the contents of variable var. Replaces with the contents of variable var or prints out the error message and exits. For instance.1. Valid embedded variable: portvar pvar1 80 portvar pvar2 [$pvar1. Format config <directive> [: <value>] 29 .90] Invalid embedded variable: var pvar1 80 portvar pvar2 [$pvar1.Variable Syntax var $(var) or $var $(var:-default) $(var:?message) Description Defines a meta-variable. noudp. udp. Not all DAQs support modes. Sets the alerts output file. See Section 3. Specifies the maximum number of nodes to track when doing ASN1 decoding. Types of packets to drop if invalid checksums. noicmp. Set a DAQ specific variable. 30 . Select the DAQ mode: passive. Values: none. this option will cause Snort to revert back to it’s original behavior of alerting if the decoder or preprocessor generates an event. This can be repeated. tcp.31 for more information and examples. Tell Snort where to look for available dynamic DAQ modules. Default (with or without directive) is enabled. notcp. or read-file. Specifies BPF filters (snort -F). noip. Decodes Layer2 headers (snort -e). udp. Snort just passes this information down to the DAQ. noip. Specify disabled to disable loading rules.5. noicmp. icmp or all. icmp or all (only applicable in inline mode and for packets checked per checksum mode config option). Chroots to specified dir (snort -t). inline. Types of packets to calculate checksums. tcp. See the DAQ distro README for possible DAQ modes or list DAQ capabilities for a brief summary. See Table 3. See the DAQ distro README for possible DAQ).2 for a list of classifications. You can optionally specify a directory to include any dynamic DAQs from that directory. Values: none. You can also preceed this option with extra DAQ directory options to look in multiple directories. notcp. If Snort was configured to enable decoder and preprocessor rules. ip. The selected DAQ will be the one with the latest version. ip. Tell Snort to dump basic DAQ capabilities and exit. Selects the type of DAQ to instantiate. noudp. The DAQ with the highest version of the given type is selected if there are multiple of the same type (this includes any built-in DAQs). Forks as a daemon (snort -D). Global configuration directive to enable or disable the loading of rules into the detection engine. moderate performance) 31 . moderate performance) – Other search methods (the above are considered superior to these) ∗ ac-std .Low Memory Keyword Trie (low memory.Aho-Corasick Full (high memory. high performance) ∗ acs .Aho-Corasick Full with ANYANY port group evaluated separately (low memory. ∗ ac-bnfa and ac-bnfa-q .config detection: <method>] [search-method Select type of fast pattern matcher algorithm to use.Intel CPM library (must have compiled Snort with location of libraries to enable this) – No queue search methods .Aho-Corasick SparseBanded (high memory.Aho-Corasick Sparse (high memory. split-any-any ∗ intel-cpm . high performance).The ”nq” option specifies that matches should not be queued and evaluated as they are found. • search-method <method> – Queued match search methods . ∗ lowmem-nq . moderate performance) ∗ ac-banded . best performance).Matches are queued until the fast pattern matcher is finished with the payload. Note this is shorthand for search-method ac.Aho-Corasick Full (high memory.Low Memory Keyword Trie (low memory.Aho-Corasick Binary NFA (low memory.Aho-Corasick Standard (high memory. ∗ ac and ac-q . moderate performance) ∗ ac-split . best performance).Aho-Corasick Binary NFA (low memory.Aho-Corasick Banded (high memory. high performance). ∗ ac-nq . This is the default search method if none is specified. high performance) ∗ lowmem and lowmem-q . then evaluated. moderate performance) ∗ ac-sparsebands . This was found to generally increase performance through fewer cache misses (evaluating each rule would generally blow away the fast pattern matcher state in the cache). ∗ ac-bnfa-nq . When used with ac-bnfa. ANYANY port rules are added to every non ANY-ANY port group so that only one port group rule evaluation needs to be done per packet.. Patterns longer than this length will be truncated to this length before inserting into the pattern matcher. • max-pattern-len <integer> – This is a memory optimization that specifies the maximum length of a pattern that will be put in the fast pattern matcher.e. Useful when there are very long contents being used and truncating the pattern won’t diminish the uniqueness of the patterns. but eventually fail. Default is to not set a maximum pattern length. But doing so may require two port group evaluations per packet . however CPU cache can play a part in performance so a smaller memory footprint of the fast pattern matcher can potentially increase performance.config detection: [split-any-any] [search-optimize] [max-pattern-len <int>] Other options that affect fast pattern matching. 32 . By default. rules that will be evaluated because a fast pattern was matched. Note that this may cause more false positive rule evaluations. i. Not putting the ANY-ANY port rule group into every other port group can significantly reduce the memory footprint of the fast pattern matchers if there are many ANYANY port rules. Default is not to split the ANY-ANY port group. potentially increasing performance. • search-optimize – Optimizes fast pattern memory when used with search-method ac or ac-split by dynamically determining the size of a state based on the total number of states. Of note is that the lower memory footprint can also increase performance through fewer cache misses.one for the specific port group and one for the ANY-ANY port group. thus potentially reducing performance. some fail-state resolution will be attempted. • split-any-any – A memory/performance tradeoff. Default is not to optimize. 33 . Default is to inspect stream inserts. Default is 5 events. not to do this. Default is 1024. • no stream inserts – Specifies that stream inserted packets should not be evaluated against the detection engine.config detection: [no stream inserts] [max queue events <int>] [enable-single-rule-group] [bleedover-port-limit] Other detection engine options. Not recommended. This is a potential performance improvement with the idea that the stream rebuilt packet will contain the payload in the inserted one so the stream inserted packet doesn’t need to be evaluated. (snort --disable-inline-init-failopen) Disables IP option length validation alerts. Turns on character dumps (snort -C). Turns off alerts generated by T/TCP options. • bleedover-warnings-enabled – Prints a warning if the number of source or destination ports used in a rule exceed the bleedover-port-limit forcing the rule to be moved into the ANY-ANY port group. • debug-print-rule-groups-uncompiled – Prints uncompiled port group information. config disable decode alerts config disable inline init failopen Turns off the alerts generated by the decode phase of Snort. Only useful if Snort was configured with –enable-inline-init-failopen. config enable decode oversized alerts Enable alerting on packets that have headers containing length fields for which the value is greater than the length of the packet. • debug-print-rule-groups-compiled – Prints compiled port group information. Turns off alerts generated by T/TCP options. Dumps raw packet starting at link layer (snort -X). 34 . prints information about the content being used for the fast pattern matcher. Disables option length validation alerts. [debug-print-nocontent-rule-tests] [debug-print-rule-group-build-details] • debug [debug-print-rule-groups-uncompiled] – Prints fast pattern information for a particular port [debug-print-rule-groups-compiled] group.config detection: [debug] Options for detection engine debugging. Enables the dropping of bad packets identified by decoder (only applicable in inline mode). Turns off alerts generated by experimental TCP options. • debug-print-rule-group-build-details – Prints port group information during port group compilation.-fast-pattern] [bleedover-warnings-enabled] • debug-print-nocontent-rule-tests – Prints port group information during packet evaluation. • debug-print-fast-pattern – For each rule with fast pattern content. Disables failopen thread that allows inline traffic to pass while Snort is starting up. Dumps application layer (snort . The default is 1024 bits and maximum is 2096. engine is called. Faster execution than frag2 with less complex data management. For more detail on this issue and how it affects IDS.2. check out the famous Ptacek & Newsham paper at. The basic idea behind target-based IDS is that we tell the IDS information about hosts on the network so that it can avoid Ptacek & Newsham style evasion attacks based on information about how an individual target IP stack operates.1 Frag3 The frag3 preprocessor is a target-based IP defragmentation module for Snort. Global Configuration 38 . but after the packet has been decoded. In an environment where the attacker can determine what style of IP defragmentation is being used on a particular target. For an IDS this is a big problem. but only one global configuration. heavily fragmented environments the nature of the splay trees worked against the system and actually hindered. There can be an arbitrary number of engines defined at startup with their own configuration. 2. Frag3 is intended as a replacement for the frag2 defragmentation module and was designed with the following goals:. This is where the idea for “target-based IDS” came from. Frag3 was implemented to showcase and prototype a target-based module within Snort to test this idea. Frag 3 Configuration Frag3 configuration is somewhat more complex than frag2. When IP stacks are written for different operating systems. if the attacker has more information about the targets on a network than the IDS does. The packet can be modified or analyzed in an out-of-band manner using this mechanism. there are ambiguities in the way that the RFCs define some of the edge conditions that may occur and when this happens different people implement certain aspects of their IP stacks differently. Target-based analysis is a relatively new concept in network-based intrusion detection. The format of the preprocessor directive in the Snort config file is: preprocessor <name>: <options> 2.snort. As I like to say.org/docs/ idspaper/. but that’s a topic for another day.icir. The frag2 preprocessor used splay trees extensively for managing the data structures associated with defragmenting packets. a global configuration directive and an engine instantiation.pdf. Preprocessors are loaded and configured using the preprocessor keyword. Unfortunately.org/vern/papers/activemap-oak03. Target-based host modeling anti-evasion techniques. Frag3 uses the sfxhash data structure and linked lists for data handling internally which allows it to have much more predictable and deterministic performance in any environment which should aid us in managing heavily fragmented environments. Once we have this information we can start to really change the game for these complex modeling problems.. We can also present the IDS with topology information to avoid TTL-based evasions and a variety of other issues. Check it out at. There are at least two preprocessor directives required to activate frag3. it is possible to evade the IDS. The default is ”0” (unlimited). Engine Configuration • Preprocessor name: frag3 engine • Available options: NOTE: Engine configuration options are space separated. – bind to <ip list> .255. Default is 1. Available types are first.Limits the number of overlapping fragments per packet. Fragments in the engine for longer than this period will be automatically dropped.Maximum simultaneous fragments to track.Timeout for fragments. The default is ”0” (unlimited). – detect anomalies . detect anomalies option must be configured for this option to take effect. Default is 4MB. linux. – max frags <number> . – min fragment length <number> . This is an optional parameter.Defines smallest fragment size (payload size) that should be considered valid.Detect fragment anomalies. Default type is bsd.Alternate memory management mode.Minimum acceptable TTL value for a fragment packet. Use preallocated fragment nodes (faster in some situations). Default is 8192. – prealloc frags <number> .Select a target-based defragmentation mode. if detect anomalies is also configured. This engine will only run for packets with destination addresses contained within the IP List. – overlap limit <number> . – timeout <seconds> .• Preprocessor name: frag3 global • Available options: NOTE: Global configuration options are comma separated. This is an optional parameter. – memcap <bytes> . The known mappings are as follows. By default this option is turned off. – min ttl <value> . prealloc memcap. Default is 60 seconds. Fragments smaller than or equal to this limit are considered malicious and an event is raised. the minimum is ”0”. – disabled . and prealloc frags are applied when specified with the configuration. This config option takes values equal to or greater than zero. detect anomalies option must be configured for this option to take effect.IP List to bind this engine to. – policy <type> . bsdright. bsd. The Paxson Active Mapping paper introduced the terminology frag3 is using to describe policy types. When the preprocessor is disabled only the options memcap. The accepted range for this option is 1 .Memory cap for self preservation. Default value is all. Anyone who develops more mappings and would like to add to this list please feel free to send us an email! 39 .Option to turn off the preprocessor. last. 5.5F IRIX 6.4. Packets that don’t fall within the address requirements of the first two engines automatically fall through to the third one.9-31SGI 1.0/24] policy last. IRIX 6.3 8.172.7.8 Tru64 Unix V5.1 SunOS 4.0.0 Linux 2.10.19-6.1. detect_anomalies 40 .5.2.0.0.2.9.1 OS/2 (version unknown) OSF1 V3.2.4.3) MacOS (version unknown) NCD Thin Clients OpenBSD (version unknown) OpenBSD (version unknown) OpenVMS 7.1.4 (RedHat 7.2. bind_to [10.Platform AIX 2 AIX 4.6.5.1-7. first and last policies assigned.5.16.3 Cisco IOS FreeBSD HP JetDirect (printer) HP-UX B.2 OSF1 V4.3 IRIX64 6.47.7-10 Linux 2.20 HP-UX 11.0A.0 OSF1 V3.1.5.2smp Linux.0/24. The first two engines are bound to specific IP address ranges and the last one applies to all other traffic.4 SunOS 5.10smp Linux 2.2.1.16-3 Linux 2.10 Linux 2.00 IRIX 4.4 Linux 2.14-5.0.8.0/24 policy first.5.V5. bind_to 192.168. Target-Based Stream5. etc). With Stream5. FIN and Reset sequence numbers. Read the documentation in the doc/signatures directory with filenames that begin with “123-” for information on the different event types. and the policies supported by Stream5 are the results of extensive research with many target operating systems.2 Stream5 The Stream5 preprocessor is a target-based TCP reassembly module for Snort. [show_rebuilt_packets]. etc. Data on SYN. preprocessor stream5_global: \ [track_tcp <yes|no>]. the rule ’flow’ and ’flowbits’ keywords are usable with TCP as well as UDP traffic. \ [flush_on_alert]. \ [track_udp <yes|no>]. direction. For example. Transport Protocols TCP sessions are identified via the classic TCP ”connection”. etc) that can later be used by rules. like Frag3. \ [memcap <number bytes>]. [max_tcp <number>]. The methods for handling overlapping data. Its event output is packet-based so it will work with all output modes of Snort. etc are configured via the detect anomalies option to the TCP configuration. which effectively terminate a TCP or UDP session. data received outside the TCP window. ICMP messages are tracked for the purposes of checking for unreachable and service unavailable messages. [max_icmp <number>]. [disabled] 41 . Stream API Stream5 fully supports the Stream API. 2. \ [prune_log_max <bytes>]. a few operating systems allow data in TCP SYN packets. [max_udp <number>]. such as data on SYN packets. Anomaly Detection TCP protocol anomalies. Some of these anomalies are detected on a per-target basis. while others do not. TCP Timestamps.2. It is capable of tracking sessions for both TCP and UDP. other protocol normalizers/preprocessors to dynamically configure reassembly behavior as required by the application layer protocol. identify sessions that may be ignored (large data transfers. \ [track_icmp <yes|no>]. introduces target-based actions for handling of overlapping data and other TCP anomalies. and update the identifying information about the session (application protocol. \ [overlap_limit <number>]. \ [require_3whs [<number secs>]]. [use_static_footprint_sizes]. the minimum is ”1”. By default this option is turned off. \ [small_segments <number> bytes <number> [ignore_ports number [number]*]]. minimum is ”1”. \ [max_queued_bytes <bytes>]. minimum is ”32768” (32KB). The default is ”30”. [policy <policy_id>]. Track sessions for UDP. 42 . minimum can be either ”0” (disabled) or if not disabled the minimum is ”1024” and maximum is ”1073741824”. \ [protocol <client|server|both> <all|service name [service name]*>]. max udp and max icmp are applied when specified with the configuration. and that policy is not bound to an IP address or network. When the preprocessor is disabled only the options memcap. The default is ”65536”. Print a message when a session terminates that was consuming more than the specified number of bytes. minimum is ”1”. \ [ignore_any_rules]. The default is ”131072”. The default is ”no”. maximum is ”1048576”. The default is ”1048576” (1MB). [max_queued_segs <number segs>]. [dont_reassemble_async]. One default policy must be specified. [max_window <number>]. This can have multiple occurrences. maximum is ”1073741824” (1GB). The default is ”8388608” (8MB). Option to disable the stream5 tracking. max tcp. \ [dont_store_large_packets]. Maximum simultaneous TCP sessions tracked. Flush a TCP stream when an alert is generated on that stream. and the maximum is ”86400” (approximately 1 day). minimum is ”1”. preprocessor stream5_tcp: \ [bind_to <ip_addr>]. maximum is ”1048576”. Track sessions for ICMP. \ [check_session_hijacking]. The default is ”yes”. per policy that is bound to an IP address or network. [detect_anomalies]. The default is set to off. \ [timeout <number secs>]. The default is set to any. maximum is ”1048576”. The default is ”262144”. [ports <client|server|both> <all|number [number]*>]. Session timeout. Maximum simultaneous UDP sessions tracked. Memcap for TCP packet storage. Print/display packet after rebuilt (for debugging). The default is ”yes”. Maximum simultaneous ICMP sessions tracked. Backwards compatibility. [flush_factor <number segs>] Option bind to <ip addr> timeout <num seconds> \ Description IP address or network for this policy. Stream5 TCP Configuration Provides a means on a per IP address target to configure TCP policy. The default is set to off. Performance improvement to not queue large packets in reassembly buffer. The default is ”0” (unlimited). Windows XP. and the maximum is ”1073725440” (65535 left shift 14). bsd FresBSD 4. OpenBSD 3. Alerts are generated (per ’detect anomalies’ option) for either the client or server when the MAC address for one side or the other does not match. Establish sessions only on completion of a SYN/SYN-ACK/ACK handshake. with a non-zero minimum of ”1024”. Windows 95/98/ME win2003 Windows 2003 Server vista Windows Vista solaris Solaris 9. That is the highest possible TCP window per RFCs. The default is set to off. The default is set to off.4 and newer old-linux Linux 2. Check for TCP session hijacking. This check validates the hardware (MAC) address from both sides of the connect – as established on the 3-way handshake against subsequent packets received on the session. first Favor first overlapped segment. Don’t queue packets for reassembly if traffic has not been seen in both directions.x and newer hpux HPUX 11 and newer hpux10 HPUX 10 irix IRIX 6 and newer macos MacOS 10. The default is set to off. The default is set to off. This option is intended to prevent a DoS against Stream5 by an attacker using an abnormally large window.x and newer. The default is set to off. The optional number of seconds specifies a startup timeout. A message is written to console/syslog when this limit is enforced. there are no checks performed. Use static values for determining when to build a reassembled packet to allow for repeatable tests. If an ethernet layer is not part of the protocol stack received by Snort. the minimum is ”0”. and a maximum of ”1073741824” (1GB). This option should not be used production environments.3 and newer Limits the number of overlapping packets per session. A value of ”0” means unlimited. Using this option may result in missed attacks. Limit the number of bytes queued for reassembly on a given TCP session to bytes. last Favor first overlapped segment. so using a value near the maximum is discouraged. 43 . and the maximum is ”255”. Default is ”1048576” (1MB).x and newer linux Linux 2. Maximum TCP window allowed. NetBSD 2.2 and earlier windows Windows 2000. This allows a grace period for existing sessions to be considered established during that interval immediately after Snort is started.x and newer. Detect and alert on TCP protocol anomalies. The default is ”0” (unlimited). The default is ”0” (don’t consider existing sessions established). The default is set to queue packets. the minimum is ”0”. the minimum is ”0”. The policy id can be one of the following: Policy Name Operating Systems.policy <policy id> overlap limit <number> max window <number> require 3whs [<number seconds>] detect anomalies check session hijacking use static footprint sizes dont store large packets dont reassemble async max queued bytes <bytes> The Operating System policy for the target OS. and the maximum is ”86400” (approximately 1 day). preprocessor stream5_udp: [timeout <number secs>].3) or others specific to the network. The second number is the minimum bytes for a segment to be considered ”small”. The service names can be any of those used in the host attribute table (see 2. including any of the internal defaults (see 2. Specify the client. Useful in ips mode to flush upon seeing a drop in segment size after N segments of non-decreasing size. The default settings are ports client 21 23 25 42 53 80 110 111 135 136 137 139 143 445 513 514 1433 1521 2401 3306. Specify the client. only those with content. This option can be used only in default policy. defines the list of ports in which will be ignored for this rule. A message is written to console/syslog when this limit is enforced. Don’t process any -> any (ports) rules for TCP that attempt to match payload if there are no port specific rules for the src or destination port. The default is ”2621”. or both and list of ports in which to perform reassembly. If only a bind to option is used with no other options that TCP policy uses all of the default values. The number of ports can be up to ”65535”. The drop in size often indicates an end of request or response. that is the default TCP policy. Using this does not affect rules that look at protocol headers. Rules that have flow or flowbits will never be ignored. Stream5 UDP Configuration Configuration for UDP session tracking. This can appear more than once in a given config. Since there is no target based binding. Configure the maximum small segments queued. with a maximum of ”2048”. ! △NOTE If no options are specified for a given TCP policy. A value of ”0” means unlimited. This feature requires that detect anomalies be enabled. server.7. The first number is the number of consecutive segments that will trigger the detection rule. [ignore_any_rules] 44 . This is a performance improvement and may result in missed attacks. there should be only one occurrence of the UDP configuration. This can appear more than once in a given config. derived based on an average size of 400 bytes. PCRE. and a maximum of ”1073741824” (1GB).7). The default settings are ports client ftp telnet smtp nameserver dns http pop3 sunrpc dcerpc netbios-ssn imap login shell mssql oracle cvs mysql. server. or both and list of services in which to perform reassembly. ignore ports is optional. A message is written to console/syslog when this limit is enforced. with a non-zero minimum of ”2”. The default value is ”0” (disabled). The default is ”off”. The minimum port allowed is ”1” and the maximum allowed is ”65535”. with a maximum of ”2048”. The default value is ”0” (disabled). or byte test options. ! △NOTE any rules option. but NOT to any other source or destination port. with all other traffic going to the default policy of Solaris. the minimum is ”1”. or byte test options. Using this does not affect rules that look at protocol headers. track_udp yes. This is a performance improvement and may result in missed attacks. and the maximum is ”86400” (approximately 1 day). there should be only one occurrence of the ICMP configuration. use_static_footprint_sizes preprocessor stream5_udp: \ ignore_any_rules 2. A list of rule SIDs affected by this option are printed at Snort’s startup. if a UDP rule specifies destination port 53. This example configuration is the default configuration in snort. in minimal code form and is NOT ready for use in production networks. and the maximum is ”86400” (approximately 1 day). PCRE. the ’ignored’ any -> any rule will be applied to traffic to/from port 53. This configuration maps two network segments to different OS policies.Option timeout <num seconds> ignore any rules Description Session timeout. the ignore any rules option will be disabled in this case. preprocessor stream5_global: \ max_tcp 8192. if a UDP rule that uses any -> any ports includes either flow or flowbits. For example. With the ignore the ignore any rules option is effectively pointless. Because of the potential impact of disabling a flowbits rule. track_icmp no preprocessor stream5_tcp: \ policy first. ! △NOTE any rules option. ! △NOTE untested. 45 . track_tcp yes. one for Windows and one for Linux. Don’t process any -> any (ports) rules for UDP that attempt to match payload if there are no port specific rules for the src or destination port. preprocessor stream5_icmp: [timeout <number secs>] Option timeout <num seconds> Description Session timeout. a UDP rule will be ignored except when there is another port specific rule With the ignore that may be applied to the traffic. The default is ”30”. Example Configurations 1. the minimum is ”1”. Stream5 ICMP Configuration Configuration for ICMP session tracking. It is not ICMP is currently turned on by default. only those with content. The default is ”30”. The default is ”off”. Since there is no target based binding.conf and can be used for repeatable tests of stream reassembly in readback mode. Rules that have flow or flowbits will never be ignored. 168. Nmap encompasses many. This is used to evade an IDS and obfuscate command and control hosts. most queries sent by the attacker will be negative (meaning that the service ports are closed).1. since most hosts have relatively few services available. developed by Sourcefire. This is the traditional place where a portscan takes place. sfPortscan alerts for the following types of distributed portscans: • TCP Distributed Portscan • UDP Distributed Portscan • IP Distributed Portscan These are many→one portscans.2. In the nature of legitimate network communications. policy windows stream5_tcp: bind_to 10. Distributed portscans occur when multiple hosts query one host for open services. one host scans multiple ports on another host. policy linux stream5_tcp: policy solaris 2. In the Reconnaissance phase. if not all. so we track this type of scan through the scanned host.preprocessor preprocessor preprocessor preprocessor stream5_global: track_tcp yes stream5_tcp: bind_to 192.1. only the attacker has a spoofed source address inter-mixed with the real scanning address. sfPortscan was designed to be able to detect the different types of scans Nmap can produce.0/24. sfPortscan alerts for the following types of portsweeps: 46 .1. this phase would not be necessary. of the current portscanning techniques. which are the traditional types of scans.0/24. an attacker determines what types of network protocols or services a host supports. As the attacker has no beforehand knowledge of its intended target. ! △NOTE Negative queries will be distributed among scanning hosts. negative responses from hosts are rare.. sfPortscan will currently alert for the following types of Nmap scans: • TCP Portscan • UDP Portscan • IP Portscan These alerts are for one→one portscans.3 sfPortscan The sfPortscan module. This phase assumes the attacking host has no prior knowledge of what protocols or services are supported by the target. is designed to detect the first phase in a network attack: Reconnaissance. Most of the port queries will be negative. and rarer still are multiple negative responses within a given amount of time. One of the most common portscanning tools in use today is Nmap. This tactic helps hide the true identity of the attacker. otherwise. can trigger these alerts because they can send out many connection attempts within a very small amount of time. but tags based on the original scan alert. It’s also a good indicator of whether the alert is just a very active legitimate host. Active hosts. 47 . For example.. ! △NOTE The characteristics of a portsweep scan may not result in many negative responses. sfPortscan will also display any open ports that were scanned. One host scans a single port on multiple hosts. Open port events are not individual alerts. A filtered alert may go off before responses from the remote hosts are received. On TCP sweep alerts however. we will most likely not see many negative responses. sfPortscan only generates one alert for each host pair in question during the time window (more on windows below). sfPortscan will only track open ports after the alert has been triggered. On TCP scan alerts. if an attacker portsweeps a web farm for port 80. such as NATs. ports are specified after the IP address/CIDR using a space and can be either a single port or a range denoted by a dash. etc). this setting should see very few false positives. IPs or networks not falling into this range are ignored if this option is used. However. so the user may need to deploy the use of Ignore directives to properly tune this directive. 7. 6. • high . sense level <level> Available options: • low .2. Stream gives portscan direction in the case of connectionless protocols like ICMP and UDP.conf. This most definitely will require the user to tune sfPortscan. logfile <file> This option will output portscan events to the file specified. ignore scanners <ip1|ip2/cidr[ [port|port2-port3]]> Ignores the source of scan alerts. this setting will never trigger a Filtered Scan alert because of a lack of error responses. IP address using CIDR notation. proxies.2. 5. You should enable the Stream preprocessor in your snort.“High” alerts continuously track hosts on a network using a time window to evaluate portscan statistics for that host.“Low” alerts are only generated on error packets sent from the target host. and so will generate filtered scan alerts. The parameters you can use to configure the portscan module are: 1. The parameter is the same format as that of watch ip.“Medium” alerts track connection counts. but is very sensitive to active hosts. The parameter is the same format as that of watch ip. DNS caches. and specific ports on those hosts to watch. Optionally. as described in Section 2. networks. A ”High” setting will catch some slow scans because of the continuous monitoring. after which this window is reset. this file will be placed in the Snort config dir. proto <protocol> Available options: • TCP • UDP • IGMP • ip proto • all 2. If file does not contain a leading slash. • medium . The list is a comma separated list of IP addresses.sfPortscan Configuration Use of the Stream5 preprocessor is required for sfPortscan. 48 . and because of the nature of error responses. scan type <scan type> Available options: • portscan • portsweep • decoy portscan • distributed portscan • all 3. This setting may false positive on active hosts (NATs. 4. watch ip <ip1|ip2/cidr[ [port|port2-port3]]> Defines which IPs. This setting is based on a static time window of 60 seconds. ignore scanned <ip1|ip2/cidr[ [port|port2-port3]]> Ignores the destination of scan alerts. The size tends to be around 100 . This includes any IP options. then the user won’t see open port alerts. which is why the option is off by default. which is necessary to detect ACK scans. snort generates a pseudo-packet and uses the payload portion to store the additional portscan information of priority count. disabled This optional keyword is allowed with any policy to avoid packet processing. The characteristics of the packet are: Src/Dst MAC Addr == MACDAD IP Protocol == 255 IP TTL == 0 Other than that. This means that if an output system that doesn’t print tagged packets is used. The sfPortscan alert output was designed to work with unified packet logging. especially under heavy load with dropped packets. 49 . this can lead to false alerts. 9. include midstream This option will include sessions picked up in midstream by Stream5. connection count. This option disables the preprocessor. The other options are parsed but not used. The open port information is stored in the IP payload and contains the port that is open. which is why the option is off by default.8. so it is possible to extend favorite Snort GUIs to display portscan alerts and the additional information in the IP payload using the above packet characteristics. However. 10. port count. detect ack scans This option will include sessions picked up in midstream by the stream module. This can lead to false alerts. Open port alerts differ from the other portscan alerts. because open port alerts utilize the tagged packet output system. etc.200 bytes. especially under heavy load with dropped packets. IP count. IP range. the packet looks like the IP portion of the packet that caused the portscan alert to be generated. The payload and payload size of the packet are equal to the length of the additional portscan information that is logged.. Any valid configuration may have ”disabled” added to it. and port range. When the preprocessor is disabled only the memcap option is applied when specified with the configuration. Here are some tuning tips: 1. Portscans (one-to-one) display the scanner IP. and ignore scanned options.3 -> 192. High connection count and low priority count would indicate filtered (no response received from target). one or more additional tagged packet(s) will be appended: Time: 09/08-15:07:31. Port Count Port Count keeps track of the last port contacted and increments this number when that changes.169.169. The analyst should set this option to the list of CIDR blocks and IPs that they want to watch. 50 . 4.168.603880 event_id: 2 192. 3. For one-to-one scans. We use this count (along with IP Count) to determine the difference between one-to-one portscans and one-to-one decoys. 5.3:192. Use the watch ip.Log File Output Log file output is displayed in the following format.169. and one-to-one scans may appear as a distributed scan. ignore scanners. Tuning sfPortscan The most important aspect in detecting portscans is tuning the detection engine for your network(s). Event id/Event ref These fields are used to link an alert with the corresponding Open Port tagged packet 2.3 -> 192. IP Count IP Count keeps track of the last IP to contact a host. this is a low number. and is more of an estimate for others.4 Port/Proto Count: 200 Port/Proto Range: 20:47557 If there are open ports on the target. Scanned/Scanner IP Range This field changes depending on the type of alert. and explained further below: Time: 09/08-15:07:31. and increments the count if the next IP is different. Connection Count Connection Count lists how many connections are active on the hosts (src or dst).169. Portsweep (one-to-many) scans display the scanned IP range. The higher the priority count. Priority Count Priority Count keeps track of bad responses (resets.168.168.168. This is accurate for connection-based protocols.168.5 (portscan) TCP Filtered Portscan Priority Count: 0 Connection Count: 200 IP Count: 2 Scanner IP Range: 192. the more bad responses have been received. Whether or not a portscan was filtered is determined here.168. 6.169. sfPortscan will watch all network traffic. If no watch ip is defined. The watch ip option is easy to understand. It’s important to correctly set these options.5 (portscan) Open Port Open Port: 38458 1.603881 event_ref: 2 192. For active hosts this number will be high regardless.169. unreachables). For portscans. Depending on the type of alert that the host generates. This indicates that each connection was to a different port. In the future. For portscans. Some of the most common examples are NAT IPs. The easiest way to determine false positives is through simple ratio estimations.4 RPC Decode The rpc decode preprocessor normalizes RPC multiple fragmented records into a single un-fragmented record. Port Count.The ignore scanners and ignore scanned options come into play in weeding out legitimate hosts that are very active on your network. we hope to automate much of this analysis in assigning a scope level and confidence level. 2. then add it to the ignore scanners option. Many times this just indicates that a host was very active during the time period in question. syslog servers. Connection Count / IP Count: This ratio indicates an estimated average of connections per IP. it runs against traffic on ports 111 and 32771. it will only process client-side traffic. lower the sensitivity level. The reason that Priority Count is not included. DNS cache servers. is because the priority count is included in the connection count and the above comparisons take that into consideration. If all else fails. this ratio should be high. 3. the alert type is very important. indicating that the scanning host connected to few ports but on many hosts. this ratio should be low. The following is a list of ratios to estimate and the associated values that indicate a legitimate scan and not a false positive. For portsweeps. this ratio should be low. For portsweeps. Format preprocessor rpc_decode: \ <ports> [ alert_fragments ] \ [no_alert_multiple_requests] \ [no_alert_large_fragments] \ [no_alert_incomplete] 51 . For portscans. The portscan alert details are vital in determining the scope of a portscan and also the confidence of the portscan. For portsweeps. By default. IP Range. If the host continually generates these types of alerts. When determining false positives. add it to the ignore scanners list or use a lower sensitivity level. the higher the better.2. since these are more prone to false positives. Filtered scan alerts are much more prone to false positives. Make use of the Priority Count. 4. This indicates that there were many connections to the same port. Most of the false positives that sfPortscan may generate are of the filtered scan alert type. Port Count / IP Count: This ratio indicates an estimated average of ports connected to per IP. The low sensitivity level does not catch filtered scans. and nfs servers. If stream5 is enabled. the analyst will know which to ignore it as. this ratio should be low. 2. this ratio should be high. You get the best protection the higher the sensitivity level. lower the sensitivity level. add it to the ignore scanned option. If the host is generating portscan alerts (and is the host that is being scanned). this ratio should be high and indicates that the scanned host’s ports were connected to by fewer IPs. and Port Range to determine false positives. IP Count. sfPortscan may not generate false positives for these types of hosts. but for now the user must manually do this. The low sensitivity level only generates alerts based on error responses.. It does this by normalizing the packet into the packet buffer. Connection Count. So be much more suspicious of filtered portscans. but be aware when first tuning sfPortscan for these IPs. If the host is generating portsweep events. These responses indicate a portscan and the alerts generated by the low sensitivity level are highly accurate and require the least tuning. but it’s also important that the portscan detection engine generate alerts that the analyst will find informative. Connection Count / Port Count: This ratio indicates an estimated average of connections per port. Snort’s real-time statistics are processed.Option alert fragments no alert multiple requests no alert large fragments no alert incomplete Description Alert on any fragmented RPC record. Whenever this preprocessor is turned on. where statistics get printed to the specified file name.2. either “console” which prints statistics to the console window or “file” with a file name. Don’t alert when a single fragment record exceeds the size of one packet. Don’t alert when the sum of fragmented records exceeds one packet.5 Performance Monitor This preprocessor measures Snort’s real-time and theoretical maximum performance. 2. it should have an output mode enabled. Don’t alert when there are multiple records in one packet. By default. . The fast pattern matcher is used to select a set of rules for evaluation based on the longest content or a content modified with the fast pattern rule option in a rule. • atexitonly . adding a content rule option to those rules can decrease the number of times they need to be evaluated and improve performance. At startup. • max . Snort will log a distinctive line to this file with a timestamp to all readers to easily identify gaps in the stats caused by Snort not running.Prints statistics at the console. since many operating systems don’t keep accurate kernel statistics for multiple CPUs. since checking the time sample reduces Snort’s performance. This boosts performance. reset is used. • accumulate or reset . 54 . This option can produce large amounts of output.Adjusts the number of packets to process before checking for the time sample. You may also use snortfile which will output into your defined Snort log directory. this is 10000.Defines which type of drop statistics are kept by the operating system. • file . so if possible. This prints out statistics as to the number of rules that were evaluated and didn’t match (non-qualified events) vs. generic contents are more likely to be selected for evaluation than those with longer. Rules with short.Prints out statistics about the type of traffic and protocol distributions that Snort is seeing. Rules without content are not filtered via the fast pattern matcher and are always evaluated. more unique contents pktcnt .Represents the number of seconds between intervals.Prints statistics in a comma-delimited format to the file that is specified. the number of rules that were evaluated and matched (qualified events).Turns on the theoretical maximum performance that Snort calculates given the processor speed and current performance.Turns on event reporting.Dump stats for entire life of Snort. By default. This is only valid for uniprocessor machines. By default. Both of these directives can be overridden on the command line with the -Z or --perfmon-file options. • events . A high non-qualified event to qualified event ratio can indicate there are many rules with either minimal content or no content that are being evaluated without success. • console . Not all statistics are output to this file. • time . Defines the maximum size of the comma-delimited file. Users can configure individual HTTP servers with a variety of options. The minimum is 4096 bytes and the maximum is 2147483648 bytes (2GB). it will be rolled into a new date stamped file of the format YYYY-MM-DD. Once the cap has been reached. HTTP Inspect will decode the buffer. Given a data buffer. All of the statistics mentioned above. the table will start to prune the statistics for the least recently seen host pairs to free memory. Within HTTP Inspect. The following example gives the generic global configuration format: 55 . and will be fooled if packets are not reassembled.csv pktcnt 1000 2..2. HTTP Inspect has a very “rich” user configuration. This means that HTTP Inspect looks for HTTP fields on a packet-by-packet basis. and normalize the fields. This value is in bytes and the default value is 52428800 (50MB).Sets the memory cap on the hash table used to store IP traffic statistics for host pairs. Before the file exceeds this size. For each pair of hosts for which IP traffic has been seen. but there are limitations in analyzing the protocol.Collects IP traffic distribution statistics based on host pairs. where x will be incremented each time the comma delimited file is rolled over. • flow-ip . Global Configuration The global configuration deals with configuration options that determine the global functioning of HTTP Inspect. are included. HTTP Inspect works on both client requests and server responses. The default is the same as the maximum.6 HTTP Inspect HTTP Inspect is a generic HTTP decoder for user applications. • flow-ip-memcap .• max file size . This works fine when there is another module handling the reassembly. there are two areas of configuration: global and server. followed by YYYY-MM-DD. which should allow the user to emulate any type of web server. Examples preprocessor perfmonitor: \ time 30 events flow file stats.Prints the flow IP statistics in a comma-delimited format to the file that is specified. • flow-ip-file .profile max console pktcnt 10000 preprocessor perfmonitor: \ time 300 file /var/tmp/snortstat pktcnt 10000 preprocessor perfmonitor: \ time 30 flow-ip flow-ip-file flow-ip-stats. find HTTP fields. as well as the IP addresses of the host pairs in human-readable format. The current version of HTTP Inspect only handles stateless processing. Future versions will have a stateful processing mode which will hook into various reassembly modules. we want to limit this to specific networks so it’s more useful. The iis unicode map is a required configuration parameter. you’ll get an error if you try otherwise. Configuration 1. 4. but for right now. So. ! △NOTE Remember that this configuration is for the global IIS Unicode map.map and should be used if no other codepoint map is available. This value can be set from 1 to 65535. The iis unicode map file is a Unicode codepoint map which tells HTTP Inspect which codepage to use when decoding Unicode characters. the codemap is usually 1252. 5. A Microsoft US Unicode codepoint map is provided in the Snort source etc directory by default.c. iis unicode map <map filename> [codemap <integer>] This is the global iis unicode map file. In the future. A tool is supplied with Snort to generate custom Unicode maps--ms unicode generator. compress depth <integer> This option specifies the maximum amount of packet payload to decompress. 2. detect anomalous servers This global configuration option enables generic HTTP server traffic inspection on non-HTTP configured ports. The default for this option is 2920. max gzip mem This option determines (in bytes) the maximum amount of memory the HTTP Inspect preprocessor will use for decompression. you will only receive proxy use alerts for web users that aren’t using the configured proxies or are using a rogue proxy server. This value can be set from 3276 bytes to 100MB. decompress depth <integer> This option specifies the maximum amount of decompressed data to obtain from the compressed packet payload. The default for this option is 1460. This value can be set from 1 to 65535. which is available at. Don’t turn this on if you don’t have a default server configuration that encompasses all of the HTTP server ports that your users might access.conf or be specified via a fully-qualified path to the map file.org/ dl/contrib/. please only use this feature with traditional proxy environments.Format preprocessor http_inspect: \ global \ iis_unicode_map <map_filename> \ codemap <integer> \ [detect_anomalous_servers] \ [proxy_alert] \ [max_gzip_mem <num>] \ [compress_depth <num>] [decompress_depth <num>] \ disabled You can only have a single global configuration. It is called unicode. For US servers. This option is turned off by default. and alerts if HTTP traffic is seen. The map file can reside in the same directory as snort. then you may get a lot of proxy alerts. 6. individual servers can reference their own IIS Unicode map. this inspects all network traffic. Blind firewall proxies don’t count. By configuring HTTP Inspect servers and enabling allow proxy use. Please note that if users aren’t required to configure web proxy use. proxy alert This enables global alerting on HTTP server proxy usage. This option along with compress depth and 56 .snort. 3. decompress depth determines the gzip sessions that will be decompressed at any given instant.2. Default This configuration supplies the default server configuration for any server that is not individually configured. Example Multiple IP Configuration preprocessor http_inspect_server: \ server { 10. ”compress depth” and ”decompress depth” options are applied when specified with the configuration.2.1. There is a limit of 40 IP addresses or CIDR notations per http inspect server line. This option disables the preprocessor.1. The default value for this option is 838860. disabled This optional keyword is allowed with any policy to avoid packet processing.1. the only difference being that multiple IPs can be specified via a space separated list.0/24 } profile all ports { 80 } 57 . Example IP Configuration preprocessor http_inspect_server: \ server 10. max gzip session = max gzip mem /(decompress depth + compress depth) 7. Any valid configuration may have ”disabled” added to it. Other options are parsed but not used. 10. Example Global Configuration preprocessor http_inspect: \ global iis_unicode_map unicode.”.map 1252 Server Configuration There are two types of server configurations: default and by IP address. ! △NOTE It is suggested to set this value such that the max gzip session calculated as follows is at least 1. When the preprocessor is disabled only the ”max gzip mem”.1. alert on non strict URL parsing on tab uri delimiter is set max header length 0. This differs from the iis profile by only accepting UTF-8 standard Unicode encoding and not accepting backslashes as legitimate slashes. bare-byte encoding. and iis4 0. there was a double decoding vulnerability.5. 1-D. Double decode is not supported in IIS 5. except they will alert by default if a URL has a double encoding. So that means we use IIS Unicode codemaps for each server. so it’s disabled by default. alert on iis backslash on. apache The apache profile is used for Apache web servers. 1-C. whether set to ‘yes’ or ’no’. Table 2. HTTP normalization will still occur. alert on %u decoding on. alert off multiple slash on.3. double decoding. iis The iis profile mimics IIS servers. Apache also accepts tabs as whitespace. 58 . alert off directory normalization on. We alert on the more serious forms of evasions. like IIS does. profile <all|apache|iis|iis5 0|iis4 0> Users can configure HTTP Inspect by using pre-defined HTTP server profiles. etc. iis5 0. 1. This argument specifies whether the user wants the configuration option to generate an HTTP Inspect alert or not. alert on iis unicode codepoints on. These two profiles are identical to iis. alert off apache whitespace on. %u encoding.Server Configuration Options Important: Some configuration options have an argument of ‘yes’ or ‘no’. number of headers not checked 1-B. only the alerting functionality. profile apache sets the configuration options described in Table 2. but are not required for proper operation. alert on bare byte decoding on.0.0 and IIS 5. profile iis sets the configuration options described in Table 2.1 and beyond. header length not checked max headers 0. all The all profile is meant to normalize the URI using most of the common tricks available. profile all sets the configuration options described in Table 2. This is a great profile for detecting all types of attacks. Profiles allow the user to easily configure the preprocessor for a certain type of server. iis5 0 In IIS 4. regardless of the HTTP server. alert off webroot on. apache. In other words.4. There are five profiles available: all. iis4 0. 1. The ‘yes/no’ argument does not specify whether the configuration option itself is on or off. and rules based on HTTP traffic will still trigger. alert off double decoding on. alert off iis delimiter on. backslashes. iis. 4: Options for the apache Profile Option Setting server flow depth 300 client flow depth 300 post depth 0 chunk encoding alert on chunks larger than 500000 bytes ASCII decoding on.. utf 8 encoding on. no profile The default options used by HTTP Inspect do not use a profile and are described in Table 2..6. use the SSL preprocessor. alert off directory normalization on. HTTPS traffic is encrypted and cannot be decoded with HTTP Inspect. >]} This is how the user configures which ports to decode on the HTTP server. Example preprocessor http_inspect_server: \ server 1. 59 . ports {<port> [<port>< . alert off webroot on.Table 2. However.1 profile all ports { 80 3128 } 2.1. default. header length not checked max headers 0. alert off non strict url parsing on tab uri delimiter is set max header length 0. alert on apache whitespace on. alert off multiple slash on.1. number of headers not checked 1-E. To ignore HTTPS traffic. When the compressed data is spanned 60 .c. You should select the config option ”extended response inspection” before configuring this option. http stat code. number of headers not checked 3. it’s the ANSI code page. one should use the http modifiers with content such as http header. But the ms unicode generator program tells you which codemap to use for you server. alert on non strict URL parsing on max header length 0. extended response inspection This enables the extended HTTP response inspection. So. to get the specific Unicode mappings for an IIS web server. this is usually 1252. alert off webroot on. In both cases the header name is also stored along with the cookie.org web site at. By default the cookie inspection and extraction will be turned off. To search for patterns in the header of the response. 5.Table 2. For US servers. cookie (when enable cookie is configured) and body are extracted and saved into buffers. http stat msg and http cookie. inspect gzip This option specifies the HTTP inspect module to uncompress the compressed data(gzip/deflate) in HTTP response. alert on iis backslash on. alert off iis delimiter on. alert on %u decoding on. the user needs to specify the file that contains the IIS Unicode map and also specify the Unicode map to use. Different rule options are provided to inspect these buffers. 6. status message. alert on iis unicode codepoints on.snort. alert on apache whitespace on. headers. So the decompression will end when either the ’compress depth’ or ’decompress depth’ is reached or when the compressed data ends. enable cookie This options turns on the cookie extraction from HTTP requests and HTTP response. When using this option. 4. if the HTTP response packet has a body then any content pattern matches ( without http modifiers ) will search the response body ((decompressed in case of gzip) and not the entire packet payload. iis unicode map <map filename> codemap <integer> The IIS Unicode map is generated by the program ms unicode generator. This program is located on the Snort. You can select the correct code page by looking at the available code pages that the ms unicode generator outputs. The Cookie header line is extracted and stored in HTTP Cookie buffer for HTTP requests and Set-Cookie is extracted and stored in HTTP Cookie buffer for HTTP responses. alert off multiple slash on. Executing this program generates a Unicode map for the system that it was run on. alert off directory normalization on. header length not checked max headers 0.org/dl/contrib/ directory. you run this program on that server and use that Unicode map in this configuration. alert on double decoding on. Decompression is done across packets. The default http response inspection does not inspect the various fields of a HTTP response. By turning this option the HTTP response will be thoroughly inspected. alert on bare byte decoding on. ! △NOTE When this option is turned. The different fields of a HTTP response such as status code. Snort rules are targeted at HTTP server response traffic and when used with a small flow depth value may cause false negatives. Also the amount of decompressed data that will be inspected depends on the ’server flow depth’ configured. 7. ! △NOTE To enable compression of HTTP server response. enable xff This option enables Snort to parse and log the original client IP present in the X-Forwarded-For or True-ClientIP HTTP request headers along with the generated events.6: Default HTTP Inspect Options Option Setting port 80 server flow depth 300 client flow depth 300 post depth -1 chunk encoding alert on chunks larger than 500000 bytes ASCII decoding on. This tool is present in the tools/u2spewfoo directory of snort source tree. 8. This option can be used to balance the needs of IDS performance and level of inspection of HTTP server response data. When extended response inspection is turned off the server flow depth is applied to the entire HTTP response (including headers). alert off apache whitespace on. number of headers not checked across multiple packets. server flow depth <integer> This specifies the amount of server response payload to inspect.Decompression will stop when the compressed data ends or when a out of sequence packet is received. alert off webroot on. ! △NOTE The original client IP from XFF/True-Client-IP in unified2 logs can be viewed using the tool u2spewfoo. unlimited decompress This option enables the user to decompress unlimited gzip data (across multiple packets). alert off utf 8 encoding on. The XFF/True-Client-IP Original client IP address is logged only with unified2 output and is not logged with console (-A cmg) output. Most of these rules target either the HTTP header. The decompression in a single packet is still limited by the ’compress depth’ and ’decompress depth’.e. it is suggested to set the ’compress depth’ and ’decompress depth’ to its maximum values.Table 2. Snort should be configured with the –enable-zlib flag. alert on iis backslash on. or the content 61 . Unlike client flow depth this option is applied per TCP session. alert off multiple slash on. the decompressed data from different packets are not combined while inspecting). header length not checked max headers 0. To ensure unlimited decompression. alert off iis delimiter on. 9. it is applied to the HTTP response body (decompressed data when inspect gzip is turned on) and not the HTTP headers. When extended response inspection is turned on. But the decompressed data are individually inspected. (i. alert off non strict URL parsing on max header length 0. the state of the last decompressed packet is used to decompressed the data of the next packet. alert off directory normalization on. 12. a. If less than flow depth bytes are in the payload of the HTTP response packets in a given session.. so for any Apache servers. If less than flow depth bytes are in the TCP payload (HTTP request) of the first packet. %2e = . utf 8 <yes|no> The utf-8 decode option tells HTTP Inspect to decode standard UTF-8 Unicode sequences that are in the URI. Note that the 1460 byte maximum flow depth applies to stream reassembled packets as well. but your mileage may vary. a value of 0 causes Snort to inspect all HTTP client side traffic defined in ”ports” (note that this will likely slow down IDS performance). Unlike server flow depth this value is applied to the first packet of the HTTP request. It is normal to see ASCII encoding usage in URLs. Apache uses this standard. so it is recommended that you disable HTTP Inspect alerting for this option. 14. It has a default value of 300. If more than flow depth bytes are in the payload of the first packet only flow depth bytes of the payload will be inspected. the entire payload will be inspected. a value of 0 causes Snort to inspect all HTTP server payloads defined in ”ports” (note that this will likely slow down IDS performance). This option is turned off by default and is not supported with any of the profiles. Values above 0 tell Snort the number of bytes to inspect in the first packet of the client request. When the extended response inspection is turned on. This abides by the Unicode standard and only uses % encoding. post depth <integer> This specifies the amount of data to inspect in a client post message. client flow depth <integer> This specifies the amount of raw client request payload to inspect. Inversely. Values above 0 tell Snort the number of bytes to inspect of the server response (excluding the HTTP headers when extended response inspection is turned on) in a given HTTP session. etc. ASCII decoding is also enabled to enforce correct functioning.that is likely to be in the first hundred or so bytes of non-header data. It is suggested to set the client flow depth to its maximum value. which will be deprecated in a future release. 62 . you may be interested in knowing when you have a UTF-8 encoded URI. value of -1 causes Snort to ignore the HTTP response body data and not the HTTP headers. The default value is -1. Only packets payloads starting with ’HTTP’ will be considered as the first packet of a server response.. It is suggested to set the server flow depth to its maximum value. a value of 0 causes Snort to inspect all the client post message.k. When utf 8 is enabled. but this will be prone to false positives as legitimate web clients use this type of encoding. extended ascii uri This option enables the support for extended ASCII codes in the HTTP request URI. make sure you have this option turned on.” Inversely. This value can be set from -1 to 1460. Inversely. Headers are usually under 300 bytes long. As for alerting. 13. Rules that are meant to inspect data in the payload of the HTTP response packets in a session beyond 65535 bytes will be ineffective unless flow depth is set to 0. the entire payload will be inspected. ascii <yes|no> The ascii decode option tells us whether to decode encoded ASCII chars. Note that the 65535 byte maximum flow depth applies to stream reassembled packets as well. Rules that are meant to inspect data in the payload of the first packet of a client request beyond 1460 bytes will be ineffective unless flow depth is set to 0. 11.a %2f = /. It is not a session based flow depth. This value can be set from -1 to 65535. This increases the performance by inspecting only specified bytes in the post message. A value of -1 causes Snort to ignore all the data in the post message. A value of -1 causes Snort to ignore all server side traffic for ports defined in ports when extended response inspection is turned off. The value can be set from -1 to 65495. 10. A value of -1 causes Snort to ignore all client side traffic for ports defined in ”ports. ! △NOTE server flow depth is the same as the old flow depth option. It primarily eliminates Snort from inspecting larger HTTP Cookies that appear at the end of many client request Headers. The default value for server flow depth is 300. When base36 is enabled. If no iis unicode map is specified before or after this option. bare byte. the default codemap is used. In the first pass.. so be careful. If %u encoding is enabled. Please use this option with care. 17. base36 <yes|no> This is an option to decode base36 encoded chars. An ASCII character is encoded like %u002f = /. bare byte <yes|no> Bare byte encoding is an IIS trick that uses non-ASCII characters as valid values when decoding UTF-8 values. because you could configure it to say. The iis unicode option handles the mapping of non-ASCII codepoints that the IIS server accepts and decodes normal UTF-8 requests. and %u. because base36 won’t work. This option is based on info from:. so something like: “foo/////////bar” get normalized to “foo/bar. This is again an IIS emulation. 16. it seems that all types of iis encoding is done: utf-8 unicode. bare byte. ASCII and UTF-8 decoding are also enabled to enforce correct decoding. This value can most definitely be ASCII. iis unicode uses the default codemap. otherwise. the following encodings are done: ASCII. The alert on this decoding should be enabled. like %uxxxx. You have to use the base36 option with the utf 8 option. If there is no iis unicode map option specified with the server config. Anyway. The directory: 63 . because we are not aware of any legitimate clients that use this encoding.patch. 21. When iis unicode is enabled. because there are no legitimate clients that encode UTF-8 this way since it is non-standard. So a request URI of “/foo\bar” gets normalized to “/foo/bar.>]} This option lets users receive an alert if certain non-RFC chars are used in a request URI. 19. You should alert on the iis unicode option.yk. 20. How the %u encoding scheme works is as follows: the encoding scheme is started by a %u followed by 4 characters. a user may not want to see null bytes in the request URI and we can alert on that. and %u. so ASCII is also enabled to enforce correct decoding. you must enable also enable utf 8 yes. use no. this option will not work. etc. non rfc char {<byte> [<byte .. 22.rim. We leave out utf-8 because I think how this works is that the % encoded utf-8 is decoded to the Unicode byte in the first pass. doing decodes in each one. This is not in the HTTP standard.or. because it is seen mainly in attacks and evasion attempts. alert on all ‘/’ or something like that. How this works is that IIS does two passes through the request URI. u encode <yes|no> This option emulates the IIS %u encoding scheme. iis unicode <yes|no> The iis unicode option turns on the Unicode codepoint mapping. 18. multi slash <yes|no> This option normalizes multiple slashes in a row. double decode <yes|no> The double decode option is once again IIS-specific and emulates IIS functionality. as all non-ASCII values have to be encoded with a %. When double decode is enabled. ASCII encoding is also enabled to enforce correct behavior. In the second pass. directory <yes|no> This option normalizes directory traversals and self-referential directories. For instance. To alert on UTF-8 decoding. ASCII. You should alert on %u encodings. It’s flexible. then configure with a yes. Bare byte encoding allows the user to emulate an IIS server and interpret non-standard encodings correctly. Don’t use the %u option.. So it is most likely someone trying to be covert.15. iis backslash <yes|no> Normalizes backslashes to slashes. this is really complex and adds tons of different encodings for one character.” If you want an alert when multiple slashes are seen. The xxxx is a hex-encoded value that correlates to an IIS Unicode codepoint.” 23. %u002e = . and then UTF-8 is decoded in the second stage.jp/˜ shikap/patch/spp\_http\_decode. /foo/fake\_dir/. but may also be false positive prone. so if the emulated web server is Apache. iis delimiter <yes|no> This started out being IIS-specific. Only use this option on servers that will accept URIs like this: ”get /index. chunk length <non-zero positive integer> This option is an anomaly detector for abnormally large chunk sizes. 25. The non strict option assumes the URI is between the first and second space even if there is no valid HTTP identifier after the second space. 24. and may also alert on HTTP tunneling that uses chunk encoding. pipeline requests are not decoded and analyzed per HTTP protocol field. otherwise. This means that no alert will be generated if the proxy alert global keyword has been used. no pipeline req This option turns HTTP pipeline decoding off. It is only inspected with the generic pattern matching. specify yes./bar gets normalized to: /foo/bar The directory: /foo/. 30. This should limit the alerts to IDS evasion type attacks. but Apache takes this non-standard delimiter was well. The argument specifies the max char directory length for URL directory. 29. apache whitespace <yes|no> This option deals with the non-RFC standard of using tab for a space delimiter. 64 .. then this option does nothing. oversize dir length <non-zero positive integer> This option takes a non-zero positive integer as an argument. and is a performance enhancement if needed. A good argument value is 300 characters. This picks up the Apache chunk encoding exploits. allow proxy use By specifying this keyword. non strict This option turns on non-strict URI parsing for the broken way in which Apache servers will decode a URI. This has no effect on HTTP rules in the rule set. enable this option. Since this is common. 27. 28. This alert may give false positives. like whisker -i 4. since some web sites refer to files using directory traversals. By default. If the proxy alert keyword is not enabled.html alsjdfk alsj lj aj la jsj s\n”. 31. The allow proxy use keyword is just a way to suppress unauthorized proxy use for an authorized server. the user is allowing proxy use on this server. If a url directory is larger than this argument size. no alerts This option turns off all alerts that are generated by the HTTP Inspect preprocessor module./bar gets normalized to: /foo/bar If you want to configure an alert. Alerts on this option may be interesting. But you can still get an alert on this option. pipeline requests are inspected for attacks. but when this option is enabled. an alert is generated. Apache uses this. specify no. 26. we always take this as standard since the most popular web servers accept it. No argument is specified. then no inspection will take place. Apache accepts tab as a delimiter.0\r\n\r\n No alert will be generated when inspect uri only is enabled. normalize cookies This option turns on normalization for HTTP Cookie Fields (using the same configuration parameters as the URI normalization (ie. and if there are none available. For IIS. 38. tab uri delimiter This option turns on the use of the tab character (0x09) as a delimiter for a URI. max header length <positive integer up to 65535> This option takes an integer as an argument. because it doesn’t alert on directory traversals that stay within the web server directory structure. specify an integer argument to max header length of 1 to 65535. The integer is the maximum length allowed for an HTTP client request header field. ”utf-16be”. not including Cookies (using the same configuration parameters as the URI normalization (ie. Specifying a value of 0 is treated as disabling the alert. When enabled. To enable. normalize headers This option turns on normalization for HTTP Header Fields. ”utf-32le”. Whether this option is on or not. To enable. This is obvious since the URI is only inspected with uricontent rules. directory. It is useful for normalizing Referrer URIs that may appear in the HTTP Header. It is useful for normalizing data in HTTP Cookies that may be encoded. So if you need extra performance. 39. 34. This generates much fewer false positives than the directory option. HTTP Inspect will attempt to normalize these back into 8-bit encoding. IIS does not.32. 37. This alert is off by default. For example. 36. multi-slash. Requests that exceed this length will cause a ”Long Header” alert. then there is nothing to inspect. or ”utf-32be”. 35. 33. a tab in the URI should be treated as any other character. enable this optimization. directory. etc. As this field usually contains 90-95% of the web attacks. The inspect uri only configuration turns off all forms of detection except uricontent inspection. webroot <yes|no> This option generates an alert when a directory traversal traverses past the web server root directory. content: "foo". if we have the following rule set: alert tcp any any -> any 80 ( msg:"content". normalize utf This option turns on normalization of HTTP response bodies where the Content-Type header lists the character set as ”utf-16le”.). The alert is off by default.htm http/1. It’s important to note that if this option is used without any uricontent rules. 65 .). etc. multi-slash. The integer is the maximum number of HTTP client request header fields. you’ll catch most of the attacks. max headers <positive integer up to 1024> This option takes an integer as an argument. It only alerts when the directory traversals go past the web server root directory. a tab is treated as whitespace if a space character (0x20) precedes it. inspect uri only This is a performance optimization. Specifying a value of 0 is treated as disabling the alert. ) and the we inspect the following URI: get /foo. No argument is specified. only the URI portion of HTTP requests will be inspected for attacks. Requests that contain more HTTP Headers than this value will cause a ”Max Header” alert. which is associated with certain web attacks. specify an integer argument to max headers of 1 to 1024. generating an alert if the extra bytes are non-zero. 66 .7 SMTP Preprocessor The SMTP preprocessor is an SMTP decoder for user applications. a loss of coherent stream data results in a loss of state). However maintaining correct state is dependent on the reassembly of the client side of the stream (ie. tabs. http methods {cmd[cmd]} This specifies additional HTTP Request Methods outside of those checked by default within the preprocessor (GET and POST). data header data body sections. The config option. SMTP will decode the buffer and find SMTP commands and responses. and TLS data. Given a data buffer.40. line feed or carriage return. SMTP handles stateless and stateful processing. It saves state between individual packets. The list should be enclosed within braces and delimited by spaces.2.1. It will also mark the command.1. braces and methods also needs to be separated by braces. http_methods { PUT CONNECT } ! △NOTE Please note the maximum length for a method name is 7 Examples preprocessor http_inspect_server: \ server 10. 9. max command line len <int> Alert if an SMTP command line is longer than this value. 10. Default is an empty list. 8. such as port and inspection type. cmds just checks commands listed with the normalize cmds parameter. inspection type <stateful | stateless> Indicate whether to operate in stateful or stateless mode. all checks all commands none turns off normalization for all commands. Absence of this option or a ”0” means never alert on response line length. invalid cmds { <Space-delimited list of commands> } Alert if this command is sent from client side. for encrypted SMTP. } 67 . Typically. 3. We do not alert on commands in this list. alt max command line len <int> { <cmd> [<cmd>] } Overrides max command line len for specific commands. TLS-encrypted traffic can be ignored. Normalization checks for more than one space character after a command. valid cmds { <Space-delimited list of commands> } List of valid commands. max header line len <int> Alert if an SMTP DATA header line is longer than this value. 6. no alerts Turn off all alerts for this preprocessor. Absence of this option or a ”0” means never alert on data header line length. 11. RFC 2821 recommends 1024 as a maximum data header line length. max response line len <int> Alert if an SMTP response line is longer than this value. 7.. } This specifies on what ports to check for SMTP data. Since so few (none in the current snort rule set) exploits are against mail data. RFC 2821 recommends 512 as a maximum response line length. RFC 2821 recommends 512 as a maximum command line length. this is relatively safe to do and can improve the performance of data inspection. Default is an empty list.. ports { <port> [<port>] . SMTP command lines can be normalized to remove extraneous spaces. Space characters are defined as space (ASCII 0x20) or tab (ASCII 0x09). ignore data Ignore data section of mail (except for mail headers) when processing rules. normalize <all | none | cmds> This turns on normalization. 12. 4. 5. which improves performance. this will include 25 and possibly 465.Configuration SMTP has the usual configuration items. In addition. ignore tls data Ignore TLS-encrypted data when processing rules. 2. Absence of this option or a ”0” means never alert on command line length. The configuration options are described below: 1. Also. regular mail data can be ignored for an additional performance boost. The default value for this in snort in 1460 bytes. alert unknown cmds Alert if we don’t recognize command. This value can be set from 3276 bytes to 100MB. Drop if alerted. xlink2state { enable | disable [drop] } Enable/disable xlink2state alert. 18.13. normalize cmds { <Space-delimited list of commands> } Normalize this list of commands Default is { RCPT VRFY EXPN }. The default value for this option is 838860. Note: It is suggested to set this value such that the max mime session calculated as follows is atleast 1. Default is off. 15. 19. This not normally printed out with the configuration because it can print so much data. Default is enable. max mime mem <int> This option determines (in bytes) the maximum amount of memory the SMTP preprocessor will use for decoding base64 encode MIME attachments/data. 17. This is useful when specifying the max mime depth and max mime mem in default policy without turning on the SMTP preprocessor. When stateful inspection is turned on the base64 encoded MIME attachments/data across multiple packets are decoded too. The option take values ranging from 5 to 20480 bytes. print cmds List all commands understood by the preprocessor. max mime session = max mime mem /(max mime depth + max decoded bytes) max decoded bytes = (max mime depth/4)*3 Also note that these values for max mime mem and max mime depth need to be same across all policy. } \ 68 . enable mime decoding Enables Base64 decoding of Mime attachments/data. max mime depth <int> Specifies the maximum number of base64 encoded data to decode per SMTP session. See 3. disabled Disables the SMTP preprocessor in a policy. 20. This option along with max mime depth determines the base64 encoded MIME/SMTP sessions that will be decoded at any given instant. Multiple base64 encoded MIME attachments/data in one packet are pipelined.24 rule option for more details. The decoding of base64 encoded attachments/data ends when either the max mime depth or maximum MIME sessions (calculated using max mime depth and max mime mem) is reached or when the encoded data ends.5. 14. The decoded data is available for detection using the rule option file data:mime. 16. there are four areas of configuration: Global. and FTP Server. This argument specifies whether the user wants the configuration option to generate a ftptelnet alert or not. Users can configure individual FTP servers and clients with a variety of options. } \ } \ HELO ETRN } \ VRFY } 2. meaning it looks for information and handles reassembled data correctly.6). The default is to run FTP/Telnet in stateful inspection mode. they are referred to as RCPT and MAIL. For the preprocessor configuration. ! △NOTE Some configuration options have an argument of yes or no. The following example gives the generic global configuration format: 69 . the preprocessor actually maps RCPT and MAIL to the correct command name. meaning it only looks for information on a packet-bypacket basis. Within FTP/Telnet. similar to that of HTTP Inspect (See 2. FTP/Telnet has a very “rich” user configuration.8 FTP/Telnet Preprocessor FTP/Telnet is an improvement to the Telnet decoder and provides stateful inspection capability for both FTP and Telnet data streams. The presence of the option indicates the option itself is on. which should allow the user to emulate any type of FTP server or FTP Client. Global Configuration The global configuration deals with configuration options that determine the global functioning of FTP/Telnet. FTP/Telnet has the capability to handle stateless processing. while the yes/no argument applies to the alerting functionality associated with that option. respectively. FTP/Telnet will decode the stream. Telnet. Within the code.2.2. FTP Client. identifying FTP commands and responses and Telnet escape sequences and normalize the fields. FTP/Telnet works on both client requests and server responses. encrypted traffic <yes|no> This option enables detection and alerting on encrypted Telnet and FTP command channels. Configuration 1. 70 . you’ll get an error if you try otherwise.. and subsequent instances will override previously set values. The FTP/Telnet global configuration must appear before the other three areas of configuration. whereas in stateful mode. check encrypted Instructs the preprocessor to continue to check an encrypted session for a subsequent command to cease encryption.Format preprocessor ftp_telnet: \ global \ inspection_type stateful \ encrypted_traffic yes \ check_encrypted You can only have a single global configuration. 2. inspection type This indicates whether to operate in stateful or stateless mode. 3. a particular session will be noted as encrypted and not inspected any further. checks for encrypted traffic will occur on every packet. ! △NOTE When inspection type is in stateless mode. It functions similarly to its predecessor. certain implementations of Telnet servers will ignore the SB without a corresponding SE. so adding port 22 will only yield false positives. Most of your FTP servers will most likely end up using the default configuration. it is also susceptible to this behavior. Typically port 23 will be included. the telnet decode preprocessor. Being that FTP uses the Telnet protocol on the control connection. detect anomalies In order to support certain options. 2. It is only applicable when the mode is stateful.1. the only difference being that specific IPs can be configured.1. >]} 73 for the list of options set in default ftp server configuration.. SSH tunnels cannot be decoded.1 ports { 21 } ftp_cmds { XPWD XCWD } 71 . Rules written with ’raw’ content options will ignore the normalized buffer that is created when this option is in use. Default This configuration supplies the default server configuration for any FTP server that is not individually configured. ports {<port> [<port>< . 3. However.. Telnet supports subnegotiation.. normalize This option tells the preprocessor to normalize the telnet traffic by eliminating the telnet escape sequences. subnegotiation begins with SB (subnegotiation begin) and must end with an SE (subnegotiation end).Configuration 1. 4. The detect anomalies option enables alerting on Telnet SB without the corresponding SE. Configuration by IP Address This format is very similar to “default”. This is anomalous behavior which could be an evasion case. Example IP specific FTP Server Configuration preprocessor _telnet_protocol: \ ftp server 10. ayt attack thresh < number > This option causes the preprocessor to alert when the number of consecutive telnet Are You There (AYT) commands reaches the number specified. optional value enclosed within [] 72 string host port long host port extended host port {}. where: n Number C Character [] optional format enclosed | OR {} choice of options .FTP Server Configuration Options 1. chk str fmt {cmd[cmd]} This option causes a check for string format attacks in the specified commands. def max param len <number> This specifies the default maximum allowed parameter length for an FTP command. 7. ports {<port> [<port>< . per RFC 2428 One of choices enclosed within. | {}. ftp cmds {cmd[cmd]} The preprocessor is configured to alert when it sees an FTP command that is not allowed by the server. this option causes the preprocessor to print the configuration for each of the FTP commands for this server. [] . For example: ftp_cmds { XPWD XCWD XCUP XMKD XRMD } 4. per RFC 959 Parameter must be a long host port specified. This option specifies a list of additional commands allowed by this server. >]} This is how the user configures which ports to decode as FTP command channel traffic. fmt must be enclosed in <>’s and may contain the following: Value int number char <chars> date <datefmt> Description Parameter must be an integer Parameter must be an integer between 1 and 255 Parameter must be a single character. so the appropriate configuration would be: alt_max_param_len 16 { USER } 6. outside of the default FTP command set as specified in RFC 959. 2. 5. as well as any additional commands as needed. alt max param len <number> {cmd[cmd]} This specifies the maximum allowed parameter length for the specified FTP command(s). It can be used as a basic buffer overflow detection. 3. per RFC 1639 Parameter must be an extended host port specified. For example the USER command – usernames may be no longer than 16 bytes. one of <chars> Parameter follows format specified. Typically port 21 will be included.. It can be used as a more specific buffer overflow detection. This may be used to allow the use of the ’X’ commands identified in RFC 775. + .literal Parameter is a string (effectively unrestricted) Parameter must be a host/port specified. cmd validity cmd < fmt > This option specifies the valid format for parameters of a given command. print cmds During initialization.. separated by | One of the choices enclosed within {}. Setting this option to ”yes” means that NO INSPECTION other than TCP state will be performed on FTP data transfers. accept a format using YYYYMMDDHHmmss[.ietf. cmd_validity MODE < char ASBCZ > # Allow for a date in the MDTM command. ”data chan” will be removed in a future release. Injection of telnet escape sequences could be used as an evasion attempt on an FTP command channel. cmd_validity MDTM < [ date nnnnnnnnnnnnnn[.n[n[n]]] ] string > MDTM is an off case that is worth discussing. If your rule set includes virus-type rules. ignore data chan <yes|no> This option causes the rest of Snort (rules.uuu]. While not part of an established standard. especially with large file transfers from a trusted source. 9. Using this option means that NO INSPECTION other than TCP state will be performed on FTP data transfers. including mode Z which allows for # zip-style compression.Examples of the cmd validity option are shown below. # This allows additional modes. 11. especially with large file transfers from a trusted source. If your rule set includes virus-type rules.txt) To check validity for a server that uses the TZ format. Some FTP servers do not process those telnet escape sequences. per RFC 959 and others performed by the preprocessor. other preprocessors) to ignore FTP data channel connections. FTP Server Base Configuration Options The base FTP server configuration is as follows. use the following: cmd_validity MDTM < [ date nnnnnnnnnnnnnn[{+|-}n[n]] ] string > 8.org/internetdrafts/draft-ietf-ftpext-mlst-16. it is recommended that this option not be. The most common among servers that do. ignore telnet erase cmds <yes|no> This option allows Snort to ignore telnet escape sequences for erase character (TNC EAC) and erase line (TNC EAL) when normalizing FTP command channel. 73 . It can be used to improve performance. telnet cmds <yes|no> This option turns on detection and alerting when telnet escape sequences are seen on the FTP command channel. Options specified in the configuration file will modify this set of options. 10. The other options will override those in the base configuration. These examples are the default checks. Some others accept a format using YYYYMMDDHHmmss[+—]TZ format. It can be used to improve performance. The example above is for the first case (time format as specified in. other preprocessors) to ignore FTP data channel connections. Use of the ”data chan” option is deprecated in favor of the ”ignore data chan” option. data chan This option causes the rest of snort (rules. FTP commands are added to the set of allowed commands. certain FTP servers accept MDTM commands that set the modification time on a file.] > 74. ! △NOTE } \ 75. 76 or if a client generates server traffic. and Experimental Record Types..9. The available configuration options are described below. If Challenge-Response Overflow or CRC 32 false positive. the preprocessor will stop processing traffic for a given session. Example Configuration from snort.conf Looks for attacks on SSH server port 22.. enable protomismatch Enables checking for the Protocol Mismatch exploit. 2. enable paysize Enables alerts for invalid payload sizes. 10. enable experimental types Alert on Experimental (per RFC 1035) Record Types 4. Obsolete Record Types. 11. DNS looks at DNS Response traffic over UDP and TCP and it requires Stream preprocessor to be enabled for TCP decoding. 2. After max encrypted packets is reached. ports {<port> [<port>< . enable recognition Enable alerts for non-SSH traffic on SSH ports. try increasing the number of required client bytes with max client bytes. if the presumed server generates client traffic.2. 1.10 DNS The DNS preprocessor decodes DNS Responses and can detect the following exploits: DNS Client RData Overflow. >]} This option specifies the source ports that the DNS preprocessor should inspect traffic. The SSH preprocessor should work by default. enable badmsgdir Enable alerts for traffic flowing the wrong direction. Configuration By default. 12. enable obsolete types Alert on Obsolete (per RFC 1035) Record Types 3. For instance. all alerts are disabled and the preprocessor checks traffic on port 53. enable rdata overflow Check for DNS Client RData TXT Overflow 77 . Typically.The DNS preprocessor does nothing if none of the 3 vulnerabilities it checks for are enabled. Check for the DNS Client RData overflow vulnerability. the only observed response from one endpoint will be TCP ACKs. ports {<port> [<port>< . Verifying that faultless encrypted traffic is sent from both endpoints ensures two things: the last client-side handshake packet was not crafted to evade Snort. such as the handshake. 3.11 SSL/TLS Encrypted traffic should be ignored by Snort for both performance reasons and to reduce false positives. preprocessor dns: \ ports { 53 } \ enable_rdata_overflow 2. Therefore. Configuration 1. the user should use the ’trustservers’ option. SSL is used over port 443 as HTTPS. >]} This option specifies which ports SSLPP will inspect traffic on. SSLPP watches the following ports: • • • • • • • • • 443 HTTPS 465 SMTPS 563 NNTPS 636 LDAPS 989 FTPS 992 TelnetS 993 IMAPS 994 IRCS 995 POPS 2. By enabling the SSLPP to inspect port 443 and enabling the noinspect encrypted option. It will not operate on TCP sessions picked up midstream.. Default is off. no further inspection of the data on the connection is made. This requires the noinspect encrypted option to be useful. 78 . By default. Do not alert on obsolete or experimental RData record types. Use this option for slightly better performance if you trust that your servers are not compromised. if a user knows that server-side encrypted data can be trusted to mark the session as encrypted. SSLPP looks for a handshake followed by encrypted traffic traveling to both sides. and it will cease operation on a session if it loses state because of missing data (dropped packets). If one side responds with an indication that something has failed. In some cases. By default. the session is not marked as encrypted. documented below. and that the traffic is legitimately encrypted. only the SSL handshake of each connection will be inspected.. The SSL Dynamic Preprocessor (SSLPP) decodes SSL and TLS traffic and optionally determines if and when Snort should stop inspection of it.conf Looks for traffic on DNS server port 53. especially when packets may be missed. trustservers Disables the requirement that application (encrypted) data must be observed on both sides of the session before a session is marked encrypted. noinspect encrypted Disable inspection on traffic that is encrypted. Once the traffic is determined to be encrypted.2. Examples/Default Configuration from snort. Default is off. and are OR’ed together.0. ssl_version:tls1. via a comma separated list. The option will match if the connection is currently in any one of the OR’ed states. Lists of identifiers are OR’ed together.2. ssl_state:client_keyx. To ensure the connection has reached each of a set of states. multiple rules using the ssl state rule option should be used.1. state-list state = ["!"] "client_hello" | "server_hello" | "client_keyx" | "server_keyx" | "unknown" Examples ssl_state:client_hello. via a comma separated list.2" Examples ssl_version:sslv3. ssl_version:!sslv2.server_keyx.0" | "tls1. version-list version = ["!"] "sslv2" | "sslv3" | "tls1.Examples/Default Configuration from snort. ssl state The ssl state rule option tracks the state of the SSL encryption during the process of hello and key exchange. The option will match if any one of the OR’ed versions are used in the SSL connection.tls1. multiple ssl version rule options should be used. ssl_state:!server_hello.tls1. Syntax ssl_version: <version-list> version-list = version | version .. The list of version identifiers are below. To check for two or more SSL versions in use simultaneously. The list of states are below.conf Enables the SSL preprocessor and tells it to disable inspection on encrypted traffic. and more than one identifier can be specified.1" | "tls1. 79 . Syntax ssl_state: <state-list> state-list = state | state . More than one state can be specified. UDP and RPC over HTTP v.40.168. the preprocessor checks for unicast ARP requests. When no arguments are specified to arpspoof. The preprocessor will use this list when detecting ARP cache overwrite attacks. Write Block Raw. When inconsistency occurs.168.40.12 ARP Spoof Preprocessor The ARP spoof preprocessor decodes ARP packets and detects ARP attacks. Specify a pair of IP and hardware address as the argument to arpspoof detect host.2 f0:0f:00:f0:0f:01 The third example configuration has unicast detection enabled. Transaction Secondary.40. Format preprocessor arpspoof[: -unicast] preprocessor arpspoof_detect_host: ip mac Option ip mac Description IP address.2 f0:0f:00:f0:0f:01 2. the preprocessor inspects Ethernet addresses and the addresses in the ARP packets.40. Write AndX. and inconsistent Ethernet to IP mapping. preprocessor arpspoof The next example configuration does not do unicast detection but monitors ARP mapping for hosts 192.2.2. Alert SID 4 is used in this case.1 proxy and server. preprocessor arpspoof: -unicast preprocessor arpspoof_detect_host: 192.168. TCP. Specify one host IP MAC combo per line. an alert with GID 112 and SID 2 or 3 is generated. The preprocessor merely looks for Ethernet address inconsistencies. The host with the IP address should be on the same layer 2 segment as Snort is.168. reduce false positives and reduce the count and complexity of DCE/RPC based rules. Read Block Raw and Read AndX. Read.1 f0:0f:00:f0:0f:00 preprocessor arpspoof_detect_host: 192. Write and Close.2. An alert with GID 112 and SID 1 will be generated if a unicast ARP request is detected. Transaction. SMB desegmentation is performed for the following commands that can be used to transport DCE/RPC requests and responses: Write.168. The Ethernet address corresponding to the preceding IP. preprocessor arpspoof preprocessor arpspoof_detect_host: 192. New rule options have been implemented to improve performance. 80 .40.1 f0:0f:00:f0:0f:00 preprocessor arpspoof_detect_host: 192.1 and 192. Example Configuration The first example configuration does neither unicast detection nor ARP mapping monitoring. The following transports are supported for DCE/RPC: SMB. When ”-unicast” is specified as the argument of arpspoof.2. unicast ARP requests.168.13 DCE/RPC 2 Preprocessor The main purpose of the preprocessor is to perform SMB desegmentation and DCE/RPC defragmentation to avoid rule evasion using these techniques.40. along with a valid FID can be used to make a request. Some important differences: Named pipe instance tracking A combination of valid login handle or UID. servers or autodetecting. Samba 3.22 and earlier Any valid UID and TID. If it is decided that a session is SMB or DCE/RPC.22 and earlier. does not accept: 81 . no more requests can be written to that named pipe instance. Windows 2003 Windows XP Windows Vista These Windows versions require strict binding between the UID. i. the frag3 preprocessor should be enabled and configured. no binding. the FID becomes invalid. no more requests can be written to that named pipe instance. i. requests after that follow the same binding as Samba 3. if the TID used in creating the FID is deleted (via a tree disconnect). The preprocessor requires a session tracker to keep its data.22 in that deleting the UID or TID used to create the named pipe instance also invalidates it. It also follows Samba greater than 3. i.e. If the TID used to create the FID is deleted (via a tree disconnect). However. share handle or TID and file/named pipe handle or FID must be used to write data to a named pipe. TID and FID used to make a request to a named pipe instance. since it is necessary in making a request to the named pipe. the dcerpc2 preprocessor will enable stream reassembly for that session if necessary. the FID that was created using this TID becomes invalid. Samba (all versions) Under an IPC$ tree.0.e.0. i. stream5. Windows 2000 Windows 2000 is interesting in that the first request to a named pipe must use the same binding as that of the other Windows versions. either through configured ports. only the UID used in opening the named pipe can be used to make a request using the FID handle to the named pipe instance. Both the UID and TID used to open the named pipe instance must be used when writing data to the same named pipe instance.22 Any valid TID. Target Based There are enough important differences between Windows and Samba versions that a target based approach has been implemented. • Stream reassembly must be performed for TCP sessions. Therefore.0. i. deleting either the UID or TID invalidates the FID.Dependency Requirements For proper functioning of the preprocessor: • Stream session tracking must be enabled.e. However.e. however. Samba greater than 3. along with a valid FID can be used to make a request. If the UID used to create the named pipe instance is deleted (via a Logoff AndX).e. • IP defragmentation should be enabled. Accepted SMB commands Samba in particular does not recognize certain commands under an IPC$ tree. the FID that was created using this TID becomes invalid. The binding between these is dependent on OS/software version.0. Multiple Bind Requests A Bind request is the first request that must be made in a connection-oriented DCE/RPC session in order to specify the interface/interfaces that one wants to communicate with.e.20 Another Bind request can be made if the first failed and no interfaces were successfully bound to. only one Bind can ever be made on a session whether or not it succeeds or fails. What distinguishes them (when the same named pipe is being written to. the client has to explicitly send one of the Read* requests to tell the server to send the response and (2) a Transaction request is not written to the named pipe until all of the data is received (via potential Transaction Secondary requests) whereas with the Write* commands. all previous interface bindings are invalidated. Windows (all versions) For all of the Windows versions. Samba. i.0. whereas in using the Write* commands. Windows (all versions) Uses a combination of PID and MID to define a ”thread”. e. we don’t want to keep track of data that the server won’t accept. login/logoff and tree connect/tree disconnect.0. Ultimately. Segments for each ”thread” are stored separately and written to the named pipe when all segments are received. Transaction tracking The differences between a Transaction request and using one of the Write* commands to write data to a named pipe are that (1) a Transaction performs the operations of a write and a read from the named pipe. Multiple Transaction requests can be made simultaneously to the same named pipe. Samba (all versions) Uses just the MID to define a ”thread”. The PID represents the process this request is a part of. is very lax and allows some nonsensical combinations.Context ID 82 . An evasion possibility would be accepting a fragment in a request that the server won’t accept that gets sandwiched between an exploit. DCE/RPC Fragmented requests . An MID represents different sub-processes within a process (or under a PID). These requests can also be segmented with Transaction Secondary commands. data is written to the named pipe as it is received by the server. having the same FID) are fields in the SMB header representing a process id (PID) and multiplex id (MID).Open Write And Close Read Read Block Raw Write Block Raw Windows (all versions) Accepts all of the above commands under an IPC$ tree. multiple logins and tree connects (only one place to return handles for these). Samba 3. all previous interface bindings are invalidated.20 and earlier Any amount of Bind requests can be made. If a Bind after a successful Bind is made. Samba later than 3. on the other hand. AndX command chaining Windows is very strict in what command combinations it allows to be chained. It is necessary to track this so as not to munge these requests together (which would be a potential evasion opportunity). Any binding after that must use the Alter Context request.g. If another Bind is made. Only one global dcerpc2 configuration can be specified.. The context id field in any other fragment can contain any value. The context id field in any other fragment can contain any value.Operation number Each fragment in a fragmented request carries an operation number (opnum) which is more or less a handle to a function offered by the interface. DCE/RPC Fragmented requests . DCE/RPC Stub data byte order The byte order of the stub data is determined differently for Windows and Samba. Windows Vista The opnum that is ultimately used for the request is contained in the first fragment.Each fragment in a fragmented request carries the context id of the bound interface it wants to make the request to. Samba (all versions) The context id that is ultimately used for the request is contained in the last fragment. Samba (all versions) The byte order of the stub data is that which is used in the request carrying the stub data. The opnum field in any other fragment can contain any value. Windows (all versions) The context id that is ultimately used for the request is contained in the first fragment. Global Configuration preprocessor dcerpc2 The global dcerpc2 configuration is required. Windows (all versions) The byte order of the stub data is that which was used in the Bind request. Samba (all versions) Windows 2000 Windows 2003 Windows XP The opnum that is ultimately used for the request is contained in the last fragment. Configuration The dcerpc2 preprocessor has a global configuration and one or more server configurations. Option syntax Option memcap disable defrag max frag len events reassemble threshold disabled Argument <memcap> NONE <max-frag-len> <events> <re-thresh> NONE Required NO NO NO NO NO NO 83 Default memcap 102400 OFF OFF OFF OFF OFF . alert. in effect.65535. Default is disabled.) memcap Only one event. If a fragment is greater than this size. If the memcap is reached or exceeded. This option is useful in inline mode so as to potentially catch an exploit early before full defragmentation is done. disable this option. Run-time memory includes any memory allocated after configuration.memcap max-frag-len events pseudo-event event-list event re-thresh = = = = = = = 1024-4194303 (kilobytes) 1514-65535 pseudo-event | event | ’[’ event-list ’]’ "none" | "all" event | event ’. disable defrag Tells the preprocessor not to do DCE/RPC defragmentation. Default is to do defragmentation. smb. smb Alert on events related to SMB processing. Default is set to -1. co Stands for connection-oriented DCE/RPC. disabled Disables the preprocessor. By default this value is turned off. Alert on events related to connection-oriented DCE/RPC processing. reassemble threshold Specifies a minimum number of bytes in the DCE/RPC desegmentation and defragmentation buffers before creating a reassembly packet to send to the detection engine. The allowed range for this option is 1514 . it is truncated before being added to the defragmentation module. max frag len Specifies the maximum fragment size that will be added to the defragmention module. Option examples memcap 30000 max_frag_len 16840 events none events all events smb events co events [co] events [smb. A value of 0 supplied as an argument to this option will. (See Events section for an enumeration and explanation of events. co] events [memcap. co.’ event-list "memcap" | "smb" | "co" | "cl" 0-65535 Option explanations memcap Specifies the maximum amount of run-time memory that can be allocated. Alert on events related to connectionless DCE/RPC processing. cl] reassemble_threshold 500 84 . Default is 100 MB. events Specifies the classes of events to enable. cl Stands for connectionless DCE/RPC. When the preprocessor is disabled only the memcap option is applied when specified with the configuration. A net configuration matches if the packet’s server IP address matches an IP address or net specified in the net configuration. events smb memcap 50000. For any dcerpc2 server configuration. The default and net options are mutually exclusive. The net option supports IPv6 addresses. Option syntax Option default net policy detect Argument NONE <net> <policy> <detect> Required YES YES NO NO Default NONE NONE policy WinXP detect [smb [139. udp 135.0. the default configuration is used if no net configurations match. A dcerpc2 server configuration must start with default or net options.20" "none" | detect-opt | ’[’ detect-list ’]’ detect-opt | detect-opt ’. Note that port and ip variables defined in snort. udp 1025:.conf CANNOT be used. tcp 135. if non-required options are not specified. co. it will override the default configuration. rpc-over-http-server 593] autodetect [tcp 1025:. events [memcap.. If no default configuration is specified. events [memcap. smb. Zero or more net configurations can be specified. If a net configuration matches.. max_frag_len 14440 disable_defrag.’ detect-list transport | transport port-item | transport ’[’ port-list ’]’ "smb" | "tcp" | "udp" | "rpc-over-http-proxy" | "rpc-over-http-server" port-item | port-item ’. = = = = = = = = = = = = = = = = = <detect> NONE <shares> <max-chain> NO NO NO NO ip | ’[’ ip-list ’]’ ip | ip ’. At most one default configuration can be specified. memcap 300000.0.’ port-list port | port-range ’:’ port | port ’:’ | port ’:’ port 0-65535 85 . default values will be used for the default configuration.445].22" | "Samba-3. the defaults will be used. When processing DCE/RPC traffic. the preprocessor will always attempt to autodetect for ports specified in the detect configuration for rpc-over-http-proxy. This option is useful if the RPC over HTTP proxy configured with the detect option is only used to proxy DCE/RPC traffic. It would be very uncommon to see SMB on anything other than ports 139 and 445. Default is empty. The autodetect ports are only queried if no detect transport/ports match the packet. This is because the proxy is likely a web server and the preprocessor should not look at all web traffic. autodetect Specifies the DCE/RPC transport and server ports that the preprocessor should attempt to autodetect on for the transport. UDP and RPC over HTTP server. Option examples 86 .. detect Specifies the DCE/RPC transport and server ports that should be detected on for the transport. no autodetect http proxy ports By default. Defaults are ports 139 and 445 for SMB. Default maximum is 3 chained commands.TCP/UDP. smb max chain Specifies the maximum amount of AndX command chaining that is allowed before an alert is generated. policy Specifies the target-based policy to use when processing. 135 for TCP and UDP. Default is ”WinXP”. Defaults are 1025-65535 for TCP.’ ’"’ ’]’ ’[’ 0-255 Because the Snort main parser treats ’$’ as the start of a variable and tries to expand it. Option explanations default Specifies that this configuration is for the default server configuration.shares share-list share word var-word max-chain = = = = = = share | ’[’ share-list ’]’ share | share ’. Default is to autodetect on RPC over HTTP proxy detect ports. This value can be set from 0 to 255. RPC over HTTP server.’ share-list word | ’"’ word ’"’ | ’"’ var-word ’"’ graphical ASCII characters except ’. RPC over HTTP proxy and lastly SMB. A value of 0 disables this option.’ ’"’ ’]’ ’[’ ’$’ graphical ASCII characters except ’. 593 for RPC over HTTP server and 80 for RPC over HTTP proxy. shares with ’$’ must be enclosed quotes. smb invalid shares Specifies SMB shares that the preprocessor should alert on if an attempt is made to connect to them via a Tree Connect or Tree Connect AndX. The order in which the preprocessor will attempt to autodetect will be . Note that most dynamic DCE/RPC ports are above 1024 and ride directly over TCP or UDP. 3003:] autodetect [tcp [2025:3001.168. udp 135.0/24. autodetect none Default server configuration preprocessor dcerpc2_server: default. \ detect [smb.3003:]] autodetect [tcp. rpc-over-http-proxy [1025:6001.445].168.feab:45b3::/126].0/255. detect [smb.168. smb_max_chain 3 Complete dcerpc2 default configuration 87 . udp] autodetect [tcp 2025:.56. rpc-over-http-server 593]. tcp 135. tcp]. "ADMIN$"]. udp 135.11.22 detect none detect smb detect [smb] detect smb 445 detect [smb 445] detect smb [139. udp 2025:] autodetect [tcp 2025:. rpc-over-http-server [1025:6001. policy WinVista.445]. autodetect tcp 1025:.0/24.11.445] detect [smb [139.0.4.0.57]. rpc-over-http-server [593.4.10.10.4. udp 1025:.net 192.168. smb_max_chain 1 preprocessor dcerpc2_server: \ net [10. policy Win2000 preprocessor dcerpc2_server: \ default.10 net 192.4. tcp 135.4. feab:45b3:ab92:8ac4:d322:007f:e5aa:7845] policy Win2000 policy Samba-3. \ smb_invalid_shares ["C$". "ADMIN$"] preprocessor dcerpc2_server: net 10.168. policy WinXP. \ detect [smb [139.0/24. policy Win2000. "C$"] smb_invalid_shares ["private".6002:6004]] autodetect none autodetect tcp autodetect [tcp] autodetect tcp 2025: autodetect [tcp 2025:] autodetect tcp [2025:3001. policy Samba.255.0.168.0.445]] detect [smb.0. detect smb. feab:45b3::/32] net [192.2103]] detect [smb [139. \ autodetect [tcp 1025:.10.10. tcp [135.6005:]].6005:]] smb_invalid_shares private smb_invalid_shares "private" smb_invalid_shares "C$" smb_invalid_shares [private. "C$"] smb_max_chain 1 Configuration examples preprocessor dcerpc2_server: \ default preprocessor dcerpc2_server: \ default. no_autodetect_http_proxy_ports preprocessor dcerpc2_server: \ net [10. rpc-over-http-server 1025:].0.0/24] net 192.10. autodetect [tcp. policy WinVista.0. policy Win2000 preprocessor dcerpc2_server: \ net [10. rpc-over-http-proxy 8081].feab:45b3::/126]. \ smb_invalid_shares ["C$". tcp] detect [smb 139. "D$".0/24 net [192.255. tcp.0/24. udp. especially the commands from the SMB Core implementation require a data format field that specifies the kind of data that will be coming next. Some commands require a specific format for the data. SMB events SID 2 Description An invalid NetBIOS Session Service type was specified in the header. the preprocessor will alert. \ detect [smb [139. udp 1025:. have a field containing the total amount of data to be transmitted. SMB commands have pretty specific word counts and if the preprocessor sees a command with a word count that doesn’t jive with that command. Request (only from client). The word count of the command header is invalid.. The preprocessor will alert if the remaining NetBIOS packet length is less than the size of the SMB command byte count specified in the command header. Memcap events SID 1 Description If the memory cap is reached and the preprocessor is configured to alert. Some SMB commands. id of \xfeSMB is turned away before an eventable point is reached. If a command requires this and the byte count is less than the minimum required byte count for that command. The SMB id does not equal \xffSMB. such as Transaction. The preprocessor will alert if the NetBIOS Session Service length field contains a value less than the size of an SMB header. Retarget Response (only from server) and Keep Alive. (Total data count must always be greater than or equal to current data size. rpc-over-http-server 1025:]. rpc-over-http-server 593]. \ autodetect [tcp 1025:. the preprocessor will alert. the preprocessor will alert. Valid types are: Message. If this offset puts us before data that has already been processed or after the end of payload. udp 135. Positive Response (only from server). tcp 135. Some commands require a minimum number of bytes after the command header. An SMB message type was specified in the header.445]. the preprocessor will alert. Either a request was made by the server or a response was given by the client.) 3 4 5 6 7 8 9 10 11 12 13 14 88 . The preprocessor will alert if the remaining NetBIOS packet length is less than the size of the SMB command header to be decoded. If this field is zero. Negative Response (only from server).preprocessor dcerpc2: memcap 102400 preprocessor dcerpc2_server: \ default. Some commands. The preprocessor will alert if the remaining NetBIOS packet length is less than the size of the SMB command data size specified in the command header. policy WinXP. Many SMB commands have a field containing an offset from the beginning of the SMB header to where the data the command is carrying starts. smb_max_chain 3 Events The preprocessor uses GID 133 to register events. 89 . When a Session Setup AndX request is sent to the server. With commands that are chained after a Session Setup AndX request. It looks for a Tree Connect or Tree Connect AndX to the share. The combination of a Open AndX or Nt Create AndX command with a chained Close command. The Tree Disconnect command is used to disconnect from that share. (The byte count must always be greater than or equal to the data size. essentially logins in and logs off in the same request and is anomalous behavior. The preprocessor will alert if it sees this. An Open AndX or Nt Create AndX command is used to open/create a file or named pipe. the preprocessor has to queue the requests up and wait for a server response to determine whether or not an IPC share was successfully connected to (which is what the preprocessor is interested in). The preprocessor will alert if it sees this. The preprocessor will alert if the number of chained commands in a single request is greater than or equal to the configured amount (default is 3). the server responds (if the client successfully authenticates) which a user id or login handle. only one place in the SMB header to return a tree handle (or Tid). The preprocessor will alert if the byte count specified in the SMB command header is less than the data size specified in the SMB command. so it need to be queued with the request and dequeued with the response.) The Close command is used to close that file or named pipe. There should be under normal circumstances no more than a few pending tree connects at a time and the preprocessor will alert if this number is excessive. however. The combination of a Tree Connect AndX command with a chained Tree Disconnect command. however Samba does. The server response. does not contain this file id. Windows does not allow this behavior. The preprocessor will alert if it sees any of the invalid SMB shares configured. (The preprocessor is only interested in named pipes as this is where DCE/RPC requests are written to. they are responded to in the order they were sent. The combination of a Session Setup AndX command with a chained Logoff AndX command. With AndX command chaining it is possible to chain multiple Session Setup AndX commands within the same request. The Read* request contains the file id associated with a named pipe instance that the preprocessor will ultimately send the data to. This is anomalous behavior and the preprocessor will alert if it happens. however Samba does. A Logoff AndX request is sent by the client to indicate it wants to end the session and invalidate the login handle. there is no indication in the Tree Connect response as to whether the share is IPC or not. A Tree Connect AndX command is used to connect to a share. The preprocessor will alert if the byte count minus a predetermined amount based on the SMB command is not equal to the data size. For the Tree Connect command (and not the Tree Connect AndX command). it issues a Read* command to the server to tell it to send a response to the data it has written. With AndX command chaining it is possible to chain multiple Tree Connect AndX commands within the same request. essentially connects to a share and disconnects from the same share in the same request and is anomalous behavior. only one place in the SMB header to return a login handle (or Uid). Unlike the Tree Connect AndX response. There should be under normal circumstances no more than a few pending Read* requests at a time and the preprocessor will alert if this number is excessive. however.15 16 17 18 19 20 21 22 23 24 25 26 The preprocessor will alert if the total amount of data sent in a transaction is greater than the total data count specified in the SMB command header. essentially opens and closes the named pipe in the same request and is anomalous behavior. The preprocessor will alert if it sees this. There is. Windows does not allow this behavior. the login handle returned by the server is used for the subsequent chained commands. however. This is anomalous behavior and the preprocessor will alert if it happens. This is used by the client in subsequent requests to indicate that it has authenticated. There is.) Some of the Core Protocol commands (from the initial SMB implementation) require that the byte count be some value greater than the data size exactly. In this case the preprocessor is concerned with the server response. If multiple Read* requests are sent to the server. After a client is done writing data using the Write* commands. this number should stay the same for all fragments. The operation number specifies which function the request is calling on the bound interface.. If a request is fragmented. wrapping the sequence number space produces strange behavior from the server. The byte order of the request data is determined by the Bind in connection-oriented DCE/RPC for Windows. The preprocessor will alert if the connectionless DCE/RPC PDU type is not a valid PDU type. If a request if fragmented. The context id is a handle to a interface that was bound to. The preprocessor will alert if the opnum changes in a fragment mid-request. The preprocessor will alert if it changes in a fragment mid-request. 35 36 37 38 39 90 .Connection-oriented DCE/RPC events SID 27 28 29 30 31 32 33 34 Description The preprocessor will alert if the connection-oriented DCE/RPC major version contained in the header is not equal to 5. there are no transfer syntaxes to go with the requested interface. so this should be considered anomalous behavior. Most evasion techniques try to fragment the data as much as possible and usually each fragment comes well below the negotiated transmit size. this number should stay the same for all fragments. The call id for a set of fragments in a fragmented request should stay the same (it is incremented for each complete request). In testing. The preprocessor will alert if in a Bind or Alter Context request. It is anomalous behavior to attempt to change the byte order mid-session. The preprocessor will alert if the fragment length defined in the header is less than the size of the header. there are no context items specified. The preprocessor will alert if the connection-oriented DCE/RPC PDU type contained in the header is not a valid PDU type. The preprocessor will alert if the packet data length is less than the size of the connectionless header. The preprocessor will alert if in a Bind or Alter Context request. The preprocessor will alert if the context id changes in a fragment mid-request. The preprocessor will alert if a fragment is larger than the maximum negotiated fragment length. The preprocessor will alert if the remaining fragment length is less than the remaining packet size. The preprocessor will alert if a non-last fragment is less than the size of the negotiated maximum fragment length. Optional arguments are an interface version and operator to specify that the version be less than (’<’). Also. It is necessary for a client to bind to a service before being able to make a call to it. The preprocessor eliminates the need for two rules by normalizing the UUID. A DCE/RPC request can specify whether numbers are represented as big endian or little endian. Each interface UUID is paired with a unique index (or context id) that future requests can use to reference the service that the client is making a call to. Each interface is represented by a UUID. however. say 5 bytes into the request (maybe it’s a length field). if the any frag option is used to specify evaluating on all fragments. When a client sends a bind request to the server. specify one or more service interfaces to bind to. This option requires tracking client Bind and Alter Context requests as well as server Bind Ack and Alter Context responses for connection-oriented DCE/RPC in the preprocessor. A rule which is looking for data. i.. will be looking at the wrong data on a fragment other than the first. whether or not the client has bound to a specific interface UUID and whether or not this client request is making a request to it. the client specifies a list of interface UUIDs along with a handle 91 . using this rule option. dce_iface:4b324fc8-1670-01d3-1278-5a47bf6ee188. Some versions of an interface may not be vulnerable to a certain exploit. a DCE/RPC request can be broken up into 1 or more fragments. The any frag argument says to evaluate for middle and last fragments as well. =1. equal to (’=’) or not equal to (’!’) the version specified. When a client makes a request. An interface contains a version. since subsequent fragments will contain data deeper into the DCE/RPC request. greater than (’>’).one for big endian and one for little endian. dce_iface:4b324fc8-1670-01d3-1278-5a47bf6ee188. The server will respond with the interface UUIDs it accepts as valid and will allow the client to make requests to those services. Syntax dce_iface:<uuid>[. Many checks for data in the DCE/RPC request are only relevant if the DCE/RPC request is a first fragment (or full request). This can eliminate false positives where more than one service is bound to successfully since the preprocessor can correlate the bind UUID to the context id used in the request.e. The representation of the interface UUID is different depending on the endianness specified in the DCE/RPC previously requiring two rules . By default it is reasonable to only evaluate if the request is a first fragment (or full request). it can. However. it will specify the context id so the server knows what service the client is making a request to. Flags (and a field in the connectionless header) are set in the DCE/RPC header to indicate whether the fragment is the first. any_frag]. a middle or the last fragment. any_frag. This can be a source of false positives in fragmented DCE/RPC traffic. Also. Instead of using flow-bits. a rule can simply ask the preprocessor. For each Bind and Alter Context request. dce_iface:4b324fc8-1670-01d3-1278-5a47bf6ee188. by default the rule will only be evaluated for a first fragment (or full request. not a fragment) since most rules are written to start at the beginning of a request. since the beginning of subsequent fragments are already offset some length from the beginning of the request. any_frag. <operator><version>][. This option is used to specify an interface UUID. <2. This tracking is required so that when a request is processed. After is has been determined that a client has bound to a specific interface and is making a request to it (see above . For TCP rules.(or context id) for each interface UUID that will be used during the DCE/RPC session to reference the interface. Note that a defragmented DCE/RPC request will be considered a full request. This option will not match if the fragment is not a first fragment (or full request) unless the any frag option is supplied in which case only the interface UUID and version need match. ! △NOTE Using this rule option will automatically insert fast pattern contents into the fast pattern matcher. If a content in the rule uses the fast pattern rule option. the context id used in the request can be correlated with the interface UUID it is a handle for.dce iface) usually we want to know what function call it is making to that service. As an example. hexlong and hexshort will be specified and interpreted to be in big endian order (this is usually the default way an interface UUID will be seen and represented). |05 00 00| will be inserted into the fast pattern matcher. Syntax dce_opnum:<opnum-list>. in both big and little endian format will be inserted into the fast pattern matcher. it will unequivocally be used over the above mentioned patterns. |05 00| will be inserted into the fast pattern matcher. opnum-list opnum-item opnum-range opnum = = = = opnum-item | opnum-item ’. the interface UUID.. It is likely that an exploit lies in the particular DCE/RPC function call.it either accepts or rejects the client’s wish to bind to a certain interface. the version operation is true. the best (meaning longest) pattern will be used. dce opnum The opnum represents a specific function call to an interface. For UDP rules. (1) if the rule option flow:to server|from client is used.’ opnum-list opnum | opnum-range opnum ’-’ opnum 0-65535 Examples 92 . The server response indicates which interfaces it will allow the client to make requests to . |05 00 02| will be inserted into the fast pattern matcher and (3) if the flow isn’t known. Note that if the rule already has content rule options in it. (2) if the rule option flow:from server|to client is used. [!]<operator>. 35000. These rule options will take as a new argument dce and will work basically the same as the normal byte test/byte jump. byte jump Syntax byte_jump:<convert>. dce. oct and from beginning. This option is used to specify an opnum (or operation number). string. The opnum of a DCE/RPC request will be matched against the opnums specified with this option. relative. relative].post_offset -4. relative][. byte test and byte jump with dce A DCE/RPC request can specify whether numbers are represented in big or little endian. dce. relative. This option matches if there is DCE/RPC stub data. dce stub data Since most netbios rules were doing protocol decoding only to get to the DCE/RPC stub data. When using the dce argument to a byte test. dce. opnum range or list containing either or both opnum and/or opnum-range. but since the DCE/RPC preprocessor will know the endianness of the request. !=. This option is used to place the cursor (used to walk the packet payload in rules processing) at the beginning of the DCE/RPC stub data. little. This option takes no arguments.relative. the following normal byte test arguments will not be allowed: big. multiplier <mult_value>] \ [. dce. this option will alleviate this need and place the cursor at the beginning of the DCE/RPC stub data. 18-20.e. string. post_offet <adjustment_value>]. hex. 17. -10. 2280. hex.dce_opnum:15.multiplier 2.4294967295 -65535 to 65535 Examples byte_test:4. dce_opnum:15.align. There are no arguments to this option. i. When using the dce argument to a byte jump. dce_opnum:15-18. 93 . byte_test:2. <offset> [. dce_opnum:15.dce. 0. little. 20-22. >. dec. regardless of preceding rule options. convert operator value offset = = = = 1 | 2 | 4 (only with option "dce") ’<’ | ’=’ | ’>’ | ’&’ | ’ˆ’ 0 . it will be able to do the correct conversion.-4. byte test Syntax byte_test:<convert>. <offset>[. <value>. dec and oct. the remote procedure call or function call data. the following normal byte jump arguments will not be allowed: big.65535 -65535 to 65535 Example byte_jump:4. Example dce_stub_data. align][. convert offset mult_value adjustment_value = = = = 1 | 2 | 4 (only with option "dce") -65535 to 65535 0 . This reduces the number of rule option checks and the complexity of the rule. This option matches if any one of the opnums specified match the opnum of the DCE/RPC request. This should be set higher than the highest individual count in your ”sd pattern” rules.139. reference:cve.dce.relative. sid:1000068.S.dce. The preprocessor config starts with: preprocessor sensitive_data: Option syntax Option alert threshold mask output ssn file alert_threshold = Argument <number> NONE <filename> 1 .2007-1748.593.{12}(\x00\x00\x00\x00|. byte_jump:4.2007-1748. \ classtype:attempted-admin.>. A limited regular expression syntax is also included for defining your own PII. This is only done on credit card & Social Security numbers.256. flow:established. \ byte_test:4.-4. Social Security numbers.23470. dce_opnum:0-11. This option specifies how many need to be detected before alerting. \ pcre:"/ˆ. Dependencies The Stream5 preprocessor must be enabled for the Sensitive Data preprocessor to work. \ dce_iface:50abc2a4-574d-40b3-9d66-ee4fd5fba076.align.23470. \ classtype:attempted-admin.>. byte_jump:4. reference:cve.{12})/sR". dce_stub_data.1024:] \ (msg:"dns R_Dnssrv funcs2 overflow attempt". U. 94 . flow:established. \ pcre:"/ˆ. sid:1000069. \ byte_test:4.1024:] \ (msg:"dns R_Dnssrv funcs2 overflow attempt".{12}(\x00\x00\x00\x00|.relative.) alert udp $EXTERNAL_NET any -> $HOME_NET [135.{12})/sR". mask output This option replaces all but the last 4 digits of a detected PII with ”X”s.2.relative. Preprocessor Configuration Sensitive Data configuration is split into two parts: the preprocessor config. dce_stub_data.256.Example of rule complexity reduction The following two rules using the new rule options replace 64 (set and isset flowbit) rules that are necessary if the new rule options are not used: alert tcp $EXTERNAL_NET any -> $HOME_NET [135. reference:bugtraq. reference:bugtraq.to_server.align. \ dce_iface:50abc2a4-574d-40b3-9d66-ee4fd5fba076.4.4.14 Sensitive Data Preprocessor The Sensitive Data preprocessor is a Snort module that performs detection and filtering of Personally Identifiable Information (PII).445.) 2. dce_opnum:0-11. and the rule options.65535 Required NO NO NO Default alert threshold 25 OFF OFF Option explanations alert threshold The preprocessor will alert when any combination of PII are detected in a session. This information includes credit card numbers. where an organization’s regulations may prevent them from seeing unencrypted numbers. and email addresses.to_server.relative.dce.-4.dce. count = 1 . but the preprocessor will check matches against the list of currently allocated group numbers. The SSNs are expected to have dashes between the Area. Social Security numbers without dashes separating the Area. email 95 . and Serial sections.255 pattern = any string Option Explanations count This dictates how many times a PII pattern must be matched for an alert to be generated. Example preprocessor config preprocessor sensitive_data: alert_threshold 25 \ mask_output \ ssn_file ssn_groups_Jan10. Group.ssn file A Social Security number is broken up into 3 sections: Area (3 digits). The count is tracked across all packets in a session. These numbers can be updated in Snort by supplying a CSV file with the new maximum Group numbers to use. us social This pattern matches against 9-digit U.and 16-digit credit card numbers. us social nodashes This pattern matches U. the Social Security Administration publishes a list of which Group numbers are in use for each Area.csv Rule Options Snort rules are used to specify which PII the preprocessor should look for.S. This covers Visa. On a monthly basis. and Serial sections. dashes. By default. Discover. There are a few built-in patterns to choose from: credit card The ”credit card” pattern matches 15. Syntax sd_pattern:<count>. and Serial (4 digits). These numbers may have spaces. Group (2 digits). Group. Mastercard. <pattern>. SSNs have no check digits. or nothing in between groups.S. Snort recognizes Social Security numbers issued up through November 2009. A new rule option is provided by the preprocessor: sd_pattern This rule option specifies what type of PII a rule should detect. Social Security numbers. Credit card numbers matched this way have their check digits verified using the Luhn algorithm. pattern This is where the pattern of the PII gets specified. and American Express. . Alerts on 5 U. metadata:service smtp. \\ matches a backslash \{. To enable the normalizer. Examples sd_pattern: 2. Also. If a policy is configured for inline test or passive mode. normalizations will only be enabled if the selected DAQ supports packet replacement and is operating in inline mode.This pattern matches against email addresses.. Note that in the following.S. it is helpful to normalize packets to help minimize the chances of evasion. rev:1. There are also many new preprocessor and decoder rules to alert on or drop packets with ”abnormal” encodings. Trying to use other rule options with sd pattern will result in an error message. Alerts when 2 social security numbers (with dashes) appear in a session. example: ” ?” matches an optional space. This behaves in a greedy manner. sid:1000.2. If the pattern specified is not one of the above built-in patterns. Other characters in the pattern will be matched literally. 96 .us_social. ? makes the previous character or escape sequence optional. Unlike PCRE. following the format (123)456-7890 Whole rule example: alert tcp $HOME_NET $HIGH_PORTS -> $EXTERNAL_NET $SMTP_PORTS \ (msg:"Credit Card numbers sent over email". ! △NOTE\w in this rule option does NOT match underscores. any normalization statements in the policy config are ignored. then it is the definition of a custom PII pattern. Custom PII types are defined using a limited regex-style syntax. Rules using sd pattern must use GID 138. use the following when configuring Snort: . phone numbers. sd_pattern: 5. gid:138./configure --enable-normalizer The normalize preprocessor is activated via the conf as outlined below. 2.(\d{3})\d{3}-\d{4}. \ sd_pattern:4.) Caveats sd pattern is not compatible with other rule options.15 Normalizer When operating Snort in inline mode. \} matches { and } \? matches a question mark. example: ”{3}” matches 3 digits.credit_card. fields are cleared only if they are non-zero. • TTL normalization if enabled (explained below). [rf] Base normalizations enabled with ”preprocessor normalize ip4” include: • Truncate packets with excess payload to the datagram length specified in the IP header. • NOP all options octets. • rf reserved flag: clear this bit on incoming packets. TCP Normalizations TCP normalizations are enabled with: 97 .. Optional normalizations include: • df don’t fragment: clear this bit on incoming packets. IP6 Normalizations IP6 normalizations are enabled with: preprocessor normalize_ip6 Base normalizations enabled with ”preprocessor normalize ip6” include: • Hop limit normalizaton if enabled (explained below). • Clear the differentiated services field (formerly TOS).IP4 Normalizations IP4 normalizations are enabled with: preprocessor normalize_ip4: [df]. • NOP all options octets in hop-by-hop and destination options extension headers. 12. • Clear the reserved bits in the TCP header. • opts NOP all option bytes other than maximum segment size.preprocessor normalize_tcp: \ [ips] [urp] \ [ecn <ecn_type>]. • Clear the urgent flag if the urgent pointer is not set. 7 } <partial_order> ::= { 9. • Set the urgent pointer to the payload length if it is greater than the payload length. Optional normalizations include: • ips ensure consistency in retransmitted data (also forces reassembly policy to ”first”). 15 } <md5> ::= { 19 } <num> ::= (3. • urp urgent pointer: don’t adjust the urgent pointer if it is greater than payload length. window scaling. • ecn stream clear ECN flags if usage wasn’t negotiated. You can allow options to pass by name or number. 10 } <conn_count> ::= { 11. 13 } <alt_checksum> ::= { 14. • ecn packet clear ECN flags on a per packet basis (regardless of negotiation). Any segments that can’t be properly reassembled will be dropped. • Clear the urgent pointer and the urgent flag if there is no payload. • Remove any data from RST packet. Should also enable require 3whs. \ [opts [allow <allowed_opt>+]] <ecn_type> ::= stream | packet <allowed_opt> ::= \ sack | echo | partial_order | conn_count | alt_checksum | md5 | <num> <sack> ::= { 4. • Clear any option padding bytes. • Trim data to window.255) Base normalizations enabled with ”preprocessor normalize tcp” include: • Remove data on SYN. and any explicitly allowed with the allow keyword. timestamp. • Clear the urgent pointer if the urgent flag is not set.. • Trim data to MSS. 98 . 5 } <echo> ::= { 6. 99 . Decoder config options will still determine whether or not to generate decoder events. e. They also allow one to specify the rule type or action of a decoder or preprocessor event on a rule by rule basis. For example. See doc/README. as follows: config min_ttl: <min_ttl> config new_ttl: <new_ttl> <min_ttl> ::= (1. When TTL normalization is turned on the new ttl is set to 5 by default. or valid but not negotiated.6: preprocessor stream5_tcp: min_ttl <#> By default min ttl = 1 (TTL normalization is disabled).. Note that this configuration item was deprecated in 2. if config disable decode alerts is in snort. the TTL will be set to new ttl. • opts if timestamp was negotiated but not present. • opts clear TS ECR if ACK flag is not set.255) <new_ttl> ::= (<min_ttl>+1. these options will take precedence over the event type of the rule.conf or the decoder or preprocessor rule type is drop. block the packet. • opts MSS and window scale options are NOP’d if SYN flag is not set..8.. config enable decode drops. the drop cases only apply if Snort is running inline.3 Decoder and Preprocessor Rules Decoder and preprocessor rules allow one to enable and disable decoder and preprocessor events on a rule by rule basis. decoder events will not be generated regardless of whether or not there are corresponding rules for the event. Also note that if the decoder is configured to enable drops.g. • opts trim payload length to MSS if longer.conf. A packet will be dropped if either a decoder config drop option is in snort. then if a packet is received with a TTL ¡ min ttl.255) If new ttl ¿ min ttl. 2. NOP the timestamp octets.• opts if timestamp is present but invalid.decode for config options that control decoder events. Of course. decode.conf will make Snort revert to the old behavior: config autogenerate_preprocessor_decoder_rules 100 . define the path to where the rules are located and uncomment the include lines in snort. include $PREPROC_RULE_PATH/preprocessor.3.1 Configuring The following options to configure will enable decoder and preprocessor rules: $ . These files are updated as new decoder and preprocessor events are added to Snort.3. classtype:protocol-command-decode. sid: 1.rules respectively.rules. classtype:protocol-command-decode. just comment it with a # or remove the rule completely from the file (commenting is recommended). and have the names decoder.) to drop (as well as alert on) packets where the Ethernet protocol is IPv4 but version field in IPv4 header has a value other than 4. rev: 1. See README. To enable these rules in snort. sid: 1.gre and the various preprocessor READMEs for descriptions of the rules in decoder...conf. To change the rule type or action of a decoder/preprocessor rule.2. rev: 1.2 Reverting to original behavior If you have configured snort to use decoder and preprocessor rules./configure --enable-decoder-preprocessor-rules The decoder and preprocessor rules are located in the preproc rules/ directory in the top level source tree. \ metadata: rule-type decode . gid: 116. README. The gen-msg.rules include $PREPROC_RULE_PATH/decoder.map under etc directory is also updated with new decoder and preprocessor rules. The generator ids ( gid ) for different preprocessors and the decoder are as follows: 2.rules and preprocessor.) to drop ( msg: "DECODE_NOT_IPV4_DGRAM". Any one of the following rule types can be used: alert log pass drop sdrop reject For example one can change: alert ( msg: "DECODE_NOT_IPV4_DGRAM". just replace alert with the desired rule type.rules and preprocessor.conf that reference the rules files.rules To disable any rule. \ metadata: rule-type decode . var PREPROC_RULE_PATH /path/to/preproc_rules . the following config option in snort. gid: 116. 10.4 Event Processing Snort provides a variety of mechanisms to tune event processing to suit your needs: • Detection Filters You can use detection filters to specify a threshold that must be exceeded before a rule generates an event. This can be tuned to significantly reduce false alarms. 2.conf. This option applies to rules not specified and the default behavior is to alert. • Event Suppression You can completely suppress the logging of unintersting events. This is covered in section 3. 2.. • Event Filters You can use event filters to reduce the number of logged events for noisy rules.4.7. 101 . you also have to remove the decoder and preprocessor rules and any reference to them from snort. and the first applicable action is taken Note that if you want to revert to the old behavior. \ new_action alert|drop|pass|log|sdrop|reject. destination IP address. the time period over which count is accrued. c must be nonzero value. restrict the configuration to only to source or destination IP address (indicated by track parameter) determined by <ip-list>. sig_id 1. An event filter may be used to manage number of alerts after the rule action is enabled by rate filter. sig_id <sid>. sdrop and reject are conditionally compiled with GIDS. rate filter may be used to detect if the number of connections to a specific server exceed a specific count. Option track by src | by dst | by rule Description rate is tracked either by source IP address. even if the rate falls below the configured limit.all are required except apply to. and sdrop can be used only when snort is used in inline mode. \ count <c>. For rules related to Stream5 sessions. Note that events are generated during the timeout period.allow a maximum of 100 connection attempts per second from any one IP address. \ count 100. 0 seconds means count is a total count instead of a specific rate. drop. new action replaces rule action for t seconds. This means the match statistics are maintained for each unique source IP address. seconds <s>. or they are aggregated at rule level. \ new_action drop. source and destination means client and server respectively. revert to the original rule action after t seconds. track by rule and apply to may not be used together.Format Rate filters are used as standalone configurations (outside of a rule) and have the following format: rate_filter \ gen_id <gid>. 0 seconds only applies to internal rules (gen id 135) and other use will produce a fatal error by Snort. count c seconds s new action alert | drop | pass | log | sdrop | reject timeout t apply to <ip-list> Examples Example 1 . and block further connections from that IP address for 10 seconds: 102 . \ track <by_src|by_dst|by_rule>. for each unique destination IP address. track by rule and apply to may not be used together.allow a maximum of 100 successful simultaneous connections from any one IP address. reject. or by rule. which is optional. For example. \ track by_src. timeout 10 Example 2 . and block further connection attempts from that IP address for 10 seconds: rate_filter \ gen_id 135. the maximum number of rule matches in s seconds before the rate filter limit to is exceeded. \ timeout <seconds> \ [. then rule action is never reverted back. If t is 0. seconds 1. apply_to <ip-list>] The options are described in the table below . Snort will terminate with an error while reading the configuration information. ! △NOTE filter may be defined for a given gen id. \ count <c>. sig_id <sid>. Thresholds in a rule (deprecated) will override a global event filter.all are required. If more than one event filter is Only one event applied to a specific gen id. There are 3 types of event filters: • limit Alerts on the 1st m events during the time interval. Format event_filter \ gen_id <gid>.4.rate_filter \ gen_id 135. Standard filtering tests are applied first. sig_id <sid>. then ignores any additional events during the time interval. \ type <limit|threshold|both>. \ count 100. threshold is deprecated and will not be supported in future releases. • threshold Alerts every m times we see this event during the time interval. seconds <s> threshold is an alias for event filter. (gen id 0. event filters with sig id 0 are considered ”global” because they apply to all rules with the given gen id. sig id != 0 is not allowed). however. then the filter applies to all rules. \ type <limit|threshold|both>. Such events indicate a change of state that are significant to the user monitoring the network. \ track <by_src|by_dst>. 103 . if they do not block an event from being logged. seconds <s> threshold \ gen_id <gid>. This can be tuned to significantly reduce false alarms. \ track by_src. \ count <c>. sig_id 2. seconds 0. the global filtering test is applied. sig id pair. \ new_action drop. then ignores events for the rest of the time interval. If gen id is also 0. ! △NOTE can be used to suppress excessive rate filter alerts. • both Alerts once per time interval after seeing m occurrences of the event. Both formats are equivalent and support the options described below . timeout 10 2. sig id. the first new action event event filters of the timeout period is never suppressed.2 Event Filtering Event filtering can be used to reduce the number of logged alerts for noisy rules by limiting the number of times a particular event is logged during a specified time interval. \ track <by_src|by_dst>. Global event filters do not override what’s in a signature or a more specific stand-alone event filter. triggering each rule for each event generator: event_filter \ gen_id 0. but only if we exceed 30 events in 60 seconds: event_filter \ gen_id 1. seconds 60 104 \ . sig_id 0. sig id 0 specifies a ”global” filter because it applies to all sig ids for the given gen id. time period over which count is accrued. s must be nonzero value. \ count 30. sig_id 1853. sig_id 0. Specify the signature ID of an associated rule. \ type limit. \ count 3. gen id 0. track by_src. number of rule matching in s seconds that will cause event filter limit to be exceeded. \ count 1. \ type threshold. then ignores events for the rest of the time interval. track by_src. seconds 60 Limit logging to every 3rd event: event_filter \ gen_id 1. type limit alerts on the 1st m events during the time interval. \ type both. \ count 1. This means count is maintained for each unique source IP addresses. track by_src. sig id 0 can be used to specify a ”global” threshold that applies to all rules. then ignores any additional events during the time interval. track by_src. Ports or anything else are not tracked. seconds 60 Limit logging to just 1 event per 60 seconds. count 1. seconds 60 Limit to logging 1 event per 60 seconds per IP. \ type limit. c must be nonzero value. or for each unique destination IP addresses. track by_src. Examples Limit logging to 1 event per 60 seconds: event_filter \ gen_id 1. sig_id 1851. seconds 60 Limit to logging 1 event per 60 seconds per IP triggering each rule (rule gen id is 1): event_filter \ gen_id 1. or destination IP address. rate is tracked either by source IP address. Type threshold alerts every m times we see this event during the time interval. Type both alerts once per time interval after seeing m occurrences of the event.Option gen id <gid> sig id <sid> type limit|threshold|both track by src|by dst count c seconds s Description Specify the generator ID of an associated rule. sig_id 1852. \ type limit. ip <ip-list> Option gen id <gid> sig id <sid> track by src|by dst ip <list> Description Specify the generator ID of an associated rule. \ track <by_src|by_dst>. but if present. ip must be provided as well.Events in Snort are generated in the usual way. \ suppress \ gen_id <gid>. Specify the signature ID of an associated rule. Suppression uses an IP list to select specific networks and users for suppression. SIDs. Suppress by source IP address or destination IP address. Read genmsg. sig id 0 can be used to specify a ”global” threshold that applies to all rules. and IP addresses via an IP list . Format The suppress configuration has two forms: suppress \ gen_id <gid>. sig_id <sid>.4. or suppressed when the causative traffic is going to or coming from a specific IP or group of IP addresses. You may also combine one event filter and several suppressions to the same non-zero SID. This is optional. If track is provided. You may apply multiple suppressions to a non-zero SID. gen id 0. Examples Suppress this event completely: suppress gen_id 1. Users can also configure a memcap for threshold with a “config:” option: config event_filter: memcap <bytes> # this is deprecated: config threshold: memcap <bytes> 2. sig id 0 specifies a ”global” filter because it applies to all sig ids for the given gen id. Suppression are standalone configurations that reference generators. event filters are handled as part of the output system. sig_id 1852: Suppress this event from this IP: 105 .3 Event Suppression Event suppression stops specified events from firing without removing the rule from the rule base. ip must be provided as well. This allows a rule to be completely suppressed. sig_id <sid>.map for details on gen ids. Restrict the suppression to only source or destination IP addresses (indicated by track parameter) determined by ¡list¿. Suppression tests are performed prior to either standard or global thresholding tests. 0/24 2. but change event order: config event_queue: order_events priority Use the default event queue values but change the number of logged events: config event_queue: log 2 106 . The default value is 8. 1. sig_id 1852. sig_id 1852.4 Event Logging Snort supports logging multiple events per packet/stream that are prioritized with different insertion methods.54 Suppress this event to this CIDR block: suppress gen_id 1. • content length . track by_dst. and rules that have a longer content are ordered before rules with shorter contents. max queue This determines the maximum size of the event queue. 2. The method in which events are ordered does not affect rule types such as pass.. For example. track by_src. etc.4.suppress gen_id 1. only 8 events will be stored for a single packet or stream. log This determines the number of events to log for a given packet or stream.1. The default value is 3. log. ip 10. We currently have two different methods: • priority . You can’t log more than the max event number that was specified. 3.1. alert. such as max content length or event ordering using the event queue. if the event queue has a max size of 8.’.1.The highest priority (1 being the highest) events are ordered first.1. order events This argument determines the way that the incoming events are ordered. ip 10. The default value is content length.Rules are ordered before decode or preprocessor alerts. conf and Snort will print statistics on the worst (or all) performers on exit. These files will be found in the logging directory.txt each time config profile rules: filename performance.5 Performance Profiling Snort can provide statistics on rule and preprocessor performance. If append is not specified. filename perf. The filenames will have timestamps appended to them. save results to performance. save results to perf. sorted by number of checks config profile rules: print all.txt 107 . a new file will be created each time Snort is run. based on total time config profile rules: print 100.txt append • Print top 20 rules. sort avg ticks • Print all rules. the statistics will be saved in these files.1 Rule Profiling Format config profile_rules: \ print [all | <num>].2. 2. you must build snort with the --enable-perfprofiling option to the configure script. To use this feature.txt with timestamp in filename config profile rules: print 20. sort total ticks • Print with default options. When a file name is provided in profile rules or profile preprocs. based on highest average time config profile rules: print 10.txt config profile rules: filename rules stats. sort checks • Print top 100 rules.txt append • Print the top 10 rules. sort by avg ticks.5. and append to file rules stats. \ sort <sort_option> \ [. Each require only a simple config option to snort. sort by avg ticks (default configuration if option is turned on) config profile rules • Print all rules. print 4. If ”append” is not specified. Quick to check. The filenames will have timestamps appended to them. The Microsecs (or Ticks) column is important because that is the total time spent evaluating a given rule.0 0. that most likely contains PCRE.0 107822 53911.5. this information will be printed to the console when Snort exits.0 53911. A high Avg/Check is a poor performing rule. We are looking at moving some of these into code.0 0. filename <filename> [append]] • <num> is the number of preprocessors to print 108 .0 90054 45027.conf to specify a file where this will be written. the few options may or may not match. These files will be found in the logging directory.0 Avg/Match Avg/Nonmatch ========= ============ 385698. especially those with low SIDs.0 0. if that rule is causing alerts. a new file will be created each time Snort is run. But.2 Preprocessor Profiling Format config profile_preprocs: \ print [all | <num>]. By default. it makes sense to leave it alone.1: Rule Profiling Example Output Output Snort will print a table much like the following at exit.0 0.0 45027. You can use the ”filename” option in snort.0 46229. \ sort <sort_option> \ [.0 Figure 2. will be high for rules that have no options) • Alerts (number of alerts generated from this rule) • CPU Ticks • Avg Ticks per Check • Avg Ticks per Match • Avg Ticks per Nonmatch Interpreting this info is the key. High Checks and low Avg/Check is usually an any->any rule with few rule options and no content.. sort total ticks 2. conf to specify a file where this will be written. sort checks . a new file will be created each time Snort is run. based on highest average time config profile preprocs: print 10. etc) • Exits (number of corresponding exits – just to verify code is instrumented correctly. unless an exception was trapped) • CPU Ticks • Avg Ticks per Check • Percent of caller . the Pct of Caller field will not add up to 100% of the caller’s time.For non layer 0 preprocessors. ports matched.txt append • Print the top 10 preprocessors.When printing a specific number of preprocessors all subtasks info for a particular preprocessor is printed for each layer 0 preprocessor stat.• <sort option> is one of: checks avg ticks total ticks • <filename> is the output filename • [append] dictates that the output will go to the same file each time (optional) Examples • Print all preprocessors.txt config profile preprocs: filename preprocs stats. sort avg ticks • Print all preprocessors. Configuration line used to print the above table: config profile_rules: \ print 3. The filenames will have timestamps appended to them. It does give a reasonable indication of how much relative time is spent within each subtask. and other factors. By default. Layer 1 preprocessors are listed under their respective caller (and sorted similarly). subroutines within preprocessors. Because of task swapping. If ”append” is not specified.The number is indented for each layer. app layer header was correct. You can use the ”filename” option in snort. sort by avg ticks. sort total_ticks The columns represent: • Number (rank) . • Checks (number of times preprocessor decided to look at a packet. this identifies the percent of the caller’s ticks that is spent for this subtask. and append to file preprocs stats.e. These files will be found in the logging directory. sort by avg ticks (default configuration if option is turned on) config profile preprocs • Print all preprocessors. • Preprocessor Name • Layer . this information will be printed to the console when Snort exits. i. 109 print all. sorted by number of checks config profile preprocs: Output Snort will print a table much like the following at exit. non-instrumented code. should ALWAYS match Checks. 00 0.65 1.94 99.25 77.00 0.53 21.02 0.01 0.00 0.00 0.34 0.06 0.84 0.02 11.17 21.62 3.80 0.94 3.12 0.85 84.59 0.07 0.46 99.88 44.00 0.23 21.00 0.33 8.02 47.81 6.83 0.77 0.20 0.00 0.00 0.00 0.2: Preprocessor Profiling Example Output 110 .72 1.89 2.06 3.29 2.37 0.37 0.20 34.00 0.20 47.01 0.04 0.14 25.06 0.01 0.00 0.87 71.66 0.59 19.00 0.58 0.92 3.01 0.57 1.91 15.78 1.00 Figure 2.77 0.70 0.07 6.00 0.01 0.73 1.08 0.79 0.00 0.32 0.00 4.01 0.78 2.81 93.12 0.16 0.22 15657.16 0.77 39.00 65.00 0.27 0.73 1.32 0.00 0.08 9.68 38.00 0.17 18.02 0.21 1.11 0.89 0.62 17.14 307.10 0.06 0.30 0.16 1.56 0.00 0.03 8.20 19.34 1.17 21.24 0.70 0.34 0.04 0.00 0.56 39.01 19.86 4.06 0.15 0.70 0.87 0.84 0.00 0.09 0.51 6.53 21.16 0.81 39.07 17.39 13.14 0.41 0.06 0.43 39.01 0.51 2.04.40 28.12 12.03 0.10 1.02 0. sample output.2. The action taken upon detection of excessive latency is configurable. and some implementation details worth noting. \ threshold count. so one or both or neither may be enabled. Configuration Packet Configuration Options max-pkt-time <micro-secs> • enables packet latency thresholding using ’micros-secs’ as the limit. or together in just one config ppm 111 . as above.5. \ rule-log [log] [alert] Packets and rules can be configured separately.3 Packet Performance Monitoring (PPM) PPM provides thresholding mechanisms that can be used to provide a basic level of latency control for snort. PPM is configured as follows: # Packet configuration: config ppm: max-pkt-time <micro-secs>. Both rules and packets can be checked for latency. Packet and rule monitoring is independent. To use PPM. It does not provide a hard and fast latency guarantee but should in effect provide a good average latency control. The following sections describe configuration. \ suspend-expensive-rules. \ fastpath-expensive-packets. \ debug-pkts # Rule configuration: config ppm: max-rule-time <micro-secs>. you must build with the –enable-ppm or the –enable-sourcefire option to configure. \ pkt-log. \ suspend-timeout <seconds>. 112 .Rule Configuration Options max-rule-time <micro-secs> • enables rule latency thresholding using ’micros-secs’ as the limit. Example 2: The following suspends rules and aborts packet inspection. A summary of this information is printed out when snort exits. then no action is taken other than to increment the count of the number of packets that should be fastpath’d or the rules that should be suspended. threshold 5 If fastpath-expensive-packets or suspend-expensive-rules is not used.. 633125 usecs Rule Performance Summary: 113 . \ pkt-log. packet fastpathed. 0 rules. PPM: Process-BeginPkt[61] caplen=60 PPM: Pkt[61] Used= 8.0438 usecs. threshold 5..21764 usecs PPM: Process-EndPkt[64] . \ suspend-timeout 300.. 1 nc-rules tested. Process-BeginPkt[63] caplen=60 Pkt[63] Used= 8. debug-pkt config ppm: \ max-rule-time 50.3659 usecs PPM: Process-EndPkt[62] PPM: PPM: PPM: PPM: Pkt-Event Pkt[63] used=56.config ppm: \ max-pkt-time 50.394 usecs Process-EndPkt[63] PPM: Process-BeginPkt[64] caplen=60 PPM: Pkt[64] Used= 8. suspend-expensive-rules.. fastpath-expensive-packets.. . Sample Snort Exit Output Packet Performance Summary: max packet time : 50 usecs packet events : 1 avg pkt time : 0.15385 usecs PPM: Process-EndPkt[61] PPM: Process-BeginPkt[62] caplen=342 PPM: Pkt[62] Used= 65. • This implementation is software based and does not use an interrupt driven timing mechanism and is therefore subject to the granularity of the software based timing tests.2675 usecs • Enforcement of packet and rule processing times is done after processing each rule. The output modules are run when the alert or logging subsystems of Snort are called. Due to the granularity of the timing measurements any individual packet may exceed the user specified packet or rule processing time limit.6. output plugins send their data to /var/log/snort by default or to a user directed directory (using the -l command line switch). not just the processor time the Snort application receives. This was a conscious design decision because when a system is loaded. They allow Snort to be much more flexible in the formatting and presentation of output to its users.6 Output Modules Output modules are new as of version 1. it is recommended that you tune your thresholding to operate optimally when your system is under load. Output modules are loaded at runtime by specifying the output keyword in the config file: output <name>: <options> output alert_syslog: log_auth log_alert 2. When multiple plugins of the same type (log. As with the standard logging and alerting systems. after the preprocessors and detection engine. they are stacked and called in sequence when an event occurs. 2. Therefore this implementation cannot implement a precise latency guarantee with strict timing guarantees. • Time checks are made based on the total system time. This module also allows the user to specify the logging facility and priority within the Snort config file. Hence the reason this is considered a best effort approach. Available Keywords Facilities • log auth • log authpriv • log daemon 114 . alert) are specified.6. latency thresholding is presently only available on Intel and PPC platforms. Latency control is not enforced after each preprocessor. Multiple output plugins may be specified in the Snort configuration file. the latency for a packet is based on the total system time. • Since this implementation depends on hardware based high performance frequency counters. Therefore. giving users greater flexibility in logging alerts.1 alert syslog This module sends alerts to the syslog facility (much like the -s command line switch).max rule time rule events avg nc-rule time Implementation Details : 50 usecs : 0 : 0. The format of the directives in the config file is very similar to that of the preprocessors. not processor usage by Snort. ] \ <facility> <priority> <options> 115 port is 514.1. a hostname and port can be passed as options. output alert_syslog: \ [host=<hostname[:<port>].0.0. The default host is 127. 1. The default name is ¡logdir¿/alert. The alerts will be written in the default logging directory (/var/log/snort) or in the logging directory specified at the command line. only brief single-line entries are logged. The minimum is 1 KB. <facility> <priority> <options> 2. The name may include an absolute or relative path.Example output alert_syslog: host=10.2 alert fast This will print Snort alerts in a quick one-line format to a specified output file. You may specify ”stdout” for terminal output. You may specify ”stdout” for terminal output. • packet: this option will cause multiline entries with full packet headers to be logged. The creation of these files slows Snort down considerably.13 for more information. Example output alert_full: alert. See 2. The minimum is 1 KB.6. This output method is discouraged for all but the lightest traffic situations.1.3 alert full This will print Snort alert messages with full packet headers. Format output alert_fast: [<filename> ["packet"] [<limit>]] <limit> ::= <number>[(’G’|’M’|K’)] • filename: the name of the log file.6. Format output alert_full: [<filename> [<limit>]] <limit> ::= <number>[(’G’|’M’|K’)] • filename: the name of the log file. See 2. • limit: an optional limit on file size which defaults to 128 MB.full 116 . It is a faster alerting method than full alerts because it doesn’t need to print all of the packet headers to the output file and because it logs to only 1 file.fast 2. By default.1:514.6. a directory will be created per IP.6.13 for more information. Inside the logging directory. The default name is ¡logdir¿/alert. • limit: an optional limit on file size which defaults to 128 MB. The name may include an absolute or relative path. Example output alert_fast: alert. These files will be decoded packet dumps of the packets that triggered the alerts. Format output log_tcpdump: [<filename> [<limit>]] <limit> ::= <number>[(’G’|’M’|K’)] • filename: the name of the log file.Port number to connect to at the server host. When a sequence of packets is to be logged. If a non-zero-length string is specified. The arguments to this plugin are the name of the database to be logged to and a parameter list. The default name is ¡logdir¿/snort. Without a host name.6. See 2.log 2.Host to connect to. the aggregate size is used to test the rollover condition. TCP/IP communication is used. More information on installing and configuring this module can be found on the [91]incident. A UNIX timestamp is appended to the filename. Parameters are specified with the format parameter = argument. This is useful for performing post-process analysis on collected traffic with the vast number of tools that are available for examining tcpdump-formatted files.Database name 117 .6. The name may include an absolute or relative path. it will connect using a local UNIX domain socket. Format database: <log | alert>.6. Format alert_unixsock Example output alert_unixsock 2.3 for example usage. port . see Figure 2. • limit: an optional limit on file size which defaults to 128 MB. This is currently an experimental interface. <parameter list> The following parameters are available: host . or socket filename extension for UNIX-domain connections. dbname .org web page.log. <database type>. Example output log_tcpdump: snort.13 for more information.4 alert unixsock Sets up a UNIX domain socket and sends alert reports to it.5 log tcpdump The log tcpdump module logs packets to a tcpdump-formatted file. External programs/processes can listen in on this socket and receive Snort alert and packet data in real time.2.6 database This module from Jed Pickel sends Snort data to a variety of SQL databases.6. requires post processing base64 . Setting the type to log attaches the database logging functionality to the log facility within the program.Represent binary data as a base64 string. Storage requirements . If you set the type to log. Storage requirements .Database username for authentication password . Storage requirements .2x the size of the binary Searchability .3x the size of the binary Searchability . There are five database types available in the current version of the plugin.very good for searching for a text string impossible if you want to search for binary human readability .output database: \ log.7. You can choose from the following options.very good detail .3: Database Output Plugin Configuration user . ! △NOTE The database output plugin does not have the ability to handle alerts that are generated by using the tag keyword.Password used if the database demands password authentication sensor name . then data for IP and TCP options will still be represented as hex because it does not make any sense for that data to be ASCII. Setting the type to alert attaches the plugin to the alert output chain within the program. These are mssql. If you choose this option.∼1. there is a logging method and database type that must be defined. dbname=snort user=snort host=localhost password=xyz Figure 2.Log all details of a packet that caused an alert (including IP/TCP options and the payload) fast . This is the only option where you will actually lose data.’.very good Human readability .5 for more details. mysql.<. and protocol) Furthermore. So i leave the encoding option to you.slightly larger than the binary because some characters are escaped (&.How much detailed data do you want to store? The options are: full (default) .Log only a minimum amount of data. mysql. source ip. See section 3.>) Searchability . postgresql.Represent binary data as an ASCII string. the plugin will be called on the log output chain.not readable unless you are a true geek. signature.Specify your own name for this Snort sensor. The following fields are logged: timestamp. tcp flags. source port.not readable requires post processing ascii . but this is still the best choice for some applications. Non-ASCII Data is represented as a ‘.Because the packet payload and option data is binary. 118 . and odbc.impossible without post processing Human readability .Represent binary data as a hex string. If you do not specify a name. Blobs are not used because they are not portable across databases. destination port. log and alert. Set the type to match the database you are using. You severely limit the potential of some analysis applications if you choose this option. oracle. Each has its own advantages and disadvantages: hex (default) . destination ip. there is no one simple and portable way to store it in a database. There are two logging types available. one will be generated automatically encoding . Format output alert_csv: [<filename> [<format> [<limit>]]] <format> ::= "default"|<list> <list> ::= <field>(.2.. See 2. the output is in the order of the formatting options listed.7 csv The csv output plugin allows alert data to be written in a format easily importable to a database. If the formatting option is ”default”. <limit> ::= <number>[(’G’|’M’|K’)] • filename: the name of the log fi. 119 .6. The name may include an absolute or relative path.. The minimum is 1 KB. You may specify ”stdout” for terminal output.csv.6. • format: The list of formatting options is below.13 for more information. The output fields and their order may be customized.<field>)* <field> ::= "dst"|"src"|"ttl" . The default name is ¡logdir¿/alert. then MPLS labels will be not be included in unified2 events. but a slightly different logging format.csv timestamp. and a log file. alert logging will only log events and is specified with alert unified2. <limit <file size limit in MB>] Example output alert_unified: snort. <limit <size in MB>] [.6.csv default output alert_csv: /var/log/alert. See section 2. unified 2 files have the file creation time (in Unix Epoch format) appended to each file when it is created. packet logging. msg 2. limit 128 2. To include both logging styles in a single. Format output alert_unified2: \ filename <base filename> [.8 unified The unified output plugin is designed to be the fastest possible method of logging Snort events. MPLS labels can be included in unified2 events.6. Unified2 can work in one of three modes. message id).alert. protocol. limit 128 output log_unified: snort. ! △NOTE Files have the file creation time (in Unix Epoch format) appended to each file when it is created.8 on unified logging for more information.h. mpls_event_types] 120 . as the unified output plugin creates two different files.9 unified 2 The unified2 output plugin is a replacement for the unified output plugin. When MPLS support is turned on. Packet logging includes a capture of the entire packet and is specified with log unified2. allowing another programs to handle complex logging mechanisms that would otherwise diminish the performance of Snort. If option mpls event types is not used. <limit <file size limit in MB>] output log_unified: <base file name> [. simply specify unified2.Example output alert_csv: /var/log/alert. port. The alert file contains the high-level details of an event (eg: IPs. Likewise. The unified output plugin logs events in binary format. The name unified is a misnomer. alert logging. Format output alert_unified: <base file name> [. It has the same performance characteristics. Both file types are written in a binary format described in spo unified. The log file contains the detailed packet information (a packet dump with the associated event ID). unified file.6.log. ! △NOTE By default. or true unified logging. an alert file. nostamp] [. Use option mpls event types to enable this. output log_unified2: \ filename <base filename> [, <limit <size in MB>] [, nostamp] output unified2: \ filename <base file name> [, <limit <size in MB>] [, nostamp] [, mpls_event_types]use alert prelude is not built in by default. To use alert prelude, snort must be built with the support to –enable-prelude argument ruletype info { type alert 121 # like using snort -n output alert_fast: info.alert output log_null } 2.6.12 alert aruba action ! △NOTEuse alert aruba action is not built in by default. To use alert aruba action, snort must be built with Support . and any client attributes are ignored. . For example. a host running Red Hat 2.1. for a given host entry. udp. and protocol (http. FTP..1. HTTP Inspect is configured to inspect traffic on port 2300. TCP port 22 is ssh (running Open SSH). On that host. if. even if the telnet portion of the FTP/Telnet preprocessor is only configured to inspect port 23.0</ATTRIBUTE_VALUE> <CONFIDENCE>89</CONFIDENCE> </VERSION> </APPLICATION> </CLIENT> </CLIENTS> </HOST> </ATTRIBUTE_TABLE> </SNORT_ATTRIBUTES> ! △NOTE With Snort 2. the stream and IP frag information are both used.168. The application and version for a given service attribute. etc).<VERSION> <ATTRIBUTE_VALUE>6.1. A DTD for verification of the Host Attribute Table XML file is provided with the snort packages.234 port 2300 because it is identified as telnet. They will be used in a future release. etc) are used. SMTP. ssh. This host has an IP address of 192.168. Telnet.3 Attribute Table Example In the example above.7.234. and TCP port 2300 is telnet. That field is not currently used by Snort. Of the service attributes.2.2.8. only the IP protocol (tcp.234 port 2300 as telnet.1 and 2.2). HTTP Inspect will NOT process the packets on a connection to 192. port. The confidence metric may be used to indicate the validity of a given service or client application and its respective elements. 2.6 is described. Below is a list of the common services used by Snort’s application layer preprocessors and Snort rules (see below). Conversely.168. The IP stack fragmentation and stream reassembly is mimicked by the ”linux” configuration (see sections 2. etc) make use of the SERVICE information for connections destined to that host on that port. but may be in future releases. • Application Layer Preprocessors The application layer preprocessors (HTTP. Snort will inspect packets for a connection to 192. for example. sid:10000003. alert tcp any any -> any 23 (msg:"Telnet traffic".) 126 .168. The following few scenarios identify whether a rule will be inspected or not. When both service metadata is present in the rule and in the connection.established.168.) • Alert: Rule Has No Service Metadata.) • No Alert: Rule Has No Service Metadata. sid:10000007. Connection Service Matches One of them The following rule will be inspected and alert on traffic to host 192.168.) • Alert: Rule Has Multiple Service Metadata.established.) • No Alert: Rule Has Service Metadata.1. flow:to_server.234 port 2300 because that traffic is identified as telnet.168. flow:to_server.1.1.1.168.234 port 2300 because the service is identified as telnet and there are other rules with that service.234 port 2300 because the port matches.established.established. flow:to_server. metadata: service ssh. flow:to_server. Snort uses the service rather than the port. alert tcp any any -> any 23 (msg:"Port 23 traffic". service smtp. alert tcp any any -> any 2300 (msg:"Port 2300 traffic". flow:to_server.234 port 2300 because it is identified as telnet.234 port 2300 because it is identified as telnet. metadata: service telnet.) alert tcp any any -> any 2300 (msg:"Port 2300 traffic". sid:10000001. sid:10000004.234 port 2300 because the port does not match. Packet has service + other rules with service The first rule will NOT be inspected and NOT alert on traffic to host 192.Attribute Table Affect on rules Similar to the application layer preprocessors. Port Matches The following rule will be inspected and alert on traffic to host 192. • Alert: Rule Has Service Metadata. but the service is ssh. Port Matches The following rule will NOT be inspected and NOT alert on traffic to host 192. sid:10000005. alert tcp any any -> any 2300 (msg:"SSH traffic". Snort will ONLY inspect the rules that have the service that matches the connection. alert tcp any any -> any 2300 (msg:"Port 2300 traffic". Port Does Not Match The following rule will NOT be inspected and NOT alert on traffic to host 192.established. sid:10000002.1. sid:10000006. Connection Service Does Not Match.established.established. metadata: service telnet. Connection Service Matches The following rule will be inspected and alert on traffic to host 192.168. flow:to_server. rules configured for specific ports that have a service metadata will be processed based on the service identified by the attribute table. metadata: service telnet. flow:to_server. If there are rules that use the service and other rules that do not but the port matches. alert tcp any any -> any 23 (msg:"Telnet traffic".1.) • Alert: Rule Has No Service Metadata. See chapter 4 for more information on dynamic detection rules libraries. See chapter 4 for more information on dynamic engine libraries. Note that for some preprocessors. Or. (Same effect as --dynamic-preprocessor-lib or --dynamic-preprocessor-lib-dir options). (Same effect as --dynamic-engine-lib or --dynamic-preprocessor-lib-dir options).2 Directives a directory of detection rules shared libraries. Specify file. Snort must be configured with the --disable-dynamicplugin flag. Or. (Same effect as --dynamic-detection-lib or --dynamic-detection-lib-dir options). 127 .8. followed by the full or relative path to a directory of preprocessor shared libraries.6. however. followed by the full or relative path to the shared library. specify directory. Or. use the new configuration. Specify file. the main Snort packet processing thread will swap in the new configuration to use and will continue processing under the new configuration.1 Format <directive> <parameters> 2. See chapter 4 for more information on dynamic preprocessor libraries. followed by the full or relative path to the shared library..2. When a swappable configuration object is ready for use. Tells snort to load the dynamic detection rules shared library (if file is used) or all dynamic detection rules shared libraries (if directory is. specify directory. ! △NOTE To disable use of dynamic modules. 2.8.conf or via command-line options. They can be loaded via directives in snort.8 Dynamic Modules Dynamically loadable modules were introduced with Snort 2. All newly created sessions will. dynamicengine [ file <shared library path> | directory <directory of shared libraries> ] dynamicdetection [ file <shared library path> | directory <directory of shared libraries> ] 2. followed by the full or relative path to a directory of preprocessor shared libraries. existing session data will continue to use the configuration under which they were created in order to continue with proper state for that session. Specify file. specify directory. Tells snort to load the dynamic engine shared library (if file is used) or all dynamic engine shared libraries (if directory is used). g. Snort will restart (as it always has) upon receipt of a SIGHUP.e.conf -T 2. To disable this behavior and have Snort exit instead of restart. • Any changes to output will require a restart. This functionality 2. e. etc. • Adding/modifying/removing preprocessor configurations are reloadable (except as noted below).2. This option is enabled by default and the behavior is for Snort to restart if any nonreloadable options are added/modified/removed.9.1 Enabling support To enable support for reloading a configuration. $ snort -c snort. dynamicengine and dynamicpreprocessor are not reloadable. Modifying any of these options will cause Snort to restart (as a SIGHUP previously did) or exit (if --disable-reload-error-restart was used to configure Snort). add --disable-reload-error-restart in addition to --enable-reload to configure when compiling. e.9. any new/modified/removed shared objects will require a restart. ! △NOTE is not currently supported in Windows. so you should test your new configuration An invalid before issuing a reload. Then. startup memory allocations. i.9. Non-reloadable configuration options of note: • Adding/modifying/removing shared objects via dynamicdetection. add --enable-reload to configure when compiling. There is also an ancillary option that determines how Snort should behave if any non-reloadable options are changed (see section 2.3 Non-reloadable configuration options There are a number of option changes that are currently non-reloadable because they require changes to output. If reload support ! △NOTEconfiguration will still result in Snort fatal erroring.9.2 Reloading a configuration First modify your snort. Reloadable configuration options of note: • Adding/modifying/removing text rules and variables are reloadable.conf (the file passed to the -c option on the command line). send Snort a SIGHUP signal.g. Changes to the following options are not reloadable: attribute_table config alertfile config asn1 config chroot 128 . to initiate a reload.3 below). $ kill -SIGHUP <snort pid> ! △NOTE is not enabled. Those parameters are listed below the relevant config option or preprocessor.. 10 Multiple Configurations Snort now supports multiple configurations based on VLAN Id or IP subnet within a single instance of Snort. using the following configuration line: config binding: <path_to_snort. Even though 2.e.Refers to ip subnets. Each configuration can have different preprocessor settings and detection rules.conf . VLANs/Subnets not bound to any specific configuration will use the default configuration. Negative vland Ids and alphanumeric are not supported.10. they are included as valid in terms of configuring Snort.2. vlanIdList . policy_id policy_mode policy_version The following config options are specific to each configuration.1 Creating Multiple Configurations Default configuration for snort is specified using the existing -c option. ! △NOTE can not be used in the same line.conf> net <ipList> path to snort.Refers to the comma seperated list of vlandIds and vlanId ranges. the default values of the option (not the default configuration values) take effect. Subnets can be CIDR blocks for IPV6 or IPv4.Refers to the absolute or relative path to the snort. The format for ranges is two vlanId separated by a ”-”. Valid vlanId is any number in 0-4095 range. Each unique snort configuration file will create a new configuration instance within snort. config config config config config checksum_drop disable_decode_alerts disable_decode_drops disable_ipopt_alerts disable_ipopt_drops 130 .conf> vlan <vlanIdList> config binding: <path_to_snort. ipList . The following config options are specific to each configuration. A default configuration binds multiple vlans or networks to non-default configurations. Configurations can be applied based on either Vlans or Vlan and Subnets Subnets not both.2 Configuration Specific Elements Config Options Generally config options defined within the default configuration are global by default i.conf for specific configuration. 2. A maximum of 512 individual IPv4 or IPv6 addresses or CIDRs can be specified. their value applies to all other configurations. ! △NOTE Vlan Ids 0 and 4095 are reserved.10. If not defined in a configuration. Spaces are allowed within ranges.. Refers to a 16-bit unsigned value. Variables Variables defined using ”var”. ”portvar” and ”ipvar” are specific to configurations. If the rules in a configuration use variables. ! △NOTE If no policy id is specified. payload detection options. This is required as some mandatory preprocessor configuration options are processed only in default configuration. to each configuration using the following config line: config policy_id: <id> id . A preprocessor must be configured in default configuration before it can be configured in non-default configuration. This policy id will be used to identify alerts from a specific configuration in the unified2 records. are processed only in default policy. To enable vlanId logging in unified2 records the following option can be used. and post-detection options. Parts of the rule header can be specified differently across configurations. including the general options. If a rule is not specified in a configuration then the rule will never raise an event for the configuration. through specific limit on memory usage or number of instances. A rule shares all parts of the rule options. limited to: Source IP address and port Destination IP address and port Action A higher revision of a rule in one configuration will override other revisions of the same rule in other configurations. These options are ignored in non-default policies without raising an error. 131 . Options controlling specific preprocessor memory usage. those variables must be defined in that configuration. non-payload detection options. The options control total memory usage for a preprocessor across all policies. Events and Output An unique policy id can be assigned by user. Preprocessors Preprocessors configurations can be defined within each vlan or subnet specific configuration. snort assigns 0 (zero) value to the configuration. For addressed based configuration binding. If VLANID is present. including: • a single mechanism for all responses • fully encoded reset or icmp unreachable packets • updated flexible response rule option • updated react rule option • added block and sblock rule actions These changes are outlined below.300) Active responses will be encoded based on the triggering packet. then destination IP address is searched to the most specific subnet that is bound to a non-default configuration. . default configuration is used if no other matching configuration is found.11./configure --enable-active-response / -DACTIVE_RESPONSE preprocessor stream5_global: \ max_active_responses <max_rsp>. this can lead to conflicts between configurations if source address is bound to one configuration and destination address is bound to another..Refers to the absolute or relative filename. In this case..9 includes a number of changes to better handle inline operation.1 Enabling Active Response This enables active responses (snort will send TCP RST or ICMP unreachable/port) when dropping a session. Each event 2.3 How Configuration is applied? Snort assigns every incoming packet to a unique configuration based on the following criteria. TTL will be set to the value captured at session pickup. that can be applied to the packet. In the end. 2.output alert_unified2: vlan_event_types (alert logging only) output unified2: filename <filename>.When this option is set. \ min_response_seconds <min_sec> <max_rsp> ::= (0. snort will use unified2 event type 104 and 105 for IPv4 and IPv6 respectively.10. 132 . ! △NOTElogged will have the vlanId from the packet if vlan headers are present otherwise 0 will be used.11 Active Response Snort 2. The packet is assigned non-default configuration if found otherwise the check is repeated using source IP address. vlan event types . 2. snort will use the first configuration in the order of definition. then the innermost VLANID is used to find bound configuration. vlan_event_types (true unified logging) filename .25) <min_sec> ::= (1. If the bound configuration is the default configuration. 4 React react is a rule option keyword that enables sending an HTML page on a session and then resetting it. . Each attempt (sent in rapid succession) has a different sequence number. .. non-functional.20) 2.11../configure --enable-flexresp / -DENABLE_RESPOND -DENABLE_RESPONSE config flexresp: attempts 1 * Flexresp2 is deleted. At most 1 ICMP unreachable is sent. This sequence ”strafing” is really only useful in passive mode./configure --enable-active-response config response: attempts <att> <att> ::= (1. In inline mode the reset is put straight into the stream in lieu of the triggering packet so strafing is not necessary.11.3 Flexresp Flexresp and flexresp2 are replaced with flexresp3./configure --enable-react / -DENABLE_REACT The page to be sent can be read from a file: 133 . * Flexresp is deleted./configure --enable-flexresp3 / -DENABLE_RESPOND -DENABLE_RESPONSE3 alert tcp any any -> any 80 (content:"a".2.11. resp:<resp_t>. TCP data (sent for react) is multiplied similarly.. and will be deleted in a future release: . This is built with: . these features are deprecated. these features are no longer avaliable: . if and only if attempts ¿ 0. In fact.config react: <block. 134 . including any HTTP headers. which defaults to: <default_msg> ::= \ "You are attempting to access a forbidden site. a resp option can be used instead. If no page should be sent. Note that the file must contain the entire response. This is an example rule: drop tcp any any -> any $HTTP_PORTS ( \ content: "d". 2.html> or else the default is used: <default_page> ::= \ "HTTP/1. \ react: <react_opts>. When the rule is configured. charset=utf-8\r\n" "\r\n" "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1. The deprecated options are ignored. msg:"Unauthorized Access Prohibited!". sid:4.1//EN\"\r\n" \ " \" Rule Actions The block and sblock actions have been introduced as synonyms for drop and sdrop to help avoid confusion between packets dropped due to load (eg lack of available buffers for incoming packets) and packets blocked due to Snort’s analysis. [proxy <port#>] The original version sent the web page to one end of the session only if the other end of the session was port 80 or the optional proxy port.dtd\">\r\n" \ "<html xmlns=\".". charset=UTF-8\" />\r\n" \ "<title>Access Denied</title>\r\n" \ "</head>\r\n" \ "<body>\r\n" \ "<h1>Access Denied</h1>\r\n" \ "<p>%s</p>\r\n" \ "</body>\r\n" \ "</html>\r\n". <dep_opts>] These options are deprecated: <dep_opts> ::= [block|warn].org/TR/xhtml11/DTD/xhtml11.w3.) <react_opts> ::= [msg] [.1 403 Forbidden\r\n" "Connection: close\r\n" "Content-Type: text/html.<br />" \ "Consult your system administrator for details. The new version always sends the page to the client.w3. You could craft a binary payload of arbitrary content. the page is loaded and the selected message.org/1999/xhtml\" xml:lang=\"en\">\r\n" \ "<head>\r\n" \ "<meta http-equiv=\"Content-Type\" content=\"text/html. the response isn’t strictly limited to HTTP.11. The rule option section contains alert messages and information on which parts of the packet should be inspected to determine if the rule action should be taken. protocol. The words before the colons in the rule options section are called option keywords.2 Rules Headers 3.1 The Basics Snort uses a simple. msg:"mountd access".8. and the source and destination ports information. The first item in a rule is the rule alert tcp any any -> 192. source and destination IP addresses and netmasks. the various rules in a Snort rules library file can be considered to form a large logical OR statement. The rule header contains the rule’s action. for that matter). This was required in versions prior to 1.1 illustrates a sample Snort rule.2. the rule header and the rule options.0/24 111 \ (content:"|00 01 86 a5|". they are just used for the sake of making tighter definitions of packets to collect or alert on (or drop.) Figure 3. Snort rules are divided into two logical sections.1. 3. All of the elements in that make up a rule must be true for the indicated rule action to be taken. There are a number of simple guidelines to remember when developing Snort rules that will help safeguard your sanity. Figure 3. The text up to the first parenthesis is the rule header and the section enclosed in parenthesis contains the rule options. where. In current versions of Snort. and what of a packet. At the same time. the elements can be considered to form a logical AND statement.Chapter 3 Writing Snort Rules 3.1 Rule Actions The rule header contains the information that defines the who. rules may span multiple lines by adding a backslash \ to the end of the line.168. as well as what to do in the event that a packet with all the attributes indicated in the rule should show up. ! △NOTE Note that the rule options section is not specifically required by any rule.1: Sample Snort Rule 135 . Most Snort rules are written in a single line. When taken together. lightweight rules description language that is flexible and quite powerful. For example.log the packet 3. the address/CIDR combination 192. 8. reject. mysql. you have additional options which include drop. and then send a TCP reset if the protocol is TCP or an ICMP port unreachable message if the protocol is UDP.168. IPX.3 IP Addresses The next portion of the rule header deals with the IP address and port information for a given rule. There are 5 available default actions in Snort. In the future there may be more. /16 a Class B network. log. activate . the destination address would match on any address in that range. IGRP. and then log the packet 2. and sdrop. There are four protocols that Snort currently analyzes for suspicious behavior – TCP.1 to 192. pass . The keyword any may be used to define any address. 1. if you are running Snort in inline mode.block the packet but do not log it. In addition. The rule action tells Snort what to do when it finds a packet that matches the rule criteria. drop .log } This example will create a rule type that will log to syslog and a MySQL database: ruletype redalert { type alert output alert_syslog: LOG_AUTH LOG_ALERT output database: log. reject . such as ARP. Snort does not have a mechanism to provide host name lookup for the IP address fields in the config file. user=snort dbname=snort host=localhost } 3.block the packet.ignore the packet 4.2 Protocols The next field in a rule is the protocol. RIP. alert. dynamic .1. The CIDR designations give us a nice short-hand way to designate large address spaces with just a few characters.action. The addresses are formed by a straight numeric IP address and a CIDR[3] block. GRE. You can then use the rule types as actions in Snort rules. log it. then act as a log rule 6. etc.alert and then turn on another dynamic rule 5.168. ICMP. OSPF. and dynamic. sdrop . and /32 indicates a specific machine address.255.block and log the packet 7.generate an alert using the selected alert method. say. activate.1. 136 . This example will create a type that will log to just tcpdump: ruletype suspicious { type log output log_tcpdump: suspicious.0/24 would signify the block of addresses from 192. Any rule that used this designation for. You can also define your own rule types and associate one or more output plugins with them. 3.remain idle until activated by an activate rule .2. UDP. alert . The CIDR block indicates the netmask that should be applied to the rule’s address and any incoming packets that are tested against the rule. and IP.1.168. log . pass. A CIDR block mask of /24 indicates a Class C network.2. The negation operator may be applied against any of the other rule types (except any.4 Port Numbers Port numbers may be specified in a number of ways.) Figure 3.1.1.0/24 111 \ (content:"|00 01 86 a5|".168. if for some twisted reason you wanted to log everything except the X Windows ports.10. See Figure 3. For the time being.0/24 any -> 192. such as in Figure 3. This rule’s IP addresses indicate any tcp packet with a source IP address not originating from the internal network and a destination address on the internal network. For example. msg:"external mountd access".1. and by negation.1. including any ports..alert tcp !192.1.2.5 The Direction Operator The direction operator -> indicates the orientation.2: Example IP Address Negation Rule alert tcp ![192.3 for an example of an IP list in action. 3. This operator tells Snort to match any IP address except the one indicated by the listed IP address.4: Port Range Examples 137 .4.168. the negation operator.3: IP Address Lists In Figure 3.0/24 1:1024 log udp traffic coming from any port and destination ports ranging from 1 to 1024 log tcp any any -> 192.. 23 for telnet.1.0/24 :6000 log tcp traffic from any port going to ports less than or equal to 6000 log tcp any :1024 -> 192.0/24] any -> \ [192. You may also specify lists of IP addresses.) Figure 3. The range operator may be applied in a number of ways to take on different meanings.1. etc. There is an operator that can be applied to IP addresses.168. Port ranges are indicated with the range operator :. An IP list is specified by enclosing a comma separated list of IP addresses and CIDR blocks within square brackets. the IP list may not include spaces between the addresses. static port definitions.2. or 80 for http. you could do something like the rule in Figure 3.0/24. For example. the source IP address was set to match for any computer talking.168. such as 111 for portmapper. meaning literally any port.168. Any ports are a wildcard value. Static ports are indicated by a single port number. how Zen. The IP address and port numbers on the left side of the direction operator is considered to be the traffic coming from the source log udp any any -> 192. of the traffic that the rule applies to. Port negation is indicated by using the negation operator !.168. ranges.10. 3.1.1.1.0/24] 111 (content:"|00 01 86 a5|".1.1. an easy modification to the initial example is to make it alert on any traffic that originates outside of the local net with the negation operator as shown in Figure 3. The negation operator is indicated with a !.0/24. or direction.5. and the destination address was set to match on the 192. which would translate to none.1.168.0/24 500: log tcp traffic from privileged ports less than or equal to 1024 going to ports greater than or equal to 500 Figure 3.0 Class C network.2.).168. \ msg:"external mountd access". This is very useful if you want to set Snort up to perform follow on recording when a specific rule goes off. \ content:"|E8C0FFFFFF|/bin".6. You can now have one rule activate another when it’s action is performed for a set number of packets.0/24 23 Figure 3. activate tcp !$HOME_NET any -> $HOME_NET 143 (flags:PA. and the address and port information on the right side of the operator is the destination host.7.6.1.7. there’s a very good possibility that useful data will be contained within the next 50 (or whatever) packets going to that same service port on the network. Activate rules act just like alert rules. Dynamic rules are just like log rules except are dynamically enabled when the activate rule id goes off.does not exist is so that rules always read consistently. In Snort versions before 1.168.7. Activate rules are just like alerts but also tell Snort to add a rule when a specific network event occurs.5: Example of Port Negation log tcp !192.168.) Figure 3. count. \ msg:"IMAP buffer overflow!". All Snort rule options are separated from each other using the semicolon (.8. Dynamic rules act just like log rules. Also. so there’s value in collecting those packets for later analysis.0/24 any <> 192. There is also a bidirectional operator.5) and flowbits (3. such as telnet or POP3 sessions. which is indicated with a <> symbol. Rule option keywords are separated from their arguments with a colon (:) character. combining ease of use with power and flexibility. note that there is no <. count:50.) character. An example of the bidirectional operator being used to record both sides of a telnet session is shown in Figure 3.7: Activate/Dynamic Rule Example 138 . Put ’em together and they look like Figure 3. activates:1.0/24 !6000:6010 Figure 3. except they have a *required* option field: activates.10). The reason the <. Activate/dynamic rule pairs give Snort a powerful capability. Dynamic rules have a second required field as well.2. 3.6 Activate/Dynamic Rules ! △NOTE Activate and Dynamic rules are being phased out in favor of a combination of tagging (3. These rules tell Snort to alert when it detects an IMAP buffer overflow and collect the next 50 packets headed for port 143 coming from outside $HOME NET headed to $HOME NET.1.3 Rule Options Rule options form the heart of Snort’s intrusion detection engine.1.operator. If the buffer overflow happened and was successful.168.) dynamic tcp !$HOME_NET any -> $HOME_NET 143 (activated_by:1. but they have a different option field: activated by.log tcp any any -> 192. This is handy for recording/analyzing both sides of a conversation. 3. the direction operator did not have proper error checking and many people used an invalid token.6: Snort rules using the Bidirectional Operator host. This tells Snort to consider the address/port pairs in either the source or destination orientation. com/bid/. reference:arachnids.whitehats.org/plugins/dump.4.4).) alert tcp any any -> any 21 (msg:"IDS287/ftp-wuftp260-venglin-linux". \ 139 . content:"|fff4 fffd 06|".mitre.] Examples alert tcp any any -> any 7070 (msg:"IDS411/dos-realaudio".nessus.4.nai.1: Supported Systems URL Prefix. \ flags:AP. [reference:<id system>.1 msg The msg rule option tells the logging and alerting engine the message to print along with a packet dump or to an alert. The plugin currently supports several specific systems as well as unique URLs. This plugin is to be used by output plugins to provide a link to additional information about the alert produced. 3.IDS411. It is a simple text string that utilizes the \ as an escape character to indicate a discrete character that might otherwise confuse Snort’s rules parser (such as the semi-colon . character).4. <id>. Table 3. Format msg:"<message text>".2 reference The reference keyword allows rules to include references to external attack identification systems.com/info/IDS.” 3.org/show/osvdb/ http:// System bugtraq cve nessus arachnids mcafee osvdb url Format reference:<id system>. Make sure to also take a look at for a system that is indexing descriptions of alerts based on of the sid (See Section 3.com/vil/content/v. <id>.There are four major categories of rule options.php3?id= (currently down) General Rule Options 3. \ reference:arachnids. This information is useful when postprocessing alert to map an ID to an alert message.map contains a mapping of alert messages to Snort rule IDs.4 sid The sid keyword is used to uniquely identify Snort rules. (See section 3. sid:1. (See section 3.) 3. reference:bugtraq.000. sid:1000983.000 Used for local rules The file sid-msg. content:"|31c031db 31c9b046 cd80 31c031db|". it is not recommended that the gid keyword be used.) 140 . rev:1.map contains contains more information on preprocessor and decoder gids. This option should be used with the sid keyword. it is recommended that values starting at 1.flags:AP. alert tcp any any -> any 80 (content:"BOB".000 be used. Example This example is a rule with the Snort Rule ID of 1000983. Format sid:<snort rules id>.CAN-2000-1574.1387. For example gid 1 is associated with the rules subsystem and various gids over 100 are designated for specific preprocessors and the decoder.5) • <100 Reserved for future use • 100-999.4.IDS287. For general rule writing. alert tcp any any -> any 80 (content:"BOB".4) The file etc/gen-msg. it will default to 1 and the rule will be part of the general rule subsystem. This information allows output plugins to identify rules easily. \ reference:cve.) 3. This option should be used with the rev keyword. See etc/generators in the source tree for the current generator ids in use. To avoid potential conflict with gids defined in Snort (that for some reason aren’t noted it etc/generators).4. Example This example is a rule with a generator id of 1000001.000.999 Rules included with the Snort distribution • >=1. rev:1.4. Format gid:<generator id>.4. gid:1000001. ) Attack classifications defined by Snort reside in the classification. Example This example is a rule with the Snort Rule Revision of 1. The file uses the following syntax: config classification: <class name>.5 rev The rev keyword is used to uniquely identify revisions of Snort rules. Format classtype:<class name> . alert tcp any any -> any 80 (content:"BOB".4.4.4) Format rev:<revision integer>. Snort provides a default set of attack classes that are used by the default set of rules it provides. allow signatures and descriptions to be refined and replaced with updated information. rev:1. nocase. \ content:"expn root".<class description>.) 3. sid:1000983. Revisions.4. Example alert tcp any any -> any 25 (msg:"SMTP expn root". This option should be used with the sid keyword.2.6 classtype The classtype keyword is used to categorize a rule as detecting an attack that is part of a more general type of attack class. (See section 3. They are currently ordered with 4 default priorities.<default priority> These attack classifications are listed in Table 3. Defining classifications for rules provides a way to better organize the event data Snort produces. A priority of 1 (high) is the most severe and 4 (very low) is the least severe.3. Table 3. along with Snort rule id’s. classtype:attempted-recon.config file. flags:A+. \ dsize:>128.conf by using the config classification option. Format priority:<priority integer>. \ content:"/cgi-bin/phf".config that are used by the rules it provides.4. flags:A+. Examples of each case are given below. classtype:attempted-admin. priority:10 ).7 priority The priority tag assigns a severity level to rules. priority:10.) alert tcp any any -> any 80 (msg:"EXPLOIT ntpdx overflow". Examples alert tcp any any -> any 80 (msg:"WEB-MISC phf attempt". 142 . Snort provides a default set of classifications in classification. 3. A classtype rule assigns a default priority (defined by the config classification option) that may be overridden with a priority rule. 143 .) 3. with keys separated by commas. Table 3. When the value exactly matches the service ID as specified in the table. Keys other than those listed in the table are effectively ignored by Snort and can be free-form.8 metadata The metadata tag allows a rule writer to embed additional information about the rule. the second a single metadata keyword. the rule is applied to that packet. Certain metadata keys and values have meaning to Snort and are listed in Table 3. metadata:key1 value1. while keys and values are separated by a space. metadata:key1 value1.) alert tcp any any -> any 80 (msg:"Shared Library Rule Example".3.7 for details on the Host Attribute Table. .4: General rule option keywords Keyword msg reference gid Description The msg keyword tells the logging and alerting engine the message to print with the packet dump or alert. Multiple keys are separated by a comma.4. The first uses multiple metadata keywords. Format The examples below show an stub rule from a shared library rule. \ metadata:engine shared. key2 value2. with a key and a value. Examples alert tcp any any -> any 80 (msg:"Shared Library Rule Example". the rule is not applied (even if the ports specified in the rule match).) alert tcp any any -> any 80 (msg:"HTTP Service Rule Example". otherwise. soid 3|12345. typically in a key-value format.9 General Rule Quick Reference Table 3. \ metadata:engine shared. \ metadata:service http.4. metadata:soid 3|12345. The gid keyword (generator id) is used to identify what part of Snort generates the event when a particular rule fires. The reference keyword allows rules to include references to external attack identification systems. See Section 2.3. if using content:!"A". the alert will be triggered on packets that do not contain this content. The priority keyword assigns a severity level to rules. The binary data is generally enclosed within the pipe (|) character and represented as bytecode. It allows the user to set rules that search for specific content in the packet payload and trigger response based on that data. modifiers included. The metadata keyword allows a rule writer to embed additional information about the rule. 3. The option data for the content keyword is somewhat complex. Whenever a content option pattern match is performed. it can contain mixed text and binary data. the result will return a match. 144 . use isdataat as a pre-cursor to the content. typically in a key-value format. The example below shows use of mixed text and binary data in a Snort rule.) alert tcp any any -> any 80 (content:!"GET".) ! △NOTE A ! modifier negates the results of the entire content search. Be aware that this test is case sensitive. This allows rules to be tailored for less false positives. Note that multiple content rules can be specified in one rule. within:50.sid rev classtype priority metadata The sid keyword is used to uniquely identify Snort rules.1 content The content keyword is one of the more important features of Snort.5. This is useful when writing rules that want to alert on packets that do not match a certain pattern ! △NOTE Also note that the following characters must be escaped inside a content rule: . If data exactly matching the argument data string is contained anywhere within the packet’s payload. \ " Format content:[!]"<content string>". If there must be 50 bytes for a valid match. The classtype keyword is used to categorize a rule as detecting an attack that is part of a more general type of attack class. Examples alert tcp any any -> any 139 (content:"|5c 00|P|00|I|00|P|00|E|00 5c|".5 Payload Detection Rule Options 3. For example. Bytecode represents binary data as hexadecimal numbers and is a good shorthand method for describing complex binary data. If the rule is preceded by a !. the test is successful and the remainder of the rule option tests are performed. and there are only 5 bytes of payload and there is no ”A” in those 5 bytes. The rev keyword is used to uniquely identify revisions of Snort rules. the Boyer-Moore pattern match function is called and the (rather computationally expensive) test is performed against the packet contents. 5.5.5.5.5.14 http raw uri 3.5.16 http stat msg 3.8 http cookie 3. These modifier keywords are: Table 3.9 http raw cookie 3.5.5. 145 .5.12 http method 3.5. Format nocase.5 distance 3.2 nocase The nocase keyword allows the rule writer to specify that the Snort should look for the specific pattern.5. The modifier keywords change how the previously specified content works.1 option.6 within 3.2 rawbytes 3.19 3.3 rawbytes The rawbytes keyword allows rules to look at the raw packet data.7 http client body 3. format rawbytes.5.5.5.) 3. nocase modifies the previous content keyword in the rule. This acts as a modifier to the previous content 3. nocase.17 fast pattern 3.Changing content behavior The content keyword has a number of modifier keywords.11 http raw header 3.5.5.5.5.10 http header 3.13 http uri 3.5. ignoring any decoding that was done by preprocessors.4 offset 3.5: Content Modifiers Modifier Section nocase 3.15 http stat code 3.5. Example alert tcp any any -> any 21 (msg:"FTP ROOT". content:"USER root". ignoring case.3 depth 3. ) 146 .5. The offset and depth keywords may be used together. and depth search rule.Example This example tells the content pattern matcher to look at the raw traffic. offset. This keyword allows values greater than or equal to the pattern length being searched.5 offset The offset keyword allows the rule writer to specify where to start searching for a pattern within a packet. distance. A depth of 5 would tell Snort to only look for the specified pattern within the first 5 bytes of the payload. or within (to modify the same content). instead of the decoded traffic provided by the Telnet decoder. As this keyword is a modifier to the previous content keyword.5. there must be a content in the rule before offset is specified. offset modifies the previous ’content’ keyword in the rule. Format depth:[<number>|<var_name>]. alert tcp any any -> any 21 (msg:"Telnet NOP". there must be a content in the rule before depth is specified. alert tcp any any -> any 80 (content:"cgi-bin/phf".4 depth The depth keyword allows the rule writer to specify how far into a packet Snort should search for the specified pattern. offset:4. You can not use offset with itself. The value can also be set to a string value referencing a variable extracted by the byte extract keyword in the same rule. The value can also be set to a string value referencing a variable extracted by the byte extract keyword in the same rule. or within (to modify the same content). The minimum allowed value is 1. An offset of 5 would tell Snort to start looking for the specified pattern after the first 5 bytes of the payload.) 3. Format offset:[<number>|<var_name>]. 3. You can not use depth with itself. rawbytes. depth modifies the previous ‘content’ keyword in the rule. The offset and depth keywords may be used together. content:"|FF F1|". This keyword allows values from -65535 to 65535. The maximum allowed value for this keyword is 65535. Example The following example shows use of a combined content. As the depth keyword is a modifier to the previous content keyword. depth:20. distance. content:"DEF". You can not use distance with itself. or depth (to modify the same content). within:10. alert tcp any any -> any any (content:"ABC".5. You can not use within with itself.3. This can be thought of as exactly the same thing as offset (See Section 3. This keyword allows values from -65535 to 65535. content:"EFG"}DEF/.6) rule option. Format within:[<byte_count>|<var_name>]. Examples This rule constrains the search of EFG to not go past 10 bytes past the ABC match. This keyword allows values greater than or equal to pattern length being searched.5). The value can also be set to a string value referencing a variable extracted by the byte extract keyword in the same rule. alert tcp any any -> any any (content:"ABC".5.) 3. Format distance:[<byte_count>|<var_name>].) 147 . The maximum allowed value for this keyword is 65535. Example The rule below maps to a regular expression of /ABC. offset. It’s designed to be used in conjunction with the distance (Section 3. distance:1.1 ). or depth (to modify the same content). offset.5.5.5. except it is relative to the end of the last pattern match instead of the beginning of the packet.7 within The within keyword is a content modifier that makes sure that at most N bytes are between pattern matches using the content keyword ( See Section 3. The distance and within keywords may be used together..2. When enable cookie is not specified.3. 148 .6). The cookie buffer also includes the header name (Cookie for HTTP requests or Set-Cookie for HTTP responses). If enable cookie is not specified.) !.5. there must be a content in the rule before ’http client body’ is specified. alert tcp any any -> any 80 (content:"ABC". Examples This rule constrains the search for the pattern ”EFG” to the raw body of an HTTP client request. 3. The amount of data that is inspected with this option depends on the post depth config option of HttpInspect. per the configuration of HttpInspect (see 2. alert tcp any any -> any 80 (content:"ABC". The Cookie Header field will be extracted only when this option is configured. As this keyword is a modifier to the previous content keyword.6). This keyword is dependent on the enable cookie config option. content:"EFG". content:"EFG". using http cookie is the same as using http header. Format http_cookie.8 http client body The http client body keyword is a content modifier that restricts the search to the body of an HTTP client request. the cookie still ends up in HTTP header. http_cookie. Format http_client_body.5. http_client_body. The extracted Cookie Header field may be NORMALIZED. there must be a content in the rule before http cookie is specified. Pattern matches with this keyword wont work when post depth is set to -1. content:"EFG". per the configuration of HttpInspect (see 2.2. As this keyword is a modifier to the previous content keyword. http_raw_cookie. 149 .3. This keyword is dependent on the enable cookie config option. Format http_header.. http cookie or fast pattern modifiers for the same content. The extracted Header fields may be NORMALIZED.) ! △NOTE The http raw cookie modifier is not allowed to be used with the rawbytes_header.2. alert tcp any any -> any 80 (content:"ABC". Format http_raw_cookie. As this keyword is a modifier to the previous content keyword. 3.5. Examples This rule constrains the search for the pattern ”EFG” to the extracted Header fields of a HTTP client request or a HTTP server response.5.6).6).6). there must be a content in the rule before http raw cookie is specified. alert tcp any any -> any 80 (content:"ABC".2. content:"EFG". As this keyword is a modifier to the previous content keyword. alert tcp any any -> any 80 (content:"ABC".20). Format http_raw_header. The http method 3. content:"EFG". http header or fast pattern The http raw modifiers for the same content. As this keyword is a modifier to the previous content keyword. there must be a content in the rule before http method is specified. alert tcp any any -> any 80 (content:"ABC". http_raw_header. As this keyword is a modifier to the previous content keyword.13 http method The http method keyword is a content modifier that restricts the search to the extracted Method from a HTTP client request. http_method. there must be a content in the rule before http uri is specified. 3.5.6).3.) ! △NOTE modifier is not allowed to be used with the rawbytes modifier for the same content.5. Using a content rule option followed by a http uri modifier is the same as using a uricontent by itself (see: 3. 150 .5. Examples This rule constrains the search for the pattern ”GET” to the extracted Method from a HTTP client request. Examples This rule constrains the search for the pattern ”EFG” to the extracted Header fields of a HTTP client request or a HTTP server response.2. there must be a content in the rule before http raw header is specified. content:"GET".5.) ! △NOTE header modifier is not allowed to be used with the rawbytes.14 http uri The http uri keyword is a content modifier that restricts the search to the NORMALIZED request URI field . Format http_method. content:"EFG".5. The Status Code field will be extracted only if the extended reponse inspection is configured for the HttpInspect (see 2. alert tcp any any -> any 80 (content:"ABC".. Format http_raw_uri. http_uri.) ! △NOTE The http raw uri modifier is not allowed to be used with the rawbytes. As this keyword is a modifier to the previous content keyword. content:"EFG". 151 . Format http_stat_code. http_raw_uri.6). alert tcp any any -> any 80 (content:"ABC".5. 3. Examples This rule constrains the search for the pattern ”EFG” to the UNNORMALIZED URI.) ! △NOTE The http uri modifier is not allowed to be used with the rawbytes modifier for the same content. http uri or fast pattern modifiers for the same content.Format http_uri. there must be a content in the rule before http raw uri is specified. 3.2. This rule option will not be able to detect encodings if the specified HTTP fields are not NORMALIZED. The Status Message field will be extracted only if the extended reponse inspection is configured for the HttpInspect (see 2. 3. The keywords ’uri’.5. alert tcp any any -> any 80 (content:"ABC". ’header’ and ’cookie’ determine the HTTP fields used to search for a particular encoding type. content:"200". Negation is allowed on these keywords.2. There are eleven keywords associated with http encode. Examples This rule constrains the search for the pattern ”Not Found” to the extracted Status Message field of a HTTP server response. The keyword ’cookie’ is dependent on config options ’enable cookie’ and ’normalize cookies’ (see 2. The config option ’normalize headers’ needs to be turned on for rules to work with the keyword ’header’. The keywords ’utf8’. ’non ascii’.Examples This rule constrains the search for the pattern ”200” to the extracted Status Code field of a HTTP server response. ’double encode’. alert tcp any any -> any 80 (content:"ABC". ’iis encode’ and ’bare byte’ determine the encoding type which would trigger the alert.6). ’uencode’. 3. content:"Not Found".6).) ! △NOTE The http stat msg modifier is not allowed to be used with the rawbytes or fast pattern modifiers for the same content. http_stat_code. These keywords can be combined using a OR operation. 152 .17 http stat msg The http stat msg keyword is a content modifier that restricts the search to the extracted Status Message field from a HTTP server response. ’base36’.2. http_stat_msg.18 http encode The http encode keyword will enable alerting based on encoding type present in a HTTP client request or a HTTP server response (per the configuration of HttpInspect 2. Format http_stat_msg. ’ascii’. there must be a content in the rule before http stat msg is specified. As this keyword is a modifier to the previous content keyword.6).) ! △NOTE The http stat code modifier is not allowed to be used with the rawbytes or fast pattern modifiers for the same content.5.2. 19 fast pattern The fast pattern keyword is a content modifier that sets the content within a rule to be used with the fast pattern matcher. The better the content used for the fast pattern matcher.5. ! △NOTE The fast pattern modifier cannot be used with the following http content modifiers: http cookie. The fast pattern option may be specified only once per rule. Note. http_encode:uri. 3. http raw header. there must be a content rule option in the rule before fast pattern is specified. Since the default behavior of fast pattern determination is to use the longest content in the rule. http raw cookie. http stat msg.) alert tcp any any -> any any (msg:"No UTF8". As this keyword is a modifier to the previous content keyword. http_encode:uri. OR and negation operations work only on the encoding type field and not on http buffer type field. however. [!][<utf8|double_encode|non_ascii|base36|uencode|bare_byte|ascii|iis_e Examples alert tcp any any -> any any (msg:"UTF8/UEncode Encoding present". it is useful if a shorter content is more ”unique” than the longer content. [!]<encoding type> http_encode:[uri|header|cookie]. The fast pattern matcher is used to select only those rules that have a chance of matching by using a content in the rule for selection and only evaluating that rule if the content is found in the payload. that it is okay to use the fast pattern modifier if another http content modifier not mentioned above is used in combination with one of the above to modify the same content. http stat code.utf8|uencode. http raw uri. 153 . the less likely the rule will needlessly be evaluated. it can significantly reduce the number of rules that need to be evaluated and thus increases performance. Though this may seem to be overhead.!utf8. meaning the shorter content is less likely to be found in a packet than the longer content.) ! △NOTE Negation(!) and OR(|) operations cannot be used in conjunction with each other for the http encode keyword. the URI: 154 .! △NOTE modifier can be used with negated contents only if those contents are not modified with The fast pattern offset. depth. these rules will not alert. depth.5. The optional argument only can be used to specify that the content should only be used for the fast pattern matcher and should not be evaluated as a rule option. fast_pattern. This is useful.) 3. This is useful if the pattern is very long and only a portion of the pattern is necessary to satisfy ”uniqueness” thus reducing the memory required to store the entire pattern in the fast pattern matcher. distance or within. ! △NOTE arguments only and <offset>. content:"IJKLMNO". as it saves the time necessary to evaluate the rule option. The reason is that the things you are looking for are normalized out of the URI buffer. This is equivalent to using the http uri modifier to a content keyword. As such if you are writing rules that include things that are normalized.) This rule says to use the content ”IJKLMNO” for the fast pattern matcher and that the content should only be used for the fast pattern matcher and not evaluated as a content rule option. the meaning is simply to use the specified content as the fast pattern content for the rule. content:"IJKLMNO". distance or within.<length> are mutually exclusive. The optional argument <offset>. alert tcp any any -> any 80 (content:"ABCDEFGH". alert tcp any any -> any 80 (content:"ABCDEFGH".<length>.<length> can be used to specify that only a portion of the content should be used for the fast pattern matcher. Format The fast pattern option can be used alone or optionally take arguments. fast_pattern:<offset>. even though it is shorter than the earlier pattern ”ABCDEFGH”.. For example. but still evaluate the content rule option as ”IJKLMNO”.20 uricontent The uricontent keyword in the Snort rule language searches the NORMALIZED request URI field. nocase. for example. fast_pattern:1. fast_pattern:only. such as %2f or directory traversals.) This rule says to use ”JKLMN” as the fast pattern content. The optional Examples This rule causes the pattern ”IJKLMNO” to be used with the fast pattern matcher. alert tcp any any -> any 80 (content:"ABCDEFGH". fast_pattern. fast_pattern:only. if a known content must be located in the payload independent of location in the payload. content:"IJKLMNO". When used alone.5. 5.5.5. 3.%252fp%68f? will get normalized into: /cgi-bin/phf? When writing a uricontent rule.exe?/c+ver Another example.7 fast pattern 3. Format uricontent:[!]"<content string>".5. the minimum length. If you wish to uricontent search the UNNORMALIZED request URI field.1) uricontent can be used with several of the modifiers available to the content keyword.2 depth 3.. Format urilen:min<>max.5.. ! △NOTE cannot be modified by a rawbytes modifier or any of the other HTTP modifiers. (See Section 3.19 This option works in conjunction with the HTTP Inspect preprocessor specified in Section 2.5. These include: Table 3. use the http raw uri modifier with a content option.4 offset 3.21 urilen The urilen keyword in the Snort rule language specifies the exact length. You can write rules that look for the non-normalized content by using the content option.6. the maximum length.exe?/c+ver will get normalized into: /winnt/system32/cmd..2. write the content that you want to find in the context that the URI will be normalized./scripts/. For example. if Snort normalizes directory traversals.5.6 within 3. The following example will match URIs that are 5 bytes long: 155 . urilen:[<|>]<number>.5 distance 3.%c0%af. the URI: /cgi-bin/aaaaaaaaaaaaaaaaaaaaaaaaaa/.6: Uricontent Modifiers Modifier Section nocase 3. or range of URI lengths to match.5./winnt/system32/cmd. do not include directory traversals. When the rawbytes modifier is specified with isdataat. 3.pcre.7. isdataat:50. relative|rawbytes]. S and Y.22 isdataat Verify that the payload has data at a specified location. would alert if there were not 10 bytes after ”foo” before the payload ended. The following example will match URIs that are greater than 5 bytes and less than 10 bytes: urilen:5<>10. check out the PCRE web site. The post-re modifiers set compile time flags for the regular expression.23 pcre The pcre keyword allows rules to be written using perl compatible regular expressions. 156 . Format isdataat:[!]<int>[. This modifier will work with the relative modifier as long as the previous content match was in the raw packet data. A ! modifier negates the results of the isdataat test. the rule with modifiers content:"foo". ignoring any decoding that was done by the preprocessors. The modifiers H.2. C. it looks at the raw packet data. K. P. \ content:!"|0a|". Example alert tcp any any -> any 111 (content:"PASS". I.5.relative. ! △NOTE R (relative) and B (rawbytes) are not allowed with any of the HTTP modifiers such as U. It will alert if a certain amount of data is not present within the payload.9 for descriptions of each modifier.5. 3.org Format pcre:[!]"(/<regex>/|m<delim><regex><delim>)[ismxAEGRUBPHMCOIDKYS]". then verifies that there is not a newline character within 50 bytes of the end of the PASS string. within:50. optionally looking for data relative to the end of the previous content match. and 3. See tables 3.relative. then verifies there is at least 50 bytes after the end of the string PASS. D.) This rule looks for the string PASS exists in the packet. M. For example. The following example will match URIs that are shorter than 5 bytes: urilen:<5. 3.6.8. This option works in conjunction with the HTTP Inspect preprocessor specified in Section 2.urilen:5. For more detail on what can be done via a pcre regular expression. isdataat:!10. This is dependent on the SMTP config option enable mime decoding. Inverts the ”greediness” of the quantifiers so that they are not greedy by default.2. This option matches if there is HTTP response body or SMTP body or SMTP MIME base64 decoded data. you must use either a content or a uricontent.5. certain HTTP Inspect options such as extended response inspection and inspect gzip (for decompressed gzip data) needs to be turned on. Format file_data. For this option to work with HTTP response.8: PCRE compatible modifiers for pcre the pattern must match only at the start of the buffer (same as ˆ ) Set $ to match only at the end of the subject string. pcre) to use. the string is treated as one big line of characters. $ also matches immediately before the final character if it is a newline (but not before any other newlines).6 for more details. whitespace data characters in the pattern are ignored except when escaped or inside a character class A E G Table 3. When used with argument mime it places the cursor at the beginning of the base64 decoded MIME attachment or base64 decoded MIME body. file_data:mime. but become greedy if followed by ”?”. byte jump. This option will operate similarly to the dce stub data option added with DCE/RPC2. 3. Without E.7 for more details. 157 . PCRE when used without a uricontent only evaluates the first URI.) ! △NOTE Snort’s handling of multiple URIs with PCRE does not work as expected.i s m x Table 3. ˆ and $ match immediately following or immediately before any newline in the buffer. When m is set.24 file data This option is used to place the cursor (used to walk the packet payload in rules processing) at the beginning of either the entity body of a HTTP response or the SMTP body data. See 2. in that it simply sets a reference for other relative rule options ( byte test. alert ip any any -> any any (pcre:"/BLAH/i". See 2. In order to use pcre to inspect all URIs.2. Example This example performs a case-insensitive search for the string BLAH in the payload.7: Perl compatible modifiers for pcre case insensitive include newlines in the dot metacharacter By default. as well as the very start and very end of the buffer. ˆ and $ match at the beginning and ending of the string. This file data can point to either a file or a block of data. ][offset <offset>[. nocase. \ file_data. Example alert tcp any 80 -> any any(msg:"foo at the start of http response body". This modifier is not allowed with the normalized HTTP request or HTTP response header modifier(H) for the same content. (Similar to distance:0. Match normalized HTTP request method (Similar to http method) Match normalized HTTP request or HTTP response cookie (Similar to http cookie). within:10.1.) Match the decoded URI buffers (Similar to uricontent and http uri). It completely ignores the limits while evaluating the pcre pattern specified. within:3.5. content:"foo". Match unnormalized HTTP request or HTTP response cookie (Similar to http raw cookie). Match unnormalized HTTP request body (Similar to http client body) Match normalized HTTP request or HTTP response header (Similar to http header).) alert tcp any any -> any any(msg:"MIME BASE64 Encoded Data". This modifier is not allowed with the HTTP request uri buffer modifier(U) for the same content.R U I P H D M C K S Y B O Table 3. This modifier is not allowed with the unnormalized HTTP request or HTTP response cookie modifier(K) for the same content. This modifier is not allowed with the unnormalized HTTP request or HTTP response header modifier(D) for the same content. This option is particularly useful in case of HTTP headers such as HTTP authorization headers. This modifier is not allowed with the normalized HTTP request or HTTP response cookie modifier(C) for the same content.) 3. relative]]]. ! △NOTE Multiple base64 encoded attachments in one packet are pipelined. Match the unnormalized HTTP request uri buffer (Similar to http raw uri). 158 . Format base64_decode[:[bytes <bytes_to_decode>][. content:"foo". Match unnormalized HTTP request or HTTP response header (Similar to http raw header).\ file_data:mime.25 base64 decode This option is used to decode the base64 encoded data. This option unfolds the data before decoding it. The above arguments to base64 decode are optional. \ content:"NTLMSSP". content:"Authorization: NTLM". Specifies the inspection for base64 encoded data is relative to the doe ptr.) 3. Determines the offset relative to the doe ptr when the option relative is specified or relative to the start of the packet payload to begin inspection of base64 encoded data. \ content:"foo bar". in that it simply sets a reference for other relative rule options ( byte test. Examples alert tcp $EXTERNAL_NET any -> $HOME_NET any \ (msg:"Base64 Encoded Data". base64_data. Format base64_data. content:"NTLMSSP".) alert tcp $EXTERNAL_NET any -> $HOME_NET any \ (msg:"Authorization NTLM". \ base64_decode:bytes 12. \ within:20. The rule option base64 decode needs to be specified before the base64 data option. pcre) to use. This option will operate similarly to the file data option. Fast pattern content matches are not allowed with this buffer. This option matches if there is base64 decoded buffer. If folding is not present the search for base64 encoded data will end when we see a carriage return or line feed or both without a following space or tab. base64_decode. relative. This option needs to be used in conjunction with base64 data for any other relative rule options to work on base64 decoded buffer. http_header. within:20. ! △NOTE This option can be extended to protocols with folding similar to HTTP. within:8. byte jump. offset 6. base64_data.) alert tcp any any -> any any (msg:"Authorization NTLM". 159 . ! △NOTE Any non-relative rule options in the rule will reset the cursor(doe ptr) from base64 decode buffer. This argument takes positive and non-zero values only. \ content:"Authorization:". base64_decode:relative. This argument takes positive and non-zero values only. This option does not take any arguments.5.Option bytes offset relative Description Number of base64 encoded bytes to decode. When this option is not specified we look for base64 encoded data till either the end of header line is reached or end of packet payload is reached. base64_data.26 base64 data This option is used to place the cursor (used to walk the packet payload in rules processing) at the beginning of the base64 decode buffer if present. \ content:"Authorization:". 2 and 4. If the & operator is used. <value>.13 for a description and examples (2. Format byte_test:<bytes to convert>. base64_data. string.Process data as big endian (default) • little .Converted string data is represented in octal dce Let the DCE/RPC 2 preprocessor determine the byte order of the value to be converted.Process data as little endian string number type Data is stored in string format in packet Type of number being read: • hex . \ base64_decode:bytes 12. If used with dce allowed values are 1. Capable of testing binary values or converting representative byte strings to their binary equivalent and testing them. <number type>][. offset 6.27 byte test Test a byte field against a specific value (with operator).13 for quick reference).Converted string data is represented in hexadecimal • dec . Option bytes to convert operator Any of the operators can also include ! to check if the operator is not true. http_header. \ content:"NTLMSSP".) 3.greater than • = . For a more detailed explanation. The allowed values are 1 to 10 when used without dce.Example alert tcp any any -> any any (msg:"Authorization NTLM". Operation to perform to test the value: • < . bytes operator value offset = = = = 1 .equal • & .2. then it would be the same as using if (data & value) { do something(). ! △NOTE Snort uses the C operators for each of these operators.4294967295 -65535 to 65535 Description Number of bytes to pick up from the packet.Converted string data is represented in decimal • oct . See section 2. relative][. <offset> \ [. please read Section 3. If ! is specified without an operator.9. [!]<operator>.2.less than • > . then the operator is set to =. within:8.5.10 ’<’ | ’=’ | ’>’ | ’&’ | ’ˆ’ 0 .} Examples alert udp $EXTERNAL_NET any -> $HOME_NET any \ 160 . dce]. <endian>][.bitwise OR value offset relative endian Value to test the converted value against Number of bytes into the payload to start processing Use an offset relative to last pattern match Endian type of the number being read: • big .bitwise AND • ˆ . relative.5. \ byte_test:4. bytes offset mult_value post_offset = = = = 1 . >.) alert udp any any -> any 1237 \ (byte_test:10. 20. 0. <endian>][. dec. dec. from_beginning][. distance:4. relative][. 1000. 20. \ content:"|00 00 00 07|".) alert udp any any -> any 1236 \ (byte_test:2. dec. string.) 3. 0.) alert udp any any -> any 1234 \ (byte_test:4.10 -65535 to 65535 0 . within:4. For a more detailed explanation. By having an option that reads the length of a portion of data. \ msg:"got DEADBEEF!". =. dce]. Format byte_jump:<bytes_to_convert>. >. 0.65535 -65535 to 65535 161 . or doe ptr. \ msg:"got 123!". <number_type>]\ [. string.28 byte jump The byte jump keyword allows rules to be written for length encoded protocols trivially. then skips that far forward in the packet. 0. hex. \ content:"|00 00 00 07|". 123. string. distance:4. align][. dec. \ msg:"got 1234!".(msg:"AMD procedure 7 plog overflow". string. 12.) alert udp any any -> any 1235 \ (byte_test:3. 0. \ msg:"got 12!". \ msg:"got 1234567890!". within:4. relative. =. rules can be written that skip over specific portions of length-encoded protocols and perform detection in very specific locations. move that many bytes forward and set a pointer for later detection. =. string. \ content:"|00 04 93 F3|". This pointer is known as the detect offset end pointer. 1234. \ content:"|00 04 93 F3|". \ byte_test:4. please read Section 3.5. relative. =. 0xdeadbeef. 1234567890.) alert udp any any -> any 1238 \ (byte_test:8. The byte jump option does this by reading some number of bytes. =. post_offset <adjustment value>][. 1000. multiplier <mult_value>][.5. <offset> \ [. string. convert them to their numeric representation.) alert tcp $EXTERNAL_NET any -> $HOME_NET any \ (msg:"AMD procedure 7 plog overflow".9. ). multiplier <multiplier value>][. <value> may be 2 or 4. within:4. 2 and <align value>][. These variables can be referenced later in the rule. >. Example alert udp any any -> any 32770:34000 (content:"|00 01 86 B8|". Process data as big endian (default) Process data as little endian Use the DCE/RPC 2 preprocessor to determine the byte-ordering. relative][. 20.Option bytes to convert offset relative multiplier <value> big little string hex dec oct align from beginning post offset <value> dce Description Number of bytes to pick up from the packet. ! △NOTE Only two byte extract variables may be created per rule. string. align. The allowed values are 1 to 10 when used without dce. The DCE/RPC 2 preprocessor must be enabled for this option to work. Use an offset relative to last pattern match Multiply the bytes read from the packet by <value> and save that number into the variable.13 for a description and examples (2. 12. See section 2. They can be re-used in the same rule any number of times.2.5. 900.29 byte extract The byte extract keyword is another useful option for writing rules against length-encoded protocols.13 for quick reference). <name> \ [. It reads in some number of bytes from the packet payload and saves it to a variable. Let the DCE/RPC 2 preprocessor determine the byte order of the value to be converted. Here is a list of places where byte extract variables can be used: 162 . Its use is in extracting packet data for use. Skip forward or backwards (positive of negative value) by <value> number of bytes after the other jump options have been applied.2. Number of bytes into the payload to start processing Use an offset relative to last pattern match Multiply the number of calculated bytes by <value> and skip forward that number of bytes. relative. \ byte_jump:4. instead of using hard-coded values. relative. Format byte_extract:<bytes_to_extract>. \ msg:"statd format string buffer overflow". Other options which use byte extract variables A byte extract rule option detects nothing by itself. <offset>. \ content:"|00 00 00 01|". distance:4. This will be used to reference the variable in other rule options. <endian>]\ [. \ byte_test:4. <number_type>][. \ content:"bad stuff". str_offset. This keyword must have one argument which specifies the length to compare against. content:"PORT". the offset value. The syntax looks like. str_depth. This is the absolute offset from the beginning of the packet.31 asn1 The ASN. you would say “absolute offset 0”. oversize_length <value>][.established. 0.1 detection plugin decodes a packet or a portion of a packet. depth. Format asn1:[bitstring_overflow][. \ msg:"Bad Stuff detected within field". This is known to be an exploitable function in Microsoft. “oversize length 500”. pcre:"/ˆPORT/smi". the whole option evaluates as true. Option bitstring overflow double overflow oversize length <value> Description Detects invalid bitstring encodings that are known to be remotely exploitable. you would specify ’content:"foo". So if you wanted to start decoding and ASN. Example alert tcp $EXTERNAL_NET any -> $HOME_NET 21 (msg:"FTP PORT bounce attempt". For example. relative_offset 0’. absolute offset <value> relative offset <value> 163 .5. Multiple options can be used in an ’asn1’ option and the implied logic is boolean OR. Detects a double ASCII encoding that is larger than a standard buffer. Offset values may be positive or negative.30 ftpbounce The ftpbounce keyword detects FTP bounce attacks. double_overflow][.Rule Option content/uricontent byte test byte jump isdataat Arguments that Take Variables offset. This is the relative offset from the last content match or byte test/jump. within offset. depth:str_depth. \ byte_extract:1. alert tcp any any -> any any (byte_extract:1. sid:3441.1 sequence right after the content “foo”. So if any of the arguments evaluate as true. absolute offset has one argument. Compares ASN. value offset offset Examples This example uses two variables to: • Read the offset of a string from a byte at offset 0. offset:str_offset.1 type is greater than 500. • Use these values to constrain a pattern match to a smaller area. and looks for various malicious encodings. \ flow:to_server. asn1:bitstring_overflow. Offset may be positive or negative. absolute_offset <value>|relative_offset <value>].\ classtype:misc-attack. Format ftpbounce. the option and the argument are separated by a space or a comma. If an option has an argument.) 3. rev:1. nocase. 1. distance. This means that if an ASN. ftpbounce.) 3. the offset number.1 type lengths with the supplied argument. relative offset has one argument. • Read the depth of a string from a byte at offset 1. then this keyword is evaluated as true. but it is unknown at this time which services may be exploitable. The ASN. The preferred usage is to use a space between option and argument.1 options provide programmatic detection capabilities as well as some more dynamic type detection.5. if you wanted to decode snmp packets. 3. \ asn1:bitstring_overflow. cvs:invalid-entry.2.33 dce iface See the DCE/RPC 2 Preprocessor section 2.13 for a description and examples of using this rule option. CVE-2004-0396: ”Malformed Entry Modified and Unchanged flag insertion”.) 3.37 ssl state See the SSL/TLS Preprocessor section 2.2. SSH (usually port 22).11. e.35 dce stub data See the DCE/RPC 2 Preprocessor section 2. 3.36 ssl version See the SSL/TLS Preprocessor section 2. Format cvs:<option>.2. 164 .5.11 for a description and examples of using this rule option.2. \ asn1:oversize_length 10000.11 for a description and examples of using this rule option. Default CVS server ports are 2401 and 514 and are included in the default ports for stream reassembly.5.) 3. \ flow:to_server.5. ! △NOTE This plugin cannot do detection over encrypted sessions.15 and before. 3.established. 3.5.10: Payload detection rule option keywords Keyword content Description The content keyword allows the user to set rules that search for specific content in the packet payload and trigger response based on that data.) alert tcp any any -> any 80 (msg:"ASN1 Relative Foo". Option invalid-entry Description Looks for an invalid Entry string. 3.Examples alert udp any any -> any 161 (msg:"Oversize SNMP Length". Examples alert tcp any any -> any 2401 (msg:"CVS Invalid-entry".5.2. which is a way of causing a heap overflow (see CVE-2004-0396) and bad pointer derefenece in versions of CVS 1.32 cvs The CVS detection plugin aids in the detection of: Bugtraq-10384.38 Payload Detection Quick Reference Table 3.5. absolute_offset 0.13 for a description and examples of using this rule option.g.13 for a description and examples of using this rule option.34 dce opnum See the DCE/RPC 2 Preprocessor section 2. relative_offset 0.5. content:"foo". >. fragbits:M. =. This example checks for a time-to-live value that between 3 and 5. See the DCE/RPC 2 Preprocessor section 2.1 fragoffset The fragoffset keyword allows one to compare the IP fragment offset field against a decimal value. 165 .6.6. The byte jump keyword allows rules to read the length of a portion of data. The isdataat keyword verifies that the payload has data at a specified location. Example alert ip any any -> any any \ (msg:"First Fragment". ttl:<3. Format fragoffset:[!|<|>]<number>. See the DCE/RPC 2 Preprocessor section 2. The uricontent keyword in the Snort rule language searches the normalized request URI field. Format ttl:[<. The pcre keyword allows rules to be written using perl compatible regular expressions. you could use the fragbits keyword and look for the More fragments option in conjunction with a fragoffset of 0. fragoffset:0.13. The cvs keyword detects invalid entry strings. The offset keyword allows the rule writer to specify where to start searching for a pattern within a packet. This option keyword was intended for use in the detection of traceroute attempts. ignoring any decoding that was done by preprocessors. This keyword takes numbers from 0 to 255. then skip that far forward in the packet. >=]<number>.13. See the DCE/RPC 2 Preprocessor section 2. <=. The asn1 detection plugin decodes a packet or a portion of a packet.6 Non-Payload Detection Rule Options 3. To catch all the first fragments of an IP session.2 ttl The ttl keyword is used to check the IP time-to-live value. ttl:[<number>]-[<number>]. The depth keyword allows the rule writer to specify how far into a packet Snort should search for the specified pattern. and looks for various malicious encodings.13. The within keyword is a content modifier that makes sure that at most N bytes are between pattern matches using the content keyword. Example This example checks for a time-to-live value that is less than 3. 3. The distance keyword allows the rule writer to specify how far into a packet Snort should ignore before starting to search for the specified pattern relative to the end of the previous pattern match.2. The byte test keyword tests a byte field against a specific value (with operator).2.) 3.2. The ftpbounce keyword detects FTP bounce attacks. Some tools (exploits. ttl:5-.6. 166 . ttl:=5. ttl:=<5. ttl:5-3. Few other examples are as follows: ttl:<=5. for example. id:31337.3 tos The tos keyword is used to check the IP TOS field for a specific value. Format id:<number>. Format tos:[!]<number>. the value 31337 is very popular with some hackers. This example checks for a time-to-live value that between 5 and 255. ttl:-5. Example This example looks for the IP ID of 31337. ttl:>=5. Example This example looks for a tos value that is not 4 tos:!4. 3. 3.ttl:3-5.6.4 id The id keyword is used to check the IP ID field for a specific value. scanners and other odd programs) set this field specifically for various purposes. The following examples are NOT allowed by ttl keyword: ttl:=>5. This example checks for a time-to-live value that between 0 and 5. esec - IP Extended Security lsrr - Loose Source Routing lsrre - Loose Source Routing (For MS99-038 and CVE-1999-0909)|esec|lsrr|lsrre|ssrr|satid|any>; Example This example looks for the IP Option of Loose Source Routing. ipopts:lsrr; Warning Only a single ipopts keyword may be specified per rule.+; 167)12>]; Example This example checks if just the SYN and the FIN bits are set, ignoring reserved bit 1 and reserved bit 2. alert tcp any any -> any any (flags:SF,12;) 168)] [,(to_client|to_server|from_client|from_server)] [,(no_stream|only_stream)] [,(no_frag|only_frag)];. Reset all states on a given flow. 169 logged_in. 3. content:"LIST". Format window:[!]<number>.6. Examples alert tcp any 143 -> any any (msg:"IMAP login".6. ack:0.) 3. 3. window:55808. Example This example looks for a TCP sequence number of 0.6.logged_in.11 seq The seq keyword is used to check for a specific TCP sequence number. Format ack:<number>. flowbits:noalert. flowbits:set.) alert tcp any any -> any 143 (msg:"IMAP LIST".13 window The window keyword is used to check for a specific TCP window size. content:"OK LOGIN". flowbits:isset. Format seq:<number>. 170 . Example This example looks for a TCP window size of 55808. <GROUP_NAME>].Format flowbits:[set|unset|toggle|isset|isnotset|noalert|reset][. seq:0.12 ack The ack keyword is used to check for a specific TCP acknowledge number. Example This example looks for a TCP acknowledge number of 0. <STATE_NAME>][. 171 . Example This example looks for an ICMP ID of 0. This is useful because some covert channel programs use static ICMP fields when they communicate. This particular plugin was developed to detect the stacheldraht DDoS agent.16 icmp id The icmp id keyword is used to check for a specific ICMP ID value. Format icmp_id:<number>.3. This particular plugin was developed to detect the stacheldraht DDoS agent. Example This example looks for an ICMP code greater than 30. 3. Format itype:min<>max. Format icode:min<>max. Example This example looks for an ICMP type greater than 30. itype:[<|>]<number>.6.6. icode:>30. itype:>30. This is useful because some covert channel programs use static ICMP fields when they communicate.14 itype The itype keyword is used to check for a specific ICMP type value. icode:[<|>]<number>.17 icmp seq The icmp seq keyword is used to check for a specific ICMP sequence value.6. Format icmp_seq:<number>. 3.15 icode The icode keyword is used to check for a specific ICMP code value. icmp_id:0.6. 3. *. alert ip any any -> any any (ip_proto:igmp. [<version number>|*]. 3.) 3. Format sameip. Warning Because of the fast pattern matching engine. 3. the RPC keyword is slower than looking for the RPC values by using normal content matching.6. Example The following example looks for an RPC portmap GETPORT request. Format rpc:<application number>.6. see /etc/protocols.) 172 .Example This example looks for an ICMP Sequence of 0. version. [<procedure number>|*]>. and procedure numbers in SUNRPC CALL requests. 3. Example This example looks for IGMP traffic.). icmp_seq:0. Wildcards are valid for both version and procedure numbers by using ’*’. alert ip any any -> any any (sameip. Format ip_proto:[!|>|<] <name or number>.19 ip proto The ip proto keyword allows checks against the IP protocol header. For a list of protocols that may be specified by name.6. alert tcp any any -> any 111 (rpc:100000.20 sameip The sameip keyword allows rules to check if the source ip is the same as the destination IP.18 rpc The rpc keyword is used to check for a RPC application. Example This example looks for any traffic where the Source IP and the Destination IP is the same. ! △NOTE The stream size option is only available when the Stream5 preprocessor is enabled.3. as determined by the TCP sequence numbers.11: Non-payload detection rule option keywords Keyword fragoffset ttl tos Description The fragoffset keyword allows one to compare the IP fragment offset field against a decimal value.21 stream reassemble The stream reassemble keyword allows a rule to enable or disable TCP stream reassembly on matching traffic.greater than • = . to disable TCP reassembly for client traffic when we see a HTTP 200 Ok Response message. ! △NOTE The stream reassemble option is only available when the Stream5 preprocessor is enabled. Format stream_size:<server|client|both|either>.not equal • <= .greater than or equal Example For example. • The optional fastpath parameter causes Snort to ignore the rest of the connection. <number>. fastpath].) 3. use: alert tcp any any -> any any (stream_size:client.<.6. use: alert tcp any 80 -> any any (flow:to_client. The tos keyword is used to check the IP TOS field for a specific value. The ttl keyword is used to check the IP time-to-live value. to look for a session that is less that 6 bytes from the client side.) 3. Example For example.22 stream size The stream size keyword allows a rule to match traffic according to the number of bytes observed. <server|client|both>[.less than • > .6. noalert][. Format stream_reassemble:<enable|disable>. • The optional noalert parameter causes the rule to not generate an alert when it matches. content:"200 OK".noalert. established.equal • != . 173 .6. Where the operator is one of the following: • < .client.less than or equal • >= . <operator>. stream_reassemble:disable.23 Non-Payload Detection Quick Reference Table 3.6. log tcp any any <> any 12345 (metadata:service ftp-data. version.7.1 logto The logto keyword tells Snort to log all packets that trigger this rule to a special output log file. Format session:[printable|binary|all]. etc. The fragbits keyword is used to check if fragmentation and reserved bits are set in the IP header. The window keyword is used to check for a specific TCP window size. log tcp any any <> any 23 (session:printable. this example logs the payload bytes in binary form. The binary keyword prints out data in a binary format. The sameip keyword allows rules to check if the source ip is the same as the destination IP.2 session The session keyword is built to extract user data from TCP Sessions. HTTP CGI scans. The flags keyword is used to check if specific TCP flag bits are present. 3. The icmp id keyword is used to check for a specific ICMP ID value. The flow keyword allows rules to only apply to certain directions of the traffic flow. session:binary. The ip proto keyword allows checks against the IP protocol header. The ack keyword is used to check for a specific TCP acknowledge number. There are many cases where seeing what users are typing in telnet. Format logto:"filename". binary. ftp. The all keyword substitutes non-printable characters with their hexadecimal equivalents.) Given an FTP data session on port 12345. or even web sessions is very useful. or all. The flowbits keyword allows rules to track states during a transport protocol session. Example The following example logs all printable strings in a telnet packet. The icode keyword is used to check for a specific ICMP code value. rlogin. This is especially handy for combining data from things like NMAP activity. The printable keyword only prints out data that the user would normally see or be able to type.7 Post-Detection Rule Options 3. It should be noted that this option does not work when Snort is in binary logging mode. The ipopts keyword is used to check if a specific IP option is present.) 174 . 3. and procedure numbers in SUNRPC CALL requests.7. The icmp seq keyword is used to check for a specific ICMP sequence value. The seq keyword is used to check for a specific TCP sequence number. The dsize keyword is used to test the packet payload size. The itype keyword is used to check for a specific ICMP type value. The rpc keyword is used to check for a RPC application. There are three available argument keywords for the session rule option: printable. 1.Tag the host/session for <count> packets • seconds . The binary keyword does not log any protocol headers below the application layer. metric • packets . The session keyword is best suited for post-processing binary (pcap) log files.4 any -> 10.Tag packets containing the destination IP address of the packet that generated the initial event. described in Section 2.6.1. 3.Count is specified as a number of units. See 2. does not properly handle tagged alerts.600.0.4 react The react keyword enables an active response that includes sending a web page or other content to the client and then closing the connection. See 2. but it is the responsibility of the output plugin to properly handle these special alerts. React can be used in both passive and inline modes.seconds. a tagged packet limit will be used to limit the number of tagged packets regardless of whether the seconds or bytes count has been reached.tagged. You can disable this packet limit for a particular rule by adding a packets metric to your tag option and setting its count to 0 (This can be done on a global scale by setting the tagged packet limit option in snort. • dst .Tag packets containing the source IP address of the packet that generated the initial event.tagged. Currently.6.1 any \ (content:"TAGMYPACKETS".5 tag The tag keyword allow rules to log more than just the single packet that triggered the rule.only relevant if host type is used.3 for details.1.src. <count>.7. The default tagged packet limit value is 256 and can be modified by using a config option in your snort.seconds. • src .7.) alert tcp 10. tagged alerts will be sent to the same output plugins as the original alert.) 175 .packets. alert tcp any any <> 10. Tagged traffic is logged to allow analysis of response codes and post-attack traffic. Resp can be used in both passive or inline modes. flowbits:set. tag:host.Warnings Using the session keyword can slow Snort down considerably. so it should not be used in heavy load situations. 3. additional traffic involving the source and/or destination host is tagged. Format tag:<type>. tag:host. Subsequent tagged alerts will cause the limit to reset.1. direction]. 3. type • session .1.1 any (flowbits:isnotset.src.) Also note that if you have a tag option in a rule that uses a metric other than packets. the database output plugin.Log packets from the host that caused the tag to activate (uses [direction] modifier) count • <integer> .7. Once a rule is triggered.3 on how to use the tagged packet limit config option).1.600. <metric>[. Doing this will ensure that packets are tagged for the full amount of seconds or bytes and will not be cut off by the tagged packet limit.Tag the host/session for <count> bytes direction .4 for details. Note that neither subsequent alerts nor event filters will prevent a tagged packet from being logged.11. and Stream reassembly will cause duplicate data when the reassembled packets are logged. Units are specified in the <metric> field.1.11.Tag the host/session for <count> seconds • bytes .3 resp The resp keyword enables an active response that kills the offending session.conf file (see Section 2.conf to 0).Log packets in the session that set off the rule • host . (Note that the tagged packet limit was introduced to avoid DoS situations on high bandwidth sensors for tag rules with a high seconds or bytes counts. after evaluating all other rule options (regardless of the position of the filter within the rule source). 3. Format activated_by:1.7.1. 3. seconds <s>.1. nocase.Example This example logs the first 10 seconds or the tagged packet limit (whichever comes first) of any telnet session.1. flow:established. Format activates:1. rev:1. after the first 30 failed login attempts: drop tcp 10. offset:0.2. tag:session.100 during one sampling period of 60 seconds. It allows the rule writer to specify how many packets to leave the rule enabled for after it is activated.10.) 176 .9 replace The replace keyword is a feature available in inline mode which will cause Snort to replace the prior matching content with the given string.12.this rule will fire on every failed login attempt from 10. See Section 3. See Section 3.2.100 22 ( \ msg:"SSH Brute Force Attempt". Example .6 for more information. \ content:"SSH". At most one detection filter is permitted per rule. 3.7 activated by The activated by keyword allows the rule writer to dynamically enable a rule when a specific activate rule is triggered.2.100 any > 10. 3. Format activated_by:1. See Section 3. count:50.7. You can have multiple replacements within a rule. detection filter has the following format: detection_filter: \ track <by_src|by_dst>.1. \ sid:1000001.2. seconds 60. \ detection_filter:track by_src.) 3.7.to_server.2. one per content. Snort evaluates a detection filter as the last step of the detection phase.7.6 for more information. \ count <c>.seconds..7.8 count The count keyword must be used in combination with the activated by keyword. depth:4. replace:"<string>". count 30. alert tcp any any -> any 23 (flags:s.6 for more information. 10) within rules. The session keyword is built to extract user data from TCP Sessions. or event filters (2. track \ 177 .8 Rule Thresholds ! △NOTE Rule thresholds are deprecated and will not be supported in a future release. This keyword implements an ability for users to react to traffic that matches a Snort rule by closing connection and sending a notice. flow:to_server.txt access". For instance. threshold can be included as part of a rule.2) as standalone configurations instead. These should incorporate the threshold into the rule. Available in inline mode only. alert tcp $external_net any -> $http_servers $http_ports \ (msg:"web-misc robots. Some rules may only make sense with a threshold. This keyword allows the rule writer to dynamically enable a rule when a specific activate rule is triggered. Replace the prior matching content with the given string of the same length. It allows the rule writer to specify how many packets to leave the rule enabled for after it is activated. \ track <by_src|by_dst>. Track by source or destination IP address and if the rule otherwise matches more than the configured rate it will fire. or you can use standalone thresholds that reference the generator and SID they are applied to. This keyword must be used in combination with the activated by keyword. There is a logical difference. It makes sense that the threshold feature is an integral part of this rule. established.7. C must be nonzero.12: Post-detection rule option keywords Keyword logto session resp react tag activates activated by count replace detection filter Description The logto keyword tells Snort to log all packets that trigger this rule to a special output log file. a rule for detecting a too many login password attempts may require more than 5 attempts. reference:nessus. The resp keyword is used attempt to close sessions when an alert is triggered.10302. Format threshold: \ type <limit|threshold|both>. a detection filter would normally be used in conjunction with an event filter to reduce the number of logged events.11 Post-Detection Quick Reference Table 3. \ count <c>.Option track by src|by dst count c seconds s Description Rate is tracked either by source IP address or destination IP address. Use detection filters (3. This means count is maintained for each unique source IP address or each unique destination IP address. \ classtype:web-application-activity. This can be done using the ‘limit’ type of threshold. Examples This rule logs the first event of this SID every 60 seconds. Since potentially many events will be generated. The value must be nonzero. seconds <s>. 3. The tag keyword allow rules to log more than just the single packet that triggered the rule. The maximum number of rule matches in s seconds allowed before the detection filter limit to be exceeded. threshold:type limit.4. There is no functional difference between adding a threshold to a rule. Time period over which count is accrued. 3. \ uricontent:"/robots. This keyword allows the rule writer to specify a rule to add when a specific network event occurs.7. or using a standalone threshold applied to the same rule.txt". nocase. instead of shellcode that binds a shell. a multi-pattern matcher is used to select rules that have a chance at matching based on a single content. Selecting rules for evaluation via this ”fast” pattern matcher was found to increase performance.Option type limit|threshold|both track by src|by dst count c seconds s Description type limit alerts on the 1st m events during the time interval.9. Type threshold alerts every m times we see this event during the time interval. such as pcre and byte test. For rules with content.1 Content Matching Snort groups rules by protocol (ip. alert tcp $external_net any -> $http_servers $http_ports \ (msg:"web-misc robots. rate is tracked either by source IP address. \ uricontent:"/robots. then by ports (ip and icmp use slightly differnet logic).9 Writing Good Rules There are some general concepts to keep in mind when developing Snort rules to maximize efficiency and speed.3 Catch the Oddities of the Protocol in the Rule Many services typically send the commands in upper case letters. seconds 60 . Ports or anything else are not tracked. 3. tcp. count 10. \ uricontent:"/robots. then ignores any additional events during the time interval. threshold:type both. count 10 . sid:1000852. time period over which count is accrued. nocase.10302. potentially putting a drag on performance. or destination IP address.it’s safe to say there is generally more ”good” traffic than ”bad”. alert tcp $external_net any -> $http_servers $http_ports \ (msg:"web-misc robots. instead of a specific exploit. This means count is maintained for each unique source IP addresses. or for each unique destination IP addresses. established. track \ by_dst. try and have at least one content (or uricontent) rule option in your rule. If at all possible. threshold:type threshold.9. The longer and more unique a content is. reference:nessus. rev:1. c must be nonzero value. to send the username.10302. perform detection in the payload section of the packet. rev:1. the rule is less vulnerable to evasion when an attacker changes the exploit slightly. While some detection options.9.txt access". nocase. sid:1000852. look for a the vulnerable command with an argument that is too large. \ classtype:web-application-activity. Type both alerts once per time interval after seeing m occurrences of the event. flow:to_server. s must be nonzero value. reference:nessus. FTP is a good example. the client sends: user username_here A simple rule to look for FTP root login attempts could be: 178 .txt access". they are not used by the fast pattern matching engine. For example.txt". Rules without content are always evaluated (relative to the protocol and port group in which they reside).) This rule logs at most one event every 60 seconds if at least 10 events on this SID are fired. number of rule matching in s seconds that will cause event filter limit to be exceeded. In FTP.) 3. the less likely that rule and all of it’s rule options will be evaluated unnecessarily . 3. especially when applied to large rule groups like HTTP. udp. then by those with content and those without. established. \ track by_dst.txt". By writing rules for the vulnerability. icmp). \ classtype:web-application-activity. then ignores events for the rest of the time interval.2 Catch the Vulnerability. seconds 60. 3. flow:to_server. Not the Exploit Try to write rules that target the vulnerability. most unique string in the attack. that may not sound like a smart idea. and because of recursion. A packet of 1024 bytes of 0x13 would fail immediately. followed by root. then check the dsize again. 3. ignoring case. looking for root.) This rule would look for “a”. For example.) There are a few important things to note in this rule: • The rule has a flow option. within:1. By looking at this rule snippit. as the dsize check is the first option checked and dsize is a discrete check without recursion.4 Optimizing Rules The content matching portion of the detection engine has recursion to handle a few evasion cases. The following rule options are discrete and should generally be placed at the beginning of any rule: • dsize • flags • flow 179 .established. Without recursion. The optimized rule snipping would be: dsize:1. This option is added to allow the fast pattern matcher to select this rule for evaluation only if the content root is found in the payload. The way the recursion works now is if a pattern matches. content:"|13|". • The rule has a pcre option. which is the longest. content:"b". A good rule that looks for root login on ftp would be: alert tcp any any -> any 21 (flow:to_server. Reordering the rule options so that discrete checks (such as dsize) are moved to the beginning of the rule speed up Snort. a packet with 1024 bytes of 0x13 could cause 1023 too many pattern match attempts and 1023 too many dsize checks. repeating until 0x13 is not found in the payload again. verifying this is traffic going to the server on an established session. each of the following are accepted by most FTP servers: user root user root user root user root user<tab>root To handle all of the cases that the FTP server might handle. it is obvious the rule looks for a packet with a single byte of 0x13. immediately followed by “b”. the rule needs more smarts than a simple string match. Rules that are not properly written can cause Snort to waste time duplicating checks. followed at least one space character (which includes tab). and if any of the detection options after that pattern fail. because the first ”a” is not immediately followed by “b”. However. While recursion is important for detection.9. • The rule has a content option. even though it is obvious that the payload “aab” has “a” immediately followed by “b”. but it is needed. Why? The content 0x13 would be found in the first byte. the recursion implementation is not very smart. take the following rule: alert ip any any -> any any (content:"a". then look for the pattern again after where it was found the previous time. Repeat until the pattern is not found again or the opt functions all succeed. For example. the following rule options are not optimized: content:"|13|". a good rule will handle all of the odd things that the protocol might handle when accepting the user command. the payload “aab” would fail. looking for user. pcre:"/user\s+root/i". the content 0x13 would be found again starting after where the previous 0x13 was found. once it is found.alert tcp any any -> any any 21 (content:"user root".) While it may seem trivial to write a rule that looks for the username root. because of recursion. On first read. For example. \ content:"root". dsize:1. then the dsize option would fail. ... . • Strings are written as a uint32 specifying the length of the string.................... as RPC uses simple length based encoding for passing data.... @(:....../. RPC was the protocol that spawned the requirement for these two rule options. a random uint32............./bin/sh............system.............metasplo 180 . The string “bob” would show up as 0x00000003626f6200...... describe each of the fields. 89 00 00 00 00 00 00 00 09 00 00 01 00 00 00 00 9c 00 00 87 00 00 00 00 e2 00 02 88 0a 01 01 20 the request id... ........... . .. .... and figure out how to write a rule to catch this exploit. .... ................... In order to understand why byte test and byte jump are useful..@(:.. .......... .... unique to each request rpc type (call = 0............../ .. There are a few things to note with RPC: • Numbers are written as uint32s..• fragbits • icmp id • icmp seq • icode • id • ipopts • ip proto • itype • seq • session • tos • ttl • ack • window • resp • sameip 3.... . ....... the string...5 Testing Numerical Values The rule options byte test and byte jump were written to support writing rules for protocols that have length encoded data............... taking four bytes.. and then null bytes to pad the length of the string to end on a 4 byte boundary.................. ./. Let’s break this up.. The number 26 would show up as 0x0000001a.........9..e........metasplo it... aligning on the 4 byte boundary.40 28 3a 10 . content:"|00 00 00 00|". content:"|00 01 87 88|". depth:4. Then. offset:20. However. content:"|00 00 00 01|". content:"|00 00 00 01|". content:"|00 01 87 88|". Now that we have all the detection capabilities for our rule. we need to make sure that our packet is an RPC call. we need to make sure that our packet is a call to the procedure 1. Starting at the length of the hostname. content:"|00 00 00 00|". within:4.uid of requesting user (0) 00 00 00 00 .unix timestamp (0x40283a10 = 1076378128 = feb 10 01:55:28 2004 gmt) 00 00 00 0a . aka none) . and turn those 4 bytes into an integer and jump that many bytes forward. Then.length of verifier (0. This is where byte test is useful.verifier flavor (0 = auth\_null. 181 . byte_jump:4. content:"|00 00 00 00|". First. turn it into a.length of the client machine name (0x0a = 10) 4d 45 54 41 53 50 4c 4f 49 54 00 00 . offset:16. and jump that many bytes forward.align. 36 bytes from the beginning of the packet. then we want to look for the uid of 0. aka none) The rest of the packet is the request that gets passed to procedure 1 of sadmind. we know the vulnerability is that sadmind trusts the uid coming from the client. we need to make sure that our packet has auth unix credentials. we use: byte_jump:4. offset:12. offset:12. depth:4. offset:4. depth:4. let’s put them all together.36. content:"|00 00 00 01|". depth:4. the value we want to check. depth:4. offset:20. offset:16. the vulnerable procedure.metasploit 00 00 00 00 . To do that in a Snort rule. making sure to account for the padding that RPC requires on strings. As such.extra group ids (0) 00 00 00 00 00 00 00 00 . content:"|00 00 00 00|". we want to read 4 bytes.36. We don’t care about the hostname.gid of requesting user (0) 00 00 00 00 . depth:4. we need to make sure that our packet is a call to sadmind.align. depth:4. we are now at: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 which happens to be the exact location of the uid. within:4. depth:4. we have decoded enough of the request to write our rule. Then. sadmind runs any request where the client’s uid is 0 as root. offset:4. content:"|00 00 00 01|". but we want to skip over it and check a number value after the hostname. If we do that. In english. 200. instead of reading the length of the hostname and jumping that many bytes forward. offset:4. We end up with: content:"|00 00 00 00|". 00 00 01|". we would check the length of the hostname to make sure it is not too large. depth:8.align. If the sadmind service was vulnerable to a buffer overflow when reading the client’s hostname. offset:12.36. depth:4. In Snort. To do that. offset:16. and then make sure it is not too large (let’s say bigger than 200 bytes). turn it into a number.>. so we should combine those patterns. content:"|00 01 87 88|".36.The 3rd and fourth string match are right next to each other.200. depth:4. content:"|00 00 00 01 00 00 00 01|". depth:8. content:"|00 00 00 00|". byte_test:4. content:"|00 01 87 88|". we would read 4 bytes. offset:12. Our full rule would be: content:"|00 00 00 00|". we do: byte_test:4.>. offset:4. within:4. depth:4. depth:4. starting 36 bytes into the packet. offset:16. 182 . content:"|00 00 00 01 00 byte_jump:4.36. and rules as a dynamic plugin to snort. access to the StreamAPI. fatal errors. the dynamic API presents a means for loading dynamic libraries and allowing the module to utilize certain functions within the main snort code. The definition of each is defined in the following sections. and rules can now be developed as dynamically loadable module to snort. A shared library can implement all three types. char *libraryPath. } DynamicPluginMeta. This includes functions to register the preprocessor’s configuration parsing. int minor. 183 . errors. Beware: the definitions herein may be out of date. This data structure should be initialized when the preprocessor shared library is loaded. int major. Check the header file for the current definition. rules.h as: #define MAX_NAME_LEN 1024 #define TYPE_ENGINE 0x01 #define TYPE_DETECTION 0x02 #define TYPE_PREPROCESSOR 0x04 typedef struct _DynamicPluginMeta { int type. 4. int build. exit.h. 4. When enabled via the –enabledynamicplugin configure option.2 DynamicPreprocessorData The DynamicPreprocessorData structure defines the interface the preprocessor uses to interact with snort itself. check the appropriate header files for the current definitions. detection engines. but typically is limited to a single functionality such as a preprocessor.1. It includes function to log messages. or detection engine). and path to the shared library. and it provides access to the normalized http and alternate data buffers.1. and processing functions. detection capabilities. The remainder of this chapter will highlight the data structures and API functions used in developing preprocessors. and debugging info. It is defined in sf dynamic meta. restart.1 Data Structures A number of data structures are central to the API.Chapter 4 Dynamic Modules Preprocessors. 4. the version information. It is defined in sf dynamic preprocessor. It also includes information for setting alerts. char uniqueName[MAX_NAME_LEN]. handling Inline drops.1 DynamicPluginMeta The DynamicPluginMeta structure defines the type of dynamic module (preprocessor. int *debugMsgLine. It is defined in sf dynamic engine. errors. DebugMsgFunc debugMsg. #define RULE_MATCH 1 #define RULE_NOMATCH 0 typedef struct _Rule { IPInfo ip. LogMsgFunc fatalMsg. PCREExecFunc pcreExec. LogMsgFunc logMsg. CheckFlowbit flowbitCheck. fatal errors.1. 4. This includes functions for logging messages. RegisterRule ruleRegister. Check the header file for the current definitions. and debugging info as well as a means to register and check flowbits. DetectAsn1 asn1Detect. priority. #ifdef HAVE_WCHAR_H DebugWideMsgFunc debugWideMsg.5 Dynamic Rules A dynamic rule should use any of the following data structures. SetRuleData setRuleData. #endif char **debugMsgFile.h. The following structures are defined in sf snort plugin api. It also includes a location to store rule-stubs for dynamic rules that are loaded. PCREStudyFunc pcreStudy.h. /* NULL terminated array of RuleOption union */ ruleEvalFunc evalFunc. and it provides access to the normalized http and alternate data buffers.3 DynamicEngineData The DynamicEngineData structure defines the interface a detection engine uses to interact with snort itself.4 SFSnortPacket The SFSnortPacket structure mirrors the snort Packet structure and provides access to all of the data contained in a given packet. RuleOption **options. 4. char *dataDumpDirectory.4. 184 . That includes protocol. GetPreprocRuleOptFuncs getPreprocOptFuncs. revision. RegisterBit flowbitRegister.1. LogMsgFunc errMsg. generator and signature IDs. It also includes a list of rule options and an optional evaluation function. and a list of references).h as: typedef struct _DynamicEngineData { int version. RuleInformation info. u_int8_t *altBuffer. classification.1. } DynamicEngineData. UriInfo *uriBuffers[MAX_URIINFOS]. Rule The Rule structure defines the basic outline of a rule and contains the same set of information that is seen in a text rule. It and the data structures it incorporates are defined in sf snort packet. address and port information and rule information (classification. PCRECompileFunc pcreCompile. Additional data structures may be defined to reference other protocol fields. GetRuleData getRuleData. char *classification. /* } Rule. destination address and port. src address and port. char *refIdentifier. /* NULL terminated array of references */ RuleMetaData **meta. char noAlert. HTTP PORTS. RuleReference The RuleReference structure defines a single rule reference. u_int32_t revision. IPInfo The IPInfo structure defines the initial matching criteria for a rule and includes the protocol. HOME NET.any. and a list of references. /* 0 for non TCP/UDP */ char direction. revision. priority. } RuleReference. char * src_addr. char *message. char * src_port. /* Rule Initialized. used internally */ Hash table for dynamic data pointers */ The rule evaluation function is defined as typedef int (*ruleEvalFunc)(void *). used internally */ /* Flag with no alert. and direction. u_int32_t numOptions. void *ruleData. HTTP SERVERS.char initialized. used internally */ /* Rule option count. RuleReference **references. where the parameter is a pointer to the SFSnortPacket structure. /* String format of classification name */ u_int32_t priority. /* 0 for non TCP/UDP */ } IPInfo. including the system name and rereference identifier. /* NULL terminated array of references */ } RuleInformation. Some of the standard strings and variables are predefined . RuleInformation The RuleInformation structure defines the meta data for a rule and includes generator ID. typedef struct _RuleReference { char *systemName. char * dst_port. signature ID. classification. message text. u_int32_t sigID. typedef struct _IPInfo { u_int8_t protocol. /* non-zero is bi-directional */ char * dst_addr. #define #define #define #define #define #define #define ANY_NET HOME_NET EXTERNAL_NET ANY_PORT HTTP_SERVERS HTTP_PORTS SMTP_SERVERS "any" "$HOME_NET" "$EXTERNAL_NET" "any" "$HTTP_SERVERS" "$HTTP_PORTS" "$SMTP_SERVERS" 185 . etc. typedef struct _RuleInformation { u_int32_t genID. OPTION_TYPE_BYTE_TEST. relative. } ContentInfo. OPTION_TYPE_BYTE_EXTRACT. The most unique content. such as the compiled PCRE information. } option_u. depth and offset. if no ContentInfo structure in a given rules uses that flag. Additional flags include nocase. • OptionType: Content & Structure: ContentInfo The ContentInfo structure defines an option for a content search. #define CONTENT_NOCASE #define CONTENT_RELATIVE #define CONTENT_UNICODE2BYTE 0x01 0x02 0x04 186 . typedef enum DynamicOptionType { OPTION_TYPE_PREPROCESSOR. CursorInfo *cursor. OPTION_TYPE_SET_CURSOR. The option types and related structures are listed below. union { void *ptr. OPTION_TYPE_FLOWBIT. PCREInfo *pcre. and a designation that this content is to be used for snorts fast pattern evaluation. OPTION_TYPE_CURSOR. OPTION_TYPE_BYTE_JUMP. int32_t offset. OPTION_TYPE_MAX }. unicode. typedef struct _ContentInfo { u_int8_t *pattern. ContentInfo *content.RuleOption The RuleOption structure defines a single rule option as an option type and a reference to the data specific to that option. OPTION_TYPE_ASN1. the integer ID for a flowbit. The ”Not” flag is used to negate the results of evaluating that option. OPTION_TYPE_FLOWFLAGS. Boyer-Moore content information. should be marked for fast pattern evaluation. FlowFlags *flowFlags. OPTION_TYPE_HDR_CHECK. /* must include a CONTENT_BUF_X */ void *boyer_ptr. OPTION_TYPE_LOOP. } RuleOption. and flags (one of which must specify the buffer – raw. typedef struct _RuleOption { int optionType. URI or normalized – to search). Each option has a flags field that contains specific flags for that option as well as a ”Not” flag. u_int32_t flags. OPTION_TYPE_CONTENT. u_int32_t depth. the one with the longest content length will be used. ByteExtract *byteExtract. u_int8_t *patternByteForm. ByteData *byte. FlowBitsInfo *flowBit. etc. #define NOT_FLAG 0x10000000 Some options also contain information that is initialized at run time. that which distinguishes this rule as a possible match to a packet. In the dynamic detection engine provided with Snort. u_int32_t incrementLength. HdrOptCheck *hdrData. OPTION_TYPE_PCRE. u_int32_t patternByteFormLength. It includes the pattern. Asn1Context *asn1. LoopInfo *loop. PreprocessorOption *preprocOpt. It mirrors the ASN1 rule option and also includes a flags field. /* pcre. as defined in PCRE. which specify the direction (from server. It includes the name of the flowbit and the operation (set.h. unset. #define ASN1_ABS_OFFSET 1 187 . void *compiled_extra. u_int32_t flags. to server). } FlowBitsInfo. isset. • OptionType: Flow Flags & Structure: FlowFlags The FlowFlags structure defines a flow option. It includes the flags. and flags to specify the buffer. etc.. It includes the PCRE expression. .1 & Structure: Asn1Context The Asn1Context structure defines the information for an ASN1 option. established session. /* compile_flags. u_int32_t id. } FlowFlags. void *compiled_expr. toggle. u_int8_t operation. • OptionType: Flowbit & Structure: FlowBitsInfo The FlowBitsInfo structure defines a flowbits option. isnotset). u_int32_t flags.h provides flags: PCRE_CASELESS PCRE_MULTILINE PCRE_DOTALL PCRE_EXTENDED PCRE_ANCHORED PCRE_DOLLAR_ENDONLY PCRE_UNGREEDY */ typedef struct _PCREInfo { char *expr. • OptionType: ASN. pcre flags such as caseless. /* specify one of CONTENT_BUF_X */ } CursorInfo. as well as byte tests and byte jumps. • OptionType: Cursor Check & Structure: CursorInfo The CursorInfo structure defines an option for a cursor evaluation.¿. This can be used to verify there is sufficient data to continue evaluation. /* u_int32_t flags. /* u_int32_t op. • OptionType: Protocol Header & Structure: HdrOptCheck The HdrOptCheck structure defines an option to check a protocol header for a specific value. int print. ¡.=. unsigned int max_length. The cursor is the current position within the evaluation buffer.#define ASN1_REL_OFFSET 2 typedef struct _Asn1Context { int bs_overflow. int offset. It includes an offset and flags that specify the buffer. /* u_int32_t mask_value. } Asn1Context. multiplier. an offset. as related to content and PCRE searches. The flags must specify the buffer. and flags. a value. similar to the isdataat rule option. u_int32_t flags. u_int32_t flags.¿. a value. -. an operation (for ByteTest.etc) -. It includes the header field. It includes the number of bytes. int length value. typedef struct _CursorInfo { int32_t offset. a mask to ignore that part of the header field. the operation (¡.etc). int offset_type. Field to check */ Type of comparison */ Value to compare value against */ bits of value to ignore */ • OptionType: Byte Test & Structure: ByteData The ByteData structure defines the information for both ByteTest and ByteJump operations. int double_overflow. and flags.=. } HdrOptCheck. #define #define #define #define #define #define #define #define #define CHECK_EQ CHECK_NEQ CHECK_LT CHECK_GT CHECK_LTE CHECK_GTE CHECK_AND CHECK_XOR CHECK_ALL 0 1 2 3 4 5 6 7 8 188 . /* void *memoryLocation. /* } ByteExtract. /* char *refId. /* Holder */ int32_t staticInt. u_int32_t flags. 4. and a reference to the DynamicElement. It includes the number of bytes. /* Pointer to value of dynamic */ } data. multiplier. One of those options may be a ByteExtract.DynamicElement The LoopInfo structure defines the information for a set of options that are to be evaluated repeatedly. CursorInfo *cursorAdjust.static or reference */ char *refId. int32_t offset. } LoopInfo. the value is filled by a related ByteExtract option that is part of the loop. u_int8_t initialized. for checkValue. The loop option acts like a FOR loop and includes start. and increment values as well as the comparison operation for termination. end.#define CHECK_ATLEASTONE #define CHECK_NONE typedef struct _ByteData { u_int32_t bytes. struct _Rule *subRule. • OptionType: Set Cursor & Structure: CursorInfo See Cursor Check above. an offset. /* /* /* /* /* /* * /* /*. /* u_int32_t multiplier. u_int32_t op. or extracted value */ Offset from cursor */ Used for byte jump -.32bits is MORE than enough */ must include a CONTENT_BUF_X */ • OptionType: Byte Jump & Structure: ByteData See Byte Test above. */ The ByteExtract structure defines the information to use when extracting bytes for a DynamicElement used a in Loop evaltion. DynamicElement *increment. typedef struct _LoopInfo { DynamicElement . For a dynamic element. u_int32_t value. specifies * relative. } ByteData. u_int32_t op. for checkValue */ Value to compare value against. #define DYNAMIC_TYPE_INT_STATIC 1 #define DYNAMIC_TYPE_INT_REF 2 typedef struct _DynamicElement { char dynamicType. flags specifying the buffer.ByteExtract. /* type of this field . /* u_int32_t flags. } DynamicElement. u_int32_t flags. It includes whether the element is static (an integer) or dynamic (extracted from a buffer in the packet) and the value. u_int32_t multiplier. DynamicElement *end. a reference to a RuleInfo structure that defines the RuleOptions are to be evaluated through each iteration.2 Required Functions Each dynamic module must define a set of functions and data objects to work within this framework. 9 10 /* /* /* /* /* /* Number of bytes to extract */ Type of byte comparison. typedef struct _ByteExtract { u_int32_t bytes. /* int32_t offset. It includes a cursor adjust that happens through each iteration of the loop. /* reference ID (NULL if static) */ union { void *voidPtr. /* Value of static */ int32_t *dynamicInt. • OptionType: Loop & Structures: LoopInfo. 189 . ByteData *byteData. ByteData *byteData. With a text rule. CursorInfo *cursorInfo. • int InitializePreprocessor(DynamicPreprocessorData *) This function initializes the data structure for use by the preprocessor into a library global variable. • int InitializeEngineLib(DynamicEngineData *) This function initializes the data structure for use by the engine. u int8 t **cursor) This function evaluates a single content for a given packet. as delimited by Asn1Context and cursor.1 check for a given packet. etc). u int8 t **cursor) This function evaluates a single pcre for a given packet. Asn1Context *asn1. dpd and invokes the setup function. drop. ContentInfo* content. u int8 t *cursor) This function compares the value to the value stored in ByteData. New cursor position is returned in *cursor. 190 . u int32 t value. Each of the functions below returns RULE MATCH if the option matches based on the current criteria (cursor position. u int8 t **cursor) This function adjusts the cursor as delimited by CursorInfo. • int ruleMatch(void *p.2. as specified by FlowBitsInfo. u int8 t **cursor) This is a wrapper for extractValue() followed by setCursor(). The sample code provided with Snort predefines those functions and defines the following APIs to be used by a dynamic rules library. • int LibVersion(DynamicPluginMeta *) This function returns the metadata for the shared library. The metadata and setup function for the preprocessor should be defined sf preproc info.c. CursorInfo *cursorInfo. – int byteJump(void *p. checking for the existence of the expression as delimited by PCREInfo and cursor. Cursor position is updated and returned in *cursor. ByteExtract *byteExtract. the with option corresponds to depth. FlowFlags *flowflags) This function evaluates the flow for a given packet. • int DumpRules(char *. • int LibVersion(DynamicPluginMeta *) This function returns the metadata for the shared library. initialize it to setup content searches. – int byteTest(void *p. – int extractValue(void *p.Rule **) This is the function to iterate through each rule in the list and write a rule-stop to be used by snort to control the action of the rule (alert.2 Detection Engine Each dynamic detection engine library must define the following functions. It handles bounds checking for the specified buffer and returns RULE NOMATCH if the cursor is moved out of bounds. ByteData *byteData. as specified by ByteExtract and delimited by cursor. u int8 t *cursor) This function extracts the bytes from a given packet. This uses the individual functions outlined below for each of the rule options and handles repetitive content issues. – int checkCursor(void *p. and pcreMatch to adjust the cursor position after a successful match.4. – int contentMatch(void *p. – int setCursor(void *p.2. – int processFlowbits(void *p. u int8 t *cursor) This function evaluates an ASN. u int8 t *cursor) This function validates that the cursor is within bounds of the specified buffer. – int detectAsn1(void *p. FlowBitsInfo *flowbits) This function evaluates the flowbits for a given packet. Value extracted is stored in ByteExtract memoryLocation parameter. etc).1 Preprocessors Each dynamic preprocessor library must define the following functions. – int pcreMatch(void *p. log. – int checkValue(void *p. byteJump. • int RegisterRules(Rule **) This is the function to iterate through each rule in the list. u int8 t *cursor) This is a wrapper for extractValue() followed by checkValue(). and register flowbits. checking for the existence of that content as delimited by ContentInfo and cursor. 4.h. PCRE evalution data. It is also used by contentMatch. It will interact with flowbits used by text-based rules. PCREInfo *pcre. Rule *rule) This is the function to evaluate a rule if the rule does not have its own Rule Evaluation Function. These are defined in the file sf dynamic preproc lib. Cursor position is updated and returned in *cursor. and the distance option corresponds to offset. – int checkFlow(void *p. 4. • int EngineVersion(DynamicPluginMeta *) This function defines the version requirements for the corresponding detection engine library. u int8 t **cursor) This function iterates through the SubRule of LoopInfo. It should set up fast pattern-matcher content. etc. • int LibVersion(DynamicPluginMeta *) This function returns the metadata for the shared library. as delimited by LoopInfo and cursor.– int checkHdrOpt(void *p.h. – int loopEval(void *p. • Rule *rules[] A NULL terminated list of Rule structures that this library defines. PreprocessorOption *preprocOpt. This assumes the the files sf dynamic preproc lib. This preprocessor always alerts on a Packet if the TCP port matches the one configured. u int8 t **cursor) This function is used to handled repetitive contents to save off a cursor position temporarily to be reset at later point. u int8 t **cursor) This function evaluates the preprocessor defined option.3 Rules Each dynamic rules library must define the following functions. – void revertTempCursor(u int8 t **temp cursor. register flowbits. HdrOptCheck *optData) This function evaluates the given packet’s protocol headers. LoopInfo *loop. • int InitializeDetection() This function registers each rule in the rules library. u int8 t **cursor) This function is used to revert to a previously saved temporary cursor position.h are used.so. as spepcifed by PreprocessorOption. – void setTempCursor(u int8 t **temp cursor. This is the metadata for this preprocessor. Define the Setup function to register the initialization function.1 Preprocessor Example The following is an example of a simple preprocessor. Cursor position is updated and returned in *cursor.c into lib sfdynamic preprocessor example.c. If you decide to write you own rule evaluation function.c and sf dynamic preproc lib.3. Examples are defined in the file sfnort dynamic detection lib. The sample code provided with Snort predefines those functions and uses the following data within the dynamic rules library. Take extra care to handle this situation and search for the matched pattern again if subsequent rule options fail to match. #define #define #define #define MAJOR_VERSION 1 MINOR_VERSION 0 BUILD_VERSION 0 PREPROC_NAME "SF_Dynamic_Example_Preprocessor" ExampleSetup #define DYNAMIC_PREPROC_SETUP extern void ExampleSetup(). The metadata and setup function for the preprocessor should be defined in sfsnort dynamic detection lib.2. patterns that occur more than once may result in false negatives.c and is compiled together with sf dynamic preproc lib. The remainder of the code is defined in spp example.h. Cursor position is updated and returned in *cursor. as specified by HdrOptCheck. defined in sf preproc info. 4. 191 . ! △NOTE 4. – int preprocOptionEval(void *p.3 Examples This section provides a simple example of a dynamic preprocessor and a dynamic rule. This should be done for both content and PCRE options. • int DumpSkeletonRules() This functions writes out the rule-stubs for rules that are loaded. } /* Register the preprocessor function. arg = strtok(args.debugMsg(DEBUG_PLUGIN. char *argEnd. "Preprocessor: Example is initialized\n").#define GENERATOR_EXAMPLE 256 extern DynamicPreprocessorData _dpd. if (!arg) { _dpd.logMsg(" } else { _dpd. 192 . } Port: %d\n". } The function to process the packet and log an alert if the either port matches. void ExampleProcess(void *. if (port < 0 || port > 65535) { _dpd.fatalMsg("ExamplePreproc: Missing port\n").debugMsg(DEBUG_PLUGIN. void ExampleInit(unsigned char *args) { char *arg.addPreproc(ExampleProcess. "\t\n\r"). ExampleInit). portToCheck). if(!strcasecmp("port".fatalMsg("ExamplePreproc: Invalid port %d\n". ID 10000 */ _dpd. " \t\n\r"). unsigned long port. &argEnd. void ExampleSetup() { _dpd. 10).logMsg("Example dynamic preprocessor configuration\n"). u_int16_t portToCheck. if (!p->ip4_header || p->ip4_header->proto != IPPROTO_TCP || !p->tcp_header) { /* Not for me. Transport layer. void *).conf. _dpd. _dpd. arg)) { arg = strtok(NULL. DEBUG_WRAP(_dpd. #define SRC_PORT_MATCH 1 #define SRC_PORT_MATCH_STR "example_preprocessor: src port match" #define DST_PORT_MATCH 2 #define DST_PORT_MATCH_STR "example_preprocessor: dest port match" void ExampleProcess(void *pkt. } The initialization function to parse the keywords from snort. return */ return. DEBUG_WRAP(_dpd. "Preprocessor: Example is setup\n").registerPreproc("dynamic_example". void ExampleInit(unsigned char *). } portToCheck = port.).).fatalMsg("ExamplePreproc: Invalid option %s\n". 10000). port). void *context) { SFSnortPacket *p = (SFSnortPacket *)pkt. PRIORITY_TRANSPORT. arg). } port = strtoul(arg. } if (p->dst_port == portToCheck) { /* Destination port matched. and non-relative. 1.. It is implemented to work with the detection engine provided with snort. return. static FlowFlags sid109flow = { FLOW_ESTABLISHED|FLOW_TO_CLIENT }. classtype:misc-activity. SRC_PORT_MATCH. \ sid:109. NOTE: This content will be used for the fast pattern matcher since it is the longest content option for this rule and no contents have a flag of CONTENT FAST PATTERN. \ content:"NetBus". reference:arachnids. SRC_PORT_MATCH_STR. 3. 193 . } } 4.401. 1. 0.) This is the metadata for this rule library. no depth or offset. The snort rule in normal format: alert tcp $HOME_NET 12345:12346 -> $EXTERNAL_NET any \ (msg:"BACKDOOR netbus active". SID 109. static RuleOption sid109option1 = { OPTION_TYPE_FLOWFLAGS. 0). log alert */ _dpd. Search on the normalized buffer by default. content is ”NetBus”.established. • Flow option Define the FlowFlags structure and its corresponding RuleOption. 3.established. { &sid109flow } }. flow is from server. DST_PORT_MATCH. • Content Option Define the ContentInfo structure and its corresponding RuleOption.h. log alert */ _dpd.alertAdd(GENERATOR_EXAMPLE. Declaration of the data structures. DST_PORT_MATCH_STR. case sensitive. rev:5. flow:from_server. Per the text version. Per the text version. 0. take from the current rule set.2 Rules The following is an example of a simple rule.c. return.3.if (p->src_port == portToCheck) { /* Source port matched.alertAdd(GENERATOR_EXAMPLE. defined in detection lib meta. /* genid -. { &sid109content } }.static ContentInfo sid109content = { "NetBus". Rule sid109 = { /* protocol header. /* sigid */ 5. /* offset */ CONTENT_BUF_NORMALIZED. /* Holder. message.use 3 to distinguish a C rule */ 109. NULL }. NULL }. search for */ boyer/moore info */ byte representation of "NetBus" */ length of byte representation */ increment length */ The list of rule options. used internally */ 0. /* message */ sid109refs /* ptr to references */ }. &sid109option2. /* proto */ HOME_NET. option count. meta data (sid. The rule itself. /* Use internal eval func */ 0. with the protocol header. • Rule and Meta Data Define the references. /* classification */ 0. sid109options. /* destination port */ }. no alert. used internally for flowbits */ NULL /* Holder. /* depth */ 0. /* flags */ NULL. /* metadata */ { 3. RuleOption *sid109options[] = { &sid109option1. not yet initialized. /* pattern to 0. /* Holder. static RuleOption sid109option2 = { OPTION_TYPE_CONTENT. /* priority */ "BACKDOOR netbus active". etc). akin to => tcp any any -> any any */ { IPPROTO_TCP. /* ptr to rule options */ NULL. /* source port(s) */ 0. /* holder for 0 /* holder for }. used internally */ 0. static RuleReference *sid109refs[] = { &sid109ref_arachnids. /* holder for NULL. /* Type */ "401" /* value */ }. rule data. /* holder for 0. /* revision */ "misc-activity". /* destination IP */ ANY_PORT. /* source IP */ "12345:12346". classification. /* Direction */ EXTERNAL_NET. used internally */ 194 . /* Holder. static RuleReference sid109ref_arachnids = { "arachnids". Rule options are evaluated in the order specified. The InitializeDetection iterates through each Rule in the list and initializes the content. &sid637. 195 .• The List of rules defined by this rules library The NULL terminated list of rules. NULL }. extern Rule sid109. pcre. Rule *rules[] = { &sid109. extern Rule sid637. etc. flowbits. 5. 5. Similarly. Check out src/decode. traffic is acquired from the network link via libpcap. this chapter is here as a place holder. We are currently cleaning house on the available output options. there are a lot of packet flags available that can be used to mark a packet as “reassembled” or logged. End users don’t really need to be reading this section. 5. 5. 196 . Later.3 Output Plugins Generally. Each preprocessor checks to see if this packet is something it should look at. This is intended to help developers get a basic understanding of whats going on quickly. Packets are passed through a series of decoder routines that first fill out the packet structure for link level protocols then are further decoded for things like TCP and UDP ports. Features go into HEAD. new output plugins should go into the barnyard project rather than the Snort project. look at an existing output plugin and copy it to a new item and change a few things. If you are going to be helping out with Snort development. Packets are then sent through the registered set of preprocessors. It will someday contain references on how to create new detection plugins and preprocessors.1 Preprocessors For example. Bug fixes are what goes into STABLE.sourceforge.net mailing list. a TCP analysis preprocessor could simply return if the packet does not have a TCP header. We’ve had problems in the past of people submitting patches only to the stable branch (since they are likely writing this stuff for their own IDS purposes). Patches should done with the command diff -nu snort-orig snort-new.2 Detection Plugins Basically.2 Snort Data Flow First. we’ll document what these few things are.2. please use the HEAD branch of cvs. Each of the keyword options is a plugin.2. Packets are then sent through the detection engine. The detection engine checks each packet against the various options listed in the Snort config files. It can do this by checking: if (p->tcph==null) return.1 Submitting Patches Patches to Snort should be sent to the snort-devel@lists.Chapter 5 Snort Development Currently. 5.h for the list of pkt * constants. This allows this to be easily extensible.2. 5 197 . net/dedicated/cidr.securify.org/snortdb [6] [5] [3] 198 .com/mag/phrack/phrack49/p49-06 [2] [1] [4]. This action might not be possible to undo. Are you sure you want to continue? We've moved you to where you read on your other device. Get the full title to continue reading from where you left off, or restart the preview.
https://www.scribd.com/doc/64055996/Snort-Manual
CC-MAIN-2017-04
refinedweb
58,781
60.72
Sept. 2015 for i in (1, 2, 3, 4, 5): print("All work and no play makes Jack a dull boy") Modify it to print the line 100 times (You want to do a loop, check python’s documentation) One possible solution, using a “while loop”: n = 1 while n <= 100: print("All work and no play makes Jack a dull boy") n = n + 1 Another, using a “for loop” and the function range: for _ in range(100): print("All work and no play makes Jack a dull boy") Modify the program to randomly select a name in the list (John, Jack, Paul, Tim) at each line. (Hint: import the module “random”) import random NAMES = ('John', 'Jack', 'Paul', 'Tim') for _ in range(100): name = random.choice(NAMES) print("All work and no play makes " + name + " a dull boy") def mysterious(n): """ ???? """ sum = 0 for i in range(1, n+1): sum = sum + i return sum It computes the sum of all integers between 1 and n. Remark: Freidriech Gauss would probably have written: def sum2(n): """ returns the sum of integers between 1 and n """ return n * (n + 1) / 2 There are 10 kinds of people: those who count in binary and the others. Computers represent everything as series of 0 and 1, also known as bits (for “binary digits”). Just like a number can be written in base 10, it can be written in base 2: E.g. 12 : 10 + 2 = 8 + 4 = 2**3 + 2**1 : 1010 33 : 30 + 3 = 32 + 1 = 2**5 + 1 : 100001 1 : 1 2 : 10 3 : 11 4 : 100 5 : 101 6 : 110 7 : 111 ... To learn more about how integer numbers are reprsented in binary format, you can check out Answer: 5, 8, 11, 255 def todec(s): """ convert a string of 0 and 1 representing a binary number into an integer """ n = 0 for i in s: n = n * 2 + int(i) return n for i in ['101', '1000', '1011', '11111111']: print(todec(i)) <<<<<<< HEAD:06_Representation_of_numbers_images_text/representing_numbers_images_text.md ======= ``` #endif >>>>>>> 56025cfc85e9a40663e452f055225e216a22239a:06a_Representation_of_numbers_images_text/representing_numbers_images_text.md If you have an idea how to program it, please proceed. If not, we propose that you follow the following steps: num = 143 d3 = int(num/1000) % 10 # thousands d2 = int(num/100) % 10 # hundreds d1 = int(num/10) % 10 # dec d0 = num % 10 print(str(d3) + str(d2) + str(d1) + str num = 17 b0 = num % 2 b1 = int(num/2) % 2 b2 = int(num/4) % 2 b3 = int(num/8) % 2 b4 = int(num/16) % 2 b5 = int(num/32) % 2 b6 = int(num/64) % 2 b7 = int(num/128) % 2 b8 = int(num/256) % 2 print(str(b8) + str(b7) + str(b6) + str(b5) + str(b4) + str(b3) + str(b2) + str(b1) + str def tobin(num): b8 = int(num/256) % 2 b7 = int(num/128) % 2 b6 = int(num/64) % 2 b5 = int(num/32) % 2 b4 = int(num/16) % 2 b3 = int(num/8) % 2 b2 = int(num/4) % 2 b1 = int(num/2) % 2 b0 = num % 2 return (str(b8) + str(b7) + str(b6) + str(b5) + str(b4) + str(b3) + str(b2) + str(b1) + str(b0)) for n in range(256): print(n, tobin(n)) ``` def binary(n): if n==0: return "0" s = "" while n > 0: b = str(n % 2) s = b + s n = n / 2 return s def binary(num): if num == 0: return "0" if num == 1: return "1" return(binary(int(num /2)) + binary(num % 2)) print(binary(1234)) Answer: It is a recursive function which calls itself. See Remark: measures of memory size Exercice (advanced): Write a function that return the hexadecimal representation (base 16) of a number. To go further: If you want to know how negative integer numbers are represented, see To understand how real numbers are encoded, read What Every Programmer Should Know About Floating-Point Arithmetic and A text file is nothing but a sequences of characters (a word document is not a text file). For a long time, characters were encoded using ASCII code. ascii table For example, if you name is ‘ZOE’, you would type: print(chr(90)+chr(79)+chr(69)) 56025cfc85e9a40663e452f055225e216a22239a:06a_Representation_of_numbers_images_text/representing_numbers_images_text.md Remark: ASCII codes use one byte per characters. This is fine for English, but cannot cover all the caracters of all alphabets. It cannot even encode french accented letters. Unicode was invented that associate a unique 2 bytes number to each character of any human script. It is possible to write text files using these number, but more economic to encode the most common letters with one byte, and keep the compatibility with ASCII (UTF-8). Download Alice in Wonderland f = file('alice.txt') o = f.read() print(o) lines = o.split("\\n") print(lines) . . . f = file('alice.txt') o = f.read() print(o) lines = o.split("\n") nlines = len(lines) nw = 0 for l in lines: nw += len(l.split(" ")) print(nlines) print(nw) def spot_nsa(filename): f = file(filename) o = f.read() lines = o.split("\n") found = False for l in lines: if "NSA" in l.split(" "): found = True break return found Images can be stored either: Here we are just going to manipulate bitmaps. <<<<<<< HEAD:06_Representation_of_numbers_images_text/representing_numbers_images_text.md ## Black and white bitmaps ======= ### Black and white bitmaps >>>>>>> 56025cfc85e9a40663e452f055225e216a22239a:06a_Representation_of_numbers_images_text/representing_numbers_images_text.md Each dot (pixel) is either ‘0’ (black) or ‘1’ (white). Answer: 1024*768/8/1024=96 KB import numpy as np import matplotlib.pyplot as plt a = np]]) plt.imshow(a, cmap=plt.cm.gray, interpolation='nearest') plt.show() Numpy’s arrays are a new type of object. There are similar to lists, but optimised for mathematical computations. Notably, they can be multidimensional (i.e. you can use a[i,j] notation). You can learn more about arrays in the documents and. a = np.zeros((200,200)) for i in range(200): a[i, i] = 1 plt.imshow(a, cmap=plt.cm.gray, interpolation='nearest') plt.show() a[0:200:2,] = 1 plt.imshow(a, cmap=plt.cm.gray, interpolation='nearest') plt.show() Each dot is now associated to an integer value, e.g. ranging from 0 to 255 for 8-bits codes, coding for a grey level (smaller=darker). Each dot needs one byte. How large is the file for a 1024x768 image pixels with 256 grey levels? The following code displays an image: import scipy.misc l = scipy.misc.lena() plt.imshow(l, cmap=plt.cm.gray) plt.show() This code runs a low pass (averaging) filter on it: import scipy.ndimage bl = scipy.ndimage.gaussian_filter(l, 3) plt.imshow(bl, cmap=plt.cm.gray) plt.show() Edge detector. It is easy to implement an edge detector with a neural network. See. Using the ndimage.convolve function, apply the following filters to the image and diplay the results. kernel1 = np.array([[-1, -1, -1], [-1, 8, -1], [-1, -1, -1]]) kernel2 = np.array([[-1, -1, -1, -1, -1], [-1, 1, 2, 1, -1], [-1, 2, 4, 2, -1], [-1, 1, 2, 1, -1], [-1, -1, -1, -1, -1]]) More manipulations are available at. Each dot is now associated to three bytes, representing the Red, Gree and Blue intensities (see). How large is the file for a 1024x768 RGB image? Exercice: What are the RGB triplets for BLACK, WHITE, RED, YELLOW?
http://www.pallier.org/lectures/AIP2015/06_Representation_of_numbers_images_text/representing_numbers_images_text_new-slides.html
CC-MAIN-2017-51
refinedweb
1,210
63.8
I am currently trying to take a PCL Monogame Content Importer to handle loading my Json Serialized game objects but what builds fine in code fails in the "build" of the monogame content pipeline tool with the following error - Importer 'AnimationEditorImporter' had unexpected failure!System.NotImplementedException: This functionality is not implemented in the portable version of this assembly.You should reference the PCLExt.FileStorage NuGet package from your main application project in order to reference the platform-specific implementation. at PCLExt.FileStorage.Files.FileFromPath.GetFileFromPath(String path) at PCLExt.FileStorage.Files.FileFromPath.ctor(String path) ..... I have tried to add a reference to the PCLExt.FileStorage library I am using the "read" in my JSON file in the Monogame Pipeline Tool so I can use Newtonsoft.Json to Deserialize it back into an object when loading but it does not seem to do anything for me. What am I missing here or is there library or way to read files in a PCL library that are known to work with the Monogame content pipeline? Here is my very basic Content Importer's Code. [ContentImporter(".json", DisplayName = "Json Importer", DefaultProcessor = "")] public class AnimationEditorImporter : ContentImporter { public override Actor Import(string filename, ContentImporterContext context) { context.Logger.LogMessage("Importing Actor file: {0}", filename); BaseFile file = new FileFromPath(filename); using (var reader = new StreamReader(file.Open(FileAccess.Read))) return JsonConvert.DeserializeObject<Actor>(reader.ReadToEnd()); } } Basically as soon as file.Open is called the build freaks out saying it is not implemented in the portable version. Thanks I seem to have gotten around this issue. I referenced in the "Game Project" the NuGet package for this and it seems to now get past it complaining now about FileNotFound so I guess that is the answer. Not only do you have to reference in the Monogame Pipeline tool the assembly's but also in the Game Project as well. Has anyone seem to ran into issues with the pipeline tool not able to import Newtonsoft.Json library's? I cannot get this thing to find the DLL and it just errors with the following not found exception --System.Exception: Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, etc. Odd thing is I have no idea where it is trying to find that version as it is NOT the version that is linked in my "Monogame Content Importer Library" or even the "Game'' as those are all referencing v11.0.2 and is also the version I am linking in the Pipeline tool as well. I am linking these with absolute paths also if that is somehow an issue (which I dont see how they would have wrote it to not allow that..) Any help would be greatly appreciated.
http://community.monogame.net/t/pcl-content-importer-building-errors/10850/3
CC-MAIN-2018-34
refinedweb
458
55.34
okY so i got the errors down to 5.. here the new code so far... i forgot to give a option for the user to enter grade.. import java.util.Scanner; public class Q7_A_112532 { public static void main(System[] args){ Scanner input = new Scanner(System.in); int num = 0; int excellentstudent; excellentstudent = 0; double percentage = 0; int grade; System.out.print("enter the total number of students: "); num = input.nextInt(); int i; int studentarray; studentarray = new.int[num]; {for (i = 0; i < studentarray.length, i++ )}; sum = sum + arr[num]; System.out.print("Enter the grade of the student: "); grade = input.nextInt(); if (grade >= 90 ) gradecount ++; percentage = count * 100 / num; System.out.printf("The percentage f excellent student is : %.1f", + percentage); } } um i thought u would need to calculate the percentage of excellent students... thats why... u think i should remove that part? But you aren't using it anywhere. But I wouldn't worry about that at the moment, the first thing is to get your code compiling. Posting code? Use code tags like this: [code]...Your code here...[/code] Please use code tags when posting code. Format your code properly so the curly braces and indents are all consistently aligned, this will help highlight at least one problem. If I have to keep asking you to post error message etc this will take all night and I don't have all night. If there are 5 errors, post the messages. okay i got all the errors i could fixed... but still have four left!:26: error: illegal start of expression {for (i = 0; i < studentarray.length; i++ )}; C:\Users\Al Doctor\Documents\NetBeansProjects\HafsaShahab_112532\src\Q7_A_112532.java:42: error: reached end of file while parsing } 4 errors i am so sorry for bothering you.... but at the current moment u are the only help i have! i am so sorry for bothering you.. Don't worry, I'm just concerned we don't have enough time. The first two errors I have already explained in an earlier post. The 3rd error is because the for statement shouldn't be wrapped in curly braces The 4th is because you probably don't have the same number of opening and closing curly braces hence my earlier comment about formatting your code properly. Last edited by keang; December 18th, 2012 at 03:32 PM. i think the atempt of fixing the last four errors i have messed it all up all over...i bet u might be thinking i am like a crazy person or something.... but i think its slowly getting over m,y head.... now i think i am screwed it big time... coz in the middle i was working on another program... which was fine... but now donno what to do! am, trying to get back to where it was.. okay wait i think i got everything back.. lemme work on ur suggestion and i will get back to you Fixing one error can often make more errors appear, it doesn't necessarily mean you done something wrong. yeah never thought of that..am gonna keep that in mind... okay so am down to 3 errors.. okay so i removed the curly brace from one of em... but there is a new error in it..:48: error: class, interface, or enum expected } 3 errors okay so got ride of the last error... but the other two are still pending... can re-explain what i have to do to fix it. Without seeing the current code it's hard to say exactly but you certainly shouldn't have a '.' in 'new.int' and you probably haven't declared studentarray import java.util.Scanner; public class Q5_112532 { public static void main(String[] args){ Scanner input = new Scanner(System.in); int integer; System.out.print("Enter an integer less then 2147483648: "); integer = input.nextInt(); int sum = 0; while (integer != 0){ sum += integer % 10; integer /= 10; } System.out.print("the sum of digits of integers is "); if (sum % 2 == 0){ System.out.println("even!"); } else { System.out.println("odd!"); } } } SO THIS WHAT I HAVE GOTTEN AFTER ALL THAT!! WOOPS DORRY WRONG PROGRAM!! import java.util.Scanner; public class Q7_A_112532 { public static void main(String[] args) { Scanner input = new Scanner(System.in); int num = 0; double percentage = 0; int grade; System.out.print("Enter the number of students"); num = input.nextInt(); int sum; int studentarray; studentarray = new.int[num]; for (num = o; num < studentarray.length; num ++); sum = sum + arr[num]; System.out.print("enter the grade of the student: "); grade = input.nextInt(); if ( grade >= 90) gradecount ++; percentage = gradecount * 100 / num; System.out.printf("The percentage of excelent students: %.1f", +percentage); } } What about error messages and you still have a '.' in 'new.int' Forum Rules
http://forums.codeguru.com/showthread.php?531231-i-need-help-writing-a-program-using-array-ASAP!&p=2096929
CC-MAIN-2014-10
refinedweb
790
70.09
Interfacing LCD with CloudX Board Contents To have a good relationship between human world and machine world, display units plays a vital part. Displays allows us to know what’s happening in a device like the voltage, temperature, present status of the device and even device fault detection etc. LCD’s have a very wide application in embedded systems and it is more preferred than seven segment displays. Alphanumeric LCDs are most commonly used in embedded projects since it is commonly available and easy to use. In this tutorial, we will use the most commonly used 16×2 alphanumeric display. It has 16 columns and 2 rows, other sizes are also available like 8×1, 16×1, 16×4, 20×4, 32×2, 40×2, 40×4 etc. Component Required - CloudX Microcontroller board (SoftCard and Controller) - 16×2 LCD Display - 1KΩ resistor - Breadboard - Male-Male jumper wires CloudX LCD Library CloudX LCD library provides all the necessary routines to drive a LCD having HD44780 compliant controllers. LCD Setting Prototype : void LCD_setting(char RS, char EN, char D4, char D5, char D6, char D7); Initializes the LCD based on the provided connections. LCD Cmd Prototype : LCD_cmd(unsigned char command); Sends the specified command to the LCD display. This function requires the LCD to be initialized with LCD_setting function. It accepts below commands. LCD Write Prototype : LCD_write(unsigned char row, unsigned char col, unsigned char chr); Prints a character in the LCD on the specified position. LCD WriteCP Prototype : LCD_writeCP(unsigned char chr); Prints a character in the LCD on the current cursor position. LCD WriteText Prototype : LCD_writeText(unsigned char row, unsigned char col, char *s); Prints a string on the LCD starting from the specified position. LCD WriteTextCP Prototype : LCD_writeTextCP(unsigned char *s); Prints a string on the LCD starting from the current position. Custom Character Prototype : void customCharacter(unsigned char row, unsigned char column, unsigned char addressCGRAM); This function is used to print custom character on the specified position. Circuit Diagram Connections Program #include <CloudX\M633.h #include <CloudX\Lcd.h> setup(){ //setup here LCD_setting(1,2,3,4,5,6); //RS, EN, D4, D5, D6, D7 LCD_cmd(clear); //Clear the display loop(){ //Program here LCD_writeText(1,1,"Hello, am CloudX"); delay(1000); } } Description The code above shows how to print a message in the LCD. Always ensure that M633.h included first before any other library, then we included the LCD library since that’s what we are working with. Under the setup(), we configured the LCD pins based on our hardware design using LCD_setting(1,2,3,4,5,6). I will advise you to go through the CloudX documentation file to learn more about any library before you are using. Then we cleared the screen using LCD_cmd(clear), it will clear any junk data on the display. Then write text on the screen using LCD_writeText(1,1,”Hello, am CloudX”) . Experiment
https://electrosome.com/interfacing-lcd-cloudx-board/
CC-MAIN-2022-40
refinedweb
484
62.17
Php support and added a few new features, including coverage reports with PCOV and PHPDBG, customizable syntax for Twig Support, and more. Download PhpStorm 2020.1 EAP 5 facts about Early Access Programs that you should know: - Important! PhpStorm EAP builds are not fully tested and may be unstable. - You can install an EAP build side by side with a stable PhpStorm version to try out the latest features. - We will publish a fresh build for the upcoming version of PhpStorm every week. - EAP builds provide access to the newest features currently being developed. - EAP builds are free to use but expire within 30 days of the build date. Composer support improvements It’s hard to imagine a PHP project without a composer.json file in it. Yet only 20% percent of PhpStorm users who have composer.json files in their projects have installed the PHP composer.json support plugin. We reached out to the author of the plugin, Piotr Śliwa, and agreed that the PhpStorm team will take it over and rebuild it from scratch to bring out of the box support for composer.json to all users. Thanks to Piotr for the great job building this from the ground up for the community! So let’s take a look at what’s in store for composer.json in the PhpStorm 2020.1 release. In short, the 2020.1 release will bring you a number of convenient completion features, resolving paths and references, some inspections, and other useful time-saving features. Create new composer.json action When you start a new project, you can create a composer.json file in the IDE by right-clicking in the project tree and selecting New -> composer.json File. Additionally, you can modify the template for new composer.json files under Preferences/Settings | Editor | File and Code Templates in the Files section. Completion for license and minimum stability version Now you can just start typing the name of a license type or package version, or press Cmd(Ctrl)+Space, and choose the license you need from the suggestion list. Completion for PHP and extensions You can specify the required PHP version and a list of extensions to run the app. PhpStorm will suggest choosing from the list of available versions. Managing dependencies We are thinking about deprecating the manage dependencies dialog because working with the packages from inside the composer.json file is often far easier. For example, if you need to add a new package, you can start typing its name in the file, and just like with PHP and extensions, it will be autocompleted for you. All the available versions of the specific package will be listed, too. Additionally, the info popup will show details about the package, including the number downloads and stars it has. All the information is taken from packagist.org and cached. Updating and installing packages PhpStorm will detect and highlight if there’s a dependency that is specified in composer.json but that has not yet been installed. You can easily install a missing dependency from inside the editor just by hitting Alt+Enter! This fix allows you to update all dependencies or just a specific one. Navigation to files and folders You can use Cmd(Ctrl)+Click on a package and PhpStorm will highlight the folder of that package under the vendor directory in Project Tree. The same Cmd(Ctrl)+Click (or Cmd(Ctrl)+B) trick works to open any link in composer.json in a new browser. And it works for files, as well. Completion in Autoload Sections If you need to add an entry under either the “autoload” or “autoload-dev” section, you’ll now find it a bit quicker, as both namespaces and folder paths will be autocompleted based on the classes and folder structure you have. Cmd(Ctrl)+Click (or Cmd(Ctrl)+B) also works on paths, taking you to that target folder in the Project Tree. Exciting Additions for Scripts The “scripts” section contains commands for the package, such as “test”, “deploy”, “cache:clear”, etc. It’s awesome when package developers specify commands via the unified “scripts” interface. That’s because any package user can then execute composer run --list or just take a look at composer.json and instantly know what commands are available and how to run them without diving deep into the documentation or code. In Composer, a command in the scripts section can be either a PHP callback (defined as a static method) or any command-line executable command. PhpStorm 2020.1 will include completion and navigation for classes and static method names. It will also include completion for binaries, available under the “vendor/bin” directory. Running scripts Each entry in the scripts section has a play icon in the gutter that you can press to instantly run it. This will also create a run сonfiguration which allows you to run the command using the shortcut Ctrl+R: Quality Tools Setup If there is a FriendsOfPHP/PHP-CS-Fixer in your dev-dependencies, PhpStorm will now check whether the corresponding inspection is enabled and whether the ruleset has been adjusted. You can use Alt+Enter as a quick fix if the lines are highlighted: Code Coverage with PCOV and PHPDBG In PHP, probably the first tool that comes to mind (right after PHPUnit) when you think about code coverage is Xdebug. This is not the only option, however. And if you only need code coverage without the debugging capabilities, you may want to try krakjoe/pcov – a lightweight extension for generating coverage reports. To get a coverage report, make sure you have the extension installed with your PHP interpreter (either remote or local). Then create a Run configuration for tests. In the Run configurations settings, there is a dropdown to choose a preferred coverage driver: After selecting the preferred driver, press the Run with Coverage button in the main toolbar (or use Shift-Shift to find the action) and observe see the coverage results: Another tool for generating coverage reports is PHPDBG. It uses a less robust detection of executable code and sometimes generates reports with known defects, unfortunately. On the other hand, however, it comes bundled with PHP 5.6+, and you don’t need any additional extensions to install it. In PhpStorm 2020.1 you can use PHPDBG as a code coverage driver, as well. You can find out more about the differences between the code coverage reporting of Xdebug, PCOV, and phpdbg in this GitHub repository. Customize Lexer Syntax for Twig Sometimes it makes sense to change default tags for Twig templates, like, for example, when you are using it with Angular because it has the same syntax. In PhpStorm 2020.1, syntax for Twig templates can be configured under Preferences/Settings | Languages & Frameworks | PHP | Twig. Other There’s also a host of general changes that are available for all JetBrains IDEs, thanks to the IntelliJ Platform team: - The brand-new JetBrains Mono font (Settings/Preferences | Editor | Font). - The IDEs now use the reworked Interactively Rebase from Here dialog, which allows you to edit, combine, and remove your previous commits. - The light theme is now unified for all operating systems and goes by the name IntelliJ Light. If you’d like to go back to the old theme, you can switch under Preferences/Settings | Appearance & Behavior | Appearance | Theme. - The Quick documentation popup now appears on mouseover by default. You can disable this option in Settings/Preferences | Editor | General. The release brings a lot more, and we will describe other notable changes in subsequent posts, so follow our updates on Twitter and Facebook! The full list of changes, including bug-fixes and improvements, is available in the release notes. Please report any problems you find to our issue tracker, or by commenting on this post. Your feedback is much appreciated, and the most active EAPers will get special limited-edition gifts from us! That’s right, the PhpStorm elephpant is finally coming! Your JetBrains PhpStorm team The Drive to Develop
https://blog.jetbrains.com/phpstorm/2020/01/phpstorm-2020-1-early-access-program-is-now-open/
CC-MAIN-2021-17
refinedweb
1,336
55.54
Hi,i have this code that i need to turn in for my homework. I based it off some things i saw on the internet. The point of the homework is that i need to have 2 or more structures and use some functions. It would mean a lot if someone could help me fix it,im very new at programing and cant quite wrap my head around some things. Heres the code. #include <iostream> using namespace std; struct Product { char name[50]; int amount; float weight; }; struct Market { char nameofmarket[100]; }; Market chooseMarket(Market); Product getData(Product); void displayData(Product, Market); int main() { Product p; Market m; m = chooseMarket(m); main. p = getData(p); displayData(p, m); cout << "Totali: " << p.weight * 5 << " $" << endl; return 0; } Market chooseMarket(Market m) { cout << "Enter the name of the Market you want to visit: "; cin.getline(m.nameofmarket, 100); return m; } Product getData(Product p) { cout << "Enter name of the fruit/vegetable: "; cin.get(p.name, 50); cout << "Enter amount: "; cin >> p.amount; cout << "Enter weight(in kg): "; cin >> p.weight; return p; } void displayData(Product p, Market m) { cout << "\nDisplaying Information." << endl; cout << "\n" << m.nameofmarket << " Market" << endl; cout << "Product Name: " << p.name << endl; cout << "Amount: " << p.amount << endl; cout << "Weight: " << p.weight << endl; }
https://www.daniweb.com/programming/threads/522127/error-c4700-uninitialized-local-variable-c
CC-MAIN-2022-21
refinedweb
212
76.72
Created on 2002-11-05 17:56 by gvanrossum, last changed 2012-07-29 19:01 by mstefanro. This issue is now closed. The __name__ attribute of a nested class should be set to 'outer.inner', both for classic and for new-style classes. E.g. >>> class C: ... class C1: pass ... >>> C.C1.__name__ 'C.C1' >>> Logged In: YES user_id=6380 Hm, but should this also be done for functions inside classes? E.g. class C: def foo(self): pass assert C.foo.__name__ == "C.foo" assert C.__dict__["foo"].__name__ == "C.foo" And what about classes inside functions? def f(): class C: pass return C assert f().__name__ == "f.C" ??? Logged In: YES user_id=6380 I'm less sure I even want this now, and not at all sure how to do it any more, so lowering priority. Any interest for Python 3000 on this? Otherwise we can close it. I don't think so. Closing.'>"
http://bugs.python.org/issue633930
CC-MAIN-2017-17
refinedweb
157
87.42
Red Hat Bugzilla – Bug 22418 g++ segfaults while compiling mozilla CVS tree Last modified: 2007-04-18 12:30:14 EDT On my mostly redhat 7.0 machine (with bits of rawhide), g++ segfaults when compiling a mozilla cvs tree I pulled down yesterday (2000/12/16) Relevant packages: gcc-c++-2.96-65 (from rawhide) gmake[3]: Entering directory `/home/craig/mozilla/db/mork/src' morkTable.cpp c++ -o morkTable.o -c -DOSTYPE=\"Linux2.4\" -DOJI -I../../../dist/include -I../../../dist/include -I/usr/X11R6/include -fPIC -fno-rtti -fno-exceptions -Wall -Wconversion -Wpointer-arith -Wbad-function-cast -Wcast-align -Woverloaded-virtual -Wsynth -pedantic -Wno-long-long -pthread -O6 -DNDEBUG -DTRIMMED -DMOZILLA_CLIENT -include ../../../config-defs.h -Wp,-MD,.deps/morkTable.pp morkTable.cpp morkTable.cpp: In method `void morkTable::NoteTableAddRow (morkEnv *, morkRow *)': morkTable.cpp:764: Internal error: Segmentation fault. Please submit a full bug report. See <URL:> for instructions. Note that I'm compiling with -O6. I have glibc-2.2-7 installed and am using a 2.4.0test11pre4 kernel. My machine compiled mozilla happily previously using the redhat 7.0 supplied g++ but since then I have upgraded to the rawhide g++ and grabbed a fresh mozilla CVS tree so I can't say for sure that the vanilla g++ would have been happy with things either and I haven't downgraded g++ to check. Can you please rerun the above command with -save-temps -v options and put morkTable.ii it creates here as an attachement? Thanks. Created attachment 6517 [details] morkTable.ii as requested OK. Here is the output. I think I've managed to attached the morkTable.ii file too a moment ago ... thank you! Reading specs from /usr/lib/gcc-lib/i386-redhat-linux/2.96/specs gcc version 2.96 20000731 (Red Hat Linux 7.0) /usr/lib/gcc-lib/i386-redhat-linux/2.96/cpp0 -lang-c++ -D__GNUG__=2 -v -I../../../dist/include -I../../../dist/include -I/usr/X11R6/include -D__GNUC__=2 -D__GNUC_MINOR__=96 -D__GNUC_PATCHLEVEL__=0 -D__ELF__ -Dunix -Dlinux -D__ELF__ -D__unix__ -D__linux__ -D__unix -D__linux -Asystem(posix) -D__OPTIMIZE__ -Wall -Wconversion -Wpointer-arith -Wbad-function-cast -Wcast-align -Woverloaded-virtual -Wsynth -Wno-long-long -pedantic -Acpu(i386) -Amachine(i386) -Di386 -D__i386 -D__i386__ -D__tune_i386__ -D__PIC__ -D__pic__ -D_REENTRANT -DOSTYPE="Linux2.4" -DOJI -DNDEBUG -DTRIMMED -DMOZILLA_CLIENT -include ../../../config-defs.h -MD .deps/morkTable.pp morkTable.cpp morkTable.ii GNU CPP version 2.96 20000731 (Red Hat Linux 7.0) (cpplib) (i386 Linux/ELF) ignoring nonexistent directory "/usr/i386-redhat-linux/include" ignoring duplicate directory "../../../dist/include" #include "..." search starts here: #include <...> search starts here: ../../../dist/include /usr/X11R6/include /usr/include/g++-3 /usr/local/include /usr/lib/gcc-lib/i386-redhat-linux/2.96/include /usr/include End of search list. /usr/lib/gcc-lib/i386-redhat-linux/2.96/cc1plus morkTable.ii -quiet -dumpbase morkTable.cpp -O6 -Wall -Wconversion -Wpointer-arith -Wbad-function-cast -Wcast-align -Woverloaded-virtual -Wsynth -Wno-long-long -pedantic -version -fPIC -fno-rtti -fno-exceptions -o morkTable.s GNU C++ version 2.96 20000731 (Red Hat Linux 7.0) (i386-redhat-linux) compiled by GNU C version 2.96 20000731 (Red Hat Linux 7.0). morkTable.cpp: In method `void morkTable::NoteTableAddRow (morkEnv *, morkRow *)': morkTable.cpp:764: Internal error: Segmentation fault. Please submit a full bug report. See <URL:> for instructions. Thanks, apparently my bug introduced fairly recently (someone fixed it already in CVS trunk so I'll just include that fix in gcc-c++-2.96-69. Thanks for the report. Magic. Thank you. I assume bugzilla will let me know when the bug status changes. A couple of semi-related questions if you don't mind: Your reply seems to indicate that there should be a gcc-c++-2.96-68 somewhere but only has -65. Am I looking in the right spot or is the internal rawhide tree only synced to the ftp site every so often? Also, Joe Buck's comments on linuxtoday: suggest that 2.96 does not produce optimal code for some 'inner loops'. Is that fixed in the rawhide package/CVS too? I'm hoping it will speed up mozilla on my machine ;) Thank you! Yep, rawhide is not cut daily. To answer the other question, yes, 2.96-nn up to 67 had optimization issues Joe Buck is talking about, in 2.96-68 there are three small patches which lower Stepanov abstraction penalty from 3.88 to 1.41 or less. Thank you for the answers to my other questions. I've just installed all the 2.96-69 which has appeared in updates directory and recompiled the latest mozilla CVS tree. Thank you! I've changed the resolution to 'ERRATA' btw. given that the package is in the 7.0 updates dir. Please change it if I've flagged it incorrectly. Thank you.
https://bugzilla.redhat.com/show_bug.cgi?id=22418
CC-MAIN-2018-43
refinedweb
803
62.54
Hello!. problem 1: libraries that tell you to npm install them. problem 2: I don’t understand frontend build tools: - compiles Vue templates - runs Babel (??) - does type checking for Typescript (if you’re using typescript) - does all of the above with webpack which I will not try to explain much because I don’t understand it, I think it’s a system with a million plugins that does a million things - probably some other things I’m forgetting or don’t even know about If I were working on a big frontend project I’d probably use those tools whether or not I understood them because they do useful things. But I haven’t been using them. esbuild: a simple way to resolve… problem 3: it didn’t work? frontend libraries can have many different build artifacts: - dev vs prod (how verbose are the error messages?) - runtime vs not-runtime (does it include a template compiler?) - whatever the difference between vue.jsvs vue.esm.jsvs vue.common.jsis (something about ES6 modules vs CommonJS???) how the build artifact usually gets chosen: webpack or something! what build artifact is esbuild loading? template compiler version of Vue fixed everything gives you all the build artifacts This is a simple thing but I didn’t really understand it before – it seems like npm install vue: - the package maintainer runs. not every NPM package has a; people seem to prefer import over require for frontend code Here’s what I’ve understood about import vs require so far: - there are two ways to use import/ require, you can do a build step to collapse all the imports and put everything into one file (which is what I’m doing), or you can do the imports/requires at runtime - browsers can’t do requireat runtime, only import. This is because requireloads the code synchronously - there are 2 standards (CommonJS and ES6 modules), and that requireis CommonJS and importis ES6 modules. importseems to be a lot more restricted than requirein general (which is good) I think this means that I should use import and not require in my frontend code. it’s exciting to be able to do imports.
https://jvns.ca/blog/2021/11/15/esbuild-vue/
CC-MAIN-2022-21
refinedweb
363
58.32
a simple code that tries to load a wav file into an input stream.a simple code that tries to load a wav file into an input stream.Code : import java.io.*; import sun.audio.*; public class Sample { public static void main(String[] args) throws Exception { String soundFile = "C:\\KKKFOLDER\\samp.wav"; InputStream in = new FileInputStream(soundFile); AudioStream audioStream = new AudioStream(in); AudioPlayer.player.start(audioStream); } } but no matter what code i tried to run from Google and web resources i always get this errorneed some precise guide with this one..need some precise guide with this one..Quote: could not create audio stream from input stream
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/9116-could-not-create-audio-stream-input-stream-printingthethread.html
CC-MAIN-2014-41
refinedweb
107
59.8
But if you use inheritance, don't the structs become non-POD types? That might create more undefined behavior to deal with -- for example, I was thinking of using memcmp for detecting redundant state-changes in the RenderGroup class, but that would only work if the structs were POD.You've got a good eye for C++ details ;) I should've said inheritance avoids the strict-aliasing issues, but you're right, the standard says that using inheritance like that means they're now non-POD. However, on the compilers that I support, they still act as if they were POD, so I can still memcmp/memcpy them on these compilers. Relying on compiler details should generally be avoided, but it's something you can choose to do Instead of inheritance, I guess I could've used composition to be fully compliant, e.g. struct Command { int id; }; struct FooCommand { Command baseClass; int fooValue; }; I too am puzzled by how redundant state changes are eliminated in this model. Am I correct in that states may be submitted in any order? And if this is the case, then states may be sorted and then linearly compared. However, this seems expensive considering how many states may be set per frame. I'm sure you have a much more clever way of doing this.I haven't really mentioned redundant state removal, except that I do it at the "second level". The 1st level takes a stream of commands, and can't do any redundant state removal besides the traditional technique, which is to check the value of every state before submitting it, something like: if( 0!=memcmp(&cache[state.id], &state, sizeof(State)) ) { cache[state.id]=state; Apply(state); } A lot of renderers do do redundant state checking at that level, which pretty much means having an if like the above every time you go to set a state. I do a little bit of this kind of state caching, but try to avoid it. Instead, I do redundant state checking at the next level up -- the part that generates the sequences of commands in the first place. This part of the code also submits commands to set states back to their default values if a particular draw-call hasn't been paired with any values for that state. After sorting my render-items, the "2nd layer" which produces the stream of commands for the 1st layer looks like: defaults[maxStates] = {/*states to apply if a value doesn't exist for them*/} previousState[maxStates] = {NULL} // a cache of which states are 'current' nonDefaultState[maxStates] = {true} // which states have a non-default value for each item in renderItems draw = item.draw stateGroups = item.stateGroups statesSet[maxStates] = {false} //which states have been set by this item for each group in stateGroups for each state in group if statesSet[state.id] == false && //this state not set by a previous group in this item previousState[state.id] != state //this state not set by a previous item and still current then Submit(state) // add to command buffer, or send to device statesSet[state.id] = true previousState[state.id] = state endif endfor endfor setToDefault = nonDefaultState & ~statesSet nonDefaultState = statesSet for each id in setToDefault Submit(defaults[state.id]) // add to command buffer, or send to device previousState[state.id] = defaults[state.id] endfor Submit(draw) // add to command buffer, or send to device endforExcept the actual C++ code uses a lot of bitmasks instead of arrays of bools, and uses pointers to identify state value equality, and everything is tightly laid out to be cache-friendly, etc...
http://www.gamedev.net/index.php?app=forums&module=extras&section=postHistory&pid=5020261
CC-MAIN-2014-10
refinedweb
598
58.82
I'm trying to override the ToString() method in a generic class. A trimmed down version of the class is using System; public class GenericClass<T> { public T Value { get; set; } public override string ToString() { return (Value != null) ? Value.ToString() : string.Empty; } } ReSharper gives me a warning: "possible compare of value type with 'null'" on the (Value != null) expression. Since my class is meant to be able to both take reference types and value types, it is true that there is a possible compare of a value type with null. I don't know why it would be a problem though (the code runs just fine). I'd like to know if and how I can rewrite my code so the warning disappears. I've tried public class GenericClass<T> { public T Value { get; set; } public override string ToString() { if (Value is ValueType) return Value.ToString(); return (Value != null) ? Value.ToString() : string.Empty; } } in which case the (Value != null) will only be evaluated if Value is not a ValueType. But the warnings remains. This seems like a bug in ReSharper. I found this post from 2007 that describes the same problem. Unfortunately it doesn't have any replies. I'm not sure if I'm misunderstanding something, this is a bug, or this is a feature request. as workaround would this help? Actually, this is one of the analysis with lots of false positives. The main idea of this analysis is that comparison with 'null' for reference types is always false, and thus behavior of code could be wrong if there is no 'class' constraint. I suppose you mean the result of comparing a ValueType with null is always false? That's why I already tried to check first if it's not a ValueType. I would've hoped the code analyzer is smart enough to see that in my (Value!=null) check, the argument can't be a ValueType anymore. As a workaround that certainly has the desired result. Thanks. I would dare to say that in more than 99% of the cases where something like "if (x != null)" appears it is used to check whether or not it is safe to call a method on it (e.g. x.ToString()) without causing a null reference exception and therefor the statement is exactly what the author had in mind. I usually disable this warning as it is more annoying than helpful. A warning should catch common pitfalls or bad style but somehow I have trouble to imagine pitfalls for this case and I can't see it as bad style. I also think there is a bug in the suggestion which comes along with the warning: It offers you to convert the expression to "if (x != default(T))" which is wrong. It won't compile - at least not on C# 3.0 (.Net 3.5). It's also wrong here: Even if would be legal the suggestion would very likely introduce unexpected behaviour. Cheers Christian Thank you for the feedback. For now, I'm still deciding what to do with this analysis, because it actually has a lot of false-positives, but could though catch potentional bug... I'm not sure whether the JIT compiler is clever enough to remove the null check when the type parameter is a value type. You might end up with a call to "object.Equals(object, object)", which would cause the value to be boxed. Here's a workaround inspired by the MiscUtil project: Now you can replace "if (value == null)" with "if (!GenericMath.HasValue(value))", and everything will work as expected. Yes the value type will be boxed, however your code is a classic case of premature optimization. Performance wise it is quite bad. Benchmark: Result: So your code actually takes about 5 times longer than just leaving it to the compiler and boxing a value type seems to incur not much of an overhead (at least in this scenario) Cheers Christian It looks like the JIT compiler is smart enough to remove the null comparison check for non-nullable value types, at least in a release build. In a debug build, the difference is nowhere near as noticable. There's also some variation between x86 and x64 executables, and between .NET 3.5 and .NET 4.0 builds, but nothing significant. I can get the code down to around 2x slower by building a delegate, but it's probably not worth it. I'll just stick with "if (value == null)" and ignore the R# warning. BTW, you don't really need your HighResolutionTimer class - the Stopwatch class introduced in .NET 2.0 does the same thing. Didn't try it in debug - it just shows that doing something in your own code instead of using the standard language construct takes optimization potential away from the compiler. I have found so many different "workarounds" on google for this trying to solve a problem which actually isn't one. Really strange. Missed the StopWatch class. The HPT class comes from before 2.0 and has stuck around in our lib since then. Thanks for the reminder. Cheers Christian
https://resharper-support.jetbrains.com/hc/en-us/community/posts/206037219-How-to-prevent-warning-possible-compare-of-value-type-with-null-
CC-MAIN-2020-24
refinedweb
855
73.47
For the past couple of years the industry has continued to follow Moore’s Law by shifting from CPU clock speed to increasing the number of cores and threads per core. Even cell phones are getting multiple cores these days! Taking advantage of all these cores and threads is one of the hallmarks of modern GUI platforms. But all this concurrency brings a multitude of problems to the application developer, not least of which is that writing multithreaded applications is hard! In designing JavaFX 2.0, we of course needed to address both how the scene graph would behave in the presence of multiple threads, and how developers could effectively do work in background threads and keep the UI responsive. In short, the JavaFX scene graph, like all other mainstream GUI toolkits, is not thread-safe and must be accessed and manipulated from the UI thread (call the FX Application thread). Swing and AWT had the same basic policy (only work with Swing or AWT from the Event Dispatching Thread), as did SWT (only interact with SWT resources and components from the thread that owns them), as do all other major toolkits (JavaScript / HTML included). The most common problem with this design is that developers who do not do work on background threads invariably create unresponsive applications, since this long lived (potentially blocking) code happens on the same thread that processes user events. That is, while your long lived operation is running, no mouse or key events are being processed, which leads to an application that appears to “hang”. Further, actually writing well behaved background workers is difficult and error prone. Even if you create a Runnable and create a Thread and do your long-lived work in that background thread, at some point you need to communicate back to the UI, either with the result of the long-lived computation, or by communicating to a ProgressIndicator of some kind what the progress of this long-lived operation is. This is error prone, because you must be sure to communicate with the UI by putting events back onto the event queue (using Platform.runLater, the equivalent of Swing’s invokeLater). Note: This article is a sneak peek at a new API which is coming in the next couple of weeks, but is not currently available in the Beta builds! There is a deprecated Task class in the beta builds which will be removed and replaced with the one detailed here. Suppose we have a simple background thread which just counts from 0 to 1 million. Suppose I have a single ProgressBar, and that I need to update the progress of this ProgressBar as the counter runs. A naive implementation might look like this: final ProgressBar bar = new ProgressBar(); new Thread(new Runnable() { @Override public void run() { for (int i=1; i<=1000000; i++) { final int counter = i; Platform.runLater(new Runnable() { @Override public void run() { bar.setProgress(counter/1000000.0); } }); } } }).start(); This is a hideous hunk of code, a crime against nature (and programming in general). First, you’ll lose brain cells just looking at this double nesting of Runnables. Second, it is going to swamp the event queue with little Runnables — a million of them in fact. Clearly, we needed some API to make it easier to write background workers which then communicate back with the UI. Java comes with a very complete set of concurrency libraries in the java.util.concurrent package. We wanted to leverage what was already defined in Java, but we needed to extend these APIs to take into account the FX Application thread and the constraints that GUI programmers are under. The javafx.concurrent package contains three core files: Worker, Task, and Service. Before diving into the rather verbose description (taken from the proposed javadocs) for Worker, Task, and Service I wanted to cut to the chase and show some examples. The first key thing to mention, is that Worker is an interface that is implemented by both Task and Service, and which adds the sort of convenience API necessary for a background worker that is useful for communicating back with a UI. Second, Task extends from java.util.concurrent.FutureTask. This means that a Task can very cleanly fit into the concurrent libraries. As you may know, FutureTask implements Runnable, and can be passed to an Executor’s execute() method. So real quick, here is the same example as above, but it suffers from none of the flaws exhibited in the naive implementation. Task task = new Task<Void>() { @Override public Void run() { static final int max = 1000000; for (int i=1; i<=max; i++) { updateProgress(i, max); } return null; } }; ProgressBar bar = new ProgressBar(); bar.progressProperty().bind(task.progressProperty()); new Thread(task).start(); In this example, I first create my Task. The task implementation just does its work, invoking the protected updateProgress method defined on Task, which ends up updating progress, totalWork, and workDone properties on the Task. I then create my ProgressBar and bind its progress property with the progress property of the Task. Then, since Task is a Runnable, I can just create a new Thread passing it the Task and then start the Thread. Alternatively, I could create an Executor or ExecutorService (such as a ThreadPoolExecutorService) and execute the task using the ExecutorService. Edit July 11, 2011: I have updated the API slightly since this post was originally written, and I’ve updated the post to reflect the current names. In particular, the “progress” property is now a value between 0 and 1 (or -1), matching the “progress” property on ProgressIndicator and other parts of the platform. “workDone” and “totalWork” are used to indicate the total units of work to do (such as bytes to be downloaded) and the total units of work that have been done (such as the bytes that have been downloaded). I’m not totally jazzed by the names, but felt it was important for “progress” to mean the same thing on Worker and ProgressIndicator. Below are some further descriptions taken from the javadocs. Worker A Worker is an object which performs some work in one or more background threads, and who’s state is observable and available to JavaFX applications and is usable from the main JavaFX Application thread. This interface is primarily implemented by both Task and Service, providing a common API among both classes which makes it easier for libraries and frameworks to write user interfaces with observable workers. A Worker may, or may not be reusable, depending on the implementation. A Task, for example, is not reusable while a @link Service is. A Worker has a well defined life cycle. Every Worker begins in the READY state. When the Worker has been scheduled for work (for example, when a Service’s start() method is called), it is transitioned to SCHEDULED. Even Workers which are not technically scheduled, but started immediately (such as with Task#run()) will transition through SCHEDULED on its way to the RUNNING state. When the Worker is actually performing its work, the state will have been transitioned to RUNNING. If the Worker completes normally, it will end in the SUCCEEDED state, and the result of the Worker will be set as the value property. If however an Exception occurs during the execution of the Worker, then the state will be set to FAILED and the exception property will be set to the Exception which occurred. At any time prior to the conclusion of the Worker (that is, if the state is not already SUCCEEDED or FAILED) the developer may invoke the Worker#cancel() method. If called, the Worker will cease execution (if possible, including use of Thread.interrupt) and the state changed to CANCELLED. The only valid beginning state for a Worker is READY, and the valid ending states are CANCELLED, SUCCEEDED, and FAILED. The running property is set to true when the state is either SCHEDULED or RUNNING. The Worker’s progress can be monitored via three different properties, workDone, totalWork, and progress. These properties are set by the actual implementation of the Worker interface, but can be observed by anybody. The workDone is a number between -1 (meaning indeterminate progress) and totalWork, inclusive. When workDone == totalWork the progress will be 100% (or 1). totalWork will be a number between -1 and Long.MAX_VALUE, inclusive. The progress will be either -1 (meaning indeterminate), or a value between 0 and 1, inclusive, representing 0% through 100%. A Worker which is in the READY or SCHEDULED states will always have workDone and progress set to -1. A Worker which is in the SUCCEEDED state will always have workDone == totalWork and progress == 1 or -1. In any other state, the values for these properties may be any value in their respective valid ranges. Task A fully observable implementation of a FutureTask. Tasks exposes additional state and observable properties useful for programming asynchronous tasks in JavaFX, as defined in the Worker interface. An implementation of Task must override the Task#call() method. This method is invoked on the background thread. Any state which is used in this method must be safe to read and write from a background thread. For example, manipulating a live scene graph from this method is unsafe and will result in runtime exceptions. Tasks are flexibly and extremely useful for the encapsulation of work. Because Service is designed to execute a Task, any Tasks defined by the application or library code can easily be used with a Service. Likewise, since Task extends from FutureTask, it is very easy and natural to use a Task with the java concurrency java.util.concurrent.Executor API. Finally, since a Task is Runnable, you can also call it directly (by invoking the Task#run() method) from another background thread. This allows for composition of work. Although java.util.concurrent.ExecutorService defines several methods which take a Runnable, you should generally limit yourself to using the execute method inherited from java.util.concurrent.Executor. As with FutureTask, a Task is a one-shot class and cannot be reused. See Service for a reusable Worker. Because the Task is designed for use with JavaFX GUI applications, it ensures that every change to the public properites, as well as change notifications for state, errors, and for event handlers, all occur on the main JavaFX application thread. Accessing these properties from a background thread will result in runtime exceptions being raised. Service A Service is a non-visual component encapsulating the information required to perform some work on one or more background threads. As part of the JavaFX UI library, the Service knows about the JavaFX Application thread and is designed to alieviate the application developer from the burden of manging multithreaded code that interacts with the user interface. As such, all of the methods and state on the Service are intended to be invoked exclusively from the JavaFX Application thread. Service implements {@link Worker}. As such, you can observe the state of the background operation and optionally cancel it. Service is a reusable Worker, meaning that it can be reset and restarted. Due to this, a Service can be constructed declarativley and restarted on demand.). Because a Service is intended to simplify declarative use cases, subclasses should expose as properties the input parameters to the work to be done. For example, suppose I wanted to write a Service which read the first line from any URL and returned it as a String. Such a Service might be defined, such that it had a single property, url. It might be implemented as: public class FirstLineService extends Service { private StringProperty url = new StringProperty(); public final void setUrl(String value) { url.set(value); } public final String getUrl() { return url.get(); } public final StringProperty urlProperty() { return url; } protected Task createTask() { final String _url = getUrl(); return new Task<InputStream>() { protected String call() { URL u = new URL(_url); BufferedReader in = new BufferedReader( new InputStreamReader(u.openStream())); String result = in.readLine(); in.close(); return result; } } } } Conclusion We anticipate that libraries of Tasks, both specialized for your specific application and also general libraries of Tasks will be developed over time that perform common operations such as downloading files, performing HTTP form submits, copying files, uploading files, sorting, doing statistical analysis, and so forth. These reusable bodies of code can then be combined together, used with thread pools or other rich executor services, and used with Services. Let us know what you think!?^( 4. “new Thread(task).start()” “no suitable constructor found for Thread(javafx.async.Task)” :((( Shame on me, it is wrong Task! 🙂 Is javafx.concurrent available for now? I can’t reach it from Netbeans and JavaFx SDK b32 Hi Anatol, sorry for the confusion! While editing the blog post I accidentally removed one vital bit of information, which is that this change will show up in I think b34 (give it a couple of weeks). This is all cutting edge stuff. The reason Task was deprecated in previous builds was because we were planning on making the changes detailed in this post, and wanted to make sure people were aware of this. Excellent information! It will be extremely useful package!!! It is good news that such work is done, and will definitly help to keep all those cores busy 🙂 However, from a Clojure point-of-view the proposed solution is unfortunate. In some areas of the JFX API I saw the same challenge: creating an anon class and calling protected methods. The low-level binding API requires the same. In an ideal API a class would introduce many methods itself (mostly getters and setters). It only would offer (public) fields. Nearly all methods are introduced by implementing interfaces (yes, this would lead to many interfaces that include methods which will be implemented by only one class). I understand that this will not be possible, but it would still be useful to offer some alternative approaches so that other JVM languages also could use JFX, without requiring to write Java code. When I want to write a Task, then I would just like to provide a function object (the implementation), and be done with it. JFX should not have Clojure as a dependency, and so overloading it and accepting a Clojure function as argument for a method call is not the right way. One Way could be to offer static methods that take an object that implements a specific interface. There could be a interface TaskITF that provides the necessary methods. One could then call Task.createTask(TaskITF t). All without having the need to subclass or to call protected methods, or anything from superclasses. Great article indeed! Ps: i think there ‘s a typo in the code example using Task. Static should be removed from the line: static final int max = 1000000; great info! thanks for the explanation. It is really important to have that kind of feedback from you guys. at the risk of changing the subject: do you plan to include FXML in javafx 2.0 GA…and post a similar post concerning FXML? Yep, it should be available within the next few weeks to play with (about the same time as this Task stuff, actually). great news! Looking forward to it Oh well, a pity, but I’m sure there are sensible reasons for it. I’d got my hopes up. I was hoping JavaFX 2.0 would take the step of being thread-safe. Tasks still seem predicated on the idea that off-UI-thread tasks are long and few. As cores increase, it seems to me that off-thread tasks in future might be short and many. So the Task would increasingly be boilerplate littering code. I had quietly hoped JavaFX 2.0 would be designed to be thread-safe, and that the default would be that the Application does not sit on the event dispatch thread but entirely in one or more Worker threads. At first glance, closures/lambdas seemed to be an easy way to make that possible. Internally to the API, methods would either executeAndWait if they are not called from the EDT, or run directly if they are. But then it’s easy to think “Wouldn’t it be nice if…” when I don’t have to write the code or discover what the unintended ramifications for the API would be! Actually, what we want to do is to “fail-fast” much like the Collection’s framework or WPF or SWT, such that if you attempt to use the scene graph from the wrong thread we throw an unchecked exception, as opposed to Swing which would just carry on (and perhaps deadlock, or perhaps silently corrupt data, or perhaps just work). Truly thread-safe GUI toolkits are definitely still a research problem — none of the major toolkits attempt it. Richard – this is wonderful stuff and a welcome change from the JavaTaskBase/RunnableFuture pairs we use so heavily in our SoMa app. I’m eager to start experimenting with Worker/Task/Service. Please forgive me for using your threading post as a segue, but my principal concern for Presidio and beyond is not so much the ‘how’ of worker threading, but the ‘what’ – as in what the background heavy lifting actually is. Our SoMa app frequently creates RunnableFutures that go to work on BufferedImages of type TYPE_USHORT_GRAY, and are suffused with BufferedImage, Raster, WritableRaster, getPixel, setPixel and ImageIO. Through trial and error, we discovered that, after background image processing,we can downsample and use getGraphicsConfiguration().createCompatibleImage() to get a decent visual representation into the scene graph via SwingUtils.toFXImage() and ImageView. I haven’t tried it yet but it seems that, in Presidio, we ought to be able to encode a BufferedImage to a byte array and use the Image constructor that takes a java.io.InputStream to get it into the scene graph. However, from the roadmap and various 2.0 posts, I understand that java.awt (presumably including java.awt.image) is antithetical to Prism. Are you able to share your plans for a successor to the BufferedImage stack? Otherwise, Presidio is shaping up to be really terrific and please know that some of us out here are great admirers of your work. Rick Hi Rick, Actually with FX / Swing interop (ability to embed FX in Swing), we still use Prism. It runs side-by-side with AWT, so it would seem that your use case or approach here should work. I could see some threading issues potentially cropping up, but I don’t see anything that says this absolutely couldn’t work. javafx.async.Task is deprecated in the latest JavaFX 2.0 build 34. I take it that this post is out of date? What is the updated equivalent? This new API described in this post made it into b35, so in the next public drop you’ll see it. Great, I got build 36 installed and I see the non-deprecated javafx.concurrent stuff. First, there is no JavaDoc for javafx.concurrent. I see JavaDoc for all the other JavaFX 2.0 packages in .netbeans/7.0/lib/docs/api/javafx, but javafx concurrent is not there. Secondly, how do I kick off a background task from the GUI thread and implement a completion callback that runs in the GUI thread? In FX 1.2.x, this was pretty straightforward with JavaTaskBase. I’ve reread this post in it’s entirety and I don’t see how to do this with the new package. (BTW, sorry for my first comment. I see you addressed that issue in the main post and several times in the comments) Hi Richard, this is a really great start for us. I realise this post is getting a tad old now but this still seems to be the only real example of using the new Service stuff in JFX2. It is a bit of a teaser though. It would be great to see an actual example of how to use this API to do the common UI/background workflow, namely: 1. Get some stuff from the screen (i.e. details enetered in a form) 2. Do a slow background task using the details entered 3. Update the screen with the results from the background task There are many different properties and options, so seeing how it is *intended* to be used for this common scenario would be extremely useful for me and I imagine many others. Cheers, zonski Hi Richard Task priceUpdateTask = new Task() { @Override public Void run() { while (true) { BigDecimal price = getFinancialPriceFromSomewhere(…) updateProgress( price ); } return null; } }; What happens if I have a “task”, which is not predictable and may not exit or runs forever? How can one just update the price using a decimal type e.g. float, double, BigDecimal? Currently the only way I found was Platform.runLater() see my talk Progressive JavaFX 2.0 and code Yep, using Platform.runLater() is the best solution I would say. Any chance the Service class will get an onFinished event we can listen in on or a finished callback of some kind? That will give us extra flexibility beyond the runLater option. Here is the issue:, please vote for it if you want it! I think this is a fine thing, earlier versions of the class did have these events but I pulled them because, as an API designer, “less is more” until customers make specific requests. That is, it is sometimes hard to know up front exactly what convenience API would make somebodies life a lot easier and what convenience API is just “bloat”, so I decided to start off with a smaller API and wait for the shouting :-). I personally like the idea of having events for these things.. Yes, definitely request more things! One of our main goals for the next year is “fit and finish”, so knowing what areas cause pain is very important. Hi All, Looks old thread but very informative.I am stuck here. Looks simple but its tricky. I have a progressbar which gets progressed at different places in doInBackgroud() method. Here in doInBackground i am doing something like this. (Consider it as sequential.) Task.setTaskProgress(60); MessageResponse response = getHttpURLConnectionResponse(connection); Task.setTaskProgress(100); Here it waits for the response for quite a long time and progressbar looks hung at 60%. and after getting the response it jumps to 100%. So my question is how can i slow increment the progress bar from 60% to 100% . (fake update till i get the response).? The. Richard thanks a lot for the reply. The problem that I’m facing is. Wherever I use the above reponse statement program waits till the response and then continues execution. I wanted to show some progress during that waiting time. Your help is greatly appreciated. @Pavan, I don’t know what you are asking. I assume you are executing the blocking call on the background thread and not the FX thread. The normal UI interaction is to use an indeterminate progress visual when you are doing something that could last some arbitrary amount of time, and a determinate progress visual when you are some determined amount through some task (such as downloading bytes). Hi Richard, thanks for the article. How does one schedule a Service to run after a certain amount of time? I see there is a SCHEDULED state, however this doesn’t seem to be exposed? In a nutshell, is there an equivalent of ScheduledExecutorService.schedule()? Good article! however I think using the Task example above to replace the inline Thread example to justify this statement “Second, it is going to swamp the event queue with little Runnables — a million of them in fact” is a little overlooked. Event if Task is used and GUI update is required then the Platform.runLater is still needed. The “A Task Which Modifies The Scene Graph” example in will justify. Good, good, good! Very Useful. Thanks for this article, helped a lot. thank you
http://fxexperience.com/2011/07/worker-threading-in-javafx-2-0/
CC-MAIN-2020-16
refinedweb
3,990
63.09
Supreme Court Judgments Subscribe R.C. Lahoti & K.G. Balakrishnan R.C. Lahoti, J. The controversy centres around the interpretation of sub-section (7) of Section 6 of the Press Council Act, 1978 (hereinafter 'the Act', for short), viz., for how many terms of the Council a member can be nominated? The facts are jejune. Harbhajan Singh, the appellant, is an editor of Indian Observer. All India Small and Medium Newspapers Federation, the respondent no.2 is an 'association of persons' within the meaning of clause (b) of sub-section (4) of Section 5 of the Act. The appellant had been a member of the Council for two terms of three years each, namely, 1982-1985 and 1985-1988. Steps were taken for the constitution of the Seventh Council commencing from the year 1998. A notification in that regard was issued on 21.11.1997. On 5.5.1997 and 9.8.1997 the Federation __ respondent No.2 had sought for a clarification-cum-opinion from the Chairman of the Press Council of India as to whether a person who had already been a member of the Council for two terms earlier is eligible for being nominated though such nomination did not amount to re-nomination, that is to say, at the time of being nominated he was not a retiring member. In response, the Council circulated an opinion of the President dated 30.9.1997, the substance whereof is, that Section 6(7) debars the same person from holding the office as a member of the Council for more than two terms in his life. The appellant and the Federation, respondent no.2 herein, filed a writ petition before the High Court of Delhi seeking quashing of the opinion of the Chairman of the Press Council. A learned Single Judge of the High Court directed rule nisi to issue and on 9.12.1997 issued an interim direction that the decision of the Press Council would be subject to the decision in the writ petition. The Federation __ respondent No.2 nominated the appellant and also his son as a cover candidate. The appellant's nomination was not accepted by the Council on the ground that he having remained a member of the Council for two terms, was ineligible for nomination as per sub-section (7) of Section 6 of the Act. After hearing the petitioners and the Press Council, as also the Union of India, the learned Single Judge vide order dated August 18, 2000 allowed the writ petition and quashed the decision of the Press Council of India rejecting the nomination of the appellant. The learned Single Judge formed an opinion that the language of the statute was plain, admitting of no ambiguity, and therefore, deserves to be assigned the plain meaning which naturally flows from a reading thereof. In the opinion of the learned Single Judge the disqualification spelled out by sub-section (7) of Section 6 attaches to a member 'retiring' in presenti and was sought to be 're-nominated' but did not apply to a person who had 'retired' some time in the past though having held two consecutive terms as member of the Council and was now being only 'nominated' and 'not re-nominated'. The Press Council of India preferred an intra-court appeal before a Division Bench which allowed the appeal and set aside the judgment of the learned Single Judge. Tracing out the legislative history of the enactment and giving a liberal interpretation to sub-section(7) of Section 6 in its desire to spell out and read the objective sought to be achieved by the Act, the Division Bench formed an opinion that the Legislature intended not to allow a member to hold office for more than two terms in his life-time, and therefore, the appellant was not eligible for nomination to membership of the Council for the term commencing 1998 in view of his having held membership of the Council for two terms 1982-1985 and 1985-1988. The appellant has filed this appeal by special leave. Leave granted. The Act, as its preamble shows, proposed to establish a Press Council for the purpose of preserving the freedom of the Press and of maintaining and improving the standards of newspapers and news agencies in India. Section 4 provides for incorporation, and Section 5 provides for composition, of the Council. The details are irrelevant for our purpose. Section 6, in so far as relevant for our purpose, provides that the Chairman and other members of the council shall hold office for a period of three years. Sub-section(7) reads as under:- (7) A retiring member shall be eligible for re-nomination for not more than one term." According to the appellant, all that the provision bars is a member holding two terms of office successively. According to the respondent Council the total number of terms for which a member can hold office, whether in succession or otherwise, is two, as the provision makes it permissible for any member to seek re-nomination for one term only. This is the narrow controversy. Clearly the language of Sub-Section (7) of Section 6 abovesaid, is plain and simple. There are two manners of reading the provision. Read positively, it confers a right on a retiring member to seek re- nomination. Read in a negative manner, the provision speaks of a retiring member not being eligible for re-nomination for more than one term. The spell of ineligibility is cast on 're-nomination' of a member who is 'retiring'. The event determinative of eligibility or ineligibility is 're-nomination', and the person, by reference to whom it is to be read, is 'a retiring member'. 'Retiring member' is to be read in contra-distinction with a member/person retired some time in past, and so, would be called a retired or former member. 'Re' means again, and is freely used as prefix. It gives colour of 'again' to the verb with which it is placed. 'Re-nomination' is an act or process of being nominated again. Any person who had held office of member some time in past, if being nominated now, cannot be described as being 'again nominated'. It is only a member just retiring who can be called 'being again nominated' or 're-nominated'. No other meaning can be assigned except by doing violence to the language employed. Legislature does not waste its words. Ordinary, grammatical and full meaning is to be assigned to the words used while interpreting a provision to honour the rule Legislature chooses appropriate words to express what it intends, and therefore, must be attributed with such intention as is conveyed by the words employed so long as this does not result in absurdity or anomaly or unless material intrinsic or external is available to permit a departure from the rule. The provision is cast in present tense. A retiring member is ineligible for re-nomination. 'Not more than one term' qualifies 're- nomination'. The words 'retiring', used in present tense, and 're- nomination' speak aloud of the intention of the Legislature. If the word 'retiring' was capable of being read as 'retired' (sometime in past) then there would have been no occasion to use 're-nomination' in the construction of the sentence. If the intention of law framers would have been not to permit a person to be a member of council for more than two terms in his lifetime then a different, better and stronger framing of the provision was expected. It could have been said __ 'no member shall be eligible for nomination for more than two terms', or it could have been said __ 'a retired member shall not be eligible for nomination for more than two terms'. Cross in Statutory Interpretation (Third Edition, 1995) states : "The governing idea here is that if a statutory provision is intelligible in the context of ordinary language, it ought, without more, to be interpreted in accordance with the meaning an ordinary speaker of the language would ascribe to it as its obvious meaning, unless there is sufficient reason for a different interpretation. . . . .Thus, an 'ordinary meaning' or 'grammatical meaning' does not imply that the judge attributes a meaning to the words of a statute independently of their context or of the purpose of the statute, but rather that he adopts a meaning which is appropriate in relation to the immediately obvious and unresearched context and purpose in and for which they are used. By enabling citizens (and their advisers) to rely on ordinary meanings unless notice is given to the contrary, the legislature contributes to legal certainty and predictability for citizens and to greater transparency in its own decisions, both of which are important values in a democratic society" (p.32 ibid). The learned author cites three quotations from speeches of Lord Reid in House of Lords cases, the gist whereof is: (i) in determining the meaning of any word or phrase in a statute ask for the natural or ordinary meaning of that word or phrase in its context in the statute and follow the same unless that meaning leads to some result which cannot reasonably be supposed to have been the legislative intent; (ii) rules of construction are our servants and not masters; and (iii) a statutory provision cannot be assigned a meaning which it cannot reasonably bear; if more than one meaning are capable you can choose one but beyond that you must not go (p.40, ibid). Justice G.P. Singh in his celebrated work __ Principles of Statutory Interpretation (Eighth Edition, 2001) states (at page 54) __ ." The learned author states at another place (at page 74, ibid) that the rule of literal construction whereby the words have to be assigned their natural and grammatical meaning can be departed from but subject to caution. The golden rule is that the words of statute must prima facie be given their ordinary meaning. A departure is permissible if it can be shown that the legal context in which the words are used or the object of the statute in which they occur requires a different meaning. To quote, '. A modern statement of the rule is to be found in the speech of Lord Simon of Glaisdale in Suthendran v. Immigration Appeal Tribunal, (1976) 3 All ER 611, 616 to the effect __ or statutory objective the language may be modified sufficiently to avoid such disadvantage, though no further'." Sir Dinshah Mulla, while interpreting Article 182 of the Limitation Act, 1908 emphasised the need of testing the question of interpretation upon the plain words of the Article and opined that there is no warrant for reading into the words quoted any qualification and the strict grammatical meaning of the words is the only safe and Ors. AIR 1932 P.C. 165). Viscount Maugham in General Abdul Rahim AIR 1941 P.C. 6 approved the principle that it may be desirable for an act to receive such construction as the language in its plain meaning imports. The same principle has been followed by the Supreme Court of India in several decisions. Suffice it to refer to Siraj-il-Haq Khan and Ors. VS. The Sunni Central Board of Waqf U.P. and Ors. 1959 SCR 1287, wherein P.B. Gajendragadkar, J. (as His Lordship then was) said that effect must be given to the strict grammatical meaning of the words used. Without multiplying the authorities we would still like to refer to two more decisions which we of Wealth Tax (1990) 3 SCC 624, the expression "where the interest is available to an assessee for a period not exceeding six years from the date the interest vests in the assessee" contained in Section 2(e)(2)(iii) of the Wealth Tax Act, 1957 came up for consideration and the emphasis was on the significance of "is" on the import of the provision. This Court held that the word "is", normally refers to the present and often a future meaning. It may also have a past signification as in the sense of "has been". However, in the setting in which "is" was used followed by the word "available", it was held "the word 'is' must be construed as referring to the present and the future. In that sense it would mean that the interest is presently available and is to be available in future for a period not exceeding six years". The High Court had construed the word "is" to mean "has been" which construction was discarded by this Court. The tense of the sentence played a pre-dominant role in the interpretation placed on the relevant provision by this Court in F.S. Gandhi's case. In and Anr.- (1966) 1 All ER 545, under the relevant Statute the Minister was empowered to declare that the school should cease to be an unaided school and that the Director should be the Manager of it, if the Minister was satisfied that an unaided school "is being administered" in contravention of any provisions of the Act. Their Lordships opined, "Before the Minister had jurisdiction to make the order he must be satisfied that 'any school.is being so administered in contravention of any of the provisions of this Act'. The present tense is clear. It would have been easy to say 'has been administered' or 'in the administration of the school any breach of any of the provisions of this Act has been committed', if such was the intention of the legislature; but for reasons which common sense may easily supply, it was enacted that the Minister should concern himself with the present conduct of the school, not the past, when making the order. This does not mean, of course, that a school may habitually misconduct itself and yet repeatedly save itself from any order of the Minister by correcting its faults as soon as they are called to its attention. Such behaviour might well bring it within the words 'is being administered' but in the present case no such situation arose. There was, therefore, no ground on which the Minister could be 'satisfied' at the time of making the order. As appears from the passages of his broadcast statement which are cited above, he failed to consider the right question. He considered only whether a breach had been committed, and not whether the school was at the time of his order being carried on in contravention of any of the provisions of the Act. Thus he had no jurisdiction to make the order at the date on which he made it". The Division Bench, in its impugned judgment, entered into tracing the legislative history and tried to find out the object of enactment and intention of the Legislature. The effort made by the Division Bench can be appreciated but regrettably the deductions drawn by the Bench are based on no material. In fact, the learned Judges of the Division Bench fell into the same error as has been pointed out above, that is, of attributing such intention to Legislature as suited their own view of the policy behind enactment. M.H. Beg, J. warned against beginning with a theory as to what the real purpose or need is or could be, for the danger is that we may be injecting a subjective notion or purpose of our own into what is, after all a legal question of construction or interpretation. His Lordship emphasized the need of avoiding the danger of a priori determination of the meaning of a provision based on our own preconceived notions of an ideological structure or scheme into which the provision to be interpretated is somehow fitted. (See, concurring judgment of M.H. and Ors. etc. (1977) 2 SCC 273. The Division Bench has not culled out and placed material on record, either available intrinsically in the Act or from any external aid to interpretation, so as to lead to the inference drawn by the Division Bench and sustain departure from the golden rule of interpretation. The learned single Judge followed the correct track on the path of interpretation of statutes by reading what has been said and comparing with what has not been said. The learned single Judge gave at least three illustrations of what could have been said but has not been said so as to find out how the Legislature would have construed the provision in question if the intention would have been not to permit a person to be a member of the council for more than two terms. It would be advantageous to restate briefly the three illustrations from the judgment of the learned single Judge which are as under: (i) In the Schedule appended to the Delhi University Act, 1922 called 'The Schedule __ The Statutes of the University', para 5(1) provides for composition of the Executive Council as comprising the various members as specified. Clause (2) provides __ "No person shall be a member under item (ix) or (x) of Clause (1) for more than two consecutive terms". (ii) Section (1) of the Twenty-second Amendment of the US Constitution provides __ "No person shall be elected to the office of the President for more than twice, and no person who has held the office of President, or acted as President, for more than two years of a term to which some other person was elected President shall be electe d to the office of President more than once. . . . . . . . . ." (iii) In Section 31(5) of the Delhi Cooperative Societies Act, 1972 it is provided__ "Notwithstanding anything contained in the Act, a person shall be disqualified for election as, or for being, the president, vice-president, chairman, vice-chairman, managing director, secretary, joint secretary or treasurer of a committee: (a) if he has held any such office on that committee during two consecutive terms whether full or part; . . . . . . ." In all the three illustrations of drafting, the intended bar against holding the given office for more than two terms (as provided) is clearly and categorically spelled out. Having given the three illustrations, the learned single Judge held that if the construction suggested by the Council was to be accepted, one would be required to read 'retiring member' as 'a retired member'. Yet another reason assigned by the learned single Judge, and rightly so, is that the right to be appointed as a member having been conferred by the law, ineligibility entailing prohibition or bar on being appointed to an office should be clearly stated or positively spelled out, in absence whereof the same cannot be read into the provision on the basis of the assumed intention of fulfilling the object of the statute. The learned single Judge quoted very apt and Co., (1897) AC 22, 38 to the effect :- " ." The Division Bench has, during the course of the judgment, noted that Press Council was intended to be an independent body and if any person was permitted to remain a member of the Council for more than two terms, it will erode independence of the body as the elements of vested interest would creep in and this would also defeat the object of Sub-Section (7) of Section 6 of the Act. We fail to find any justification for such an observation much less any basis for forming such an opinion. Simply because the Press Council has taken a particular view of the relevant provision it can hardly be a ground for the Court to lean in favour of such a construction. We are clearly of the opinion that Sub-Section (7) of Section 6 of the Press Council Act must be assigned its ordinary, grammatical and natural meaning as the language is plain and simple. There is no evidence available, either intrinsic or external, to read the word 'retiring' as 'retired'. Nor can the word 're-nomination' be read as nomination for an independent term detached from the previous term of membership or otherwise than in succession. The provision on its plain reading does not disqualify or make ineligible a person from holding the office of a member of the Council for more than two terms in his life. The use of the words 'retiring' as qualifying 'member' coupled with the use of word 're-nomination' clearly suggests that a member is disqualified for being a member for the third term in continuation in view of his having held the office of membership for more than two terms just preceding, one of which terms, the later one, was held on re-nomination. Such an interpretation does not lead to any hardship, inconvenience, injustice, absurdity or anomaly and, therefore, the rule of ordinary and natural meaning being followed cannot be departed from. For the foregoing reasons, the appeal is allowed. The judgment of the Division Bench is set aside and that of the learned single Judge is restored. No order as to the costs. . . . . . . . . . . . . J. ( R.C. LAHOTI ) . . . . .J. Back
https://www.advocatekhoj.com/library/judgments/index.php?go=2002/march/28.php
CC-MAIN-2022-33
refinedweb
3,496
52.63
14 May 2010 17:00 [Source: ICIS news] (recasts paragraph 18 for clarity) MUMBAI (ICIS news)--An expansion of the new Fujian petrochemical complex in China is being considered just months after it became operational because of strong demand and a favourable market reception for the complex’s products, an executive of energy giant ExxonMobil said on Friday. “Our partners at the ?xml:namespace> “There is a study on what is going to happen next, but there is no decision yet,” she said. ExxonMobil has a 25% interest in the $4.5bn Fujian Integrated Refining and Ethylene Joint Venture that was started up in November last year. Fujian Petrochemical Co Ltd, a unit of Sinopec, controls 50% of the project, while Saudi Aramco holds the remaining 25% stake. The Its downstream plants include an 800,000 tonne/year polyethylene unit, a 400,000 tonne/year polypropylene unit and a 700,000 tonne/year paraxylene unit. The complex also has a 250-megawatt cogeneration facility. “All units are operating at full capacity. They have demonstrated their nameplate capability,” said Lachenmyer. Products take-up had been very robust and, as long as the growth continues, there is scope for expanding its capacity, she said. “All the products have been placed with the local provincial area. The receptivity of our products in the market place has been good,” Lachenmyer said. Meanwhile, ExxonMobil expects to reach “peak work load” at its second petrochemical complex in The Lachenmyer said demand recovery in the petrochemical industry since the second half of 2009 up to the first quarter of this year had been swift, but this should be treated with caution given that the global economy has yet to find solid footing. “We’re surprised at how swiftly the recovery has come about – which is good – but there’s still a lot of caution in the market,” she said, citing the uncertainty of how GDP would grow once the stimulus packages across countries have been reduced. Global economic recovery remained in “very much a fragile state”, she said. A supply glut also looms over the industry, with about 12m tonnes/year of new capacity expected to come on stream this year in the Middle East and “We expect to see more of that volume coming in the second half of this year and certainly the exports coming out of the Middle East will flow either into Europe or to Asia, [while] the rest of the capacity additions are in As a result there could be an additional negative impact on the margins of the overall industry, she warned. For more on ExxonMobil, Sinopec and Saudi Aramco visit ICIS company intelligence
http://www.icis.com/Articles/2010/05/14/9359817/exxonmobil-eyes-fujian-china-chem-complex-expansion.html
CC-MAIN-2014-10
refinedweb
443
55.88
From: jsiek_at_[hidden] Date: 1999-12-08 23:55:12 Fantastic. We're making great progress. Just some replies to your questions here. Dietmar Kuehl writes: > In which namespace do 'begin()' and 'end()' live? Since 'std::pair' is in > defined in namespace 'std' which is by definition closed, it is necessary > to provide the namespace for these functions! I don't think they should > go into the global namespace. Maybe it would be resonable to use > 'p.first' and 'p.second' instead? The reason I had begin() and end() there was that I was thinking that perhaps it would be nice to not actually specify the use of std::pair as the return type, but just require that it is something that works with begin() and end(). I suppose the begin() and end() functions could go in the same namespace as the graph library implementations (and later in std when it gets accepted ;) I've actually wished for these functions for use with the returned pair of equal_range(). The begin() and end() aren't terribly important to me, though having the single function that returns a pair is. > Personally, I would prefer if there were separate functions to get the > respective iterator, especially as C++ misses such neat assignment > operations as there are in perl where you can assign to a list of > objects at once (well, I think there was a library for this mentioned > somewhere; was it Boost or have seen it in news: I don't know). Is Yes, it was posted to Boost. I like it. Here's how it would look with the graph interface: tie(first,last) = adj(v,g); A dumbed-down, two argument version is trivial to implement: template <class A, class B> class Tie { public: Tie(A a, B b) : first(a), second(b) { } template <class Pair> Tie& operator=(const Pair& p) { first = p.first; second = p.second; } protected: A first; B second; }; template <class A, class B> Tie<A&,B&> tie(A& a, B& b) { return Tie<A&,B&>(a,b); } Perhaps just specifying pair is fine, and leave it up to people's taste as to what they do with it. This is already the approach taken in STL. > it save to assume that the overhead involved in creating the pair, > returning it from a function, and selecting only one of the members > is removed by a good compiler, at least if the function is inline? If > not I would like to measure the effect of this before I would accept > it... My experience with SGI CC, Metrowerks, and KAI C++ would say the overhead goes away completely (and IMHO the bad compilers just need to get better). > Is the difference between "edge list iterator" and "edge iterator" > that the former iterates over the edges incident to a node while > the latter iterates over all edges of a graph? If this is the case, I > would suggest renaming "edge list iterator" into "incidence > iterator"! The names are otherwise too close to prevent confusion. > At least I know that I would keep getting confused... I agree, the names are too close. incidence iterator is OK with me. > Other than that, I assume that this interface is kind of a "complete" > interface conforming to several requirements which have to be > factored out: Not all algorithms need all of these properties and > thus it is neither necessary nor desirable to require all of the > properties. I made the same assumption in the list of operations > I posted. Yes, it should be factored. > Is the intention of the adjacency iterator convenient access to the > node descriptor or is for iteration over the set of the adjacent nodes > excluding multiply visiting a node? For the former case it would be > reasonable although counter intuitive since this iterator might visit > the same node multiple times if there are parallel edges. In the latter > case it is sometimes hard to provide, eg. if a list of incident edges is > stored. I really don't know which of these is the desired behavior. I'm not sure either. Perhaps we can find some algorithm examples where this makes a difference. > > >v = source(e) // I don't see a need for the graph object on this one > >v = target(e) > > Assume a graph representation using a vector for the set of > directed edges. Each node stores the index of the first and one > beyond the last outgoing edge. The incidence iterator can be a > thin wrapper for an integer which is desirable to have efficient > access to the edge ID for use in a property accessor mapping > IDs to properties stored in a vector. The edge descriptor can be > identical to the iterator. However, there is no way to determine Or the edge descriptor could just be the edge ID... > the nodes incident to the edge. The graph object would provide > somehow a reference to the corresponding vector where the edge > can be looked up and with it the corresponding node. > Thus, I think it is reasonable to provide the graph object for these > operations, too. If the operation is such simple that everything is > directly accessible from an edge descriptor, it is likely to be > implemented inline and a minor exercise for the compiler to be as > efficient with graph object as without. Fair enough. > Excellent: Looks like we get agreement on the graph interface > relatively fast, too! Now that is is basically nailed down, we should > invite other parties, eg. those from GTL and LEDA, to participate > in the discussion :-) Shall we start on a more formal write up of the interface? Which format do you prefer, latex? html? (please not MS word :) Do you want to focus on the write up for PropertyAccessor, and I on the traversal interface? One request that I have for the document format. The "concepts" should be documented similarly to Matt Austern's book (though perhaps using requirement tables closer to how they look in the standard). As to getting in touch with the GTL and LEDA folks, sounds good (though I have to admit I would not want to change much from our current interface). Cheers, Jeremy ---------------------------------------------------------------------- Jeremy Siek Ph.D. Candidate email: jsiek_at_[hidden] Univ. of Notre Dame work phone: (650) 933-8724 and cell phone: (415) 377-5814 C++ Library & Compiler Group fax: (650) 932-0127 SGI www: ---------------------------------------------------------------------- Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/1999/12/1152.php
CC-MAIN-2020-50
refinedweb
1,083
62.48
EonilFSEvents Eonil 2018 Maintenance. 2019 Maintenance. It's possible to use FSEvents directly in Swift, but it still involves many boilerplate works and subtle conversions. This library provides mostly-faithful wrapper around FSEvents feature tailored for Swift 5. Quickstart Import. import EonilFSEvents Start. try EonilFSEvents.startWatching( paths: ["/"], for: ObjectIdentifier(self), with: { event in print(event) }) Stop. EonilFSEvents.stopWatching(for: ObjectIdentifier(self)) Using Full Features Make a EonilFSEventStream, schedule it to a GCD queue, and start. let s = try EonilFSEventStream(pathsToWatch: paths, sinceWhen: .now, latency: 0, flags: [], handler: handler) s.setDispatchQueue(DispatchQueue.main) try s.start() After use, deinitialize by stop, invalidate(unschedule). s.stop() s.invalidate() As soon as the last strong reference gets removed, the stream will be destroyed. Caveats In the Xcode, AppKit apps are configured to use Sandbox by default. Sandboxed apps cannot access files out of its container. Therefore, it could look like it cannot receive file system events out of the container. To receive file system events out of container, you should turn off sandboxing. At this point, xcodebuild fails on dependency resolution for packages. I don't know why. It seems Xcode have some issues with it. To work around, just set SYMROOT explicitly. See test.zsh how to set it. Credits & License Copyright(c) 2018 Hoon H., Eonil. All rights reserved. Use of this library is granted under "MIT License". Github Help us keep the lights on Dependencies Used By Total: 0
https://swiftpack.co/package/eonil/FSEvents
CC-MAIN-2019-43
refinedweb
239
62.14
Comparison to Common Lisp and Scheme This page clarifies some differences between newLISP and Common Lisp and Scheme. Read the About page to find out more about newLISP's unique approach to LISP. The purpose of this comparison is not to point out that one language is better than the other. Different styles of programming appeal to different personalities. Each approach has different strengths and weaknesses. The notion that there could be designed a single, all-purpose language is naive. The author of newLISP uses 'C' and Java concurrently with newLISP. Others use a different set of tools tailored to the character of their projects and style of programming. newLISP's aesthetic, casual and flexible style has attracted not only the traditional computer programmer but many people from other professions. Many contributions to the design of newLISP come from people who are not primarily programmers. For many, newLISP is not only a programming language but also a tool for modeling and organizing creative thought. Scripting language versus compiled languagenewLISP is a scripting language designed not to be compiled but to be fully dynamic and introspective. Many of the differences to other LISPs result from this distinction. Both approaches have their place in modern computing. For a discussion of this subject see here: In Praise of Scripting: Real Programming Pragmatism. For more about history, critique and other aspects of Lisp see here. Openness and TransparencynewLISP is completely open. There are no hidden states. All language and data objects are first class. Although newLISP initially compiles program source into an internal s-expression-tree made of LISP-cells, everything can be serialized back to human readable text all the time. This includes the symbol environments in contexts (name-spaces) and lambda expressions. This openness eases interactive working and debugging and eases the understanding of the language. newLISP programs are fully self-reflective and can inspect and modify itself at all times. newLISP is network aware regarding file resources in a transparent way. In most instances where files are used, URLs can be used instead. Files can be read, written and appended, programs can be loaded or saved using the same code for local or network access. This facilitates writing distributed applications. Function application as in SchemeUnlike Common Lisp, newLISP and Scheme evaluate the operator part of an expression before applying the operator to its arguments. Lambda expressionsIn newLISP, lambda expressions are constants evaluating to themselves. They are a subtype of the list data type, a first-class data object that can be manipulated like any other list. In Common Lisp and Scheme, lambda expressions, when evaluated, return a special function data type forming a lexical closure after binding its free variables to the current environment. In newLISP, binding of free variables in lambda expressions takes place during application of the lambda expression without creating a closure. Lambda expressions in newLISP can be treated as data all the time, even after being bound in a function definition: (define (foo x) (+ x x)) => (lambda (x) (+ x x)) (last foo) => (+ x x) Other LISPs use lambda closures to create functions with state. Maintaining state is a precondition for a programming language to allow object-oriented programming. In newLISP, lexically closed contexts (namespaces) can be used to write state-full functions. Like lambda expressions, contexts in newLISP are first-class objects. Contexts can be created and destroyed during runtime, passed as parameters, and referred to by symbols. See the page: Closures and Contexts for a comparison of Scheme closures and newLISP contexts and see also the definition of def-static. One symbol spaceIn newLISP and Scheme, variables, primitives, and user-defined functions share the same symbol space. In Common Lisp, function symbols and variable symbols each use a dedicated name space. This is why Common Lisp function symbols sometimes must be prefixed with the sharp quote #'. Symbols in newLISP are case-sensitive. Dynamic scoping inside isolated namespacesnewLISP is sometimes criticized for using dynamic scoping and fexprs. These critics overlook that newLISP's namespace contexts shield function symbols from the traditional disadvantages of dynamic scoping and fexprs. In newLISP, all variables are dynamically scoped by default. However, by defining a function in its own context, static/lexical scoping can be achieved and variable capture can be avoided in fexprs. In newLISP, several functions and data can share a namespace. By enclosing functions in their own namespace, a lexical closure- like mechanism is achieved. Common Lisp and Scheme are lexically scoped by default and use lambda expressions as the closure mechanism. Common Lisp also offers special variables for dynamic scoping. The problems of free variables in dynamic scoping can be avoided. In the rare cases when free variables must be used, you can partition code into namespace modules for easier control over free variables. You can then exploit the advantages of dynamic scoping. With dynamic scoping inside lexically-closed namespaces, newLISP combines the best of both scoping worlds. newLISP has no funarg problem because it follows a simple rule: variables always show the binding of their current environment. When expressions with local variables are entered, newLISP saves the current variable state on a stack and restores it on exit of that expression. In newLISP, not only are function parameters and variables declared with let expressions local, loop variables in all looping expressions are local too. The lisp cell and consIn Common Lisp and Scheme, the cdr part of the lisp cell can be used to contain another LISP object, in which case we have a dotted pair. In newLISP, there are no dotted pairs. Instead, each newLISP cell contains one object and a pointer to another object if the cell is part of a list. As a result, cons behaves differently in newLISP than in other LISPs. ;; Common Lisp and Scheme (cons 'a 'b) => (a . b) ; a dotted pair [a | b] ;; newLISP (cons 'a 'b) => (a b) ; a list [ ] \ [a] -> [b] ;; LISP cells in newLISP (+ 2 3 (* 4 3)) [ ] \ [+] -> [2] -> [3] -> [ ] \ [*] -> [4] -> [3] Function arguments are optionalIn newLISP, all arguments to a user-defined function are optional. Unassigned argument variables will assume the value nil inside the function. Implicit symbol creationLogically, there are no unbound or non-existing symbols in newLISP. Any unbound or non-existing symbol is created and bound to nil in the current namespace when it is first seen by newLISP. nil and true are Boolean constantsnil and true are Boolean constants in newLISP. In Common Lisp, nil has an additional role as a list terminator: ;; newLISP (cons 'x nil) => (x nil) ;; Scheme (cons 'x #f) => (x . #f) ;; Common Lisp (cons 'x nil) => (x) Scheme has the two Boolean constants #t and #f for true and false. In newLISP first and in Scheme car will throw and error when used on and empty list. Common Lisp car will return nil in that case: ;; newLISP (first '()) => error ;; Scheme (car '()) => error ;; Common Lisp (car '()) => nil One Reference Only (ORO) memory managementIn newLISP, every object is only referenced once (ORO), with the exception of symbols and contexts. newLISP's ORO rule allows automatic, stack-based, on the go memory management, without the problems of traditional garbage collection algorithms used in other scripting languages. newLISP's ORO memory management is faster and uses less resources. newLISP passes parameters by value-copy and stores intermediate results on a result stack. The memory created for intermediate results gets recycled after function return. Like traditional garbage collection, ORO memory management frees the programer from dealing with memory allocation and reallocation. To avoid copying data objects when passing by value-copy, they can be enclosed in context objects and passed by reference. The following code snippet shows reference passing using a namespace default functor: (define (modify data value) (push value data)) (set 'reflist:reflist '(b c d e f g)) (modify reflist 'a) ; passed by reference reflist:reflist => (a b c d e f g) newLISP's automatic memory management is fully transparent to the programmer but faster and lighter on resource requirements when compared to classic garbage collection algorithms. Because ORO memory management is synchronous, newLISP code has constant and repeatable execution time. Programming languages using traditional garbage collection display sudden delays and pauses. The combination of newLISP's value-copy passing style and unique memory management make it the fastest interactive (non-compiled) LISP available and one of the fastest scripting languages available in general. As shown above, reference style passing is available, too. For built-in functions reference passing is the default. As a by-product of newLISP's ORO memory management, only the equal sign = is required to test for equality. Common Lisp requires eq, eql, equal, equalp, =, string=, string-equal, char=, and char-eq for equality tests of expressions, data types, identical objects, and referenced objects. Fexpr macros and rewrite macrosIn newLISP, special forms are created using fexprs defined with define-macro. Common Lisp macros use template expansion and compilation to create special forms. Special forms don't evaluate their arguments or evaluate only under special conditions. In newLISP, fexprs are still called macros because they serve a similar purpose to macros in other LISP dialects: they allow the definition of special forms. Fexpr's created with define-macro completely control when arguments are evaluated. As a result, newLISP macros can work like built-in special forms: (define-macro (my-setq x y) (set x (eval y))) ;; as hygienic macro avoiding variable capture (define-macro (my-setq) (set (args 0) (eval (args 1)))) newLISP can initiate variable expansion explicitly using expand and letex: (define (raise-to power) (expand (fn (base) (pow base power)) 'power)) (define square (raise-to 2)) (define cube (raise-to 3)) (square 5) => 25 (cube 5) => 125 Variable expansion can be used to capture the state of free variables. See an application of this here: The Why of Y in newLISP. newLISP frequently combines define-macro and template expansion using expand or letex. Variable capture in fexprs in newLISP can be avoided by either enclosing them in a namespace, or by using the args function to retrieve passed parameters, i.e. (args 0) for the first (args 1) for the second and so forth. Either way, the resulting fexpr's are completely hygienic with no danger of variable capture. In version 10.1.6, newLISP introduced rewrite-expansion macros in a loadable module. Since version 10.6.0, the same functionality is available with a built-in, native macro function working the same way: ; register a macro template (macro (cube X) (pow X 3)) ; during code loading the macros are expanded. (cube 3) => 27 The macros expansion facility hooks between source reading/translation and the evaluation process. In the example every occurrence of (cube n) would be translated into (pow n 3). This way the overhead of fexprs is avoided. Impicit IndexingnewLISP features implicit indexing. This is a logical extension of LISP evaluation rules overloading lists, strings or numbers with the indexing functionality available from built-in list and string functions like nth, rest or slice, i.e.: (set 'myList '(a b c (d e) f g)) ; using nth (nth 2 myList) => c ; with address vector (nth '(3 1) myList) => e (nth '(3 0) myList) => d ; using implicit indexing (myList 2) => c (myList 3 1) => e (myList -3 0) => d ; with address vector (set 'v '(3 1)) (myList v) => e ; implicit rest, slice (1 myList) => (b c (d e) f g) (-3 myList) => ((d e) f g) (1 2 myList) => (b c) Using implicit indexing is optional. In many instances it increases speed and readability. LinksAutomatic Memory Management in newLISP Expression evaluation, Implicit Indexing, Contexts and Default Functors in the newLISP Scripting Language Closures and Contexts in newLISP The Why of Y in newLISP History, Critique and Aesthetic Aspects of Lisp several links, several authors Scripting: Higher Level Programming for the 21st Century John K. Ousterhout In Praise of Scripting: Real Programming Pragmatics Ronald P. Loui About the newLISP the author Lutz Mueller.
http://www.newlisp.org/index.cgi?page=Differences_to_Other_LISPs
CC-MAIN-2016-30
refinedweb
1,988
53.71
This installment of Embed with Elliot begins with a crazy rant. If you want to read the next couple of paragraphs out loud to yourself with something like an American-accented Dave-Jones-of-EEVBlog whine, it probably won’t hurt. Because, for all the good Arduino has done for the Hackaday audience, there’s two aspects that really get our goat. (Rant-mode on!) First off is the “sketch” thing. Listen up, Arduino people, you’re not writing “sketches”! It’s code. You’re not sketching, you’re coding, even if you’re an artist. If you continue to call C++ code a “sketch”, we get to refer to our next watercolor sloppings as “writing buggy COBOL”. And you’re not writing “in Arduino”. You’re writing in C/C++, using a library of functions with a fairly consistent API. There is no “Arduino language” and your “.ino” files are three lines away from being standard C++. And this obfuscation hurts you as an Arduino user and artificially blocks your progress into a “real” programmer. (End of rant.) Let’s take that second rant a little bit seriously and dig into the Arduino libraries to see if it’s Arduinos all the way down, or if there’s terra firma just beneath. If you started out with Arduino and you’re looking for the next steps to take to push your programming chops forward, this is a gentle way to break out of the Arduino confines. Or maybe just to peek inside the black box. Arduino is C/C++ Click on the “What is Arduino” box on the front page of arduino.cc, and you’ll see the following sentence: “ARDUINO SOFTWARE: You can tell your Arduino what to do by writing code in the Arduino programming language…” Navigate to the FAQ, and you’ll see “the Arduino language is merely a set of C/C++ functions that can be called from your code”. Where we come from, a bunch of functions written in a programming language is called a library. So which is it, Arduino? (The Language Reference page is a total mess, combining parts of standard C with functions defined in the Arduino core library.) Maybe that’s not as sexy or revolutionary as claiming to have come up with a new programming language, but the difference matters and it’s a damn good thing that it’s just a set of libraries. Because the beauty about the Arduino libraries is that you don’t have to use them, and that you can pick and choose among them. And since the libraries are written in real programming languages (C/C++), they’re a totally useful document if you understand those languages. C and Assembly language, on the other hand, are different languages. If you’re writing assembler, you can easily specify exactly which of the chip’s native instructions to use for any particular operation — not so in C. Storing data in particular registers in the CPU is normal in assembler, but heroic in C. So if you start out writing your code in C, and then find out that you need some of the features of assembler, you’re hosed. You stop writing in C and port all your code over to assembler. You have to switch languages. You don’t get to pick and choose. (Yes, there is inline assembler in GCC. That’s cheating.) This is not at all the case with Arduino: it’s not a programming language at all, and that’s a darned good thing. You’re writing in C/C++ with some extra convenience libraries on top, so where the libraries suck, or they’re just plain inconvenient, you don’t have to use them. It’s that simple. A prime example is digitalWrite() in the Arduino’s core library, found in the “wiring_digital.c” file. It’s madness to use the ridiculously slow digitalWrite() functions when speed or timing matters. Compared to flipping bits in the output registers directly, digitalWrite() is 20-40x slower. The scope shots here are from simply removing the delay statements from the Blink.ino example code that comes with Arduino — essentially toggling the LED pin at full speed. Upper left is using digitalWrite() to flip the pin state. Upper right is using direct bit manipulation in C: PORTB ^= (1 << LED_BIT); Because Arduino’s digitalWrite() command has a bunch of if...then statements in it that aren’t optimized away by the compiler, it runs 28 times slower. (And worse, as you can see in the lower left, the Arduino code runs with occasional timing glitches, because an interrupt service routine gets periodically called to update the millisecond timer. That’s not a problem with digitalWrite() per se, but it’s a warning when attempting tight timing using the Arduino defaults.) OK, so digitalWrite() is no good for timing-critical coding. If Arduino were a real language, and you were stuck with digitalWrite(), you wouldn’t be able to use the language for anything particularly sophisticated. But it’s just a convenience function. So you can feel free to use digitalWrite() in the setup() portion of your code where it’s not likely to be time critical. That doesn’t mean that you have to use it in the loop() portion when timing does matter. And what this also means is that you’re no longer allowed to say “Arduino sucks”. Arduino is C/C++, and at least C doesn’t suck. (Zing! Take that, C++ lovers. De gustibus non disputandem est.) If you think that some of the Arduino libraries suck, you’re really going to have to specify which libraries in particular you mean, or we’ll call you out on it, because nobody’s forcing you to use them wholesale. Indeed, if you’re coding on an AVR-based Arduino, you’ve got the entire avr-libc project baked in. And it doesn’t suck. The “.ino” is a Lie So if Arduino is just C/C++, what’s up with the “.ino” filetype? Why is it not “.c” or “.cpp” like you’d expect? According to the Arduino build process documentation, “The Arduino environment performs a few transformations to your main sketch file (the concatenation of all the tabs in the sketch without extensions) before passing it to the avr-gcc compiler.” True C/C++ style requires you to declare (prototype) all functions that you’re going to use before you define them, and this is usually done in a separate header “.h” file. When C compiles your code, it simply takes each function and turns it into machine code. In a philosophically (and often practically) distinct step, references to a function are linked up with the compiled machine code representing them. The linker, then, only needs to know the names of each function and what types of variables it needs and returns — exactly the data in the function declaration. Long story short: functions need prior declaration in C, and your “.ino” code defines setup() and loop() but never declares them. So that’s one thing that the Arduino IDE does for you. It adds two (or more, if you define more functions in your “.inos”) function prototypes for you. The other thing the IDE’s preprocessor does is to add #include "Arduino.h" to the top of your code, which pulls in the core Arduino libraries. (And then, for some mysterious reason, it also deletes all comments from your code, making it harder to debug later on. Does anyone out there know why the Arduino IDE does this?) So that’s it. Three lines (or maybe a few more) of very simple boilerplate separate a “sketch” from valid C/C++ code. This was presumably done in the interest of streamlining the coding experience for newbies, but given that almost every newb is going to start off with the template project anyway, it’s not clear that this buys much. On the other hand, the harm done to the microcontroller newbie is reasonably large. The newb doesn’t know that it’s actually C/C++ underneath the covers and doesn’t learn anything about one of the most introductory, although mindless, requirements of the language(s): function declarations. When the newb eventually does want to include outside code, the newb will need to learn about #include statements anyway, so hiding #include "Arduino.h" is inconsistent and sets up future confusion. In short, the newb is blinded from a couple of helpful learning opportunities, just to avoid some boilerplate that’s templated out anyway. Write C++ Directly in the Arduino IDE And if you don’t believe that Arduino is C/C++, try the following experiment: - Save a copy of the example Blink project. - Go into the “sketch’s” directory and copy Blink.ino to Blink.cpp. - Re-open the project in Arduino and delete everything from Blink.ino - Add the required boilerplate to Blink.cpp. (One include and two function declarations.) - Verify, flash, and whatever else you want. You’ve just learned to write C/C++ directly from within the Arduino IDE. (Note: for some reason, the Arduino IDE requires a Blink.ino file to be present, even if it’s entirely empty. Don’t ask us.) main.cpp So if Blink.ino turns into Blink.cpp, what’s up with the setup() and loop() functions? When do they ever get called? And wait a minute, don’t all C and C++ programs need a main() function to start off? You are on the path to enlightenment. Have a look at the main.cpp file in hardware/arduino/avr/cores/arduino. There’s your main() function! And although we’ve streamlined the file a little bit for presentation, it’s just about this straightforward. The init() function is called before any of your code runs. It is defined in “wiring.c” and sets up some of the microcontroller’s hardware peripherals. Included among these tasks on the AVR platform is configuring the hardware timers for the milliseconds tick and PWM ( analogOut()) functions, and initializing the ADC section. Read through the init() function and the corresponding sections of the AVR datasheet if you’ve never done any low-level initializations of an AVR chip; that’s how it’s done without Arduino. And then we get to the meat. The setup() function is called, and in an endless for loop, the loop() function is continually called. That’s it, and it’s the same code you’d write in C/C++ for any other microcontroller on the planet. That’s the magic Arduino setup() and loop(). The emperor has no clothes, and the Wizard of Oz is just a pathetic little man behind a curtain. If you want to dig around more into the internals of the Arduino core library, search for “Arduino.h” on your local install, or hit up the core library on Github. The Arduino Compile Phase So we’ve got C/C++ code. Compiling it into an Arduino project is surprisingly straightforward, and it’s well-documented in the Arduino docs wiki. But if you just want to see for yourself, go into Preferences and enable verbose logging during compilation. Now the entire build process will flash by you in that little window when you click “Verify”. It’s a lot to take in, but it’s almost all repetitive. The compiler isn’t doing anything strange or unique at all. It’s compiling all of the functions in the Arduino core files, and putting the resulting functions into a big (static) library file. Then it’s taking your code and this library and linking them all together. That’s all you’d do if you were writing your own C/C++ code. It’s just that you don’t know it’s happening because you’re pressing something that looks like a play button on an old Walkman. But it’s not rocket science. There is one more detail here. If you include a library file through the menu, and it’s not part of the core Arduino libraries, the IDE locates its source code and compiles and links it in to the core library for you. It also types the #include line into your “.ino” file. That’s nice, but hardly a deal-breaker. If you’d like to see this build process in the form of a Makefile, here’s (our) primitive version that’s more aimed at understanding, and this version is more appropriate for production use. Next Steps If the Arduino is the embedded electronics world’s gateway drug, what are the next steps that the Arduino programmer should take to become a “real” embedded programmer slash oil-burning heroin junkie? That depends on you. Are you already good at coding in a lower-level language like C/C++? Then you need to focus on the microcontroller-specific side of things. You’re in great shape to just dive into the Arduino codebase. Try to take a few of the example pieces, or even some of your own “sketches” and look through the included Arduino library’s source code. Re-write some simple code outside the IDE and make sure that you can link to the Arduino core code. Then replace bits of the core with your own code and make sure it still works. You’ll spend half of your time looking into the relevant micro’s datasheet, but that’s good for you. Are you comfy with electronics but bewildered by coding? You might spend a bit of time learning something like C. Learn C the Hard Way is phenomenal, and although it’s aimed at folks working on bigger computers, it’s got a lot of the background that you’ll need to progress through and beyond the Arduino codebase. You’re going to need to learn about the (relatively trivial) language conventions and boilerplatey stuff to get comfortable in straight C/C++, and then you can dig in to the Arduino source. Wherever you are, remember that Arduino isn’t a language: it’s a set of libraries written in C/C++, some of them really quite good, and some of them (we’re looking at you EEPROM) simply C++ wrappers on the existant avr-libc EEPROM library. And that means that for every Arduino project you’ve written, you’ve got the equivalent source code sitting around in C/C++, ready for you to dig into. Thank goodness they didn’t invent their own programming language! 157 thoughts on “Embed with Elliot: There is no Arduino “Language”” /TIC NO, STOP !!!!! Is it too late to get this posting deleted !!! Don’t tell these people that they are coding, are you nuts !! Its like telling your brother he is a chef, just because he can boil water. Once people learn that they have been coding all this time, they will drop this hobby. WHY, you ask ? Because engineering is too hard for a Liberal Arts types. Girls can’t code, they have been taught this through out history ! No, keep telling them all they are writing sketchs ( or what ever they call them). That way they won’t give up and say its just too hard for a poor kid like me. /TIC You forgot to mention the people who put the posts up here think they’re ‘writers’, ‘journalists’, ‘editors’ or some such nonsense. !TIC And some think they are funny. ( but which one ) Genius! anyway, in my part of the world we wouldn’t even bother putting the /TIC… That would make the comment even more TIC. PS: TIC = Tounge-In-Cheek Thanks, I have never seen TIC anywhere else used to describe tongue-in-cheek and was about to ask what the heck you were going on about. I thought it was a facial tick; twitching from anger. This is a great break down. Thanks. Great writeup. I find it to be the gateway drug, and look forward to learning more and getting down to the basics of microcontroller programming. I would expect that digging into the libraries and writing to raw c code streamlines the functionality….and the more streamlined the project is, the less problems you can expect. Thanks. Arduino was my gateway into programming :) but I did a bit more research then a normal person would do, and found it to be just c/c++ so I started learning that, and soon after started doing bare-metal programming on the avr’s :) I do Program using the Arduino libraries sometimes, cause it’s nice and easy, and sometimes handy to work out an idea. This is a great break down of what’s happening behind the scenes with the Arduino IDE. Thanks! What’s in a name? I know where the urge to argue about names and definitions comes from (a very nice explanation is at), but do we really care?. I think the whole point of Elliot’s exploration is to get us out of the rut where we’re telling people that they’t not coding, they’re sketching. This is a different type of barrier where people then think “I can’t code, all I’ve ever done is screw around with Arduino”. Instead let them know that coding is easy. But great coding takes practice, study, talent, and interest. In closing, “crappy C++ code” will always be written. Hiding the fact that people are writing C++ won’t help that. But educating them to encourage learning more about the language might. I can’t agree more. I went to school, but struggled with a lot of C++ coding. I ran across AutoHotKey in the windows environment a while back which is essentially a macro writing “language” that is nothing more than some nicely simplified libraries for C++. It’s not the fastest or must efficient by far, but it does make putting together a program with menus and a GUI pretty easy for someone. I think Arduino is similar (except there s a more comprehensive IDE available for AHK) in that you are coding, but it simplified for people that don’t need the fastest or most efficient code. The problems I see is that a LOT of Arduino example sketches and libraries are poorly commented and documented. when you want to change things, it’s really hard to figure out the correct function call in a library to perform. Telling people they aren’t coding isn’t really a solution. Proper coding technique should always be used even if your comments are 10x the side of the code. AHK is great and was much more approachable for me too. I’ve saved countless hours of work (at work) because of it. C++ was a tougher nut to crack but with a class of it at uni and some time to let it sink in, it is now easy enough for me. Really? I see a similar problem on many of these… ahem sketches that I do with PHP as opposed to AHK. That many of the people don’t know HOW to write good code, period. Comments aside, I’ll see dumb little things like decrementing counters inside loops that have an incrementing (and unused) counter. Just use the same decrementing counter for the loop or rearrange your code to use the incrementing counter instead. Or a common problem with Ardurino fans, last I checked, is strings and string manipulation. A) they don’t realize how C manages strings B) they don’t know how to store immutable strings properly (hint, don’t bother copying them to RAM) and C) have absolutely no clue how to pack, reduce, or reuse their strings. The Analog functions are (were?) a mess. I was handed a sketch to fix and the Analog functions were so hard to unravel that I simply threw away the entire mess and rewrote it all. At least Arduino isn’t as bad as PHP. Arduino invites bad code and rarely punishes the user for it. PHP begs, pleads and demands bad code and punishes you to your face and stabs you in the back. Does it matter what language you write your code in for it to be called coding? So only C/C++ is coding, and nothing else is? No, the point is that Arduino calls it “Arduino language” while it’s really just c/c++ and not it’s own language. Every programmer uses pre-created tools all the time. The choice of what abstraction layer you work at is mostly arbitrary. Even Assembly (especially on x86, but really just about anywhere) should be considered a high-level language these days. Real programmers use discreet parts to program. Real programmers turn into managers so they don’t have to program anymore The reality of your comment hurts. I still have trouble calling sketches C++, C yes with some limited C++ functionality (objectality?). I know a few phrases in French but I don’t call myself bilingual. I simply must tell a joke at this point. Q: what do you call someone (in english) who speaks 3 languages? A: trilingual Q: what do you call someone who speaks 2 languages? A: bilingual Q: what do you call someone who speaks 1 language? A: an american (laugh. its funny. and a little bit true). Most people who take up a second language choose English – and there’s a reason for that. And it’s my observation that most people who say they speak another language really do not. They know enough to answer “Do you speak English?” with a smile and a bashful “Yes” and after that… Nada! I know right!? Arduino “C++” is really just like a stripped down C++, practically just C but with classes. It has no support whatsoever for anything like flexible declarations, new, delete, scoping, or even function overloading. Wait…is there a “g++” at the end of that “avr-“? “no support whatsoever for … even function overloading.” – Where did you get that idea? Overloading is implemented and is used pretty extensively by the Arduino core (in particular, by Print()) I throw out the whole Arduino ide and library right into the thrash a few days after I bought my first arduino. Seriously, the ide is totally inconvenient and the functions in the library are messed up like hell. And for what? Nothing. It just calls gcc+avrdude and that’s all. Well I can also do that, thank you very much. Just download WinAVR, it’s the same thing, except it doesn’t take years to unzip. And for the editor, I like to use something that’s actually useful, and not slowing me down. (e.g. notepad++) I would rather program in vi on a 80*25 char monochrome screen than to use arduino ide. So the arduino ide is not, repeat, NOT coding. It’s just playing with electronics for 8-year-olds. If you want to code, write a makefile and a proper c code, open up a command line, and use normal tools. [ ok ] Transferring enormous rage…done I like the IDE for “press button to compile and upload everything without fiddly bullshit”. Other than that, yes, I agree. The “Use External Editor” preference is the way to go. +1 for contextual hardware and programmer selection. The IDE has driven me batty on a few different occasions. Just the find/replace tools are enough to pull your hair out. But, it is FOSS and improvements are a possibility. I’ve got cheap, used chipKIT Max32 with network shield. they use Arduino-based MPIDE. I ran it once and replaced it with UECIDE, just because I like my IDE to be more than fancy version of notepad. Gah, no! Two words that need to change are the “verify” and “upload” to “build” and “flash”. Don’t know why it pisses me off so much… To top it off, it always rebuilds when you upload – even if you just built it. sounds like someone has a case of the mondays…. (runs away…) ;) F*ckin’ A man I use Sublime + Stino It is awesome! Say what you want it’s hella convienient. Doubtlessly the minor “white lies” it tells improve access to microcontrollers. Anyone who wants to will quickly move away from it and delve deeper. Thank you for this post– Though I always use C/ASM on PIC/ARM, for the ‘simpler’ projects on Arduino this is one of the questions I ‘highly expected’… But was just ‘too afraid to ask’. So, I’ve been into 8 bit AVR’s since the STK-500 days and I do have wicked love for AVR libc and avr-gcc. I don’t care for C++, I find (like most people) the Arduino IDE lacking. With that said, I think Arduino is absolutely wonderful anyway. Nano and mini clones are dirt cheap. You just dowload the IDE and install one thing and you’re off. This enables just about anyone who wants, to reflash my firmware replacement(s) for the STC-1000 thermostat, for just a few bucks and a few minutes of spare time and without a degree in CS. If this gets you exited, to after a few minutes of playing, being able to flash a LED, then read a sensor, control a motor or whatever. Then it is a good thing. You can eventually learn proper C/C++, if you want to, or just be satisfied with playing around. If a kid is exited about playing an instrument, would you rather not have him/her loose interest learning to read sheet music BEFORE allowed to try or would it be ok to not know the chord names and juat bang out a few three chord songs to get them up and running? Well said. I share your “genesis story” coming up with AVR’s before Arduino. AVRfreaks is a huge help in learning all the ins and outs of these chips. I’m always a bit suspicious of what hardware the Arduino code is using and how it might mess up my use of timers and interrupts. It’s hasn’t bitten me yet, and Elliot’s exploration of the back end of things is quite helpful. look in the library code and see- it is all there, usually reasonably well documented …which is essentially the point of the article. I agree. It does a good job of getting newcomers interested without overwhelming them. Also, I like your music analogy. “Stop telling {kids who bang out three chord songs} that they are {playing an instrument}, it encourages a culture of crappy {instrument playing}. There IS a right way and a wrong way and {banging out three chord songs} doesn’t do anything to help show the difference.” I guess the folks I was aiming the article at are the folks who are currently using Arduino and asking, “what’s next?” I think the Arduino docs/community/webstuff does a good enough job roping in the newbs. I’ve seen people who buy the hype that there’s something unique about Arduino, and that blocks them in moving forward because they think that writing code outside the Arduino libs is somehow different. “Oh, I could never learn C/C++, so I’ll just stick with Arduino.” Those are the ones I’m trying to get over the hump. I’ve been playing with the attiny13 reducing code bloat is required learning. I’ve been loving it! This info is targeted straight at me. I always thought what was written to the “Arduino” boards was different than what was written to an AVR. Is the code compiled down to the same hex file and just flashed to the chip? Or is there something different on an Arduino (bootloader?) that makes it easier to write to? I started with ATtiny’s and AVR-dude, and would have never thought it as easy to implement USB as it is with an Arduino pro-micro and using it as an HID board. Arduino boards have a (pretty standard) bootloader on them so you don’t need a separate ISP programmer, but otherwise they’re bog standard boards. Some of them (Uno) have USB interface ICs onboard, and some (Leonardo) have built in USB support. Trav, Please do not take offense to my comment. Here is a good example of a non-engineer making a guess on how microprocessor software development works. Yes, the code compiled down IS the same hex file that is flashed into an AVR chip. There is a step never discussed called “linking” that creates that hex file. If you check the directory that the source file live in, you will see said .hex file. There are added code to facilitate the ease of use that the Arduino environment brings to developing code. These “hidden” features, such as linking is required but has not been discussed here as its one of those magic steps that is just done by the IDE. I remember when I first started programming microcontrollers I was using Arduino. At the time it only supported the ATmega8 and ATmega168. My ATmega8 was running out of room and I figured out that all the Arduino core libraries were compiled in regardless of whether I used any functions in those libraries. I compiled my sketch directly with WinAVR, with the options enabled for dead code elimination, and suddenly I had a bunch of space. After that I started programming with WinAVR it gives you a lot more control and your codes runs faster, since it’s not slowed down by virtual pin mapping. It’s a shame more Arduino users don’t move past the Arduino IDE, you can still use the entire Arduino core or you can just use a single library. If you only use a single library without the core you’ll have to edit the library and replace the references to the virtual pin mapping with pin macros. Eclipse has an WinAVR plug-in, but personally I like editing my code and make files with notepad++ or programmers notepad and calling the compiler from the command line. I think there’s an audience of people who really don’t want to be coders. They just want to do some cool thing. Most of electronics these days is sensor–>processor–>UI, and most electro-mechanical is software driven, so that puts us in the unenviable position of having to code to get our projects to work. But we don’t want to have to learn the subtle intricacies of some new processor and some new compiler, we just want the thing to do what we want it to do. So for us Arduino is perfect – extract from a couple of samples, look up a few libraries, stitch it all together and bob’s your uncle. And the industry obviously sees this – how many low cost modules are coming out from name brand electronics manufacturers and how many multi-thousand dollar dev environments are now free. And remember when JTAG programmers cost $1500? Arduino is a revolution. DougM As a geek who’s been learning C since I could get a Slackware CD and an old computer to install it on, the Arduino was great! Sure, if you knew someone else with a chip flasher, you could build a parallel port chip programmer pretty cheap; but I didn’t know any one else and couldn’t find one. I went to university and learned C and C++ (and the difference between the two) and picked up C99 for embedded programming even though I had nothing to program on. Why didn’t I get a PICKit or AVRDude or something else before the Arduino? Do you remember what the prices on those were back in the 90s? If you could find one at the Shack it would be near $100, and if you were lucky enough to have a Digikey or Mouser catalog it was still over $50. If I had gotten into an embedded course, the boards used there were $300 or so. The $30 Arduino just broke the price point and told the old guard that the old ports weren’t needed for the bargain boards. And it’s changed the embedded chip landscape in relatively short time. Thank you for making this article.. It clearly explains what I’ve been trying to make some people understand for a long time. Rants like this drive me nuts. Get over yourself. The Arduino platform wasn’t designed for hardcore embedded systems junkies. It was designed for students, artists, and hobbyists without a computer science or electrical engineering background. It is precisely for this reason that I used it to teach a beginners embedded systems class for three years when I was an undergrad. Yes, the “Arduino Language” is C/C++ and yes, you could program things JUST as effectively in another editor with the same compilers, libraries, ect. The reason Arduino has taken off the way it has is because it hides all the messy, confusing bits off to the side which prevents folks who have no prior programming background from getting overwhelmed and quitting. After folks play with the IDE and dev boards long enough, they start to find the drawbacks to using the stock libraries and the IDE as a whole and start finding forums and amateur white papers explaining how to do things more efficiently without libraries and such. They learn proper code and AVR tricks as they develop their projects and grow as engineers and coders. A bit of a side note, but don’t hate on the “sketch”. The Arduino environment is a development environment and not meant to be used in a final consumer product. The whole idea is to write a bit of code, slap it on a processor fast, and then test it out. If you don’t like it, tweak it, and try again. It is very much like sketching out ideas on an artist’s pad. It sounds like you had in mind a different audience than I did in writing the piece. This was not intended to be an article for beginners, and I’m presuming a kind of intermediate level of knowledge that I think a lot of our readership has. (I don’t see beginners reading a column with “Embed” in the title either, so I don’t think we’re deceiving anyone.) The idea behind the article was to help demystify the way “Arduino…hides all the messy, confusing bits” for people who are at the point where they _want_ to understand those particular bits. I dig it, thanks Elliot. Actually never used Arduino, myself, but always had a vague idea it was something along the lines you described here. I’ve taken kinda a backwards-intro to Arduino, but this was exactly what I needed to do-so. If they’re not meant to be used in the final product someone might want to tell this guy and the shitload of others doing similar. You forgot to mention the stupidest thing about the Arduino IDE. It’s written in Java. But you can escape, and use vim and make instead. See LOL Java amrite? LOL PHP amrite? LOL JS amrite? LOL Go amrite? LOL Swift amrite? LOL SCSS amrite? LOL DELPHI amrite? LOL {EOL} amrite? Can we please stop making fun of people, because {x} is the only language to be taken seriously. That is just stupid. Like you need to distance yourself from everything that is not {x} and cant be taken seriously because you work with {x} since 2-20Years and already lost the ability to look beyond one’s nose. What are you? 14? Can we please not stigmatize people because of the compiler they are using? Are you calling yourself an evangelist too? Because you sound bigoted when using that term. If your language is superiorin in every way, I wonder why it is not used as the main tool for the job. Maybe… just maybe you are not right that your language {x} is the soltution to every Problem. Try to comprehend that for a change… LOL PHP amrite? LOL PHP amrite? LOL PHP amrite? As much as I detest Java and Arduino, that argument holds virtually no merit. I wrote emulated hardware using Python connecting to an ARM controller simulating two Serial ports I wrote in C attached to an AVR running what I wrote in ASM to debug an Android App I wrote in a subset of Java. Oh yeah… I’m doing it all inside of Win8.1. :D cool, i can dust off this old article for this excellent quote :) “Arduino: baby-talk programming for pothead” – ArnoldB, AVRfreaks.net Loved that article when it came out. And you are still right, four years later. I certainly hope that this article didn’t come across as my harshing on the Arduino libs. By pointing out that there’s nothing much to Arduino but libraries, I actually intended to dispell some of the Arduino bashing of exactly the ArnoldB variety. Using libraries to get coding done is what all professional programmers do all the time. Easier, clearer, better-debugged libraries are better than the opposite. And I think the (mostly community written?) libs are a huge part of why Arduino won. Using good code libs isn’t “baby talk”, it’s best practice. But exactly because Arduino “won” and got a lot of people into the hobby, there are a lot of people wondering “what’s next?” and feeling trapped by the slightly black-boxy presentation of the Arduino IDE from the outside. The article was meant to be a look into the black box, and an encouragement to look further. This is Hackaday, after all. About half of our readership use screwdrivers to turn screws and build things. The other half use them as ghetto pry-bars to get into sealed plastic cases and figure out how things work. I like to write for the latter. I really liked your article; it’s nice to know what’s going on under the hood. Several years back I was using an ATtiny micro and trying to get it to play nicely with a character LCD I bought off ebay. I used 3 Libraries I found on the internet that should have work but didn’t. The ATtiny wasn’t supported by the Arduino IDE, but the according to the Ebay description the LCD worked with Arduino LCD library. So I took the Arduino LCD Library deleted the references to wiring_digital.c used pin macros and compiled it in WinAVR. Everything worked perfectly and it made my life easier. Good article for the great unwashed. :-) A couple of minor points to add. Using the PIN register is the fastest way to toggle a pin. So instead of: PORTB ^= (1 << LED_BIT) use: PINB = (1 << LED_BIT) And to use the Arduino (Wiring) libraries but with a much faster digitalWrite, go with Wiring 1.x. Download it from wiring.org.co. I rejoiced when I discovered this trick. Even wrote an article about it: The only comparable “eureka” moment was when I discovered bit-banding in ARM chips. Brilliant silicon design that allows you to change 1’s to 0’s and 0’s to 1’s at the same time without performing a read-modify-write instruction. Can you elaborate on what you mean about ARM bit banging? Do you mean the separate set and clear registers that some(most?) have? i.e. writing 0x11 to the set register sets bits 4 & 0 to 1 without clearing the rest. It is something I’ve wished the AVRs had when I’ve been writing bit-banged UART and SPI code. It’s bit-banding, not bit-banging. It’s where (for the special bit-band memory region) they map each individual bit to it’s own word in an “alias” region. This let’s you change a single bit by writing to the corresponding alias word. You can see a brief description beginning on page 15 of this PDF: Or you can google it and maybe find a better description / example. Bit banding solves the “atomic bit access” problem in an arbitrary address space, so it works in RAM, or on peripherals (usually. It depends on vendor choices.) Most ARM chips aimed at replacing microcontrollers have also implemented Clear/Set/Toggle registers in their GPIO peripherals, which achieves about the same thing for most cases. (I guess bit-banding could save a conditional jump in an arduino digitalWrite() like function, iff you wanted to enforce that the “true” value for pin state had a 1 in the lsb…) The ARM Cortex M bit-band alias comes very handy when working with monochromatic graphical LCDs. The difference between the two operations is that you’ve totally clobbered the entire register with the simple assignment rather than the |= , ^= way where only one bit is modified. They’re different things, really. But yeah. That’s the “20-40x” faster in the text. The simple assignment is another factor of two faster than the read, write version. I didn’t know the the Wiring libraries had sped up digitalWrite. That’s good to know. Thanks! (Seems to me that digitalWrite() could be implemented in a pre-processor macro, and thus costless, for most cases except where you’re dynamically allocating pins based on user input. I wonder why they didn’t go that way?) Two reasons I’ve heard mentioned: 1) Arduino uses an older version of GCC, which lacks some optimizations found in newer versions, and are needed to do that properly. 2) Consider what happens with code that *relies* on digitalWrite() being slow. For example, if someone is bit-banging a serial protocol using digitalWrite(), chances are it already runs slowly enough that they’ve never needed to even consider the possibility that it might need to be slowed down. And even if they did, perhaps they deliberately omitted timing loops, since under normal circumstances it would make something already too slow even slower; if the timing loop finds it can immediately exit, there is still some overhead for the check. Should a new version of the environment be able to substitute a faster digitalWrite() under certain circumstances, it would break some existing code, make execution times unpredictable, etc. Seriously? Do this… FastDigitalWrite () Done. Don’t like that? Then overload DigitalWrite() with an extra flag to force the newer code or default to the older code. C’mon guys, all the major languages figured it out…. except for maybe PHP…. There’s some interesting discussion of attempts to make digitalWrite() faster here: and here: Thank you for those links. That clears a lot up. I should have been more careful about posting at 2am. DDRB |= (1<<PB5); evaluates to an sbi call, which takes two clocks. DDRB = (1<<PB5); evaluates to an ldi and an out, which also takes two clocks. "Potato, potatoe" as Dan Quayle used to say. “you’ve totally clobbered the entire register”… Nope; writing to PINX (which used to be an input only register, back in the Atmega8 days) atomically toggles ONLY the bits that are one in the byte you write. Just like the “xxxTOG” registers in some newer processors with lots of address space to throw away. It’s a bit un-elegant, re-using a register that way. But occasionally useful. pre-processor based digitalWriteFast() has been done, but it’s pretty gross. An inline function can do a good job, but it needs an extra copy of the pin abstraction data, since the compiler optimization doesn’t know about PROGMEM. (Hmm. Didn’t know about. I wonder how it does now, with the new “named address space” feature. (Which, alas, C++ doesn’t support.)) I’ve been playing with an ARM recently, and one of the interesting observations is that the ratio of “optimized constant-based digitalWrite() to full variable-based digitalWrite is about 4:12 instructions, rather than 1:50 as for the AVR. OMG. He was writing to PIN in output mode. I didn’t even know about that trick. Learn something new every day! Talk about a way to produce unreadable code. Re: digitalWriteFast(). Yeah, I quickly read through that thread (linked, above) on arduino.cc. It looks like making the best of a bad situation, honestly. I wonder how many people know it’s there / care / use it. Half of the time, I think all the speed stuff is pointless for most people, and then you see something really simple like an IR receiver that needs more speed than digitalRead() has (according to). But also, re: the whole darn thing. If the Arduino folks just labelled the pins PB3, etc on the board, there’s trivial macros that would make everything work. Trying to shoehorn the physical device into the abstraction rather than make an abstraction a convenient / simplified representation of the device is the problem, IMO. It’s always going to be leaky or clunky. Re: ARM. Is it the compiler? Cool. I just figured out how to create a filter in gmail to send all emails with in the subject line to the trash. Isn’t technology wonderful? Let me try that again: I just figured out how to create a filter in gmail to send all emails with ‘There is no Arduino “Language”’ in the subject line to the trash. Isn’t technology wonderful? >> “emails with ‘There is no Arduino “Language”’ in the subject line” Or you could have clicked on the [ Unsubscribe from all follow-up comments ] link in those same emails. Isn’t reading wonderful. Re ARM: special “IO addreses” or instructions are anathema to RISC architectures, and I don’t think you can do a write (any value) to an arbitrary memory location in less than three instructions. (load (base)address into one register, load value into 2nd register, write value to (possibly)indexed address. The 4th byte is because Atmel (at least) made the gpio ports 32bits wide, and the “move immediate” instruction is limited to 8bits (in it’s 16bit version.) Of course, if they’d done that, then as soon as they introduced the Mega or the Leonardo, everyone would have had to rewrite all their code. Wait… WHAT??? Since When?! Or, more importantly, I guess… who needs to *toggle* a single pin that often…? The only cases I can think of, off-hand, is for “blink” (which doesn’t need to be fast), a bit-banged serial-clock or maybe bit-banged NRZ-encoding? Regardless, of my lack of use-perception at the moment, handy trick for future-reference. Thanks. Google and you will understand. Hmmm, take two WS2812B + Arduino I believe the reason they called them ‘sketches’ and not ‘programs’ or ‘code’ is that they are trying to reduce the fear-factor of new folks getting into the controller scene. that’s a perfectly valid way, too; its less scary to think you are writing ‘sketches’ rather than programs. to us who are software people by education or trade, its just a word game. you are still writing code. it does not matter (should not matter) what you call it, for us. we are not timid about controllers or programming. why are so many of US so annoyed at the terminology that is meant to make things easier on the new folks? I do think that removing ‘main()’ was a mistake. this is not a hard concept to deal with. and if you are going to code in C, you do have to understand forward declarations; and when the system does too many things for you, its going to be THAT much harder to jump into (cough) real programming, later on. as for the IDE, its minimal functionality but that’s also an educational thing. first, its on all 3 platforms and that’s a bit of work as it is. its dumbed-down on purpose so that the basics can be done and there’s less scary stuff or clutter in the menus. I’ve been able to write 13k lines of C with the crappy IDE. its not fun, but its do-able. the lack of debugger is the bigger problem, not the editor/gui. then again, some so-called professional ARM tools don’t have debugges (I attended a company demo where they ‘only had printf’ as the debug tool; and this is a commercial vendor, not some maker-thing!) Remember the whole Arduino (TM) thing? I think it is more of their nature to want to Trademark those names… They can’t exactly can’t really trademark C and C++. So we should call math “fuzzy-kitty-petting”? It won’t make the theorems any easier to prove. (I don’t think the “sketch” thing matters one way or another, honestly.) I’m not sure which of the Arduino conveniences are the key to its success, and I’ve thought about it a lot. My guess is that it’s the quality/range of the libs. Want an LCD? Lib. Want an SPI EEPROM? Lib. Oh, and the IDE / all-batteries-included toolchain in a box. I think that stuff matters a lot more than fuzzy kitty petting, but I could totally be wrong. What goes around ….. Years before Arduino, I had helped some friends get started with an Atmega32, AVRISP and WINAVR. All command line driven. One of those friends told me a few years later, “you should have shown us the Arduino Compiler” !! :-D And before Arduino there was Basic Stamp and Basic52-based SBCs. Whose target audience was similar ,and whose performance was worse, and higher cost, for the same groups of people who didn’t want to have to learn too much. And they were both revolutionary game changers as well. But … a lot harder to break out of, going from an interpreted baby language to the assembler or bare C that was the alternative. In fact, for someone straining at boundries, Arduino might be a FINE starting place. If you were using Atmel ASF, or STMCube, or Tivaware, your implementation of “port_pin_set_output_level()” (the ASF equiv of digitalWrite()) might be a LOT harder to follow than the arduino code. Thanks to layers of abstraction that “real” coders put around things that they expect might have to work on several hundred different chips, rather than just “a few.” That’s sort-of sad. >Thank goodness they didn’t invent their own programming language! yeah, like apple, google and MS did? yup, ever single one of those have looked at C and said ‘thanks, but we’ll start all over from scratch and do our own thing’. really absurd when you think about it. you used to be able to know C and get software jobs. now, the language explosion is totally out of hand and its too wasteful to keep trying to be good at large numbers of languages. so, at least arduino is still basically C. they could have pulled an apple/ms/google on us and really full-retard. I started programming around 33 years ago. In that time I’ve programmed in Basic, Assembly, C, C++, FORTH, FORTRAN77, Java, JavaScript, PHP, PERL, Pascal, Delphi, ActiveX, ColdFusion, plus spinoffs like Allen Bradley ladder logic, R, SQL, bash, and probably a few more I’m forgetting. And wanna know something? I’m kinda tired of it. I like having high-level constructs in place so I can focus on my desired purpose and overall logic rather than worry about null pointers and other fiddly syntax gotchas. Yeah, maybe the current incarnation of “the Arduino Langauge” is a thin skin overtop of generic C/C++. Maybe it’s a little disingenuous to call it its own “language”. But I’ll say that even as someone with decades of programming experience, if Arduino was any closer to bare metal programming, I wouldn’t even be here. Right now I just want to dabble with blinky lights, and remote controls for my camera, and making tangible electronic things to play with. Having to write code to make them work is an unfortunately necessary evil and the simpler and more invisible that part is, the happier I’d be. I actually wish Arduino were even more abstracted from the C/C++ world and I’m quite happy to think in terms of “sketches” rather than gcc compiler flags and whatnot. As a fledgling “arduino programmer” I greatly appreciated this article. I had strongly suspected that it was all C/C++ under the hood but was somewhat discouraged from poking around because “I’m not a real programmer”. Looking at things this way makes me more apt to learn proper C/C++ coding conventions and work from there rather than following the standard blueprint of “what do i need to accomplish? has someone else done it? oh this guy did something similiar, can I adapt his code to suit my needs? Too bad its written in C and thats not compatible with the ‘arduino language'” So you want to blink an LED. How? First, refer to the data sheet for your specific chip to see which port/pin you need to use, then set up the port appropriately, and then use funky C notation which looks like line noise. Or just use digitalWrite from the Arduino domain specific language. Which is easier? Sure, to an experienced C programmer familiar with embedded systems and AVR in particular, this is all unsurprising stuff. People using Arduino are not C programmers and are not familiar with embedded system design. Arduino is not C. It is not intended for writing timing-critical control systems. It is a tool set for people wanting to build cool stuff quickly. You’re totally right! Using bitwise logical operations to turn on an LED is a huge barrier to newbies. A ton of “real” C programmers don’t ever do low-level bit manipulation, and it’s nearly as bad for them. In that sense, you totally can’t complain about digitalWrite(). But, ummm, Arduino _is_ C (with some libraries). I think that’s even in the title of the article. :) Point is, you can choose, without giving either up. Direct port assignments if/when it counts, and digitalWrite() otherwise. Precisely because Arduino is C (libraries). Bravo for you! I wrote a medical billing database in C on Interactive Unix 386 boxen back in the mid 80s – early 90s. Learned C with K&R’s “The C Programming Language”. We started coding it BEFORE there was a C++, but took some of the object oriented ideas and used them by creating structures with references to functions. So… I’m an old guy. I started playing around with Arduino in the last couple of months, and was amazed how easy it was to get back onto the coding bicycle. I *was* curious about all the “Man-behind-the-curtain” stuff that’s obscured by the Arduino IDE. Thanks for clearing that up for me. Interestingly, about an hour before I read your article, I sent an email to another coder about one of my Arduino projects and was complaining about “Why in the HELL do they call it a “sketch” when it’s obviously C/C++ code?”. OooooooooOEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEOOOOOOOooooooooooo! I would also like to know if the gcc that comes with the package supports C++11 (yeah the compiler will probably be ok but what about the standard library?) Also, C/C++ does NOT require you to declare the functions before they are defined. They just need to be defined/declared before they are used. This is perfectly fine: void do_something() { // bla bla } int main() { do_something(); return 0; } Actually in this case they have to declare setup() and loop() before main() because Arduino user is not required to use both of them in a sketch. The only reason setup and main are declared is so that they can be referenced from main in a different source file. They’re both required: try taking the Arduino bare minimum sketch, removing setup(), and hitting compile. It will fail. There is essentially no libstdc++ for AVR, so you can only do things that don’t require library support. I don’t know if it’s a magic flag that AS sets, but my current ARM experiment spits out warnings if I don’t have a prototype before the definition… led_toggle.c(103,6): warning: no previous prototype for ‘digitalWrite’ [-Wmissing-prototypes] void digitalWrite(uint8_t pinno, uint8_t level) As .ino files have to be pre-process into .cpp before beeing compile by gcc one can’t say it is C/C++ code. here a surprise I had first time and only time I used Arduino: /* LED intensity variation by PWM board trinket pro */ int pwmPin=3; // LED void setup(){ } void loop(){ byte i=0; cahr delta=1; i += delta; analogWrite(pwmPin,i); delay(5); if (i==255 || i==0) delta=-delta; } This doen’t worked when I tried it. I was thinking that once loop() is called the program stayed in loop(). It is not the case. So locales variables were reinitialized. So ‘byte’ and ‘i’ must be defined outside of loop(). Sketch don’t give you access to the actuel infinite loop inside main(). For me it disqualify it as C/C++ proper. Mismatch type is your problem. Why is byte being uses to identify a bit? You could have simply used a int identifier. Char variables tend to need the single quotes (‘1’) to identify a character. If you use a number, it will assign which ever character is represented by that number in accordance with ASCII (line break iirc). You then try to add a byte to a char with forces a type change. Now it’s a string (it won’t add them as number because concatenation takes precedence due to delta being an char), or it just added the number but shifted it due to the byte identifier. If you rework the way you did that, you would see that it does work without the variables needing to be initialized before executing the loop() function. Sorry, that’s bogus. C++ does not do implicit conversion to string; you’re probably thinking of PHP. That has nothing to do with whether the code is C/C++ or not. Did you expect the IDE to add an implicit loop inside loop()? That does also not happen with regular C/C++ – you would do something like int main() { byte i = 0; char delta = 1; while (1) { } } cahr delta = t; Miss-spelled “char”. Checks OK. What is scary is that “byte” must have been declared somewhere. Maybe it’s a reserved word. But “i”??? The Arduino system must be inserting global declarations for you somewhere. It’s good not to care about what you are doing. I notice on the Arduino forum there a lot of great people with the patience of a saint that will write most of your code for you. I guess your project gets done, but can you claim it as your own? Woops. Byte is a type. Miss-read that bit. First: Arduino’s “language” is a lie-to-children (). Nothing wrong with that. It’s a proven way to introduce people (not just children) to subjects that may be perceived as complex. Secondly: No such thing as C/C++. Arduino’s language is C++ and if you don’t believe me, try to declare a variable called ‘class’. Luckily, C++ supports such a big subset of C that most C programmers don’t notice they’re using the language they love to hate. Stepping out of rant mode: OK, most people probably use that subset of the C++ language that overlaps with C, I get it. Thirdly: yes, Arduino’s digitalWrite() functions are slow. The writers of those functions have made some choices and I think they probably made the right ones given their audience. For one, there’s some extra checking needed because the pin used in the digitalWrite could previously have been used for an analogWrite() (another lie-to-children), which means the digitalwrite function must switch of pwm, but there are more big choices that end up slowing down digitalWrite. It is, by the way, possible to implement a digitalWrite() function that is exactly as fast as fiddling with bits (I’ve explored such an implementation and described it here:) Oh, and by all means I do support the message of this article: It is a good thing to make people aware that Arduino sketches are C++ programs. It’s just that at the same time I don’t think that it’s a bad thing to tell them they’re writing a “sketch” when they write their first piece of embedded software. Nice. I wrote the article to dispell the lie-to-children for the metaphorical adolescents in the audience. But I like that turn of phrase. C/C++: some of the Arduino core is written in C, some in C++, which is what I really meant. (And included within extern “C” brackets to get included into the C++ parts of the code.) Nice point about the digitalWrite functions. I’d always wondered why they didn’t write them to be faster, but hadn’t thought of the clash with PWM. (I could have actually looked at the code, I suppose. Taking my own medicine and all that.) I’ll look into your functions. Thanks. Anyway, you raise your kids your way. My son is going to know about electrons in kindergarten. This. So much this. Hell, I only started working with the arduino once someone told me that it’s “programming language” was just something gentle over C++ and I could use standard stuff (within limits) to my heart’s content. Otherwise, people would talk about wiring and I’d think, “Christ, another programming language?” And then the lie-to-children part happens and my friend who’s ecstatic about making LEDs blink finally gets that they’re coding in a real language and looks deeper. I’ve little interest in being an EE, and I’m trying very hard to stop being a coder while avoiding managing coders. That’s why I call my tiny mallot skills I have the audacity to call soldering a cheap hack even though I’m putting a lot of thought into it. And that’s why I come to Hackaday and stopped reading Spectrum and NANOG. I’ve never trusted people who talk about how a specific programming language is “ugly” or that something “isn’t really programming.” I’d always end up with something that would sacrifice maintainability or ease of use in the pursuit of some pure design concept. Wasn’t really supposed to be a reply. But I think it works? I understand but have to ask, have you ever tried to read a Perl program? Dealing with others code and the lack of documentation you can run across in even the most professional environments can make you cringe at the mention of some languages. Trying to standardize on just one language doesn’t work either. I had prototyped a project that used network sockets. Easy in the language I chose to work in. Then some executive decided it needed to be implemented in Cobol before it went into production. That project died a slow agonizing death. I’ve heard that the language you think in will effect how you solve problems. I think it’s similar with computer languages. Let the project dictate the language you use. First off, Arduino is an amazing way to get an easy first step into the world of embedded programming. It’s only natural that they hide a few things for the beginners, and any real programmer will quickly progress and eventually take off the training wheels. Second, and far more importantly, it’s “PER SE”, not “PER SAY”. “Per se” is latin for “in itself”. “Per say” means nothing and is stupid. [quote]So if you start out writing your code in C, and then find out that you need some of the features of assembler, you’re hosed. You stop writing in C and port all your code over to assembler.[/quote] Silly me writing my assembly in (dot)s files and just linking them with my C. I will have to go back and get all the mixed C/ASM I have done and port it all to pure ASM. Can’t believe I’ve been fooled for so long. Good point about including assembler routines with C. I’ve always gotten by with inline asm, as mentioned in the article, but I suppose for longer functions that makes sense. I should have picked more dissimilar languages for the example. Dang! You can ALWAYS call assembler subroutines from HLLs. At least, if you can’t, that’s a good sign that you should “run away.” I wrote an assembler subroutine for (original) IBMPC BASICA that implemented an H19 terminal emulator, one for pascal that did interprocess comm using shared code memory segments, and one for Fortran that compiled texual math expressions, and then allowed that to be called as another fortran subroutine. Someone needs to write un.arduino.me a program that takes a sketch and compiles is down into a directory (removed setup and loop by plopping them into main) and pulling the required includes into a standard directory structure. Auto spit out a generic makefile as well. That would truly help someone migrate from the Arduino IDE(cringe) and just hammering libraries together into learning whats going on behind the scenes. This would help migrate projects that started as Arduino “hash bang” into developer friendly products. Anybody try adding functionality to the Marlin reprap firmware before? If you need to debug something your totally up the creek. See the two solutions listed in the “Compile Phase” section of the post. All of this C++ programming is for babies and idiots. Real programmers use machine code directly, entered with toggle switches, one bit at a time. : O ) Speaking of entering data into IC’s with toggle switches, I have done something similar on a much smaller scale. A few months back I came up with a creative way to manually enter bits into a shift register to get around switch bounce issue. I used latching hall effect sensors and a magnet, to manually clock in bits. I still have it sitting on the desk The Arduino IDE / Library is a great example of how to write a good API that is clear and consistent. It is not over-engineered. IDE without debug? Really? Points well taken, but one good rant deserves another : Elliot wrote, “. . . there’s two aspects that really get *our* goat” (emphasis added). My rant is against the growing use of plural pronouns such as “we” or “our” by single individuals referring to themselves. This is rampant among my fellow ham-radio operators. In this particular case, if there are other C++ programmers who share Elliot’s grievances, he doesn’t say so or that he’s speaking for them. It is in “our” style guide here at HaD to do so. When I go out on a limb like that, it really gets my goat to have to incriminate the rest of the fine HaD crew. But I have my marching orders. (And I take liberties in the comments!) Though the Arduino IDE is mostly helpful when introducing newbies to programming, it is often hard to get them to later appreciate the difference between a microcontroller (atmel’s 8 bit atmega family and all the rest that keep being added) and a handy development platform called “Arduino” based on the “wiring” “language,” which is a layer on top of the open source C++ compiler behind the scenes, that some artsy people came up with to make projects easier…… and decided to call “Arduino” ….. sigh. Great article! Couldn’t agree more. If you’re on a Mac, I highly recommend embedXcode (). I have been using it for a long time, now. It’s excellent and you get to use Apple’s Xcode IDE. When I use it, however, I’ve undone the Arduino abstraction to make the very fine work the author has done more akin to Atmel’s AVR Studio. I prefer not to run Windoze on my Mac, so this solution is a great way to work with the AVR chips without Atmel Studio. AND, it’s an excellent way to work with dozens of other boards and frameworks: Atmel Cortex-M0+ SAMD and Cortex-M3 SAM, Microchip PIC32, Expressif SoC, MSP430, MSP432, C2000 and Cortex-M4 Tiva C MCUs, Maple boards with ARM Cortex-M3 STM32 F103RB, Teensy boards with Freescale ARM Cortex-M4 MK20, Spark Core with WiFi, RedBear boards with Nordic nRF51822 SoC, Nucleo and Freedom boards on mbed with ARM Cortex MCUs It’s amazing work and a great IDE. You get all the features you expect from a professional grade IDE (REAL syntax highlighting, version control integration, code reference, etc.) AND it’s a fully native and very powerful OS X app. I’ve written code for the AVRs and the Freescale Freedom embed boards with it. It’s an excellent experience. I’ve ordered some TI LaunchPad boards for my next project, which are also supported. I wrote a a very brief intro article about it on my blog, if anyone is interested in getting a quick tour: As a C developer, I got frustrated with the inadequacies with the runtime and “IDE” pretty early on, and ended up building a new performance runtime for AVR. I haven’t touched it for a while (moved on to Mbed), but for those in AVR land, Its an easy abstraction of the hardware, without the attached baggage of the Arduino runtime. Its BSD licensed, and encourages event driven programming. You can check it out here: i was doing c/++ before i got into micros. recently the ‘arduino way’ was biting me in the ass. i wrote a struct to store a data frame that i wanted to pass over serial, then under that i wrote a function to fill out that struct with data from a couple analog channels and a couple digital pin readings. this was all above the setup() and loop() functions. the compiler then gives me a ‘function uses undefined struct’ error, which in unobfuscated c would have been totally valid, but in arduino is not. the way arduino sticks all the function prototypes at the top of the file was causing issues while writing things the c way. i even tried placing my own function declaration after the struct but it seems it was ignored while the one arduino placed was not. either structs need to have the same prototyping rules or there needs to be a way to override this behavior. ultimately i turned it into a class with a member function, which is totally fine to stick above setup() it seems. the other option was to stick the function and struct in another header file. all my ‘sketch’ did was calling the function in loop, and writing the data out with Serial.write(); followed by a delay(). having two files for such a simple job seemed rather overkill in my book. I wonder if they used to have “you’re not a programmer, you’re just a coder!” debates, back when programming, coding, keypunching, and computer operations, were all separate jobs… All of you people are an embarrassment to people on the autism spectrum. Use what tools you like and be mature enough to not disparage things you don’t like for your own superficial, childish reasons. “The Arduino IDE is limited, hurrr” Who gives a fuck?, man up! Just grow up for fuck’s sake, you’re not funny or entertaining at all, you’re just bitching about shit that doesn’t matter. For those in the know, is this similar to the relation between Processing and Java? I always thought Processing ##was## Java, with a nice preprocessor. Yes. Although I gather that Processing does a bit more in creating a friendly pre-built run-time environment as well; something that would have taken significant code in pure Java. “Yes, there is inline assembler in GCC. That’s cheating.” Maybe so, but this was one of the most fun thing we did as undergrads to outdo each other, performance-wise, (circa 1988) in all the classes where we could use C. Inline assembly saved you from popping parameters from the stack, pushing registers, then popping back the vales for the registers before exiting your functions, and pushing returned values. Also you could do fun things with the video memory and mess around with the registers of the VGA card…great times. ‘Arduino’ is a keyword for typing into aliexpress to filter for the stuff I need for my next project. I really don’t understand all this Arduino bashing. Programming an Arduino is programming, is coding. Does it matter it is not raw C/C++. Is driving a automatic car not really driving? I for one Consumed this article. Visiting hackday daily I seek the bias or perhaps knowledgeable comments aimed at every article, this is in fact atleast for me is one major reason I return daily. I Don’t want to be limited to tunnel vision. Tho people’s ideologies may not “currently” aline with my own. I always google-fu their alternatives In hopes of finding the light so to speak. I started “Sketching” (don’t wanna call it “coding” Due to Possible flares-up it not be prudent to my point) With arduino And It’s So-called IDE environment. Mostly due to the Large “friendly'” “Helpful” Community. I had to start somewhere And Like others Before me, At first needed to ask the stupid questions like which way is up (extreme over simplification) but, To do So in more Vet area’s like avr forums Your quickly flamed for Sucking. and If your lucky given the correct terms to google or pointed to a data sheet and hopefully atleast in some vague suggestion pointed to WTH your suppose to be looking for in it. Quickly becoming comfy In the Arduino’s IDE in the soon realized Kindergarten Version of the english language. I knew in order to complete real tasks with Atmega’s chips, I needed to dive into the back side of the libraries. As extensive as the options are their designed purposefully to be mostly cookie cutter and don’t fill specific needs. Like Space requirements, speed and additional options not foreseen by the author of said lib. This left me in aww realizing in the said IDE I wasn’t learning to coding per se’ but in fact was like ordering Apple’s Siri to do stuff but having little idea how it was finding where or how to get it done. So at this point I was like ok, Time to start figuring out how to programming these MCU’s the way the rest do. Right up front there’s little in the way of Tut’s that are (So You can use arduino HUH?, Here’s whats different in the real world compared to how arduino does it”) Just my two cents and tho It may upset those vets who learned c/c++ the hard way. The one who make’s a great video series on how to transition from arduino’s IDE to making and using Makefile’s and .cpp etc. Will rule! There are many out there like me starting and asking is this for me then wanting more. There are also many out there who will never progress past it. But both are equally important as the demand is high for the hardware for either case and that drives abundance of options and prices down for everyone.. Greeks who grew up speaking greek believe it comes naturally. Others who learned to speak greek frown upon others who haven’t yet. Having a rosette stone can only help the Greek community grow! I can not agree more, that the IDE sucks in comparison to almost any other and that that .ino stuff is retarded, but the fact that “it just works” and is easy to use makes it possible for lots of beginners and non-programmers to use a microcontroller. If you give a person that has never programmed and has only basic electronics knowledge a PC without an IDE and the proper tools, I guess they will be much, much quicker to have their blinking LED (regardless of what OS they’re using) by installing Arduino IDE themselves, read an online tutorial, than by installing and using vim+GCC+avrdude… That said a proper IDE for Arduino would be nice… I’ve always used eclipse CDT with avr-eclipse, avr-gcc and avrdude. Open source, multi-platform, feature rich and fully integrated. I believe that some people have debugging working as well, but I never invested in the right programming hw. think about it this way: by removing complicated looking noise from embedded systems in harware and software the number of embedded projects exploded. arduino boards (that essentially are just plain old AVR-boards) have been sold in masses which dropped the price quite a lot. this is a benefit for every real embedded programmer who can still run plain C code on them. so at some point you could say this whole idea of arduino was just a way to enlarge the AVR-board market. personally, i don’t need to design development boards that cost me time and money. i find it rather irritating that whenever my friend spots electronics with some black chip he thinks it’s arduino. but who cares.. My thoughts exactly … i use Arduino boards for prototyping and write code with commercial compiler. It costs money? Yup, but my computer is also not freeware, my Fluke, Rigol, … Compiler is just a tool you need and people should look at it that way. I have much respect for guys that made Arduino project possible, but when you’re beyond “use 16×2 and LM35 library to make thermometer” stuff … you need better tools. >> “with some black chip he thinks it’s arduino” This has to be the saddest part of the Arduino landscape. The non-engineers that have found embedded systems do not realize that Atmel is not the only “black chip” out there. Like what kind of car someone drives, there are many to choose from with their own strengths and weakness. I have used almost every 8-bit processor since 1978 on some project/product or another. Some I liked, some were too much of a hassle to get working properly. ( anybody remember the SCAMP: ) So Arduino bashing may be fun in the short term, but knowing what’s on the market and understanding those strengths and weakness will help build a product that is both easy to build and profitable. There is no free lunch …
https://hackaday.com/2015/07/28/embed-with-elliot-there-is-no-arduino-language/
CC-MAIN-2017-43
refinedweb
13,235
72.16
Wednesday, June 6, 2012 ZK Quick Start This post is the Quick Start guide of ZK, talking about how to getting it started quickly, NO ZK Studio, NO Maven, just the simple clear traditional way. 1. Download Eclipse: 1.1: Go to Eclipse official site (, for 2012-06-06) 1.2: Click Downloads 1.3: Click Eclipse IDE for Java EE Developers (I choose 32 Bit version) 1.4: Click download button to download it. 2. Download Tomcat: 2.1: Go to Tomcat official site (, for 2012-06-06) 2.2: Click 'Tomcat 7.0' 2.3: Find the 'Binary Distributions' and download it 3. Download ZK 3.1: Go to ZK official site (, for 2012-06-06) 3.2: Click Downloads -> ZK 3.3: Click 'Download ZK CE' to download it 4. Start Eclipse: 4.1: Extract the downloaded file eclipse-jee-indigo-SR2-win32.zip 4.2: Create a workspace folder for Eclipse 4.3: Double-click on eclipse/eclipse.exe to open it, choose the workspace then click 'OK' 4.4: Click 'Workbench' to enter workbench 5. Add Tomcat Server in Eclipse 5.1: Extract the downloaded file apache-tomcat-7.0.27-windows-x86.zip 5.2: Right-click in Eclipse's Servers view -> New -> Server 5.3: Select Apache/Tomcat v7.0 Server, click next 5.4: Choose server folder, click finish 6. Create Test Project 6.1: Click File -> New -> Dynamic Web Project 6.2: Enter Project name then click Finish 6.3: Extract the downloaded file zk-bin-6.0.1.zip 6.4: Copy all jar files under zk-bin-6.0.1\dist\lib to WebContent/WEB-INF/lib 6.5: Copy zk-bin-6.0.1\dist\WEB-INF\web.xml to WebContent/WEB-INF/ 6.6: Right-click on WebContent -> New -> File, create a file 'index.zul' under WebContent 6.7: Edit index.zul as below: 7. Run Test Project 7.1: Right-click on server, click Add and Remove 7.2: Select test project, click Add then click Finish 7.3: Click 'Run' button 7.4: Open browser then go to the test project 7.6: Click the test button, a label will appear Finish On Question regarding ZK Chosenbox .Can we use SelectOption class with Chosenbox?Like we can do for ZK combobox where we can show some label to user but if user select some label in backend Java code we can get vale which can be use for DB. Currently Chosenbox only guess everything are String, but I believe it allows any java bean in ZK 6.5.2. Do you know how can we can do it i am using ZK6.5.2 Still did not get any Single Document where someone explain how we can use SelectOption kind of thing with Chosenbox I'm not sure what does SelectOption mean, is it something like getSelectedObjects? As a previously told you i want to show a label to user but in java code i want to use id for selected item thats why i want to use SelectOption type class.. public class SelectOption implements Serializable, Comparable> { private static final long serialVersionUID = 1L; private T value; private String label; private String description; public SelectOption() { } public SelectOption(T value) { this.value = value; } public SelectOption(T value, String label) { this(value); this.label = label; } //get/set methods In Chosenbox, you can pass any object into model and then it will use Object.toString() as the label to display, after you select some labels, you can get the selected objects via Chosenbox.getSelectedObjects(), is this fits your need? If not, what is your expected action? I have created a list List mytype;/get,Set Method and ChooseBoxContainer class have two variables label,value now in ZUl page Now model have a List of classes of type ChooseBoxContainer.java now how can i show only lable to user i have to use Rendered for that? Thanks Ben i have done it with itemrendered attribute Only One issue How can i bind these selecteditem with Java class as i did not get any attribute like selecteditem or selecteditems? You can get selected items by public LinkedHashSet<Object> getSelectedObjects () in Chosenbox But i am using MVVM Architecture i did not Wire the Component in this case how can i get selected items? You can bind it in vm since Chosenbox has proper getter/setter zul: <chosenbox model="@load(vm.model)" selectedObjects="@bind(vm.selectedObjects)" /> vm: public ListModel getModel () { ... } public void setSelectedObjects (Set selectedObjects) { ... } public Set getSelectedObjects () { ... } Thanks Ben but in Documentation these thing not added If possible please add these thing in Zk Official Documentation. i am getting this exception org.zkoss.zel.ELException: Error writing 'selectedObjects' on type org.zkoss.zkmax.zul.Chosenbox >>java.lang.NullPointerException >> at org.zkoss.zkmax.zul.Chosenbox.setSelectedObjects(Chosenbox.java:318) Maybe you can try the working sample at zkfiddle: Here sample with Exception.. Since you put Container in ListModel, you need to put Container in selectedObjects, too. Below is a working sample works with ZK 6.5.2 or later: By the way, currently chosenbox not works with itemRenderer well, what we can do now is overriding toString and equals (and even hashCode) properly in custom data class. FYI ...Sorry ben your fiddle example is throwing same exception Error writing 'selectedObjects' on type org.zkoss.zkmax.zul.Chosenbox on Page rendered and click on the button Hmm...but it works well for me with ZK EE eval 6.5.2, please refer to the online demo. I was doing three mistakes.. 1-I was testing code in fiddle while you mentioed it should work only in zk6.5.2 2-I am not checking for Null inside getSelectdObjet. 3-Using Item rendered i removed item rendered. Hi Benbai After selecting some items in the choosen box, i want to give onClick event of each item. is that possible. Yes, please refer to sample at gist:
http://ben-bai.blogspot.com/2012/06/zk-quick-start.html
CC-MAIN-2017-39
refinedweb
991
61.12
Opened 4 years ago Closed 4 years ago Last modified 3 years ago #5246 closed enhancement (fixed) [PATCH] Load/Save embedded ICC Profiles (TIFF/JPEG/PNG) Description In order to be able to do colour management, the ICC Profile or other colour information needs to be retrieved from the file. TIFF has the following tags: TIFFTAG_ICCPROFILE TIFFTAG_PRIMARYCHROMATICITIES TIFFTAG_WHITEPOINT TIFFTAG_TRANSFERFUNCTION JPEG has an APP2 marker with ID string of "ICC_PROFILE\0". PNG also has ICC profiles. Unfortunately, the original colour space is required to use colour profiles, yet there is still a ticket (#5097) that I can't move forward where JPEG YCCK returns inverted CMYK while reporting YCCK colour space. I provided a fix in that ticket. BTW, what is the mechanism for approving changes and where is the repository? Can I add changes myself? Thanks Attachments (1) Change History (23) comment:1 Changed 4 years ago by comment:2 Changed 4 years ago by Yes, exactly. Expose it as metadata. For TIFF, it could use the same prefix as the other tags (they all start with TIFFTAG_), though it'd be nice if certain metadata were more consistent across formats. For example, the resolution metadata is different on every format. Would it be possible to try and have the ICC Profile itself under the same metadata name for all file formats? It's not critical. Just makes code easier to maintain. If someone is willing to do this, that'd be great. Otherwise, I'll try and find time at some point in the future. The TIFF one doesn't look hard. But the JPEG one needs the APP blocks to be appended if I'm not mistaken. And I know nothing of PNG's internals. comment:3 Changed 4 years ago by I've started working on this. For TIFFs I'm also loading the colorimetric data. I've got the following metadata: SOURCE_ICC_PROFILE TIFFTAG_PRIMARIES_RED TIFFTAG_PRIMARIES_GREEN TIFFTAG_PRIMARIES_BLUE TIFFTAG_WHITEPOINT TIFFTAG_TRANSFERFUNCTION_RED TIFFTAG_TRANSFERFUNCTION_GREEN TIFFTAG_TRANSFERFUNCTION_BLUE TIFFTAG_TRANSFERRANGE_BLACK TIFFTAG_TRANSFERRANGE_WHITE For PNG and JPG, I will only add SOURCE_ICC_PROFILE. Does anyone have an issue with the name for the TIFF tags? Normally, there is a one to one match. But here, the primaries for example is actually only one tag. And the transfer function return three arrays. So I split them up this way. I think it's fairly straightforward. As for the ICC profile, I'd like to use the same name across drivers. So this will be one tag that doesn't have the TIFFTAG prefix. If anyone has objection to this or comments, let me know. comment:4 Changed 4 years ago by Is there a style guide somewhere? Why is the code written like C in a C++ environment? Am I allowed to use STL for internal temporary stuff? I do know you can't use STL for anything public, but internally, it should be fine. comment:5 Changed 4 years ago by It would be good to have a common metadata prefix, for example ICC_ . Another possibility is to expose those metadata as a separate ICC metadata domain, as it of specialized use. gives a few programming guide line. Otherwise the best is to look a bit at the existing code to see the common practices. As far as C++ is concerned, we tend to avoid too fancy C++ features and yes it does actually look like C with classes. Common C++ containers (vector, map, ...) are sometimes used. comment:6 Changed 4 years ago by I'm currently testing these changes. JPEG has been tested. Will test the other soon and hopefully add some unit tests. JPEG, PNG and TIFF have support for read/write of Profile and colorimetric data. Note that if a profile exists or is output, colorimetric info is ignored as it's not necessary. The PNG specs seem to indicate that other info is recommended to be added for apps that don't support profiles, but I have no way of getting that info from the profile w/o adding a colour management library to GDAL and I see no point in that. The user could add this info, but again, I'd have to add a lot more code for not much gain. I'm using the following tags because they relate to the original colour space, are found in multiple formats and relate to the original source data. The names have changed slightly. SOURCE_ICC_PROFILE SOURCE_ICC_PROFILE_NAME SOURCE_PRIMARIES_RED SOURCE_PRIMARIES_GREEN SOURCE_PRIMARIES_BLUE SOURCE_WHITEPOINT The profile name is only used with PNG right now. But they have a tag for sRGB without the profile itself. So I need a way to check for that. PNG also has a name property for the profile. Basically, check if a profile exists. If it is not available, check if the profile name is 'sRGB'. That'll handle the PNG case. The primaries and whitepoints are in "x, y, 1.0" format in xyY colours. TIFFTAG_TRANSFERFUNCTION_RED TIFFTAG_TRANSFERFUNCTION_GREEN TIFFTAG_TRANSFERFUNCTION_BLUE TIFFTAG_TRANSFERRANGE_BLACK TIFFTAG_TRANSFERRANGE_WHITE These are tiff specific, so I left them as tiff tags even though it's a single tag in the file (one for transfer function and one for transfer range). For PNG, there is: PNG_GAMMA I'll update all driver docs. I'm now getting an issue where the profile is being output to the pam xml file when I open the file. Anyone know how I can disable this? I haven't really looked into it, but thought I'd ask if there's an obvious answer first. Hope this is good for everyone. I also put all of the tags in the "IMAGE_STRUCTURE" domain since that is where SOURCE_COLOR_SPACE was and this relates directly to the interpretation of the colour data. If anyone has suggestions, changes, comments, etc., please let me know. comment:7 Changed 4 years ago by Regarding metadata going to pam xml, I believe this must be due to the fact that you call SetMetadata? or SetMetadataItem? after the "Initialize any PAM information" section (that is often found at the end of the Open() method of drivers). As far as the gist of your work is concerned, I'm afraid I'm not familiar enough with the topic to have an opinion without seeing a patch. comment:8 Changed 4 years ago by Ah ok, thanks! I'll look for that. I'll post the patches when I'm done the unit tests and after I've had it code reviewed here. comment:9 Changed 4 years ago by I'm trying to escape binary strings from python in one part of the unit test. I load the binary data from the file and it is the correct length. But when I call this, it's a little over half the original size. It appears to combine every two bytes as a single codepoint. icc = gdal.EscapeString?(data, scheme=gdal.CPLES_BackslashQuotable) Does anyone have an example how to get this working? If I get this working, I think I'm done. comment:10 Changed 4 years ago by I'll use base64 in Python and see if it gives identical results to CPLBase64Encode(). If so, I'll use that. It's more standard and base64 encoding is available on every development environment. comment:11 Changed 4 years ago by I decided to use COLOR_PROFILE namespace for the new metadata. I didn't want to risk interfering with existing tags in the IMAGE_STRUCTURE namespace. I attached a zip file containing the patch to be applied from within the gdal folder. There is also a autotest folder that should be decompressed into the folder of the same name. They are all new files and should be added via SVN (3 unit test files and 1 data file). comment:12 Changed 4 years ago by Quite substantial patch... It will take some time to review. Not sure when I'll be able to do so. Ping me or other committers if this stalls for too long. Just one note: this will definitely not make it into 1.10.2 as it is a new feature, but it will rather go into trunk ( 2.0 or 1.11 ) comment:13 Changed 4 years ago by OK, thanks. The docs in the zip will have to be updated with the correct version number of when these tags are being introduced. As to the code itself, you'll find that the new code required very few changes from existing code and doesn't change any pre-existing variables (aside from getting/setting metadata). I tried to make it all fairly independent and self-contained from the rest of the code (low coupling). The length of it is mostly due to the various colorimetric tags that need to be parsed or converted, but should be very simple to follow. Changed 4 years ago by comment:14 Changed 4 years ago by Patch commited in trunk in r26537 with a few corrections: compilation fix for libpng < 1.5 (a few arguments have changed signature), and I've also fixed in geotiff.cpp the loop at line 6494 to be "for(int i = 0; ((i < 2) && bOutputTransferRange); i++)" (the maximum index was 3 which is wrong since pszTXRNames contains only 2 values). By the way, this part of reading/writing TIFFTAG_TRANSFERRANGE does not work (at least in my testing with internal libtiff) since the tag isn't declared in libtiff. You would likely need to declare a custom tiff field info like in GTiffTagExtender(). If you need revisions of your code, please make them on trunk now. comment:15 Changed 4 years ago by Ah, and I've fixed the .py scripts to be compatible with Python 2.X too comment:16 Changed 4 years ago by comment:17 Changed 4 years ago by comment:18 Changed 4 years ago by comment:19 Changed 4 years ago by Thanks! About transfer range, the tag is in the specs (and thanks for fixing the loop). However, I've only read of one kind of colorimetric info (ie. company) that would use it. I added it to be complete. If the tests pass, then everything looks good to me. BTW, I can't remember for certain, but if you are releasing an update, you may want to verify that szCreateOptions is large enough in GDALRegister_GTiff(). I seem to recall that someone had updated the string, but not the size of the string. I'd take a look at revision 24653 (I believe it was the alpha type changes). I took this into account when I updated the size in my changes. But for an update before 2.0, I'd verify the size. I was getting crashes when I was first testing the GTiff changes. Thanks again for applying my patch and making the relevant changes! I'll be double checking again in our apps that ICC profiles are working correctly. JPEG is done already. I'll post a quick comment when I'm done. comment:20 Changed 4 years ago by I've applied your changes locally and tested reading and writing ICC profiles for JPEG, TIFF and PNG. Everything looks good. So your idea would be to expose ICC profiles as GDAL metadata ? The standard way of having changes applied is to prepare a patch against the subversion repository ( ) and attach it to a ticket for review. Direct access to the repository is for approved committers.
http://trac.osgeo.org/gdal/ticket/5246
CC-MAIN-2017-26
refinedweb
1,889
74.49
Coding with security in mind: interfaces This post is by Tomás Touceda, a member of SpiderOak’s Engineering team. At SpiderOak we do a lot of coding in Go. I personally really like Go because it feels like Python with the type safety guard rails and almost magical concurrency helpers. But the point of this post is not to do yet another deep dive into why Go might be better than some other language, or how we use it at SpiderOak. The goal is to talk briefly about subtleties in coding that mean the difference between a secure environment and an insecure one. Hashing DISCLAIMER: This finding is not mine, but Frank Sievertsen’s. Hashing is an operation in use in many different scenarios, some not even really security related. A popular hashing algorithm is SHA 256, let’s take that as an example. Here’s how you calculate the SHA 256 sum of a sequence of bytes in Go: sum := sha256.Sum256([]byte("hello world\n")) Super simple. Ok, so what’s the problem? Nothing with that line above, but how about this code: h := sha256.New() sum := h.Sum([]byte("hello world\n")) If you read the documentation closely, you’ll see that that’s wrong. And a lot of people would argue that you need to read the documentation in a lot of detail, specially when you are using cryptographic primitives. But… if we all did everything the way we have to do it, this world would be extremely different. In case the problem above is not clear, the issue is that sha256.New() returns something that implements the hash.Hash interface. That interface has a Sum([]byte) []byte method, but here's the documentation for it: type Hash interface { ... // Sum appends the current hash to b and returns the resulting slice. // It does not change the underlying hash state. Sum(b []byte) []byte ... } So we are adding what we want to hash to what we think is the hash sum of it. Not good at all. You could say that’s a silly mistake, and in some ways you’d be correct, but when it comes to cryptography, I prefer to design things trying to prevent misuse as much as possible. Of course, there’s no easy way to detect really bad use, but since appending a byte slice is not a complicated thing to write, maybe the helper in Sum([]byte) []byte is not really needed. Encryption A really well known person in the cryptography community is djb. I know close to nothing about the mathematical background behind basic cryptography, and even less about djb’s work, but one thing I really like about the way djb designs his cryptographic primitives is that they tend to be really hard to implement them in an unsafe way (keywords here are: side channel attack resistant). I won’t dive into the specifics; maybe that’ll be a future post although there’s a lot of material online already. NaCL is among the many gems that came from djb et al. It’s an encryption library that’s amazingly fast and really secure. One of the main reasons it’s secure is the abstractions it works with. When you use it, you don’t care about specifics: you care about the functionality and trust the writers of the library to make the right call for you because, chances are, they know better. This library introduces the abstraction of “box” and “secret box”. The idea is that a “box” is something you can “seal” in a way that only somebody else can “open”. If the box is tampered with, the receiver can detect this. A “secret box” is similar, but the way the keys work is different. For more details, please see the official documentation. Since NaCL uses primitives that are easy to implement securely, there are a lot of implementations. In our case, we’ll focus on 2: Go’s official implementation and libsodium (actually, the Go wrappers for libsodium). NaCL itself is implemented in the most efficient way possible, so there’s quite a bit of assembler code in it. This is the reason why libsodium exists, it’s a compatible library that is implemented in a more portable way. Let’s see how you would generate a key pair to be used when sealing/opening boxes in Go’s official implementation: publicKey, privateKey, err := box.GenerateKey(crypto_rand.Reader) Super simple, great! That’s the point! Let’s assume you start implementing whatever you’re working on and you realize that for some reason you’d rather migrate to libsodium. You open up your favorite search engine, type “libsodium go” and chances are you’ll find this version of it. So you change your key generation: publicKey, privateKey, err := cryptobox.CryptoBoxKeyPair() And that’s it! … right? WRONG. CryptoBoxKeyPair returns first the secret key, so it should be like this: privateKey, publicKey, err := cryptobox.CryptoBoxKeyPair() One option to address this is to make use of Go’s type system, return a PublicKey and PrivateKey type, which can be []byte underneath, but they will be checked when they are used. PyNaCL, the python bindings for libsodium (not NaCL), does this differently: from nacl.public import PrivateKey sk = PrivateKey.generate() pk = sk.public_key This is a lot harder to get wrong. Tweetnacl.js returns an object with publicKey and privateKey as members. Finally, we have Tink that is developed specially to “(…) provide simple and misuse-proof APIs for common cryptographic tasks”. Let’s look at how this library let’s you generate a key and encrypt data (example copied from the README):128_GCM); // 2. Get the primitive. Aead aead = AeadFactory.getPrimitive(keysetHandle); // 3. Use the primitive. byte[] ciphertext = aead.encrypt(plaintext, aad); That looks quite amazing. Inspecting the Go version of it, key generation for ECDSA at first hand looks too complicated, but closer inspection shows that it doesn’t simply use []byte and they introduce the idea of a key manager. If we look at the interfaces it presents to the user, it’s pretty straight forward: type Aead interface { // Encrypt encrypts {@code plaintext} with {@code additionalData} as additional // authenticated data. The resulting ciphertext allows for checking // authenticity and integrity of additional data ({@code additionalData}), // but does not guarantee its secrecy. Encrypt(plaintext []byte, additionalData []byte) ([]byte, error) // Decrypt decrypts {@code ciphertext} with {@code additionalData} as additional // authenticated data. The decryption verifies the authenticity and integrity // of the additional data, but there are no guarantees wrt. secrecy of that data. Decrypt(ciphertext []byte, additionalData []byte) ([]byte, error) } Clearly there are a lot of ways to implement the same thing. The goal is perfection, but since that is unreachable by definition, you want to shoot for pushing the bar as high up as you can to make it harder to misuse. So… if you are a user of libraries implementing cryptographic libraries, read the documentation really carefully! If you are implementing a cryptography library, please have the requirement “hard to misuse” in the same level as “provide secure primitives”. Originally published at engineering.spideroak.com on October 24, 2018.
https://medium.com/@SpiderOak/coding-with-security-in-mind-interfaces-6ea2d66c360f?source=rss-50bb10e05ffe------2
CC-MAIN-2020-16
refinedweb
1,189
56.35
Dec 22, 2013 02:29 PM|mattdaddym2|LINK Hi all, Gridview looks a bit like this: <asp:UpdatePanel <ContentTemplate> <asp:GridView <columnCrudHere> </asp:GridView> </ContentTemplate> </asp:UpdatePanel> Gridview is bound to linqdatasource using the Selecting event. This code works perfectly without the updatepanel. It also works perfectly if I copy to a page that isn't a Content Page to a Master Page. I've read a lot of posts about gridview issues in update panels with paging and sorting. In fact, there is one where they guy comments at the end that he got it working but it still fails when using a MasterPage. I've tried using a scriptmanager in the same page as the gridview and changing various options of the scriptmanager. To get it working, I just create a new page, copy my gridview, linqdatasource, scriptmanager, and code behind...and boom it works. It makes me wonder if I have something else in the page getting in the way. I do have other updatepanels where I can update content fine. So, this...combined with the post where the same issue is mentioned briefly has me perplexed. I've also tried explicitly listing the event: <Triggers> <asp:AsyncPostBackTrigger </Triggers> As I continue to test this, it becomes more frustrating and fascinating. I have created two new pages with only the gridview, linqdatasource, scriptmanager, and databinding methods. One page has no master....the other page has a master (but a completely new and clean one to avoid any possible interference). Same results! Paging/Sorting works great asynchronously as long as I'm not using a master page. :( Thanks all! Dec 23, 2013 04:20 AM|valuja|LINK Hi, I have created a test site to try to see the problem that you have. Tha master page looks like this: <%@ Master <head runat="server"> <title></title> <asp:ContentPlaceHolder </asp:ContentPlaceHolder> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager</asp:ScriptManager> <div> <asp:ContentPlaceHolder </asp:ContentPlaceHolder> </div> </form> </body> </html> and the content page with code: <%@ Page </asp:Content> <asp:Content <asp:UpdatePanel <ContentTemplate> <asp:GridView <Columns> <asp:BoundField <asp:BoundField </Columns> </asp:GridView> <asp:LinqDataSource </asp:LinqDataSource> </ContentTemplate> </asp:UpdatePanel> </asp:Content> using System; using System.Linq; using System.Web.UI.WebControls; namespace WebApplication6 { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void GW_OnPageIndexChanging(object sender, GridViewPageEventArgs e) { } protected void LinqDataSource1_OnSelecting(object sender, LinqDataSourceSelectEventArgs e) { var ctx = new MSSEntities(); var countries = from country in ctx.dim_Country orderby country.CountryName select country; e.Result = countries; } } } This works without any problems so I wonder what the main differences are from your code so that I may see if I can find the error? Best regards Johan Dec 23, 2013 12:50 PM|mattdaddym2|LINK Thank you for taking the time to do that. So, I just re-learned an important lesson. Remember the test page I set up to test the issue where I took only the related code so there would be "no interference" from anything else on the page. Well, I had some code in that page from a previous test. I went back and removed EVERYTHING except the bare minimum needed for this test and everything worked just as it did for you. LESSON LEARNED (AGAIN): When you test, don't assume anything and test in as much of a pristine environment as you can. But the question remains, what is causing my code NOT to work? In my test page, I found that I had code in the Page_Load that was executing a "Response.Write" from a previous test. The "Response.Write" breaks the gridview paging in the UpdatePanel. I have toggled that line off and on to verify it is the culprit. I went back to my original page, but I don't have anything like that. So far, I cannot find what is causing the issue there, but I know that something is causing it, so I can methodically work at this. Can anyone explain what the Response.Write is doing to the page to break this? Thanks! All-Star 30411 Points Dec 24, 2013 02:20 AM|Fuxiang Zhang - MSFT|LINK mattdaddym2Can anyone explain what the Response.Write is doing to the page to break this? Hi mattdaddym2, Thank you post the issue to asp.net forum. According to your description, I see that you were using the Response.Write when the updatepanel async post back. As we all know that we can't use Response.Write during an asynchronous postback. If you want to use it when gridview paging or sorting. I think you should set it as PostBackTrigger of updatepanel. Like below: <asp:UpdatePanel <ContentTemplate> <asp:Button <asp:GridView <Columns> <asp:BoundField <asp:TemplateField> <ItemTemplate> <asp:Button </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </ContentTemplate> <Triggers> <asp:PostBackTrigger <asp:PostBackTrigger </Triggers> </asp:UpdatePanel> Code behind: protected void Button1_Click(object sender, EventArgs e) { Response.Write("Button1_Click!"); } protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { Response.Write("GridView1_RowCommand!"); } Besides, you can also set it in the code behind like below. ScriptManager.GetCurrent(this).RegisterPostBackControl(GridView1); Thanks. Best Regards! Dec 24, 2013 04:27 PM|mattdaddym2|LINK Hi, I wasn't using the response.write during an async postback. I executed during page_load. At that point the async postbacks in mygridview wouldn't work. Removing the Response.Write got things working in my test page, but I don't have any code like this in production. I'm also still curious why this happens. Also, I wasn't looking for a postback trigger. Making the gridview a postback trigger for itself seems like it would defeat the purpose of putting it in an updatepanel in the first place. The gridview should page and sort asynchronously, but it isn't. Something in my page is getting in the way. Luckily, I finally tracked it down. The answer to this issue is a bit embarrassing. Lesson 1 - When you test, you isolate your issue as completely as possible and do not assume anything. Lesson 2 - When troubleshooting AJAX issues, look for javascript errors. Turns out my code works fine. The issue was other updatepanels on the page set to update "always". I noticed a javascript error in Firebug alerting me that an updatepanel couldn't be found when trying to sort/page the gridview I was having issues with. When I try to page my gridview, any updatepanel set to always also tries to update. Well, there is a "hidden" section of my page (visibility is off) with updatepanels. When attempting to sort/page my gridview, javascript is looking for these, I assume to update them, but cannot find them. There is a javascript error and all progress stops. The solution was to change the updatepanels that are hidden all to conditional (which has other repercussions but its bearable). Does this seem like the correct behavior by default. If an updatepanel is inside another control whose visibility is turned off, should it be attempting to update? Thanks all. All-Star 30411 Points Dec 24, 2013 08:10 PM|Fuxiang Zhang - MSFT|LINK Hi mattdaddym, I'm glad to see you post back. According to your description, I'm sorry to say I cannot reproduce the scenes you described. Would you mind share a simple demo with us and let us reproduce the scenes. Then we will provide further solutions for you. Thanks. Best Regards! 5 replies Last post Dec 24, 2013 08:10 PM by Fuxiang Zhang - MSFT
https://forums.asp.net/t/1958073.aspx?Gridview+inside+UpdatePanel+paging+sorting+doesn+t+work+ONLY+when+using+MasterPage
CC-MAIN-2021-04
refinedweb
1,248
57.27
In this chapter, we will get started with D and explore some of its core features. You will learn the following recipes: Installing the compiler and writing a "Hello World" program Adding additional modules (files) to your program Using external libraries Building and processing arrays Using associative arrays to translate input Creating a user-defined vector type Using a custom exception type Understanding immutability Slicing a string to get a substring Creating a tree of classes The D language borrows from several other programming languages, including statically typed languages such as C, C++, and Java, as well as dynamic languages such as Ruby, Python, and JavaScript. The overall syntax is very similar to C; the use of curly braces to denote blocks, declarations in the form of typename initializer, and more. In fact, a lot of, but not all, C code will compile in D too. D also is aimed at convenience, productivity, and modeling power. These principles can be illustrated with D's type inference feature. Type inference means you can write code without explicitly thinking of and repeating a variable's type. This gives the convenience of using a dynamic language, without sacrificing the compile-time checks of static typing. You'll use type inference throughout your programs. Any variable declared without a type (typically, the keyword auto is used to declare a variable without an explicit type) has an inferred type, where the type is automatically determined by the right-hand side of the assignment. D is one of the fastest compiling languages available, and it gives quick edit-run cycles that help rapid development in dynamic languages. Modeling power comes in the form of D's rich code generation, introspection, and user-defined types, which you'll start exploring in this chapter when you look at structs and classes. You're going to create your first D program; a simple "Hello World" program. Let's execute the following steps to create your first program: Download the DMD compiler from. If you use a platform installer, it will install. If you use a ZIP file, simply unzip it and use it in place of the platform installer. The binaries for each operating system are found in dmd2/your_os_name/bin. You may choose to add this directory to your PATHenvironment variable so you do not need to use the full path each time you run the compiler. Create a file with your favorite text editor with the following content and name it hello.d: import std.stdio : writeln;;; void main() { writeln("Hello, world!"); } Compile the program. In your command prompt, run the following: dmd hello.d Run the program as follows: hello You should see the following message appear: Hello, world! Tip Downloading the example code You can download the example code files for all Packt books you have purchased from your account at. If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you. The DMD compiler is the key tool needed to use D. Although IDEs exist, you won't be using them in this book. So, you'll learn how to use the compiler and be better equipped to handle problems encountered during the build process. D source files are Unicode text, which are compiled into executable programs. The DMD compiler, by default, generates an executable file with the same base name as the first file passed to it. So here, when you called dmd hello.d, it created a file named hello.exe on Windows or hello on Unix systems. You can change the output file with the dmd –of option, for example dmd –oftest hello.d will create a file named test.exe. You'll learn more about the options of dmd as and when they'll be required. Next, let's look at each of the lines of hello.d, beginning with the following import statement: import std.stdio; A D program is composed of modules. Each module is a file, but unlike C or C++, where you use textual #include directives, D uses a symbolic import. When you import a module, its public members become available for use. You can import the same module multiple times without any negative effect, and the order of top-level imports does not matter. In this case, you're importing the module std.stdio, which is a part of the standard library that provides input and output functions, including the writeln function you'll use later in the code. Next, let's discuss the following main() function: void main() D programs typically begin execution at the main() function. D's main() function can optionally take command-line arguments of type string[], and they may return either void or integer values. All forms are equally valid. Tip It is possible to write D programs that start somewhere other than main(), which allows you to bypass D runtime initialization. You'll see this in Chapter 11, D for Kernel Coding. Here, you're returning void because you aren't returning any specific value. The runtime will automatically return zero to the operating system upon normal termination, and it will return an error code automatically if the program is terminated by an exception. Now, let's look at the following output function: writeln("Hello, world!"); Finally, you'll call the function writeln from the std.stdio module to say Hello, World!. The writeln function can take any number of arguments of any type, and it will automatically convert them to string for printing. This function automatically adds a newline character to the end of the output. Here, you used the DMD compiler. There are two other major D compilers available: GDC and LDC. You can learn more about these at and, respectively. As your program grows, you'll want to break it up across multiple files. D offers a way to do this that is similar, but not identical to other popular programming languages. D source files are also called D modules. Let's add modules to your program by executing the following steps: Create an additional file. Put the moduledeclaration in the other file with a package and module name. These names should be meaningful for your project and this specific file, respectively, as shown: module yourpackage.yourmodulename;;; Import it in the existing file to use it. Import works in different ways—it does not have to be at the top of the file and may appear more than once in the file. The importstatement should always match the full name given in the modulestatement in the file being imported, as shown in the following code: import yourpackage.yourmodulename; Use the functions, disambiguating with the full module name if required. Compile with all files listed on the command line using the following syntax: dmd file1.d file2.d This will produce a single executable file out of the passed files. The name of the executable is, by default, the same as the first file passed. So here, the executable file will be named file1. In D, code is organized into modules. There is a one-to-one correspondence between files and modules—every D source file is a module, and every D module is a file. Using a module involves importing it into the current scope, accessing its members in code, and adding it to the build command when compiling. Tip If you forget to add a module to the build command, you'll see an error such as cannot find module of name NAME or undefined symbol _D6module. Modules are conceptually similar to static classes with a single instance; they can have constructors, destructors, fields, and so on. Each declaration inside a module may have attributes and protection qualifiers. In D, unlike C++, modules (not classes) are the unit of encapsulation. Therefore, any code can access any entity within the same module (regardless of the entity's protection qualifier). Modules have logical names that do not need to match the filename. This is set with the module statement, which must appear at the top of the file. The module statement is not strictly required. If you leave it off, it will default to the filename. However, it is strongly recommended that you write it, including a package name, (the first part of the dot-separated full name) in every module that may ever be imported, because relying on the default module name will cause trouble if you organize your code into directories. The common error module foo.bar must be imported as the foo module is caused by a missing module statement in the imported module. The typical organization of modules into packages mirrors the source files' directory structures. You are to match package and module names with directory and filenames, but doing so will help other users and build tools understand your project layout. The import statement may appear at any point. In module scope, it may appear anywhere and any number of times without changing anything. It can also be used in local scopes, where it must appear before the member is used and visibility is limited to that scope. Names of members in a module are not required to be unique among all the modules that make up a program. Instead, when necessary, they are disambiguated at the usage point or at the import statement by the module identifier, as shown in the following code: import project.foo;; // disambiguate with project.foo import bar; // you can disambiguate calls with the name bar project.foo.func(); // call project.foo.func bar.func(); // call bar.func The compiler will always issue an error if a reference is ambiguous so that you can specify your intent. The dmd distribution also includes a program called rdmd, which can recursively find dependent modules and compile them all automatically. With rdmd, you only have to pass the module that contains main. The module documentation at details how D's module system works, including a list of all the forms of the importstatement and information about symbol protection D can use external libraries written in D, as well as other languages, with direct access to C functions, such as those provided by the operating system or the wealth of code written in C that can perform a variety of tasks. Here, you'll learn how to use an external library in your D program. Let's use external libraries by executing the following steps: Create or download bindings, a list of function prototypes, and a data structure definition from the library. On 32-bit Windows with dmd only, get or create an importlibrary ( .libfile). If you have a .libfile, you can use coffimplib. If you only have a DLL file, you can use implib. Import the binding by using the following statement: import package.module.name; Compile with the library. For Linux, pass –L-llibnameto dmd. On Windows, pass the .libfile to dmdwhen compiling your program. This will link the file with the generated executable, producing a working program. D is binary compatible with C, but not source compatible. This means you can link directly to C libraries, including most operating system libraries, without any wrapper or invoker code. You do need, however, to port the header files, the function prototypes, and the variable declarations, to D. This process is called binding. While you can use a library by only providing the prototypes for the functions you need, being minimally type-safe, the recommended way is to port the C header as closely as possible. This will minimize bugs and maximize the ease of use for programmers who are familiar with the usage and documentation of C. In your code, using the library is the same as using any other module; you import the module, call the functions, and disambiguate the names by using fully-qualified package and module names. When compiling, the –L flag to dmd passes the rest of the argument straight to the linker. On 32-bit Windows, using an existing library may be difficult because dmd uses an old library file format called OMF that is incompatible with the newer and more common COFF format. This is where implib and coffimplib come into play—these programs generate the format that the linker, optlink, expects from the more common formats available. The implib command creates a .lib file that you can use with D directly from a .dll file. The implib command's invocation format is as follows: implib /s myfile.lib myfile.dll The coffimplib command converts the more common COFF .lib format to the format D requires. The coffimplib command's invocation format is as follows: coffimplib myfile.lib These programs can be separately downloaded from Digital Mars, the small company behind the D programming language and DMD compiler. They are not necessary when building 64-bit Windows programs, or programs on any other operating system. The DMD compiler supports pragma(lib, "name");, which will automatically handle the linker flag while building, if you pass the module to dmd's command line. This pragma is not fully supported on GDC, but it doesn't necessarily hurt either. It will issue a warning about an unsupported pragma. You can also create D interface files for D libraries, the extension .di is used traditionally. The .di files can be automatically generated with the dmd –H option. The D interface files are similar to header files in C or C++; they list the interface definitions, but omit function bodies. The use of D interface files is optional. Sometimes, using other libraries isn't as simple as calling their function, or you want to improve upon the API somehow. Chapter 4, Integration, explains how to address these issues. Deimos () is the official repository for translated bindings and common C libraries. It makes no attempt to change the API; it is simply a collection of ports of C library headers that can be used in D, saving you the trouble of recreating the prototypes yourself. Dub () is the semi-official D package manager, and code.dlang.org lists community libraries that are available through it. This includes C bindings as well as pure D libraries. If you are developing for 32-bit Windows, the Basic Utilities Package from Digital Mars () contains the implibtool as well as others to build advanced Windows .exefiles. The directory dmd2/src/druntime/importin the dmd's ZIP file has various D interface files for the D runtime library and the C standard library. D has three types of arrays built in: static arrays, with a set length known at compile time; dynamic arrays, with a variable length; and associative arrays, which are similar to hashmaps or dictionaries in other languages. D's arrays and array slices are a very flexible and easy-to-use tool used in almost all D programs. Here, you'll look at some of their capabilities by building a list of integers and then finding the sum of the contents. Let's use the following steps to build and process arrays: Declare an array variable by using the following statement: int[] arr; Append data to it as shown: arr ~= 1; arr ~= [2, 3]; Create a function that takes a slice and does some processing on it, as shown in the following code: int sum(in int[] data) { int total = 0; foreach(item; data) total += item; return total; } Pass a slice of the array to the function, as shown in the following code: // Dynamic arrays can be passed directly. Static // arrays can be sliced with the [] operator.. writeln("The sum of ", arr, " is ", sum(arr)); D types are always read from right to left. The int[] array is an array of integers. The string*[]* pointer is a pointer to an array of pointers to string. The int[][] array is an array of an array of integers; a staggered array. There are two kinds of arrays in D: static and dynamic. A static array is a value type that represents a solid, fixed-size block of memory (this corresponds to an array in C). A dynamic array is conceptually a struct with two members: a pointer to the data and the length of the data. Thus, unlike a static array, dynamic arrays and slices have reference semantics. You can access the pointer and length components with the .ptr and .length properties, respectively. In the example here, you used a dynamic array, which has the same syntax as a slice. There are three major operations on an array: appending, indexing, and slicing. Appending: This is done with the ~=operator. There's also the binary ~operator (not to be confused with the unary ~operator, which inverts bits), which concatenates two arrays to form a new one. You can append an individual element or another static or dynamic array of compatible type. Indexing: This is done with the [expr]operator, for example, arr[0]. This is very similar to C, but a key difference in D is that arrays know their own length, enabling automatic bounds checking. If you attempt to access an out-of-bounds index, you will see a RangeError. Slicing: This is done with the []operator, for example, arr[]or arr[0 .. 2]. This is done to get a view into an array starting at the left-hand index (inclusive) and ending at the right-hand index (exclusive, which means you can use the array's length as an ending bound, which also has a shorthand syntax $). [][][]gets a slice into the whole thing, and it is useful to pass static arrays or user-defined array types to functions expecting slices or dynamic arrays. Slicing is a fast, constant-time operation. You can iterate over an array or slice using the foreach loop. You put the iteration variable, then a semicolon, and then the variable you want to iterate over. You do not have to explicitly name the variable's type, for example, foreach(item; array) or foreach(int item; array). In the example code, the function parameter is defined as an in variable. The in variable is shorthand keyword to give the parameter the storage classes of const and scope. What this means in practice is that you must not modify the array or its contents (this will be a compile error), nor should you keep a copy of or return a reference to the passed array. D also supports array vector operations like the following: arr[] = arr[] + 5;;; This code will add five to every element of the array. You can also create array copies this way: arr2[] = arr[]. This will copy arr into arr2. For this to work, the lengths of the two arrays must already match. To do an array copy without matching lengths, you can write array.dup. for details of array memory management and the difference between a dynamic array and a slice. for a more complete listing of what D's arrays can do. The Creating an array replacement recipe in Chapter 5, Resource Management. This will show you how to create a new array type that has the same capabilities as the built-in arrays, with custom behavior or memory allocation strategies. The Avoiding the garbage collector recipe in Chapter 5, Resource Management. This will discuss the built-in array's memory allocation habits and what to avoid if you don't want to use the garbage collector. D also has associative arrays, sometimes called maps or dictionaries. An associative array maps arbitrary keys to values. Unlike a regular array, the keys do not need to be sequential and do not need to be integers. Here, you'll explore their functionality by creating a program that translates input strings to other strings. Let's translate an input by using the following steps: Declare the associative array with string keys and string values. Initialize it with initial data. Loop over input lines. If the line is in the array, show the value and remove it. If not, add this line with a replacement. When you're done, loop over the array to show your changes. The code is as follows: void main() { import std.stdio, std.string; string[string] replacements = ["test" : "passed", "text" : "replaced"]; replacements["foo"] = "bar"; assert(replacements["test"] == "passed"); foreach(line; stdin.byLine()) { line = line.strip(); // cut off whitespace // see if the given line is in the mapping… if(auto replacement = line in replacements) { // if yes, show the replacement, then unmap it writeln(line, " => ", *replacement); replacements.remove(line.idup); } else { // if no, add it to the map writeln(line); replacements[line.idup] = "previously inserted!"; } } foreach(line, replacement; replacements) writeln("Mapping ", line, " => ", replacement);); } When the program runs out of lines to process, it will print out the current array contents, showing you what has been added and removed as you entered data. First, you declared your main function and then imported the std.stdio and std.string modules, which contain the I/O and whitespace stripping functions that you used later. Next, you declared an associative array that maps strings to other strings. The syntax is ValueType[KeyType], and both sides can be of any D type. You also initialized the replacements with an associative array literal. Note It is also possible to use user-defined types as associative array keys. Using custom types as key types requires that they implement opHash, opCmp, and opEquals. The syntax of an associative array (AA) literal is [Key:Value, Key:Value, …]. AA literals can have both compile-time constant and runtime data; ["foo":x] is legal too. Next, you can set a value outside the literal and check the value of a key, just for demonstration purposes. Associative arrays have similar syntax to regular arrays: you use the same bracket syntax to get and set elements. Then, you can enter the replacement loop, reading the standard input by line and then stripping off whitespace and looking for the line in the replacements array. Let's look at this line in more detail, as follows: if(auto replacement = line in replacements) { On the right-hand side, you can use the in operator to do a key lookup. This operator returns a pointer to the element if it is found, and null if it is not found. Tip You don't have to use the pointer returned by the in operator. if(line in replacements) works just as well. There's also the inverse of in, which is !in. The if(line !in replacements) statement is true if line is not in the replacements array. On the left-hand side, you can declare and assign the variable right inside the if statement. This keeps the newly declared variable limited in scope. If the variable replacement is available, you can be certain that it is not null, since the if statement will not execute otherwise! In the next example, you'll proceed into the true branch of the if statement. This branch uses the dereference operator, *replacement, to print out the value. The * operator is necessary because the in operator returns a pointer to the element rather than the element itself. Then you'll remove this key from the mapping by using the built-in associative array property remove. Next time you insert that line, it will not be replaced. After that, the false branch of the if statement does not have the null pointer stored in the variable replacement available to use. Any attempt to access it will be a compile error. Instead, you can add the new line to the replacement map. The .idup property is required because associative array keys must be immutable, and stdin.byLine returns a mutable buffer. Array.idup creates a new, immutable copy of the data. Finally, once the input has been exhausted, you can loop over the associative array with a foreach loop. The syntax is foreach(index, value; array), and you can print out the current state. The index parameter is optional if you only need the values. User-defined types are used everywhere in D to group data, model objects, provide compile-time checks, and more. Here, you'll create a simple vector type with a length and direction to look at some basic capabilities. Whenever you create a user-defined collection in D, the first decision to make is whether it should be a class, struct, mixin template, or union. Mixin templates are great for code reuse. They define code that can be copied (or mixed in) to another type, with parameterization. Unions are for the cases when you need the same block of memory to have multiple types, and are the least common in typical D code. Classes and structs are the backbone of user-defined types in D, and they have the most in common. The key difference is polymorphic inheritance; if you need it, you probably want a class. Otherwise, structs are lighter weight and give maximum flexibility. Using them, you can precisely define the layout of each byte with no hidden data, overload all operators, use deterministic destruction (the RAII idiom from C++), and use both reference or value semantics depending on your specific needs. D's structs also support a form of subtyping, though not virtual functions, which you'll see in Chapter 6, Wrapped Types. Let's summarize as follows: Since your vector type will not need virtual functions, it will be a struct. Let's look at creating a vector type using the following steps: Declare the structvariable with a name. This declaration can appear anywhere; but, in your case, you want it to be generally accessible. So, it should go in the top-level scope of your module. Unlike C++, there is no need to put a semicolon at the end of the structdefinition, as shown in the following code: struct Vector {} Determine which data members are needed and add them to the struct. Here, you need a magnitude and direction, and they will be floating point types: struct Vector { float magnitude; float direction; } Add methods that operate on the data to the struct. In this case, you want to be able to add vectors together and convert from (x, y)coordinates. The complete code is as follows: struct Vector { // the data float magnitude; float direction; // the methods /// create a Vector from an (x, y) point static Vector fromPoint(float[2] point) { import std.math; Vector v; float x = point[0]; float y= point[1]; v.magnitude = sqrt(x ^^ 2 + y ^^ 2); v.direction = atan2(y, x); return v; }}} /// converts to an (x,y) point. returns in an array. float[2] toPoint() const { import std.math; float x = cos(direction) * magnitude; float y = sin(direction) * magnitude; return [x, y]; } /// the addition operator Vector opBinary(string op : "+")(Vector rhs) const { auto point = toPoint(), point2 = rhs.toPoint(); point[0] += point2[0]; point[1] += point2[1];];]; return Vector.fromPoint(point);); } } Use the new type as follows: auto origin = Vector(0, 0); import std.math; auto result = origin + Vector(1.0, PI); import std.stdio; writeln("Vector result: ", result); writeln(" Point result: ", result.toPoint()); It will print Vector(1.0, 3.14) and [-1, 0], showing the vector sum as magnitude and direction, and then x, y. Your run may have slightly different results printed due to differences in how your computer rounds off the floating point result. Structs are aggregate types that can contain data members and function methods. All members and methods are defined directly inside the struct, between the opening and closing braces.. The this variable is an automatically declared variable that represents the current object instance in a method. The following recipe on immutability will discuss these keywords in more detail. Operator overloading in D is done with methods and special names. In this section, you defined opBinary, which lets you overload the binary operators such as the addition and subtraction operators. It is specialized only on the + operator. It is also possible to overload casting, assignment, equality checking, and more. At the usage point, you declared a vector with auto, using the automatically defined constructor. Finally, when you write the result, you use the automatic string formatting that prints the name and the values, in the same way as the automatic constructor. It is also possible to take control of this by implementing your own toString method. Chapter 6, Wrapped Types, will show more advanced capabilities, including how to use structs to make a reference type and to use constructors, destructors, postblits, and so on. Inheritance and dynamic class casting will show how to make the most of classes. Visit for the language documentation on operator overloading. It details all the operators available for overloading and how to do it. D uses exceptions to handle errors, just like many other programming languages. In D, exceptions are always implemented as classes that derive from the class Throwable, and they are differentiated by their type. So, it is best to generate a new exception subclass for different types of errors your code can generate. This way, users of your code will get the most information and control out of your exceptions. Let's use a custom exception type by using the following steps: Declare a class that inherits from Exception. Make a constructor that takes, minimally, two parameters: string fileand size_t line, with default values of __FILE__and __LINE__, respectively. Have the constructor forward the arguments to the constructor of Exception. Use your exception. The following is the code: class MyException : Exception { this(string message, string file = __FILE__, size_t line = __LINE__, Throwable next = null) { super(message, file, line, next); } } void main() { import std.stdio; try throw new MyException("message here"); catch(MyException e) writeln("caught ", e); } D uses exceptions to handle errors. All throwable objects inherit from either Exception, for recoverable events, or Error for unrecoverable errors, which generally ought not be caught. The common base class is Throwable. Typically, a custom exception inherits from Exception, then declares, minimally, a constructor that forwards the functionality to super(). You may also store additional information specific to your use case. The constructor of Exception (here, called with super()) takes four arguments: a string message, a filename, a line number, and optionally, a reference to another exception. The message, filename, and line number are used to construct a message for the user, which is printed to the console if the exception is not caught. You don't have to specify the file and line number at the throw site; any default argument of __FILE__ or __LINE__ is automatically expanded at the function's call site. This is useful to make the error message more useful by showing exactly where the exception came from. The fourth parameter, Throwable next, is used if an exception handler throws an exception. It references the exception that was being handled when this one was generated. You should check error codes when using the C functions and turn them into exceptions. If it sets errno for error details, the std.exception module has a subclass called ErrnoException that is perfect for the following code: import core.sys.posix.unistd; // for the low-level Posix functions import core.sys.posix.fnctl // for more low-level Posix functions import std.exception; // for ErrnoException auto fd = open("myfile.txt", O_RDONLY); // open() returns -1 if it was unable to open the file, // and sets errno with error details. Check for that failure. if(fd == -1) throw new ErrnoException("Couldn't open myfile.txt"); // close the file automatically at the end of the scope scope(exit) close(fd); /* read the file here */ Scope guards, discussed in Chapter 5, Resource Management, are convenient for use with exceptions. They let you put clean-up or recovery code near the creation point in an exception-safe way. In the preceding example, you used a scope guard to ensure the file is properly closed when the function returns, even if an exception is thrown. Here, you'll look at how to use immutability in your functions and data types. Immutability helps us to write code that is easier to understand and maintain because it limits the places where things can change. First, write a function. Then, look at it and determine what it needs to do. Does it just look at the data passed to it? Does it store or return a reference to data passed in? We'll use these facts about how the function uses its arguments to determine the best-fit qualifiers. The use of const and immutable is slightly different on free functions and object methods. If you are accepting a value type, const and immutable aren't very important. If you are borrowing a value—going to look at it, but not store it nor modify it—use the in keyword and, if it is a character string, use char[] instead of string ( string is an alias for immutable(char)[]): void foo(in char[] lookAtThis) { /* inspect lookAtThis */ } If you are going to store a reference, it is best to take immutable data, if possible as follows: void foo(immutable(ubyte)[] data) { stored = data; } If you are going to modify the data, but not store it, use scope, but not const ( in is shorthand for scope const), as follows: void foo(scope char[] changeTheContents) { /* change it */ } If you are not going to modify or store the contents, but will return a reference to it, use inout as follows: inout(char)[] substring(inout(char)[] haystack, size_t start, size_t end) { return haystack[start .. end]; } If you are going to change the value itself (not just the contents it references), use ref as follows: void foo(ref string foo) { /* change foo itself */ } When writing object methods, all of the preceding functions still apply, in addition to putting a qualifier on the this parameter. The qualifier for this goes either before or after the function as follows: int foo() const { return this.member; } /* this is const */ const int foo() { return this.member; } /* same as above */ Since the second form can be easily confused with returning a const value (the correct syntax for that is const(int) foo() { …}), the first form is preferred. Put qualifiers on this at the end of the function. D's const qualifiers is different than that of C++ in two key ways: D has immutable qualifiers, which means the data will never change, and D's const and immutable qualifiers are transitive, that is, everything reachable through a const/ immutable reference is also const/ immutable. There is no escape like the mutable keyword of C++. These two differences result in a stronger guarantee, which is useful, especially when storing data. When storing data, you generally want either immutable or mutable data— const usually isn't very useful on a member variable; although it prevents your class from modifying it, it doesn't prevent other functions from modifying it. Immutable means nobody will ever modify it. You can store that with confidence that it won't change unexpectedly. Of course, mutable member data is always useful to hold the object's own private state. The guarantee that the data will never change is the strength of immutable data. You can get all the benefits of a private copy, knowing that nobody else can change it, without the cost of actually making a copy. The const and immutable qualifiers are most useful on reference types such as pointers, arrays, and classes. They have relatively little benefit on value types such as scalars ( int, float, and so on) or structs because these are copied when passed to functions anyway. When inspecting data, however, you don't need such a strong guarantee. That's where const comes in. The const qualifier means you will not modify the data, without insisting that nobody else can modify it. The in keyword is a shorthand that expands to scope const. The scope parameters aren't fully implemented as of the time of this writing, but it is a useful concept nonetheless. A scope parameter is a parameter where you promise that no reference to it will escape. You'll look at the data, but not store a reference anywhere. When combined with const, you have a perfect combination for input data that you'll look at. Other than that you have the short and convenient in keyword. When you do return a reference to const data, it is important that the constancy is preserved, and this should be easy. This is where D's inout keyword is used. Consider the standard C function strstr: char *strstr(const char *haystack, const char *needle); This function returns a pointer to haystack where it finds needle, or null if needle is not found. The problem with this prototype is that the const character attached to haystack is lost on the return value. It is possible to write to constant data through the pointer returned by strstr, breaking the type system. In C++, the solution to this is often to duplicate the function, one version that uses const, and one version that does not. D aims to fix the system, keeping the strong constancy guarantee that C loses and avoiding the duplication that C++ requires. The appropriate definition for a strstr style function in D will be as follows: inout(char)* strstr(inout(char)* haystack, in char* needle); The inout method is used on the return value, in place of const, and is also attached to one or more parameters, or the this reference. Inside the function, the inout(T) data is the same as const(T) data. In the signature, it serves as a wildcard that changes based on the input data. If you pass a mutable haystack, it will return a mutable pointer. A const haystack returns a const pointer. Also, an immutable haystack will return an immutable pointer. One function, three uses. D also has the ref function parameters. These give a reference to the variable itself, as shown in the following code: void foo(int a) { a = 10; } void bar(ref int a) { a = 10; } int test = 0; foo(test); assert(test == 0); bar(test); assert(test == 10); In this example, the variable test is passed to foo normally. Changes to a inside the function is not seen outside the function. Note If a was a pointer, changes to a will not be seen, but changes to *a will be visible. That's why const and immutable are useful there. With the function bar, on the other hand, it takes the parameter by reference. Here, the changes made to a inside the function are seen at the call site; test becomes 10. Tip Some guides recommend passing structs to a function by ref for performance reasons rather than because they want changes to be seen at the call site. Personally, I do not recommend this unless you have profiled your code and have identified the struct copy as a performance problem. Also, you cannot pass a struct literal as ref, because there is no outer variable for it to update. So, ref limits your options too. D's strings are actually just an array of characters. This means any operation that you can do on arrays, also works on strings. However, since string is a UTF-8 array, there are some behaviors that you may find surprising. Here, you'll get a substring by slicing and discuss potential pitfalls. Let's try to get a substring from a string using the following steps: Declare a string as follows: string s = "月明かり is some Japanese text."; Get the correct index for start and end. You'll get the Japanese text out by searching the string for the first space, and slice up to that point by using the following code: import std.string; string japaneseText = s[0 .. s.indexOf(" ")]; Loop over the string, looking at the UTF-8 code units as well as the Unicode code points. So, you can see the difference in your string by using the following code: import std.stdio; foreach(idx, char c; japaneseText) writefln("UTF-8 Code unit at index %d is %d", idx, c); foreach(dchar c; japaneseText) writefln("UTF-32 code unit with value %d is %c", c, c); The program will print out more code units in UTF-8 than in dchars, because the Japanese text is composed of multibyte characters, unlike English text. D's implementations of strings uses Unicode. Unicode is a complicated standard that could take up a whole book on its own, but you can use it in D knowing just some basics. D string, as well as D source code, uses UTF-8 encoding. This means you can paste in text from any language into a D source file and process it with D code. However, UTF-8 has a complication; the length of a single code point is variable. Often, one code point is one character, though Unicode's complexity means graphemes (that is, what you might also call a visible character) may consist of more than one code point! For English text, UTF-8 beautifully maps directly to ASCII, which means that one code unit is one character. However, for other languages, there are too many characters to express in one byte. Japanese is one example where all the characters are multibyte in UTF-8. So, while there are only four characters in your program, if you slice from s[0 .. 4], you won't get all four characters. D's slice operator works on code units. You'll get a partial result here, which may not be usable. Instead, you found the correct index by using the standard library function indexOf. This searches the string for the given substring and returns the index, or -1 if it could not be found. The slice [start .. end] goes from start, including it, to the end, not including that. So, [0 .. indexOf(…)] goes from the start, up to, but not including, the space. This slice is safe to use, even if it contains multibyte characters. Finally, you looped over the Japanese text to examine the encodings. The foreach loop understands UTF encoding. The first variant asks for characters, or UTF-8 code units, and yields them without decoding. The second variant asks for dchars, which are UTF-32 code units that are numerically equivalent to Unicode code points. Asking for dchars is slower than iterating over chars, but has the advantage of removing much of the complexity of handling multibyte characters. The second loop prints only one entry per Japanese character, or any other character that cannot be encoded in a single UTF-8 unit. D also supports UTF-16 and UTF-32 strings. These are typed wstring and dstring, respectively. Let's look at each of these as follows: wstring: This is very useful on Windows, because the Windows operating system natively works with UTF-16. dstring: This eats a lot of memory, about 4 times more than strings for English text, but sidesteps some of the issues discussed here. The reason is that each array index corresponds to one Unicode code point. Classes are used to provide object-oriented features in D. To explore how they work, you're going to write a small inheritance hierarchy to evaluate basic addition and subtraction operations. Before writing a class, step back and ask yourself whether it is the best tool for the job. Will you be using inheritance to create objects that are substitutable for their parent? If not, a struct may be more appropriate. If you plan to use inheritance for code reuse without substitutability, a mixin template may be more appropriate. Here, you'll use classes for substitutability, and a mixin template for some code reuse. Let's create a tree of classes by executing the following steps: Create a class, with the data and methods it needs. For your expression evaluator, you'll create two classes: AddExpressionand SubtractExpression. They will need variables for the left and right-hand side of the expression, and a method to evaluate the result. Move common methods from substitutable classes out to an interface, and make the classes inherit from it by putting a colon after the class name, followed by the interface name. In both AddExpressionand SubtractExpression, you will have an evaluate method. You'll move this function signature, but not the function body, to the interface, called Expression. If there is still a lot of code duplication, move the identical code out to a mixin template, and mix it in at the usage point. Functions should operate on interface parameters, if possible, instead of classes, for maximum reusability. The following is the code you have so far: interface Expression { // this is the common method from the classes we made int evaluate(); } mixin template BinaryExpression() { // this is the common implementation code from the classes private int a, b; this(int left, int right) { this.a = left; this.b= right; } } // printResult can evaluate and print any expression class // thanks to taking the general interface void printResult(Expression expression) { import std.stdio; writeln(expression.evaluate()); } class AddExpression : Expression { // inherit from the interface mixin BinaryExpression!(); // adds the shared code int evaluate() { return a + b; } // implement the method } class SubtractExpression : Expression { mixin BinaryExpression!(); int evaluate() { return a - b; } } Let's also add a BrokenAddExpressionclass that uses inheritance to override the evaluatefunction of AddExpression: class BrokenAddExpression : AddExpression { this(int left, int right) { super(left, right); } // this changes evaluate to subtract instead of add! // note the override keyword override int evaluate() { return a - b; } } Finally, you'll construct some instances and use them as follows: auto add = new AddExpression(1, 2); printResult(add); auto subtract = new SubtractExpression(2, 1); printResult(subtract); // same function as above! The usage will print 3 and 1, showing the different operations. You can also create a BrokenAddExpression function and assign it to add as follows: add = new BrokenAddExpression(1, 2); printResult(add); // prints -1 Classes in D are similar to classes in Java. They are always reference types, have a single inheritance model with a root object, and may implement any number of interfaces. Class constructors are defined with the this keyword. Any time you create a new class, it calls one of the constructors. You may define as many as you want, as long as each has a unique set of parameters. Note Classes may have destructors, but you typically should not use them. When a class object is collected by the garbage collector, its child members may have already been collected, which means that they cannot be accessed by the destructor. Any attempt to do so will likely lead to a program crash. Moreover, since the garbage collector may not run at a predictable time (from the class' point of view), it is hard to know when, if ever, the destructor will actually be run. If you need a deterministic destruction, you should use a struct instead, or wrap your class in a struct and call the destructor yourself with the destroy() function. Object instances are upcasted implicitly. This is why you could assign BrokenAddException to the add variable, which is statically typed as AddExpression. This is also the reason why you can pass any of these classes to the printResult function, since they will all be implicitly cast to the interface when needed. However, going the other way, when casting from interface or a base class to a derived class, you must use an explicit cast. It returns null if the cast fails. Use the following code to better understand this: if(auto bae = cast(BrokenAddExpression) expression) { /* we were passed an instance of BrokenAddExpression and can now use the bae variable to access its specific members */ } else { /* we were passed some other class */ } In classes, all methods are virtual by default. You can create non-virtual methods with the final keyword, which prevents a subclass from overriding a method. Abstract functions, created with the abstract keyword, need not to have an implementation, and they must be implemented in a child class if the object is to be instantiated. All methods in an interface that are not marked as final or static are abstract and must be implemented by a non-abstract class. When you override a virtual or abstract function from a parent class, you must use the override keyword. If a matching function with any method marked override cannot be found, the compiler will issue an error. This ensures that the child class's method is actually compatible with the parent definition, ensuring that it is substitutable for the parent class. (Of course, ensuring the behavior is substitutable too is your responsibility as the programmer!) The mixin template is a feature of D that neither C++ nor Java have. A mixin template is a list of declarations, variables, methods, and/or constructors. At the usage point, use the following code: mixin BinaryExpression!(); This will essentially copy and paste the code inside the template to the point of the mixin statement. The template can take arguments as well, given in the parenthesis. Here, you didn't need any parameterization, so the parentheses are empty. Templates in D, including mixin templates, can take a variety of arguments including values, types, and symbols. You'll discuss templates in more depth later in the book. Using interfaces and mixin templates, like you did here, can also be extended to achieve a result similar to multiple inheritance in C++, without the inheritance of state and avoiding the diamond inheritance problem that C++ has. The Simulating inheritance with structs recipe in Chapter 6, Wrapped Types, shows how you can also achieve something subtyping and data extension, similar to inheritance with data, using structs. The official documentation can be found at and it goes into additional details about the capabilities of classes.
https://www.packtpub.com/product/d-cookbook/9781783287215
CC-MAIN-2021-17
refinedweb
8,284
63.39
From: Eric Niebler (eric_at_[hidden]) Date: 2004-07-08 15:13:18 Rozental, Gennadiy wrote: > Why subject configuration still failing on min/max according to Linux > regression? > > Gennadiy. There appear to be failures in graph-copy and graph-adj_list_cc due to min/max, but for some reason, they are only reported as _Warn_ in the summary, so I didn't see them. (Bug?) There is also a min/max failure in random-random_test. I haven't figured out what the problem is regarding graph. I would need a preprocessed file to analyze. The random_test is interesting. There are member functions min/max that are hiding the min/max in the boost namespace. I'm running out of ideas for fixing this broken toolset. And I'm hamstrung because I don't have access to it. I'll give it some more thought. Are there any other failures regarding min/max you've noticed, or is it just the three tests I've mentioned? -- Eric Niebler Boost Consulting Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2004/07/67627.php
CC-MAIN-2020-40
refinedweb
189
69.07
A friendly place for programming greenhorns! Big Moose Saloon Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login JavaRanch » Java Forums » Databases » Object Relational Mapping Author Need help with Mapping(Annotation) and Composition Timothy Sam Ranch Hand Joined: Sep 18, 2005 Posts: 751 posted May 11, 2007 05:13:00 0 Hi guys! I have a problem... I have this mapping in my class named FixedItem. And with it is a member named assignedTo which is mapped to an int in a relational table. This is suppose to be a foreign key but I decided not to make it one because I'm not gonna be relating it in the database but instead get its value from a webservice. @Column(name = "assigned_to", nullable = false) private int assignedTo; Now, I wanted to change the member from an int to a class named Employee which looks like this... public class Employee { private Integer employeeId; private String employeeName; /** Creates a new instance of Employee */ public Employee() { }; } } thus, changing the code to private Employee assignedTo; but I don't know where to put the annotations and which mapping to make. The employeeId needs to be the one mapped to the database table field. assigned_to. If you need to take a look at my FixedItem class and its mapping, here it is... /* * FixedItem.java * * Created on May 2, 2007, 4:12 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package com.wp.wpinventory.model; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.JoinColumn; import javax.persistence.Lob; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * Entity class FixedItem * * @author paul.timothy */ @Entity @Table(name = "fixed_item") @NamedQueries( { @NamedQuery(name = "FixedItem.findByFixedItemId", query = "SELECT f FROM FixedItem f WHERE f.fixedItemId = :fixedItemId"), @NamedQuery(name = "FixedItem.findByControlId", query = "SELECT f FROM FixedItem f WHERE f.controlId = :controlId"), @NamedQuery(name = "FixedItem.findByItemName", query = "SELECT f FROM FixedItem f WHERE f.itemName = :itemName"), @NamedQuery(name = "FixedItem.findBySerialNo", query = "SELECT f FROM FixedItem f WHERE f.serialNo = :serialNo"), @NamedQuery(name = "FixedItem.findByModelNo", query = "SELECT f FROM FixedItem f WHERE f.modelNo = :modelNo"), @NamedQuery(name = "FixedItem.findByAssignedTo", query = "SELECT f FROM FixedItem f WHERE f.assignedTo = :assignedTo"), @NamedQuery(name = "FixedItem.findByInvoiceRef", query = "SELECT f FROM FixedItem f WHERE f.invoiceRef = :invoiceRef"), @NamedQuery(name = "FixedItem.findByInvoiceAmount", query = "SELECT f FROM FixedItem f WHERE f.invoiceAmount = :invoiceAmount"), @NamedQuery(name = "FixedItem.findByDepartmentId", query = "SELECT f FROM FixedItem f WHERE f.departmentId = :mrgreen: epartmentId"), @NamedQuery(name = "FixedItem.findByDatePurchased", query = "SELECT f FROM FixedItem f WHERE f.datePurchased = :mrgreen: atePurchased"), @NamedQuery(name = "FixedItem.findByDateChecked", query = "SELECT f FROM FixedItem f WHERE f.dateChecked = :mrgreen: ateChecked") }) public class FixedItem implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "fixed_item_id", nullable = false) private Integer fixedItemId; @Column(name = "control_id") private String controlId; @Column(name = "item_name") private String itemName; @Column(name = "serial_no") private String serialNo; @Column(name = "model_no") private String modelNo; @Column(name = "assigned_to", nullable = false) private int assignedTo; //@Column(name = "assigned_to", nullable = false) //private Employee assignedTo; @Lob @Column(name = "description") private String description; @Column(name = "invoice_ref") private String invoiceRef; @Column(name = "invoice_amount") private BigDecimal invoiceAmount; @Column(name = "department_id") private Integer departmentId; @Column(name = "date_purchased") @Temporal(TemporalType.TIMESTAMP) private Date datePurchased; @Column(name = "date_checked") @Temporal(TemporalType.TIMESTAMP) private Date dateChecked; @JoinColumn(name = "fixed_item_type_id", referencedColumnName = "fixed_item_type_id") @ManyToOne private FixedItemType fixedItemTypeId; @JoinColumn(name = "supplier_id", referencedColumnName = "supplier_id") @ManyToOne private InventorySupplier supplierId; @JoinColumn(name = "assigned_by", referencedColumnName = "user_id") @ManyToOne private InventoryUser assignedBy; @JoinColumn(name = "item_condition_id", referencedColumnName = "item_condition_id") @ManyToOne private ItemCondition itemConditionId; /** Creates a new instance of FixedItem */ public FixedItem() { } /** * Creates a new instance of FixedItem with the specified values. * @param fixedItemId the fixedItemId of the FixedItem */ public FixedItem(Integer fixedItemId) { this.fixedItemId = fixedItemId; } /** * Creates a new instance of FixedItem with the specified values. * @param fixedItemId the fixedItemId of the FixedItem * @param assignedTo the assignedTo of the FixedItem */ public FixedItem(Integer fixedItemId, int assignedTo) { this.fixedItemId = fixedItemId; this.assignedTo = assignedTo; } /* public FixedItem(Integer fixedItemId, Employee assignedTo) { this.fixedItemId = fixedItemId; this.assignedTo = assignedTo; } */ //getters/setters here } Sorry for my ignorance, I'm just depending on the netbeans auto-generated code and so are my mappings. Please help me form my annotation and mapping. Thanks! [ May 11, 2007: Message edited by: Timothy Sam ] SCJP 1.5 Mark Spritzler ranger Sheriff Joined: Feb 05, 2001 Posts: 17276 6 I like... posted May 11, 2007 10:59:00 0 Well here is some things, you can have two instance variables for assignedTo, meaning private int assignedTo; and private Employee assignedEmployee; Now the assignedTo is still mapped to the int column, because it sounds like you can't change the database. Now what you will have to do to get the assignedEmployee, is to now look it up. And to go the other way, you have the assignedEmployee, and call the getId from it to get the value to set assignedTo to. Personally, If it is a referential integrity need, make the foreign key relationship. You have too many ways to mess up the data if you don't. Then you will only need the @ManyToOne for private Employee assignedTo; Mark Mark Perfect World Programming, LLC - iOS Apps How to Ask Questions the Smart Way FAQ Mark Spritzler ranger Sheriff Joined: Feb 05, 2001 Posts: 17276 6 I like... posted May 11, 2007 11:00:00 0 I see your topic has Composition, if it is truely composition, then look at the @Embeddable and @Embedded annotations and see if that is what you are looking for. Mark Timothy Sam Ranch Hand Joined: Sep 18, 2005 Posts: 751 posted May 12, 2007 07:57:00 0 Hi! Thank you for your suggestion. I'm off the office now so I can't test them yet. Your first suggestion would seem to work. But it sounds like I'll be doing a hack and I'm not a good fan of hacking my own code. Sounds very clever and very tempting though. I will be trying the @Embeddable and @Embedded annotations once I get back to work. I surely hope this could solve my problem. There is no referential integrity for the assigned_to field by the way... It's just an ordinary int value with no relationship whatsoever. I will be getting its value from a webservice. Thank you very much for your reply! I agree. Here's the link: subject: Need help with Mapping(Annotation) and Composition Similar Threads Mysql auto generated PK used for another table and JPA Apache Derby Sql Statement's Members are not poppulated? Can a class be mapped to a table and be Embeddable at the same time? Value is session managed bean's attribute is nulled All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/217243/ORM/databases/Mapping-Annotation-Composition
CC-MAIN-2015-48
refinedweb
1,161
50.84
>> French Supreme Court rejected an appeal against the ban on extracting shale gas in France. Starting from today shale gas extraction is illegal in France. How come they don't want to become the second Norway? Just don't tell me that they banned the use of this controversial technology in France for no reason at all. best part of this post is The current regulations are inadequate. It can take over a year for companies to obtain the permits to change their work programme thanks Regards Emily.Bronte Cities to Visit in Minnesota Shale gas is so far Poland's unfulfilled dream. In the meantime Poland still invests in coal plants... "In recent years Warsaw has found itself alone in resisting demands from Brussels to adopt more stringent emissions targets." In recent years Warsaw, i.e. Donald Tusk "government" and Radek Sikorski's "diplomacy", has been making a dog's dinner of "resisting" stringent demands regarding emission, too. Their predecessors had agreed to set targets but with base year being 1990. This encompassed the dismantling of communist-era heavy industry, so the emissions targets would have been met with a huge surplus. When Tusk and Sikorski took over, they agreed to base year being 2005, thus the problem now. This was very much in the Polish news a couple of weeks ago. But of course, just like he "mad and messy" regulations, this is what you have when the mainstream media are so totally uncritical of a government for six years. Fundamental differences between the USA and Poland: 1. All subsurface resources in Poland are State owned.In the USA the surface land owner also owns the minerals below ground level, which encourages the latter to allow oil/gas companies to drill on his/her land. In Poland local landowners resist any drilling as they get nothing from it. 2. Shale gas/oil deposits in Poland are deeply bedded (at least 4km down) whereas in the USA they are geologically shallow. New technology is therefore needed. 3. Polish State legislators, both Parliament and the government have made too many easy assumptions. They forgot that private companies (mostly foreign) take a business risk of a high exploratory spend for possibly/probably zero return (most drilled wells are "dry"). Instead of encouraging exploration the regulations are designed to strangle it in favour of Polish State owned companies which have little experience, if any at all, in the technology to be used. The regulators clearly ignored the fact that oil/gas companies can look elsewhere for a more positive business environment. 4. Those companies that remain in the game are mostly Polish State owned, with little or no experience of drilling for shale gas/oil.In North America and elsewhere, State owned comanies are not involved in the business. The whole shale gas episode in Poland looks like a damp squid. It would be far better for the Poles to concentrate on extracting methane gas from their extensive deep coal mines (average depth is already 1km), which gas already has to be continually flared off if miners are to work at those depths. Some of that methane is already burnt to produce electricity for the minimg operations. Of course such production will need to be connected to the local gas grid. It should be pointed out that Poland's major coal resources lie where there are large urban concentrations of population. Thus distance to market will not be an issue. Energy diversification, including importing LNG from a variety of sources plus encouraging renewable power generation (which means modernising the grid and allowing multiple connectors for producers) will reduce the current dependence on expensive Russian gas. News item, - July 11 – Royal Dutch Shell may expand its presence in Ukraine by tapping existing and reviving exhausted natural gas wells that, with the help of new technology, may increase output by 30%, the government reported. Shell has been preparing to start drilling for shale gas in the Kharkiv and Donetsk regions, but the new projects may further expand the company’s involvement in Ukraine. I just wanted to correct point #1...in the United States land surface rights do not inherently guarantee mineral rights...these items are two separate entities meaning one can buy the surface land rights of a property but also need to purchase the mineral rights if they wish to own what is below the surface....Also interested to note are water rights, however this is a whole different ball game and differs from state to state. LOL, the Poland shale gas wet dreams proved to be a dream of a zombie :D Here is why Poland shale gas is a butt of any joke: 1. The US EIA estimates about the Poland shale "recoverable deposits" are nothing but a big lie, disproved even by the Poland own geological survey. The US shale gas pushers got cot lying multiple times. 2. Presence of shale deposits does not warrant that the area will provide industrial quantity gas or/and oil concentrate. The experience with the US fracking demonstrates that only a handfull of cites produce meaningful amount of gas and the deposits are unpredictable. No wonder neither Exxon nor Talisman found any meaningfull amount of shale gas in their drills and decided it is not worth to waste time and money. 3. Even if Poland shale miraculously give some gas the US experience prove that the shale gas technology is extremely inefficient due to fast exhaustion of the drills (~45% in a year), so the US fraksters were drilling like crazy thousands new wells to keep the flow. All this drives the production price way up. 4. The US fraksters shoot themselves in the foot and went broke unable to survive low natural gas prices. The Exxon boss spill the beans about the dire state of the shale gas producers : "NEW YORK—-Even energy titan Exxon Mobil Corp. is showing signs of strain from low natural-gas prices. On Wednesday Exxon Chief Executive Rex Tillerson broke from the previous company line that it wasn't being hurt by natural gas prices, admitting that the Irving, Texas-based firm is among those hurting from the price slump. "We are all losing our shirts today." Mr. Tillerson said in a talk before the Council on Foreign Relations in New York. "We're making no money. It's all in the red."" No wonder GAZPROM poke fun on the US shale gas ineptitude and stupidity due to inherent US greed : ." If the US can not compete then Poland stands no chance at all, heh, heh, heh :D 5. The US fraksters experience demonstrates that in 2012 the shale gas investors LOST over $8BN - they pumped over $40BN and produced less than $32BN worth of gas. Good job, Poland most definitely will follow the same suit :D 6. Poland has no infrastructure to distribute their gas if they have any - this is an US assessment. 7. The US fracksters proved to the world that the shale gas extraction is dirty and have serious environmental impact upon the underground watter resources as chemicals used by them are found in the watter wells in the vicinity of the drills. Russian Gazprom Propaganda Department must have been busy producing plain Bullcakes for distribution by hired servants. It's more than visible this is Russian propaganda, whatever Russian agencies say remember there is not free speeech in this country, especially in crucial energy sector. Why you are so happy about US and Poland allegedly not being able to compete with Russia? Are you employed by Rusian authorities ? Hurray for Omricon Domestic use is paramount. This will ensure sustainable growth and better environmental laws. Shale gas MUST be retrieved without destroying water aquifers. Money over the environment is bad news. Maybe not for foreigners. Why do countries politicians so often squabble about oil that has yet to be exploited? Brazil's pre-sal, deposits off Cyprus and now polish shale. At least the UK's (disgraceful) windfall tax waited until the oil had already been extracted. You mention deposits off Cyprus. Russian Gazprom has already offered its "services" to Cyprus and anyone interested. Just to make sure gas supply monopoly to Europe remains in their hands. Lets get that TAP pipeline project via Turkey and Greece started without delay. The Exxon Mobil exit was likely a strategic move to take advantage of the huge potential of Russia's Bazhenov shale which was announced around the same time of their exit. Also consider they didn't' surrender the licenses: They're up for sale so they can't be truly worthless. Talisman's exit is much more to due with realignment in Canada and their new Chinese owners than anything to do with Polish rocks. Politics changes, but the rocks are eternal and as Pawel points out, they still look really good. We'll hear some good news from the likes of BNK, San Leon, Wisent and 3 Legs this year, and the news will not only be about gas. Releasing oil production in Poland could be transformative as well. But Poland is instructive as a negative example of how despite the top level supporting shale, it has to get down to all levels. When we see mad planning regulations where drillers have to wait 18 months to go horizontal from a vertical well for example, we can understand the frustration. As such, Poland gives an example to be avoided to the UK on how to squander what could be great national resources that belong not to the gas companies, but to the people. Poland, as in New York State, also underlines the possibility that if you play hard to get, you may end up with nothing. Five years ago, Poland looked like the only hope in Europe for shale. Today, everyone has it. That is something governments also need to consider. "if you play hard to get, you may end up with nothing. Five years ago, Poland looked like the only hope in Europe for shale. Today, everyone has it. That is something governments also need to consider." You are right about playing hard to get and getting little or nothing. This truism has been proven hundreds of times in mineral resource development. Its not too late for Polish government to consult with and to learn from other resource rich countries. Canada's exprience in encouraging, but also in controlling long term exploitation of that country's huge oil sands deposits in Alberta comes to mind as an example worth learning from. The article well summarizes but fails to directly name the process undegoing in Poland. Which is a tug-of-war between Polish state and some of the investors. The logical line of the article: 1. investors complain Poland ignores their demands (about rights to FUTURE use of the gas) 2. the legislation regarding shale gas extraction is poor 3. two companies withdrew though only 40 wells have been drilled so far, one company withdrew after drilling just two wells, the other cited unsatisfactory results as the reason. What article fails to directly mention is that A. the remaining companies - PGNiG, Petrolinvest, 3leg resources, Orlen, to name a few I remember- though indeed complain that their demands are not being fully fulfilled still drill around the country. So it is not really the mad and messy regulations that are the reasons of redrawal. B. all wells drilled so far confirmed shale gas existence C. Poland is now very sensitive to 'bonanza seekers' - firms that don't look for fair business but which in the past intended to use lack of experience of Polish decision makers and managers grown up/educated in pre-1989 times. Few examples of such bad deals: FIAT plants, F-16 warplanes deal, motorways building contracts. In the latter example - the authorities were virtually blackmailed prior to soccer cup EURO2012 'we will finish the road if you pay us more'. No such hurry in case of shale gas - on the opposite the later commercial extraction starts the better for the environment since the works on fracking methods with minimal impact on environment are underway. D. Poland is trapped in energy dependance between Germany - acting very selfishly here - and Russia which uses energy as a tool of policy. Poland does not get any meaningful assistance or backing from EU in building safe energy market, despite her vulnerable position. Much of what is written and said about shale gas and generally energy market in EU and in Poland is the direct result of two sets of lobbying - natural gas providers and green energy producers. . In effect - I tend to think it will be very hard to change mind of Polish authorities which are positive about the need to use local coal deposits and shale gas. The main opposition party seems even more determined than the ruling one, to provide relative energy independence by increasing the role of local sources in energy production. Forlana Yours is a good summary of the situation as you see it. I would offer a comment on a couple of your points: a)'the legislation regarding shale gas extraction is poor' This is, of course, at the very root of the issue. The fact that 'the mad and messy regulations' (your words) have not caused ALL companies to stop the drilling is not a proof that the others regard the regulations as satisfactory. Surely, the existence of 'messy regulations' in coal mining, or in the forest industry, or elsewhere, would have comparable negative impact. Lets keep in mind: the old communist style central planning does not work. Period. b) You said: 'Poland is trapped in energy dependance'. Of course it is, all thanks to energy policies inherited from the decades of central planning by the experts of the 'Peoples Poland'. As we all know, Poland is not the only European country to be so 'trapped', nor is it, in relative terms, in the worst position in terms of energy balance. Poland's rich coal resources and apparently plenty of shale gas underground are good evidence. Plus, to Poland's credit, the country has already made a huge step forward towards opening up LNG terminal on the Baltic. Meanwhile, it was and remains Poland's decision to reject a nuclear energy option keeping in mind decisions made with regard to nuclear power by a multitude of countries of about the same size or more. The bottom line is that Poland's energy needs will not change by blaming now decades old Gazprom's monopoly in Central and Eastern Europe but by reducing that monopolistic influence in cooperation with other European countries. Helping to speed up commercial development of Poland's shale gas resources should be the country's policy priority. And expanding the scope and transit capacity of the LNG on the Baltic coast should be another priority. Hi Didomyk, I read and hear the legislation is poor indeed. Nonetheless the roots of withdrawals are mentioned here Plus the companies which suspended drilling have found out that neither easy money option is secured by the government, nor the extraction is as easy as where they gained experience (US). However you are completely right that the legislation should be clear and logical, even if no easy money opportunity is provided. With your (b) point I almost completely agree of course, though it is not clear to me why getting to the shale gas deposits ASAP would be more beneficial than doing it as long as possible to maximize the local profits. Even if that would mean doing it step-by-step without the help of experienced and blessed with high solvency ratio American companies. Also, I tend to think that developing the nuclear energy production in Poland is simply the best way to get clean, safe energy in a country with no winds, few waters and moderately sunny. P.S. 'the mad and messy regulations' aren't my words but the subtitle of the article - a citation from those companies which withdrew, perhaps. "'the mad and messy regulations' aren't my words " Sorry, you are right, its TE author"s. As to the nuclear power option, somebody in Polish scientific-technical hierarchy should become more vocal about world-wide record and the relative benefits and risks of nuclear. Coal mines worldwide are known to have had tragic accidents. LNG is not without risks. Neither are gas pipelines that most of Europe has lived with for at least half a century. Its all relative. The good news is that the gas will stay down there if it is not extracted fast. San Leon Energy is buying the reserves from those who quit, and it is said has local oligarchs like Kulczyk as shareholders. The driling news from Lewino-1G2 is optimistic. For longer term investors there will be opportunities because Poland has to sort this out and the Polish economy does grow faster than average despite really clunky government (even if no one understands why) It's quite amazing that even before the resources are anywhere near proven, they are changing the rules of the game. Investors really don't like rule changes, so this is tantamount to killing the golden goose even before the goose grows up and lays a single egg. Where is emotional story line of Polish peasants valiantly fighting Chevron in Zamość? "..Companies that have already invested millions of dollars drilling wells are also worried the proposals do not give them a legal guarantee to transfer their existing exploration licenses into production licenses.." Whoever drafted that kind of legislation obviously should be sent back for retraining in resource economics starting with Economics 101. The Good News is that Oil was found in your land. The Bad News is that Oil was found in your land. _____________________________ The Disappointing News is that Expected Oil in your land was a Mirage. The Great News is that Expected Oil in your land was a Mirage. _____________________________ Long term, it is better that Poland resemble Germany's energy policy than Saudi Arabia's. A countries oil related woes usually begin when it starts generating lots of money for the state through exports rather than generating enough for internal use. This middle ground would be the best for Poland. - This would also be good morally as it thumbs the nose at Russia's attempt to use resources as a means of controlling their neighbours. Russia is bad enough for its own people let alone when it interferes with its neighbours. Just one problem: if you export, you get more money (and money is needed, especially in shale gas extraction procedures -no free meals, no free drills...-). So you have to choose: more sure money now, or the perspective to thumb somebody's nose tomorrow (and in the meantime remain with less or no money at all)?
http://www.economist.com/comment/2085372
CC-MAIN-2014-52
refinedweb
3,146
61.06
ITP for Visual Studio 2010. I’d been in Wallisellen to attend an MSDN TechTalk presentation by Stephen Toub, Principal Architect on Microsoft’s Parallel Computing Platform team. I’ve followed Stephen via his blog – and the Parallel Programming with .NET blog – for a long time, and thought it’d be a great opportunity to see him present in person (especially as such events in Switzerland tend to be quite intimate affairs – a great opportunity to have your questions answered). I wasn’t disappointed: Stephen really (and I mean really) knows his stuff, and I left the seminar inspired and itching to try some things out with the Async CTP. I can only hope that developers working with Autodesk technology get the same feeling when leaving one of my presentations (it’s certainly a goal worth striving for, at least). The ability to make asynchronous function calls easily is going to really significant for developers in .NET 5: I’ve been using F#’s excellent Asynchronous Workflows capability to do that, before – getting significant speed-ups on sequential/synchronous code – but having the capability integrated directly into the .NET Framework makes it even simpler for such a use-case (where there’s an existing C# or VB.NET codebase). The basic premise is simple enough: when you call a synchronous method to get data over the wire (in particular, although you also get delays from accessing local storage) you have to wait for the results to come back. And if you’re getting multiple files and processing each one, you’re going to have significant overhead in your processing loop. The fact that synchronous calls block your UI is also significant: ideally you want to at least have the UI repaint – and probably show a progress bar – during such operations, rather than just going grey and showing the “Not responding” message in the application’s title bar. Until now, asynchronous calls were typically handled by separate threads and lots of manual coordination code: you typically wrap your code up into a delegate and attach it to an event called on completion of asynchronous method (basically a very manual continuation passing mechanism), which makes for messy, messy code. The Async CTP (and presumably the same will be true of .NET 5) does all this under the covers: whenever you use the “await” keyword to wait for the results of an asynchronous call, execution continues in the outer, calling function – so it can continue to iterate through a loop, for instance – and the remaining code after the asynchronous call will get executed once the method returns. And that code will execute by default on the UI thread, which means you can update AutoCAD’s UI without having to implement any special coordination capability (in F# I used a MailboxProcessor for this). Which means that you can literally take synchronous code and add a few keywords (a combination of async and await) – and change your method calls to the usually-also-available Async versions – and the code will speed up significantly. You not only stop your code from blocking while waiting for asynchronous calls to complete, you make more efficient use of your CPU(s) as the work gets spread across whatever cores are available. And all this with minimal changes to your application’s code. Too cool! For now there are a few extra steps – such as adding a project reference to AsyncCtpLibrary.dll, which contains (no doubt among other things) asynchronous extension methods on System.Net.WebClient such as DownloadFileTaskAsync(), which creates an asynchronous task for which you can await completion – but these will disappear once the capabilities are integrated into the core .NET Framework. The steps for using the CTP are in this migration guide, which is well worth a look. I went through the process for my BrowsePhotosynth application, which previous had three modes of operation: C# Synchronous, F# Synchronous and F# Asynchronous. It was really easy to add C# Asynchronous into the mix using the CTP. Here’s the new source file, with the lines where it differs from the original synchronous version in red: 1 using Autodesk.AutoCAD.DatabaseServices; 2 using Autodesk.AutoCAD.EditorInput; 3 using Autodesk.AutoCAD.Runtime; 4 using System.Threading.Tasks; 5 using System.Net; 6 using System.IO; 7 using System; 8 9 namespace PhotosynthProcAsyncCs 10 { 11 public class PointCloudProcessor 12 { 13 Editor _ed; 14 ProgressMeter _pm; 15 string _localPath; 16 17 public PointCloudProcessor( 18 Editor ed, ProgressMeter pm, string localPath 19 ) 20 { 21 _ed = ed; 22 _pm = pm; 23 _localPath = localPath; 24 } 25 26 public async Task<long> ProcessPointCloud( 27 string path, int[] dims, string txtPath 28 ) 29 { 30 // Counter for the total number of points 31 32 long totalPoints = 0; 33 34 // Create our intermediate text file in the temp folder 35 36 FileInfo t = new FileInfo(txtPath); 37 StreamWriter sw = t.CreateText(); 38 using (sw) 39 { 40 // We'll use a web client to download each .bin file 41 42 WebClient wc = new WebClient(); 43 using (wc) 44 { 45 for (int maj=0; maj < dims.Length; maj++) 46 { 47 for (int min=0; min < dims[maj]; min++) 48 { 49 // Loop for each .bin file 50 51 string root = 52 maj.ToString() + "_" + min.ToString() + ".bin"; 53 string src = path + root; 54 string loc = _localPath + root; 55 56 try 57 { 58 await wc.DownloadFileTaskAsync(src, loc); 59 } 60 catch 61 { 62 return 0; 63 } 64 65 if (File.Exists(loc)) 66 { 67 // Open our binary file for reading 68 69 BinaryReader br = 70 new BinaryReader( 71 File.Open(loc, FileMode.Open) 72 ); 73 using (br) 74 { 75 try 76 { 77 // First information is the file version 78 // (for now we support version 1.0 only) 79 80 ushort majVer = ReadBigEndianShort(br); 81 ushort minVer = ReadBigEndianShort(br); 82 83 if (majVer != 1 || minVer != 0) 84 { 85 _ed.WriteMessage( 86 "\nCannot read a Photosynth point " + 87 "cloud of this version ({0}.{1}).", 88 majVer, minVer 89 ); 90 return 0; 91 } 92 93 // Clear some header bytes we don't use 94 95 int n = ReadCompressedInt(br); 96 for (int i = 0; i < n; i++) 97 { 98 int m = ReadCompressedInt(br); 99 100 for (int j = 0; j < m; j++) 101 { 102 ReadCompressedInt(br); 103 ReadCompressedInt(br); 104 } 105 } 106 107 // Find the number of points in the file 108 109 int numPoints = ReadCompressedInt(br); 110 totalPoints += numPoints; 111 112 _ed.WriteMessage( 113 "\nProcessed points_{0} containing {1} " + 114 "points.", 115 root, numPoints 116 ); 117 118 for (int k = 0; k < numPoints; k++) 119 { 120 // Read our coordinates 121 122 float x = ReadBigEndianFloat(br); 123 float y = ReadBigEndianFloat(br); 124 float z = ReadBigEndianFloat(br); 125 126 // Read and extract our RGB values 127 128 UInt16 rgb = ReadBigEndianShort(br); 129 130 int r = (rgb >> 11) * 255 / 31; 131 int g = ((rgb >> 5) & 63) * 255 / 63; 132 int b = (rgb & 31) * 255 / 31; 133 134 // Write the point with its color to file 135 136 sw.WriteLine( 137 "{0},{1},{2},{3},{4},{5}", 138 x, y, z, r, g, b 139 ); 140 } 141 } 142 catch (System.Exception ex) 143 { 144 _ed.WriteMessage( 145 "\nError processing point cloud file " + 146 "\"points_{0}\": {1}", 147 root, ex.Message 148 ); 149 } 150 } 151 152 // Delete our local .bin file 153 154 File.Delete(loc); 155 156 // Show some progress 157 158 _pm.MeterProgress(); 159 System.Windows.Forms.Application.DoEvents(); 160 161 if ( 162 PhotosynthImporter.Commands.CheckEscape(_ed) 163 ) 164 { 165 return 0; 166 } 167 } 168 } 169 } 170 } 171 } 172 return totalPoints; 173 } 174 175 private static int ReadCompressedInt(BinaryReader br) 176 { 177 int i = 0; 178 byte b; 179 180 do 181 { 182 b = br.ReadByte(); 183 i = (i << 7) | (b & 127); 184 } 185 while (b < 128); 186 187 return i; 188 } 189 190 private static float ReadBigEndianFloat(BinaryReader br) 191 { 192 byte[] b = br.ReadBytes(4); 193 return BitConverter.ToSingle( 194 new byte[] { b[3], b[2], b[1], b[0] }, 195 0 196 ); 197 } 198 199 private static UInt16 ReadBigEndianShort(BinaryReader br) 200 { 201 byte b1 = br.ReadByte(); 202 byte b2 = br.ReadByte(); 203 204 return (ushort)(b2 | (b1 << 8)); 205 } 206 } 207 } The calling code also ended up being very similar to the C# Synchronous implementation – the only difference being we receive a Task<long> back rather than a long (hopefully it’s also safe to just extract the Result from the Task – at least it worked well in my various tests): PhotosynthProcAsyncCs.PointCloudProcessor pcp = new PhotosynthProcAsyncCs.PointCloudProcessor( ed, pm, localPath ); System.Threading.Tasks.Task<long> task = pcp.ProcessPointCloud(path, dims, txtPath); totalPts = task.Result; I know I’ll get asked whether I still prefer F# Asynchronous Workflows to the Async CTP capabilities. On the one hand, I certainly like the purity of describing tasks in F#’s more declarative style – this definitely appeals to me – but on the other hand (which must be the more pragmatic of the two :-) the fact you can integrate this capability with so few modified lines of C# code is astonishing. I’ll definitely keep space in my toolbox for both approaches. In terms of performance, the C# Asynchronous implementation is equivalent to F# Asynchronous (and both are 8-10X quicker than their synchronous siblings, for this particular implementation scenario). I think I’m going to put together a quick screen-cam video to show this in action. I’ll hopefully post something in the next few days.
http://through-the-interface.typepad.com/through_the_interface/2011/06/finally-working-with-the-async-ctp-for-vs-2010.html
CC-MAIN-2017-51
refinedweb
1,569
50.77
Next Thread | Thread List | Previous Thread Start a Thread | Settings Hello, has anybody expierienced with the Realview Compiler (ARM) and C++ interrupt programming? How can I call an non static method as a interrupt handler? I use ATMEL AT91SAM7 controllers. It's not easy if one has just started to learn C++ at all ... (the reviews I found haven't helped me much). Interrupt programming really has nothing to do with C++ - actually, C++ is not a factor in it whatsoever. use standard C or assembly for that, and refer to your compiler's data sheet to see how. by the way, I hope you are aware of the intricacies involved in using C++, especially on microcontrollers...? PROGRAMMING POINTERS by Dan Saks: Better even at the lowest levels "Why might you prefer to write low-level code in C++ rather than in C? You've got much to gain and little or nothing to lose." Andy, I read the article. My personal opinion is that the risks that are introduced into software by using C++ are far greater than the mild benefits of stripped embedded C++. Yes, sometimes I'm DIEING to able to inherit, but for me, in comes down to the following: writing correct C++ code is far more challenging that writing C code. performance might be more of less the same (given a good compiler and some size trade-offs) but still - I would not use it for really low-level software. Why might you prefer to write low-level code in C++ rather than in C? You've got much to gain and little or nothing to lose. Thank you for the link, but I'll stick to C :-) There is actually a lot to loose: C++ is much harder to learn and use. And the only real-world example in the article is not convincing at all... Make a static ISR and call the non-static method from within that ISR. That's why I don't like C++: a whole new level of abstraction, a whole new lot of unnecessary choices, and plenty of new ways to shoot yourself in the foot. But I guess it has its uses... How can I call an non static method as a interrupt handler? Do you have to use a method as an interrupt handler? Won't a plain function do? No extra trouble to get C++ to work. It is a quite straight-forward language as long as you don't spend too much time digging yourself down with multiple base classes with or without virtual base classes. But operator-overriden C++ can result in a few nice trivial lines of code that actually consuming huge amounts of CPU time because the operator overloading isn't obvious. Because of this, great care should be used in interrupt service routines. They are intended to be fast, to let the next interrupt also be serviced quickly. The processor interrupt can never enter an object method since the processor only knows how to call a specific address. But an ISR can make use of a global variable to call a non-static method. But if you have a single global object that your ISR is calling one method in, then you can think about having a single function and a number of variables directly inside a namespace. It will also encapsulate the symbols and except for no overloading will be quite similar to a singleton object. And that encapsulated function can be specified as an ISR directly, instead of requiring an extra function call. Per, A very informative post. I only want to add that some implicit, innocent mistakes can have, as you stated, a large impact on performance/correctness: * implicit type conversions can lead to unexpected program behavior. if somebody adds a type conversion/constructor to a class without you knowing about it, it might introduce program stability issues/invalidate correctness. * using arrays polymorphically will destroy and program. * ... But isn't that also true of ANSI 'C'...? The following is an example of what I use on an the STR711Z2 (STmicro ARM 7) As Per states you will need to call 1 C or Assembly language function that saves your context properly (i.e. ceic_irq_function). If ALL of your interrupt routines are in C++, you could call the ceic_IRQhandler as your single IRQ_HANDLER. I am sure this could be easily adapted to your ARM processor. As for myself, I have found C++ to allow me to make my code smaller (yes, I said smaller) as well as more likely to be correct algorithmically. ( I have certainly written code that does not work in both C and C++ and still can, but I find it easier to do correctly in C++ than C) I am not trying to start a war here. If you prefer C that's find and you should stick with C. No reason you can't provide the same functionality, just in a different way. I just sometimes find people claim C++ has "issues" in ways that it really does not. And sometimes these so called issues are actually strengths of the language. #include "callback.h" // Callback definitions #include "eic.h" // ux types and STR eic library defs // that is all the includes class devCeic { public: devCeic() {}; static void setHandler(IRQChannel_TypeDef channel, CallbackBase<void> *callback, u16 prio = 1, FunctionalState NewState = ENABLE); static void setConfig(IRQChannel_TypeDef channel, FunctionalState NewState); static void setPriority(IRQChannel_TypeDef channel, u8 prio) { EIC_IRQChannelPriorityConfig(channel, prio); }; static void setIRV(void *irv) { EIC->IVR = (u32) irv; }; // static CallbackBase<void>* operator[] (u16 channel) { return vectors[channel]; }; friend void ceic_IRQhandler(void) __irq; private: static CallbackBase<void>* vectors[32]; }; extern devCeic CEIC; void ceic_IRQhandler(void) __irq { u16 vector; vector = EIC->CICR; //determine vector // Enable and save IRQ nesting here if desired if (devCeic::vectors[vector]) (*devCeic::vectors[vector])(); // This is a none static member function call // i.e. call to a member function of a specific instance of an object // Interrupt routine has no knowledge of the object // other than the member function to be called takes no parameters // Called member function has full knowledge of the instance of the object, because it is the object EIC->IPR = 1 << vector; // acknowledge interrupt } The following link gives one definition for the Generic Callback class. It is worth the time to go through it and understand it (complexity rating of 5 out of 10). Understanding means you can define templates that handle callbacks that return a value of a generic type and handles anywhere from 0 to at least 2 parameters. "implicit type conversions can lead to unexpected program behavior." This is basically the operator overloading I'm talking about. Elegance dictates that overloading should be invisible. When talking about performance or interrupts, invisible "extras" can be dangerous. This isn't so much a problem with the language. I think it is more a question of experience to not always do it the academic way and strive for maximum elegance. Sometimes it helps to make operations visible. In an performance-oriented world, you do not want to have to single-step in the debugger to be able to understand the code. "using arrays polymorphically will destroy and program." Some object-oriented languages solves this elegantly by not allowing you to create arrays of objects - just arrays of primitive data types or arrays of pointers. A very academic solution that may result in millions of memory allocations. And since they don't like pointers, the call them references and let the garbage collector solve the problem. It looks elegant, but consumes many, many extra MW of processing power. The people who complains about TVs left in stand-by should probably take a closer look at the power consumption of todays PCs, and what percentage of the power that is lost because of programming languages or how the languages are used. I have programs that can consume more processor instructions/second when I move the mouse cursor over their icon in the menu bar than my old dual-processor P90 could peak. A C++ program with heavy use of operator overloading etc can be such a wasteful program. But a C++ program may on the other hand be just as lean as a C program. I think that is one of the advantages of C++. Since it was originally designed to be a direct superset of C, the developer may decide how to use it. In a PC environment, you may go for smart pointers to get similar behaviour as the garbage collect of Java. In a tiny embedded environment, you may write C code with very limited objectification. But the rule is the same as for any other language: You are expected to know your tools. And you are epxected to know _why_ a specific code construct works. It is the "magic black boxes" that will hurt. I suspect that the 'C' programmers that make such claims are very much like the assembler programmers who assume that all 'C' code is inherently bloatware. And I also suspect that the same 'C' programmers that so vehemently defend 'C' against such ill-founded acusations from ill-informed (or just antagonistic?) assembler programmers are the same ones that make the similar accusations against C++... But I am just a 'C' programmer, so I can't see it from the C++ programmer's viewpoint... I suspect that the 'C' programmers that make such claims are very much like the assembler programmers who assume that all 'C' code is inherently bloatware. Not necessarily. It just so happens that for a many (most?) embedded applications C is the best tool for the job. I have worked with C++ in the past. I have made up my mind based on my experience and quite some reading. Mike and Tamir, you guys should stay with what you are comfortable with. There is nothing more detrimental to a project than someone coding in C++ that would really rather code in C. I find C++ to be an excellent choice for embedded applications. This would be based on experience. I would be interested to know what bad experiences any of you have had with C++. Maybe you should consider these as learning experiences. Identify the mistakes that were made and don't do them again. I am sure this is how you became "good" C programmers. I am also 100% certain it was not the C++ language itself that caused your issues and that using the C language in itself would not have solved them. Thank you for all your answers, to be honest, it was not my intention to start a general discussion on C++ or C programming. However I notice that there is a big interest in this. Sometimes I also wonder what is better. But since I am requested to program in C++ at work there's no real choice. Scott Meyers says C++ should be seen as a combination of languages (which includes C, Object Oriented C++ Template C++ and STL). The rules can change if you change from one "sub-language to another". I think this is exactly where the problem lies. With langauges like Java there was a clear cut to a completely new language. Another problem lies in the many possibilities of the language. When you are a beginner you don't know where to start learning to get the most for your applications. Another thing is that there are (at least to my knowledge) no books about C++ for embedded systems, which show how to solve specific problems of embedded systems (not repeating basics already covered many times elsewhere). I know there are books with embedded C/C++ in the title but there isn't much C++ really in them. To come back to my original intention - to discuss interrupt implementations of embedded systems (ARM7/9 etc.) controllers: I have found the following article about interrupts: The frustrating thing about it was the source code wasn't available anymore. But now I have found it here: I didn't get it to work with the realview compiler yet. I tried to strip it down and managed to compile but not to link. Another article can be found at: I have implemented my own simple version to call a non static member from an interrupt useing a me method pointer (initialized with the this pointer at the constructor) as described in the article above. Before I knew how to do it I studied Michael Melkonian's comment which can be found at: Best wishes and a happy new year to all of you, Oliver Deb
http://www.keil.com/forum/13850/
CC-MAIN-2015-14
refinedweb
2,102
61.67
Discovering basestring Wednesday, February 10, 2010 This may seem simple and trivial, but today I discovered the basestring type in Python. It is essentially a base type for str and unicode, which comes in handy when writing isinstance(foo, basestring) in test code for example. Strangely, despide PEP 237 mentioning the equivalent for int and long as " integer" I can't actually find what has become of that, so still writing isinstance(foo, (int, long)) for now. Note that this is Python 2.x only, in 3.x it's all unicode so there is no longer a need for a common base type. int and long are unified as well in Python 3.x obviously. 2 comments: Anonymous said... import __builtin__ __builtin__.baseint = int, long assert isinstance(1, baseint) assert isinstance(1L, baseint) assert isinstance(False, baseint) Anonymous said... Starting from python 2.6 you can use the numbers module. >>> from numbers import Integral >>> isinstance(1, Integral) True >>> isinstance(1l, Integral) True >>> isinstance(1.1, Integral) False New comments are not allowed.
http://blog.devork.be/2010/02/discovering-basestring.html
CC-MAIN-2019-09
refinedweb
173
68.57
qdropevent.3qt man page QDropEvent — Event which is sent when a drag and drop is completed Synopsis #include <qevent.h> Inherits QEvent and QMimeSource. Inherited by QDragMoveEvent. Public Members QDropEvent ( const QPoint & pos, Type typ = Drop ) const QPoint & pos () const bool isAccepted () const void accept ( bool y = TRUE ) void ignore () bool isActionAccepted () const void acceptAction ( bool y = TRUE ) enum Action { Copy, Link, Move, Private, UserAction = 100 } void setAction ( Action a ) Action action () const QWidget * source () const virtual const char * format ( int n = 0 ) const virtual QByteArray encodedData ( const char * format ) const virtual bool provides ( const char * mimeType ) const QByteArray data ( const char * f ) const (obsolete) void setPoint ( const QPoint & np ) Description The QDropEvent class provides an event which is sent when a drag and drop is completed.. Member Type Documentation QDropEvent::Action This enum describes the action which a source requests that a target perform with dropped data. QDropEvent::Copy - The default action. The source simply uses the data provided in the operation. QDropEvent::Link - The source should somehow create a link to the location specified by the data. QDropEvent::Move - The source should somehow move the object from the location specified by the data to a new location. QDropEvent::Private - The target has special knowledge of the MIME type, which the source should respond to in a similar way to a Copy. QDropEvent::UserAction - The source and target can co-operate using special actions. This feature is not currently supported. The Link and Move actions only makes sense if the data is a reference, for example, text/uri-list file lists (see QUriDrag). Member Function Documentation QDropEvent::QDropEvent ( const QPoint & pos, Type typ = Drop ) Constructs a drop event that drops a drop of type typ on point pos. void QDropEvent::accept ( bool y = TRUE ). void QDropEvent::acceptAction ( bool y = TRUE ) Call this to indicate that the action described by action() is accepted (i.e. if y is TRUE, which is the default), not merely the default copy action. If you call acceptAction(TRUE), there is no need to also call accept(TRUE). Examples: Action QDropEvent::action () const Returns the Action which the target is requesting to be performed with the data. If your application understands the action and can process the supplied data, call acceptAction(); if your application can process the supplied data but can only perform the Copy action, call accept(). Examples: QByteArray QDropEvent::data ( const char * f ) const This function is obsolete. It is provided to keep old source working. We strongly advise against using it in new code. Use QDropEvent::encodedData(). QByteArray QDropEvent::encodedData ( const char * format ) const [virtual] Returns a byte array containing the drag's data, in format.. const char * QDropEvent::format ( int n = 0 ) const [virtual](). Example: iconview/main.cpp. Reimplemented from QMimeSource. void QDropEvent::ignore () The opposite of accept(), i.e. you have ignored the drop event. Example: fileiconview/qfileiconview.cpp. bool QDropEvent::isAccepted () const Returns TRUE if the drop target accepts the event; otherwise returns FALSE. bool QDropEvent::isActionAccepted () const Returns TRUE if the drop action was accepted by the drop site; otherwise returns FALSE. const QPoint & QDropEvent::pos () const Returns the position where the drop was made. Example: dirview/dirview.cpp. bool QDropEvent::provides ( const char * mimeType ) const [virtual] Returns TRUE if this event provides format mimeType; otherwise returns FALSE. See also data(). Example: fileiconview/qfileiconview.cpp. Reimplemented from QMimeSource. void QDropEvent::setAction ( Action a ) Sets the action to a. This is used internally, you should not need to call this in your code: the source decides the action, not the target. void QDropEvent::setPoint ( const QPoint & np ) Sets the drop to happen at point np. You do not normally need to use this as it will be set internally before your widget receives the drop event. QWidget * QDropEvent::source () const If the source of the drag operation is a widget in this application, this function returns that source, otherwise it returns 0. The source of the operation is the first parameter to drag object subclasses. This is useful if your widget needs special behavior when dragging to itself, etc. See QDragObject::QDragObject() and subclasses.dropevent.3qt) and the Qt version (3.3.8). Referenced By QDropEvent.3qt(3) is an alias of qdropevent.3qt(3).
https://www.mankier.com/3/qdropevent.3qt
CC-MAIN-2017-17
refinedweb
706
56.66
a = [[[0] for col in range(4)] for row in range(4)] I do that code and it runs fine, and then I manipulate that list with code I have later and it runs fine at a reasonable speed. But if I put this code in a module. Module ListToFillUp.py def make(x,y,content): list = [[content for col in range(x)] for row in range(y)] return list Module that I'm working in b = ListToFillUp.make(4, 4, [0]) And then I import the module into the other module and use this line to make the list, it is fine and it is identical to the other list as checked by ==, but it encounters code later on that it just hangs on until I have a memory error. There could be a problem with the code later on that I didn't post, but the bigger problem is how there seems to be an actual difference between the lists created. But when I compare the two lists with == it comes up as true. And I see the lists printed out and they are the same. I even do "copy.deepcopy(b)" and the problem still exists. So is there anything else I can check to see if they are different or if there is another explanation why I am getting a memory error?
https://www.daniweb.com/programming/software-development/threads/351570/i-m-having-a-weird-problem-code-is-running-differently-in-a-module-than-in-line
CC-MAIN-2017-34
refinedweb
226
75.34
The Xamarin.Forms Switch allows you to turn an item on and off, and provides an optional indeterminate state. It supports VSM, a busy state, and gradient. The Xamarin.Forms Switch provides three built-in visual types. These visual types save time when customizing a switch based on different devices in maintaining the same visual on all three kinds of devices (Android, iOS, and UWP). Apart from the usual on and off states, there is also a state called indeterminate. Use the Visual State Manager to customize Xamarin.Forms Switch’s thumb and track based on switch states. Its supported visual states are on, off, indeterminate, and disabled. Switches with busy indicator support are the most common scenario in service-based apps. The Xamarin.Forms Switch can turn on or off items based on validation. The Xamarin.Forms Switch supports vertical orientation. The Xamarin.Forms Switch can be integrated when the app requires an interface to set values at high, low, and medium. The highly customizable Xamarin.Forms Switch control allows you to customize its background with gradients. Customize the Xamarin.Forms Switch control with images to illustrate the use case of the switch action. The Xamarin.Forms Switch has been designed with Flow Direction compatibility. Easily get started with the Xamarin.Forms Switch using a few simple lines of XAML and, C# code example as demonstrated below. Also explore our Xamarin.Forms Switch Example that shows you how to render and configure the Switch for Xamarin.Forms. xmlns:syncfusion="clr-namespace:Syncfusion.XForms.Buttons;assembly=Syncfusion.Buttons.XForms" SfSwitch sfSwitch = new SfSwitch(); We do not sell the Xamarin Switch separately. It is only available for purchase as part of the Syncfusion Xamarin suite, which contains over 155 Xamarin components, including the Switch, are not sold individually, only as a single package. However, we have competitively priced the product so it only costs a little bit more than what some other vendors charge for their.
https://www.syncfusion.com/xamarin-ui-controls/xamarin-switch?utm_source=nuget&utm_medium=listing&utm_campaign=xamarin-wpf-buttons-nuget
CC-MAIN-2022-27
refinedweb
325
50.33
POJ 1250 模拟题 终于在POJ上碰到一道简单题,,不容易啊。。模拟,可以轻松水过。。题目: Tanning Salon Description Tan Your Hide, Inc., owns several coin-operated tanning salons. Research has shown that if a customer arrives and there are no beds available, the customer will turn around and leave, thus costing the company a sale. Your task is to write a program that tells the company how many customers left without tanning. Input The input consists of data for one or more salons, followed by a line containing the number 0 that signals the end of the input. Data for each salon is a single line containing a positive integer, representing the number of tanning beds in the salon, followed by a space, followed by a sequence of uppercase letters. Letters in the sequence occur in pairs. The first occurrence indicates the arrival of a customer, the second indicates the departure of that same customer. No letter will occur in more than one pair. Customers who leave without tanning always depart before customers who are currently tanning. There are at most 20 beds per salon. Output For each salon, output a sentence telling how many customers, if any, walked away. Use the exact format shown below. Sample Input 2 ABBAJJKZKZ 3 GACCBDDBAGEE 3 GACCBGDDBAEE 1 ABCBCA 0 Sample Output All customers tanned successfully. 1 customer(s) walked away. All customers tanned successfully. 2 customer(s) walked away.ac代码: #include <iostream> #include <string> #include <cstdio> using namespace std; int numbed,visted[30]; int main(){ //freopen("11.txt","r",stdin); while(scanf("%d",&numbed),numbed){ memset(visted,0,sizeof(visted)); string ss; cin>>ss; int num=numbed; int sum=0; int len=ss.size(); for(int i=0;i<len;++i){ if(visted[ss[i]-'A']==2) continue; else if(num<=0&&!visted[ss[i]-'A']){sum++;visted[ss[i]-'A']=2;} else if(!visted[ss[i]-'A']&&num){ visted[ss[i]-'A']=1; num--; } else if(visted[ss[i]-'A']){ num++; } } if(sum==0)printf("All customers tanned successfully.\n"); else printf("%d customer(s) walked away.\n",sum); } return 0; }
http://blog.csdn.net/wmn_wmn/article/details/7382432
CC-MAIN-2018-13
refinedweb
343
60.01